chore: sync workspace changes

This commit is contained in:
liufumingren 2026-03-23 17:10:07 +08:00
parent 9ab060d223
commit bbc5891d16
92 changed files with 7570 additions and 3713 deletions

3
.gitignore vendored
View File

@ -1,5 +1,6 @@
logs/
run/
temp/
node_modules/
coverage/
.nyc_output/
@ -23,3 +24,5 @@ native/addons/*.node
Thumbs.db
*.sw*
*.un~
todo.txt
test/.runtime/

View File

@ -111,9 +111,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- 扫描范围:app/service/**/*.js
- 本节内容由脚本生成,新增/修改 service 后请同步刷新。
- 刷新命令:node .\script\tmp-gen-service-method-inventory.cjs
- 临时清单输出:temp/tmp-service-method-inventory.md
<!-- SERVICE_METHOD_INVENTORY:BEGIN -->
自动生成时间: 2026-03-22T09:03:11.802Z
自动生成时间: 2026-03-22T15:27:37.958Z
扫描范围: app/service/**/*.js
文件数: 50
@ -146,8 +147,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- create, query
- app/service/qimenMethods/taobao/qimen/service.js (1)
- heartbeat
- app/service/system.js (3)
- callMethod, validateParams, saveLog
- app/service/system.js (4)
- callMethod, validateParams, validateRequestContext, saveLog
- app/service/systemMethods/config.js (1)
- list
- app/service/systemMethods/dashboard.js (6)
@ -172,8 +173,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- login, logout, info, changeRole, register
- app/service/systemMethods/warehouse.js (20)
- getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, createRack, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo
- app/service/systems/account_platform.js (8)
- switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext
- app/service/systems/account_platform.js (11)
- getActiveInclude, getPrimaryRoleBinding, formatActiveContext, switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext
- app/service/systems/auth/user.js (21)
- login, ID, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register
- app/service/systems/delivery_order.js (7)
@ -214,8 +215,10 @@ rg "class .*Service|module.exports" app/service/qimenMethods
- index
- app/service/systems/storage/receiving.js (16)
- getReceivingList, getReceivingDetail, batchCancelReceiving, isEmptyValue, buildSequelizeCondition, processConditionValue, create, get, addDetail, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, completeReceiving
- app/service/systems/store.js (13)
- getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores
- app/service/systems/store.js (14)
- getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, ensureEmployeeRoleBinding, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores
- app/service/systems/upload.js (14)
- initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback
<!-- SERVICE_METHOD_INVENTORY:END -->

View File

