From e590808062cb27639279b66d8568fafd4121922a Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 5 Apr 2026 21:45:18 +0800 Subject: [PATCH] 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'); + }); +});