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