@ -10,10 +10,15 @@
## 2. 数据库调试脚本
临时文件规则(强制):
- 所有临时产物统一生成到 `temp/` 目录。
- `temp/` 目录不提交到 git。
项目已提供数据库查询脚本:`script/db-query.ps1`
脚本能力:
- 自动读取 `config/config.local.js` 中的 `config.mysql.clients.<clientName>` 配置
- 支持通过 `-DbClient` 显式切换 mysql client(如 `wms`、`ye4s`),默认 `wms`
- 执行传入 SQL 并返回 JSON
- 可选表格输出,便于命令行快速查看
@ -34,12 +39,19 @@ powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT id
# 指定 mysql client(默认是 wms)
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Query "SHOW TABLES"
# 切换到 ye4s client
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SHOW TABLES"
# 快速确认当前连接到哪个库/账号
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "SELECT DATABASE() AS db, USER() AS loginUser"
powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient ye4s -Query "SELECT DATABASE() AS db, USER() AS loginUser"
```
### 2.3 参数说明
- `-Query`:必填,SQL 语句
- `-DbClient`:可选,MySQL 客户端名,默认 `wms`
- `-DbClient`:可选,MySQL 客户端名(例如 `wms`、`ye4s`),默认 `wms`
- `-ConfigPath`:可选,配置文件路径,默认 `.\config\config.local.js`(相对于项目根目录)
- `-AsTable`:可选,按表格输出结果
@ -59,6 +71,16 @@ powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -DbClient wms -Qu
}
```
### 2.5 区分 wms 与 ye4s(快速自检)
- 步骤 1:不传 `-DbClient` 执行一次 `SELECT DATABASE() AS db, USER() AS loginUser`
- 步骤 2:传 `-DbClient ye4s` 再执行同一条 SQL
- 期望结果:
- 默认执行返回 `client = wms` 且 `db = wms`
- 指定 `ye4s` 返回 `client = ye4s` 且 `db = ye4s`
说明:脚本会从 `config.mysql.clients.<clientName>` 读取连接参数,返回体中的 `client` 字段可直接用于确认当前路由。
## 3. AI 协助时建议使用的提问模板
### 3.1 只读查询(推荐)
@ -86,27 +108,99 @@ SELECT * FROM account LIMIT 20;
4) 输出最终根因和修复建议
```
## 4. 常见问题
## 4. Redis 缓存调试脚本
项目已提供 Redis 调试脚本:`script/redis-cache.ps1`
脚本能力:
- 自动读取 `config/config.local.js`(可切换 `-ConfigPath`)中的 `config.redis.clients.<clientName>` 配置连接 Redis
- 支持缓存读取与修改:`get/set/del/exists/ttl/expire/keys/hget/hset/hdel/hgetall/incr/decr`
- 可选表格输出(`-AsTable`)
### 4.1 基本用法
```powershell
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system"
```
### 4.2 常用示例
```powershell
# 列出 key(使用 SCAN,不直接 KEYS 阻塞)
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action keys -RedisClient cache -Pattern "user:*" -AsTable
# 读取/写入字符串缓存
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action get -RedisClient cache -Key "system"
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action set -RedisClient cache -Key "system" -Value "{\"ok\":1}" -ExpireSeconds 600
# 删除缓存
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action del -RedisClient cache -Key "system"
# Hash 结构读写
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hgetall -RedisClient cache -Key "session:123" -AsTable
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action hset -RedisClient cache -Key "session:123" -Field "status" -Value "active"
# 自增/自减计数器
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action incr -RedisClient cache -Key "counter:order"
powershell -ExecutionPolicy Bypass -File .\script\redis-cache.ps1 -Action decr -RedisClient cache -Key "counter:order" -Value 2
```
### 4.3 参数说明
- `-Action`:必填,操作类型(`get/set/del/exists/ttl/expire/keys/hget/hset/hdel/hgetall/incr/decr`)
- `-RedisClient`:可选,Redis 客户端名,默认 `cache`
- `-Key`:按操作需要传入
- `-Value`:`set/hset/incr/decr` 等操作使用
- `-Field`:`hget/hset/hdel` 必填
- `-ExpireSeconds`:`set`(可选)和 `expire`(必填)
- `-Pattern`:`keys` 操作匹配模式,默认 `*`
- `-ConfigPath`:可选,默认 `.\config\config.local.js`
- `-AsTable`:可选,表格输出
### 4.4 AI 调用模板(缓存读改)
```text
请在项目根目录执行 script/redis-cache.ps1:
1) 用 Action=keys, Pattern="user:*" 列出目标缓存键
2) 读取 key=xxx 的当前值(Action=get)
3) 按我提供的新值执行 Action=set 并设置过期时间 600 秒
4) 回读一次确认变更生效,并输出变更前后对比
```
## 5. 常见问题
- 报错 `Cannot find module 'mysql2/promise'`
- 先执行 `npm install`,确认依赖完整
- 报错 `Cannot find module 'ioredis'`
- 先执行 `npm install`,确认依赖完整
- 报错 `MySQL client "xxx" not found in config.mysql.clients`
- 检查 `config/config.local.js` 中 `config.mysql.clients` 是否包含对应 client
- SQL 语法报错且定位到 `current_user`
- 避免使用 `current_user` 作为别名,建议改成 `loginUser` 等非保留字名称
- 报错 `Redis client "xxx" not found in config.redis.clients`
- 检查 `config/config.local.js` 中 `config.redis.clients` 是否包含对应 client
- 报错连接失败(超时/拒绝访问)
- 检查数据库 IP、端口、用户名密码、网络白名单
- 报错 Redis 连接失败(超时/认证失败)
- 检查 Redis host/port/password/db 与网络连通性
- PowerShell 执行策略限制
- 使用命令中的 `-ExecutionPolicy Bypass`(仅本次命令生效)
## 5. 安全约束
## 6. 安全约束
- 默认只执行 SELECT/SHOW 等只读 SQL
- 执行 UPDATE/DELETE 前必须先让 AI 生成影响范围确认 SQL(COUNT + WHERE 条件)
- 涉及生产数据时,优先在测试环境验证
- Redis 写操作(`set/del/hset/hdel/incr/decr/expire`)前,先执行一次读取并确认影响 key 范围
## 6. 接口入口与 Method 指向
## 7. 接口入口与 Method 指向
- 入口风格:
- `/qimen`:奇门开发接口(POST)
@ -119,7 +213,7 @@ SELECT * FROM account LIMIT 20;
- 见 `AI_METHOD_ROUTING.md`
- 文档记录了 method 到 `app/service/systemMethods`、`app/service/qimenMethods` 的映射规则与示例。
## 7. methods 目录地图
## 8. methods 目录地图
目录:`methods/`
@ -133,7 +227,7 @@ SELECT * FROM account LIMIT 20;
建议将 `methods/*.json` 视为“接口文档单一事实来源(SSOT)”。
## 8. 接口变更联动工作流(强制)
## 9. 接口变更联动工作流(强制)
当出现以下任一变更时,必须同步更新 `methods` 目录下对应 JSON:
@ -166,5 +260,82 @@ node .\script\tmp-struct-system-params.cjs
执行规则:接口代码与 `methods/*.json` 不一致时,以“必须补齐文档”为完成标准。
## 10. App 能力地图(优先定位)
能力入口文件:
- `app.js`
- `app/extend/application.js`
### 10.1 启动与初始化能力(app.js)
- 设置应用根路径:`global.APP_ROOT`、`app.appRoot`
- 启动前初始化动态工厂:
- `OrderDeliveryFactory`
- `OrderItemsFactory`
- 启动时能力自检:
- `app.setCacheAsync` / `app.getCacheAsync`
- `app.Message`
- 全局日期格式化扩展:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')`
### 10.2 Application 扩展能力(app/extend/application.js)
- 业务字典访问:
- `businessDict`
- `getBusinessTypeName(code)`
- `getOperationCodeName(code)`
- `getPlatformName(code)`
- `getExternalLogTypeName(type)`
- 外部 SOAP 调用:
- `wsdl(methodName, args)`
- Redis 缓存(cache client):
- `setCacheAsync(cacheKey, data, expireSeconds = 300)`
- `getCacheAsync(cacheKey)`
- Message 扩展:
- `Message` getter(返回 `MessageClass`)
### 10.3 AI 调试优先顺序
- 遇到“方法不存在/映射异常”优先检查 `app/extend/application.js` 是否包含对应能力。
- 遇到“动态分表模型不可用”优先检查 `app.js` 的工厂初始化是否执行成功。
- 遇到“缓存读写异常”优先检查 Redis client `cache` 配置及 `setCacheAsync/getCacheAsync` 调用链。
### 10.4 AI 快速回复定义
- 回复0时默认拒绝
- 回复1时默认接收
## 11. Web 用户信息与切换角色测试(已验证)
目标:
- 使用 `/system` 入口验证 Web 端用户信息获取与角色切换链路。
- 固定请求头:`platform=web`、`project=all`。
- 将接口返回暂存到 `test/.runtime/` 便于回放与比对。
测试文件:
- `test/app/controller/system.user.info.web.test.js`
- 调用 `user.info`
- 断言 `status=200`、`flag=success`、`code=200`
- 断言返回 `platform_code=web`
- 落盘:`test/.runtime/system_user_info_web_all.json`
- `test/app/controller/system.user.changeRole.test.js`
- 先调用 `user.info` 读取当前角色与可切换角色
- 调用 `user.changeRole`(`roleId` 取可用候选角色)
- 使用返回的新 token 再调 `user.info` 验证 `employees_id` 已切换
- 落盘:`test/.runtime/system_user_change_role_web_all.json`
- 末尾自动切回原角色,降低对其他测试影响
一键执行:
```powershell
npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/controller/system.user.changeRole.test.js
```
本地验证结果:
- 2 passing
建议排查顺序(当返回菜单/权限为空时):
1. 先查 `user.info` 返回中的 `employees_id`、`store_id`、`platform_code`
2. 确认请求头是否为 `platform=web`、`project=all`
3. 若仍为空,检查账号角色授权与当前激活角色是否存在

View File

@ -1,143 +0,0 @@
{
"openapi": "3.0.1",
"info": {
"title": "打印相关接口",
"description": "print service methods",
"version": "1.0.0"
},
"paths": {
"/system": {
"post": {
"summary": "打印台相关接口",
"operationId": "printStationOperations",
"description": "根据method参数执行不同的打印台操作",
"parameters": [
{
"name": "method",
"in": "query",
"description": "调用方法名,如print.getList、print.getItem、print.updateItem、print.del、print.getComputer、print.getComputerPrinter、print.savePrinters",
"required": true,
"schema": {
"type": "string",
"enum": [
"print.getList",
"print.getItem",
"print.updateItem",
"print.del",
"print.getComputer",
"print.getComputerPrinter",
"print.savePrinters"
]
}
},
{
"name": "v",
"in": "query",
"description": "版本号",
"required": false,
"schema": {
"type": "string",
"example": "2.0"
}
},
{
"name": "timestamp",
"in": "query",
"description": "时间戳",
"required": false,
"schema": {
"type": "string",
"example": "1646908800000"
}
}
],
"requestBody": {
"required": false,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"page": { "type": "integer", "example": 1 },
"pageSize": { "type": "integer", "example": 20 },
"where": {
"type": "object",
"example": { "name": "A台" }
},
"id": { "type": "integer", "example": 1 },
"name": { "type": "string", "example": "A台" },
"computer_id": { "type": "integer", "example": 2 },
"custom_barcode": { "type": "string", "example": "123456" },
"ids": {
"type": "array",
"items": { "type": "integer" },
"example": [1,2]
},
"default": { "type": "string", "example": "打印机名称" },
"express": {
"type": "array",
"items": {
"type": "object",
"properties": {
"express_id": { "type": "integer" },
"name": { "type": "string" }
}
},
"example": [{ "express_id": 1, "name": "顺丰" }]
},
"print_station_id": { "type": "integer", "example": 1 }
}
}
}
}
},
"responses": {
"200": {
"description": "成功响应",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"code": { "type": "integer", "description": "状态码" },
"message": { "type": "string", "description": "返回信息" },
"data": { "type": "object", "description": "返回数据" }
}
}
}
}
},
"400": {
"description": "错误请求",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"code": { "type": "integer" },
"message": { "type": "string" }
}
}
}
}
},
"401": {
"description": "未授权"
}
},
"security": [
{ "bearer": [] }
]
}
}
},
"components": {
"securitySchemes": {
"bearer": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
}
}

View File

@ -1,107 +0,0 @@
{
"openapi": "3.0.1",
"info": {
"title": "默认模块",
"description": "",
"version": "1.0.0"
},
"tags": [],
"paths": {
"/system": {
"post": {
"summary": "未命名接口",
"deprecated": false,
"description": "",
"tags": [],
"parameters": [
{
"name": "method",
"in": "query",
"description": "",
"required": false,
"example": "user.login",
"schema": {
"type": "string"
}
},
{
"name": "v",
"in": "query",
"description": "",
"required": false,
"example": "2.0",
"schema": {
"type": "string"
}
},
{
"name": "timestamp",
"in": "query",
"description": "",
"required": false,
"example": "{{$date.now}}",
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"userName": {
"type": "string"
},
"passWord": {
"type": "string"
}
},
"required": [
"userName",
"passWord"
]
},
"example": {
"userName": "夫立伟",
"passWord": "Ut cillum veniam"
}
}
}
},
"responses": {
"200": {
"description": "",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {}
}
}
},
"headers": {}
}
},
"security": [
{
"bearer": []
}
]
}
}
},
"components": {
"schemas": {},
"responses": {},
"securitySchemes": {
"bearer": {
"type": "http",
"scheme": "bearer"
}
}
},
"servers": [],
"security": []
}

View File

@ -0,0 +1,94 @@
# Method 输出一致性回放说明
更新时间: 2026-03-22
## 1. 新交付条件
- 所有模型/关联相关改动,必须先执行 method 输出基线回放。
- 改动完成后,必须对同一批 method 执行 compare 回放。
- 交付标准: 修改前后 method 输出一致。
- 允许屏蔽波动字段: token、timestamp、last_login_at、created_at、updated_at、iat、exp。
## 2. 测试账号
- username: liufumingren
- password: 111111
## 3. 方法使用来源
- method 定义来源: methods/system.json
- 回放脚本会从该配置中读取 method 分组、描述、参数定义,作为样本元数据。
## 4. 测试数据来源
- 主来源表: wms_system_log
- 参考日志表:
- wms_api_log
- wms_operation_log
- wms_account_login_log
- 样本选择原则:
- 优先同账号(liufumingren)
- 优先只读方法(get/list/query/detail/info/stats)
- 优先较新数据(按日志 id 倒序)
- 优先方法去重
## 5. 执行脚本
脚本文件:
- script/method-output-regression.cjs
命令:
```powershell
# 修改前执行,生成基线
node .\script\method-output-regression.cjs baseline 8
# 修改后执行,对比输出
node .\script\method-output-regression.cjs compare
```
输出文件:
- temp/method-output/method-output-baseline.json
- temp/method-output/method-output-baseline.md
- temp/method-output/method-output-compare.json
## 6. 本次基线执行结果(修改前)
执行时间:
- baseline: 2026-03-22T13:56:52Z
- compare: 2026-03-22T13:56:57Z
样本数:
- 8
样本 method(来自 temp/method-output/method-output-baseline.md):
- storage.receiving.getReceivingDetail (sourceId: 10790)
- order.getOrderModels (sourceId: 10783)
- print.getList (sourceId: 10611)
- print.getComputerPrinter (sourceId: 10579)
- print.getItem (sourceId: 10578)
- print.getComputer (sourceId: 10577)
- store.getStoreRoles (sourceId: 10553)
- index.getExpressList (sourceId: 9820)
比对结果:
- total: 8
- mismatch: 0
- pass: true
说明:
- 当前样本中既包含 200 成功响应,也包含 403 权限响应。
- 403 响应同样纳入一致性校验范围(用于防止权限链路被意外改变)。
## 7. 后续执行要求
- 每次开始改动前,先运行 baseline 并保留输出文件。
- 每次改动后,必须运行 compare。
- 若 mismatch > 0,禁止进入交付,需先排查差异并补充说明。

238
README.md
View File

@ -1,11 +1,13 @@
# 奇门WMS(qimen-wms)
基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。
基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。基于AI协助管理项目开发,配置了AI能力脚本和完整的项目地图
## 文档导航
- 项目协作工具箱:`AI_TOOLBOX.md`
- AI项目协作工具箱:`AI_TOOLBOX.md`
- Method 路由映射说明:`AI_METHOD_ROUTING.md`
- Model 层级清单:`modelList.md`
- Method 输出一致性回归记录:`METHOD_OUTPUT_REGRESSION_20260322.md`
- system 接口文档源:`methods/system.json`
- qimen 接口文档源:`methods/qimen.json`
- 日报:`day.log`
@ -23,6 +25,7 @@
├── config/ # 配置(poloapi、redis、数据库等)
├── database/ # 迁移与数据库配置
├── methods/ # 接口文档数据源(JSON)
├── native/ # 原生扩展目录(Node.js C++ addon)
├── script/ # 调试与文档生成脚本
├── logs/ # 日志
├── run/ # 运行时/元数据
@ -37,6 +40,7 @@
- `README.md`:项目入口文档,提供整体说明与规范入口。
- `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。
- `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。
- `modelList.md`:model 层级结构与关键说明清单。
- `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。
- `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。
- `day.log`:每日工作留痕。
@ -58,6 +62,102 @@ npm run dev
- `npm run lint`:代码风格检查
- `npm test`:单元测试
## 外部 Method 测试(Egg.js test 规范)
测试文件按“暴露出口 + method”命名,位于 `test/app/controller/`:
- `system.user.login.test.js`
- `system.user.info.test.js`
测试辅助客户端位于:
- `test/support/system_method_client.js`
默认测试账号(可通过环境变量覆盖):
- `SYSTEM_TEST_USERNAME=liufumingren`
- `SYSTEM_TEST_PASSWORD=111111`
Token 暂存机制:
- 登录 token 会写入 `test/.runtime/system_user_token.json`。
- 每次执行测试会优先读取本地 token;若 token 可用,则跳过 `user.login` 调用。
- 当 token 不存在或过期时,测试脚本会自动调用 `user.login` 并刷新缓存。
常用命令:
```bash
npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js
```
可选环境变量:
- `SYSTEM_TEST_BASE_URL`:默认 `http://127.0.0.1:6060`
- `SYSTEM_TEST_TOKEN_FILE`:默认 `test/.runtime/system_user_token.json`
## Method 输出一致性回归(新规则)
目标:
- 在模型/关联/服务改动前后,确保关键 method 输出结果一致。
强制规则:
1. 改动前先执行 baseline(生成修改前输出快照)。
2. 改动后执行 compare(对同一批 method 回放并比对)。
3. compare 结果必须 `mismatch=0` 才可交付。
测试账号(默认):
- `liufumingren / 111111`
- 可通过环境变量覆盖:
- `WMS_TEST_USER`
- `WMS_TEST_PASS`
method 来源与样本来源:
- method 配置来源:`methods/system.json`
- 样本数据来源(优先最新日志):`wms_system_log`
- 参考日志来源:`wms_api_log`、`wms_operation_log`、`wms_account_login_log`
执行脚本:
- `script/method-output-regression.cjs`
- `script/tmp-generate-method-regression-test.cjs`(根据 baseline 自动生成 Egg.js 标注测试)
临时文件目录规则:
- 所有临时产物统一输出到 `temp/`。
- `temp/` 已加入 git 忽略,不纳入提交。
执行命令:
```powershell
# 修改前:生成基线(默认抽样 8 条)
node .\script\method-output-regression.cjs baseline 8
# 修改后:执行对比
node .\script\method-output-regression.cjs compare
# 生成 Egg.js 标注测试脚本
node .\script\tmp-generate-method-regression-test.cjs
# 执行生成的回归测试
npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
```
输出文件:
- `temp/method-output/method-output-baseline.json`
- `temp/method-output/method-output-baseline.md`
- `temp/method-output/method-output-compare.json`
一致性比对说明:
- 为避免误报,脚本会标准化以下波动字段:`token`、`timestamp`、`last_login_at`、`created_at`、`updated_at`、`iat`、`exp`。
- 403 权限响应同样参与一致性对比,用于防止权限链路被意外改动。
- 后续所有接口返回数据检测,统一以生成的 Egg.js 标注测试结果为准。
## 主要依赖
- egg.js 3.x
@ -70,8 +170,6 @@ npm run dev
- `GET /`:健康检查
- `POST /qimen`:奇门接口
- `POST /system`:system 统一入口
- `POST /api/v1`:旧版 API
- `POST /api/v2`:新版 API
- `GET /template/xml/:id`:打印模板
- `GET|POST /auth/printSetting/:code`:打印台设置
@ -88,6 +186,60 @@ npm run dev
- 全局业务 Header(如 `platform`、`project`)设置
- 方法级在线 POST 调试
## 接口响应规范(system)
更新时间:2026-03-22
适用范围:
- `POST /system`
统一目标:
- 统一 `/system` 入口的响应结构与错误码口径,降低调用方分支判断成本。
成功响应示例:
```json
{
"flag": "success",
"code": 1,
"message": "ok",
"data": {},
"timestamp": 1773386721
}
```
失败响应示例:
```json
{
"flag": "failure",
"code": 401,
"message": "Unauthorized",
"data": null,
"timestamp": 1773386721
}
```
说明:
- 业务层若已返回 `flag/code/message` 标准结构,将保留并补齐 `timestamp`。
- 业务层若返回普通对象或数组,控制器将自动包裹到 `data` 字段。
- HTTP 状态码保持语义(如 400/401/403/500),业务 `code` 默认与 HTTP 状态码一致。
当前错误码口径:
- 400:请求参数错误(缺少 `method`、`v`、`timestamp`、非法 `method`)
- 401:未登录/令牌无效/无令牌
- 403:无权限访问
- 406:业务授权状态异常(如仓库有效期)
- 500:服务内部错误
实现位置:
- 响应封装:`app/lib/api_response.js`
- 控制器接入:`app/controller/home.js`(system/pda)
## 接口文档联动维护(强制)
当出现以下任一变更时,必须同步更新 `methods` 下对应文档:
@ -108,6 +260,11 @@ node .\script\tmp-struct-system-params.cjs
```
4. 补充自动提取无法覆盖的信息(description/response/errors/枚举约束)
5. 执行 method 输出一致性对比:
```powershell
node .\script\method-output-regression.cjs compare
```
## 配置说明
@ -115,6 +272,53 @@ node .\script\tmp-struct-system-params.cjs
- 数据库、Redis、平台配置在对应配置文件中维护
- 敏感信息不要提交到仓库
## App 能力清单(汇总)
能力入口文件:
- `app.js`
- `app/extend/application.js`
### A. 应用启动能力(app.js)
- 设置应用根路径:`global.APP_ROOT`、`app.appRoot`
- 启动前初始化动态工厂:
- `OrderDeliveryFactory`
- `OrderItemsFactory`
- 启动时自检扩展能力:
- 缓存方法可用性(`app.setCacheAsync` / `app.getCacheAsync`)
- Message 能力类型检查(`app.Message`)
- 扩展全局日期格式化:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')`
### B. Application 扩展能力(app/extend/application.js)
- 业务字典访问能力:
- `businessDict` getter
- `getBusinessTypeName(code)`
- `getOperationCodeName(code)`
- `getPlatformName(code)`
- `getExternalLogTypeName(type)`
- 外部 SOAP 调用能力:
- `wsdl(methodName, args)`
- Redis 缓存能力(cache client):
- `setCacheAsync(cacheKey, data, expireSeconds = 300)`
- `getCacheAsync(cacheKey)`
- Message 扩展能力:
- `Message` getter(返回 MessageClass)
### C. 迁移完成确认
- 原先在 `app.js` 直接挂载的字典映射方法已迁移到 `app/extend/application.js`。
- 当前 `app.js` 仅保留启动初始化与非方法迁移逻辑,避免双源实现。
### D. Method 输出回归能力(质量门禁)
- 回归脚本:`script/method-output-regression.cjs`
- 基线文件:`temp/method-output/method-output-baseline.json`、`temp/method-output/method-output-baseline.md`
- 对比文件:`temp/method-output/method-output-compare.json`
- 使用方式:先 `baseline`,后 `compare`
- 门禁标准:`mismatch=0` 才允许交付
## 功能模块
- 多快递平台对接(快手/PolyAPI 等)
@ -122,12 +326,38 @@ node .\script\tmp-struct-system-params.cjs
- 打印与打印台管理
- 仓库/门店管理
- 权限与角色管理
- 原生扩展算法能力(native/addons)
## Native 原生扩展能力
目录:`native/addons/`
当前已存在的原生模块:
- `subset_selector.node`(已在业务代码接入)
- 接入位置:`app/service/apiMethods/test.js`
- 已使用能力:`selectOrders(orders, n, type)`
- 业务用途:对订单及 SKU 集合进行子集筛选/组合选择(用于加速 JS 侧大批量集合计算)
- `fibonacci_addon.node`(当前未检索到业务调用)
- 现状:仓库中存在产物文件,但暂无 controller/service 调用链路
当前接入状态说明:
- `subset_selector.node` 在 service 构造时通过 `require(app.appRoot + '/native/addons/subset_selector.node')` 动态加载。
- 若加载失败,日志会记录“C++插件加载失败”,对应方法会因 addon 不可用而无法执行原生算法分支。
兼容性提示:
- Node.js 原生 addon 与运行环境强相关(系统、架构、Node ABI 版本)。
- 当出现 `ERR_DLOPEN_FAILED` / `is not a valid Win32 application` 时,通常表示 addon 与当前 Node 版本或构建目标不匹配,需要使用目标环境重新编译 addon。
## 常见问题
- 启动端口默认 6060,可在配置中调整
- 数据库/Redis 连接失败优先检查 `config/config.local.js`
- 接口路由映射可查阅 `AI_METHOD_ROUTING.md`
- native addon 加载失败(`ERR_DLOPEN_FAILED`)时,优先检查 Node 版本与 addon 构建目标是否一致
## 日报维护

View File

@ -0,0 +1,719 @@
# Service 使用与 API 文档联动审计
更新时间: 2026-03-22
适用阶段: Model 重构阶段 4 及后续代码改造
目的: 在修改 service 前,先确认真实使用链路;若 service 已被使用,则必须同步更新 service、对应 API 文档,并在本文件中记录变更,便于后续复盘。
## 1. 执行规则
- 任何计划修改的 service,必须先确认是否被 systemMethods、qimenMethods、controller 或其他 service 使用。
- 只要存在真实调用链,就不能只改底层 service,必须一起评估上游入口与返回结构。
- 对外暴露为 system/qimen method 的能力,必须同步更新 methods/system.json 或 methods/qimen.json。
- 每次实际修改完成后,必须在本文件末尾追加一条变更记录。
## 2. 本轮已确认的高风险 service 使用链路
### 2.1 账号-仓库-角色关联链路
#### A. app/service/systems/store.js
关键风险:
- 直接使用不存在的 ctx.model.AccountStoreRole。
- 影响门店申请审核、角色分配、角色列表查询。
已确认调用点:
- app/service/systems/store.js:464
- app/service/systems/store.js:679
- app/service/systems/store.js:690
上游 system method:
- app/service/systemMethods/store.js:35 -> store.getStoreRoles
- app/service/systemMethods/store.js:45 -> store.auditApply
对应 API 文档:
- methods/system.json:1976 -> store.getStoreRoles
- methods/system.json:1993 -> store.auditApply
联动要求:
- 若将 AccountStoreRole 收敛为 AccountStoreEmployee 或其他真实模型,必须同步更新:
- app/service/systems/store.js
- app/service/systemMethods/store.js
- methods/system.json 中 store.getStoreRoles / store.auditApply 的参数、返回结构描述
#### B. app/service/systems/auth/user.js
关键风险:
- 当前已部分切到 AccountStoreEmployee,但变量名和注释仍保留 accountStoreRole 旧语义。
- 平台激活逻辑会联动 user.login、user.info、user.changeRole。
已确认调用点:
- app/service/systems/auth/user.js:118 -> changeRole
- app/service/systems/auth/user.js:195 -> info
- app/service/systems/auth/user.js:328 -> findById
- app/service/systems/auth/user.js:877 -> ensurePlatformActiveRole
上游 system method:
- app/service/systemMethods/user.js:11 -> user.login
- app/service/systemMethods/user.js:24 -> user.info
- app/service/systemMethods/user.js:29 -> user.changeRole
对应 API 文档:
- methods/system.json:2016 附近 -> user.login
- methods/system.json:2051 附近 -> user.info
- methods/system.json:2067 附近 -> user.changeRole
联动要求:
- 若修改 activeEmployeeId、employee_id、role_id、roles 列表结构,必须同步更新:
- app/service/systems/auth/user.js
- app/service/systemMethods/user.js
- methods/system.json 中 user.login / user.info / user.changeRole 的返回字段说明
#### C. app/service/systems/account_platform.js
关键风险:
- 该 service 当前直接依赖 AccountStoreRole 幽灵 key。
- 虽然尚未发现对外直接暴露的 system method,但它承载的平台激活角色语义与 auth.user 高度耦合。
已确认调用点:
- app/service/systems/account_platform.js:13 -> switchActiveRole
- app/service/systems/account_platform.js:77 -> getActiveRoleByPlatform
- app/service/systems/account_platform.js:159 -> getMultiplePlatformActiveRoles
- app/service/systems/account_platform.js:219 -> getAllPlatformActives
- app/service/systems/account_platform.js:309 -> getAvailableRoles
间接受影响入口:
- app/service/systems/auth/user.js:58
- app/service/systems/auth/user.js:304
- app/service/systems/auth/user.js:877
文档联动策略:
- 当前没有独立 method 文档入口。
- 若修改本 service 的输入/输出语义,必须回写到 user.login / user.info / user.changeRole 的 API 文档,因为这些接口会消费平台激活角色结果。
### 2.2 动态分表工厂链路
#### A. app/service/systemMethods/order.js
关键风险:
- 依赖 OrderDeliveryFactory / OrderItemsFactory 获取动态模型。
- 若工厂 key、返回模型或字段映射调整,会直接影响系统订单接口。
已确认调用点:
- app/service/systemMethods/order.js:18 -> getOrderModels
- app/service/systemMethods/order.js:98 -> list
- 其他 order.* 方法共享同一组动态模型入口
对应 API 文档:
- methods/system.json:422 -> order.getOrderModels
- methods/system.json:439 -> order.list
- methods/system.json:471 -> order.detail
- methods/system.json:503 -> order.listItems
- methods/system.json:535 -> order.stats
- methods/system.json:560 -> order.updateStatus
- methods/system.json:676 -> order.updateDeliveryTime
联动要求:
- 若修改动态模型获取方式、字段名或订单明细结构,必须同步更新上述 order.* 文档。
#### B. app/service/systems/delivery_order.js 与 app/service/qimenMethods/deliveryorder.js
关键风险:
- qimen 发货单接口直接依赖 OrderDeliveryFactory。
- 若动态分表模型的 key 或查询字段变化,Qimen 接口会受影响。
已确认调用点:
- app/service/systems/delivery_order.js:14
- app/service/systems/delivery_order.js:311
- app/service/qimenMethods/deliveryorder.js:7
- app/service/qimenMethods/deliveryorder.js:8
对应 API 文档:
- methods/qimen.json:14 -> deliveryorder.batchcreate
- methods/qimen.json:88 -> deliveryorder.create
- methods/qimen.json:162 -> deliveryorder.query
联动要求:
- 若修改 deliveryorder 查询、创建、历史表读取逻辑,必须同步更新 qimen deliveryorder.* 文档。
#### C. app/service/apiMethods/test.js
关键风险:
- 存在错误调用名 WmsOrderDeliveryFactory / WmsOrderItemsFactory。
- 这是内部调试链路,不是正式 API 文档入口,但必须与正式工厂 key 保持一致。
已确认调用点:
- app/service/apiMethods/test.js:50
- app/service/apiMethods/test.js:51
联动要求:
- 改动时同步修正为 OrderDeliveryFactory / OrderItemsFactory。
- 无需更新 methods 文档,但必须在本文件记录修复事实。
## 3. 本轮结论
- 即将进入的关联治理不是纯 model 内部调整,至少会影响 store、user、account_platform、order、deliveryorder 这几条真实业务链路。
- 因此后续任何代码改动都不能只改 model。
- 必须按“model -> service -> systemMethods/qimenMethods -> methods 文档 -> 变更记录”的顺序联动处理。
## 4. 修改前检查清单
- 确认目标 service 是否被上游调用。
- 确认上游调用属于 system 还是 qimen 入口。
- 确认 methods/system.json 或 methods/qimen.json 是否存在对应 method。
- 若返回结构变化,先记录旧字段,再补文档。
- 修改完成后,在本文件追加一条变更记录。
## 5. 变更记录模板
### YYYY-MM-DD HH:mm
- 修改范围:
- 涉及 service:
- 上游入口:
- 更新的 API 文档:
- 返回结构变化:
- 兼容处理:
- 验证方式:
## 6. 当前记录
### 2026-03-22 关联治理准备
- 修改范围: 阶段 4 开始前的 service 使用与文档联动审计
- 涉及 service:
- app/service/systems/store.js
- app/service/systems/auth/user.js
- app/service/systems/account_platform.js
- app/service/systemMethods/order.js
- app/service/systems/delivery_order.js
- app/service/qimenMethods/deliveryorder.js
- app/service/apiMethods/test.js
- 上游入口:
- system: store.getStoreRoles, store.auditApply, user.login, user.info, user.changeRole, order.*
- qimen: deliveryorder.batchcreate, deliveryorder.create, deliveryorder.query
- 更新的 API 文档: 尚未改动代码,本轮只完成审计与联动范围确认
- 返回结构变化: 暂无
- 兼容处理: 暂无
- 验证方式: 通过 service 调用搜索、system/qimen method 搜索、methods 文档映射完成静态核对
### 2026-03-22 关联治理执行(第一批)
- 修改范围: 修复 store 链路中 AccountStoreRole 幽灵模型引用
- 涉及 service:
- app/service/systems/store.js
- 上游入口:
- system: store.getStoreRoles, store.auditApply
- 更新的 API 文档:
- methods/system.json
- store.getStoreRoles: 补充 code 参数定义
- store.auditApply: 补充 audit_status/code/store_id/role_ids/reject_reason 参数定义
- 返回结构变化: 无(维持原有 code/message/data 结构)
- 兼容处理:
- 将账号-门店关系绑定到 AccountStoreEmployee
- 将角色绑定落到 EmployeeRole(employee_id + role_id)
- 保持接口出参与状态码行为不变
- 验证方式:
- 运行生成的改造前回归样例测试
- 运行 method-output compare 对比报告
### 2026-03-22 关联治理执行(第二批)
- 修改范围: 修复 account_platform 链路中 AccountStoreRole 幽灵模型引用
- 涉及 service:
- app/service/systems/account_platform.js
- 上游入口:
- 间接影响 system: user.login, user.info, user.changeRole
- 更新的 API 文档:
- 无直接 method 文档变更(本批未新增/修改 system method 参数)
- 返回结构变化: 无(维持 role_id/role_name/role_code/store_id/store_name/store_code 字段)
- 兼容处理:
- switchActiveRole 保持历史参数名 accountStoreRoleId,内部按 employee_id 落库
- include 链路由 AccountStoreRole 改为 AccountStoreEmployee + EmployeeRole + Role + Store
- getAvailableRoles 改为从 AccountStoreEmployee/EmployeeRole 聚合返回
- 验证方式:
- npx egg-bin test test/app/controller/system.method-output.pre-refactor.generated.test.js
- node .\\script\\method-output-regression.cjs compare
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
### 2026-03-22 关联治理执行(第三批)
- 修改范围: 清理 model 层残留命名污染(不改接口结构)
- 涉及 service/model:
- app/model/account.js
- app/model/role.js
- 上游入口:
- 间接影响 system 全链路(仅模型关联定义清理)
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 仅移除 AccountStoreRole 的遗留注释/无效解构,不调整现有 alias
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- npx egg-bin test test/app/controller/system.method-output.batch3.generated.test.js
### 2026-03-22 样例漂移策略更新
- 发现现象:
- 固定历史样例 `system.method-output.pre-refactor.generated.test.js` 因权限/业务数据变化出现与历史快照不一致。
- 策略调整:
- 每批改造前重新冻结当批 baseline,并生成当批 Egg.js 样例测试。
- 历史快照保留审计用途,不作为后续批次唯一门禁。
- 当前批次快照:
- run/method-output-baseline-batch3-20260322_224649.json
- test/app/controller/system.method-output.batch3.generated.test.js
### 2026-03-22 关联治理执行(第四批)
- 修改范围: 统一 alias 命名并引入双轨兼容(复数标准名 + 历史别名保留)
- 涉及 service/model:
- app/model/account.js
- app/model/account_store_employee.js
- app/model/role.js
- app/model/store.js
- app/service/systems/account_platform.js
- app/service/systems/auth/user.js
- 上游入口:
- 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 新增标准 alias:accountStoreEmployees / employeeRoles
- 保留历史 alias:accountStoreRoles / accountStoreEmployee / employeeRole
- service 查询切换到新 alias,并在读取层面对旧 alias 做回退兼容
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
### 2026-03-23 关联治理执行(第四批补充收敛)
- 修改范围: service 层去除旧 alias 回退依赖,统一使用新 alias(保留 model 兼容别名)
- 涉及 service:
- app/service/systems/account_platform.js
- app/service/systems/auth/user.js
- 上游入口:
- 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- account_platform 内部读取改为 employeeRoles 单轨
- model 层兼容 alias 继续保留,避免外部未迁移调用中断
- auth/user 中 accountStoreRole 变量语义更新为 accountStoreEmployee
- 验证方式:
- node .\\script\\method-output-regression.cjs baseline 8
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
### 2026-03-23 关联治理执行(第五批)
- 修改范围: 移除 model 层重复兼容 alias,完成重复关联清理
- 涉及 model:
- app/model/account.js
- app/model/account_store_employee.js
- app/model/role.js
- app/model/store.js
- 上游入口:
- 间接影响 system: user.login, user.info, user.changeRole, store.getStoreRoles
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 删除旧 alias:accountStoreRoles / employeeRole / accountStoreEmployee(Store.hasMany 语义)
- 保留必要单数 alias:AccountPlatformActive.belongsTo(AccountStoreEmployee).as = accountStoreEmployee
- 验证方式:
- node .\\script\\method-output-regression.cjs baseline 8
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
### 2026-03-23 关联治理执行(4.1 全量一致性校验)
- 修改范围: 对 app/model 全量关联定义与数据库真实外键进行一致性审计(无业务代码改动)
- 审计产物:
- association_fk_consistency_report.md
- temp/association-fk-audit.json
- 审计结论:
- DB 外键 51 条,模型关联 89 条,可直接匹配 53 条
- 模型定义但 DB 无外键约束 28 条
- DB 有外键但模型未声明 13 条
- 动态模型/示例占位无法静态解析 5 条
- 影响判断:
- 当前 system 输出门禁未受影响,但存在“模型语义与 DB 约束不完全对齐”的技术债
- 已将高优先级差异并入后续 4.4 规约与治理清单
### 2026-03-23 关联治理执行(第六批:receiving 高优先差异第一批)
- 修改范围: 处理 receiving 链路高优先差异,移除无效模型关联并收敛仓库维度查询条件
- 涉及 service/model:
- app/model/receiving.js
- app/model/receiving_detail.js
- app/service/systems/storage/receiving.js
- 上游入口:
- 间接影响 system: storage.receiving.getReceivingDetail 及 receiving 相关查询/更新链路
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 删除无效关联: `Receiving.hasMany(Storage, foreignKey: 'receiving_id')`
- 删除无效关联: `ReceivingDetail.hasMany(Storage, foreignKey: 'receiving_detail_id')`
- `StoreWarehouse` include/query 统一增加 `warehouse_id + use_status` 过滤,避免跨仓库错关联
- `create` 流程 `store_name` 统一使用 `store_remask`
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 验证结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第七批:4.4 规约文档落地)
- 修改范围: 形成并落地 eager-loading 与 N+1 风险规约(文档治理,无业务代码改动)
- 涉及文档:
- association_eager_loading_n_plus_one_guideline.md
- association_validation_checklist.md
- model_todo.txt
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- 将关联查询的最小约束(include attributes、上下文 where、门禁流程)固化为统一规约
- 验证方式:
- 以第六批回归结果作为当前代码基线(compare mismatch=0,tests 14 passing)
### 2026-03-23 关联治理执行(第八批:store_warehouse/stock_warehouse 语义收敛)
- 修改范围: 修复 stock_store 链路中 `StoreWarehouse` 仅按 `store_id` 关联导致的跨仓误匹配风险
- 涉及 service/model:
- app/service/systems/stock_store.js
- 上游入口:
- 间接影响 system: stock.* 查询链路(库存列表/搜索)
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- `store_stock` include 在 count/findAll/search 三处统一增加 `warehouse_id + use_status` 过滤
- 保持 `required` 策略不变(列表仍 required=true,搜索路径 required=false)
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 验证结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第九批:role/permission 语义收敛)
- 修改范围: 修复 auth/user 权限链路对禁用角色/权限的过滤缺失问题
- 涉及 service/model:
- app/service/systems/auth/user.js
- 上游入口:
- 间接影响 system: user.info(权限与菜单加载链路)
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无(仅收敛为“启用角色/启用权限可见”)
- 兼容处理:
- `getPermissions/getMenus` 在 EmployeeRole 查询中增加 Role.status=1 过滤
- Permission 查询增加 status=1 过滤
- role_id 与 permission_id 查询集合去重
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 验证结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第十批:role_permission 外键迁移落地)
- 修改范围: 落地 `role_permission.permission_id -> permission.id` 的可执行迁移脚本与模型类型对齐
- 涉及 service/model/migration:
- database/migrations/20260323103000-align-role-permission-fk.js
- app/model/role_permission.js
- 上游入口:
- 无直接 system/qimen 返回结构变化
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- 迁移脚本包含保护性校验:存在孤儿数据时直接失败,避免静默脏写
- down 提供外键回滚与字段类型回退
- 审计发现:
- `wms_role_permission.permission_id` 存在 4 条孤儿记录(id: 2, 3, 6, 10)
- `wms_role.store_id` 存在 3 条 `0` 哨兵值(当前不满足直接加 FK 条件)
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 实际执行结果:
- 已创建备份表并落库:
- `wms_role_permission_orphan_backup_20260323`(4 条)
- `wms_role_store_zero_backup_20260323`(3 条)
- 已清洗数据:
- 删除 `wms_role_permission.permission_id` 孤儿 4 条
- 将 `wms_role.store_id=0` 修正为 `NULL` 共 3 条
- 已执行 DDL:
- `wms_role_permission.permission_id` -> `int(11)`
- 新增外键 `fk_wms_role_permission_permission`(ON UPDATE RESTRICT, ON DELETE CASCADE)
- SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`
- 迁移后复核: 孤儿计数=0,role_store_zero=0
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第十一批:role.store_id 外键策略落地)
- 修改范围: 落地 `wms_role.store_id -> wms_store.id` 外键策略(NULL 语义)
- 涉及 migration:
- database/migrations/20260323113000-add-role-store-fk.js
- 上游入口:
- 无直接 system/qimen 返回结构变化
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- `store_id` 字段类型对齐为 `bigint(20) unsigned NULL`
- 新增索引 `idx_store_id`
- 外键策略采用 `ON DELETE SET NULL`,保留历史角色记录的 NULL 语义
- 实际执行结果:
- 外键 `fk_wms_role_store` 已生效(ON UPDATE RESTRICT, ON DELETE SET NULL)
- `wms_role` 孤儿数据复核: 0
- SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第十二批:store_warehouse/stock_warehouse 模型层语义治理)
- 修改范围: 收敛 `store_stock` 关联的模型层复合键表达,统一 include 构造入口
- 涉及 service/model:
- app/model/store_warehouse.js
- app/model/stock_warehouse.js
- app/model/receiving.js
- app/service/systems/stock_store.js
- app/service/systems/storage/receiving.js
- 上游入口:
- 间接影响 system: stock.* / storage.receiving.* 查询链路
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- StoreWarehouse 新增 `buildScopedWhere` 与 `buildStoreStockInclude`,统一生成 `warehouse_id + use_status` 约束
- 复合键语义关联统一显式 `constraints:false`,避免单列外键误解
- service 查询改为复用模型构造器,保持原有 `required` 语义不变
- 验证方式:
- node .\\script\\method-output-regression.cjs compare
- node .\\script\\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 关联治理执行(第十三批:include alias 一致性收尾扫描)
- 修改范围: 阶段 4 收尾检查(全量 include alias 一致性扫描,无业务代码改动)
- 涉及范围:
- app/model/**/*.js(association `as` 定义)
- app/service/**/*.js(include `as` 使用)
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 扫描方法:
- 全量检索 model association 与 service include 的 alias 使用
- 执行自动差集比对(service alias - model alias)
- 扫描结果:
- model alias 总数: 48
- 差集可疑项: 0
- 结论: 未发现 include alias 不一致问题
- 验证方式:
- 通过一次性 Node 差集脚本执行 `service alias - model alias` 自动比对(临时脚本未入库)
### 2026-03-23 关联治理执行(第十四批:permission.parent_id 自关联约束落地)
- 修改范围: 落地 `wms_permission.parent_id -> wms_permission.id` 自关联外键,并统一根节点语义
- 涉及 service/model/migration:
- database/migrations/20260323123000-add-permission-parent-fk.js
- app/model/permission.js
- app/service/systems/auth/user.js
- 上游入口:
- 间接影响 system: user.info(菜单树构建)
- 更新的 API 文档:
- 无(接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 根节点语义由 `parent_id=0` 规范为 `parent_id IS NULL`
- 模型 setter 兼容历史输入:`0 -> NULL`
- 菜单树构建逻辑根判断由 `parent_id===0` 收敛为 `!parent_id`
- 实际执行结果:
- 落库复核:`root_zero_after=0`、`root_null_after=42`、`orphan_after=0`
- 外键 `fk_wms_permission_parent` 已生效(ON UPDATE RESTRICT, ON DELETE SET NULL)
- SequelizeMeta 已登记 `20260323123000-add-permission-parent-fk.js`
- 触发器状态:目标库因权限限制(binlog + SUPER)未创建触发器,采用应用层归一化方案替代
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 模型能力治理执行(第十五批:阶段 5.1 清理清单盘点)
- 修改范围: 阶段 5.1(识别应迁移到 service 层的方法能力,文档治理)
- 涉及文档:
- model_cleanup_list.md
- model_todo.txt
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 盘点结论:
- 模型方法总数: 102
- 第一批应迁移(P1)聚焦: EntryOrder / EntryItems / Storage / RolePermission / Store
- 第一批无调用可清理(P2)已形成清单,待阶段 5.2 执行删除前复核
- 验证方式:
- 静态扫描 model 方法清单与引用关系(仅文档盘点,无业务代码改动)
### 2026-03-23 模型能力治理执行(第十六批:阶段 5.2 第一批无调用方法清理)
- 修改范围: 清理 model 层第一批无调用静态方法(低风险)
- 涉及 model:
- app/model/api_app.js
- app/model/interface_type.js
- app/model/print_item.js
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- 清理前执行全局引用复核,确认仅在定义处出现
- 仅删除静态 helper,不触碰关联定义与实例方法
- 删除项:
- ApiApp.findByAppKey / ApiApp.findByQimenConfig
- InterfaceType.findByCode / InterfaceType.findEnabled
- PrintItem.getGroupFields / PrintItem.getTableConfigs
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- tests: 14 passing
### 2026-03-23 模型能力治理执行(第十七批:阶段 5.2 第二批无调用方法清理)
- 修改范围: 清理 model 层第二批无调用静态方法(低风险)
- 涉及 model:
- app/model/i18n_translation.js
- app/model/stock_store.js
- 上游入口:
- 无直接 system/qimen 行为变更
- 更新的 API 文档:
- 无
- 返回结构变化: 无
- 兼容处理:
- 清理前已完成删除前引用复核(service/controller/test/script 全仓扫描)
- 仅删除静态 helper,不触碰关联定义、字段定义与实例方法
- 删除项:
- I18nTranslation.getTranslation / I18nTranslation.batchGetTranslations / I18nTranslation.getProjectTranslations / I18nTranslation.upsertTranslation / I18nTranslation.getUntranslated
- StockStore.findByItemCode / StockStore.findByStore
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
- 回归结果:
- compare: total=8, mismatch=0
- generated regression: 8 passing
- smoke: 6 passing
- tests: 14 passing
- 回归结果:
- compare: total=8, mismatch=0
- generated regression: 8 passing
- smoke: 6 passing
- tests: 14 passing
### 2026-03-23 模型能力治理执行(第十八批:阶段 5.2 P1 第一组迁移)
- 修改范围: 将 EntryOrder / EntryItems 的内部静态方法迁移到 service,收敛 model 职责
- 涉及 service/model:
- app/service/systems/entry_order.js
- app/model/entry_order.js
- app/model/entry_items.js
- 上游入口:
- 无直接新增 system/qimen method;属于内部服务能力收敛
- 更新的 API 文档:
- 无(对外接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 迁移 `EntryOrder.findByOrderCode/findByStatus/getStatsByWarehouse/updateSyncStatus/updateOrderStatus/calculateReceivedQuantities`
- 迁移 `EntryItems.batchUpdateReceived/getOrderProgress`
- `calculateReceivedQuantities` 改为 service 侧显式聚合 `wms_storage`,避免 model 版相关子查询别名不稳定
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
### 2026-03-23 模型能力治理执行(第十九批:阶段 5.2 P1 第二组迁移)
- 修改范围: 将 Storage 的内部静态方法迁移到 service,收敛 model 职责
- 涉及 service/model:
- app/service/systems/storage/index.js
- app/model/storage.js
- 上游入口:
- 无直接新增 system/qimen method;属于内部服务能力收敛
- 更新的 API 文档:
- 无(对外接口参数与返回结构未变化)
- 返回结构变化: 无
- 兼容处理:
- 迁移 `Storage.findByStockAndBatch/findBySpace/findAvailableByWarehouse/findExpiringSoon/updateQuantity/lockQuantity/unlockQuantity/allocateQuantity/getStockSummary/getSpaceUsage`
- 模型层仅保留实例行为与关联定义,跨记录聚合与更新能力归并到 service
- 验证方式:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js

29
app.js
View File

@ -1,39 +1,12 @@
// app.js
const path = require('path');
const businessDict = require('./app/dict/businessDict.js');
// 直接导出函数,而不是类
module.exports = app => {
// 设置全局应用根目录
global.APP_ROOT = path.resolve(__dirname, './');
app.appRoot = APP_ROOT;
// ========== 挂载字典到 app ==========
app.businessDict = businessDict;
// 添加字典工具方法
app.getBusinessTypeName = code => {
const dict = app.businessDict.BUSINESS_TYPE || {};
for (const key in dict) {
if (dict[key].code === code) {
return dict[key].name;
}
}
return code;
};
app.getOperationCodeName = code => {
return app.businessDict.OPERATION_CODE?.[code] || code;
};
app.getPlatformName = code => {
return app.businessDict.PLATFORM_CODE?.[code] || code;
};
app.getExternalLogTypeName = type => {
return app.businessDict.EXTERNAL_LOG_TYPE?.[type] || type;
};
app.logger.info('✅ 业务字典已挂载到 app');
app.logger.info('✅ Application 扩展能力已加载');
// 初始化工厂
app.beforeStart(async () => {
// skip factory init when model layer is absent (e.g. during tests)

View File

@ -1,169 +0,0 @@
const { Controller } = require('egg');
class ApiV2Controller extends Controller {
async index() {
const { ctx, service } = this;
ctx.query_count = 1;
const startTime = Date.now();
const logData = {
method: '',
v: '',
url: ctx.request.href,
created_at: new Date(),
body: '',
headers: JSON.stringify(ctx.headers),
result: '',
use_time: 0,
auth: '',
store_id: null,
};
try {
const getParams = ctx.query;
logData.method = getParams.method || '';
logData.v = getParams.v || '';
// 验证必要参数
if (!service.system.validateParams(getParams)) {
const errorMsg = '参数缺失或错误';
const response = this.errorResponse(errorMsg, 'json');
logData.result = response;
service.system.saveLog(logData, startTime);
ctx.body = response;
ctx.type = 'application/json';
return;
}
const authHeader = ctx.headers.authorization;
ctx.device = ctx.headers.device;
ctx.project = ctx.headers.project;
// 处理method参数
const method = getParams.method;
const methods = method.split('.');
const actionName = methods.pop();
const className = methods
.map((item, index) =>
(index === methods.length - 1 ? item : item)
)
.join('.');
// 获取JSON数据
let jsonData = '';
if (ctx.request.rawBody) {
jsonData = ctx.request.rawBody;
} else {
jsonData = await new Promise((resolve, reject) => {
let data = '';
ctx.req.on('data', chunk => {
data += chunk;
});
ctx.req.on('end', () => {
resolve(data);
});
ctx.req.on('error', reject);
});
}
jsonData = jsonData ? String(jsonData) : '';
logData.body = jsonData;
if (!jsonData || jsonData.trim() === '') {
throw new Error('json数据为空');
}
try {
jsonData = JSON.parse(jsonData);
} catch (e) {
throw new Error('json数据解析错误');
}
// 调用扁平 dispatcher 服务
const { isLog, result } = await service.dispatcher.invoke(
getParams.method,
jsonData,
authHeader,
ctx
);
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
if (ctx.user) {
logData.auth = JSON.stringify(ctx.user);
logData.store_id = ctx.user.store_id;
}
// 保存原来的日志逻辑仍然通过 system.saveLog
if (isLog) {
service.system.saveLog(logData, startTime);
}
if (result.status && result.status !== 200) {
// propagate failure message
ctx.body = result.message ? { message: result.message } : result.data;
} else {
ctx.body = result.data;
}
ctx.type = 'application/json';
ctx.status = result.status || 200;
} catch (error) {
ctx.status = 500;
console.log(error);
const response = this.errorResponse('接口错误: ' + error.message, 'json');
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
service.system.saveLog(logData, startTime);
ctx.body = response;
ctx.type = 'application/json';
}
}
validateParams(params) {
const required = [ 'method', 'v', 'format', 'timestamp' ];
for (const field of required) {
if (!params[field]) {
return false;
}
}
if (typeof params.method !== 'string' || !params.method.includes('.')) {
return false;
}
return true;
}
errorResponse(message, format = 'json') {
const timestamp = Math.floor(Date.now() / 1000);
if (format.toLowerCase() === 'xml') {
return `<?xml version="1.0" encoding="UTF-8"?>
<response>
<flag>failure</flag>
<code>0</code>
<message>${this.escapeXml(message)}</message>
</response>`;
}
return {
flag: false,
message,
code: 0,
timestamp,
};
}
escapeXml(unsafe) {
if (!unsafe) return '';
return unsafe.replace(/[<>&'\"]/g, c => {
switch (c) {
case '<':
return '&lt;';
case '>':
return '&gt;';
case '&':
return '&amp;';
case "'":
return '&apos;';
case '"':
return '&quot;';
default:
return c;
}
});
}
}
module.exports = ApiV2Controller;

View File

@ -1,9 +1,10 @@
const {
Controller,
} = require('egg');
const { toSuccess, toFailure } = require('../lib/api_response');
class HomeController extends Controller {
async testSendData(){
async testSendData() {
await this.ctx.service.systems.print.index.test();
this.ctx.body = 'ok';
}
@ -13,97 +14,6 @@ class HomeController extends Controller {
} = this;
ctx.body = 'pong';
}
async v1() {
const {
ctx,
service,
} = this;
const startTime = Date.now();
// 初始化日志数据
const logData = {
app_key: '',
method: '',
sign: '',
costomer_id: '',
v: '',
url: ctx.request.href,
created_at: new Date(),
body: '',
result: '',
use_time: 0,
};
try {
const getParams = ctx.query;
logData.method = getParams.method || '';
logData.v = getParams.v || '';
// 验证必要参数
if (!this.validateParams(getParams)) {
const errorMsg = '参数缺失或错误';
const response = this.errorResponse(errorMsg, 'json');
logData.result = response;
await this.saveLog(logData, startTime);
ctx.body = response;
ctx.type = 'application/json';
return;
}
// 处理method参数
const method = getParams.method;
const methods = method.split('.');
const actionName = methods.pop();
const className = methods.map((item, index) =>
(index === methods.length - 1 ? item : item)
).join('.');
// 获取XML数据
let jsonData = '';
if (ctx.request.rawBody) {
// 使用 rawBody 获取原始请求体
jsonData = ctx.request.rawBody;
} else {
// 如果没有 rawBody,尝试从流中读取
jsonData = await new Promise((resolve, reject) => {
let data = '';
ctx.req.on('data', chunk => {
data += chunk;
});
ctx.req.on('end', () => {
resolve(data);
});
ctx.req.on('error', reject);
});
}
// 确保 xmlData 是字符串
jsonData = jsonData ? String(jsonData) : '';
logData.body = jsonData;
if (!jsonData || jsonData.trim() === '') {
throw new Error('json数据为空');
}
try {
jsonData = JSON.parse(jsonData);
} catch (e) {
throw new Error('json数据解析错误');
}
// 调用业务方法
const result = await service.api.callMethod(className, actionName, jsonData, getParams.format);
// 记录成功响应
logData.result = typeof result === 'string' ? result : JSON.stringify(result);
await this.saveLog(logData, startTime);
ctx.body = result;
ctx.type = getParams.format === 'xml' ? 'application/xml' : 'application/json';
} catch (error) {
ctx.logger.error('调用接口失败返回数据', error);
const response = this.errorResponse('接口错误: ' + error.message, ctx.query.format || 'json');
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
await this.saveLog(logData, startTime);
ctx.body = response;
ctx.type = ctx.query.format === 'xml' ? 'application/xml' : 'application/json';
}
}
async qimen() {
const {
ctx,
@ -198,9 +108,9 @@ class HomeController extends Controller {
// 入库单提取
try {
warehouseCode = xmlArray.request?.entryOrder?.warehouseCode ||
xmlArray.request?.deliveryOrder?.warehouseCode ||
'';
} catch (e) {}
xmlArray.request?.deliveryOrder?.warehouseCode ||
'';
} catch (e) { }
}
if (warehouseCode && customerId) {
// 验证接口是否存在且启用
@ -273,7 +183,7 @@ class HomeController extends Controller {
}
validateParams(params) {
const required = [ 'method', 'v', 'format', 'timestamp' ];
const required = ['method', 'v', 'format', 'timestamp'];
for (const field of required) {
if (!params[field]) {
@ -289,7 +199,7 @@ class HomeController extends Controller {
return true;
}
validateQimenParams(params) {
const required = [ 'app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp' ];
const required = ['app_key', 'method', 'v', 'format', 'sign_method', 'sign', 'timestamp'];
for (const field of required) {
if (!params[field]) {
@ -403,13 +313,17 @@ class HomeController extends Controller {
const getParams = ctx.query;
logData.method = getParams.method || '';
logData.v = getParams.v || '';
// 验证必要参数
if (!service.system.validateParams(getParams)) {
const errorMsg = '参数缺失或错误';
const response = this.errorResponse(errorMsg, 'json');
const requestCheck = service.system.validateRequestContext(getParams, ctx.headers);
if (!requestCheck.ok) {
const response = toFailure({
message: requestCheck.message,
httpStatus: requestCheck.status,
code: requestCheck.code,
});
logData.result = response;
service.system.saveLog(logData, startTime);
ctx.body = response;
ctx.status = requestCheck.status;
ctx.type = 'application/json';
return;
}
@ -464,13 +378,26 @@ class HomeController extends Controller {
if (isLog) {
service.system.saveLog(logData, startTime);
}
ctx.body = result.data;
if (result.status && result.status !== 200) {
ctx.body = toFailure({
message: result.message || '请求失败',
httpStatus: result.status,
code: result.code,
data: result.data || null,
});
} else {
ctx.body = toSuccess(result.data);
}
ctx.type = 'application/json';
ctx.status = result.status || 200;
} catch (error) {
ctx.status = 500;
console.log(error);
const response = this.errorResponse('接口错误: ' + error.message, 'json');
const response = toFailure({
message: '接口错误: ' + error.message,
httpStatus: 500,
code: 500,
});
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
service.system.saveLog(logData, startTime);
ctx.body = response;
@ -506,13 +433,17 @@ class HomeController extends Controller {
const getParams = ctx.query;
logData.method = getParams.method || '';
logData.v = getParams.v || '';
// 验证必要参数
if (!service.system.validateParams(getParams)) {
const errorMsg = '参数缺失或错误';
const response = this.errorResponse(errorMsg, 'json');
const requestCheck = service.system.validateRequestContext(getParams, ctx.headers);
if (!requestCheck.ok) {
const response = toFailure({
message: requestCheck.message,
httpStatus: requestCheck.status,
code: requestCheck.code,
});
logData.result = response;
service.system.saveLog(logData, startTime);
ctx.body = response;
ctx.status = requestCheck.status;
ctx.type = 'application/json';
return;
}
@ -569,13 +500,26 @@ class HomeController extends Controller {
if (isLog) {
service.system.saveLog(logData, startTime);
}
ctx.body = result.data;
if (result.status && result.status !== 200) {
ctx.body = toFailure({
message: result.message || '请求失败',
httpStatus: result.status,
code: result.code,
data: result.data || null,
});
} else {
ctx.body = toSuccess(result.data);
}
ctx.type = 'application/json';
ctx.status = result.status || 200;
} catch (error) {
ctx.status = 500;
console.log(error);
const response = this.errorResponse('接口错误: ' + error.message, 'json');
const response = toFailure({
message: '接口错误: ' + error.message,
httpStatus: 500,
code: 500,
});
logData.result = typeof response === 'string' ? response : JSON.stringify(response);
service.system.saveLog(logData, startTime);
ctx.body = response;

View File

@ -4,8 +4,30 @@ class MessageClass {
}
}
const soap = require('soap');
const businessDict = require('../dict/businessDict');
const MESSAGE_CLASS = Symbol('Application#Message');
module.exports = {
get businessDict() {
return businessDict;
},
getBusinessTypeName(code) {
const dict = this.businessDict.BUSINESS_TYPE || {};
for (const key in dict) {
if (dict[key].code === code) {
return dict[key].name;
}
}
return code;
},
getOperationCodeName(code) {
return this.businessDict.OPERATION_CODE?.[code] || code;
},
getPlatformName(code) {
return this.businessDict.PLATFORM_CODE?.[code] || code;
},
getExternalLogTypeName(type) {
return this.businessDict.EXTERNAL_LOG_TYPE?.[type] || type;
},
async wsdl(methodName, args) {
try {
const wsdlUrl = "http://ye4s.com/webservice/ws?wsdl";

59
app/lib/api_response.js Normal file
View File

@ -0,0 +1,59 @@
'use strict';
function nowTimestamp() {
return Math.floor(Date.now() / 1000);
}
function isObject(value) {
return value && typeof value === 'object' && !Array.isArray(value);
}
function isStandardPayload(payload) {
return isObject(payload)
&& Object.prototype.hasOwnProperty.call(payload, 'flag')
&& Object.prototype.hasOwnProperty.call(payload, 'code')
&& Object.prototype.hasOwnProperty.call(payload, 'message');
}
function toSuccess(payload, message = 'ok') {
if (isStandardPayload(payload)) {
const normalized = {
...payload,
flag: payload.flag === true || payload.flag === 'success' ? 'success' : payload.flag,
};
if (!Object.prototype.hasOwnProperty.call(normalized, 'timestamp')) {
normalized.timestamp = nowTimestamp();
}
return normalized;
}
return {
flag: 'success',
code: 1,
message,
data: payload ?? null,
timestamp: nowTimestamp(),
};
}
function toFailure(options = {}) {
const {
message = '请求失败',
httpStatus = 500,
code,
data = null,
} = options;
return {
flag: 'failure',
code: typeof code === 'number' ? code : httpStatus,
message,
data,
timestamp: nowTimestamp(),
};
}
module.exports = {
toSuccess,
toFailure,
};

View File

@ -133,12 +133,9 @@ module.exports = app => {
// 关联关系
Account.associate = function(models) {
const { AccountStoreEmployee, AccountPlatformActive } = app.model;
/* if (models.AccountStoreRole) {
}*/
Account.hasMany(AccountStoreEmployee, {
foreignKey: 'account_id',
as: 'accountStoreRoles',
as: 'accountStoreEmployees',
});
Account.hasMany(AccountPlatformActive, {
foreignKey: 'account_id',

View File

@ -94,7 +94,7 @@ module.exports = app => {
});
AccountStoreEmployee.hasMany(EmployeeRole, {
foreignKey: 'employee_id',
as: 'employeeRole',
as: 'employeeRoles',
});
AccountStoreEmployee.hasMany(Receiving, {
foreignKey: 'creator_id',

View File

@ -288,22 +288,5 @@ module.exports = app => {
return generatedSignature === signature;
};
// 类方法 - 根据AppKey查找
ApiApp.findByAppKey = async function(appKey) {
return await this.findOne({
where: { self_app_key: appKey },
});
};
// 类方法 - 根据奇门配置查找
ApiApp.findByQimenConfig = async function(appKey, customerId) {
return await this.findOne({
where: {
qimen_app_key: appKey,
qimen_customer_id: customerId,
},
});
};
return ApiApp;
};

View File

@ -191,74 +191,6 @@ module.exports = app => {
};
};
// 静态方法 - 批量更新收货数量(带验证)
EntryItems.batchUpdateReceived = async function(app, updates, options = {}) {
const transaction = options.transaction || await app.model.transaction();
try {
// 先检查所有更新是否合法
for (const update of updates) {
const { id, quantity } = update;
const item = await app.model.EntryItems.findByPk(id, { transaction });
if (!item) {
throw new Error(`入库明细 ${id} 不存在`);
}
// 验证数量
item.validateReceiveQuantity(quantity);
}
// 执行更新
for (const update of updates) {
const { id, quantity } = update;
const item = await app.model.EntryItems.findByPk(id, { transaction });
const newReceived = (item.received_quantity || 0) + quantity;
await item.update({
received_quantity: newReceived,
}, { transaction });
}
if (!options.transaction) {
await transaction.commit();
}
return { success: true };
} catch (error) {
if (!options.transaction) {
await transaction.rollback();
}
throw error;
}
};
// 静态方法 - 获取入库单总进度
EntryItems.getOrderProgress = async function(app, orderId) {
const items = await app.model.EntryItems.findAll({
where: { order_id: orderId },
attributes: [
[ app.Sequelize.fn('SUM', app.Sequelize.col('count')), 'total_plan' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('received_quantity')), 'total_received' ],
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'item_count' ],
],
raw: true,
});
const result = items[0] || {};
const totalPlan = parseInt(result.total_plan) || 0;
const totalReceived = parseInt(result.total_received) || 0;
return {
total_plan: totalPlan,
total_received: totalReceived,
total_remaining: Math.max(0, totalPlan - totalReceived),
item_count: parseInt(result.item_count) || 0,
progress_percent: totalPlan > 0 ? Math.min(100, Math.round((totalReceived / totalPlan) * 100)) : 0,
is_completed: totalReceived >= totalPlan,
};
};
// 钩子函数 - 保存前验证
EntryItems.beforeSave(async (instance, options) => {
const received = instance.received_quantity || 0;

View File

@ -275,237 +275,5 @@ module.exports = app => {
return this.is_enabled === 1 && !this.deleted_at;
};
// 静态方法
EntryOrder.findByOrderCode = async function(app, entryOrderCode, warehouseId, storeId) {
return await app.model.EntryOrder.findOne({
where: {
entry_order_code: entryOrderCode,
warehouse_id: warehouseId,
store_id: storeId,
is_enabled: 1,
deleted_at: null,
},
include: [
{
model: app.model.Store,
as: 'warehouse',
attributes: [ 'store_name', 'store_code' ],
},
{
model: app.model.Store,
as: 'store',
attributes: [ 'store_name' ],
},
{
model: app.model.EntryItems,
as: 'items',
include: [{
model: app.model.StockWarehouse,
as: 'stock',
attributes: [ 'product_code', 'product_name' ],
}],
},
],
});
};
EntryOrder.findByStatus = async function(app, status, params = {}) {
const { warehouse_id, store_id, start_date, end_date, page = 1, pageSize = 20 } = params;
const where = {
order_status: status,
is_enabled: 1,
deleted_at: null,
};
if (warehouse_id) {
where.warehouse_id = warehouse_id;
}
if (store_id) {
where.store_id = store_id;
}
if (start_date || end_date) {
where.created_at = {};
if (start_date) {
where.created_at[app.Sequelize.Op.gte] = start_date;
}
if (end_date) {
where.created_at[app.Sequelize.Op.lte] = end_date;
}
}
const { count, rows } = await app.model.EntryOrder.findAndCountAll({
where,
include: [
{
model: app.model.Store,
as: 'warehouse',
attributes: [ 'store_name' ],
},
{
model: app.model.Store,
as: 'store',
attributes: [ 'store_name' ],
},
],
order: [[ 'created_at', 'DESC' ]],
offset: (page - 1) * pageSize,
limit: parseInt(pageSize),
distinct: true,
});
return {
list: rows,
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total: count,
totalPages: Math.ceil(count / pageSize),
},
};
};
EntryOrder.getStatsByWarehouse = async function(app, warehouseId, startDate, endDate) {
const where = {
warehouse_id: warehouseId,
is_enabled: 1,
deleted_at: null,
};
if (startDate || endDate) {
where.created_at = {};
if (startDate) {
where.created_at[app.Sequelize.Op.gte] = startDate;
}
if (endDate) {
where.created_at[app.Sequelize.Op.lte] = endDate;
}
}
const result = await app.model.EntryOrder.findAll({
attributes: [
'order_status',
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'count' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('total_order_lines')), 'total_lines' ],
],
where,
group: [ 'order_status' ],
raw: true,
});
const stats = {
pending: 0,
confirmed: 0,
partial_received: 0,
completed: 0,
cancelled: 0,
total: 0,
total_lines: 0,
};
result.forEach(item => {
const status = item.order_status.toLowerCase();
if (stats[status] !== undefined) {
stats[status] = parseInt(item.count) || 0;
}
stats.total += parseInt(item.count) || 0;
stats.total_lines += parseInt(item.total_lines) || 0;
});
return stats;
};
EntryOrder.updateSyncStatus = async function(app, orderId, status, message = null) {
const order = await app.model.EntryOrder.findByPk(orderId);
if (!order) {
throw new Error('入库单不存在');
}
const updateData = {
sync_status: status,
};
if (message !== null) {
updateData.sync_message = message;
}
return await order.update(updateData);
};
EntryOrder.updateOrderStatus = async function(app, orderId, status) {
const order = await app.model.EntryOrder.findByPk(orderId);
if (!order) {
throw new Error('入库单不存在');
}
const validTransitions = {
PENDING: [ 'CONFIRMED', 'CANCELLED' ],
CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ],
PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ],
CREATED: [ 'PENDING', 'CANCELLED' ],
CREATING: [ 'PENDING', 'CANCELLED' ],
};
const allowedTransitions = validTransitions[order.order_status];
if (!allowedTransitions || !allowedTransitions.includes(status)) {
throw new Error(`状态从${order.order_status}转换到${status}不被允许`);
}
return await order.update({ order_status: status });
};
EntryOrder.calculateReceivedQuantities = async function(app, orderId) {
// 这里需要根据实际业务逻辑计算已收货数量
// 通常需要查询入库明细和实际收货记录
// 示例:查询入库明细
const items = await app.model.EntryItems.findAll({
where: { order_id: orderId },
attributes: [
'id',
'count',
[ app.Sequelize.literal('(SELECT SUM(quantity) FROM wms_storage WHERE inbound_order_no = wms_entry_order.entry_order_code AND item_id = wms_entry_items.item_id)'), 'received' ],
],
include: [{
model: app.model.EntryOrder,
as: 'order',
attributes: [ 'entry_order_code' ],
}],
});
let totalExpected = 0;
let totalReceived = 0;
let allReceived = true;
let anyReceived = false;
items.forEach(item => {
const expected = item.count || 0;
const received = item.received || 0;
totalExpected += expected;
totalReceived += received;
if (expected > 0 && received < expected) {
allReceived = false;
}
if (received > 0) {
anyReceived = true;
}
});
return {
total_expected: totalExpected,
total_received: totalReceived,
all_received: allReceived,
any_received: anyReceived,
percentage: totalExpected > 0 ? Math.round((totalReceived / totalExpected) * 100) : 0,
};
};
return EntryOrder;
};

View File

@ -2,7 +2,7 @@
'use strict';
module.exports = app => {
const { STRING, INTEGER, DATE, Op } = app.Sequelize;
const { STRING, INTEGER } = app.Sequelize;
// 直接在文件中定义常量
const CONSTANTS = {
@ -60,123 +60,5 @@ module.exports = app => {
// 挂载常量到模型(可选)
I18nTranslation.CONSTANTS = CONSTANTS;
/**
* 获取翻译
* @param keyId
* @param language
*/
I18nTranslation.getTranslation = async function(keyId, language) {
return await this.findOne({
where: { key_id: keyId, language },
include: [{
model: app.model.I18nKey,
as: 'key',
}],
});
};
/**
* 批量获取翻译
* @param keyIds
* @param language
*/
I18nTranslation.batchGetTranslations = async function(keyIds, language) {
const records = await this.findAll({
where: {
key_id: keyIds,
language,
},
include: [{
model: app.model.I18nKey,
as: 'key',
attributes: [ 'key_name' ],
}],
});
// 返回键值对
const result = {};
records.forEach(record => {
if (record.key) {
result[record.key.key_name] = record.translation || record.key.key_name;
}
});
return result;
};
/**
* 获取项目翻译
* @param project
* @param language
*/
I18nTranslation.getProjectTranslations = async function(project, language) {
const records = await this.findAll({
include: [{
model: app.model.I18nKey,
as: 'key',
where: { project },
attributes: [ 'key_name' ],
}],
where: { language },
});
const result = {};
records.forEach(record => {
if (record.key && record.key.key_name) {
result[record.key.key_name] = record.translation || record.key.key_name;
}
});
return result;
};
/**
* 创建或更新翻译
* @param keyId
* @param language
* @param translation
*/
I18nTranslation.upsertTranslation = async function(keyId, language, translation) {
const [ record, created ] = await this.findOrCreate({
where: { key_id: keyId, language },
defaults: {
key_id: keyId,
language,
translation: translation || null,
translation_status: translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED,
},
});
if (!created) {
record.translation = translation || null;
record.translation_status = translation ? CONSTANTS.TRANSLATION_STATUS.PENDING_REVIEW : CONSTANTS.TRANSLATION_STATUS.UNTRANSLATED;
await record.save();
}
return record;
};
/**
* 获取未翻译列表
* @param language
* @param project
*/
I18nTranslation.getUntranslated = async function(language, project) {
return await this.findAll({
include: [{
model: app.model.I18nKey,
as: 'key',
where: { project },
}],
where: {
language,
[Op.or]: [
{ translation: null },
{ translation: '' },
],
},
});
};
return I18nTranslation;
};

View File

@ -104,27 +104,6 @@ module.exports = app => {
],
});
// 类方法 - 根据接口编码查找
InterfaceType.findByCode = async function(interfaceCode) {
return await this.findOne({
where: { interface_code: interfaceCode },
});
};
// 类方法 - 获取启用的接口列表
InterfaceType.findEnabled = async function(category = null) {
const where = { is_enabled: 1 };
if (category) {
where.interface_category = category;
}
return await this.findAll({
where,
order: [[ 'interface_name', 'ASC' ]],
});
};
// 实例方法 - 检查接口是否可用
InterfaceType.prototype.isAvailable = function() {
return this.is_enabled === 1;

View File

@ -72,8 +72,11 @@ module.exports = app => {
},
parent_id: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
allowNull: true,
defaultValue: null,
set(value) {
this.setDataValue('parent_id', value === 0 ? null : value);
},
comment: '父级ID',
},
sort: {
@ -242,7 +245,7 @@ module.exports = app => {
permissions.forEach(permission => {
const node = permissionMap.get(permission.id);
if (permission.parent_id === 0) {
if (!permission.parent_id) {
rootPermissions.push(node);
} else {
const parent = permissionMap.get(permission.parent_id);

View File

@ -232,37 +232,6 @@ module.exports = app => {
return this.table_config;
};
// 类方法:获取指定业务类型的分组字段
PrintItem.getGroupFields = async function(businessType, platform) {
return await this.findAll({
where: {
business_type: businessType,
platform: platform || 'default',
group_field: {
[app.Sequelize.Op.ne]: null,
},
status: 1,
},
order: [
[ 'group_sort', 'ASC' ],
[ 'sort_order', 'ASC' ],
],
});
};
// 类方法:获取指定业务类型的表格配置
PrintItem.getTableConfigs = async function(businessType, platform) {
return await this.findAll({
where: {
business_type: businessType,
platform: platform || 'default',
is_table: true,
status: 1,
},
order: [[ 'sort_order', 'ASC' ]],
});
};
// 关联方法
PrintItem.associate = function() {
// 如果需要关联其他表,在这里添加

View File

@ -144,7 +144,7 @@ module.exports = app => {
// 关联定义
Receiving.associate = function() {
const { ReceivingDetail, Store, AccountStoreEmployee, Storage, StoreWarehouse } = app.model;
const { ReceivingDetail, Store, AccountStoreEmployee, StoreWarehouse } = app.model;
// 关联收货明细
Receiving.hasMany(ReceivingDetail, {
foreignKey: 'receiving_id',
@ -163,15 +163,12 @@ module.exports = app => {
as: 'creator',
});
// 关联入库记录
Receiving.hasMany(Storage, {
foreignKey: 'receiving_id',
as: 'storage_records',
});
// wms_storage 无 receiving_id 字段,避免声明无效关联。
Receiving.belongsTo(StoreWarehouse, {
foreignKey: 'store_id', // 当前表的外键字段
targetKey: 'store_id', // 关联表的主键字段
targetKey: 'store_id', // 关联表的业务键字段(非主键)
as: 'store',
constraints: false,
});
};

View File

@ -143,7 +143,7 @@ module.exports = app => {
});
ReceivingDetail.associate = function() {
const { Receiving, StockWarehouse, Storage, LocationSpace } = app.model;
const { Receiving, StockWarehouse, LocationSpace } = app.model;
// 关联主表
ReceivingDetail.belongsTo(Receiving, {
foreignKey: 'receiving_id',
@ -156,12 +156,6 @@ module.exports = app => {
as: 'system_product',
});
// 关联入库记录
ReceivingDetail.hasMany(Storage, {
foreignKey: 'receiving_detail_id',
as: 'storage_details',
});
// 关联系统商品
ReceivingDetail.belongsTo(LocationSpace, {
foreignKey: 'space_id',

View File

@ -148,7 +148,7 @@ module.exports = app => {
// 关联关系
Role.associate = function(models) {
const { Account, Store, Permission, AccountStoreRole, RolePermission, EmployeeRole } = app.model;
const { Account, Store, Permission, RolePermission, EmployeeRole } = app.model;
// 创建人
Role.belongsTo(Account, {
foreignKey: 'created_by',
@ -171,7 +171,7 @@ module.exports = app => {
Role.hasMany(EmployeeRole, {
foreignKey: 'role_id',
sourceKey: 'id',
as: 'employeeRole',
as: 'employeeRoles',
});
};

View File

@ -1,7 +1,7 @@
'use strict';
module.exports = app => {
const { BIGINT, DATE } = app.Sequelize;
const { BIGINT, INTEGER, DATE } = app.Sequelize;
const RolePermission = app.model.define('role_permission', {
id: {
@ -17,7 +17,7 @@ module.exports = app => {
comment: '角色ID',
},
permission_id: {
type: BIGINT.UNSIGNED,
type: INTEGER,
allowNull: false,
comment: '权限ID',
},

View File

@ -362,45 +362,6 @@ module.exports = app => {
});
};
// 类方法 - 根据商品编码查找
StockStore.findByItemCode = async function(itemCode, options = {}) {
const where = { item_code: itemCode, is_valid: 'Y' };
if (options.warehouse_id) {
where.warehouse_id = options.warehouse_id;
}
if (options.store_id) {
where.store_id = options.store_id;
}
return await this.findOne({
where,
include: options.include || [],
});
};
// 类方法 - 获取商家的商品列表
StockStore.findByStore = async function(storeId, options = {}) {
const where = { store_id: storeId, is_valid: 'Y' };
if (options.warehouse_id) {
where.warehouse_id = options.warehouse_id;
}
if (options.owner_code) {
where.owner_code = options.owner_code;
}
return await this.findAll({
where,
include: options.include || [],
order: options.order || [[ 'create_time', 'DESC' ]],
limit: options.limit,
offset: options.offset,
});
};
// 实例方法 - 检查商品是否有效
StockStore.prototype.isValid = function() {
return this.is_valid === 'Y' && !this.delete_at;

View File

@ -224,11 +224,12 @@ module.exports = app => {
StockWarehouse.associate = function(models) {
const { StoreWarehouse, StockBarcode, ProhibitedType, StockImage, StockStore, Storage } = app.model;
// 授权关系属于商家 - 修正:需要确认StoreWarehouse模型是否有store_id字段
// store_stock 关联依赖 store_id + warehouse_id 复合语义,单列关联仅作为 include 入口。
StockWarehouse.belongsTo(StoreWarehouse, {
foreignKey: 'store_id', // 当前表的外键字段
targetKey: 'store_id', // 关联表的主键字段
targetKey: 'store_id', // 关联表业务键(非主键)
as: 'store_stock',
constraints: false,
});
StockWarehouse.hasMany(StockBarcode, {
foreignKey: 'stock_id', // StockBarcodes表中的外键字段

View File

@ -247,222 +247,5 @@ module.exports = app => {
return new Date(this.expiry_date) < new Date();
};
// 静态方法
Storage.findByStockAndBatch = async function(app, stockId, batchNo, inventoryType = 'ZP') {
return await app.model.Storage.findOne({
where: {
stock_id: stockId,
batch_no: batchNo,
inventory_type: inventoryType,
is_enabled: 1,
delete_at: null,
},
include: [
{
model: app.model.LocationSpace,
as: 'space',
attributes: [ 'space_code', 'custom_name' ],
},
{
model: app.model.Store,
as: 'warehouse',
attributes: [ 'store_name' ],
},
],
});
};
Storage.findBySpace = async function(app, spaceId) {
return await app.model.Storage.findAll({
where: {
space_id: spaceId,
is_enabled: 1,
delete_at: null,
},
include: [
{
model: app.model.StockWarehouse,
as: 'stock',
attributes: [ 'product_code', 'product_name' ],
},
],
order: [[ 'inbound_time', 'ASC' ]],
});
};
Storage.findAvailableByWarehouse = async function(app, warehouseId, stockId = null) {
const where = {
warehouse_id: warehouseId,
is_enabled: 1,
delete_at: null,
available_quantity: { [app.Sequelize.Op.gt]: 0 },
};
if (stockId) {
where.stock_id = stockId;
}
return await app.model.Storage.findAll({
where,
include: [
{
model: app.model.LocationSpace,
as: 'space',
attributes: [ 'space_code', 'custom_name' ],
},
{
model: app.model.StockWarehouse,
as: 'stock',
attributes: [ 'product_code', 'product_name' ],
},
],
order: [
[ 'expiry_date', 'ASC' ],
[ 'inbound_time', 'ASC' ],
],
});
};
Storage.findExpiringSoon = async function(app, days = 30) {
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + days);
return await app.model.Storage.findAll({
where: {
expiry_date: {
[app.Sequelize.Op.between]: [ new Date(), expiryDate ],
},
is_enabled: 1,
delete_at: null,
quantity: { [app.Sequelize.Op.gt]: 0 },
},
include: [
{
model: app.model.Store,
as: 'warehouse',
attributes: [ 'store_name' ],
},
{
model: app.model.StockWarehouse,
as: 'stock',
attributes: [ 'product_code', 'product_name' ],
},
],
order: [[ 'expiry_date', 'ASC' ]],
});
};
Storage.updateQuantity = async function(app, id, quantityChange, lockedChange = 0) {
const storage = await app.model.Storage.findByPk(id);
if (!storage) {
throw new Error('库存记录不存在');
}
const newQuantity = storage.quantity + quantityChange;
const newLocked = storage.locked_quantity + lockedChange;
if (newQuantity < 0) {
throw new Error('库存数量不能为负数');
}
if (newLocked < 0 || newLocked > newQuantity) {
throw new Error('锁定数量无效');
}
const updateData = {
quantity: newQuantity,
locked_quantity: newLocked,
available_quantity: newQuantity - newLocked,
updated_at: new Date(),
};
await storage.update(updateData);
return storage;
};
Storage.lockQuantity = async function(app, id, quantity) {
return await Storage.updateQuantity(app, id, 0, quantity);
};
Storage.unlockQuantity = async function(app, id, quantity) {
return await Storage.updateQuantity(app, id, 0, -quantity);
};
Storage.allocateQuantity = async function(app, id, quantity) {
const storage = await app.model.Storage.findByPk(id);
if (!storage) {
throw new Error('库存记录不存在');
}
if (storage.available_quantity < quantity) {
throw new Error('可用数量不足');
}
return await Storage.updateQuantity(app, id, 0, quantity);
};
Storage.getStockSummary = async function(app, warehouseId) {
return await app.model.Storage.findAll({
attributes: [
'stock_id',
'inventory_type',
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ],
],
where: {
warehouse_id: warehouseId,
is_enabled: 1,
delete_at: null,
},
group: [ 'stock_id', 'inventory_type' ],
raw: true,
});
};
Storage.getSpaceUsage = async function(app, spaceId) {
const result = await app.model.Storage.findAll({
attributes: [
'inventory_type',
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'record_count' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
],
where: {
space_id: spaceId,
is_enabled: 1,
delete_at: null,
},
group: [ 'inventory_type' ],
raw: true,
});
const usage = {
normal: 0,
defective: 0,
damaged: 0,
frozen: 0,
total: 0,
};
result.forEach(item => {
let type;
switch (item.inventory_type) {
case 'ZP': type = 'normal'; break;
case 'CC': type = 'defective'; break;
case 'JS':
case 'XS': type = 'damaged'; break;
case 'DJ': type = 'frozen'; break;
default: return;
}
usage[type] = parseInt(item.total_quantity) || 0;
usage.total += usage[type];
});
return usage;
};
return Storage;
};

View File

@ -199,10 +199,10 @@ module.exports = app => {
as: 'roles',
});
// 关联商家拥有的账号角色关联
// 关联商家拥有的账号员工关联
Store.hasMany(AccountStoreEmployee, {
foreignKey: 'store_id',
as: 'accountStoreEmployee',
as: 'accountStoreEmployees',
});
Store.hasMany(ProhibitedType, {

View File

@ -209,10 +209,12 @@ module.exports = app => {
as: 'reviewer',
});
// store_id 在业务上需要与 warehouse_id 联合约束,模型层不声明单列外键约束。
StoreWarehouse.hasMany(StockWarehouse, {
foreignKey: 'store_id',
targetKey: 'store_id',
as: 'store_stock',
constraints: false,
});
// 解除人
@ -221,12 +223,60 @@ module.exports = app => {
targetKey: 'id',
as: 'end_user',
});
// receiving 同样依赖 store_id + warehouse_id 的复合语义。
StoreWarehouse.hasMany(Receiving, {
foreignKey: 'store_id',
as: 'receiving',
constraints: false,
});
};
// 统一构造复合键语义的 where 条件,避免 service 侧重复散落。
StoreWarehouse.buildScopedWhere = function(options = {}) {
const {
warehouseId,
storeId,
useStatus = 1,
} = options;
const where = {
use_status: useStatus,
};
if (warehouseId !== undefined && warehouseId !== null) {
where.warehouse_id = warehouseId;
}
if (storeId !== undefined && storeId !== null) {
where.store_id = storeId;
}
return where;
};
// 统一构造 StockWarehouse -> StoreWarehouse(include as=store_stock) 的 include。
StoreWarehouse.buildStoreStockInclude = function(options = {}) {
const {
warehouseId,
storeId,
required = false,
useStatus = 1,
attributes = [ 'store_id', 'store_remask' ],
} = options;
return {
model: this,
as: 'store_stock',
attributes,
where: this.buildScopedWhere({
warehouseId,
storeId,
useStatus,
}),
required,
};
};
// 实例方法 - 检查授权是否有效
StoreWarehouse.prototype.isAuthValid = function() {
if (this.auth_status !== 2) return false; // 只有已通过状态才有效

View File

@ -4,17 +4,29 @@
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
// 奇门接口
router.post('/qimen', controller.home.qimen);
//预留第三方系统接口
router.post('/api/warehouse', controller.home.warehouse);
router.post('/api/store', controller.home.store);
router.post('/api/v1', controller.home.v1);
// 系统接口 PDA/WEB 统一入口
router.post('/system', controller.home.system);
router.post('/api/v2', controller.apiV2.index);
//api文档相关
router.get('/api/docs', controller.docs.list);
router.get('/api/docs/:docName', controller.docs.detail);
router.get('/api/docs/:docName/raw', controller.docs.raw);
//打印模板
router.get('/template/xml/:id', controller.template.xml);
//打印台设置
router.get('/auth/printSetting/:code', controller.auth.printerSetting);
router.get('/testSendData', controller.home.testSendData);
router.post('/auth/printSetting/', controller.auth.printerSetting);
//测试接口
router.get('/testSendData', controller.home.testSendData);
};

View File

@ -3,6 +3,9 @@
const Service = require('egg').Service;
const { XMLParser } = require('fast-xml-parser');
const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other' ]);
const ALLOWED_PROJECTS = new Set([ 'all', 'wms', 'tms', 'scm', 'other' ]);
class systemService extends Service {
async callMethod(className, actionName, requestData, authHeader) {
try {
@ -22,7 +25,11 @@ class systemService extends Service {
}else{
console.log(`调用服务: ${servicePath}, 方法: ${actionName}`);
}
const serviceInstance = systemMethods;
let serviceInstance = systemMethods;
if (typeof serviceInstance[actionName] !== 'function' && serviceInstance?.index) {
serviceInstance = serviceInstance.index;
}
// 检查方法是否存在
if (typeof serviceInstance[actionName] !== 'function') {
@ -66,6 +73,94 @@ class systemService extends Service {
return true;
}
validateRequestContext(params = {}, headers = {}) {
if (!this.validateParams(params)) {
return {
ok: false,
status: 400,
code: 400,
message: '参数缺失或错误: method/v/timestamp',
};
}
const rawTimestamp = String(params.timestamp || '').trim();
if (!/^\d+$/.test(rawTimestamp)) {
return {
ok: false,
status: 400,
code: 400,
message: 'timestamp 必须为数字时间戳',
};
}
const timestampNum = Number(rawTimestamp);
if (!Number.isFinite(timestampNum) || timestampNum <= 0) {
return {
ok: false,
status: 400,
code: 400,
message: 'timestamp 非法',
};
}
const platform = String(headers.platform || '').trim();
const project = String(headers.project || '').trim();
const authorization = String(headers.authorization || '').trim();
if (!platform) {
return {
ok: false,
status: 400,
code: 400,
message: '缺少请求头 platform',
};
}
if (!project) {
return {
ok: false,
status: 400,
code: 400,
message: '缺少请求头 project',
};
}
if (!ALLOWED_PLATFORMS.has(platform.toLowerCase())) {
return {
ok: false,
status: 400,
code: 400,
message: `platform 不支持: ${platform}`,
};
}
if (!ALLOWED_PROJECTS.has(project.toLowerCase())) {
return {
ok: false,
status: 400,
code: 400,
message: `project 不支持: ${project}`,
};
}
if (authorization && !authorization.startsWith('Bearer ')) {
return {
ok: false,
status: 401,
code: 401,
message: 'Authorization 格式错误,应为 Bearer <token>',
};
}
return {
ok: true,
status: 200,
code: 0,
message: 'ok',
};
}
async saveLog(logData, startTime) {
const {
ctx,

View File

@ -1,351 +0,0 @@
'use strict';
const MainService = require('../main');
class orderService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,detail,listItems,stats,updateStatus,updateDeliveryTime';
const _noNeedLog = 'list,detail,listItems,stats';
const _noNeedAuth = 'list,detail,listItems,stats,updateStatus,updateDeliveryTime';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
getWarehouseId(data = {}) {
const fromParam = Number(data.warehouse_id || data.warehouseId || 0);
const fromUser = Number(this.ctx.user?.store_id || 0);
return fromParam || fromUser;
}
async getOrderModels(warehouseId) {
const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const OrderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
return { DeliveryModel, OrderItemsModel };
}
applyDateRange(where, field, start, end) {
const { Op } = this.app.Sequelize;
const range = {};
if (start) {
range[Op.gte] = this.normalizeDate(start, false);
}
if (end) {
range[Op.lte] = this.normalizeDate(end, true);
}
if (Object.keys(range).length > 0) {
where[field] = range;
}
}
buildWhere(whereData = {}, warehouseId) {
const { Op } = this.app.Sequelize;
const where = { warehouse_id: warehouseId };
const eqFields = [
'id',
'store_id',
'status',
'post_status',
'storage_status',
'pick_status',
'pack_status',
'inspection_status',
'print_status',
'claim_status',
'outbound_status',
'lock_status',
'intercept_status',
'source_platform_code',
'logistics_code',
'warehouse_code',
'order_type',
];
for (const key of eqFields) {
if (whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '') {
where[key] = whereData[key];
}
}
if (whereData.delivery_order_code) {
where.delivery_order_code = { [Op.like]: `%${whereData.delivery_order_code}%` };
}
if (Array.isArray(whereData.delivery_order_codes) && whereData.delivery_order_codes.length > 0) {
where.delivery_order_code = { [Op.in]: whereData.delivery_order_codes };
}
if (whereData.logistics_name) {
where.logistics_name = { [Op.like]: `%${whereData.logistics_name}%` };
}
if (whereData.buyer_nick) {
where.buyer_nick = { [Op.like]: `%${whereData.buyer_nick}%` };
}
if (whereData.mobile) {
where.mobile = { [Op.like]: `%${whereData.mobile}%` };
}
this.applyDateRange(where, 'create_at', whereData.create_at_start, whereData.create_at_end);
this.applyDateRange(where, 'place_order_time', whereData.place_order_time_start, whereData.place_order_time_end);
this.applyDateRange(where, 'pay_time', whereData.pay_time_start, whereData.pay_time_end);
this.applyDateRange(where, 'delivery_time', whereData.delivery_time_start, whereData.delivery_time_end);
return where;
}
parseDateTime(value, fieldName) {
if (!value) return null;
const d = value instanceof Date ? value : new Date(value);
if (Number.isNaN(d.getTime())) {
throw new Error(`${fieldName} 格式错误`);
}
return d;
}
async list(data = {}) {
try {
const warehouseId = this.getWarehouseId(data);
if (!warehouseId) {
return this.fail('warehouse_id 不能为空', { code: 400 });
}
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.buildWhere(data.where || {}, warehouseId);
const page = Math.max(Number(data.pagination?.page || 1), 1);
const pageSize = Math.min(Math.max(Number(data.pagination?.pageSize || 20), 1), 200);
const offset = (page - 1) * pageSize;
const result = await DeliveryModel.findAndCountAll({
where,
offset,
limit: pageSize,
order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ],
raw: true,
});
return this.success('ok', {
data: {
list: result.rows,
pagination: {
page,
pageSize,
total: result.count,
totalPages: Math.ceil(result.count / pageSize),
hasNext: page * pageSize < result.count,
hasPrevious: page > 1,
},
},
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async detail(data = {}) {
try {
const warehouseId = this.getWarehouseId(data);
if (!warehouseId) {
return this.fail('warehouse_id 不能为空', { code: 400 });
}
const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId);
const where = { warehouse_id: warehouseId };
if (data.id) {
where.id = data.id;
} else if (data.delivery_order_code) {
where.delivery_order_code = data.delivery_order_code;
} else {
return this.fail('id 或 delivery_order_code 必填', { code: 400 });
}
const order = await DeliveryModel.findOne({ where, raw: true });
if (!order) {
return this.fail('订单不存在', { code: 404 });
}
const items = await OrderItemsModel.findAll({
where: { order_id: order.id },
order: [ [ 'id', 'ASC' ] ],
raw: true,
});
return this.success('ok', {
data: {
order,
items,
},
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async listItems(data = {}) {
try {
const warehouseId = this.getWarehouseId(data);
if (!warehouseId) {
return this.fail('warehouse_id 不能为空', { code: 400 });
}
const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId);
const where = { warehouse_id: warehouseId };
if (data.order_id) {
where.id = data.order_id;
} else if (data.delivery_order_code) {
where.delivery_order_code = data.delivery_order_code;
} else {
return this.fail('order_id 或 delivery_order_code 必填', { code: 400 });
}
const order = await DeliveryModel.findOne({ where, attributes: [ 'id', 'delivery_order_code' ], raw: true });
if (!order) {
return this.fail('订单不存在', { code: 404 });
}
const items = await OrderItemsModel.findAll({
where: { order_id: order.id },
order: [ [ 'id', 'ASC' ] ],
raw: true,
});
return this.success('ok', {
data: {
order,
items,
},
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async stats(data = {}) {
try {
const warehouseId = this.getWarehouseId(data);
if (!warehouseId) {
return this.fail('warehouse_id 不能为空', { code: 400 });
}
const { Sequelize } = this.app;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.buildWhere(data.where || {}, warehouseId);
const total = await DeliveryModel.count({ where });
const byStatusRows = await DeliveryModel.findAll({
where,
attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ],
group: [ 'status' ],
raw: true,
});
const byOutboundRows = await DeliveryModel.findAll({
where,
attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ],
group: [ 'outbound_status' ],
raw: true,
});
return this.success('ok', {
data: {
total,
byStatus: byStatusRows,
byOutboundStatus: byOutboundRows,
},
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async updateStatus(data = {}) {
try {
const warehouseId = this.getWarehouseId(data);
if (!warehouseId) {
return this.fail('warehouse_id 不能为空', { code: 400 });
}
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = { warehouse_id: warehouseId };
if (data.id) {
where.id = data.id;
} else if (data.delivery_order_code) {
where.delivery_order_code = data.delivery_order_code;
} else {
return this.fail('id 或 delivery_order_code 必填', { code: 400 });
}
const allowedFields = [
'status',
'post_status',
'storage_status',
'pick_status',
'pack_status',
'inspection_status',
'print_status',
'claim_status',
'outbound_status',
'lock_status',
'intercept_status',
];
const updateData = {};
for (const key of allowedFields) {
if (data[key] !== undefined && data[key] !== null && data[key] !== '') {
updateData[key] = data[key];
}
}
if (data.delivery_time) {
updateData.delivery_time = this.parseDateTime(data.delivery_time, 'delivery_time');
}
if (!updateData.delivery_time && updateData.outbound_status === 'fin') {
updateData.delivery_time = new Date();
}
if (Object.keys(updateData).length === 0) {
return this.fail('没有可更新字段', { code: 400 });
}
updateData.updated_at = new Date();
const [ affected ] = await DeliveryModel.update(updateData, { where });
if (!affected) {
return this.fail('订单不存在或未更新', { code: 404 });
}
const order = await DeliveryModel.findOne({ where, raw: true });
return this.success('更新成功', { data: order, code: 200 });
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async updateDeliveryTime(data = {}) {
if (!data.delivery_time) {
return this.fail('delivery_time 必填', { code: 400 });
}
const nextData = { ...data };
if (nextData.syncOutboundStatus === true || nextData.syncOutboundStatus === 1 || nextData.syncOutboundStatus === '1') {
nextData.outbound_status = 'fin';
}
return await this.updateStatus(nextData);
}
}
module.exports = orderService;

View File

@ -0,0 +1,62 @@
'use strict';
const OrderBaseService = require('./base');
class ArchiveOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getarchiveOrderlist';
const _noNeedLog = 'getarchiveOrderlist';
const _noNeedAuth = 'getarchiveOrderlist';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async getarchiveOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== '';
if (!hasOutboundFilter) {
where.outbound_status = 'fin';
}
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'outbound_status',
'delivery_time',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [ [ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultArchiveFilter: !hasOutboundFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
}
module.exports = ArchiveOrderService;

View File

@ -0,0 +1,157 @@
'use strict';
const MainService = require('../../main');
class OrderBaseService extends MainService {
ensureWarehouseId(data = {}) {
const warehouseId = this.getWarehouseId(data);
if (!warehouseId) {
throw new Error('warehouse_id 不能为空');
}
return warehouseId;
}
getWarehouseId(data = {}) {
const fromParam = Number(data.warehouse_id || data.warehouseId || 0);
const fromUser = Number(this.ctx.user?.store_id || 0);
return fromParam || fromUser;
}
async getOrderModels(warehouseId) {
const DeliveryModel = await this.ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const OrderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
return { DeliveryModel, OrderItemsModel };
}
applyDateRange(where, field, start, end) {
const { Op } = this.app.Sequelize;
const range = {};
if (start) {
range[Op.gte] = this.normalizeDate(start, false);
}
if (end) {
range[Op.lte] = this.normalizeDate(end, true);
}
if (Object.keys(range).length > 0) {
where[field] = range;
}
}
buildWhere(whereData = {}, warehouseId) {
const { Op } = this.app.Sequelize;
const where = { warehouse_id: warehouseId };
const eqFields = [
'id',
'store_id',
'status',
'post_status',
'storage_status',
'pick_status',
'pack_status',
'inspection_status',
'print_status',
'claim_status',
'outbound_status',
'lock_status',
'intercept_status',
'source_platform_code',
'logistics_code',
'warehouse_code',
'order_type',
];
for (const key of eqFields) {
if (whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '') {
where[key] = whereData[key];
}
}
if (whereData.delivery_order_code) {
where.delivery_order_code = { [Op.like]: `%${whereData.delivery_order_code}%` };
}
if (Array.isArray(whereData.delivery_order_codes) && whereData.delivery_order_codes.length > 0) {
where.delivery_order_code = { [Op.in]: whereData.delivery_order_codes };
}
if (whereData.logistics_name) {
where.logistics_name = { [Op.like]: `%${whereData.logistics_name}%` };
}
if (whereData.buyer_nick) {
where.buyer_nick = { [Op.like]: `%${whereData.buyer_nick}%` };
}
if (whereData.mobile) {
where.mobile = { [Op.like]: `%${whereData.mobile}%` };
}
this.applyDateRange(where, 'create_at', whereData.create_at_start, whereData.create_at_end);
this.applyDateRange(where, 'place_order_time', whereData.place_order_time_start, whereData.place_order_time_end);
this.applyDateRange(where, 'pay_time', whereData.pay_time_start, whereData.pay_time_end);
this.applyDateRange(where, 'delivery_time', whereData.delivery_time_start, whereData.delivery_time_end);
return where;
}
parseDateTime(value, fieldName) {
if (!value) return null;
const d = value instanceof Date ? value : new Date(value);
if (Number.isNaN(d.getTime())) {
throw new Error(`${fieldName} 格式错误`);
}
return d;
}
getPagination(pagination = {}) {
const page = Math.max(Number(pagination.page || 1), 1);
const pageSize = Math.min(Math.max(Number(pagination.pageSize || 20), 1), 200);
const offset = (page - 1) * pageSize;
return { page, pageSize, offset };
}
buildPagination(page, pageSize, total) {
return {
page,
pageSize,
total,
totalPages: Math.ceil(total / pageSize),
hasNext: page * pageSize < total,
hasPrevious: page > 1,
};
}
getOrderLocatorWhere(data = {}, warehouseId) {
const where = { warehouse_id: warehouseId };
if (data.id) {
where.id = data.id;
return where;
}
if (data.order_id) {
where.id = data.order_id;
return where;
}
if (data.delivery_order_code) {
where.delivery_order_code = data.delivery_order_code;
return where;
}
throw new Error('id 或 delivery_order_code 必填');
}
buildListData(rows, total, page, pageSize, extra = {}) {
return {
list: rows,
pagination: this.buildPagination(page, pageSize, total),
...extra,
};
}
}
module.exports = OrderBaseService;

View File

@ -0,0 +1,63 @@
'use strict';
const OrderBaseService = require('./base');
class DeliveryOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getdeliveryOrderlist';
const _noNeedLog = 'getdeliveryOrderlist';
const _noNeedAuth = 'getdeliveryOrderlist';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async getdeliveryOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== '';
if (!hasOutboundFilter) {
where.outbound_status = { [Op.ne]: 'none' };
}
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'outbound_status',
'delivery_time',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [ [ 'delivery_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultOutboundFilter: !hasOutboundFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
}
module.exports = DeliveryOrderService;

View File

@ -0,0 +1,90 @@
'use strict';
const OrderBaseService = require('./base');
class ExpectionOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getexpectionOrderlist';
const _noNeedLog = 'getexpectionOrderlist';
const _noNeedAuth = 'getexpectionOrderlist';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async getexpectionOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasExceptionFilter = [
'status',
'post_status',
'storage_status',
'pick_status',
'pack_status',
'inspection_status',
'print_status',
'claim_status',
'outbound_status',
'intercept_status',
].some(key => whereData[key] !== undefined && whereData[key] !== null && whereData[key] !== '');
if (!hasExceptionFilter) {
where[Op.or] = [
{ status: 'error' },
{ post_status: 'error' },
{ storage_status: 'error' },
{ pick_status: 'error' },
{ pack_status: 'error' },
{ inspection_status: 'error' },
{ print_status: 'error' },
{ claim_status: 'error' },
{ outbound_status: 'error' },
{ intercept_status: 'exception' },
];
}
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'post_status',
'pick_status',
'pack_status',
'inspection_status',
'outbound_status',
'intercept_status',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultExceptionFilter: !hasExceptionFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
}
module.exports = ExpectionOrderService;

View File

@ -0,0 +1,204 @@
'use strict';
const OrderBaseService = require('./base');
class OrderIndexService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder';
const _noNeedLog = 'list,detail,listItems,stats,getreviewOrderlist';
const _noNeedAuth = 'list,detail,listItems,stats,getreviewOrderlist,updateStatus,updateDeliveryTime,reviewOrder';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async list(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.buildWhere(data.where || {}, warehouseId);
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
offset,
limit: pageSize,
order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async detail(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId);
const where = this.getOrderLocatorWhere(data, warehouseId);
const order = await DeliveryModel.findOne({ where, raw: true });
if (!order) {
return this.fail('订单不存在', { code: 404 });
}
const items = await OrderItemsModel.findAll({
where: { order_id: order.id },
order: [ [ 'id', 'ASC' ] ],
raw: true,
});
return this.success('ok', {
data: { order, items },
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async listItems(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel, OrderItemsModel } = await this.getOrderModels(warehouseId);
const where = this.getOrderLocatorWhere(data, warehouseId);
const order = await DeliveryModel.findOne({
where,
attributes: [ 'id', 'delivery_order_code' ],
raw: true,
});
if (!order) {
return this.fail('订单不存在', { code: 404 });
}
const items = await OrderItemsModel.findAll({
where: { order_id: order.id },
order: [ [ 'id', 'ASC' ] ],
raw: true,
});
return this.success('ok', {
data: { order, items },
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async stats(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Sequelize } = this.app;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.buildWhere(data.where || {}, warehouseId);
const total = await DeliveryModel.count({ where });
const byStatusRows = await DeliveryModel.findAll({
where,
attributes: [ 'status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ],
group: [ 'status' ],
raw: true,
});
const byOutboundRows = await DeliveryModel.findAll({
where,
attributes: [ 'outbound_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'count' ] ],
group: [ 'outbound_status' ],
raw: true,
});
return this.success('ok', {
data: {
total,
byStatus: byStatusRows,
byOutboundStatus: byOutboundRows,
},
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async getreviewOrderlist(data = {}) {
return await this.ctx.service.systemMethods.order.reviewOrder.getreviewOrderlist(data);
}
async updateStatus(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.getOrderLocatorWhere(data, warehouseId);
const allowedFields = [
'status',
'post_status',
'storage_status',
'pick_status',
'pack_status',
'inspection_status',
'print_status',
'claim_status',
'outbound_status',
'lock_status',
'intercept_status',
];
const updateData = {};
for (const key of allowedFields) {
if (data[key] !== undefined && data[key] !== null && data[key] !== '') {
updateData[key] = data[key];
}
}
if (data.delivery_time) {
updateData.delivery_time = this.parseDateTime(data.delivery_time, 'delivery_time');
}
if (!updateData.delivery_time && updateData.outbound_status === 'fin') {
updateData.delivery_time = new Date();
}
if (Object.keys(updateData).length === 0) {
return this.fail('没有可更新字段', { code: 400 });
}
updateData.updated_at = new Date();
const [ affected ] = await DeliveryModel.update(updateData, { where });
if (!affected) {
return this.fail('订单不存在或未更新', { code: 404 });
}
const order = await DeliveryModel.findOne({ where, raw: true });
return this.success('更新成功', { data: order, code: 200 });
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async updateDeliveryTime(data = {}) {
if (!data.delivery_time) {
return this.fail('delivery_time 必填', { code: 400 });
}
const nextData = { ...data };
if (nextData.syncOutboundStatus === true || nextData.syncOutboundStatus === 1 || nextData.syncOutboundStatus === '1') {
nextData.outbound_status = 'fin';
}
return await this.updateStatus(nextData);
}
async reviewOrder(data = {}) {
return await this.ctx.service.systemMethods.order.reviewOrder.reviewOrder(data);
}
}
module.exports = OrderIndexService;

View File

@ -0,0 +1,69 @@
'use strict';
const OrderBaseService = require('./base');
class PendingOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getpendingOrderlist';
const _noNeedLog = 'getpendingOrderlist';
const _noNeedAuth = 'getpendingOrderlist';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async getpendingOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasStatusFilter = whereData.status !== undefined && whereData.status !== null && whereData.status !== '';
const hasOutboundFilter = whereData.outbound_status !== undefined && whereData.outbound_status !== null && whereData.outbound_status !== '';
if (!hasStatusFilter) {
where.status = { [Op.in]: [ 'pedding', 'created' ] };
}
if (!hasOutboundFilter) {
where.outbound_status = 'none';
}
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'outbound_status',
'inspection_status',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [ [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultPendingStatusFilter: !hasStatusFilter,
defaultPendingOutboundFilter: !hasOutboundFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
}
module.exports = PendingOrderService;

View File

@ -0,0 +1,103 @@
'use strict';
const OrderBaseService = require('./base');
class ReviewOrderService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getreviewOrderlist,reviewOrder';
const _noNeedLog = 'getreviewOrderlist';
const _noNeedAuth = 'getreviewOrderlist,reviewOrder';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
async getreviewOrderlist(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { Op } = this.app.Sequelize;
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const whereData = data.where || {};
const where = this.buildWhere(whereData, warehouseId);
const hasInspectionFilter = whereData.inspection_status !== undefined && whereData.inspection_status !== null && whereData.inspection_status !== '';
if (!hasInspectionFilter) {
where.inspection_status = { [Op.ne]: 'none' };
}
if (whereData.operator_name) {
where.operator_name = { [Op.like]: `%${whereData.operator_name}%` };
}
this.applyDateRange(where, 'operate_time', whereData.operate_time_start, whereData.operate_time_end);
const { page, pageSize, offset } = this.getPagination(data.pagination);
const result = await DeliveryModel.findAndCountAll({
where,
attributes: [
'id',
'delivery_order_code',
'status',
'inspection_status',
'operator_name',
'operate_time',
'updated_at',
'store_id',
'warehouse_id',
'buyer_nick',
'logistics_name',
],
offset,
limit: pageSize,
order: [ [ 'operate_time', 'DESC' ], [ 'updated_at', 'DESC' ], [ 'id', 'DESC' ] ],
raw: true,
});
return this.success('ok', {
data: this.buildListData(result.rows, result.count, page, pageSize, {
queryInfo: {
defaultInspectionFilter: !hasInspectionFilter,
},
}),
code: 200,
});
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
async reviewOrder(data = {}) {
try {
const warehouseId = this.ensureWarehouseId(data);
const { DeliveryModel } = await this.getOrderModels(warehouseId);
const where = this.getOrderLocatorWhere(data, warehouseId);
const reviewStatus = String(
data.review_status ?? data.reviewStatus ?? data.inspection_status ?? 'fin'
).trim();
const allowedReviewStatus = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]);
if (!allowedReviewStatus.has(reviewStatus)) {
return this.fail('review_status 参数不合法', { code: 400 });
}
const updateData = {
inspection_status: reviewStatus,
operator_name: data.operator_name || this.ctx.user?.real_name || this.ctx.user?.username || null,
operate_time: data.operate_time ? this.parseDateTime(data.operate_time, 'operate_time') : new Date(),
updated_at: new Date(),
};
const [ affected ] = await DeliveryModel.update(updateData, { where });
if (!affected) {
return this.fail('订单不存在或未更新', { code: 404 });
}
const order = await DeliveryModel.findOne({ where, raw: true });
return this.success('审核成功', { data: order, code: 200 });
} catch (error) {
return this.fail(error.message, { code: 500 });
}
}
}
module.exports = ReviewOrderService;

View File

@ -5,7 +5,7 @@ const MainService = require('../main');
class userService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'login,register';
const _noNeedLogin = 'login,loginByCode,register';
const _noNeedRight = '*';
const _noNeedLog = 'info';
const _noNeedAuth = '*';
@ -22,6 +22,45 @@ class userService extends MainService {
return this.fail('登录失败:' + result.message, result);
}
async loginByCode(data) {
const { service } = this;
const code = typeof data?.code === 'string' ? data.code.trim() : '';
if (!code) {
return this.fail('登录失败:缺少登录码 code', {
success: false,
data: null,
code: 0,
message: '缺少登录码 code',
});
}
//code先进行base64解码,看是否为json以及json是否有uuid字段,如果有则继续执行否则返回报错
let decoded;
try {
const buffer = Buffer.from(code, 'base64');
const decodedStr = buffer.toString('utf-8');
decoded = JSON.parse(decodedStr);
} catch (err) {
return this.fail('登录失败:无效的登录码格式', {
success: false,
data: null,
code: 0,
message: '无效的登录码格式',
});
}
if (!decoded || typeof decoded !== 'object' || !decoded.uuid) {
return this.fail('登录失败:登录码缺少必要的uuid字段', {
success: false,
data: null,
code: 0,
message: '登录码缺少必要的uuid字段',
});
}
const result = await service.systems.auth.user.loginByCode(code);
if (result.code) {
return this.success('登录成功', result);
}
return this.fail('登录失败:' + result.message, result);
}
async logout() {
return this.success('登出成功');
}

View File

@ -3,22 +3,85 @@
const Service = require('egg').Service;
class AccountPlatformService extends Service {
getActiveInclude(ctx) {
return [
{
model: ctx.model.AccountStoreEmployee,
as: 'accountStoreEmployee',
where: { status: 1 },
required: true,
include: [
{
model: ctx.model.EmployeeRole,
as: 'employeeRoles',
required: false,
attributes: [ 'id', 'employee_id', 'role_id' ],
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [ 'id', 'name', 'code', 'permissions', 'description' ],
},
],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'name', 'code' ],
},
],
},
];
}
getPrimaryRoleBinding(accountStoreEmployee) {
const bindings = Array.isArray(accountStoreEmployee?.employeeRoles)
? accountStoreEmployee.employeeRoles
: [];
return bindings.length > 0 ? bindings[0] : null;
}
formatActiveContext(platformActive) {
if (!platformActive || !platformActive.accountStoreEmployee) {
return null;
}
const employee = platformActive.accountStoreEmployee;
const roleBinding = this.getPrimaryRoleBinding(employee);
const role = roleBinding?.role || null;
const store = employee.store || null;
return {
account_id: platformActive.account_id,
platform_code: platformActive.platform_code,
role_id: roleBinding ? roleBinding.role_id : null,
role_name: role ? role.name : '',
role_code: role ? role.code : '',
role_permissions: role ? role.permissions : [],
store_id: employee.store_id,
store_name: store ? store.name : '',
store_code: store ? store.code : '',
created_at: platformActive.created_at,
updated_at: platformActive.updated_at,
};
}
/**
* 切换平台激活角色
* @param {number} accountId - 账号ID
* @param {number} accountStoreRoleId - 账号仓库角色关联ID
* @param {number} accountStoreRoleId - 账号仓库员工关联ID(保持历史参数名兼容)
* @param {string} platformCode - 平台编码
* @return {Promise<Object>}
*/
async switchActiveRole(accountId, accountStoreRoleId, platformCode) {
const { ctx, app } = this;
const { ctx } = this;
// 使用事务确保数据一致性
const transaction = await ctx.model.transaction();
try {
// 1. 验证角色关联的有效性
const accountStoreRole = await ctx.model.AccountStoreRole.findOne({
// 1. 验证员工关联的有效性
const accountStoreEmployee = await ctx.model.AccountStoreEmployee.findOne({
where: {
id: accountStoreRoleId,
account_id: accountId,
@ -27,18 +90,33 @@ class AccountPlatformService extends Service {
transaction,
});
if (!accountStoreRole) {
if (!accountStoreEmployee) {
throw new Error('角色关联不存在或已失效');
}
const existingActive = await ctx.model.AccountPlatformActive.findOne({
where: {
account_id: accountId,
platform_code: platformCode,
},
transaction,
});
// 2. 使用 upsert 切换激活角色
const [ platformActive, created ] = await ctx.model.AccountPlatformActive.upsert({
await ctx.model.AccountPlatformActive.upsert({
account_id: accountId,
account_store_role_id: accountStoreRoleId,
employee_id: accountStoreRoleId,
platform_code: platformCode,
}, {
transaction,
returning: true,
});
const platformActive = await ctx.model.AccountPlatformActive.findOne({
where: {
account_id: accountId,
platform_code: platformCode,
},
transaction,
});
await transaction.commit();
@ -48,7 +126,7 @@ class AccountPlatformService extends Service {
return {
success: true,
created,
created: !existingActive,
data: platformActive,
};
} catch (error) {
@ -56,7 +134,7 @@ class AccountPlatformService extends Service {
// 处理唯一约束冲突
if (error.name === 'SequelizeUniqueConstraintError') {
// 如果是 account_store_role_id 和 platform_code 冲突,说明同一个平台不能关联到不同的账号
// 如果是 employee_id 和 platform_code 冲突,说明同一个平台不能关联到不同账号
if (error.errors && error.errors.some(e => e.path === 'uk_account_store_role_platform')) {
throw new Error('该角色已被其他账号在同一平台激活');
}
@ -97,26 +175,7 @@ class AccountPlatformService extends Service {
account_id: accountId,
platform_code: platformCode,
},
include: [
{
model: ctx.model.AccountStoreRole,
as: 'accountStoreRole',
where: { status: 1 },
required: true,
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [ 'id', 'name', 'code', 'permissions' ],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'name', 'code' ],
},
],
},
],
include: this.getActiveInclude(ctx),
});
if (!platformActive) {
@ -124,19 +183,7 @@ class AccountPlatformService extends Service {
}
// 整理返回数据
const result = {
account_id: accountId,
platform_code: platformCode,
role_id: platformActive.accountStoreRole.role_id,
role_name: platformActive.accountStoreRole.role.name,
role_code: platformActive.accountStoreRole.role.code,
role_permissions: platformActive.accountStoreRole.role.permissions,
store_id: platformActive.accountStoreRole.store_id,
store_name: platformActive.accountStoreRole.store.name,
store_code: platformActive.accountStoreRole.store.code,
created_at: platformActive.created_at,
updated_at: platformActive.updated_at,
};
const result = this.formatActiveContext(platformActive);
// 缓存结果
if (useCache) {
@ -164,40 +211,22 @@ class AccountPlatformService extends Service {
account_id: accountId,
platform_code: platformCodes,
},
include: [
{
model: ctx.model.AccountStoreRole,
as: 'accountStoreRole',
where: { status: 1 },
required: true,
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [ 'id', 'name', 'code' ],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'name', 'code' ],
},
],
},
],
include: this.getActiveInclude(ctx),
});
// 转换为平台编码为key的对象
const result = {};
platformActives.forEach(active => {
const context = this.formatActiveContext(active);
result[active.platform_code] = {
role_id: active.accountStoreRole.role_id,
role_name: active.accountStoreRole.role.name,
role_code: active.accountStoreRole.role.code,
store_id: active.accountStoreRole.store_id,
store_name: active.accountStoreRole.store.name,
store_code: active.accountStoreRole.store.code,
created_at: active.created_at,
updated_at: active.updated_at,
role_id: context ? context.role_id : null,
role_name: context ? context.role_name : '',
role_code: context ? context.role_code : '',
store_id: context ? context.store_id : null,
store_name: context ? context.store_name : '',
store_code: context ? context.store_code : '',
created_at: context ? context.created_at : active.created_at,
updated_at: context ? context.updated_at : active.updated_at,
};
});
@ -221,40 +250,24 @@ class AccountPlatformService extends Service {
const platformActives = await ctx.model.AccountPlatformActive.findAll({
where: { account_id: accountId },
include: [
{
model: ctx.model.AccountStoreRole,
as: 'accountStoreRole',
where: { status: 1 },
required: true,
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [ 'id', 'name', 'code' ],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'name', 'code' ],
},
],
},
],
include: this.getActiveInclude(ctx),
order: [[ 'platform_code', 'ASC' ]],
});
return platformActives.map(active => ({
platform_code: active.platform_code,
role_id: active.accountStoreRole.role_id,
role_name: active.accountStoreRole.role.name,
role_code: active.accountStoreRole.role.code,
store_id: active.accountStoreRole.store_id,
store_name: active.accountStoreRole.store.name,
store_code: active.accountStoreRole.store.code,
created_at: active.created_at,
updated_at: active.updated_at,
}));
return platformActives.map(active => {
const context = this.formatActiveContext(active);
return {
platform_code: active.platform_code,
role_id: context ? context.role_id : null,
role_name: context ? context.role_name : '',
role_code: context ? context.role_code : '',
store_id: context ? context.store_id : null,
store_name: context ? context.store_name : '',
store_code: context ? context.store_code : '',
created_at: active.created_at,
updated_at: active.updated_at,
};
});
}
/**
@ -318,13 +331,21 @@ class AccountPlatformService extends Service {
where.store_id = storeId;
}
const accountStoreRoles = await ctx.model.AccountStoreRole.findAll({
const accountStoreEmployees = await ctx.model.AccountStoreEmployee.findAll({
where,
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [ 'id', 'name', 'code', 'description' ],
model: ctx.model.EmployeeRole,
as: 'employeeRoles',
required: false,
attributes: [ 'id', 'employee_id', 'role_id' ],
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [ 'id', 'name', 'code', 'description' ],
},
],
},
{
model: ctx.model.Store,
@ -334,23 +355,35 @@ class AccountPlatformService extends Service {
],
order: [
[ 'store_id', 'ASC' ],
[ 'role_id', 'ASC' ],
[ 'id', 'ASC' ],
],
});
return accountStoreRoles.map(item => ({
id: item.id,
account_id: item.account_id,
store_id: item.store_id,
store_name: item.store.name,
store_code: item.store.code,
role_id: item.role_id,
role_name: item.role.name,
role_code: item.role.code,
role_description: item.role.description,
real_name: item.real_name,
created_at: item.created_at,
}));
const rows = [];
for (const employee of accountStoreEmployees) {
const roleBindings = Array.isArray(employee.employeeRoles)
? employee.employeeRoles
: [];
for (const binding of roleBindings) {
const role = binding.role;
if (!role) continue;
rows.push({
id: employee.id,
account_id: employee.account_id,
store_id: employee.store_id,
store_name: employee.store ? employee.store.name : '',
store_code: employee.store ? employee.store.code : '',
role_id: binding.role_id,
role_name: role.name,
role_code: role.code,
role_description: role.description,
real_name: employee.real_name,
created_at: employee.created_at,
});
}
}
return rows;
}
/**

View File

@ -48,53 +48,7 @@ class UserService extends Service {
// 4. 更新最后登录时间
await this.updateLastLoginTime(user.id);
// 5. 设置设备类型(用于菜单查询)
const platformCode = ctx.header.platform || 'web';
// 6. 获取用户完整信息
const userInfo = await this.findById(user.id);
console.log('用户信息', userInfo);
// 7. 如果用户有角色但当前平台没有激活角色,则自动设置一个
if (userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) {
await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode);
}
// 8. 生成 JWT Token
const tokenPayload = {
id: user.id,
username: user.username,
real_name: user.real_name,
platform_code: platformCode,
current_role_id: userInfo.employees_id,
current_store_id: userInfo.store_id || null,
};
const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, {
expiresIn: app.config.jwt.expiresIn,
});
return {
success: true,
data: {
user: {
id: user.id,
username: user.username,
real_name: user.real_name,
phone: user.phone,
email: user.email,
status: user.status,
last_login_at: user.last_login_at,
roles: userInfo.roles,
role_id: userInfo.role_id,
menus: userInfo.menus,
permissions: userInfo.permissions,
userRole: userInfo.userRole,
realName: userInfo.realName,
},
token,
},
code: 200,
message: '登录成功',
};
return this.buildLoginResult(user, { includeUser: false });
} catch (error) {
app.coreLogger.error(`登录异常: ${error.message}`);
@ -108,6 +62,154 @@ class UserService extends Service {
}
}
/**
* 登录码登录:使用 ye4s_user.tmp_code 绑定的 wms_account_id 登录
* @param {string} code 登录码(ye4s_user.tmp_code)
* @return {Object} 登录结果
*/
async loginByCode(code) {
const { ctx, app } = this;
try {
const normalizedCode = typeof code === 'string' ? code.trim() : '';
if (!normalizedCode) {
return {
success: false,
data: null,
code: 0,
message: '缺少登录码 code',
};
}
const ye4sClient = ctx.app.mysql.get('ye4s');
const ye4sUser = await ye4sClient.get('ye4s_user', {
tmp_code: normalizedCode,
});
if (!ye4sUser) {
return {
success: false,
data: null,
code: 0,
message: '登录码不存在',
};
}
const wmsAccountId = Number(ye4sUser.wms_account_id);
if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) {
return {
success: false,
data: null,
code: 0,
message: '该登录码未绑定WMS账号',
};
}
const user = await ctx.model.Account.findOne({
where: { id: wmsAccountId },
});
if (!user) {
return {
success: false,
data: null,
code: 0,
message: '绑定的WMS账号不存在',
};
}
try {
this.checkUserStatus(user);
} catch (statusError) {
app.coreLogger.warn(`登录码登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`);
return {
success: false,
data: null,
code: 0,
message: '绑定账号状态异常',
};
}
await this.updateLastLoginTime(user.id);
return this.buildLoginResult(user);
} catch (error) {
app.coreLogger.error(`登录码登录异常: ${error.message}`);
return {
success: false,
data: null,
code: 0,
message: '登录失败,请稍后重试',
};
}
}
/**
* 生成统一登录成功结构
* @param {Object} user
* @return {Object}
*/
async buildLoginResult(user, options = {}) {
const { ctx, app } = this;
const includeUser = options.includeUser !== false;
// 设置设备类型(用于菜单查询)
const platformCode = ctx.header.platform || 'web';
// 获取用户完整信息
const userInfo = await this.findById(user.id);
console.log('用户信息', userInfo);
if (!userInfo) {
throw new Error('用户信息加载失败');
}
// 如果用户有角色但当前平台没有激活角色,则自动设置一个
if (userInfo && userInfo.roles && userInfo.roles.length > 0 && !userInfo.role_id) {
await this.ensurePlatformActiveRole(user.id, userInfo.roles[0].id, platformCode);
}
// 生成 JWT Token
const tokenPayload = {
id: user.id,
username: user.username,
real_name: user.real_name,
platform_code: platformCode,
current_role_id: userInfo.employees_id,
current_store_id: userInfo.store_id || null,
};
const token = app.jwt.sign(tokenPayload, app.config.jwt.secret, {
expiresIn: app.config.jwt.expiresIn,
});
const payloadData = {
token,
};
if (includeUser) {
payloadData.user = {
id: user.id,
username: user.username,
real_name: user.real_name,
phone: user.phone,
email: user.email,
status: user.status,
last_login_at: user.last_login_at,
roles: userInfo.roles,
role_id: userInfo.role_id,
menus: userInfo.menus,
permissions: userInfo.permissions,
userRole: userInfo.userRole,
realName: userInfo.realName,
};
}
return {
success: true,
data: payloadData,
code: 200,
message: '登录成功',
};
}
/**
* 切换角色(重构版)
* @param {Object} data - 切换角色数据
@ -120,7 +222,7 @@ class UserService extends Service {
const user = ctx.state.user || ctx.user;
try {
// 验证角色关联是否存在且有效
const accountStoreRole = await ctx.model.AccountStoreEmployee.findOne({
const accountStoreEmployee = await ctx.model.AccountStoreEmployee.findOne({
where: {
id: data.roleId,
account_id: user.id,
@ -129,12 +231,12 @@ class UserService extends Service {
include: [
{
model: ctx.model.EmployeeRole,
as: 'employeeRole',
as: 'employeeRoles',
},
],
});
if (!accountStoreRole) {
if (!accountStoreEmployee) {
throw new Error('角色不存在或未授权');
}
@ -159,7 +261,7 @@ class UserService extends Service {
real_name: user.real_name,
platform_code: platformCode,
current_role_id: userInfo.employees_id,
current_store_id: accountStoreRole.store_id || null,
current_store_id: accountStoreEmployee.store_id || null,
};
const newToken = app.jwt.sign(tokenPayload, app.config.jwt.secret, {
expiresIn: app.config.jwt.expiresIn,
@ -240,7 +342,7 @@ class UserService extends Service {
include: [
{
model: ctx.model.EmployeeRole,
as: 'employeeRole',
as: 'employeeRoles',
attributes: [ 'id', 'role_id' ],
},
{
@ -546,11 +648,23 @@ class UserService extends Service {
}
try {
// 1. 获取员工的角色
// 1. 获取员工绑定且启用的角色
const roles = await ctx.model.EmployeeRole.findAll({
attributes: [ 'role_id' ],
where: {
employee_id: activeEmployeeId,
},
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [],
where: {
status: 1,
},
required: true,
},
],
raw: true, // 获取纯数据对象
});
console.log('员工绑定的角色', roles);
@ -558,7 +672,10 @@ class UserService extends Service {
return [];
}
const roleIds = roles.map(item => item.role_id);
const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ];
if (roleIds.length === 0) {
return [];
}
// 2. 获取角色的权限
const rolePermissions = await ctx.model.RolePermission.findAll({
@ -573,13 +690,17 @@ class UserService extends Service {
return [];
}
const permissionIds = rolePermissions.map(item => item.permission_id);
const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ];
if (permissionIds.length === 0) {
return [];
}
const permissions = await ctx.model.Permission.findAll({
where: {
id: {
[Op.in]: permissionIds,
},
status: 1,
// 修正 like 查询
type: {
[ctx.app.Sequelize.Op.notLike]: '%_pages',
@ -613,11 +734,23 @@ class UserService extends Service {
}
try {
// 1. 获取员工的角色
// 1. 获取员工绑定且启用的角色
const roles = await ctx.model.EmployeeRole.findAll({
attributes: [ 'role_id' ],
where: {
employee_id: activeEmployeeId,
},
include: [
{
model: ctx.model.Role,
as: 'role',
attributes: [],
where: {
status: 1,
},
required: true,
},
],
raw: true, // 获取纯数据对象
});
console.log('员工绑定的角色', roles);
@ -625,7 +758,10 @@ class UserService extends Service {
return [];
}
const roleIds = roles.map(item => item.role_id);
const roleIds = [ ...new Set(roles.map(item => item.role_id).filter(Boolean)) ];
if (roleIds.length === 0) {
return [];
}
// 2. 获取角色的权限
const rolePermissions = await ctx.model.RolePermission.findAll({
@ -640,7 +776,10 @@ class UserService extends Service {
return [];
}
const permissionIds = rolePermissions.map(item => item.permission_id);
const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ];
if (permissionIds.length === 0) {
return [];
}
// 3. 获取权限对应的菜单(根据设备筛选)
const permissions = await ctx.model.Permission.findAll({
@ -648,6 +787,7 @@ class UserService extends Service {
id: {
[Op.in]: permissionIds,
},
status: 1,
// 修正 like 查询
type: {
[Op.like]: `${ctx.header.platform}_%`,
@ -697,7 +837,7 @@ class UserService extends Service {
// 构建树形结构
data.forEach(item => {
const node = map.get(item.id);
if (item.parent_id === 0) {
if (!item.parent_id) {
roots.push(node);
} else {
const parent = map.get(item.parent_id);

View File

@ -230,6 +230,348 @@ class entryOrderService extends Service {
};
}
async findByOrderCode(entryOrderCode, warehouseId, storeId) {
const { ctx } = this;
return await ctx.model.EntryOrder.findOne({
where: {
entry_order_code: entryOrderCode,
warehouse_id: warehouseId,
store_id: storeId,
is_enabled: 1,
deleted_at: null,
},
include: [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [[ 'company_name', 'store_name' ]],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [[ 'company_name', 'store_name' ]],
},
{
model: ctx.model.EntryItems,
as: 'items',
include: [
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'product_code', 'product_name' ],
},
],
},
],
});
}
async findByStatus(status, params = {}) {
const { ctx, app } = this;
const { warehouse_id, store_id, start_date, end_date, page = 1, pageSize = 20 } = params;
const where = {
order_status: status,
is_enabled: 1,
deleted_at: null,
};
if (warehouse_id) {
where.warehouse_id = warehouse_id;
}
if (store_id) {
where.store_id = store_id;
}
if (start_date || end_date) {
where.created_at = {};
if (start_date) {
where.created_at[app.Sequelize.Op.gte] = start_date;
}
if (end_date) {
where.created_at[app.Sequelize.Op.lte] = end_date;
}
}
const currentPage = Math.max(Number(page) || 1, 1);
const currentPageSize = Math.max(Number(pageSize) || 20, 1);
const { count, rows } = await ctx.model.EntryOrder.findAndCountAll({
where,
include: [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [[ 'company_name', 'store_name' ]],
},
{
model: ctx.model.Store,
as: 'store',
attributes: [[ 'company_name', 'store_name' ]],
},
],
order: [[ 'created_at', 'DESC' ]],
offset: (currentPage - 1) * currentPageSize,
limit: currentPageSize,
distinct: true,
});
return {
list: rows,
pagination: {
page: currentPage,
pageSize: currentPageSize,
total: count,
totalPages: Math.ceil(count / currentPageSize),
},
};
}
async getStatsByWarehouse(warehouseId, startDate, endDate) {
const { ctx, app } = this;
const where = {
warehouse_id: warehouseId,
is_enabled: 1,
deleted_at: null,
};
if (startDate || endDate) {
where.created_at = {};
if (startDate) {
where.created_at[app.Sequelize.Op.gte] = startDate;
}
if (endDate) {
where.created_at[app.Sequelize.Op.lte] = endDate;
}
}
const result = await ctx.model.EntryOrder.findAll({
attributes: [
'order_status',
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'count' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('total_order_lines')), 'total_lines' ],
],
where,
group: [ 'order_status' ],
raw: true,
});
const stats = {
pending: 0,
confirmed: 0,
partial_received: 0,
completed: 0,
cancelled: 0,
total: 0,
total_lines: 0,
};
result.forEach(item => {
const status = String(item.order_status || '').toLowerCase();
const count = parseInt(item.count, 10) || 0;
const totalLines = parseInt(item.total_lines, 10) || 0;
if (stats[status] !== undefined) {
stats[status] = count;
}
stats.total += count;
stats.total_lines += totalLines;
});
return stats;
}
async updateSyncStatus(orderId, status, message = null, options = {}) {
const { ctx } = this;
const order = await ctx.model.EntryOrder.findByPk(orderId, {
transaction: options.transaction,
});
if (!order) {
throw new Error('入库单不存在');
}
const updateData = {
sync_status: status,
};
if (message !== null) {
updateData.sync_message = message;
}
return await order.update(updateData, {
transaction: options.transaction,
});
}
async updateOrderStatus(orderId, status, options = {}) {
const { ctx } = this;
const order = await ctx.model.EntryOrder.findByPk(orderId, {
transaction: options.transaction,
});
if (!order) {
throw new Error('入库单不存在');
}
const validTransitions = {
PENDING: [ 'CONFIRMED', 'CANCELLED' ],
CONFIRMED: [ 'PARTIAL_RECEIVED', 'COMPLETED', 'CANCELLED' ],
PARTIAL_RECEIVED: [ 'COMPLETED', 'CANCELLED' ],
CREATED: [ 'PENDING', 'CANCELLED' ],
CREATING: [ 'PENDING', 'CANCELLED' ],
};
const allowedTransitions = validTransitions[order.order_status];
if (!allowedTransitions || !allowedTransitions.includes(status)) {
throw new Error(`状态从${order.order_status}转换到${status}不被允许`);
}
return await order.update({ order_status: status }, {
transaction: options.transaction,
});
}
async calculateReceivedQuantities(orderId) {
const { ctx, app } = this;
const order = await ctx.model.EntryOrder.findByPk(orderId, {
attributes: [ 'id', 'entry_order_code' ],
raw: true,
});
if (!order) {
throw new Error('入库单不存在');
}
const items = await ctx.model.EntryItems.findAll({
where: { order_id: orderId },
attributes: [ 'id', 'count', 'item_id' ],
raw: true,
});
const itemIds = [ ...new Set(items.map(item => item.item_id).filter(Boolean)) ];
const receivedRows = itemIds.length > 0
? await ctx.model.Storage.findAll({
where: {
inbound_order_no: order.entry_order_code,
item_id: itemIds,
},
attributes: [
'item_id',
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'received' ],
],
group: [ 'item_id' ],
raw: true,
})
: [];
const receivedMap = new Map(
receivedRows.map(row => [ Number(row.item_id), Number(row.received) || 0 ])
);
let totalExpected = 0;
let totalReceived = 0;
let allReceived = items.length > 0;
let anyReceived = false;
items.forEach(item => {
const expected = Number(item.count) || 0;
const received = receivedMap.get(Number(item.item_id)) || 0;
totalExpected += expected;
totalReceived += received;
if (expected > 0 && received < expected) {
allReceived = false;
}
if (received > 0) {
anyReceived = true;
}
});
return {
total_expected: totalExpected,
total_received: totalReceived,
all_received: allReceived,
any_received: anyReceived,
percentage: totalExpected > 0 ? Math.round((totalReceived / totalExpected) * 100) : 0,
};
}
async batchUpdateReceived(updates, options = {}) {
const { ctx } = this;
const externalTransaction = options.transaction || null;
const transaction = externalTransaction || await ctx.model.transaction();
try {
const pendingUpdates = [];
for (const update of updates) {
const { id, quantity } = update;
const item = await ctx.model.EntryItems.findByPk(id, { transaction });
if (!item) {
throw new Error(`入库明细 ${id} 不存在`);
}
item.validateReceiveQuantity(quantity);
pendingUpdates.push({
item,
quantity,
});
}
for (const pending of pendingUpdates) {
const newReceived = (pending.item.received_quantity || 0) + pending.quantity;
await pending.item.update({
received_quantity: newReceived,
}, { transaction });
}
if (!externalTransaction) {
await transaction.commit();
}
return { success: true };
} catch (error) {
if (!externalTransaction) {
await transaction.rollback();
}
throw error;
}
}
async getOrderProgress(orderId) {
const { ctx, app } = this;
const items = await ctx.model.EntryItems.findAll({
where: { order_id: orderId },
attributes: [
[ app.Sequelize.fn('SUM', app.Sequelize.col('count')), 'total_plan' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('received_quantity')), 'total_received' ],
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'item_count' ],
],
raw: true,
});
const result = items[0] || {};
const totalPlan = parseInt(result.total_plan, 10) || 0;
const totalReceived = parseInt(result.total_received, 10) || 0;
return {
total_plan: totalPlan,
total_received: totalReceived,
total_remaining: Math.max(0, totalPlan - totalReceived),
item_count: parseInt(result.item_count, 10) || 0,
progress_percent: totalPlan > 0 ? Math.min(100, Math.round((totalReceived / totalPlan) * 100)) : 0,
is_completed: totalReceived >= totalPlan,
};
}
async tryCreateEntryOrder(order, appKey, storeId, warehouseId, totalOrderLines, sourceType, qimenOwnerCode, qimenWarehouseCode, transaction = null) {
const { app } = this;
const { ctx } = this;

View File

@ -1234,15 +1234,11 @@ class stockStoreService extends Service {
// 获取总数
ctx.model.StockWarehouse.count({
where: queryOptions.where,
include: [{
model: ctx.model.StoreWarehouse,
as: 'store_stock',
attributes: [ 'store_remask' ],
where: {
use_status: 1,
},
include: [ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
required: true,
}, {
attributes: [ 'store_remask' ],
}), {
...prohibitedQueryOptions,
model: ctx.model.ProhibitedType,
as: 'prohibited',
@ -1255,15 +1251,11 @@ class stockStoreService extends Service {
// 获取分页数据
ctx.model.StockWarehouse.findAll({
...queryOptions,
include: [{
model: ctx.model.StoreWarehouse,
as: 'store_stock',
attributes: [ 'store_remask' ],
where: {
use_status: 1,
},
include: [ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
required: true,
}, {
attributes: [ 'store_remask' ],
}), {
...prohibitedQueryOptions,
model: ctx.model.ProhibitedType,
as: 'prohibited',
@ -2792,11 +2784,11 @@ class stockStoreService extends Service {
required: false,
});
}
includeConditions.push({
model: app.model.StoreWarehouse,
as: 'store_stock',
includeConditions.push(app.model.StoreWarehouse.buildStoreStockInclude({
warehouseId,
required: false,
attributes: [ 'store_id', 'store_remask' ],
});
}));
// 执行查询
console.log('查询商品===》');

View File

@ -5,5 +5,248 @@ class IndexService extends Service {
async index() {
}
async findByStockAndBatch(stockId, batchNo, inventoryType = 'ZP') {
const { ctx } = this;
return await ctx.model.Storage.findOne({
where: {
stock_id: stockId,
batch_no: batchNo,
inventory_type: inventoryType,
is_enabled: 1,
delete_at: null,
},
include: [
{
model: ctx.model.LocationSpace,
as: 'space',
attributes: [ 'space_code', 'custom_name' ],
},
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ [ 'company_name', 'store_name' ] ],
},
],
});
}
async findBySpace(spaceId) {
const { ctx } = this;
return await ctx.model.Storage.findAll({
where: {
space_id: spaceId,
is_enabled: 1,
delete_at: null,
},
include: [
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'product_code', 'product_name' ],
},
],
order: [ [ 'inbound_time', 'ASC' ] ],
});
}
async findAvailableByWarehouse(warehouseId, stockId = null) {
const { ctx, app } = this;
const where = {
warehouse_id: warehouseId,
is_enabled: 1,
delete_at: null,
available_quantity: { [app.Sequelize.Op.gt]: 0 },
};
if (stockId) {
where.stock_id = stockId;
}
return await ctx.model.Storage.findAll({
where,
include: [
{
model: ctx.model.LocationSpace,
as: 'space',
attributes: [ 'space_code', 'custom_name' ],
},
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'product_code', 'product_name' ],
},
],
order: [
[ 'expiry_date', 'ASC' ],
[ 'inbound_time', 'ASC' ],
],
});
}
async findExpiringSoon(days = 30) {
const { ctx, app } = this;
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + days);
return await ctx.model.Storage.findAll({
where: {
expiry_date: {
[app.Sequelize.Op.between]: [ new Date(), expiryDate ],
},
is_enabled: 1,
delete_at: null,
quantity: { [app.Sequelize.Op.gt]: 0 },
},
include: [
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ [ 'company_name', 'store_name' ] ],
},
{
model: ctx.model.StockWarehouse,
as: 'stock',
attributes: [ 'product_code', 'product_name' ],
},
],
order: [ [ 'expiry_date', 'ASC' ] ],
});
}
async updateQuantity(id, quantityChange, lockedChange = 0, options = {}) {
const { ctx } = this;
const storage = await ctx.model.Storage.findByPk(id, {
transaction: options.transaction,
});
if (!storage) {
throw new Error('库存记录不存在');
}
const newQuantity = storage.quantity + quantityChange;
const newLocked = storage.locked_quantity + lockedChange;
if (newQuantity < 0) {
throw new Error('库存数量不能为负数');
}
if (newLocked < 0 || newLocked > newQuantity) {
throw new Error('锁定数量无效');
}
const updateData = {
quantity: newQuantity,
locked_quantity: newLocked,
available_quantity: newQuantity - newLocked,
updated_at: new Date(),
};
await storage.update(updateData, {
transaction: options.transaction,
});
return storage;
}
async lockQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, 0, quantity, options);
}
async unlockQuantity(id, quantity, options = {}) {
return await this.updateQuantity(id, 0, -quantity, options);
}
async allocateQuantity(id, quantity, options = {}) {
const { ctx } = this;
const storage = await ctx.model.Storage.findByPk(id, {
transaction: options.transaction,
});
if (!storage) {
throw new Error('库存记录不存在');
}
if (storage.available_quantity < quantity) {
throw new Error('可用数量不足');
}
return await this.updateQuantity(id, 0, quantity, options);
}
async getStockSummary(warehouseId) {
const { ctx, app } = this;
return await ctx.model.Storage.findAll({
attributes: [
'stock_id',
'inventory_type',
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('locked_quantity')), 'total_locked' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('available_quantity')), 'total_available' ],
],
where: {
warehouse_id: warehouseId,
is_enabled: 1,
delete_at: null,
},
group: [ 'stock_id', 'inventory_type' ],
raw: true,
});
}
async getSpaceUsage(spaceId) {
const { ctx, app } = this;
const result = await ctx.model.Storage.findAll({
attributes: [
'inventory_type',
[ app.Sequelize.fn('COUNT', app.Sequelize.col('id')), 'record_count' ],
[ app.Sequelize.fn('SUM', app.Sequelize.col('quantity')), 'total_quantity' ],
],
where: {
space_id: spaceId,
is_enabled: 1,
delete_at: null,
},
group: [ 'inventory_type' ],
raw: true,
});
const usage = {
normal: 0,
defective: 0,
damaged: 0,
frozen: 0,
total: 0,
};
result.forEach(item => {
let type;
switch (item.inventory_type) {
case 'ZP':
type = 'normal';
break;
case 'CC':
type = 'defective';
break;
case 'JS':
case 'XS':
type = 'damaged';
break;
case 'DJ':
type = 'frozen';
break;
default:
return;
}
usage[type] = parseInt(item.total_quantity, 10) || 0;
usage.total += usage[type];
});
return usage;
}
}
module.exports = IndexService;

View File

@ -124,6 +124,7 @@ class ReceivingService extends Service {
attributes: ['store_remask'],
where: {
use_status: 1,
warehouse_id: ctx.user.store_id,
},
required: false,
}, {
@ -144,6 +145,7 @@ class ReceivingService extends Service {
attributes: ['store_remask'],
where: {
use_status: 1,
warehouse_id: ctx.user.store_id,
},
required: false,
}, {
@ -697,10 +699,14 @@ class ReceivingService extends Service {
let store_name = null;
if (store_id) {
const store = await app.model.StoreWarehouse.findOne({
where: { store_id },
where: {
store_id,
warehouse_id,
use_status: 1,
},
});
if (store) {
store_name = store.store_name;
store_name = store.store_remask;
}
}
@ -772,6 +778,7 @@ class ReceivingService extends Service {
attributes: ['store_remask'],
where: {
use_status: 1,
warehouse_id: warehouseId,
},
required: false,
}, {
@ -1142,11 +1149,11 @@ class ReceivingService extends Service {
const stockWarehouse = await ctx.model.StockWarehouse.findOne({
where: { id: stock_id },
include: [
{
model: ctx.model.StoreWarehouse,
as: 'store_stock',
attributes: ['store_id', 'store_remask'],
},
ctx.model.StoreWarehouse.buildStoreStockInclude({
warehouseId: ctx.user.store_id,
required: false,
attributes: [ 'store_id', 'store_remask' ],
}),
],
});
@ -1519,11 +1526,11 @@ class ReceivingService extends Service {
warehouse_id: warehouseId,
},
include: [
{
model: app.model.StoreWarehouse,
as: 'store_stock',
attributes: ['store_id', 'store_remask'],
},
app.model.StoreWarehouse.buildStoreStockInclude({
warehouseId,
required: false,
attributes: [ 'store_id', 'store_remask' ],
}),
{
model: app.model.StockBarcode,
as: 'barcodes',

View File

@ -434,6 +434,48 @@ class StoreService extends Service {
// ==================== 辅助方法 ====================
async ensureEmployeeRoleBinding({ accountId, storeId, roleId, realName = '', transaction }) {
const { ctx } = this;
const [ employee ] = await ctx.model.AccountStoreEmployee.findOrCreate({
where: {
account_id: accountId,
store_id: storeId,
},
defaults: {
account_id: accountId,
store_id: storeId,
status: 1,
real_name: realName || '',
},
transaction,
});
const shouldRefreshEmployee = Number(employee.status) !== 1
|| (realName && employee.real_name !== realName);
if (shouldRefreshEmployee) {
await employee.update({
status: 1,
real_name: realName || employee.real_name || '',
}, { transaction });
}
const [ employeeRole ] = await ctx.model.EmployeeRole.findOrCreate({
where: {
employee_id: employee.id,
role_id: roleId,
},
defaults: {
employee_id: employee.id,
role_id: roleId,
},
transaction,
});
return { employee, employeeRole };
}
/**
* 为创建者分配管理员角色
* @param storeId
@ -460,18 +502,15 @@ class StoreService extends Service {
throw new Error(`未初始化${role_code}管理员角色`);
}
// 分配角色给创建者
const storerole = await ctx.model.AccountStoreRole.create({
account_id: userId,
store_id: storeId,
role_id: adminRole.id,
status: 1,
real_name: realName || '',
assigned_by: userId,
}, {
const { employee } = await this.ensureEmployeeRoleBinding({
accountId: userId,
storeId,
roleId: adminRole.id,
realName: realName || '',
transaction,
});
return storerole;
return employee;
}
@ -675,27 +714,13 @@ class StoreService extends Service {
const { account_id, real_name } = applyData;
for (const role of roles) {
// 检查是否已存在该角色分配
const existingRole = await ctx.model.AccountStoreRole.findOne({
where: {
account_id,
store_id,
role_id: role.id,
status: 1,
},
await this.ensureEmployeeRoleBinding({
accountId: account_id,
storeId: store_id,
roleId: role.id,
realName: real_name || '',
transaction,
});
if (!existingRole) {
await ctx.model.AccountStoreRole.create({
account_id,
store_id,
role_id: role.id,
status: 1,
real_name,
join_token: code,
}, { transaction });
}
}
// 更新申请记录状态

View File

@ -0,0 +1,102 @@
# Association Eager-Loading 与 N+1 规约
更新时间: 2026-03-23
适用阶段: Model 重构阶段 4.4
范围: app/service/**/*.js 中涉及 Sequelize 关联查询的代码
## 1. 目标
- 降低关联查询的 SQL 次数与响应时间抖动。
- 统一 eager-loading 写法,避免 include 漂移导致错关联。
- 在不改变外部接口返回结构的前提下收敛查询成本。
## 2. 术语
- eager-loading: 通过 include 一次性加载关联数据。
- N+1: 先查 1 次主数据,再按每条主数据各查 1 次关联,导致总查询次数随 N 线性增长。
- 关联上下文约束: 在 include.where 中补齐业务维度(如 warehouse_id、use_status),避免跨上下文错关联。
## 3. 强制规则
1. 列表查询禁止在循环内按行查询关联表。
2. 只要关联数据是展示必需字段,优先使用 include 一次加载。
3. include 必须显式声明 attributes,禁止默认全字段拉取。
4. include 需要业务上下文约束时,必须补齐 where 条件(典型: warehouse_id + use_status)。
5. hasMany/hasOne/belongsTo 的 as 必须与 model 定义一致,禁止临时字符串别名。
6. 分页列表若包含 hasMany,优先控制返回列并评估 distinct/subQuery,防止计数与分页漂移。
7. count 与 findAll 不一致时,必须拆分并保持 where/include 语义一致。
## 4. 推荐写法
### 4.1 反模式(N+1)
```js
const list = await Model.findAll({ where });
for (const row of list) {
row.child = await Child.findOne({ where: { id: row.child_id } });
}
```
### 4.2 规约写法(eager-loading)
```js
const list = await Model.findAll({
where,
attributes: [ 'id', 'name', 'child_id' ],
include: [
{
model: Child,
as: 'child',
attributes: [ 'id', 'name' ],
required: false,
},
],
});
```
### 4.3 仓库维度约束(本仓库高频场景)
```js
include: [
{
model: ctx.model.StoreWarehouse,
as: 'store_stock',
attributes: [ 'store_id', 'store_remask' ],
where: {
warehouse_id: warehouseId,
use_status: 1,
},
required: false,
},
]
```
## 5. 当前代码落地点
- receiving 链路已按规约补齐仓库维度过滤,避免 StoreWarehouse 跨仓匹配。
- receiving 与 receiving_detail 已移除无效 Storage hasMany 关联,避免误导 include 设计。
- 后续优先治理:
- store_warehouse 与 stock_warehouse 的 store_id 语义对齐
- role / role_permission / permission 的关联约束与 include 一致性
## 6. 变更门禁
每批涉及关联查询的改动,至少执行以下门禁:
1. node .\\script\\method-output-regression.cjs compare
2. node .\\script\\tmp-generate-method-regression-test.cjs
3. npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
4. npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
交付标准:
- compare 结果 mismatch=0
- 生成回归与关键冒烟测试全部通过
## 7. PR 自检清单
- [ ] 是否存在循环内数据库查询。
- [ ] include 是否补齐 attributes。
- [ ] include.where 是否补齐业务上下文约束。
- [ ] as 是否与 model 关联定义一致。
- [ ] 是否完成 method-output compare 与回归测试。

61
association_fix_plan.md Normal file
View File

@ -0,0 +1,61 @@
# Association Fix Plan
更新时间: 2026-03-23
适用阶段: Model 重构阶段 4(关联关系规范化)
## 1. 目标
- 统一 alias 命名规则(belongsTo/hasOne 用单数,hasMany/belongsToMany 用复数)。
- 清理重复或冲突关联定义,避免 include 歧义。
- 保持 system/qimen 输出结构不变,通过 baseline/compare 门禁验证。
## 2. 已完成修复
### 2.1 幽灵模型收敛(已完成)
- 将 AccountStoreRole 相关调用链迁移到 AccountStoreEmployee + EmployeeRole + Role + Store。
- 覆盖主链路:
- app/service/systems/store.js
- app/service/systems/account_platform.js
- app/service/systems/auth/user.js
### 2.2 alias 标准化(已完成)
- 新标准 alias:
- accountStoreEmployees
- employeeRoles
- 已完成调用迁移:
- account_platform 服务 include 与读取逻辑统一为 employeeRoles
- auth/user 服务 include 统一为 employeeRoles
### 2.3 重复关联清理(已完成)
- 已移除以下重复兼容 alias 定义:
- Account.accountStoreRoles
- AccountStoreEmployee.employeeRole
- Role.employeeRole
- Store.accountStoreEmployee
- 保留必要单数 alias(belongsTo 语义):
- AccountPlatformActive.accountStoreEmployee
## 3. 验证策略
每批改动执行以下门禁:
1. node .\\script\\method-output-regression.cjs baseline 8
2. node .\\script\\method-output-regression.cjs compare
3. node .\\script\\tmp-generate-method-regression-test.cjs
4. npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
5. npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
## 4. 当前状态
- 输出一致性门禁:通过(mismatch=0)。
- 关键冒烟测试:通过。
- 对外 API 参数/返回:无结构变更。
## 5. 剩余工作
- 全量扫描其余模型类方法中的 include alias 一致性(已完成,差集扫描异常项 0 个)。
- 评估并落地 permission.parent_id 自关联约束策略(已完成:root 语义归一为 NULL + 自关联 FK)。
- 进入阶段 5:Model 内部能力清理与边界固化。

View File

@ -0,0 +1,65 @@
# Association FK Consistency Report
更新时间: 2026-03-23T03:08:35.772Z
数据库: wms
## Summary
- DB 外键数: 51
- 模型关联数: 89
- 可直接匹配外键: 53
- 模型定义但 DB 无外键约束: 28
- 无法解析到模型表映射: 5
- DB 存在但模型未声明的外键: 13
## Missing Constraints (Top 20)
- wms_receiving.creator_id->wms_account_store_employee.id (app/model/account_store_employee.js, hasMany, as=Receiving)
- wms_api_app.warehouse_id->wms_store.id (app/model/api_app.js, belongsTo, as=warehouse)
- wms_fast_where.pid->wms_fast_where.id (app/model/fast_where.js, belongsTo, as=parent)
- wms_fast_where.pid->wms_fast_where.id (app/model/fast_where.js, hasMany, as=children)
- wms_location_space.zone_id->wms_location_zone.id (app/model/location_space.js, belongsTo, as=zone)
- wms_receiving_detail.space_id->wms_location_space.id (app/model/location_space.js, hasMany, as=receiving)
- wms_location_space.zone_id->wms_location_zone.id (app/model/location_zone.js, hasMany, as=spaces)
- wms_location_zone.warehouse_id->wms_location_zone.warehouse_id (app/model/location_zone.js, belongsTo, as=pickStartPoint)
- wms_permission.parent_id->wms_permission.id (app/model/permission.js, hasMany, as=children)
- wms_permission.parent_id->wms_permission.id (app/model/permission.js, belongsTo, as=parent)
- wms_receiving.warehouse_id->wms_store.id (app/model/receiving.js, belongsTo, as=warehouse)
- wms_receiving.creator_id->wms_account_store_employee.id (app/model/receiving.js, belongsTo, as=creator)
- wms_storage.receiving_id->wms_receiving.id (app/model/receiving.js, hasMany, as=storage_records)
- wms_receiving.store_id->wms_store_warehouse.store_id (app/model/receiving.js, belongsTo, as=store)
- wms_receiving_detail.system_product_id->wms_stock_warehouse.id (app/model/receiving_detail.js, belongsTo, as=system_product)
- wms_storage.receiving_detail_id->wms_receiving_detail.id (app/model/receiving_detail.js, hasMany, as=storage_details)
- wms_receiving_detail.space_id->wms_location_space.id (app/model/receiving_detail.js, belongsTo, as=receiving_space)
- wms_role.store_id->wms_store.id (app/model/role.js, belongsTo, as=store)
- wms_role_permission.permission_id->wms_permission.id (app/model/role_permission.js, belongsTo, as=permission)
- wms_stock_warehouse.store_id->wms_store_warehouse.store_id (app/model/stock_warehouse.js, belongsTo, as=store_stock)
## Unresolved Associations (Top 20)
- app/model/order_delivery_factory.js: DynamicModel -> ItemsModel (type=hasMany, fk=order_id)
- app/model/order_delivery_factory.js: ItemsModel -> DynamicModel (type=belongsTo, fk=order_id)
- app/model/order_delivery_factory.js: DynamicModel -> this.app.model.Store (type=belongsTo, fk=store_id)
- app/model/order_delivery_factory.js: DynamicModel -> this.app.model.Store (type=belongsTo, fk=warehouse_id)
- app/model/print_item.js: PrintItem -> app.model.OtherModel (type=belongsTo, fk=xxx)
## DB-only Foreign Keys (Top 20)
- wms_account_login_log.user_id->wms_account.id
- wms_embargo_policies.warehouse_id->wms_store.id
- wms_express_setting.express_code->wms_express.code
- wms_express_setting.warehouse_id->wms_store.id
- wms_order_delivery.store_id->wms_store.id
- wms_order_delivery.warehouse_id->wms_store.id
- wms_order_express.order_id->wms_order_delivery.id
- wms_order_express_print_data.express_id->wms_order_express.id
- wms_order_items.order_id->wms_order_delivery.id
- wms_stock_warehouse.warehouse_id->wms_store.id
- wms_store_join.account_id->wms_account.id
- wms_store_join.store_id->wms_store.id
- wms_system_log.store_id->wms_store.id
## Notes
- belongsToMany 通过中间表映射,未纳入本次“直接外键”匹配。
- 动态分表工厂中的关联(order_delivery_factory/order_items_factory)不做静态表级强校验。

View File

@ -0,0 +1,165 @@
# Association Validation Checklist
更新时间: 2026-03-23
范围: app/model/*.js + 核心系统 service 调用链
## 1. 核心检查项
- [x] AccountStoreRole 幽灵引用已移除(服务主链路)。
- [x] AccountStoreEmployee <-> EmployeeRole <-> Role 关系可用。
- [x] hasMany alias 复数化(employeeRoles/accountStoreEmployees)。
- [x] 重复兼容 alias 已清理(主链路)。
- [x] 对外接口输出一致(baseline/compare mismatch=0)。
- [x] 关键登录与用户信息链路测试通过。
## 2. 关键模型校验结果
| 模型 | 关键关联 | 结果 | 备注 |
| --- | --- | --- | --- |
| Account | hasMany AccountStoreEmployee as accountStoreEmployees | PASS | 已移除 accountStoreRoles |
| AccountStoreEmployee | hasMany EmployeeRole as employeeRoles | PASS | 已移除 employeeRole |
| Role | hasMany EmployeeRole as employeeRoles | PASS | 已移除 employeeRole |
| Store | hasMany AccountStoreEmployee as accountStoreEmployees | PASS | 已移除 accountStoreEmployee |
| AccountPlatformActive | belongsTo AccountStoreEmployee as accountStoreEmployee | PASS | belongsTo 单数语义保留 |
## 3. 服务调用链校验结果
| 服务 | 校验项 | 结果 |
| --- | --- | --- |
| systems/account_platform | include/读取 employeeRoles 一致 | PASS |
| systems/auth/user | include alias 使用 employeeRoles | PASS |
| systems/store | 角色绑定链路使用 EmployeeRole | PASS |
| systems/storage/receiving | StoreWarehouse 关联补 warehouse_id/use_status 过滤,避免跨仓错关联 | PASS |
## 4. 验证记录
- method-output compare: mismatch=0
- generated test: 8 passing
- smoke test (login/info/home): 6 passing
## 5. 4.1 全量审计结果(2026-03-23)
- 审计报告: association_fk_consistency_report.md
- DB 外键: 51
- 模型关联: 89
- 可直接匹配: 53
- 模型定义但 DB 无外键约束: 28
- DB 有外键但模型未声明: 13
- 动态模型/示例占位导致无法静态解析: 5
高优先级差异(建议先处理):
- receiving / receiving_detail / storage 三表关联的 FK 约束缺失项(第一批已处理:删除无效 hasMany(Storage) 关联,并修正 service include 过滤)
- store_warehouse 与 stock_warehouse/receiving 的 store_id 外键语义差异(已完成服务层与模型层双收敛)
- role / role_permission / permission 的部分 FK 未在 DB 层约束(核心约束已补齐,remaining: permission.parent_id 自关联约束策略评估)
### 5.1 高优先差异处理进展(receiving 第一批)
- 处理内容:
- 移除 `Receiving.hasMany(Storage, foreignKey: 'receiving_id')` 无效关联(storage 表不存在 receiving_id)。
- 移除 `ReceivingDetail.hasMany(Storage, foreignKey: 'receiving_detail_id')` 无效关联(storage 表不存在 receiving_detail_id)。
- `systems/storage/receiving` 多处 `StoreWarehouse` include/query 增加 `warehouse_id + use_status` 过滤,规避跨仓库错关联。
- `create` 流程中 `store_name` 改为来源 `store_remask`,与仓库门店展示语义对齐。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
### 5.2 高优先差异处理进展(store_warehouse/stock_warehouse 第二批)
- 处理内容:
- `systems/stock_store` 的 `store_stock` include 全量补齐 `warehouse_id + use_status` 条件,避免仅按 `store_id` 关联导致跨仓误匹配。
- 覆盖 count/findAll/search 三处核心查询路径,保持原有返回结构不变。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
### 5.3 高优先差异处理进展(role/permission 第三批)
- 处理内容:
- `systems/auth/user` 的权限与菜单查询链路补齐 `Role.status=1` 约束,仅启用角色参与授权。
- 权限查询补齐 `Permission.status=1` 约束,禁用权限不再进入 `user.permissions` 与菜单树。
- 对 role_id/permission_id 增加去重处理,避免重复关联导致的冗余查询和重复路径。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
### 5.4 DB 约束补齐进展(role_permission 第四批)
- 处理内容:
- 新增迁移 `database/migrations/20260323103000-align-role-permission-fk.js`:
- 将 `wms_role_permission.permission_id` 对齐为 `int(11)`(与 `wms_permission.id` 一致)。
- 在无孤儿数据时添加 `fk_wms_role_permission_permission` 外键(ON DELETE CASCADE, ON UPDATE RESTRICT)。
- 同步模型字段类型: `app/model/role_permission.js` 的 `permission_id` 改为 `INTEGER`。
- 执行结果:
- 已完成数据清洗:`wms_role_permission.permission_id` 孤儿记录 4 条已备份并删除;`wms_role.store_id=0` 的 3 条记录已备份并修正为 `NULL`。
- 已执行迁移核心动作:`permission_id` 类型已对齐为 `int(11)`,且外键 `fk_wms_role_permission_permission` 已生效。
- SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。
- 门禁结果:method-output compare mismatch=0,generated regression + smoke: 14 passing。
### 5.5 DB 约束补齐进展(role.store_id 第五批)
- 处理内容:
- 新增迁移 `database/migrations/20260323113000-add-role-store-fk.js`:
- 将 `wms_role.store_id` 对齐为 `bigint(20) unsigned NULL`。
- 补充索引 `idx_store_id`。
- 添加外键 `fk_wms_role_store`(ON UPDATE RESTRICT, ON DELETE SET NULL)。
- 执行结果:
- `wms_role.store_id` 外键已生效,孤儿计数=0。
- SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。
- 门禁结果:method-output compare mismatch=0,generated regression + smoke: 14 passing。
### 5.6 模型层复合键语义治理进展(store_warehouse/stock_warehouse 第六批)
- 处理内容:
- `StoreWarehouse` 模型新增统一构造器:`buildScopedWhere` / `buildStoreStockInclude`,收敛 `store_stock` include 的复合键语义。
- `StockWarehouse.belongsTo(StoreWarehouse as store_stock)` 与 `StoreWarehouse.hasMany(StockWarehouse as store_stock)` 显式标记 `constraints: false`,避免误导为单列外键。
- `Receiving.belongsTo(StoreWarehouse as store)` 显式标记 `constraints: false`,与 `store_id + warehouse_id` 业务语义对齐。
- `systems/stock_store` 与 `systems/storage/receiving` 已改为复用模型构造器,减少散落条件。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
### 5.7 DB 约束补齐进展(permission.parent_id 第七批)
- 处理内容:
- 新增迁移 `database/migrations/20260323123000-add-permission-parent-fk.js`:
- 将 `wms_permission.parent_id` 根节点语义从 `0` 规范为 `NULL`。
- 添加自关联外键 `fk_wms_permission_parent`(ON UPDATE RESTRICT, ON DELETE SET NULL)。
- 模型与服务语义对齐:
- `Permission.parent_id` 改为 `allowNull: true` / `defaultValue: null`,并在 setter 中兼容输入 `0 -> NULL`。
- 权限树构建根节点判断由 `parent_id===0` 收敛为 `!parent_id`(兼容历史与新语义)。
- 执行结果:
- 数据复核: `root_zero_after=0`、`root_null_after=42`、`orphan_after=0`。
- 外键生效: `fk_wms_permission_parent` 已存在。
- SequelizeMeta 已登记 `20260323123000-add-permission-parent-fk.js`。
- 触发器策略: 目标库因权限限制(binlog + SUPER)未创建触发器,改由应用层归一化 `0 -> NULL`。
- 验证结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing
## 6. 后续检查
- [x] 全量扫描其余模型类方法中的 include 别名一致性(service as 与 model as 差集扫描结果: 0)。
- [x] 补充 N+1 风险清单与 eager-loading 建议(见 association_eager_loading_n_plus_one_guideline.md)。
### 6.1 include alias 一致性收尾扫描(2026-03-23)
- 扫描范围:
- `app/model/**/*.js` 中 association `as` 定义
- `app/service/**/*.js` 中 include `as` 使用
- 扫描方式:
- 先做全量检索(model association / service include)
- 再做集合差集(service alias - model alias)自动比对
- 扫描结论:
- model alias 总数: 48
- 差集可疑项: 0
- 结论: 未发现 include alias 不一致问题,可关闭阶段 4 收尾检查第 1 项。
## 7. 4.4 规约落地记录(2026-03-23)
- 规约文档: association_eager_loading_n_plus_one_guideline.md
- 已固化要求:
- 禁止循环内逐条查询关联表(N+1)。
- include 必须声明 attributes。
- 仓库链路 include 必须补齐 warehouse_id + use_status 约束。
- 涉及关联查询改动必须执行 compare + generated test + smoke。

View File

@ -0,0 +1,115 @@
'use strict';
const TABLE = 'wms_role_permission';
const REF_TABLE = 'wms_permission';
const FK_NAME = 'fk_wms_role_permission_permission';
async function getColumnInfo(queryInterface, tableName, columnName) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT COLUMN_TYPE, IS_NULLABLE
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :tableName
AND COLUMN_NAME = :columnName
LIMIT 1
`,
{
replacements: {
tableName,
columnName,
},
}
);
return rows[0] || null;
}
async function hasConstraint(queryInterface, tableName, constraintName) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT 1
FROM information_schema.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE()
AND TABLE_NAME = :tableName
AND CONSTRAINT_NAME = :constraintName
LIMIT 1
`,
{
replacements: {
tableName,
constraintName,
},
}
);
return rows.length > 0;
}
async function getOrphanCount(queryInterface) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT COUNT(*) AS cnt
FROM wms_role_permission rp
LEFT JOIN wms_permission p ON p.id = rp.permission_id
WHERE p.id IS NULL
`
);
return Number(rows[0]?.cnt || 0);
}
module.exports = {
async up(queryInterface) {
const permissionIdColumn = await getColumnInfo(queryInterface, TABLE, 'permission_id');
if (!permissionIdColumn) {
throw new Error('Column wms_role_permission.permission_id not found.');
}
const columnType = String(permissionIdColumn.COLUMN_TYPE || '').toLowerCase();
// permission.id is int(11), keep child key type aligned before adding FK.
if (columnType !== 'int(11)') {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role_permission` MODIFY COLUMN `permission_id` int(11) NOT NULL COMMENT \'权限ID\''
);
}
const orphanCount = await getOrphanCount(queryInterface);
if (orphanCount > 0) {
throw new Error(
`Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_role_permission.permission_id. ` +
'Please clean orphan rows first, then rerun migration.'
);
}
const exists = await hasConstraint(queryInterface, TABLE, FK_NAME);
if (!exists) {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role_permission` ' +
'ADD CONSTRAINT `fk_wms_role_permission_permission` ' +
'FOREIGN KEY (`permission_id`) REFERENCES `wms_permission` (`id`) ' +
'ON UPDATE RESTRICT ON DELETE CASCADE'
);
}
},
async down(queryInterface) {
const exists = await hasConstraint(queryInterface, TABLE, FK_NAME);
if (exists) {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role_permission` DROP FOREIGN KEY `fk_wms_role_permission_permission`'
);
}
const permissionIdColumn = await getColumnInfo(queryInterface, TABLE, 'permission_id');
if (permissionIdColumn) {
const columnType = String(permissionIdColumn.COLUMN_TYPE || '').toLowerCase();
if (columnType !== 'bigint(20) unsigned') {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role_permission` MODIFY COLUMN `permission_id` bigint(20) unsigned NOT NULL COMMENT \'权限ID\''
);
}
}
},
};

View File

@ -0,0 +1,150 @@
'use strict';
const TABLE = 'wms_role';
const REF_TABLE = 'wms_store';
const FK_NAME = 'fk_wms_role_store';
const INDEX_NAME = 'idx_store_id';
async function getColumnInfo(queryInterface, tableName, columnName) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT COLUMN_TYPE, IS_NULLABLE
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :tableName
AND COLUMN_NAME = :columnName
LIMIT 1
`,
{
replacements: {
tableName,
columnName,
},
}
);
return rows[0] || null;
}
async function hasConstraint(queryInterface, tableName, constraintName) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT 1
FROM information_schema.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE()
AND TABLE_NAME = :tableName
AND CONSTRAINT_NAME = :constraintName
LIMIT 1
`,
{
replacements: {
tableName,
constraintName,
},
}
);
return rows.length > 0;
}
async function hasIndex(queryInterface, tableName, indexName) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT 1
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = :tableName
AND INDEX_NAME = :indexName
LIMIT 1
`,
{
replacements: {
tableName,
indexName,
},
}
);
return rows.length > 0;
}
async function getOrphanCount(queryInterface) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT COUNT(*) AS cnt
FROM wms_role r
LEFT JOIN wms_store s ON s.id = r.store_id
WHERE r.store_id IS NOT NULL
AND s.id IS NULL
`
);
return Number(rows[0]?.cnt || 0);
}
module.exports = {
async up(queryInterface) {
const storeIdColumn = await getColumnInfo(queryInterface, TABLE, 'store_id');
if (!storeIdColumn) {
throw new Error('Column wms_role.store_id not found.');
}
const columnType = String(storeIdColumn.COLUMN_TYPE || '').toLowerCase();
if (columnType !== 'bigint(20) unsigned') {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role` MODIFY COLUMN `store_id` bigint(20) unsigned NULL COMMENT \'所属仓库ID\''
);
}
const orphanCount = await getOrphanCount(queryInterface);
if (orphanCount > 0) {
throw new Error(
`Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_role.store_id. ` +
'Please clean orphan rows first, then rerun migration.'
);
}
const indexExists = await hasIndex(queryInterface, TABLE, INDEX_NAME);
if (!indexExists) {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role` ADD INDEX `idx_store_id` (`store_id`)'
);
}
const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME);
if (!fkExists) {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role` ' +
'ADD CONSTRAINT `fk_wms_role_store` ' +
'FOREIGN KEY (`store_id`) REFERENCES `wms_store` (`id`) ' +
'ON UPDATE RESTRICT ON DELETE SET NULL'
);
}
},
async down(queryInterface) {
const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME);
if (fkExists) {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role` DROP FOREIGN KEY `fk_wms_role_store`'
);
}
const indexExists = await hasIndex(queryInterface, TABLE, INDEX_NAME);
if (indexExists) {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role` DROP INDEX `idx_store_id`'
);
}
const storeIdColumn = await getColumnInfo(queryInterface, TABLE, 'store_id');
if (storeIdColumn) {
const columnType = String(storeIdColumn.COLUMN_TYPE || '').toLowerCase();
if (columnType !== 'bigint(20)') {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_role` MODIFY COLUMN `store_id` bigint(20) NULL COMMENT \'所属仓库ID\''
);
}
}
},
};

View File

@ -0,0 +1,109 @@
'use strict';
const TABLE = 'wms_permission';
const COLUMN = 'parent_id';
const FK_NAME = 'fk_wms_permission_parent';
async function hasConstraint(queryInterface, tableName, constraintName) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT 1
FROM information_schema.REFERENTIAL_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE()
AND TABLE_NAME = :tableName
AND CONSTRAINT_NAME = :constraintName
LIMIT 1
`,
{
replacements: {
tableName,
constraintName,
},
}
);
return rows.length > 0;
}
async function getOrphanCount(queryInterface) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT COUNT(*) AS cnt
FROM wms_permission p
LEFT JOIN wms_permission pp ON pp.id = p.parent_id
WHERE p.parent_id IS NOT NULL
AND p.parent_id <> 0
AND pp.id IS NULL
`
);
return Number(rows[0]?.cnt || 0);
}
async function getSelfLoopCount(queryInterface) {
const [ rows ] = await queryInterface.sequelize.query(
`
SELECT COUNT(*) AS cnt
FROM wms_permission
WHERE parent_id = id
`
);
return Number(rows[0]?.cnt || 0);
}
module.exports = {
async up(queryInterface) {
const orphanCount = await getOrphanCount(queryInterface);
if (orphanCount > 0) {
throw new Error(
`Cannot add ${FK_NAME}: found ${orphanCount} orphan rows in wms_permission.parent_id.`
);
}
const selfLoopCount = await getSelfLoopCount(queryInterface);
if (selfLoopCount > 0) {
throw new Error(
`Cannot add ${FK_NAME}: found ${selfLoopCount} self-loop rows (id = parent_id) in wms_permission.`
);
}
// Normalize root sentinel to NULL before adding FK.
await queryInterface.sequelize.query(
'UPDATE `wms_permission` SET `parent_id` = NULL WHERE `parent_id` = 0'
);
await queryInterface.sequelize.query(
"ALTER TABLE `wms_permission` MODIFY COLUMN `parent_id` int(11) NULL DEFAULT NULL COMMENT '父级ID(根节点为NULL)'"
);
const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME);
if (!fkExists) {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_permission` ' +
'ADD CONSTRAINT `fk_wms_permission_parent` ' +
'FOREIGN KEY (`parent_id`) REFERENCES `wms_permission` (`id`) ' +
'ON UPDATE RESTRICT ON DELETE SET NULL'
);
}
// Root node normalization from 0->NULL is handled in application model setters.
},
async down(queryInterface) {
const fkExists = await hasConstraint(queryInterface, TABLE, FK_NAME);
if (fkExists) {
await queryInterface.sequelize.query(
'ALTER TABLE `wms_permission` DROP FOREIGN KEY `fk_wms_permission_parent`'
);
}
await queryInterface.sequelize.query(
'UPDATE `wms_permission` SET `parent_id` = 0 WHERE `parent_id` IS NULL'
);
await queryInterface.sequelize.query(
"ALTER TABLE `wms_permission` MODIFY COLUMN `parent_id` int(11) NULL DEFAULT 0 COMMENT '父级ID'"
);
},
};

BIN
day.log

Binary file not shown.

View File

@ -556,6 +556,38 @@
"response": [],
"errors": []
},
{
"method": "order.getreviewOrderlist",
"description": "分页查询订单审核列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "pagination 参数"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "where 参数,支持 inspection_status/operator_name/operate_time_start/operate_time_end"
}
],
"response": [],
"errors": []
},
{
"method": "order.updateStatus",
"description": "更新订单状态",
@ -696,6 +728,286 @@
],
"response": [],
"errors": []
},
{
"method": "order.reviewOrder",
"description": "订单审核",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "delivery_order_code",
"type": "string",
"required": false,
"source": "body",
"description": "delivery_order_code 参数"
},
{
"name": "id",
"type": "number",
"required": false,
"source": "body",
"description": "id 参数"
},
{
"name": "inspection_status",
"type": "string",
"required": false,
"source": "body",
"description": "inspection_status 参数(兼容入参)"
},
{
"name": "review_status",
"type": "string",
"required": false,
"source": "body",
"description": "review_status 参数,默认 fin"
},
{
"name": "operator_name",
"type": "string",
"required": false,
"source": "body",
"description": "operator_name 参数"
},
{
"name": "operate_time",
"type": "string",
"required": false,
"source": "body",
"description": "operate_time 参数"
}
],
"response": [],
"errors": []
},
{
"method": "order.reviewOrder.getreviewOrderlist",
"description": "分页查询订单审核列表(目录化路由)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "pagination 参数"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "where 参数,支持 inspection_status/operator_name/operate_time_start/operate_time_end"
}
],
"response": [],
"errors": []
},
{
"method": "order.reviewOrder.reviewOrder",
"description": "订单审核(目录化路由)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "delivery_order_code",
"type": "string",
"required": false,
"source": "body",
"description": "delivery_order_code 参数"
},
{
"name": "id",
"type": "number",
"required": false,
"source": "body",
"description": "id 参数"
},
{
"name": "inspection_status",
"type": "string",
"required": false,
"source": "body",
"description": "inspection_status 参数(兼容入参)"
},
{
"name": "review_status",
"type": "string",
"required": false,
"source": "body",
"description": "review_status 参数,默认 fin"
},
{
"name": "operator_name",
"type": "string",
"required": false,
"source": "body",
"description": "operator_name 参数"
},
{
"name": "operate_time",
"type": "string",
"required": false,
"source": "body",
"description": "operate_time 参数"
}
],
"response": [],
"errors": []
},
{
"method": "order.deliveryOrder.getdeliveryOrderlist",
"description": "分页查询已进入出库流程的订单列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "pagination 参数"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "where 参数,默认 outbound_status != none"
}
],
"response": [],
"errors": []
},
{
"method": "order.pendingOrder.getpendingOrderlist",
"description": "分页查询待处理订单列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "pagination 参数"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "where 参数,默认 status in [pedding, created] 且 outbound_status = none"
}
],
"response": [],
"errors": []
},
{
"method": "order.expectionOrder.getexpectionOrderlist",
"description": "分页查询异常订单列表",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "pagination 参数"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "where 参数,默认筛选各流程 error 或拦截 exception"
}
],
"response": [],
"errors": []
},
{
"method": "order.archiveOrder.getarchiveOrderlist",
"description": "分页查询归档订单列表(暂使用当前订单表完成态数据)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "pagination",
"type": "object",
"required": false,
"source": "body",
"description": "pagination 参数"
},
{
"name": "where",
"type": "object",
"required": false,
"source": "body",
"description": "where 参数,默认 outbound_status = fin"
}
],
"response": [],
"errors": []
}
]
},
@ -1985,7 +2297,15 @@
"description": "Bearer token"
}
],
"params": [],
"params": [
{
"name": "code",
"type": "string",
"required": true,
"source": "body",
"description": "申请码(join_token)"
}
],
"response": [],
"errors": []
},
@ -2002,7 +2322,43 @@
"description": "Bearer token"
}
],
"params": [],
"params": [
{
"name": "audit_status",
"type": "string",
"required": true,
"source": "body",
"description": "审核状态(approved/rejected)"
},
{
"name": "code",
"type": "string",
"required": true,
"source": "body",
"description": "申请码(join_token)"
},
{
"name": "store_id",
"type": "number",
"required": true,
"source": "body",
"description": "当前审批门店ID"
},
{
"name": "role_ids",
"type": "array",
"required": true,
"source": "body",
"description": "分配角色ID数组"
},
{
"name": "reject_reason",
"type": "string",
"required": false,
"source": "body",
"description": "拒绝原因(audit_status=rejected 时可传)"
}
],
"response": [],
"errors": []
}
@ -2014,7 +2370,7 @@
"list": [
{
"method": "user.login",
"description": "用户登录",
"description": "用户登录(仅返回 token)",
"isNeedAuth": false,
"isNeedLogin": false,
"headers": [],
@ -2037,6 +2393,24 @@
"response": [],
"errors": []
},
{
"method": "user.loginByCode",
"description": "登录码登录(使用 ye4s_user.tmp_code)",
"isNeedAuth": false,
"isNeedLogin": false,
"headers": [],
"params": [
{
"name": "code",
"type": "string",
"required": true,
"source": "body",
"description": "登录码,对应 ye4s_user.tmp_code"
}
],
"response": [],
"errors": []
},
{
"method": "user.logout",
"description": "用户登出",

View File

@ -0,0 +1,76 @@
# migration_execution_plan
更新时间: 2026-03-22
## 1. 执行原则
- 先解决 SequelizeMeta 漂移,再补新增 migration。
- 先补静态基表,再补关联表,再补日志/配置/打印等扩展表。
- 动态分表与视图单独治理,不混入普通 createTable 批次。
- 所有 migration 需保证幂等,避免现有环境重复执行报错。
## 2. 推荐顺序
### 步骤 1: 漂移核对
- 核对以下 4 个未进入 SequelizeMeta 的 migration 与当前数据库实际结构是否一致:
- 20251111083733-create-wms-stock-store.js
- 20251112085825-create-wms-entry-order.js
- 20251112085844-create-wms-entry-items.js
- 20260322061000-add-delivery-time-to-order-delivery-tables.js
- 若结构已存在且一致,优先制定“补登记基线方案”而不是直接重跑。
### 步骤 2: 补齐有 model 的静态表 migration
优先级建议:
1. 权限与组织类
2. 库位与库存类
3. 打印类
4. 日志与国际化类
### 步骤 3: 补齐无 model 但业务依赖的表 migration
优先补以下类型:
- system_log / api_log
- print_log / print_batch / printer_config
- platform_print_config
- wave_batch / wave_operation_log
- order_operation_log
### 步骤 4: 动态分表治理
- 为 order_delivery/order_items 动态分表建立统一 migration 策略。
- 后续迁移以“母表 + 动态建表 SQL 模板/工厂策略同步”为主,不逐仓库表固化。
### 步骤 5: 视图治理
- 为以下视图补充 create/drop migration:
- v_pick_space
- vw_warehouse_quota
## 3. 建议批次
- 批次 A: 漂移核对与基线修正
- 批次 B: 静态核心表 migration 补齐
- 批次 C: 日志/配置/打印扩展表 migration 补齐
- 批次 D: 动态分表与视图治理
## 4. local/test 演练方案
### local
- 先在本地库回放已有 migration。
- 再逐批执行新增 migration。
- 每批完成后执行 schema 对比与关键 API 冒烟。
### test
- 按 local 已验证通过的批次顺序执行。
- 保留每批执行前后的表结构快照。
- 若发现 drift 或兼容问题,先暂停后续批次。
## 5. 阶段 2 目标
- 明确每类表的 migration 补齐范围。
- 明确执行顺序和批次边界。
- 为后续正式补 migration 提供可直接执行的方案基础。

107
migration_gap_list.md Normal file
View File

@ -0,0 +1,107 @@
# migration_gap_list
更新时间: 2026-03-22
## 1. 现状摘要
- migration 文件数: 11
- SequelizeMeta 已执行数: 7
- 仓库文件与执行记录差值: 4
- createTable 覆盖表数: 10
- DB 物理表数: 68
- 视图数: 2
## 2. 命名与顺序审计
- 现有 migration 文件命名整体符合“时间戳-动作-对象.js”规范。
- 当前 migration 主要集中在 2025-11 和 2026-03 两个时间段。
- 当前主要问题不是命名,而是覆盖率不足和执行状态漂移。
## 3. 执行状态漂移
以下 migration 文件存在于仓库,但未记录在 SequelizeMeta:
- 20251111083733-create-wms-stock-store.js
- 20251112085825-create-wms-entry-order.js
- 20251112085844-create-wms-entry-items.js
- 20260322061000-add-delivery-time-to-order-delivery-tables.js
说明:
- 当前数据库中相关表或字段已存在,说明存在“结构已生效但 migration 未登记”或“迁移在其他环境/手工执行过”的漂移风险。
- 后续处理时不能直接盲跑这些 migration,必须先做结构一致性核对。
## 4. 有 model 但缺 create migration 的表
- wms_account_platform_active (app/model/account_platform_active.js)
- wms_account_store_employee (app/model/account_store_employee.js)
- wms_employee_role (app/model/employee_role.js)
- wms_fast_where (app/model/fast_where.js)
- wms_file (app/model/file.js)
- wms_file_reference (app/model/file_reference.js)
- wms_i18n_keys (app/model/i18n_key.js)
- wms_i18n_translations (app/model/i18n_translation.js)
- wms_location_space (app/model/location_space.js)
- wms_location_type (app/model/location_type.js)
- wms_location_zone (app/model/location_zone.js)
- wms_operation_log (app/model/operation_log.js)
- wms_order_delivery (app/model/order_delivery.js)
- wms_order_items (app/model/order_items.js)
- wms_permission (app/model/permission.js)
- wms_platform (app/model/platform.js)
- wms_platfrom_setting (app/model/platform_setting.js)
- wms_print_computer (app/model/print_computer.js)
- wms_print_items (app/model/print_item.js)
- wms_print_record (app/model/print_record.js)
- wms_print_station_express (app/model/print_station_express.js)
- wms_print_stations (app/model/print_stations.js)
- wms_print_template (app/model/print_template.js)
- wms_prohibited_type (app/model/prohibited_type.js)
- wms_qimen_log (app/model/qimen_log.js)
- wms_receiving (app/model/receiving.js)
- wms_receiving_detail (app/model/receiving_detail.js)
- wms_role (app/model/role.js)
- wms_role_permission (app/model/role_permission.js)
- wms_stock_barcodes (app/model/stock_barcode.js)
- wms_stock_unit (app/model/stock_unit.js)
- wms_stock_warehouse (app/model/stock_warehouse.js)
- wms_storage (app/model/storage.js)
- wms_store_join (app/model/store_join.js)
## 5. 无 model 且无 create migration 的 DB 表
- SequelizeMeta
- wms_api_log
- wms_embargo_policies
- wms_express
- wms_express_print_record
- wms_express_setting
- wms_order_delivery_100000
- wms_order_delivery_1000028
- wms_order_express
- wms_order_express_print_data
- wms_order_items_100000
- wms_order_items_1000028
- wms_order_operation
- wms_order_operation_log
- wms_order_picking
- wms_picking_strategy
- wms_platform_print_config
- wms_print_batch
- wms_print_log
- wms_printer_config
- wms_system_config
- wms_system_log
- wms_wave_batch
- wms_wave_operation_log
## 6. 特殊对象说明
- 动态分表:
- wms_order_delivery_*
- wms_order_items_*
这类表不建议逐张固化 create migration,应通过“母表迁移 + 动态建表策略”统一治理。
- 视图:
- vw_warehouse_quota
- v_pick_space
需要单独使用 view migration 管理。
- SequelizeMeta 属于迁移元数据表,不纳入业务模型补齐范围。

105
modelList.md Normal file
View File

@ -0,0 +1,105 @@
# modelList
更新时间: 2026-03-22
扫描范围: app/model/*.js
模型文件数: 45
## 1. 目标
- 用于快速查看模型层级结构。
- 用于后续 model 命名规范、关联规范、迁移补全的基线输入。
## 2. 模型层级结构
```text
app/model/
├─ 账号与权限
│ ├─ account.js
│ ├─ account_platform_active.js
│ ├─ account_store_employee.js
│ ├─ employee_role.js
│ ├─ permission.js
│ ├─ role.js
│ └─ role_permission.js
├─ 组织与仓库
│ ├─ store.js
│ ├─ store_join.js
│ ├─ store_warehouse.js
│ ├─ storage.js
│ ├─ receiving.js
│ ├─ receiving_detail.js
│ ├─ entry_order.js
│ └─ entry_items.js
├─ 库位与查询
│ ├─ location_type.js
│ ├─ location_zone.js
│ ├─ location_space.js
│ └─ fast_where.js
├─ 库存与商品
│ ├─ stock_store.js
│ ├─ stock_warehouse.js
│ ├─ stock_unit.js
│ ├─ stock_barcode.js
│ └─ prohibited_type.js
├─ 订单与履约
│ ├─ order_delivery.js
│ ├─ order_items.js
│ ├─ order_delivery_factory.js
│ └─ order_items_factory.js
├─ 打印能力
│ ├─ print_template.js
│ ├─ print_item.js
│ ├─ print_record.js
│ ├─ print_stations.js
│ ├─ print_station_express.js
│ └─ print_computer.js
├─ 开放平台与接口
│ ├─ api_app.js
│ ├─ qimen_app.js
│ ├─ qimen_log.js
│ ├─ platform.js
│ ├─ platform_setting.js
│ └─ interface_type.js
└─ 文件、日志与国际化
├─ file.js
├─ file_reference.js
├─ operation_log.js
├─ i18n_key.js
└─ i18n_translation.js
```
## 3. 关键说明
### 3.1 动态分表模型
- order_delivery_factory.js
- 负责按 warehouse 维度动态创建/获取发货单模型。
- order_items_factory.js
- 负责按 warehouse 维度动态创建/获取订单商品模型。
说明:
- 这两个文件不是普通静态 Sequelize 定义文件,而是动态模型工厂能力。
### 3.2 典型关联模型
- fast_where.js
- 自关联: parent/children。
- location_zone.js
- 自关联 + 与 Store、LocationSpace 的关联。
- i18n_translation.js
- 关联 i18n_key。
- prohibited_type.js
- 关联 Store、StockWarehouse。
- stock_barcode.js
- 关联 StockWarehouse。
### 3.3 命名现状观察
- define 名称存在 snake_case 与 PascalCase 混用。
- 部分模型文件命名与 define 名称不完全一致。
- 后续需结合 model_naming_standard 做统一收敛。
## 4. 后续维护规则
- 每次新增/删除/重命名 model 文件后,需同步更新本文件。
- 每次新增/调整关联后,需同步更新本文件的关键说明章节。

View File

@ -0,0 +1,52 @@
# model_association_inventory
Updated: 2026-03-22
Source: app/model/*.js
| key | file | associations |
| --- | --- | --- |
| account_platform_active | app/model/account_platform_active.js | - |
| account_store_employee | app/model/account_store_employee.js | - |
| account | app/model/account.js | - |
| api_app | app/model/api_app.js | - |
| employee_role | app/model/employee_role.js | - |
| entry_items | app/model/entry_items.js | - |
| entry_order | app/model/entry_order.js | - |
| fast_where | app/model/fast_where.js | belongsTo->FastWhere, hasMany->FastWhere |
| file_reference | app/model/file_reference.js | - |
| file | app/model/file.js | - |
| i18n_key | app/model/i18n_key.js | - |
| i18n_translation | app/model/i18n_translation.js | belongsTo->I18nKey |
| interface_type | app/model/interface_type.js | - |
| location_space | app/model/location_space.js | - |
| location_type | app/model/location_type.js | belongsTo->Store |
| location_zone | app/model/location_zone.js | belongsTo->LocationZone, hasMany->LocationZone, belongsTo->Store, hasMany->LocationSpace |
| operation_log | app/model/operation_log.js | - |
| order_delivery_factory | app/model/order_delivery_factory.js | - |
| order_delivery | app/model/order_delivery.js | - |
| order_items_factory | app/model/order_items_factory.js | - |
| order_items | app/model/order_items.js | - |
| permission | app/model/permission.js | - |
| platform_setting | app/model/platform_setting.js | - |
| platform | app/model/platform.js | - |
| print_computer | app/model/print_computer.js | - |
| print_item | app/model/print_item.js | - |
| print_record | app/model/print_record.js | - |
| print_station_express | app/model/print_station_express.js | - |
| print_stations | app/model/print_stations.js | - |
| print_template | app/model/print_template.js | - |
| prohibited_type | app/model/prohibited_type.js | belongsTo->Store, hasMany->StockWarehouse |
| qimen_app | app/model/qimen_app.js | - |
| qimen_log | app/model/qimen_log.js | - |
| receiving_detail | app/model/receiving_detail.js | - |
| receiving | app/model/receiving.js | - |
| role_permission | app/model/role_permission.js | - |
| role | app/model/role.js | - |
| stock_barcode | app/model/stock_barcode.js | belongsTo->StockWarehouse |
| stock_store | app/model/stock_store.js | - |
| stock_unit | app/model/stock_unit.js | - |
| stock_warehouse | app/model/stock_warehouse.js | - |
| storage | app/model/storage.js | - |
| store_join | app/model/store_join.js | - |
| store_warehouse | app/model/store_warehouse.js | - |
| store | app/model/store.js | - |

213
model_cleanup_list.md Normal file
View File

@ -0,0 +1,213 @@
# model_cleanup_list
更新时间: 2026-03-23
阶段: 5.1 识别应迁移到 service 层的方法能力(第一批)
## 1. 盘点结论
- 扫描范围: app/model/**/*.js
- 检出方法总数: 102(实例 + 静态)
- 高优先候选(应迁移到 service): 24
- 低风险可移除候选(当前未发现业务调用): 18
- 保留在模型层(轻量领域判断/展示映射): 22
说明:
- 本次调用扫描采用“静态方法名精确匹配”策略(Model.method(...))。
- 对“应迁移”项,目标是把跨表编排、状态机、批量事务、库存分配等逻辑从 model 剥离到 systems service。
## 2. 第一批应迁移(P1)
### 2.1 入库单聚合与状态流转
- 文件: app/model/entry_order.js
- 候选方法:
- findByOrderCode
- findByStatus
- getStatsByWarehouse
- updateSyncStatus
- updateOrderStatus
- calculateReceivedQuantities
- 迁移目标:
- app/service/systems/entry_order.js
- 原因:
- 含分页查询、跨表 include、状态流转约束、聚合统计,属于业务编排而非数据映射。
### 2.2 入库明细批量更新与进度汇总
- 文件: app/model/entry_items.js
- 候选方法:
- batchUpdateReceived
- getOrderProgress
- 迁移目标:
- app/service/systems/entry_order.js(或 app/service/systems/storage/receiving.js)
- 原因:
- 含事务控制、批量更新和跨记录校验,属于服务层职责。
### 2.3 库存分配/锁定编排
- 文件: app/model/storage.js
- 候选方法:
- updateQuantity
- lockQuantity
- unlockQuantity
- allocateQuantity
- getStockSummary
- getSpaceUsage
- findByStockAndBatch
- findBySpace
- findAvailableByWarehouse
- findExpiringSoon
- 迁移目标:
- app/service/systems/stock_store.js
- app/service/systems/storage/receiving.js
- 原因:
- 涉及库存扣减/锁定语义、聚合统计和业务筛选,属于库存域服务。
### 2.4 角色权限写入与查询编排
- 文件: app/model/role.js
- 候选方法:
- assignPermissions
- getPermissionTree
- getPermissionIds
- 文件: app/model/role_permission.js
- 候选方法:
- bulkAssign
- clearRolePermissions
- getRolePermissions
- hasPermission
- 迁移目标:
- app/service/systems/auth/user.js
- 新增 app/service/systems/auth/role_permission.js(推荐)
- 原因:
- 包含权限关系写操作、树构建和权限判定,应集中在鉴权服务边界。
### 2.5 商家数据校验与查询助手
- 文件: app/model/store.js
- 候选方法:
- validateStoreData
- checkCompanyNameExists
- findByAccountId
- findAllEnabled
- findAllWarehouses
- 迁移目标:
- app/service/systems/store.js
- 原因:
- 请求参数校验和查询策略属于服务层,不应下沉到 model。
## 3. 可移除候选(P2,先验证后删)
- 已执行(第一批):
- app/model/api_app.js: `findByAppKey`、`findByQimenConfig`(已删除)
- app/model/interface_type.js: `findByCode`、`findEnabled`(已删除)
- app/model/print_item.js: `getGroupFields`、`getTableConfigs`(已删除)
- 门禁结果: compare mismatch=0,generated regression + smoke=14 passing
- 已执行(第二批):
- app/model/i18n_translation.js: `getTranslation`、`batchGetTranslations`、`getProjectTranslations`、`upsertTranslation`、`getUntranslated`(已删除)
- app/model/stock_store.js: `findByItemCode`、`findByStore`(已删除)
- 门禁结果: compare mismatch=0,generated regression=8 passing,smoke=6 passing(合计 14 passing)
- app/model/i18n_translation.js:
- getTranslation
- batchGetTranslations
- getProjectTranslations
- upsertTranslation
- getUntranslated
- app/model/interface_type.js:
- findByCode
- findEnabled
- app/model/print_item.js:
- getGroupFields
- getTableConfigs
- app/model/api_app.js:
- findByAppKey
- findByQimenConfig
- app/model/stock_store.js:
- findByItemCode
- findByStore
说明:
- 上述方法本轮未检出业务层调用,建议先完成一次“删除前引用复核”再执行清理。
### 3.1 删除前引用复核(第二批)
- 复核时间: 2026-03-23
- 复核范围:
- app/model/i18n_translation.js
- app/model/stock_store.js
- app/service/**/*.js
- app/controller/**/*.js
- test/**/*.js
- script/**/*.js
- 复核方式:
- 方法名精确检索: getTranslation / batchGetTranslations / getProjectTranslations / upsertTranslation / getUntranslated / findByItemCode / findByStore
- 模型调用链检索: I18nTranslation.<method>、ctx.model.I18nTranslation.<method>、StockStore.<method>、ctx.model.StockStore.<method>
- 动态调用兜底检索: ['methodName'] 形式
- 复核结论:
- 未检出 I18nTranslation 5 个候选静态方法的业务调用。
- 未检出 StockStore 2 个候选静态方法的业务调用。
- 检出 I18n 相关业务仍直接使用了模型基础能力(findAll/findOne/create/count),不受本次候选方法删除影响。
- 可执行动作:
- 已执行清理并通过门禁,第二批可删除候选已关闭。
## 4. 保留在模型层(P3)
建议保留:
- 轻量实例判断(isEnabled/isHidden/isExpired 等)。
- 纯格式/展示映射(getTypeName/getRoleTypeName/getScopeName)。
- 与关联语义绑定的 include 构造器(StoreWarehouse.buildStoreStockInclude)。
## 5. 下一步(5.2 输入)
1. 已完成 P1 第一组迁移:EntryOrder / EntryItems 的 8 个静态方法已迁移到 app/service/systems/entry_order.js,并从 model 删除。
2. 已完成 P1 第二组迁移:Storage 的 10 个静态方法已迁移到 app/service/systems/storage/index.js,并从 model 删除。
3. 下一步继续迁移 P1 剩余项:RolePermission / Store。
4. 最后补 model_boundary_rules.md,固化模型层边界。
## 6. 已执行(P1 第一组)
- 执行时间: 2026-03-23
- 迁移范围:
- app/model/entry_order.js
- app/model/entry_items.js
- app/service/systems/entry_order.js
- 迁移方法:
- EntryOrder.findByOrderCode
- EntryOrder.findByStatus
- EntryOrder.getStatsByWarehouse
- EntryOrder.updateSyncStatus
- EntryOrder.updateOrderStatus
- EntryOrder.calculateReceivedQuantities
- EntryItems.batchUpdateReceived
- EntryItems.getOrderProgress
- 说明:
- 对外 system/qimen method 未新增接口,属于内部职责收敛。
- `calculateReceivedQuantities` 在 service 中改为显式查询 Storage 聚合,避免原 model 版本的相关子查询别名漂移风险。
- 门禁结果:
- compare mismatch=0
- generated regression=8 passing
- smoke=6 passing
- tests=14 passing
## 7. 已执行(P1 第二组)
- 执行时间: 2026-03-23
- 迁移范围:
- app/model/storage.js
- app/service/systems/storage/index.js
- 迁移方法:
- Storage.findByStockAndBatch
- Storage.findBySpace
- Storage.findAvailableByWarehouse
- Storage.findExpiringSoon
- Storage.updateQuantity
- Storage.lockQuantity
- Storage.unlockQuantity
- Storage.allocateQuantity
- Storage.getStockSummary
- Storage.getSpaceUsage
- 说明:
- 对外 system/qimen method 未新增接口,属于内部职责收敛。
- 更新类方法统一进入 service,模型层仅保留实例行为与关联映射。

53
model_inventory.md Normal file
View File

@ -0,0 +1,53 @@
# model_inventory
Updated: 2026-03-22
Source: app/model/*.js
Count: 45
| key | file | defineName | tableName | kind |
| --- | --- | --- | --- | --- |
| account_platform_active | app/model/account_platform_active.js | account_platform_active | wms_account_platform_active | Model |
| account_store_employee | app/model/account_store_employee.js | wms_account_store_employee | wms_account_store_employee | Model |
| account | app/model/account.js | account | wms_account | Model |
| api_app | app/model/api_app.js | api_app | wms_api_app | Model |
| employee_role | app/model/employee_role.js | employee_role | wms_employee_role | Model |
| entry_items | app/model/entry_items.js | wms_entry_items | wms_entry_items | Model |
| entry_order | app/model/entry_order.js | wms_entry_order | wms_entry_order | Model |
| fast_where | app/model/fast_where.js | fast_where | wms_fast_where | Model |
| file_reference | app/model/file_reference.js | wms_file_reference | wms_file_reference | Model |
| file | app/model/file.js | wms_file | wms_file | Model |
| i18n_key | app/model/i18n_key.js | wms_i18n_key | wms_i18n_keys | Model |
| i18n_translation | app/model/i18n_translation.js | wms_i18n_translation | wms_i18n_translations | Model |
| interface_type | app/model/interface_type.js | interface_type | wms_interface_type | Model |
| location_space | app/model/location_space.js | wms_location_space | wms_location_space | Model |
| location_type | app/model/location_type.js | location_type | wms_location_type | Model |
| location_zone | app/model/location_zone.js | wms_location_zone | wms_location_zone | Model |
| operation_log | app/model/operation_log.js | operation_log | wms_operation_log | Model |
| order_delivery_factory | app/model/order_delivery_factory.js | - | - | Factory |
| order_delivery | app/model/order_delivery.js | order_delivery | wms_order_delivery | Model |
| order_items_factory | app/model/order_items_factory.js | - | - | Factory |
| order_items | app/model/order_items.js | wms_order_items | wms_order_items | Model |
| permission | app/model/permission.js | permission | wms_permission | Model |
| platform_setting | app/model/platform_setting.js | platform_setting | wms_platfrom_setting | Model |
| platform | app/model/platform.js | platform | wms_platform | Model |
| print_computer | app/model/print_computer.js | print_computer | wms_print_computer | Model |
| print_item | app/model/print_item.js | print_item | wms_print_items | Model |
| print_record | app/model/print_record.js | PrintRecord | wms_print_record | Model |
| print_station_express | app/model/print_station_express.js | print_station_express | wms_print_station_express | Model |
| print_stations | app/model/print_stations.js | print_stations | wms_print_stations | Model |
| print_template | app/model/print_template.js | print_template | wms_print_template | Model |
| prohibited_type | app/model/prohibited_type.js | prohibitedType | wms_prohibited_type | Model |
| qimen_app | app/model/qimen_app.js | qimen_app | wms_qimen_apps | Model |
| qimen_log | app/model/qimen_log.js | qimen_log | wms_qimen_log | Model |
| receiving_detail | app/model/receiving_detail.js | wms_receiving_detail | wms_receiving_detail | Model |
| receiving | app/model/receiving.js | wms_receiving | wms_receiving | Model |
| role_permission | app/model/role_permission.js | role_permission | wms_role_permission | Model |
| role | app/model/role.js | role | wms_role | Model |
| stock_barcode | app/model/stock_barcode.js | stock_barcodes | wms_stock_barcodes | Model |
| stock_store | app/model/stock_store.js | stock_store | wms_stock_store | Model |
| stock_unit | app/model/stock_unit.js | wms_stock_unit | wms_stock_unit | Model |
| stock_warehouse | app/model/stock_warehouse.js | stock_warehouse | wms_stock_warehouse | Model |
| storage | app/model/storage.js | wms_storage | wms_storage | Model |
| store_join | app/model/store_join.js | StoreJoin | wms_store_join | Model |
| store_warehouse | app/model/store_warehouse.js | store_warehouse | wms_store_warehouse | Model |
| store | app/model/store.js | store | wms_store | Model |

184
model_naming_standard.md Normal file
View File

@ -0,0 +1,184 @@
# Model 命名规范
更新时间: 2026-03-22
适用范围: app/model、app/service、app/controller 中的 app.model / ctx.model 调用
## 1. 目标
- 统一 model 文件名、运行时 key、defineName、tableName、关联 alias 的命名规则。
- 将“可直接收敛的风格问题”和“会影响业务语义的结构问题”拆开处理。
- 为阶段 4 的关联规范化和阶段 5 的模型能力清理提供稳定基线。
## 2. 五层命名对象
当前仓库里,单个模型至少同时存在以下 5 个命名层:
1. 文件名: app/model 下的文件名。
2. 运行时 key: 代码里通过 app.model.Xxx / ctx.model.Xxx 使用的名称。
3. defineName: Sequelize 的 app.model.define(name, attributes, options) 第一个参数。
4. tableName: options.tableName,对应数据库真实对象名。
5. alias: 关联查询里的 as 字段。
后续规范要求这 5 层职责分离,不再互相混用。
## 3. 统一规则
### 3.1 文件名
- 一律使用 snake_case。
- 文件名表达“模型职责”,不表达数据库前缀。
- 工厂模型必须以 _factory 结尾。
- 除非是稳定历史兼容项,否则不在文件名中保留 wms 前缀。
示例:
- account_store_employee.js
- platform_setting.js
- order_delivery_factory.js
### 3.2 运行时 key
- 一律使用 PascalCase。
- 运行时 key 由文件名去掉扩展名后转为 PascalCase。
- 这是 service/controller/model 之间的主兼容面,优先级高于 defineName。
- 工厂模型保留 Factory 后缀。
示例:
- account_store_employee.js -> AccountStoreEmployee
- platform_setting.js -> PlatformSetting
- order_delivery_factory.js -> OrderDeliveryFactory
### 3.3 defineName
- 静态模型的 defineName 必须与运行时 key 保持一致。
- 不再使用 snake_case、wms_ 前缀或局部 lowerCamelCase 作为 defineName。
- 动态分表模型允许在运行时使用真实 tableName 作为 defineName,但外部只允许通过工厂 key 获取,不直接在业务层引用动态 defineName。
示例:
- PlatformSetting: 正确
- platform_setting: 不再推荐
- prohibitedType: 不再推荐
- wms_account_store_employee: 不再推荐
### 3.4 tableName
- tableName 只负责映射数据库真实对象。
- 一律保持数据库现状,不因 model 命名规范化而强制修改表名。
- 物理表继续保留现有 wms_ 前缀、复数形式、历史拼写问题。
- 视图、动态分表、历史表单独记录,不纳入静态命名统一的修改范围。
示例:
- PlatformSetting -> tableName: wms_platfrom_setting
- StockBarcode -> tableName: wms_stock_barcodes
- PrintStations -> tableName: wms_print_stations
说明:
- tableName 中的历史拼写错误属于数据库治理问题,不属于本阶段命名规范化问题。
### 3.5 alias
- belongsTo / hasOne 使用 lowerCamelCase 单数。
- hasMany / belongsToMany 使用 lowerCamelCase 复数。
- alias 反映关联语义,不复用旧表名或旧模型名。
- alias 必须与真实关系一致,不能把 employee 关系继续命名为 role。
示例:
- belongsTo(Store, { as: 'store' })
- hasMany(EmployeeRole, { as: 'employeeRoles' })
- belongsTo(AccountStoreEmployee, { as: 'accountStoreEmployee' })
## 4. 兼容优先级
按风险从高到低分三类处理:
### A 类: 运行时 key 不存在或调用错误
- 必须先修。
- 这类问题会直接导致运行时取不到模型,或拿到错误关联。
- 典型例子:
- AccountStoreRole
- WmsOrderDeliveryFactory
- WmsOrderItemsFactory
### B 类: defineName 不规范但运行时可用
- 可分批修。
- 前提是 tableName 已显式声明,且不存在依赖 defineName 字符串的外部逻辑。
- 典型例子:
- platform_setting
- qimen_app
- qimen_log
- prohibitedType
- stock_barcodes
### C 类: alias 与业务语义不一致
- 必须与阶段 4 一起处理。
- 不能只改 alias 文本,需要一起核对外键、include、返回结构。
- 典型例子:
- accountStoreRoles
- accountStoreRole
- employeeRole
## 5. 仓库内落地规则
### 5.1 本项目允许保留的历史兼容项
以下项目前阶段不因“风格统一”而强制改文件名:
- print_stations.js
- 原因: 运行时大量使用 PrintStations,且 tableName 为 wms_print_stations。
- store_join.js
- 原因: 运行时与 defineName 已一致,当前主要问题不在命名层。
- order_delivery_factory.js / order_items_factory.js
- 原因: 工厂职责明确,外部兼容面稳定。
### 5.2 本项目必须执行的统一动作
- 所有静态模型的 defineName 逐步收敛到 PascalCase 运行时 key。
- 所有业务代码统一通过 ctx.model.Xxx / app.model.Xxx 的 PascalCase key 调用。
- 任何 include/as 字段都必须与当前模型关联定义一致。
- 不再新增任何带 wms 前缀的 defineName。
- 不再新增任何与真实语义不一致的 alias。
## 6. 参考示例
### 6.1 标准静态模型
- 文件名: platform_setting.js
- 运行时 key: PlatformSetting
- defineName: PlatformSetting
- tableName: wms_platfrom_setting
### 6.2 标准关联模型
- 文件名: account_store_employee.js
- 运行时 key: AccountStoreEmployee
- defineName: AccountStoreEmployee
- tableName: wms_account_store_employee
- alias:
- belongsTo(Account, { as: 'account' })
- belongsTo(Store, { as: 'store' })
- hasMany(EmployeeRole, { as: 'employeeRoles' })
### 6.3 标准工厂模型
- 文件名: order_delivery_factory.js
- 运行时 key: OrderDeliveryFactory
- 对外入口:
- ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId)
- ctx.model.OrderDeliveryFactory.getHistoryModel(warehouseId)
- 约束:
- 业务代码不直接引用动态表 defineName。
## 7. 执行边界
- 本阶段先统一标准、映射和影响面,不直接大规模改名。
- 运行时 key 修复优先于 defineName 收敛。
- alias 修复必须与关联关系校验一起推进。
- 数据库表名不在本阶段统一修改范围内。

100
model_rename_map.md Normal file
View File

@ -0,0 +1,100 @@
# Model 重命名映射表
更新时间: 2026-03-22
来源:
- model_inventory.md
- app/model/*.js
- app/service/**/*.js
- app/controller/**/*.js
## 1. 使用说明
- 本表只记录阶段 3 已确认的命名规范化项。
- 变更级别分为 4 类:
- P0-调用修复: 现有代码引用错误或运行时 key 不存在,必须先修。
- P1-defineName 收敛: 只调整 defineName,不动文件名和 tableName。
- P2-alias 收敛: 需要和关联定义一起调整。
- 保持不动: 暂不建议改动。
## 2. P0: 必须先修的运行时调用
| 当前调用/命名 | 建议标准名 | 变更级别 | 原因 | 备注 |
| --- | --- | --- | --- | --- |
| WmsOrderDeliveryFactory | OrderDeliveryFactory | P0-调用修复 | 仓库内主流调用均为 OrderDeliveryFactory,当前写法与文件名不匹配 | 先修 app/service/apiMethods/test.js |
| WmsOrderItemsFactory | OrderItemsFactory | P0-调用修复 | 仓库内主流调用均为 OrderItemsFactory,当前写法与文件名不匹配 | 先修 app/service/apiMethods/test.js |
| AccountStoreRole | AccountStoreEmployee 或补回独立模型 | P0-调用修复 | 仓库内无 account_store_role.js,且当前表结构已落到 account_store_employee + employee_role | 需要先确认目标数据关系 |
| accountStoreRole | accountStoreEmployee | P0-调用修复 | AccountPlatformActive 当前关联 alias 为 accountStoreEmployee,service 仍按 accountStoreRole 取值 | 要与 include 返回结构一起改 |
## 3. P1: defineName 收敛为运行时 key
以下项优先采用“只改 defineName,不改文件名、不改 tableName”的方式收敛。
| 文件 | 当前运行时 key | 当前 defineName | 建议 defineName | 变更级别 |
| --- | --- | --- | --- | --- |
| app/model/account_platform_active.js | AccountPlatformActive | account_platform_active | AccountPlatformActive | P1-defineName 收敛 |
| app/model/account_store_employee.js | AccountStoreEmployee | wms_account_store_employee | AccountStoreEmployee | P1-defineName 收敛 |
| app/model/account.js | Account | account | Account | P1-defineName 收敛 |
| app/model/api_app.js | ApiApp | api_app | ApiApp | P1-defineName 收敛 |
| app/model/employee_role.js | EmployeeRole | employee_role | EmployeeRole | P1-defineName 收敛 |
| app/model/entry_items.js | EntryItems | wms_entry_items | EntryItems | P1-defineName 收敛 |
| app/model/entry_order.js | EntryOrder | wms_entry_order | EntryOrder | P1-defineName 收敛 |
| app/model/fast_where.js | FastWhere | fast_where | FastWhere | P1-defineName 收敛 |
| app/model/file_reference.js | FileReference | wms_file_reference | FileReference | P1-defineName 收敛 |
| app/model/file.js | File | wms_file | File | P1-defineName 收敛 |
| app/model/i18n_key.js | I18nKey | wms_i18n_key | I18nKey | P1-defineName 收敛 |
| app/model/i18n_translation.js | I18nTranslation | wms_i18n_translation | I18nTranslation | P1-defineName 收敛 |
| app/model/interface_type.js | InterfaceType | interface_type | InterfaceType | P1-defineName 收敛 |
| app/model/location_space.js | LocationSpace | wms_location_space | LocationSpace | P1-defineName 收敛 |
| app/model/location_type.js | LocationType | location_type | LocationType | P1-defineName 收敛 |
| app/model/location_zone.js | LocationZone | wms_location_zone | LocationZone | P1-defineName 收敛 |
| app/model/operation_log.js | OperationLog | operation_log | OperationLog | P1-defineName 收敛 |
| app/model/order_delivery.js | OrderDelivery | order_delivery | OrderDelivery | P1-defineName 收敛 |
| app/model/order_items.js | OrderItems | wms_order_items | OrderItems | P1-defineName 收敛 |
| app/model/permission.js | Permission | permission | Permission | P1-defineName 收敛 |
| app/model/platform_setting.js | PlatformSetting | platform_setting | PlatformSetting | P1-defineName 收敛 |
| app/model/platform.js | Platform | platform | Platform | P1-defineName 收敛 |
| app/model/print_computer.js | PrintComputer | print_computer | PrintComputer | P1-defineName 收敛 |
| app/model/print_item.js | PrintItem | print_item | PrintItem | P1-defineName 收敛 |
| app/model/print_station_express.js | PrintStationExpress | print_station_express | PrintStationExpress | P1-defineName 收敛 |
| app/model/print_stations.js | PrintStations | print_stations | PrintStations | P1-defineName 收敛 |
| app/model/print_template.js | PrintTemplate | print_template | PrintTemplate | P1-defineName 收敛 |
| app/model/prohibited_type.js | ProhibitedType | prohibitedType | ProhibitedType | P1-defineName 收敛 |
| app/model/qimen_app.js | QimenApp | qimen_app | QimenApp | P1-defineName 收敛 |
| app/model/qimen_log.js | QimenLog | qimen_log | QimenLog | P1-defineName 收敛 |
| app/model/receiving_detail.js | ReceivingDetail | wms_receiving_detail | ReceivingDetail | P1-defineName 收敛 |
| app/model/receiving.js | Receiving | wms_receiving | Receiving | P1-defineName 收敛 |
| app/model/role_permission.js | RolePermission | role_permission | RolePermission | P1-defineName 收敛 |
| app/model/role.js | Role | role | Role | P1-defineName 收敛 |
| app/model/stock_barcode.js | StockBarcode | stock_barcodes | StockBarcode | P1-defineName 收敛 |
| app/model/stock_store.js | StockStore | stock_store | StockStore | P1-defineName 收敛 |
| app/model/stock_unit.js | StockUnit | wms_stock_unit | StockUnit | P1-defineName 收敛 |
| app/model/stock_warehouse.js | StockWarehouse | stock_warehouse | StockWarehouse | P1-defineName 收敛 |
| app/model/storage.js | Storage | wms_storage | Storage | P1-defineName 收敛 |
| app/model/store_warehouse.js | StoreWarehouse | store_warehouse | StoreWarehouse | P1-defineName 收敛 |
| app/model/store.js | Store | store | Store | P1-defineName 收敛 |
## 4. 保持不动或低优先级处理项
| 文件 | 当前运行时 key | 当前 defineName | 建议 | 说明 |
| --- | --- | --- | --- | --- |
| app/model/order_delivery_factory.js | OrderDeliveryFactory | 动态 tableName | 保持不动 | 工厂模型,不参与静态 defineName 收敛 |
| app/model/order_items_factory.js | OrderItemsFactory | 动态 tableName | 保持不动 | 工厂模型,不参与静态 defineName 收敛 |
| app/model/print_record.js | PrintRecord | PrintRecord | 保持不动 | 已符合标准 |
| app/model/store_join.js | StoreJoin | StoreJoin | 保持不动 | 已符合标准 |
## 5. P2: alias 收敛候选
| 位置 | 当前 alias | 建议 alias | 变更级别 | 说明 |
| --- | --- | --- | --- | --- |
| app/model/account.js | accountStoreRoles | accountStoreEmployees | P2-alias 收敛 | 当前关联对象实际为 AccountStoreEmployee |
| app/model/account_platform_active.js | accountStoreEmployee | accountStoreEmployee | 保持 | 当前 alias 合理,问题在 service 调用侧 |
| app/model/account_store_employee.js | employeeRole | employeeRoles | P2-alias 收敛 | hasMany 建议使用复数 |
| app/model/store.js | accountStoreEmployee | accountStoreEmployees | P2-alias 收敛 | hasMany 建议使用复数 |
| app/model/role.js | employeeRole | employeeRoles | P2-alias 收敛 | hasMany 建议使用复数 |
## 6. 执行顺序建议
1. 先修 P0 调用错误,保证所有 ctx.model / app.model 均能拿到正确对象。
2. 再做 P1 defineName 收敛,限定在显式声明了 tableName 的静态模型。
3. 最后做 P2 alias 收敛,并与阶段 4 的关联核对同步执行。

130
model_todo.txt Normal file
View File

@ -0,0 +1,130 @@
Model 重构总计划(数据库 + Migrations + Models)
更新时间: 2026-03-22
当前状态: 执行中(阶段 1-3 已完成)
负责人:
目标截止时间:
执行分支:
[事务归属]
- 本子事务已纳入 `todo.txt` 总事务看板统一管理。
- 主里程碑对齐总事务 DDL(2026-04-15),以总事务验收为最终关闭条件。
[最终目标]
- 梳理数据库中所有表结构并形成统一基线。
- 补全并对齐 database/migrations 目录下的迁移文件。
- 规范所有 model 的命名与内部关联。
- 清理所有 model 内部能力(移除死代码、职责收敛、保持模型层可预测)。
[执行规则]
- [x] 本文件用于规划拆解,已完成初始化。
- [x] 已收到新任务,开始执行阶段 1。
- [x] 进入代码改动前,先核对目标 service 的真实调用链。
- [x] 若 service 已被 system/qimen 入口使用,则必须同步更新对应 API 文档。
- [x] 所有联动修改需记录到 SERVICE_API_CHANGE_AUDIT_20260322.md,便于后续复盘。
- [x] 任何模型/关联改动前,使用测试账号执行 method 基线回放(配置与样本来源必须可追溯)。
- [x] 任何模型/关联改动后,执行同一批 method 对比回放并输出比对报告。
- [x] 新增交付条件:修改前后 method 输出结果一致(允许仅屏蔽 token/timestamp 等波动字段)。
- [x] 后续所有接口返回数据检测,统一使用“自动生成的 Egg.js 标注测试脚本”执行校验。
[阶段 1: 全量盘点与基线建立]
- [x] 1.1 盘点所有数据表(字段、主键、索引、约束、注释)。
- [x] 1.2 盘点所有 model 文件(app/model 下文件、导出名、表映射)。
- [x] 1.3 盘点 model 关联(belongsTo/hasMany/hasOne/belongsToMany 与外键使用)。
- [x] 1.4 产出 DB 结构与 model 定义差异报告。
- [x] 1.5 在根目录生成 modelList.md,构建 model 层级结构与说明。
- [x] 1.6 在 README.md 增加对 modelList.md 的引用说明。
交付物:
- table_schema_inventory.md
- model_inventory.md
- model_association_inventory.md
- schema_model_gap_report.md
- modelList.md
退出标准:
- 100% 数据表与 100% model 文件覆盖完成。
- modelList.md 可用于快速定位模型层级与职责。
[阶段 2: Migration 补全与执行顺序设计]
- [x] 2.1 审核现有 database/migrations 的命名、顺序、幂等性。
- [x] 2.2 根据阶段 1 差异清单补齐缺失迁移任务。
- [x] 2.3 设计迁移执行顺序(先结构后索引/约束,必要时分批回填数据)。
- [x] 2.4 为每个迁移定义可执行回滚步骤。
- [x] 2.5 形成 local/test 环境演练方案。
交付物:
- migration_gap_list.md
- migration_execution_plan.md
- rollback_plan.md
退出标准:
- 每个结构差异都有明确迁移归属与回滚路径。
[阶段 3: Model 命名规范化]
- [x] 3.1 定义命名规范(文件名、类名、model key、表映射、alias)。
- [x] 3.2 产出非规范命名的重命名映射表。
- [x] 3.3 评估跨层影响(service/controller/query 调用点)。
- [x] 3.4 制定兼容策略(临时别名或分批重命名)。
交付物:
- model_naming_standard.md
- model_rename_map.md
- rename_impact_report.md
退出标准:
- 所有命名不规范项有明确修复路径与影响说明。
[阶段 4: 关联关系规范化]
- [x] 4.1 逐项校验关联定义与真实外键关系一致性(详见 association_fk_consistency_report.md)。
- [x] 4.2 统一 alias 命名与双向关联完整性。
- [x] 4.3 清理重复或冲突关联。
- [x] 4.4 形成 eager-loading 与 N+1 风险规约(详见 association_eager_loading_n_plus_one_guideline.md)。
交付物:
- association_fix_plan.md
- association_validation_checklist.md
退出标准:
- 关联关系可预测、无冲突、与数据库关系一致。
[阶段 5: Model 内部能力清理]
- [x] 5.1 识别应迁移到 service 层的方法能力(见 model_cleanup_list.md 第一批清单)。
- [ ] 5.2 清理 model 内死代码与调试代码(进行中:第一批/第二批 P2 无调用静态方法已清理;P1 前两组 EntryOrder/EntryItems 与 Storage 已迁移到 service)。
- [ ] 5.3 规范 hooks/scopes/virtual fields 的使用边界。
- [ ] 5.4 固化模型层边界规则(可做/不可做)。
交付物:
- model_cleanup_list.md
- model_boundary_rules.md
退出标准:
- 模型层聚焦于数据映射与轻量领域行为,职责边界清晰。
[阶段 6: 验证与交接]
- [ ] 6.1 在干净库上回放 migration 全流程。
- [ ] 6.2 验证 model CRUD 与关联查询正确性。
- [ ] 6.3 执行关键 API 冒烟回归(包含 method-output 基线/对比)。
- [ ] 6.4 更新最终文档(README + methods + 内部交接文档)。
交付物:
- verification_report.md
- handover_notes.md
退出标准:
- 无迁移漂移、无关联错配、无阻断回归问题。
[风险]
- 历史遗留表或隐式依赖未被识别。
- 环境间数据漂移导致验证结果不一致。
- 命名调整引发跨层调用副作用。
[依赖]
- 稳定可访问的数据库环境(盘点与验证)。
- 统一确认的命名与关联规范。
- 可执行的迁移窗口与回滚窗口。
[下一步]
- 阶段 4 的 4.1-4.4 已完成(含 receiving 第一批收敛与 N+1/eager-loading 规约落地)。
- 高优先差异项推进: 已完成 store_warehouse/stock_warehouse 第二批收敛(stock_store include 语义约束补齐),并通过门禁。
- 高优先差异项推进: 已完成 role / role_permission / permission 第三批收敛(启用状态过滤 + 去重),并通过门禁。
- 已完成“DB 约束补齐”执行: `wms_role_permission.permission_id -> wms_permission.id` 外键已生效,SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。
- 已完成数据清洗与备份: 4 条 permission 孤儿、3 条 role.store_id=0 哨兵数据均已处理(备份表见 `role_permission_fk_data_cleanup_plan.md`)。
- 已完成 `wms_role.store_id` 外键策略落地:外键 `fk_wms_role_store` 已生效(ON DELETE SET NULL),SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。
- 已完成 store_warehouse / stock_warehouse 模型层复合键语义治理(统一 include 构造器 + constraints:false 显式化)。
- 已完成阶段 4 收尾检查(第 1 项):全量 include alias 一致性扫描(service alias 与 model alias 差集=0)。
- 已完成阶段 4 收尾检查(第 2 项):permission.parent_id 自关联约束策略已落地(root=NULL + FK)。
- 已完成阶段 5.1:识别应迁移到 service 层的方法能力(第一批清单见 model_cleanup_list.md)。
- 已启动阶段 5.2:已完成第一批 P2 无调用静态方法清理(ApiApp / InterfaceType / PrintItem),门禁通过。
- 已完成阶段 5.2 删除前引用复核(第二批):I18nTranslation 5 个候选静态方法、StockStore 2 个候选静态方法均未检出业务调用。
- 已完成阶段 5.2 第二批 P2 方法删除(I18nTranslation / StockStore),compare + generated regression + smoke 门禁通过。
- 已完成阶段 5.2 P1 第一组迁移:EntryOrder / EntryItems 共 8 个静态方法已迁移到 `app/service/systems/entry_order.js`,并从 model 删除;compare + generated regression + smoke 门禁通过。
- 已完成阶段 5.2 P1 第二组迁移:Storage 共 10 个静态方法已迁移到 `app/service/systems/storage/index.js`,并从 model 删除。
- 下一步继续阶段 5.2:推进 P1 剩余方法(RolePermission / Store)从 model 向 service 收敛,并在迁移完成后回收对应静态方法。

168
rename_impact_report.md Normal file
View File

@ -0,0 +1,168 @@
# Model 命名影响评估报告
更新时间: 2026-03-22
范围:
- app/model/*.js
- app/service/**/*.js
- app/controller/**/*.js
## 1. 结论摘要
当前命名问题分成两层:
1. 真正会影响运行的调用错误。
2. 还能运行,但会持续制造理解成本和后续重构风险的 defineName/alias 漂移。
本轮确认的最高优先级风险有 3 个:
### 1.1 AccountStoreRole 是仓库内不存在的运行时 key
- 代码大量使用 ctx.model.AccountStoreRole。
- app/model 下没有对应的 account_store_role.js。
- 现有 schema 已落到 AccountStoreEmployee + EmployeeRole 两层关系。
- 这不是单纯命名风格问题,而是“旧关系名残留到新模型结构”的兼容断层。
### 1.2 动态分表工厂存在一组错误调用名
- 仓库主流调用是 OrderDeliveryFactory / OrderItemsFactory。
- 仅 app/service/apiMethods/test.js 仍在使用 WmsOrderDeliveryFactory / WmsOrderItemsFactory。
- 这会导致测试/调试路径与正式业务路径使用不同的模型入口。
### 1.3 alias 已经切到 employee 语义,但 service 仍按 role 语义取值
- app/model/account_platform_active.js 中 alias 是 accountStoreEmployee。
- 但 app/service/systems/account_platform.js 仍按 accountStoreRole 进行 include 和结果读取。
- 这说明 model 层与 service 层对同一关系的语义认知已经分叉。
## 2. 关键证据
### 2.1 不存在的 model key: AccountStoreRole
受影响位置:
- app/service/systems/account_platform.js:21
- app/service/systems/account_platform.js:102
- app/service/systems/account_platform.js:169
- app/service/systems/account_platform.js:226
- app/service/systems/account_platform.js:321
- app/service/systems/store.js:464
- app/service/systems/store.js:679
- app/service/systems/store.js:690
- app/model/role.js:151
现状说明:
- app/model/account_store_employee.js:6 定义的是 AccountStoreEmployee,表为 wms_account_store_employee。
- app/model/account_store_employee.js:82-99 说明当前关系是 AccountStoreEmployee -> EmployeeRole -> Role。
- app/model/account_platform_active.js:79-86 已把激活关系关联到 AccountStoreEmployee。
风险判断:
- 如果继续沿用 AccountStoreRole,后续关联收敛会同时破坏 include、字段读取、缓存结构与返回结构。
- 该问题必须在正式改 defineName 之前先做数据关系确认。
建议动作:
1. 先确认“平台激活”想绑定的是员工记录还是员工-角色明细。
2. 若绑定员工记录,则将 AccountStoreRole 全量替换为 AccountStoreEmployee,并改造 role 读取路径。
3. 若绑定员工-角色明细,则需要新增独立模型,而不是继续使用幽灵 key。
### 2.2 动态工厂 key 调用漂移
正常调用样本:
- app/service/systemMethods/order.js:22-23
- app/service/systems/delivery_order.js:14
- app/service/systems/delivery_order.js:311
- app/service/qimenMethods/deliveryorder.js:7-8
异常调用样本:
- app/service/apiMethods/test.js:50
- app/service/apiMethods/test.js:51
风险判断:
- 正式链路与调试链路的 model 入口不一致,后续如果只修主链路,测试链路会继续漂移。
- 这是低成本高收益修复项,应优先纳入第一批代码修正。
建议动作:
1. 将 WmsOrderDeliveryFactory 改为 OrderDeliveryFactory。
2. 将 WmsOrderItemsFactory 改为 OrderItemsFactory。
3. 回归验证动态表 current/history 获取能力是否一致。
### 2.3 alias 与语义漂移
证据位置:
- app/model/account.js:139 使用 alias accountStoreRoles,但实际模型是 AccountStoreEmployee。
- app/model/account_platform_active.js:84 使用 alias accountStoreEmployee。
- app/model/account_store_employee.js:95 使用 hasMany(EmployeeRole, { as: 'employeeRole' })。
- app/model/role.js:171 使用 hasMany(EmployeeRole, { as: 'employeeRole' })。
- app/service/systems/account_platform.js:102-136 仍按 accountStoreRole 读取嵌套字段。
风险判断:
- 当前 alias 命名混合了“员工关系”和“角色关系”两种语义。
- 若不先统一语义,后续只做名字替换会把问题从命名层转移到数据层。
建议动作:
1. 阶段 4 先梳理 employee、role、store 三者的真实关系。
2. hasMany alias 收敛为复数形式,如 employeeRoles、accountStoreEmployees。
3. service 层返回结构与 include 路径同步改名,避免只改 model 不改消费方。
## 3. defineName 漂移影响
以下问题当前通常不会直接导致运行失败,但会持续造成阅读成本与重构误判:
| 文件 | 证据 | 当前情况 | 风险 |
| --- | --- | --- | --- |
| app/model/platform_setting.js | :7 | defineName 为 platform_setting,运行时 key 为 PlatformSetting | 阅读时容易误以为 key 与 defineName 同名 |
| app/model/qimen_app.js | :6 | defineName 为 qimen_app,运行时 key 为 QimenApp | service 调用与模型定义风格分裂 |
| app/model/qimen_log.js | :8 | defineName 为 qimen_log,运行时 key 为 QimenLog | 日志模型定位成本高 |
| app/model/account_store_employee.js | :6 | defineName 为 wms_account_store_employee,运行时 key 为 AccountStoreEmployee | 将表名语义混入模型名 |
| app/model/stock_barcode.js | :6 | defineName 为 stock_barcodes,运行时 key 为 StockBarcode | 单复数与 key 同时漂移 |
| app/model/prohibited_type.js | :6 | defineName 为 prohibitedType,运行时 key 为 ProhibitedType | lowerCamelCase 与 PascalCase 混用 |
| app/model/print_stations.js | :5 | defineName 为 print_stations,运行时 key 为 PrintStations | 虽可运行,但风格不统一 |
影响判断:
- 新增 include、调试 SQL、追踪关联时,很容易把 defineName、key、tableName 当成同一件事。
- 后续如果继续新增 snake_case defineName,会放大维护面。
建议动作:
1. 先完成 P0 调用修复。
2. 再按 model_rename_map.md 分批将 defineName 收敛到 PascalCase。
3. 每次改 defineName 后,回归关联加载与 SQL 日志输出,确认未引入隐式副作用。
## 4. 稳定项与例外项
以下命名虽然不完全理想,但当前不建议仅因风格而改动:
- app/model/print_record.js
- defineName 已为 PrintRecord,运行时 key 与之保持一致。
- app/model/store_join.js
- defineName 已为 StoreJoin,当前问题主要不在命名层。
- app/model/order_delivery_factory.js
- 工厂模型对外 key 稳定,重点是调用方统一。
- app/model/order_items_factory.js
- 工厂模型对外 key 稳定,重点是调用方统一。
- app/model/print_stations.js
- 文件名和表名均为复数,当前更适合先保留为历史兼容项,不单独改文件名。
## 5. 推荐执行顺序
1. 第一批: 修正不存在的运行时 key 和错误工厂调用名。
2. 第二批: 收敛静态模型 defineName,保持 tableName 不变。
3. 第三批: 在关联核对完成后统一 alias 和 include 路径。
4. 第四批: 更新测试、README、modelList.md、关联清单等文档。
## 6. 对后续阶段的输入
- 阶段 4 需要重点核对 AccountPlatformActive、AccountStoreEmployee、EmployeeRole、Role、Store 的外键与 include 结构。
- 阶段 5 需要顺带清理与命名漂移绑定的死代码、调试日志和旧语义变量名。
- 阶段 6 验证时必须覆盖平台激活、仓库角色分配、动态订单分表、打印链路四类高风险场景。

View File

@ -0,0 +1,104 @@
# role_permission_fk_data_cleanup_plan
更新时间: 2026-03-23
目标: 清理 role/permission 相关孤儿数据,解除 `20260323103000-align-role-permission-fk.js` 执行阻塞。
## 1. 审计现状
- `wms_role_permission.permission_id` 孤儿记录: 4 条(id: 2, 3, 6, 10)
- `wms_role.store_id` 非法哨兵值: 3 条(store_id = 0)
- 字段类型差异:
- `wms_permission.id`: `int(11)`
- `wms_role_permission.permission_id`: `bigint(20) unsigned`(迁移已处理为对齐)
## 2. 执行顺序
1. 备份孤儿数据
2. 删除 `wms_role_permission` 孤儿行
3. 规范 `wms_role.store_id = 0` 为 `NULL`(仅对可空字段)
4. 复核计数
5. 执行迁移 `20260323103000-align-role-permission-fk.js`
## 3. 推荐 SQL(先在测试环境执行)
### 3.1 备份 role_permission 孤儿行
```sql
CREATE TABLE IF NOT EXISTS wms_role_permission_orphan_backup_20260323 AS
SELECT rp.*
FROM wms_role_permission rp
LEFT JOIN wms_permission p ON p.id = rp.permission_id
WHERE p.id IS NULL;
```
### 3.2 删除 role_permission 孤儿行
```sql
DELETE rp
FROM wms_role_permission rp
LEFT JOIN wms_permission p ON p.id = rp.permission_id
WHERE p.id IS NULL;
```
### 3.3 规范 role.store_id 哨兵值
```sql
UPDATE wms_role
SET store_id = NULL
WHERE store_id = 0;
```
### 3.4 复核
```sql
SELECT 'rp_perm_orphan' AS metric, COUNT(*) AS cnt
FROM wms_role_permission rp
LEFT JOIN wms_permission p ON p.id = rp.permission_id
WHERE p.id IS NULL
UNION ALL
SELECT 'role_store_zero' AS metric, COUNT(*) AS cnt
FROM wms_role
WHERE store_id = 0;
```
## 4. 回滚思路
- 若删除孤儿行后需要回滚,可从备份表恢复:
```sql
INSERT INTO wms_role_permission (id, role_id, permission_id, created_at)
SELECT id, role_id, permission_id, created_at
FROM wms_role_permission_orphan_backup_20260323;
```
- `wms_role.store_id` 从 `0 -> NULL` 回滚需结合业务语义,不建议盲目全量回写 `0`。
## 5. 交付门禁
清洗和迁移完成后,执行:
1. `node .\\script\\method-output-regression.cjs compare`
2. `node .\\script\\tmp-generate-method-regression-test.cjs`
3. `npx egg-bin test temp/generated-tests/system.method-output.generated.test.js`
4. `npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js`
通过标准:
- compare: mismatch=0
- 回归测试: 全部通过
## 6. 执行记录(2026-03-23)
- 备份执行结果:
- `wms_role_permission_orphan_backup_20260323`: 4 行
- `wms_role_store_zero_backup_20260323`: 3 行
- 清洗执行结果:
- role_permission 孤儿删除: 4 行
- role.store_id=0 -> NULL: 3 行
- 迁移执行结果:
- `wms_role_permission.permission_id` 已对齐为 `int(11)`
- 外键 `fk_wms_role_permission_permission` 已生效
- SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`
- 门禁结果:
- method-output compare: mismatch=0
- generated regression + smoke: 14 passing

49
rollback_plan.md Normal file
View File

@ -0,0 +1,49 @@
# rollback_plan
更新时间: 2026-03-22
## 1. 通用回滚规则
- 所有新增 migration 必须提供 down。
- 对现网已有表,down 不应默认直接 drop 整表。
- 优先回滚新增字段、索引、约束,避免误删存量数据。
- 涉及数据回填的 migration,必须保留影响范围快照或备份。
## 2. 分类型回滚策略
### 建表 migration
- 新环境可使用 dropTable 回滚。
- 现网已有表不建议通过 down 删除,应改为“标记基线 + 停止继续执行”。
### 加字段 migration
- down 使用 dropColumn。
- 执行前需确认字段不被线上代码强依赖。
### 索引 migration
- down 使用 removeIndex。
- 若为性能补丁索引,回滚前需评估查询退化风险。
### 视图 migration
- down 使用 drop view。
- 回滚前确认是否有查询依赖视图。
### 动态分表策略 migration
- 只回滚策略与模板,不批量 drop 已创建的仓库动态表。
- 已存在分表应通过单独治理,不纳入统一 down 删除范围。
## 3. 当前优先风险
- 未进入 SequelizeMeta 的 migration 不能按常规 down 处理,必须先确认其是否已在数据库中手工生效。
- order_delivery/order_items 主表与动态表结构存在差异,回滚时必须区分主表与动态表。
- 日志类表通常已有存量数据,回滚需要避免整表删除。
## 4. 建议执行前准备
- 每批 migration 执行前导出目标表结构快照。
- 若涉及数据变更,先做行数统计与影响范围确认。
- 为每批次准备单独回滚脚本,不依赖临场拼写 SQL。

View File

@ -0,0 +1,98 @@
# schema_model_gap_report
Updated: 2026-03-22
## Scope
- DB source: information_schema.TABLES / COLUMNS / STATISTICS
- Model source: app/model/*.js (tableName option)
## Count
- Model files: 45
- Model with tableName: 43
- DB tables: 68
- modelOnly table count: 0
- dbOnly table count: 25
## modelOnly tables
- none
## dbOnly tables
- SequelizeMeta
- wms_account_login_log
- wms_api_log
- wms_embargo_policies
- wms_express
- wms_express_print_record
- wms_express_setting
- wms_order_delivery_100000
- wms_order_delivery_1000028
- wms_order_express
- wms_order_express_print_data
- wms_order_items_100000
- wms_order_items_1000028
- wms_order_operation
- wms_order_operation_log
- wms_order_picking
- wms_picking_strategy
- wms_platform_print_config
- wms_print_batch
- wms_print_log
- wms_printer_config
- wms_system_config
- wms_system_log
- wms_wave_batch
- wms_wave_operation_log
## Model mapping snapshot
| key | file | defineName | tableName |
| --- | --- | --- | --- |
| account | app/model/account.js | account | wms_account |
| account_platform_active | app/model/account_platform_active.js | account_platform_active | wms_account_platform_active |
| account_store_employee | app/model/account_store_employee.js | wms_account_store_employee | wms_account_store_employee |
| api_app | app/model/api_app.js | api_app | wms_api_app |
| employee_role | app/model/employee_role.js | employee_role | wms_employee_role |
| entry_items | app/model/entry_items.js | wms_entry_items | wms_entry_items |
| entry_order | app/model/entry_order.js | wms_entry_order | wms_entry_order |
| fast_where | app/model/fast_where.js | fast_where | wms_fast_where |
| file | app/model/file.js | wms_file | wms_file |
| file_reference | app/model/file_reference.js | wms_file_reference | wms_file_reference |
| i18n_key | app/model/i18n_key.js | wms_i18n_key | wms_i18n_keys |
| i18n_translation | app/model/i18n_translation.js | wms_i18n_translation | wms_i18n_translations |
| interface_type | app/model/interface_type.js | interface_type | wms_interface_type |
| location_space | app/model/location_space.js | wms_location_space | wms_location_space |
| location_type | app/model/location_type.js | location_type | wms_location_type |
| location_zone | app/model/location_zone.js | wms_location_zone | wms_location_zone |
| operation_log | app/model/operation_log.js | operation_log | wms_operation_log |
| order_delivery | app/model/order_delivery.js | order_delivery | wms_order_delivery |
| order_delivery_factory | app/model/order_delivery_factory.js | - | - |
| order_items | app/model/order_items.js | wms_order_items | wms_order_items |
| order_items_factory | app/model/order_items_factory.js | - | - |
| permission | app/model/permission.js | permission | wms_permission |
| platform | app/model/platform.js | platform | wms_platform |
| platform_setting | app/model/platform_setting.js | platform_setting | wms_platfrom_setting |
| print_computer | app/model/print_computer.js | print_computer | wms_print_computer |
| print_item | app/model/print_item.js | print_item | wms_print_items |
| print_record | app/model/print_record.js | PrintRecord | wms_print_record |
| print_station_express | app/model/print_station_express.js | print_station_express | wms_print_station_express |
| print_stations | app/model/print_stations.js | print_stations | wms_print_stations |
| print_template | app/model/print_template.js | print_template | wms_print_template |
| prohibited_type | app/model/prohibited_type.js | prohibitedType | wms_prohibited_type |
| qimen_app | app/model/qimen_app.js | qimen_app | wms_qimen_apps |
| qimen_log | app/model/qimen_log.js | qimen_log | wms_qimen_log |
| receiving | app/model/receiving.js | wms_receiving | wms_receiving |
| receiving_detail | app/model/receiving_detail.js | wms_receiving_detail | wms_receiving_detail |
| role | app/model/role.js | role | wms_role |
| role_permission | app/model/role_permission.js | role_permission | wms_role_permission |
| stock_barcode | app/model/stock_barcode.js | stock_barcodes | wms_stock_barcodes |
| stock_store | app/model/stock_store.js | stock_store | wms_stock_store |
| stock_unit | app/model/stock_unit.js | wms_stock_unit | wms_stock_unit |
| stock_warehouse | app/model/stock_warehouse.js | stock_warehouse | wms_stock_warehouse |
| storage | app/model/storage.js | wms_storage | wms_storage |
| store | app/model/store.js | store | wms_store |
| store_join | app/model/store_join.js | StoreJoin | wms_store_join |
| store_warehouse | app/model/store_warehouse.js | store_warehouse | wms_store_warehouse |

View File

@ -0,0 +1,427 @@
const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
const ROOT = process.cwd();
const OUTPUT_DIR = path.join(ROOT, 'temp', 'method-output');
const LEGACY_RUN_DIR = path.join(ROOT, 'run');
const BASELINE_FILE = path.join(OUTPUT_DIR, 'method-output-baseline.json');
const BASELINE_SUMMARY = path.join(OUTPUT_DIR, 'method-output-baseline.md');
const COMPARE_FILE = path.join(OUTPUT_DIR, 'method-output-compare.json');
const LEGACY_BASELINE_FILE = path.join(LEGACY_RUN_DIR, 'method-output-baseline.json');
const MODE = (process.argv[2] || 'baseline').toLowerCase();
const LIMIT = Number(process.argv[3] || 8);
const TEST_USERNAME = process.env.WMS_TEST_USER || 'liufumingren';
const TEST_PASSWORD = process.env.WMS_TEST_PASS || '111111';
const READONLY_HINT = /(get|list|query|detail|info|stats|tree|search|load)/i;
const MUTATION_HINT = /(create|update|delete|remove|audit|confirm|complete|add|sync|synchronize|upload|assign|change|logout|login)/i;
const VOLATILE_KEYS = new Set([
'timestamp',
'token',
'last_login_at',
'updated_at',
'update_at',
'created_at',
'create_at',
'login_time',
'iat',
'exp',
]);
function ensureOutputDir() {
if (!fs.existsSync(OUTPUT_DIR)) {
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
}
}
function resolveBaselineFile() {
if (fs.existsSync(BASELINE_FILE)) return BASELINE_FILE;
if (fs.existsSync(LEGACY_BASELINE_FILE)) return LEGACY_BASELINE_FILE;
return BASELINE_FILE;
}
function readLocalConfig() {
const localCfgFactory = require(path.join(ROOT, 'config', 'config.local.js'));
const cfg = localCfgFactory({ name: 'wms' });
return cfg;
}
function buildBaseUrl(cfg) {
const host = cfg.cluster?.listen?.hostname && cfg.cluster.listen.hostname !== '0.0.0.0'
? cfg.cluster.listen.hostname
: '127.0.0.1';
const port = cfg.cluster?.listen?.port || 6060;
return `http://${host}:${port}`;
}
function loadSystemMethodDocs() {
const file = path.join(ROOT, 'methods', 'system.json');
const raw = fs.readFileSync(file, 'utf8');
const json = JSON.parse(raw);
const map = new Map();
const groups = json?.methods?.groups || [];
for (const group of groups) {
for (const item of group.list || []) {
map.set(item.method, {
groupName: group.groupName,
module: group.module,
description: item.description,
isNeedAuth: !!item.isNeedAuth,
isNeedLogin: !!item.isNeedLogin,
params: (item.params || []).map(p => ({
name: p.name,
type: p.type,
required: !!p.required,
source: p.source,
description: p.description,
})),
});
}
}
return map;
}
function safeJsonParse(text, fallback = null) {
if (!text || typeof text !== 'string') return fallback;
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
function normalizeValue(value) {
if (value === null || value === undefined) return value;
if (Array.isArray(value)) return value.map(item => normalizeValue(item));
if (typeof value !== 'object') return value;
const out = {};
for (const key of Object.keys(value)) {
if (VOLATILE_KEYS.has(key)) {
out[key] = '__VOLATILE__';
continue;
}
out[key] = normalizeValue(value[key]);
}
return out;
}
function stableStringify(obj) {
return JSON.stringify(obj);
}
function pickPlatform(headers, rowDevice) {
const fromHeaders = String(headers?.platform || '').trim().toLowerCase();
if (fromHeaders) return fromHeaders;
const fromDevice = String(rowDevice || '').trim().toLowerCase();
if (fromDevice === 'desktop') return 'web';
if (fromDevice) return fromDevice;
return 'web';
}
function pickProject(headers) {
const project = String(headers?.project || '').trim().toLowerCase();
if (!project) return 'wms';
if (project === 'all') return 'wms';
return project;
}
async function createDbConnection(cfg) {
const db = cfg.mysql.clients.wms;
return mysql.createConnection({
host: db.host,
port: Number(db.port),
user: db.user,
password: db.password,
database: db.database,
});
}
async function loadRecentSystemLogCases(conn, methodDocs, limit, username) {
const [rows] = await conn.query(`
SELECT id, method, body, headers, auth, device, result, created_at
FROM wms_system_log
WHERE method IS NOT NULL
AND method <> ''
AND body IS NOT NULL
AND body <> ''
ORDER BY id DESC
LIMIT 1200
`);
const preferred = [];
const fallback = [];
const seen = new Set();
for (const row of rows) {
if (!methodDocs.has(row.method)) continue;
if (row.method === 'user.login' || row.method === 'user.logout' || row.method === 'user.changeRole') continue;
const body = safeJsonParse(row.body, null);
if (!body || typeof body !== 'object') continue;
const signature = `${row.method}::${JSON.stringify(body)}`;
if (seen.has(signature)) continue;
seen.add(signature);
const headers = safeJsonParse(row.headers, {});
const auth = safeJsonParse(row.auth, {});
const fromUser = String(auth?.username || '').trim().toLowerCase() === String(username || '').trim().toLowerCase();
const methodLooksReadOnly = READONLY_HINT.test(row.method) && !MUTATION_HINT.test(row.method);
const historySuccess = typeof row.result === 'string' && row.result.includes('"status":200');
const item = {
source: 'wms_system_log',
sourceId: row.id,
sourceCreatedAt: row.created_at,
method: row.method,
body,
headers: {
platform: pickPlatform(headers, row.device),
project: pickProject(headers),
},
fromUser,
readOnlyHint: methodLooksReadOnly,
historySuccess,
};
if (fromUser && methodLooksReadOnly && historySuccess) preferred.push(item);
else if (fromUser && methodLooksReadOnly) preferred.push(item);
else if (methodLooksReadOnly) fallback.push(item);
if (preferred.length >= limit * 2) break;
}
const result = [];
const methodSeen = new Set();
for (const item of preferred) {
if (result.length >= limit) break;
if (methodSeen.has(item.method)) continue;
result.push(item);
methodSeen.add(item.method);
}
for (const item of preferred) {
if (result.length >= limit) break;
result.push(item);
}
for (const item of fallback) {
if (result.length >= limit) break;
if (methodSeen.has(item.method)) continue;
result.push(item);
methodSeen.add(item.method);
}
for (const item of fallback) {
if (result.length >= limit) break;
result.push(item);
}
return result;
}
async function callSystemMethod(baseUrl, method, body, headers, token) {
const ts = Math.floor(Date.now() / 1000);
const url = `${baseUrl}/system?method=${encodeURIComponent(method)}&v=1&timestamp=${ts}`;
const reqHeaders = {
platform: headers.platform || 'web',
project: headers.project || 'wms',
'content-type': 'application/json',
};
if (token) {
reqHeaders.authorization = `Bearer ${token}`;
}
const resp = await fetch(url, {
method: 'POST',
headers: reqHeaders,
body: JSON.stringify(body || {}),
});
const text = await resp.text();
const data = safeJsonParse(text, { __raw_text__: text });
return {
httpStatus: resp.status,
response: data,
normalized: normalizeValue(data),
};
}
function extractToken(loginResponse) {
const direct = loginResponse?.response?.data?.token;
if (typeof direct === 'string' && direct.length > 10) return direct;
return '';
}
function renderBaselineMarkdown(baseline) {
let md = '';
md += '# method-output-baseline\n\n';
md += `GeneratedAt: ${baseline.generatedAt}\n`;
md += `BaseUrl: ${baseline.baseUrl}\n`;
md += `User: ${baseline.user}\n`;
md += `CaseCount: ${baseline.cases.length}\n\n`;
md += '| method | source | sourceId | status | group | note |\n';
md += '| --- | --- | --- | --- | --- | --- |\n';
for (const c of baseline.cases) {
md += `| ${c.method} | ${c.source} | ${c.sourceId} | ${c.httpStatus} | ${c.doc?.groupName || ''} | ${c.doc?.description || ''} |\n`;
}
md += '\n';
return md;
}
async function runBaseline() {
const cfg = readLocalConfig();
const baseUrl = buildBaseUrl(cfg);
const methodDocs = loadSystemMethodDocs();
const conn = await createDbConnection(cfg);
try {
const selected = await loadRecentSystemLogCases(conn, methodDocs, LIMIT, TEST_USERNAME);
if (!selected.length) {
throw new Error('未从 wms_system_log 找到可回放的只读 method 样本');
}
const login = await callSystemMethod(
baseUrl,
'user.login',
{ username: TEST_USERNAME, password: TEST_PASSWORD },
{ platform: 'web', project: 'wms' },
''
);
const token = extractToken(login);
if (!token) {
throw new Error('登录成功但未拿到 token,请检查 user.login 返回结构');
}
const cases = [];
for (const item of selected) {
const call = await callSystemMethod(baseUrl, item.method, item.body, item.headers, token);
cases.push({
method: item.method,
source: item.source,
sourceId: item.sourceId,
sourceCreatedAt: item.sourceCreatedAt,
headers: item.headers,
requestBody: item.body,
doc: methodDocs.get(item.method) || null,
httpStatus: call.httpStatus,
response: call.response,
normalized: call.normalized,
});
}
const baseline = {
generatedAt: new Date().toISOString(),
baseUrl,
user: TEST_USERNAME,
note: 'Before-change baseline generated from recent system logs and methods/system.json',
login: {
httpStatus: login.httpStatus,
normalized: login.normalized,
},
cases,
};
ensureOutputDir();
fs.writeFileSync(BASELINE_FILE, JSON.stringify(baseline, null, 2), 'utf8');
fs.writeFileSync(BASELINE_SUMMARY, renderBaselineMarkdown(baseline), 'utf8');
console.log(`BASELINE_OK cases=${cases.length}`);
console.log(`BASELINE_FILE ${BASELINE_FILE}`);
console.log(`BASELINE_SUMMARY ${BASELINE_SUMMARY}`);
} finally {
await conn.end();
}
}
async function runCompare() {
const baselineFile = resolveBaselineFile();
if (!fs.existsSync(baselineFile)) {
throw new Error(`baseline 文件不存在: ${BASELINE_FILE}`);
}
const baseline = JSON.parse(fs.readFileSync(baselineFile, 'utf8'));
const cfg = readLocalConfig();
const baseUrl = buildBaseUrl(cfg);
const login = await callSystemMethod(
baseUrl,
'user.login',
{ username: TEST_USERNAME, password: TEST_PASSWORD },
{ platform: 'web', project: 'wms' },
''
);
const token = extractToken(login);
if (!token) {
throw new Error('compare 阶段登录后未拿到 token');
}
const compared = [];
let mismatchCount = 0;
for (const item of baseline.cases || []) {
const call = await callSystemMethod(
baseUrl,
item.method,
item.requestBody,
item.headers || { platform: 'web', project: 'wms' },
token
);
const beforeNorm = item.normalized;
const afterNorm = call.normalized;
const same = stableStringify(beforeNorm) === stableStringify(afterNorm);
if (!same) mismatchCount++;
compared.push({
method: item.method,
sourceId: item.sourceId,
httpStatusBefore: item.httpStatus,
httpStatusAfter: call.httpStatus,
outputEqual: same,
beforeNormalized: beforeNorm,
afterNormalized: afterNorm,
});
}
const report = {
comparedAt: new Date().toISOString(),
baseUrl,
user: TEST_USERNAME,
baselineFile,
total: compared.length,
mismatchCount,
pass: mismatchCount === 0,
items: compared,
};
ensureOutputDir();
fs.writeFileSync(COMPARE_FILE, JSON.stringify(report, null, 2), 'utf8');
console.log(`COMPARE_DONE total=${report.total} mismatch=${report.mismatchCount}`);
console.log(`COMPARE_FILE ${COMPARE_FILE}`);
if (report.mismatchCount > 0) {
process.exitCode = 1;
}
}
async function main() {
if (MODE !== 'baseline' && MODE !== 'compare') {
throw new Error('用法: node script/method-output-regression.cjs <baseline|compare> [limit]');
}
if (MODE === 'baseline') {
await runBaseline();
} else {
await runCompare();
}
}
main().catch(err => {
console.error(err);
process.exit(1);
});

254
script/redis-cache.ps1 Normal file
View File

@ -0,0 +1,254 @@
param(
[Parameter(Mandatory = $true)]
[ValidateSet('get', 'set', 'del', 'exists', 'ttl', 'expire', 'keys', 'hget', 'hset', 'hdel', 'hgetall', 'incr', 'decr')]
[string]$Action,
[Parameter(Mandatory = $false)]
[string]$RedisClient = 'cache',
[Parameter(Mandatory = $false)]
[string]$Key,
[Parameter(Mandatory = $false)]
[string]$Value,
[Parameter(Mandatory = $false)]
[string]$Field,
[Parameter(Mandatory = $false)]
[int]$ExpireSeconds,
[Parameter(Mandatory = $false)]
[string]$Pattern = '*',
[Parameter(Mandatory = $false)]
[string]$ConfigPath = '.\\config\\config.local.js',
[switch]$AsTable
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$scriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Path
$projectRoot = Split-Path -Parent $scriptRoot
$configFullPath = Join-Path $projectRoot $ConfigPath
$configResolved = Resolve-Path -Path $configFullPath -ErrorAction Stop
$nodeScript = @'
const path = require("path");
const { createRequire } = require("module");
(async () => {
const payloadBase64 = process.argv[2];
if (!payloadBase64) {
throw new Error("Missing payload.");
}
const payload = JSON.parse(Buffer.from(payloadBase64, "base64").toString("utf8"));
const {
projectRoot,
configPath,
clientName,
action,
key,
value,
field,
expireSeconds,
pattern,
} = payload;
const normalizedAction = String(action || "").toLowerCase();
const projectRequire = createRequire(path.join(projectRoot, "package.json"));
const Redis = projectRequire("ioredis");
const configFactory = require(path.resolve(configPath));
const config = typeof configFactory === "function"
? configFactory({ name: "wms-debug" })
: configFactory;
const redisConfig = config && config.redis;
const client = redisConfig && redisConfig.clients && redisConfig.clients[clientName]
? redisConfig.clients[clientName]
: redisConfig && redisConfig.client;
if (!client) {
throw new Error(`Redis client "${clientName}" not found in config.redis.clients.`);
}
const redis = new Redis({
host: client.host,
port: Number(client.port || 6379),
password: client.password,
db: Number(client.db || 0),
keyPrefix: client.keyPrefix || "",
connectTimeout: Number(client.connectTimeout || 10000),
lazyConnect: false,
enableReadyCheck: true,
});
const ensureKey = () => {
if (!key) {
throw new Error(`Action "${normalizedAction}" requires -Key.`);
}
};
const ensureField = () => {
if (!field) {
throw new Error(`Action "${normalizedAction}" requires -Field.`);
}
};
const scanKeys = async (matchPattern) => {
let cursor = "0";
const result = [];
do {
const reply = await redis.scan(cursor, "MATCH", matchPattern, "COUNT", 200);
cursor = reply[0];
result.push(...reply[1]);
} while (cursor !== "0");
return result;
};
try {
let result;
switch (normalizedAction) {
case "get":
ensureKey();
result = await redis.get(key);
break;
case "set":
ensureKey();
if (value === undefined || value === null) {
throw new Error('Action "set" requires -Value.');
}
if (Number.isInteger(expireSeconds) && expireSeconds > 0) {
result = await redis.set(key, String(value), "EX", expireSeconds);
} else {
result = await redis.set(key, String(value));
}
break;
case "del":
ensureKey();
result = await redis.del(key);
break;
case "exists":
ensureKey();
result = await redis.exists(key);
break;
case "ttl":
ensureKey();
result = await redis.ttl(key);
break;
case "expire":
ensureKey();
if (!Number.isInteger(expireSeconds) || expireSeconds <= 0) {
throw new Error('Action "expire" requires -ExpireSeconds > 0.');
}
result = await redis.expire(key, expireSeconds);
break;
case "keys":
result = await scanKeys(pattern || "*");
break;
case "hget":
ensureKey();
ensureField();
result = await redis.hget(key, field);
break;
case "hset":
ensureKey();
ensureField();
if (value === undefined || value === null) {
throw new Error('Action "hset" requires -Value.');
}
result = await redis.hset(key, field, String(value));
break;
case "hdel":
ensureKey();
ensureField();
result = await redis.hdel(key, field);
break;
case "hgetall":
ensureKey();
result = await redis.hgetall(key);
break;
case "incr":
ensureKey();
result = await redis.incrby(key, Number.parseInt(value || "1", 10));
break;
case "decr":
ensureKey();
result = await redis.decrby(key, Number.parseInt(value || "1", 10));
break;
default:
throw new Error(`Unsupported action: ${normalizedAction}`);
}
process.stdout.write(JSON.stringify({
client: clientName,
action: normalizedAction,
key: key || null,
field: field || null,
pattern: normalizedAction === "keys" ? (pattern || "*") : null,
expireSeconds: Number.isInteger(expireSeconds) ? expireSeconds : null,
result,
}));
} finally {
redis.disconnect();
}
})().catch((err) => {
process.stderr.write(err && err.stack ? err.stack : String(err));
process.exit(1);
});
'@
$payload = @{
projectRoot = $projectRoot
configPath = $configResolved.Path
clientName = $RedisClient
action = $Action
key = $Key
value = $Value
field = $Field
expireSeconds = $ExpireSeconds
pattern = $Pattern
} | ConvertTo-Json -Compress
$payloadBytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
$payloadBase64 = [System.Convert]::ToBase64String($payloadBytes)
$tempFile = New-TemporaryFile
$tempNodeFile = [System.IO.Path]::ChangeExtension($tempFile.FullName, '.cjs')
Move-Item -Path $tempFile.FullName -Destination $tempNodeFile -Force
Set-Content -Path $tempNodeFile -Value $nodeScript -Encoding UTF8
try {
$json = & node $tempNodeFile $payloadBase64
if ($LASTEXITCODE -ne 0) {
throw "Node redis runner exited with code $LASTEXITCODE."
}
} finally {
Remove-Item -Path $tempNodeFile -ErrorAction SilentlyContinue
}
$result = $json | ConvertFrom-Json
Write-Host "Client: $($result.client)"
Write-Host "Action: $($result.action)"
if ($AsTable) {
if ($result.result -is [System.Array]) {
if ($result.result.Count -gt 0) {
$result.result | ForEach-Object { [PSCustomObject]@{ value = $_ } } | Format-Table -AutoSize
} else {
Write-Host 'No rows.'
}
} elseif ($result.result -is [PSCustomObject]) {
$result.result.psobject.Properties | ForEach-Object {
[PSCustomObject]@{ key = $_.Name; value = $_.Value }
} | Format-Table -AutoSize
} else {
Write-Host "Result: $($result.result)"
}
} else {
$result | ConvertTo-Json -Depth 20
}

View File

@ -75,6 +75,8 @@ function extractDefineFields(text) {
async function main() {
const root = process.cwd();
const tempDir = path.join(root, 'temp');
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
const projectRequire = createRequire(path.join(root, 'package.json'));
const mysql = projectRequire('mysql2/promise');
const cfgFactory = require(path.join(root, 'config', 'config.local.js'));
@ -160,9 +162,9 @@ async function main() {
schema: tableSchemas,
};
fs.writeFileSync(path.join(root, 'tmp-order-schema-compare.json'), JSON.stringify(out, null, 2));
fs.writeFileSync(path.join(tempDir, 'tmp-order-schema-compare.json'), JSON.stringify(out, null, 2));
await conn.end();
console.log('WROTE tmp-order-schema-compare.json');
console.log('WROTE temp/tmp-order-schema-compare.json');
}
main().catch(err => {

View File

@ -2,6 +2,7 @@
const path = require('path');
const root = process.cwd();
const tempDir = path.join(root, 'temp');
const serviceRoot = path.join(root, 'app', 'service');
function walk(dir) {
@ -93,5 +94,6 @@ for (const item of inventory) {
}
}
fs.writeFileSync(path.join(root, 'tmp-service-method-inventory.md'), md, 'utf8');
console.log('WROTE tmp-service-method-inventory.md');
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
fs.writeFileSync(path.join(tempDir, 'tmp-service-method-inventory.md'), md, 'utf8');
console.log('WROTE temp/tmp-service-method-inventory.md');

View File

@ -0,0 +1,116 @@
const fs = require('fs');
const path = require('path');
const root = process.cwd();
const defaultBaselinePath = path.join(root, 'temp', 'method-output', 'method-output-baseline.json');
const defaultTargetPath = path.join(root, 'temp', 'generated-tests', 'system.method-output.generated.test.js');
const legacyBaselinePath = path.join(root, 'run', 'method-output-baseline.json');
let baselinePath = process.argv[2]
? path.resolve(process.argv[2])
: defaultBaselinePath;
const targetPath = process.argv[3]
? path.resolve(process.argv[3])
: defaultTargetPath;
if (!process.argv[2] && !fs.existsSync(baselinePath) && fs.existsSync(legacyBaselinePath)) {
baselinePath = legacyBaselinePath;
}
const supportClientPath = path.relative(
path.dirname(targetPath),
path.join(root, 'test', 'support', 'system_method_client')
).replace(/\\/g, '/');
const supportRequirePath = supportClientPath.startsWith('.') ? supportClientPath : `./${supportClientPath}`;
const describePath = path.relative(root, targetPath).replace(/\\/g, '/');
if (!fs.existsSync(baselinePath)) {
console.error(`Baseline not found: ${baselinePath}`);
process.exit(1);
}
const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf8'));
const cases = Array.isArray(baseline.cases) ? baseline.cases : [];
const header = `// @eggjs-test-generated
// @purpose 接口返回数据一致性校验(自动生成,请勿手改)
// @source ${path.relative(root, baselinePath).replace(/\\/g, '/')}
// @generatedAt ${new Date().toISOString()}
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('${supportRequirePath}');
const VOLATILE_KEYS = new Set([
'timestamp',
'token',
'last_login_at',
'updated_at',
'update_at',
'created_at',
'create_at',
'login_time',
'iat',
'exp',
]);
function normalize(value) {
if (value === null || value === undefined) return value;
if (Array.isArray(value)) return value.map(item => normalize(item));
if (typeof value !== 'object') return value;
const out = {};
for (const key of Object.keys(value)) {
if (VOLATILE_KEYS.has(key)) {
out[key] = '__VOLATILE__';
continue;
}
out[key] = normalize(value[key]);
}
return out;
}
describe(${JSON.stringify(describePath)}, () => {
let token = '';
before(async () => {
const auth = await getAuthToken();
token = auth.token;
assert.ok(token, 'token should be available');
});
`;
const body = cases.map((item, idx) => {
const title = `[${idx + 1}] ${item.method} (sourceId=${item.sourceId})`;
const requestBody = JSON.stringify(item.requestBody || {}, null, 2);
const expected = JSON.stringify(item.normalized || {}, null, 2);
const platform = JSON.stringify((item.headers && item.headers.platform) || 'web');
const project = JSON.stringify((item.headers && item.headers.project) || 'wms');
return `
it(${JSON.stringify(title)}, async () => {
const res = await invokeSystemMethod(
${JSON.stringify(item.method)},
${requestBody},
token,
{ platform: ${platform}, project: ${project} }
);
assert.equal(res.status, ${Number(item.httpStatus || 200)});
const normalized = normalize(res.body);
const expected = ${expected};
assert.deepEqual(normalized, expected);
});
`;
}).join('\n');
const footer = `
});
`;
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
fs.writeFileSync(targetPath, header + body + footer, 'utf8');
console.log(`GENERATED ${targetPath}`);
console.log(`CASE_COUNT ${cases.length}`);

View File

@ -3,12 +3,12 @@ const path = require('path');
const root = process.cwd();
const target = path.join(root, 'AI_METHOD_ROUTING.md');
const inventoryPath = path.join(root, 'tmp-service-method-inventory.md');
const inventoryPath = path.join(root, 'temp', 'tmp-service-method-inventory.md');
const base = fs.readFileSync(target, 'utf8');
const inventory = fs.readFileSync(inventoryPath, 'utf8').trim();
const section = `\n\n## 6. 全量 Service Method 能力清单(自动扫描)\n\n维护说明:\n- 扫描范围:app/service/**/*.js\n- 本节内容由脚本生成,新增/修改 service 后请同步刷新。\n- 刷新命令:node .\\script\\tmp-gen-service-method-inventory.cjs\n\n<!-- SERVICE_METHOD_INVENTORY:BEGIN -->\n${inventory}\n<!-- SERVICE_METHOD_INVENTORY:END -->\n`;
const section = `\n\n## 6. 全量 Service Method 能力清单(自动扫描)\n\n维护说明:\n- 扫描范围:app/service/**/*.js\n- 本节内容由脚本生成,新增/修改 service 后请同步刷新。\n- 刷新命令:node .\\script\\tmp-gen-service-method-inventory.cjs\n- 临时清单输出:temp/tmp-service-method-inventory.md\n\n<!-- SERVICE_METHOD_INVENTORY:BEGIN -->\n${inventory}\n<!-- SERVICE_METHOD_INVENTORY:END -->\n`;
const begin = '<!-- SERVICE_METHOD_INVENTORY:BEGIN -->';
const end = '<!-- SERVICE_METHOD_INVENTORY:END -->';

85
table_schema_inventory.md Normal file
View File

@ -0,0 +1,85 @@
# table_schema_inventory
Updated: 2026-03-22
Database: wms
Object count: 70
## Summary
- Tables: 68
- Views: 2
## Objects
| object | type | engine | collation | rows | columns | pk_cols | auto_inc | index_count |
| --- | --- | --- | --- | ---: | ---: | ---: | ---: | ---: |
| SequelizeMeta | TABLE | InnoDB | utf8_unicode_ci | 7 | 1 | 1 | 0 | 2 |
| vw_warehouse_quota | VIEW | - | - | - | 5 | 0 | 0 | 0 |
| v_pick_space | VIEW | - | - | - | 44 | 0 | 0 | 0 |
| wms_account | TABLE | InnoDB | utf8mb4_general_ci | 2 | 13 | 1 | 1 | 5 |
| wms_account_login_log | TABLE | InnoDB | utf8mb4_general_ci | 108 | 7 | 1 | 1 | 2 |
| wms_account_platform_active | TABLE | InnoDB | utf8mb4_general_ci | 3 | 5 | 2 | 0 | 5 |
| wms_account_store_employee | TABLE | InnoDB | utf8mb4_general_ci | 5 | 8 | 1 | 1 | 5 |
| wms_api_app | TABLE | InnoDB | utf8mb4_unicode_ci | 4 | 22 | 1 | 1 | 6 |
| wms_api_log | TABLE | InnoDB | utf8mb4_general_ci | 421 | 10 | 1 | 1 | 1 |
| wms_embargo_policies | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 13 | 1 | 1 | 5 |
| wms_employee_role | TABLE | InnoDB | utf8mb4_general_ci | 4 | 3 | 1 | 1 | 4 |
| wms_entry_items | TABLE | InnoDB | utf8mb4_general_ci | 2 | 12 | 1 | 1 | 3 |
| wms_entry_order | TABLE | InnoDB | utf8mb4_unicode_ci | 5 | 28 | 1 | 1 | 10 |
| wms_express | TABLE | InnoDB | utf8mb4_general_ci | 0 | 2 | 1 | 0 | 1 |
| wms_express_print_record | TABLE | InnoDB | utf8mb4_general_ci | 0 | 31 | 1 | 1 | 13 |
| wms_express_setting | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 3 |
| wms_fast_where | TABLE | InnoDB | utf8mb4_general_ci | 38 | 9 | 1 | 1 | 1 |
| wms_file | TABLE | InnoDB | utf8mb4_unicode_ci | 5806 | 20 | 1 | 1 | 8 |
| wms_file_reference | TABLE | InnoDB | utf8mb4_unicode_ci | 8299 | 8 | 1 | 1 | 5 |
| wms_i18n_keys | TABLE | InnoDB | utf8mb4_general_ci | 182 | 10 | 1 | 1 | 4 |
| wms_i18n_translations | TABLE | InnoDB | utf8mb4_general_ci | 421 | 11 | 1 | 1 | 5 |
| wms_interface_type | TABLE | InnoDB | utf8mb4_unicode_ci | 2 | 9 | 1 | 1 | 2 |
| wms_location_space | TABLE | InnoDB | utf8mb4_general_ci | 1898 | 38 | 1 | 1 | 13 |
| wms_location_type | TABLE | InnoDB | utf8mb4_general_ci | 5 | 10 | 1 | 1 | 3 |
| wms_location_zone | TABLE | InnoDB | utf8mb4_general_ci | 20 | 30 | 1 | 1 | 10 |
| wms_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 2856 | 12 | 1 | 1 | 8 |
| wms_order_delivery | TABLE | InnoDB | utf8mb4_general_ci | 0 | 54 | 1 | 1 | 4 |
| wms_order_delivery_100000 | TABLE | InnoDB | utf8mb4_general_ci | 10 | 72 | 1 | 1 | 9 |
| wms_order_delivery_1000028 | TABLE | InnoDB | utf8mb4_general_ci | 0 | 72 | 1 | 1 | 9 |
| wms_order_express | TABLE | InnoDB | utf8mb4_general_ci | 0 | 13 | 1 | 1 | 2 |
| wms_order_express_print_data | TABLE | InnoDB | utf8mb4_general_ci | 0 | 6 | 1 | 1 | 2 |
| wms_order_items | TABLE | InnoDB | utf8mb4_general_ci | 0 | 15 | 1 | 1 | 2 |
| wms_order_items_100000 | TABLE | InnoDB | utf8mb4_unicode_ci | 11 | 18 | 1 | 1 | 9 |
| wms_order_items_1000028 | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 18 | 1 | 1 | 9 |
| wms_order_operation | TABLE | InnoDB | utf8mb4_general_ci | 0 | 1 | 1 | 1 | 1 |
| wms_order_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 15 | 1 | 1 | 6 |
| wms_order_picking | TABLE | InnoDB | utf8mb4_general_ci | 0 | 1 | 1 | 1 | 1 |
| wms_permission | TABLE | InnoDB | utf8mb4_general_ci | 40 | 15 | 1 | 1 | 4 |
| wms_picking_strategy | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 25 | 1 | 1 | 3 |
| wms_platform | TABLE | InnoDB | utf8mb4_general_ci | 13 | 3 | 1 | 0 | 1 |
| wms_platform_print_config | TABLE | InnoDB | utf8mb4_general_ci | 7 | 12 | 1 | 1 | 3 |
| wms_platfrom_setting | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 4 |
| wms_printer_config | TABLE | InnoDB | utf8mb4_general_ci | 0 | 11 | 1 | 1 | 4 |
| wms_print_batch | TABLE | InnoDB | utf8mb4_general_ci | 0 | 16 | 1 | 1 | 6 |
| wms_print_computer | TABLE | InnoDB | utf8mb4_general_ci | 0 | 4 | 1 | 1 | 1 |
| wms_print_items | TABLE | InnoDB | utf8mb4_general_ci | 39 | 24 | 1 | 1 | 5 |
| wms_print_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 12 | 1 | 1 | 5 |
| wms_print_record | TABLE | InnoDB | utf8mb4_general_ci | 277 | 13 | 1 | 1 | 6 |
| wms_print_stations | TABLE | InnoDB | utf8mb4_unicode_ci | 3 | 11 | 1 | 1 | 7 |
| wms_print_station_express | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 10 | 1 | 1 | 5 |
| wms_print_template | TABLE | InnoDB | utf8mb4_general_ci | 4 | 15 | 1 | 1 | 4 |
| wms_prohibited_type | TABLE | InnoDB | utf8mb4_unicode_ci | 13 | 9 | 1 | 1 | 4 |
| wms_qimen_apps | TABLE | InnoDB | utf8mb4_general_ci | 27 | 4 | 1 | 1 | 2 |
| wms_qimen_log | TABLE | InnoDB | utf8mb4_general_ci | 27756 | 14 | 1 | 1 | 1 |
| wms_receiving | TABLE | InnoDB | utf8mb4_unicode_ci | 43 | 25 | 1 | 1 | 9 |
| wms_receiving_detail | TABLE | InnoDB | utf8mb4_unicode_ci | 38 | 26 | 1 | 1 | 8 |
| wms_role | TABLE | InnoDB | utf8mb4_general_ci | 5 | 13 | 1 | 1 | 6 |
| wms_role_permission | TABLE | InnoDB | utf8mb4_general_ci | 72 | 4 | 1 | 1 | 4 |
| wms_stock_barcodes | TABLE | InnoDB | utf8mb4_unicode_ci | 25992 | 6 | 1 | 1 | 3 |
| wms_stock_store | TABLE | InnoDB | utf8mb4_unicode_ci | 472 | 34 | 1 | 1 | 11 |
| wms_stock_unit | TABLE | InnoDB | utf8mb4_general_ci | 11 | 4 | 1 | 1 | 3 |
| wms_stock_warehouse | TABLE | InnoDB | utf8mb4_unicode_ci | 25718 | 41 | 1 | 1 | 6 |
| wms_storage | TABLE | InnoDB | utf8mb4_unicode_ci | 0 | 20 | 1 | 1 | 8 |
| wms_store | TABLE | InnoDB | utf8mb4_unicode_ci | 121 | 20 | 1 | 1 | 5 |
| wms_store_join | TABLE | InnoDB | utf8mb4_unicode_ci | 4 | 14 | 1 | 1 | 7 |
| wms_store_warehouse | TABLE | InnoDB | utf8mb4_general_ci | 119 | 21 | 1 | 1 | 8 |
| wms_system_config | TABLE | InnoDB | utf8mb4_general_ci | 1 | 5 | 1 | 1 | 1 |
| wms_system_log | TABLE | InnoDB | utf8mb4_general_ci | 4591 | 14 | 1 | 1 | 2 |
| wms_wave_batch | TABLE | InnoDB | utf8mb4_general_ci | 0 | 20 | 1 | 1 | 5 |
| wms_wave_operation_log | TABLE | InnoDB | utf8mb4_general_ci | 0 | 11 | 1 | 1 | 5 |

View File

@ -1,43 +0,0 @@
const { strict: assert } = require('node:assert');
const { app } = require('egg-mock/bootstrap');
describe('test/app/controller/api_v2.test.js', () => {
before(() => {
// avoid database or factory initialization during tests
app.model = {};
});
it('dispatches a simple method and returns payload', async () => {
// mock dispatcher.invoke so we don't need real services or auth
app.mockService('dispatcher', 'invoke', async (method, data, auth, ctx) => {
// verify parameters arrived as expected
assert(method === 'index.fastWhereTree');
assert.deepEqual(data, { type: 'example' });
// return a fake successful response
return { isLog: true, result: { status: 200, data: { foo: 'bar', method } } };
});
const res = await app.httpRequest()
.post('/api/v2?method=index.fastWhereTree&v=1.0&format=json&timestamp=123')
.set('Content-Type', 'application/json')
.send({ type: 'example' })
.expect(200);
assert.deepEqual(res.body, { foo: 'bar', method: 'index.fastWhereTree' });
});
it('returns 401 when dispatcher.invoke throws (simulating auth failure)', async () => {
// simulate auth failure by making invoke return unauthorized
app.mockService('dispatcher', 'invoke', async () => {
return { isLog: false, result: { status: 401, message: 'Unauthorized' } };
});
const res = await app.httpRequest()
.post('/api/v2?method=index.fastWhereTree&v=1.0&format=json&timestamp=123')
.set('Content-Type', 'application/json')
.send({})
.expect(401); // controller forwards status from dispatcher
assert(res.body && res.body.message === 'Unauthorized');
});
});

View File

@ -17,7 +17,7 @@ describe('test/app/controller/home.test.js', () => {
it('should GET /', async () => {
return app.httpRequest()
.get('/')
.expect('hi, egg')
.expect('pong')
.expect(200);
});
});

View File

@ -0,0 +1,83 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
async function switchToWarehouseRoleWithOrderData(token) {
let currentToken = token;
const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id));
const candidateRoleIds = [ ...new Set([
...warehouseRoles.map(item => Number(item.id)),
...FALLBACK_ROLE_IDS,
].filter(Boolean)) ];
assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色');
for (const roleId of candidateRoleIds) {
const changeRes = await invokeSystemMethod('user.changeRole', {
roleId,
}, currentToken, EXTRA_HEADERS);
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) {
continue;
}
currentToken = changeRes.body?.data?.token || currentToken;
const statsRes = await invokeSystemMethod('order.stats', {
where: {},
}, currentToken, EXTRA_HEADERS);
assert.equal(statsRes.status, 200);
assert.equal(statsRes.body.flag, 'success');
assert.equal(statsRes.body.code, 200);
const total = Number(statsRes.body?.data?.total || 0);
if (total > 0) {
return {
token: currentToken,
};
}
}
throw new Error('未找到有订单数据的仓库角色');
}
describe('test/app/controller/system.order.getreviewOrderlist.test.js', () => {
it('should call order.getreviewOrderlist with platform=web project=all', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRoleWithOrderData(token);
const res = await invokeSystemMethod('order.getreviewOrderlist', {
pagination: {
page: 1,
pageSize: 10,
},
where: {},
}, switched.token, EXTRA_HEADERS);
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 200);
assert.ok(res.body.data);
assert.ok(Array.isArray(res.body.data.list));
assert.ok(res.body.data.pagination);
assert.equal(typeof res.body.data.pagination.total, 'number');
});
});

View File

@ -0,0 +1,143 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]);
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
async function switchToWarehouseRoleWithOrderData(token) {
let currentToken = token;
const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id));
const candidateRoleIds = [ ...new Set([
...warehouseRoles.map(item => Number(item.id)),
...FALLBACK_ROLE_IDS,
].filter(Boolean)) ];
assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色');
for (const roleId of candidateRoleIds) {
const changeRes = await invokeSystemMethod('user.changeRole', {
roleId,
}, currentToken, EXTRA_HEADERS);
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) {
continue;
}
currentToken = changeRes.body?.data?.token || currentToken;
const statsRes = await invokeSystemMethod('order.stats', {
where: {},
}, currentToken, EXTRA_HEADERS);
assert.equal(statsRes.status, 200);
assert.equal(statsRes.body.flag, 'success');
assert.equal(statsRes.body.code, 200);
const total = Number(statsRes.body?.data?.total || 0);
if (total > 0) {
return {
token: currentToken,
roleId,
total,
};
}
}
throw new Error('未找到有订单数据的仓库角色');
}
describe('test/app/controller/system.order.namespaced.test.js', () => {
it('should query all namespaced order lists', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRoleWithOrderData(token);
const methods = [
'order.reviewOrder.getreviewOrderlist',
'order.deliveryOrder.getdeliveryOrderlist',
'order.pendingOrder.getpendingOrderlist',
'order.expectionOrder.getexpectionOrderlist',
'order.archiveOrder.getarchiveOrderlist',
];
for (const method of methods) {
const res = await invokeSystemMethod(method, {
pagination: {
page: 1,
pageSize: 10,
},
where: {},
}, switched.token, EXTRA_HEADERS);
assert.equal(res.status, 200, `${method} http status 异常`);
assert.equal(res.body.flag, 'success', `${method} flag 异常`);
assert.equal(res.body.code, 200, `${method} code 异常`);
assert.ok(res.body.data, `${method} 缺少 data`);
assert.ok(Array.isArray(res.body.data.list), `${method} list 不是数组`);
assert.ok(res.body.data.pagination, `${method} 缺少 pagination`);
assert.equal(typeof res.body.data.pagination.total, 'number', `${method} total 不是 number`);
}
});
it('should review order through namespaced method and restore status', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRoleWithOrderData(token);
const listRes = await invokeSystemMethod('order.list', {
pagination: {
page: 1,
pageSize: 1,
},
where: {},
}, switched.token, EXTRA_HEADERS);
assert.equal(listRes.status, 200);
assert.equal(listRes.body.flag, 'success');
assert.equal(listRes.body.code, 200);
const order = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list[0] : null;
assert.ok(order, '订单列表为空,无法测试目录化 reviewOrder');
assert.ok(order.id, '订单缺少 id,无法测试目录化 reviewOrder');
const originalStatus = ALLOWED_REVIEW_STATUS.has(String(order.inspection_status || ''))
? String(order.inspection_status)
: 'none';
const targetStatus = originalStatus === 'fin' ? 'running' : 'fin';
const reviewRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', {
id: Number(order.id),
review_status: targetStatus,
}, switched.token, EXTRA_HEADERS);
assert.equal(reviewRes.status, 200);
assert.equal(reviewRes.body.flag, 'success');
assert.equal(reviewRes.body.code, 200);
assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id));
assert.equal(reviewRes.body?.data?.inspection_status, targetStatus);
const restoreRes = await invokeSystemMethod('order.reviewOrder.reviewOrder', {
id: Number(order.id),
review_status: originalStatus,
}, switched.token, EXTRA_HEADERS);
assert.equal(restoreRes.status, 200);
assert.equal(restoreRes.body.flag, 'success');
assert.equal(restoreRes.body.code, 200);
assert.equal(restoreRes.body?.data?.inspection_status, originalStatus);
});
});

View File

@ -0,0 +1,112 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const EXTRA_HEADERS = {
platform: 'web',
project: 'all',
};
const ALLOWED_REVIEW_STATUS = new Set([ 'none', 'padding', 'running', 'fin', 'error' ]);
const FALLBACK_ROLE_IDS = [ 4, 6, 30 ];
async function switchToWarehouseRoleWithOrderData(token) {
let currentToken = token;
const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : [];
const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id));
const candidateRoleIds = [ ...new Set([
...warehouseRoles.map(item => Number(item.id)),
...FALLBACK_ROLE_IDS,
].filter(Boolean)) ];
assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色');
for (const roleId of candidateRoleIds) {
const changeRes = await invokeSystemMethod('user.changeRole', {
roleId,
}, currentToken, EXTRA_HEADERS);
if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) {
continue;
}
currentToken = changeRes.body?.data?.token || currentToken;
const statsRes = await invokeSystemMethod('order.stats', {
where: {},
}, currentToken, EXTRA_HEADERS);
assert.equal(statsRes.status, 200);
assert.equal(statsRes.body.flag, 'success');
assert.equal(statsRes.body.code, 200);
const total = Number(statsRes.body?.data?.total || 0);
if (total > 0) {
return {
token: currentToken,
roleId,
total,
};
}
}
throw new Error('未找到有订单数据的仓库角色');
}
describe('test/app/controller/system.order.reviewOrder.test.js', () => {
it('should review order and restore inspection status', async () => {
const { token } = await getAuthToken();
const switched = await switchToWarehouseRoleWithOrderData(token);
const listRes = await invokeSystemMethod('order.list', {
pagination: {
page: 1,
pageSize: 1,
},
where: {},
}, switched.token, EXTRA_HEADERS);
assert.equal(listRes.status, 200);
assert.equal(listRes.body.flag, 'success');
assert.equal(listRes.body.code, 200);
const order = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list[0] : null;
assert.ok(order, '订单列表为空,无法测试 reviewOrder');
assert.ok(order.id, '订单缺少 id,无法测试 reviewOrder');
const originalStatus = ALLOWED_REVIEW_STATUS.has(String(order.inspection_status || ''))
? String(order.inspection_status)
: 'none';
const targetStatus = originalStatus === 'fin' ? 'running' : 'fin';
const reviewRes = await invokeSystemMethod('order.reviewOrder', {
id: Number(order.id),
review_status: targetStatus,
}, switched.token, EXTRA_HEADERS);
assert.equal(reviewRes.status, 200);
assert.equal(reviewRes.body.flag, 'success');
assert.equal(reviewRes.body.code, 200);
assert.equal(Number(reviewRes.body?.data?.id || 0), Number(order.id));
assert.equal(reviewRes.body?.data?.inspection_status, targetStatus);
const restoreRes = await invokeSystemMethod('order.reviewOrder', {
id: Number(order.id),
review_status: originalStatus,
}, switched.token, EXTRA_HEADERS);
assert.equal(restoreRes.status, 200);
assert.equal(restoreRes.body.flag, 'success');
assert.equal(restoreRes.body.code, 200);
assert.equal(restoreRes.body?.data?.inspection_status, originalStatus);
});
});

View File

@ -0,0 +1,98 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const RUNTIME_FILE = path.join(process.cwd(), 'test', '.runtime', 'system_user_change_role_web_all.json');
function saveRuntime(payload) {
fs.mkdirSync(path.dirname(RUNTIME_FILE), { recursive: true });
fs.writeFileSync(RUNTIME_FILE, JSON.stringify(payload, null, 2), 'utf8');
}
describe('test/app/controller/system.user.changeRole.test.js', () => {
it('should switch role via user.changeRole and persist response', async () => {
const { token } = await getAuthToken();
const beforeInfoRes = await invokeSystemMethod('user.info', {}, token, {
platform: 'web',
project: 'all',
});
assert.equal(beforeInfoRes.status, 200);
assert.equal(beforeInfoRes.body.flag, 'success');
assert.equal(beforeInfoRes.body.code, 200);
const beforeData = beforeInfoRes.body.data || {};
const employees = Array.isArray(beforeData.employees) ? beforeData.employees : [];
const currentRoleId = Number(beforeData.employees_id || 0);
const target = employees.find(item => Number(item.id) && Number(item.id) !== currentRoleId)
|| employees.find(item => Number(item.id));
assert.ok(target, '当前账号没有可用于切换的角色');
const changeRoleRes = await invokeSystemMethod('user.changeRole', {
roleId: Number(target.id),
}, token, {
platform: 'web',
project: 'all',
});
assert.equal(changeRoleRes.status, 200);
assert.equal(changeRoleRes.body.flag, 'success');
assert.equal(changeRoleRes.body.code, 200);
assert.equal(changeRoleRes.body.success, true);
assert.ok(changeRoleRes.body.data);
assert.ok(changeRoleRes.body.data.token);
const switchedToken = changeRoleRes.body.data.token;
const afterInfoRes = await invokeSystemMethod('user.info', {}, switchedToken, {
platform: 'web',
project: 'all',
});
assert.equal(afterInfoRes.status, 200);
assert.equal(afterInfoRes.body.flag, 'success');
assert.equal(afterInfoRes.body.code, 200);
assert.equal(Number(afterInfoRes.body.data.employees_id || 0), Number(target.id));
saveRuntime({
savedAt: new Date().toISOString(),
method: 'user.changeRole',
headers: {
platform: 'web',
project: 'all',
},
before: {
employees_id: currentRoleId,
employees_count: employees.length,
},
targetRoleId: Number(target.id),
response: changeRoleRes.body,
verify: {
employees_id: Number(afterInfoRes.body.data.employees_id || 0),
},
});
assert.equal(fs.existsSync(RUNTIME_FILE), true);
// 尽量恢复原角色,避免影响其他测试。
if (currentRoleId && currentRoleId !== Number(target.id)) {
const restoreRes = await invokeSystemMethod('user.changeRole', {
roleId: currentRoleId,
}, switchedToken, {
platform: 'web',
project: 'all',
});
assert.equal(restoreRes.status, 200);
assert.equal(restoreRes.body.flag, 'success');
assert.equal(restoreRes.body.code, 200);
}
});
});

View File

@ -0,0 +1,21 @@
'use strict';
const assert = require('node:assert/strict');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
describe('test/app/controller/system.user.info.test.js', () => {
it('should call user.info with bearer token', async () => {
const { token } = await getAuthToken();
const infoRes = await invokeSystemMethod('user.info', {}, token);
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
assert.ok(infoRes.body.data);
assert.equal(infoRes.body.data.id, 1);
assert.equal(infoRes.body.data.platform_code, 'web');
});
});

View File

@ -0,0 +1,45 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const {
getAuthToken,
invokeSystemMethod,
} = require('../../support/system_method_client');
const RUNTIME_FILE = path.join(process.cwd(), 'test', '.runtime', 'system_user_info_web_all.json');
function saveRuntime(payload) {
fs.mkdirSync(path.dirname(RUNTIME_FILE), { recursive: true });
fs.writeFileSync(RUNTIME_FILE, JSON.stringify(payload, null, 2), 'utf8');
}
describe('test/app/controller/system.user.info.web.test.js', () => {
it('should call user.info with platform=web project=all and persist response', async () => {
const { token } = await getAuthToken();
const infoRes = await invokeSystemMethod('user.info', {}, token, {
platform: 'web',
project: 'all',
});
assert.equal(infoRes.status, 200);
assert.equal(infoRes.body.flag, 'success');
assert.equal(infoRes.body.code, 200);
assert.ok(infoRes.body.data);
assert.equal(infoRes.body.data.platform_code, 'web');
assert.ok(Array.isArray(infoRes.body.data.employees));
saveRuntime({
savedAt: new Date().toISOString(),
method: 'user.info',
headers: {
platform: 'web',
project: 'all',
},
response: infoRes.body,
});
assert.equal(fs.existsSync(RUNTIME_FILE), true);
});
});

View File

@ -0,0 +1,35 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const { getAuthToken, TOKEN_FILE } = require('../../support/system_method_client');
describe('test/app/controller/system.user.login.test.js', () => {
it('should get token from cache or login method', async () => {
const { token, fromCache } = await getAuthToken();
assert.equal(typeof token, 'string');
assert.ok(token.length > 20);
assert.equal(typeof fromCache, 'boolean');
});
it('should persist token cache file', async () => {
assert.equal(fs.existsSync(TOKEN_FILE), true);
});
it('user.login should return token only', async () => {
const { invokeSystemMethod, USERNAME } = require('../../support/system_method_client');
const password = process.env.SYSTEM_TEST_PASSWORD || '111111';
const loginRes = await invokeSystemMethod('user.login', {
username: USERNAME,
password,
});
assert.equal(loginRes.status, 200);
assert.equal(loginRes.body.flag, 'success');
assert.equal(loginRes.body.code, 200);
assert.equal(typeof loginRes.body.data?.token, 'string');
assert.equal(loginRes.body.data?.user, undefined);
});
});

View File

@ -0,0 +1,52 @@
'use strict';
const assert = require('node:assert/strict');
const { invokeSystemMethod } = require('../../support/system_method_client');
const VALID_LOGIN_CODE = process.env.SYSTEM_TEST_LOGIN_CODE
|| 'eyJ1dWlkIjoiMDg2MTk4MzQtY2FhYS00OTIyLWJmNjctODc5M2U2Y2MwYzJkIn0=';
describe('test/app/controller/system.user.loginByCode.test.js', () => {
it('should login successfully when code is valid', async () => {
const res = await invokeSystemMethod('user.loginByCode', {
code: VALID_LOGIN_CODE,
});
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'success');
assert.equal(res.body.code, 200);
assert.equal(res.body.success, true);
assert.equal(typeof res.body.data?.token, 'string');
assert.ok(res.body.data.token.length > 20);
assert.equal(typeof res.body.data?.user?.id, 'number');
});
it('should fail when code is missing', async () => {
const res = await invokeSystemMethod('user.loginByCode', {});
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'failure');
assert.equal(res.body.code, 0);
assert.match(String(res.body.message || ''), /code/);
});
it('should fail when code is not valid base64 json', async () => {
const code = `INVALID_CODE_${Date.now()}`;
const res = await invokeSystemMethod('user.loginByCode', { code });
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'failure');
assert.equal(res.body.code, 0);
assert.match(String(res.body.message || ''), /无效的登录码格式/);
});
it('should fail when decoded payload does not contain uuid', async () => {
const code = Buffer.from(JSON.stringify({ foo: 'bar' }), 'utf8').toString('base64');
const res = await invokeSystemMethod('user.loginByCode', { code });
assert.equal(res.status, 200);
assert.equal(res.body.flag, 'failure');
assert.equal(res.body.code, 0);
assert.match(String(res.body.message || ''), /uuid/);
});
});

View File

@ -0,0 +1,137 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const assert = require('node:assert/strict');
const BASE_URL = process.env.SYSTEM_TEST_BASE_URL || 'http://127.0.0.1:6060';
const TOKEN_FILE = process.env.SYSTEM_TEST_TOKEN_FILE
|| path.join(process.cwd(), 'test', '.runtime', 'system_user_token.json');
const USERNAME = process.env.SYSTEM_TEST_USERNAME || 'liufumingren';
const PASSWORD = process.env.SYSTEM_TEST_PASSWORD || '111111';
function nowSec() {
return Math.floor(Date.now() / 1000);
}
function decodeJwtPayload(token) {
try {
const payloadSegment = token.split('.')[1];
if (!payloadSegment) return null;
const normalized = payloadSegment.replace(/-/g, '+').replace(/_/g, '/');
const padded = normalized + '='.repeat((4 - normalized.length % 4) % 4);
return JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
} catch {
return null;
}
}
function isTokenUsable(token) {
if (!token) return false;
const payload = decodeJwtPayload(token);
if (!payload || !payload.exp) return false;
return payload.exp - nowSec() > 120;
}
function readCachedToken() {
if (!fs.existsSync(TOKEN_FILE)) return null;
try {
const content = fs.readFileSync(TOKEN_FILE, 'utf8');
const parsed = JSON.parse(content);
const token = parsed && parsed.token;
return isTokenUsable(token) ? token : null;
} catch {
return null;
}
}
function writeCachedToken(token) {
fs.mkdirSync(path.dirname(TOKEN_FILE), { recursive: true });
const payload = decodeJwtPayload(token);
const record = {
token,
username: USERNAME,
cachedAt: new Date().toISOString(),
exp: payload && payload.exp ? payload.exp : null,
};
fs.writeFileSync(TOKEN_FILE, JSON.stringify(record, null, 2), 'utf8');
}
async function invokeSystemMethod(method, body = {}, token, extra = {}) {
const timestamp = nowSec();
const url = `${BASE_URL}/system?method=${encodeURIComponent(method)}&v=1.0&timestamp=${timestamp}`;
const platform = extra && extra.platform ? extra.platform : 'web';
const project = extra && extra.project ? extra.project : 'wms';
const headers = {
platform,
project,
'Content-Type': 'application/json',
};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(body),
});
const text = await response.text();
let json;
try {
json = JSON.parse(text);
} catch {
throw new Error(`Invalid JSON from ${method}: ${text}`);
}
return {
status: response.status,
body: json,
};
}
async function getAuthToken(options = {}) {
const { forceLogin = false } = options;
if (!forceLogin) {
const cached = readCachedToken();
if (cached) {
return { token: cached, fromCache: true };
}
}
const loginRes = await invokeSystemMethod('user.login', {
username: USERNAME,
password: PASSWORD,
});
assert.equal(loginRes.status, 200, 'user.login should return HTTP 200');
assert.equal(loginRes.body.flag, 'success', `user.login should succeed: ${JSON.stringify(loginRes.body)}`);
const token = loginRes.body
&& loginRes.body.data
&& loginRes.body.data.token;
assert.ok(token, 'user.login response should contain token');
writeCachedToken(token);
return {
token,
fromCache: false,
};
}
module.exports = {
BASE_URL,
TOKEN_FILE,
USERNAME,
invokeSystemMethod,
getAuthToken,
readCachedToken,
};

File diff suppressed because it is too large Load Diff

View File

@ -27,7 +27,7 @@
## 4. 已生成产物
- 结构与差异总结果: tmp-order-schema-compare.json
- 结构与差异总结果: temp/tmp-order-schema-compare.json
- 比对脚本(可复跑): script/tmp-compare-order-schema.cjs
## 5. 关键比对结论
@ -68,7 +68,7 @@ node .\script\tmp-compare-order-schema.cjs
### 6.2 快速查看结果摘要
PowerShell:
Get-Content .\tmp-order-schema-compare.json -TotalCount 160
Get-Content .\temp\tmp-order-schema-compare.json -TotalCount 160
## 7. 后续建议

View File

@ -1,105 +0,0 @@
自动生成时间: 2026-03-22T09:03:11.802Z
扫描范围: app/service/**/*.js
文件数: 50
- app/service/api.js (1)
- callMethod
- app/service/apiMethods/test.js (4)
- entryorderConfirm, playbackRequest, fibonacci, fibonacciRecursive
- app/service/dispatcher.js (3)
- buildMap, getMethodMap, invoke
- app/service/main.js (11)
- success, fail, normalizeDate, setInfo, getInfo, findQimenAppWithContract, queryFromDatabase, checkAuth, checkApiPermission, setUserContext, systemInit
- app/service/pda.js (3)
- callMethod, validateParams, saveLog
- app/service/qimen.js (12)
- validateApi, getErpName, parseXmlToArray, cleanXmlString, callMethod, formatResponse, xmlResponse, buildXmlNode, escapeXml, saveQimenLog, saveQimenLogResult, saveQimenLogBody
- app/service/qimenMethods/deliveryorder.js (3)
- query, create, batchcreate
- app/service/qimenMethods/entryorder.js (2)
- create, query
- app/service/qimenMethods/inventory.js (1)
- query
- app/service/qimenMethods/order.js (2)
- cancel, pending
- app/service/qimenMethods/returnorder.js (2)
- create, query
- app/service/qimenMethods/singleitem.js (2)
- synchronize, query
- app/service/qimenMethods/stockout.js (2)
- create, query
- app/service/qimenMethods/taobao/qimen/service.js (1)
- heartbeat
- app/service/system.js (3)
- callMethod, validateParams, saveLog
- app/service/systemMethods/config.js (1)
- list
- app/service/systemMethods/dashboard.js (6)
- storeStats, warehouseStats, hot_order_rank, express_ratio, platform_distribution, order_trend
- app/service/systemMethods/index.js (13)
- fastWhereTree, loadStores, getCOSUploadConfig, getImages, uploadSuccessNotify, ReferenceFile, getMessageDetail, getI18nMessage, putI18nCollect, extractModule, tryAutoTranslateNewKeys, searchSpace, getExpressList
- app/service/systemMethods/order.js (11)
- getWarehouseId, getOrderModels, applyDateRange, buildWhere, parseDateTime, list, detail, listItems, stats, updateStatus, updateDeliveryTime
- app/service/systemMethods/print.js (3)
- send, sendToComputer, log
- app/service/systemMethods/printer/station.js (1)
- list
- app/service/systemMethods/setting/printTemplate.js (3)
- list, save, listTemplatesByType
- app/service/systemMethods/stock.js (21)
- stockWarehouse, getProhibitedType, getInfo, saveWarehouseStock, createWarehouseStock, getBarcodes, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, checkItemCodeUnique, queryStockLogs, handleBatchDelete, deleteUnit, deleteProhibited, handleBatchChange, getStockUnits, getUnitList, createProhibited, createUnit, search
- app/service/systemMethods/storage/receiving.js (13)
- getReceivingList, getReceivingDetail, batchCancelReceiving, create, addItem, removeItem, saveReceiving, get, addDetail, deleteDetail, detailChange, cancel, completeReceiving
- app/service/systemMethods/store.js (6)
- createStore, createWarehouse, joinStore, joinWarehouse, getStoreRoles, auditApply
- app/service/systemMethods/user.js (5)
- login, logout, info, changeRole, register
- app/service/systemMethods/warehouse.js (20)
- getWarehouseZones, getWarehouseTree, getChildren, create, update, delete, detail, checkBarcodeUnique, toggleActive, getPath, createRack, getPickPath, updateRackPosition, recalculatePickPath, updateNeighbors, getAreaRacks, getSpacesByRack, createRackWithSpaces, getSpaceInfo, updateSpaceInfo
- app/service/systems/account_platform.js (8)
- switchActiveRole, getActiveRoleByPlatform, getMultiplePlatformActiveRoles, getAllPlatformActives, clearPlatformActive, clearPlatformCache, getAvailableRoles, getCurrentContext
- app/service/systems/auth/user.js (21)
- login, ID, changeRole, info, getRoles, findById, setUserCache, getAvatarByEmployeeId, clearUserCache, clearRelatedCache, getPermissions, getMenus, convertToRoutes, findUserByIdentifier, checkUserStatus, verifyPassword, encryptPassword, generateSalt, updateLastLoginTime, ensurePlatformActiveRole, register
- app/service/systems/delivery_order.js (7)
- addOrder, generateItemsHash, calculateCRC32, prepareOrderData, addOrderLines, safeParseFloat, addOrderToQueue
- app/service/systems/entry_order.js (9)
- addOrder, getLineCount, received, success, fail, tryCreateEntryOrder, addItems, qimenEntryorderConfirm, entryorderConfirm
- app/service/systems/fast_where.js (13)
- buildTree, getTreeByType, buildSubTree, getWithChildrenByType, getAllChildren, getByType, getGroups, getChildrenByPid, getTreeChildrenByPid, create, update, findById, delete
- app/service/systems/file.js (2)
- getImages, ReferenceFile
- app/service/systems/location_space.js (16)
- create, batchCreate, list, detail, update, delete, toggleStatus, updateStatus, findAvailableSpaces, findByCode, findByBarcode, getWarehouseStats, getZoneStats, validateAllocation, validateTransferOut, _validateReferences
- app/service/systems/location_zone.js (22)
- getWarehouseLevelZones, getZoneTreeByWarehouse, getChildrenByZoneId, isLeafNode, createZone, validateBasicFields, validateByZoneType, validateParentElement, validateZoneOverlap, isOverlap, generateZoneCodeByType, getDefaultColorByType, getZoneTypeText, updateZone, deleteZone, checkZoneOverlap, getZoneDetail, toggleZoneActive, getZonePath, generateSpacesForRack, getSpaceInfo, checkBarcodeUnique
- app/service/systems/location.js (10)
- createRackWithSpaces, _generateSpacesForRack, _calculateAreaRackOrder, _calculatePickPathForWarehouse, _updateSpacePickSequence, _calculatePickPriority, updateRackPosition, getPickPath, updateNeighborRelations, _findNeighborRacks
- app/service/systems/notification.js (1)
- send
- app/service/systems/operation_log.js (4)
- createOperationLog, queryStockLogs, queryOrderLogs, getMessageDetail
- app/service/systems/platform.js (6)
- checkPlatformExists, getPlatformInfo, clearPlatformCache, getPlatformSettingDetail, batchCheckPlatforms, createPlatformSetting
- app/service/systems/polo_api.js (6)
- getJsonDatas, getJsonData, getSignText, md5Encrypt, _formatDate, _formatPickupDate
- app/service/systems/print/index.js (2)
- sendToComputer, test
- app/service/systems/qimen_query.js (6)
- send, replaceXmlTagsWithString, addSign, getQueryParams, generateUrlWithParams, sendRequest
- app/service/systems/setting/print_template.js (14)
- listTemplatesByType, getTree, getTemplatesByType, save, getBusinessTypesAndItem, getGroupedPrintItems, getTableConfigs, clearBusinessTypesCache, getXmlByTemplate, buildXmlFromElements, renderElement, computeItemStyle, computeTableItemStyle, renderTable
- app/service/systems/sign.js (10)
- Constants, toXml, signTopRequest, verifyTopRequest, verifyAndExtractParams, generateSignedParams, encryptHMAC, encryptHMACSHA256, encryptMD5, byte2hex
- app/service/systems/space.js (1)
- searchSpace
- app/service/systems/stock_store.js (34)
- create, initQimenStockData, convertToQimenFormat, getItemInfoWithCache, getItemStorages, _calculateCacheTTL, clearItemStorageCache, lockItemStorages, ID, inbound, outbound, checkAndCreateWarehouseStock, getWarehouseStock, buildSequelizeCondition, processConditionValue, formatDate, isEmptyValue, getProhibitedType, getBarcodes, handleBatchChange, saveWarehouseStockBarcode, getStoreStocks, bindItem, unbindItem, getInfo, saveWarehouseStock, createWarehouseStock, validateSaveParams, stockLog, checkItemCodeUnique, handleBatchDelete, deleteUnit, deleteProhibited, search
- app/service/systems/storage/index.js (1)
- index
- app/service/systems/storage/receiving.js (16)
- getReceivingList, getReceivingDetail, batchCancelReceiving, isEmptyValue, buildSequelizeCondition, processConditionValue, create, get, addDetail, updateDetail, getStockStoreInfo, updateReceivingStats, deleteDetail, detailChange, invalid, completeReceiving
- app/service/systems/store.js (13)
- getStoreName, getStoreRemaskName, createStore, createWarehouse, joinStore, joinWarehouse, assignAdminRoleToCreator, generateJoinToken, sendNotification, sendNotificationToAdmins, getStoreRoles, auditApply, loadStores
- app/service/systems/upload.js (14)
- initCOS, getUploadParams, hash_hmac, validateFileInfo, generateFileName, parseSizeToBytes, formatFileSize, getFrontendConfig, uploadFile, validateFile, uploadSuccessNotify, getMimeType, createFileReference, handleUploadCallback