feat: refine setting role/account/permission auth and tests
This commit is contained in:
parent
2f838186de
commit
920d201c0e
@ -3,8 +3,8 @@
|
||||
const path = require('path');
|
||||
|
||||
module.exports = {
|
||||
"config": path.join(__dirname, 'database/config.json'),
|
||||
"migrations-path": path.join(__dirname, 'database/migrations'),
|
||||
"seeders-path": path.join(__dirname, 'database/seeders'),
|
||||
"models-path": path.join(__dirname, 'app/model'),
|
||||
config: path.join(__dirname, 'database/config.js'),
|
||||
'migrations-path': path.join(__dirname, 'database/migrations'),
|
||||
'seeders-path': path.join(__dirname, 'database/seeders'),
|
||||
'models-path': path.join(__dirname, 'app/model'),
|
||||
};
|
||||
@ -1,6 +1,6 @@
|
||||
# AI 工具箱(WMS)
|
||||
|
||||
本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。
|
||||
本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。AI每次应答文尾加喵~以判断是否丢失上下文
|
||||
|
||||
## 1. 适用范围
|
||||
|
||||
@ -591,4 +591,46 @@ npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/contr
|
||||
- `print.getList`
|
||||
- `storage.entry.list`
|
||||
- `stock.warehouse.list`
|
||||
|
||||
## 15. system API 权限映射规则(wms_permission)
|
||||
|
||||
适用范围:`/system` 入口,权限类型为 `type=api`。
|
||||
|
||||
### 15.1 映射规则
|
||||
|
||||
- `wms_permission.path` 作为 system method 的权限标识(例如:`setting.account.list`)。
|
||||
- 同步来源以 `methods/system.json` 为准:`isNeedAuth=true` 的 method 必须存在对应 `wms_permission(type=api,path=method)`。
|
||||
- 角色权限不再以 `wms_role_permission` 作为主存储,统一写入 `wms_role.permissions`。
|
||||
- `wms_role.permissions` 支持两种值:
|
||||
- JSON 数组:如 `[1,2,3]`
|
||||
- `"*"`:表示拥有所有权限
|
||||
- 新增 API 权限后,`role_id=2` 的授权应同步更新其 `permissions` 字段;若该字段为 `"*"` 则无需额外追加。
|
||||
|
||||
### 15.2 外部脚本(批量补齐)
|
||||
|
||||
固定命令:
|
||||
|
||||
```powershell
|
||||
# 预览差异(不写库)
|
||||
npm run permission:sync:system-api -- --dry-run
|
||||
|
||||
# 执行补齐(写库)
|
||||
npm run permission:sync:system-api
|
||||
```
|
||||
|
||||
可选参数:
|
||||
|
||||
- `--role-id=2`:绑定角色 ID(默认 `2`)
|
||||
- `--db-client=wms`:数据库客户端名(默认 `wms`)
|
||||
- `--config-path=./config/config.local.js`:配置文件路径
|
||||
- `--method-doc=./methods/system.json`:method 文档路径
|
||||
|
||||
### 15.3 运行时兜底(仅 debug)
|
||||
|
||||
- 入口:`app/service/main.js` 的 `checkApiPermission`。
|
||||
- 逻辑:当用户权限列表不包含目标 method 时,若 `app.config.debug === true`,自动:
|
||||
1. 参考现有 `type=api` 权限行构建缺失权限行;
|
||||
2. 更新 `wms_role(id=2).permissions`,将新权限 ID 追加到 JSON 数组;若该字段为 `"*"` 则保持不变。
|
||||
- 生产建议:保持 `app.config.debug=false`,避免运行时自动写库。
|
||||
|
||||
|
||||
391
README.md
391
README.md
@ -1,12 +1,11 @@
|
||||
# 奇门WMS(qimen-wms)
|
||||
|
||||
基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。基于AI协助管理项目开发,配置了AI能力脚本和完整的项目地图
|
||||
基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。
|
||||
|
||||
## 文档导航
|
||||
|
||||
- AI项目协作工具箱:`AI_TOOLBOX.md`
|
||||
- 项目协作工具箱:`AI_TOOLBOX.md`
|
||||
- Method 路由映射说明:`AI_METHOD_ROUTING.md`
|
||||
- stock.warehouse.list 前端查询规则:`docs/stock-stockWarehouse-query-rules.md`
|
||||
- system 接口文档源:`methods/system.json`
|
||||
- qimen 接口文档源:`methods/qimen.json`
|
||||
- 日报:`day.log`
|
||||
@ -24,7 +23,6 @@
|
||||
├── config/ # 配置(poloapi、redis、数据库等)
|
||||
├── database/ # 迁移与数据库配置
|
||||
├── methods/ # 接口文档数据源(JSON)
|
||||
├── native/ # 原生扩展目录(Node.js C++ addon)
|
||||
├── script/ # 调试与文档生成脚本
|
||||
├── logs/ # 日志
|
||||
├── run/ # 运行时/元数据
|
||||
@ -39,7 +37,6 @@
|
||||
- `README.md`:项目入口文档,提供整体说明与规范入口。
|
||||
- `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。
|
||||
- `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。
|
||||
- `docs/stock-stockWarehouse-query-rules.md`:stock.warehouse.list 的 where 构造规则与失败返回说明。
|
||||
- `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。
|
||||
- `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。
|
||||
- `day.log`:每日工作留痕。
|
||||
@ -57,121 +54,10 @@ npm run dev
|
||||
|
||||
- `npm run dev`:本地开发
|
||||
- `npm start`:启动生产服务
|
||||
- `npm stop`:仅停止当前目录对应的 Egg 生产进程
|
||||
- `npm run deploy:prod`:按 `config/deploy.config.local.cjs` 通过 SSH 发布到生产目录 `/www/wwwroot/qimen`
|
||||
- `npm run deploy:init`:首次发布初始化远端目录与 `config/` 基础文件(不覆盖已有配置)
|
||||
- `npm run rollback:prod`:按最近一次备份回退生产目录(可加 `-- --backup=backup-时间戳.tar.gz` 指定备份)
|
||||
- `npm run deploy:precheck`:只读预检 SSH 连通、目录权限、远端 Node/npm/tar 与健康检查,不改动远端文件
|
||||
- `npm run deploy:version`:查询当前线上版本号(读取远端 `.deploy/state/current-release.json`)
|
||||
- `npm run deploy:version:history`:查询最近 20 次线上版本历史
|
||||
- `npm run deploy:inspect`:查看远端 `.deploy/state`、`latest-backup.txt` 与备份目录清单
|
||||
- `npm run deploy:smoke`:在远端机器本机对 `/`、`/api/docs`、`/internal/v1/gateway`、`/system` 做最小连通冒烟
|
||||
- `npm run deploy:verify`:组合执行 `deploy:inspect` + `deploy:smoke`
|
||||
- `npm run deploy:cleanup-backups -- <backup-file...>`:按文件名清理远端 `.deploy/backups` 中指定备份
|
||||
- `npm run deploy:gateway-probe -- <method> [payloadJson]`:调用 `/internal/v1/gateway` 做 method 级连通探针
|
||||
- `npm run version:record`:记录一次本地包版本快照(写入 `versioning/`,用于回退追溯)
|
||||
- `npm run version:history`:查询最近 50 条本地版本快照记录
|
||||
- `npm run guard:git`:检查当前暂存区是否包含禁止提交的本地机密/运行产物
|
||||
- `npm run setup:hooks`:将仓库 pre-commit hook 固化到 `.githooks/pre-commit`
|
||||
- `npm stop`:停止生产服务
|
||||
- `npm run lint`:代码风格检查
|
||||
- `npm test`:单元测试
|
||||
|
||||
## 外部 Method 测试(Egg.js test 规范)
|
||||
|
||||
测试文件按“暴露出口 + method”命名,位于 `test/app/controller/`:
|
||||
|
||||
- `system.user.login.test.js`
|
||||
- `system.user.info.test.js`
|
||||
|
||||
测试辅助客户端位于:
|
||||
|
||||
- `test/support/system_method_client.js`
|
||||
|
||||
默认测试账号(可通过环境变量覆盖):
|
||||
|
||||
- `SYSTEM_TEST_USERNAME=liufumingren`
|
||||
- `SYSTEM_TEST_PASSWORD=111111`
|
||||
|
||||
Token 暂存机制:
|
||||
|
||||
- 登录 token 会写入 `test/.runtime/system_user_token.json`。
|
||||
- 每次执行测试会优先读取本地 token;若 token 可用,则跳过 `user.login` 调用。
|
||||
- 当 token 不存在或过期时,测试脚本会自动调用 `user.login` 并刷新缓存。
|
||||
|
||||
常用命令:
|
||||
|
||||
```bash
|
||||
npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js
|
||||
```
|
||||
|
||||
可选环境变量:
|
||||
|
||||
- `SYSTEM_TEST_BASE_URL`:默认 `http://127.0.0.1:6060`
|
||||
- `SYSTEM_TEST_TOKEN_FILE`:默认 `test/.runtime/system_user_token.json`
|
||||
|
||||
## Method 输出一致性回归(新规则)
|
||||
|
||||
目标:
|
||||
|
||||
- 在模型/关联/服务改动前后,确保关键 method 输出结果一致。
|
||||
|
||||
强制规则:
|
||||
|
||||
1. 改动前先执行 baseline(生成修改前输出快照)。
|
||||
2. 改动后执行 compare(对同一批 method 回放并比对)。
|
||||
3. compare 结果必须 `mismatch=0` 才可交付。
|
||||
|
||||
测试账号(默认):
|
||||
|
||||
- `liufumingren / 111111`
|
||||
- 可通过环境变量覆盖:
|
||||
- `WMS_TEST_USER`
|
||||
- `WMS_TEST_PASS`
|
||||
|
||||
method 来源与样本来源:
|
||||
|
||||
- method 配置来源:`methods/system.json`
|
||||
- 样本数据来源(优先最新日志):`wms_system_log`
|
||||
- 参考日志来源:`wms_api_log`、`wms_operation_log`、`wms_account_login_log`
|
||||
|
||||
执行脚本:
|
||||
|
||||
- `script/method-output-regression.cjs`
|
||||
- `script/tmp-generate-method-regression-test.cjs`(根据 baseline 自动生成 Egg.js 标注测试)
|
||||
|
||||
临时文件目录规则:
|
||||
|
||||
- 所有临时产物统一输出到 `temp/`。
|
||||
- `temp/` 已加入 git 忽略,不纳入提交。
|
||||
|
||||
执行命令:
|
||||
|
||||
```powershell
|
||||
# 修改前:生成基线(默认抽样 8 条)
|
||||
node .\script\method-output-regression.cjs baseline 8
|
||||
|
||||
# 修改后:执行对比
|
||||
node .\script\method-output-regression.cjs compare
|
||||
|
||||
# 生成 Egg.js 标注测试脚本
|
||||
node .\script\tmp-generate-method-regression-test.cjs
|
||||
|
||||
# 执行生成的回归测试
|
||||
npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
|
||||
```
|
||||
|
||||
输出文件:
|
||||
|
||||
- `temp/method-output/method-output-baseline.json`
|
||||
- `temp/method-output/method-output-baseline.md`
|
||||
- `temp/method-output/method-output-compare.json`
|
||||
|
||||
一致性比对说明:
|
||||
|
||||
- 为避免误报,脚本会标准化以下波动字段:`token`、`timestamp`、`last_login_at`、`created_at`、`updated_at`、`iat`、`exp`。
|
||||
- 403 权限响应同样参与一致性对比,用于防止权限链路被意外改动。
|
||||
- 后续所有接口返回数据检测,统一以生成的 Egg.js 标注测试结果为准。
|
||||
|
||||
## 主要依赖
|
||||
|
||||
- egg.js 3.x
|
||||
@ -184,6 +70,8 @@ npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
|
||||
- `GET /`:健康检查
|
||||
- `POST /qimen`:奇门接口
|
||||
- `POST /system`:system 统一入口
|
||||
- `POST /api/v1`:旧版 API
|
||||
- `POST /api/v2`:新版 API
|
||||
- `GET /template/xml/:id`:打印模板
|
||||
- `GET|POST /auth/printSetting/:code`:打印台设置
|
||||
|
||||
@ -200,70 +88,6 @@ npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
|
||||
- 全局业务 Header(如 `platform`、`project`)设置
|
||||
- 方法级在线 POST 调试
|
||||
|
||||
### user.getBindWechatCode 调用约定(微信绑定码)
|
||||
|
||||
- 默认行为:立即返回当前状态(不会长等待,适合页面初始化)。
|
||||
- 显式长轮询:仅当 body 传 `waitForChange=true`(或兼容字段 `longPoll=true`)时启用。
|
||||
- 长轮询时长:后端单次最长等待 60 秒;60 秒内状态变化会立即返回。
|
||||
- 超时返回:若 60 秒内无变化,返回当前状态并提示超时。
|
||||
- 初始化强制立即返回:可传 `init=true`(兼容 `isInit=true`、`firstLoad=true`)。
|
||||
- 可选等待参数:`waitTimeoutMs`,后端自动封顶 60000。
|
||||
- 前端超时建议:HTTP 超时设置为 120000ms(2 分钟),覆盖网络抖动与重试开销。
|
||||
|
||||
## 接口响应规范(system)
|
||||
|
||||
更新时间:2026-03-22
|
||||
适用范围:
|
||||
|
||||
- `POST /system`
|
||||
|
||||
统一目标:
|
||||
|
||||
- 统一 `/system` 入口的响应结构与错误码口径,降低调用方分支判断成本。
|
||||
|
||||
成功响应示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"flag": "success",
|
||||
"code": 1,
|
||||
"message": "ok",
|
||||
"data": {},
|
||||
"timestamp": 1773386721
|
||||
}
|
||||
```
|
||||
|
||||
失败响应示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"flag": "failure",
|
||||
"code": 401,
|
||||
"message": "Unauthorized",
|
||||
"data": null,
|
||||
"timestamp": 1773386721
|
||||
}
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- 业务层若已返回 `flag/code/message` 标准结构,将保留并补齐 `timestamp`。
|
||||
- 业务层若返回普通对象或数组,控制器将自动包裹到 `data` 字段。
|
||||
- HTTP 状态码保持语义(如 400/401/403/500),业务 `code` 默认与 HTTP 状态码一致。
|
||||
|
||||
当前错误码口径:
|
||||
|
||||
- 400:请求参数错误(缺少 `method`、`v`、`timestamp`、非法 `method`)
|
||||
- 401:未登录/令牌无效/无令牌
|
||||
- 403:无权限访问
|
||||
- 406:业务授权状态异常(如仓库有效期)
|
||||
- 500:服务内部错误
|
||||
|
||||
实现位置:
|
||||
|
||||
- 响应封装:`app/lib/api_response.js`
|
||||
- 控制器接入:`app/controller/home.js`(system/pda)
|
||||
|
||||
## 接口文档联动维护(强制)
|
||||
|
||||
当出现以下任一变更时,必须同步更新 `methods` 下对应文档:
|
||||
@ -284,163 +108,12 @@ node .\script\tmp-struct-system-params.cjs
|
||||
```
|
||||
|
||||
4. 补充自动提取无法覆盖的信息(description/response/errors/枚举约束)
|
||||
5. 执行 method 输出一致性对比:
|
||||
|
||||
```powershell
|
||||
node .\script\method-output-regression.cjs compare
|
||||
```
|
||||
|
||||
## 配置说明
|
||||
|
||||
- 主要配置文件在 `config/`(如 `config.default.js`、`config.local.js`、`poloapi.js`)
|
||||
- 数据库、Redis、平台配置在对应配置文件中维护
|
||||
- 敏感信息不要提交到仓库
|
||||
- 远程发布配置模板:`config/deploy.config.example.cjs`
|
||||
- 本地 SSH 发布配置:`config/deploy.config.local.cjs`(已加入 git ignore,仅本机保留)
|
||||
|
||||
## 远程发布与回退(SSH)
|
||||
|
||||
生产目录固定为:`/www/wwwroot/qimen`
|
||||
|
||||
约定:
|
||||
|
||||
- 发布脚本通过本机 `ssh/scp/tar/git` 执行,不依赖额外 npm 包。
|
||||
- 每次发布前会在服务器上生成一份当前目录备份,保存到 `/www/wwwroot/qimen/.deploy/backups/`。
|
||||
- 回退默认使用最近一次发布前备份,也支持显式传入备份名。
|
||||
- 发布和回退都会保留 `.deploy`、`logs`、`run`、`temp` 目录,避免误删运行态目录。
|
||||
- 发布与回退阶段的停服务操作只会匹配当前 `deployRoot` 对应的 Egg 进程,不再直接调用全局 `egg-scripts stop` 扫描整机进程。
|
||||
|
||||
首次配置:
|
||||
|
||||
1. 完善 `config/deploy.config.local.cjs` 中的 `host`、`username`、`privateKeyPath`。
|
||||
2. 执行 `npm run setup:hooks`,启用本地 pre-commit 安全检查。
|
||||
3. 确认远端机器存在 Node.js、npm、tar,且 SSH 用户对 `/www/wwwroot/qimen` 有读写权限。
|
||||
4. 执行 `npm run deploy:init` 完成首次初始化(只在远端 `config/` 缺失或为空时写入基础文件)。
|
||||
|
||||
发布命令:
|
||||
|
||||
```powershell
|
||||
npm run deploy:init
|
||||
npm run deploy:prod
|
||||
```
|
||||
|
||||
回退命令:
|
||||
|
||||
```powershell
|
||||
npm run rollback:prod
|
||||
npm run rollback:prod -- --backup=backup-20260324123045.tar.gz
|
||||
```
|
||||
|
||||
脚本行为:
|
||||
|
||||
- 发布时按 Egg.js 最小运行集打包(默认仅 `app.js`、`app/**`、`methods/**`、`native/addons/**`、`package*.json`)。
|
||||
- 打包文件来自已跟踪 git 文件(`git ls-files --cached`),不会带入本地未跟踪文件。
|
||||
- `config/` 目录不参与发布包覆盖,远端发布与回退过程都会保留现有 `config/`。
|
||||
- 首次发布若远端不存在 `config/`,发布会中止并提示先创建生产配置。
|
||||
- 默认发布后执行:`npm install --production`、定点停止当前部署目录进程、`npm start`。
|
||||
- 若配置了 `healthCheckUrl`,发布与回退后会执行一次健康检查。
|
||||
- 每次发布会自动生成线上版本号,格式:`v{package.version}-{yyyyMMddHHmmss}-{gitShortCommit}`。
|
||||
- 发布会写入版本元数据到远端:
|
||||
- 当前版本:`/www/wwwroot/qimen/.deploy/state/current-release.json`
|
||||
- 历史版本:`/www/wwwroot/qimen/.deploy/state/release-history.jsonl`
|
||||
|
||||
版本查询命令:
|
||||
|
||||
```powershell
|
||||
npm run deploy:version
|
||||
npm run deploy:version:history
|
||||
```
|
||||
|
||||
运维检查与清理命令:
|
||||
|
||||
```powershell
|
||||
npm run deploy:inspect
|
||||
npm run deploy:smoke
|
||||
npm run deploy:verify
|
||||
npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz
|
||||
npm run deploy:gateway-probe -- releaseProbe.ping "{}"
|
||||
```
|
||||
|
||||
## 本地版本管理目录(回退辅助)
|
||||
|
||||
目录:`versioning/`
|
||||
|
||||
用途:
|
||||
|
||||
- 记录每次更新时的包版本、提交号、分支、时间。
|
||||
- 部署成功后会自动追加一条记录(source=`deploy:prod`)。
|
||||
- 也可手动记录一次快照(source=`version:record`)。
|
||||
|
||||
文件:
|
||||
|
||||
- `versioning/package-version-current.json`:当前最近一条本地版本记录
|
||||
- `versioning/package-version-history.jsonl`:本地版本历史(JSONL)
|
||||
|
||||
说明:
|
||||
|
||||
- `versioning/` 目录内容默认不提交到 git(仅保留目录占位)。
|
||||
- 回退前可先通过本地历史快速定位目标版本,再结合远端备份名执行回退。
|
||||
|
||||
本地命令:
|
||||
|
||||
```powershell
|
||||
# 手动记录一次本地版本快照
|
||||
npm run version:record
|
||||
|
||||
# 查询本地版本历史
|
||||
npm run version:history
|
||||
```
|
||||
|
||||
当前等待项:
|
||||
|
||||
- 由于 SSH 目标主机、账号、私钥路径仍是占位值,完成这些字段前不要执行发布/回退测试。
|
||||
|
||||
## App 能力清单(汇总)
|
||||
|
||||
能力入口文件:
|
||||
|
||||
- `app.js`
|
||||
- `app/extend/application.js`
|
||||
|
||||
### A. 应用启动能力(app.js)
|
||||
|
||||
- 设置应用根路径:`global.APP_ROOT`、`app.appRoot`
|
||||
- 启动前初始化动态工厂:
|
||||
- `OrderDeliveryFactory`
|
||||
- `OrderItemsFactory`
|
||||
- 启动时自检扩展能力:
|
||||
- 缓存方法可用性(`app.setCacheAsync` / `app.getCacheAsync`)
|
||||
- Message 能力类型检查(`app.Message`)
|
||||
- 扩展全局日期格式化:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')`
|
||||
|
||||
### B. Application 扩展能力(app/extend/application.js)
|
||||
|
||||
- 业务字典访问能力:
|
||||
- `businessDict` getter
|
||||
- `getBusinessTypeName(code)`
|
||||
- `getOperationCodeName(code)`
|
||||
- `getPlatformName(code)`
|
||||
- `getExternalLogTypeName(type)`
|
||||
- 外部 SOAP 调用能力:
|
||||
- `wsdl(methodName, args)`
|
||||
- Redis 缓存能力(cache client):
|
||||
- `setCacheAsync(cacheKey, data, expireSeconds = 300)`
|
||||
- `getCacheAsync(cacheKey)`
|
||||
- Message 扩展能力:
|
||||
- `Message` getter(返回 MessageClass)
|
||||
|
||||
### C. 迁移完成确认
|
||||
|
||||
- 原先在 `app.js` 直接挂载的字典映射方法已迁移到 `app/extend/application.js`。
|
||||
- 当前 `app.js` 仅保留启动初始化与非方法迁移逻辑,避免双源实现。
|
||||
|
||||
### D. Method 输出回归能力(质量门禁)
|
||||
|
||||
- 回归脚本:`script/method-output-regression.cjs`
|
||||
- 基线文件:`temp/method-output/method-output-baseline.json`、`temp/method-output/method-output-baseline.md`
|
||||
- 对比文件:`temp/method-output/method-output-compare.json`
|
||||
- 使用方式:先 `baseline`,后 `compare`
|
||||
- 门禁标准:`mismatch=0` 才允许交付
|
||||
|
||||
## 功能模块
|
||||
|
||||
@ -449,41 +122,55 @@ npm run version:history
|
||||
- 打印与打印台管理
|
||||
- 仓库/门店管理
|
||||
- 权限与角色管理
|
||||
- 原生扩展算法能力(native/addons)
|
||||
- Excel 表格生成、导入与解析
|
||||
|
||||
## Native 原生扩展能力
|
||||
## Excel 服务能力
|
||||
|
||||
目录:`native/addons/`
|
||||
系统已提供服务类:`app/service/systems/excel.js`,可通过 `ctx.service.systems.excel` 调用。
|
||||
|
||||
当前已存在的原生模块:
|
||||
支持能力:
|
||||
|
||||
- `subset_selector.node`(已在业务代码接入)
|
||||
- 接入位置:`app/service/apiMethods/test.js`
|
||||
- 已使用能力:`selectOrders(orders, n, type)`
|
||||
- 业务用途:对订单及 SKU 集合进行子集筛选/组合选择(用于加速 JS 侧大批量集合计算)
|
||||
- 生成单 sheet / 多 sheet Excel
|
||||
- 按 `columns + rows` 输出表格
|
||||
- 输出 `Buffer`、写入本地文件、直接作为下载响应返回
|
||||
- 解析 `.xlsx` / `.xls` 文件内容为 JSON
|
||||
- 自动处理空表头、重复表头
|
||||
|
||||
- `fibonacci_addon.node`(当前未检索到业务调用)
|
||||
- 现状:仓库中存在产物文件,但暂无 controller/service 调用链路
|
||||
常用方法:
|
||||
|
||||
当前接入状态说明:
|
||||
- `generateBuffer(options)`:生成 Excel 二进制内容
|
||||
- `writeFile(filePath, options)`:写入本地文件
|
||||
- `sendFile({ filename, sheets })`:HTTP 下载输出
|
||||
- `parseBuffer(buffer, options)`:解析上传后的文件流
|
||||
- `parseFile(filePath, options)`:解析本地 Excel 文件
|
||||
|
||||
- `subset_selector.node` 在 service 构造时通过 `require(app.appRoot + '/native/addons/subset_selector.node')` 动态加载。
|
||||
- 若加载失败,日志会记录“C++插件加载失败”,对应方法会因 addon 不可用而无法执行原生算法分支。
|
||||
示例:
|
||||
|
||||
兼容性提示:
|
||||
```js
|
||||
const buffer = await ctx.service.systems.excel.generateBuffer({
|
||||
sheets: [
|
||||
{
|
||||
name: '入库单',
|
||||
columns: [
|
||||
{ header: '单号', key: 'order_no', width: 20 },
|
||||
{ header: '货主', key: 'owner_name', width: 18 },
|
||||
],
|
||||
rows: [
|
||||
{ order_no: 'RK20260404001', owner_name: '测试货主' },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
- Node.js 原生 addon 与运行环境强相关(系统、架构、Node ABI 版本)。
|
||||
- 当出现 `ERR_DLOPEN_FAILED` / `is not a valid Win32 application` 时,通常表示 addon 与当前 Node 版本或构建目标不匹配,需要使用目标环境重新编译 addon。
|
||||
const parsed = await ctx.service.systems.excel.parseFile('D:/tmp/demo.xlsx');
|
||||
```
|
||||
|
||||
## 常见问题
|
||||
|
||||
- 启动端口默认 6060,可在配置中调整
|
||||
- 数据库/Redis 连接失败优先检查 `config/config.local.js`
|
||||
- 接口路由映射可查阅 `AI_METHOD_ROUTING.md`
|
||||
- native addon 加载失败(`ERR_DLOPEN_FAILED`)时,优先检查 Node 版本与 addon 构建目标是否一致
|
||||
- `npm run deploy:prod` 提示 SSH 配置未完善时,先补齐 `config/deploy.config.local.cjs` 中的 `host/username/privateKeyPath`
|
||||
- `npm run guard:git` 或 pre-commit 拦截提交时,说明暂存区包含本地机密文件或运行产物
|
||||
- system接口的日志在数据库wms中的表wms_system_log
|
||||
|
||||
## 日报维护
|
||||
|
||||
- 日报统一记录在 `day.log`
|
||||
|
||||
@ -20,24 +20,51 @@ function isEmptyValue(value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
function normalizeDate(value) {
|
||||
function formatLocalDateTime(date, isEnd = false) {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day} ${isEnd ? '23:59:59' : '00:00:00'}`;
|
||||
}
|
||||
|
||||
function normalizeDate(value, options = {}) {
|
||||
const { isEnd = false } = options;
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
if (isNaN(value.getTime())) return value;
|
||||
return value.toISOString().slice(0, 19).replace('T', ' ');
|
||||
return formatLocalDateTime(value, isEnd);
|
||||
}
|
||||
|
||||
if (typeof value === 'number') {
|
||||
const date = new Date(value);
|
||||
if (isNaN(date.getTime())) return value;
|
||||
return date.toISOString().slice(0, 19).replace('T', ' ');
|
||||
return formatLocalDateTime(date, isEnd);
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
if (/^\d+$/.test(trimmed)) {
|
||||
const date = new Date(Number(trimmed));
|
||||
if (!isNaN(date.getTime())) {
|
||||
return formatLocalDateTime(date, isEnd);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const parsed = new Date(trimmed);
|
||||
if (!isNaN(parsed.getTime())) {
|
||||
return formatLocalDateTime(parsed, isEnd);
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
return value;
|
||||
@ -59,11 +86,13 @@ function processConditionValue(value, type) {
|
||||
return value;
|
||||
|
||||
case 'date':
|
||||
return normalizeDate(value, { isEnd: false });
|
||||
|
||||
case 'daterange':
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(v => normalizeDate(v));
|
||||
return value.map((v, index) => normalizeDate(v, { isEnd: index === value.length - 1 }));
|
||||
}
|
||||
return normalizeDate(value);
|
||||
return normalizeDate(value, { isEnd: false });
|
||||
|
||||
case 'number': {
|
||||
const num = parseFloat(value);
|
||||
|
||||
@ -177,6 +177,7 @@ module.exports = app => {
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
paranoid: false,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
comment: 'API应用配置表',
|
||||
|
||||
27
app/model/express.js
Normal file
27
app/model/express.js
Normal file
@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { STRING } = app.Sequelize;
|
||||
|
||||
const Express = app.model.define('express', {
|
||||
code: {
|
||||
type: STRING(50),
|
||||
primaryKey: true,
|
||||
allowNull: false,
|
||||
comment: '快递编码',
|
||||
},
|
||||
name: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '快递名称',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
comment: '快递基础信息表',
|
||||
});
|
||||
|
||||
return Express;
|
||||
};
|
||||
204
app/model/express_print_record.js
Normal file
204
app/model/express_print_record.js
Normal file
@ -0,0 +1,204 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, INTEGER, DATE, TEXT, JSON } = app.Sequelize;
|
||||
|
||||
const ExpressPrintRecord = app.model.define('express_print_record', {
|
||||
id: {
|
||||
type: BIGINT(20),
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
express_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: false,
|
||||
comment: '快递记录ID',
|
||||
},
|
||||
order_id: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '订单ID',
|
||||
},
|
||||
express_no: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '快递单号',
|
||||
},
|
||||
platform: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: '平台编码',
|
||||
},
|
||||
template_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: false,
|
||||
comment: '模板ID',
|
||||
},
|
||||
template_url: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '模板URL',
|
||||
},
|
||||
printer_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '打印机名称',
|
||||
},
|
||||
printer_config_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: true,
|
||||
comment: '打印配置ID',
|
||||
},
|
||||
print_data: {
|
||||
type: JSON,
|
||||
allowNull: false,
|
||||
comment: '打印请求数据',
|
||||
},
|
||||
encrypted_data: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '加密数据',
|
||||
},
|
||||
signature: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '签名',
|
||||
},
|
||||
add_data: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '附加数据',
|
||||
},
|
||||
custom_data: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '自定义数据',
|
||||
},
|
||||
print_status: {
|
||||
type: STRING(20),
|
||||
allowNull: false,
|
||||
defaultValue: 'PENDING',
|
||||
comment: '打印状态',
|
||||
},
|
||||
print_count: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
comment: '打印次数',
|
||||
},
|
||||
last_print_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '最近打印时间',
|
||||
},
|
||||
next_retry_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '下次重试时间',
|
||||
},
|
||||
request_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '请求ID',
|
||||
},
|
||||
document_id: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '文档ID',
|
||||
},
|
||||
batch_no: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '批次号',
|
||||
},
|
||||
print_result: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '打印结果',
|
||||
},
|
||||
error_message: {
|
||||
type: STRING(500),
|
||||
allowNull: true,
|
||||
comment: '错误信息',
|
||||
},
|
||||
print_cost_time: {
|
||||
type: INTEGER(11),
|
||||
allowNull: true,
|
||||
comment: '打印耗时(ms)',
|
||||
},
|
||||
create_interface: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '创建接口名',
|
||||
},
|
||||
print_interface: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: '打印接口名',
|
||||
},
|
||||
operator_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: true,
|
||||
comment: '操作人ID',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20),
|
||||
allowNull: true,
|
||||
comment: '仓库ID',
|
||||
},
|
||||
create_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
print_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '打印时间',
|
||||
},
|
||||
update_time: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express_print_record',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
comment: '快递面单打印记录表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_express_id',
|
||||
fields: [ 'express_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_order_id',
|
||||
fields: [ 'order_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_express_no',
|
||||
fields: [ 'express_no' ],
|
||||
},
|
||||
{
|
||||
name: 'uk_request_id',
|
||||
unique: true,
|
||||
fields: [ 'request_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_print_status',
|
||||
fields: [ 'print_status' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return ExpressPrintRecord;
|
||||
};
|
||||
48
app/model/express_setting.js
Normal file
48
app/model/express_setting.js
Normal file
@ -0,0 +1,48 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { INTEGER, STRING, BIGINT } = app.Sequelize;
|
||||
|
||||
const ExpressSetting = app.model.define('express_setting', {
|
||||
id: {
|
||||
type: INTEGER(11),
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
express_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '快递编码',
|
||||
},
|
||||
code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '设置项编码',
|
||||
},
|
||||
warehouse_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '仓库主体ID',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_express_setting',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
comment: '快递配置表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_express_code',
|
||||
fields: [ 'express_code' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_warehouse_id',
|
||||
fields: [ 'warehouse_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return ExpressSetting;
|
||||
};
|
||||
@ -102,6 +102,12 @@ module.exports = app => {
|
||||
defaultValue: null,
|
||||
comment: '更新时间',
|
||||
},
|
||||
expire_time: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '过期时间,为空表示永不过期',
|
||||
},
|
||||
is_deleted: {
|
||||
type: BOOLEAN,
|
||||
allowNull: false,
|
||||
|
||||
@ -76,6 +76,7 @@ module.exports = app => {
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
paranoid: false,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
comment: '接口类型配置表',
|
||||
|
||||
162
app/model/notification_webhook.js
Normal file
162
app/model/notification_webhook.js
Normal file
@ -0,0 +1,162 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, TINYINT, DATE, JSON } = app.Sequelize;
|
||||
|
||||
const NotificationWebhook = app.model.define('notification_webhook', {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '主体ID,对应 wms_store.id',
|
||||
references: {
|
||||
model: 'store',
|
||||
key: 'id',
|
||||
},
|
||||
},
|
||||
hook_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: 'Webhook 名称',
|
||||
},
|
||||
hook_type: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
validate: {
|
||||
notEmpty: {
|
||||
msg: 'hook_type 不能为空',
|
||||
},
|
||||
len: {
|
||||
args: [ 1, 50 ],
|
||||
msg: 'hook_type 长度应在1-50个字符之间',
|
||||
},
|
||||
},
|
||||
comment: 'Webhook 类型,用于按类型分派通知结构处理逻辑',
|
||||
},
|
||||
hook_url: {
|
||||
type: STRING(500),
|
||||
allowNull: false,
|
||||
validate: {
|
||||
notEmpty: {
|
||||
msg: 'hook_url 不能为空',
|
||||
},
|
||||
len: {
|
||||
args: [ 1, 500 ],
|
||||
msg: 'hook_url 长度应在1-500个字符之间',
|
||||
},
|
||||
},
|
||||
comment: 'Webhook 链接地址',
|
||||
},
|
||||
events: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '订阅事件列表',
|
||||
},
|
||||
extra_config: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '扩展配置,如签名、请求头、模板映射等',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT(4),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
validate: {
|
||||
isIn: {
|
||||
args: [[ 0, 1 ]],
|
||||
msg: '状态值不合法,0-禁用,1-启用',
|
||||
},
|
||||
},
|
||||
comment: '状态:0-禁用,1-启用',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_by: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '创建人',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_notification_webhook',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
comment: '外部通知 WebHook 配置表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_notification_webhook_store_id',
|
||||
fields: [ 'store_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_notification_webhook_hook_type',
|
||||
fields: [ 'hook_type' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_notification_webhook_status',
|
||||
fields: [ 'status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_notification_webhook_store_type',
|
||||
fields: [ 'store_id', 'hook_type' ],
|
||||
},
|
||||
{
|
||||
name: 'uk_notification_webhook_store_type_url',
|
||||
unique: true,
|
||||
fields: [ 'store_id', 'hook_type', 'hook_url' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
NotificationWebhook.associate = function() {
|
||||
const { Store, Account } = app.model;
|
||||
|
||||
NotificationWebhook.belongsTo(Store, {
|
||||
foreignKey: 'store_id',
|
||||
targetKey: 'id',
|
||||
as: 'store',
|
||||
});
|
||||
|
||||
NotificationWebhook.belongsTo(Account, {
|
||||
foreignKey: 'created_by',
|
||||
targetKey: 'id',
|
||||
as: 'creator',
|
||||
constraints: false,
|
||||
});
|
||||
};
|
||||
|
||||
NotificationWebhook.prototype.isEnabled = function() {
|
||||
return Number(this.status) === 1;
|
||||
};
|
||||
|
||||
return NotificationWebhook;
|
||||
};
|
||||
89
app/model/order_express.js
Normal file
89
app/model/order_express.js
Normal file
@ -0,0 +1,89 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE, ENUM } = app.Sequelize;
|
||||
|
||||
const OrderExpress = app.model.define('order_express', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
waybill_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '运单号',
|
||||
},
|
||||
order_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '订单ID',
|
||||
},
|
||||
create_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '创建时间',
|
||||
},
|
||||
delete_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
is_galaxy_receive: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: true,
|
||||
comment: '是否星河签收',
|
||||
},
|
||||
is_back: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: true,
|
||||
comment: '是否退回',
|
||||
},
|
||||
is_intercept: {
|
||||
type: ENUM('Y', 'N'),
|
||||
allowNull: true,
|
||||
comment: '是否拦截',
|
||||
},
|
||||
logistics_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '物流编码',
|
||||
},
|
||||
logistics_interface_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '物流接口ID',
|
||||
},
|
||||
logistics_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '物流名称',
|
||||
},
|
||||
logistics_interface_name: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '物流接口名称',
|
||||
},
|
||||
platform_code: {
|
||||
type: STRING(50),
|
||||
allowNull: true,
|
||||
comment: '平台编码',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_order_express',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
comment: '订单快递信息表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_order_id',
|
||||
fields: [ 'order_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return OrderExpress;
|
||||
};
|
||||
54
app/model/order_express_print_data.js
Normal file
54
app/model/order_express_print_data.js
Normal file
@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, DATE, TEXT } = app.Sequelize;
|
||||
|
||||
const OrderExpressPrintData = app.model.define('order_express_print_data', {
|
||||
id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
express_id: {
|
||||
type: BIGINT(20).UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '快递记录ID',
|
||||
},
|
||||
data: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '打印数据',
|
||||
},
|
||||
create_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '创建时间',
|
||||
},
|
||||
delete_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
update_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '更新时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_order_express_print_data',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: false,
|
||||
comment: '订单快递打印数据表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'idx_express_id',
|
||||
fields: [ 'express_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return OrderExpressPrintData;
|
||||
};
|
||||
@ -135,8 +135,8 @@ module.exports = app => {
|
||||
});
|
||||
|
||||
// 关联关系 - 自关联,构建树形结构
|
||||
Permission.associate = function(models) {
|
||||
const { Role, Permission, RolePermission } = app.model;
|
||||
Permission.associate = function() {
|
||||
const { Permission } = app.model;
|
||||
// 子权限
|
||||
Permission.hasMany(Permission, {
|
||||
foreignKey: 'parent_id',
|
||||
@ -152,13 +152,6 @@ module.exports = app => {
|
||||
as: 'parent',
|
||||
});
|
||||
|
||||
// 角色权限关联
|
||||
Permission.belongsToMany(Role, {
|
||||
through: RolePermission,
|
||||
foreignKey: 'permission_id',
|
||||
otherKey: 'role_id',
|
||||
as: 'roles',
|
||||
});
|
||||
};
|
||||
|
||||
// 实例方法:获取类型对应的中文名称
|
||||
|
||||
@ -49,6 +49,11 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '角色描述',
|
||||
},
|
||||
permissions: {
|
||||
type: TEXT,
|
||||
allowNull: true,
|
||||
comment: '角色权限集,JSON数组;* 表示所有权限',
|
||||
},
|
||||
role_type: {
|
||||
type: TINYINT(4),
|
||||
allowNull: false,
|
||||
@ -117,6 +122,12 @@ module.exports = app => {
|
||||
allowNull: true,
|
||||
comment: '所属仓库ID',
|
||||
},
|
||||
pid: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
defaultValue: 0,
|
||||
comment: '父级角色ID,顶级为0',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_role',
|
||||
freezeTableName: true,
|
||||
@ -143,12 +154,16 @@ module.exports = app => {
|
||||
name: 'idx_status',
|
||||
fields: [ 'status' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_pid',
|
||||
fields: [ 'pid' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// 关联关系
|
||||
Role.associate = function(models) {
|
||||
const { Account, Store, Permission, RolePermission, EmployeeRole } = app.model;
|
||||
Role.associate = function() {
|
||||
const { Account, Store, EmployeeRole } = app.model;
|
||||
// 创建人
|
||||
Role.belongsTo(Account, {
|
||||
foreignKey: 'created_by',
|
||||
@ -161,13 +176,6 @@ module.exports = app => {
|
||||
as: 'store',
|
||||
});
|
||||
|
||||
// 权限关联
|
||||
Role.belongsToMany(Permission, {
|
||||
through: RolePermission,
|
||||
foreignKey: 'role_id',
|
||||
otherKey: 'permission_id',
|
||||
as: 'permissions',
|
||||
});
|
||||
Role.hasMany(EmployeeRole, {
|
||||
foreignKey: 'role_id',
|
||||
sourceKey: 'id',
|
||||
|
||||
@ -1,78 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, INTEGER, DATE } = app.Sequelize;
|
||||
|
||||
const RolePermission = app.model.define('role_permission', {
|
||||
id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '关联ID',
|
||||
},
|
||||
role_id: {
|
||||
type: BIGINT.UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '角色ID',
|
||||
},
|
||||
permission_id: {
|
||||
type: INTEGER,
|
||||
allowNull: false,
|
||||
comment: '权限ID',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
comment: '创建时间',
|
||||
},
|
||||
}, {
|
||||
tableName: 'wms_role_permission',
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
paranoid: false, // 明确禁用软删除
|
||||
createdAt: 'created_at',
|
||||
updatedAt: false,
|
||||
comment: '角色权限关联表',
|
||||
indexes: [
|
||||
{
|
||||
name: 'uk_role_permission',
|
||||
fields: [ 'role_id', 'permission_id' ],
|
||||
unique: true,
|
||||
},
|
||||
{
|
||||
name: 'idx_role_id',
|
||||
fields: [ 'role_id' ],
|
||||
},
|
||||
{
|
||||
name: 'idx_permission_id',
|
||||
fields: [ 'permission_id' ],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// 关联关系
|
||||
RolePermission.associate = function(models) {
|
||||
const { Role, Permission } = app.model;
|
||||
// 关联角色
|
||||
RolePermission.belongsTo(Role, {
|
||||
foreignKey: 'role_id',
|
||||
as: 'role',
|
||||
});
|
||||
|
||||
// 关联权限
|
||||
RolePermission.belongsTo(Permission, {
|
||||
foreignKey: 'permission_id',
|
||||
as: 'permission',
|
||||
});
|
||||
};
|
||||
|
||||
// 实例方法:检查关联是否有效
|
||||
RolePermission.prototype.isValid = function() {
|
||||
// 这里可以添加更多的有效性检查
|
||||
return this.role_id && this.permission_id;
|
||||
};
|
||||
|
||||
return RolePermission;
|
||||
};
|
||||
@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize;
|
||||
const { BIGINT, STRING, DATE, TINYINT } = app.Sequelize;
|
||||
|
||||
const Store = app.model.define('store', {
|
||||
id: {
|
||||
@ -179,7 +179,7 @@ module.exports = app => {
|
||||
|
||||
// 关联关系 - 使用您推荐的方式
|
||||
Store.associate = function() {
|
||||
const { Account, Role, AccountStoreEmployee, ProhibitedType } = app.model;
|
||||
const { Account, Role, AccountStoreEmployee, ProhibitedType, NotificationWebhook } = app.model;
|
||||
|
||||
// 关联创建人
|
||||
Store.belongsTo(Account, {
|
||||
@ -209,6 +209,11 @@ module.exports = app => {
|
||||
foreignKey: 'warehouse_id',
|
||||
as: 'prohibitedTypes',
|
||||
});
|
||||
|
||||
Store.hasMany(NotificationWebhook, {
|
||||
foreignKey: 'store_id',
|
||||
as: 'notificationWebhooks',
|
||||
});
|
||||
};
|
||||
|
||||
// 实例方法:检查商家是否启用
|
||||
|
||||
334
app/service/apiMethods/print.js
Normal file
334
app/service/apiMethods/print.js
Normal file
@ -0,0 +1,334 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
class PrintApiService extends Service {
|
||||
getPrinterRedis() {
|
||||
return this.app.redis.get('printer');
|
||||
}
|
||||
|
||||
normalizeBindValue(bindValue) {
|
||||
let bindValueObj = bindValue;
|
||||
try {
|
||||
bindValueObj = JSON.parse(bindValue);
|
||||
} catch (_) {
|
||||
bindValueObj = bindValue;
|
||||
}
|
||||
return bindValueObj;
|
||||
}
|
||||
|
||||
async getEmployeePermissions(employeeId) {
|
||||
const { ctx } = this;
|
||||
const roleRows = await ctx.model.EmployeeRole.findAll({
|
||||
attributes: [ 'role_id' ],
|
||||
where: {
|
||||
employee_id: employeeId,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Role,
|
||||
as: 'role',
|
||||
attributes: [],
|
||||
where: {
|
||||
status: 1,
|
||||
},
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (!roleRows || roleRows.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const roleIds = [ ...new Set(roleRows.map(item => item.role_id).filter(Boolean)) ];
|
||||
if (roleIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, {
|
||||
includeDisabled: false,
|
||||
});
|
||||
if (permissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const permissions = await ctx.model.Permission.findAll({
|
||||
attributes: [ 'path' ],
|
||||
where: {
|
||||
id: {
|
||||
[ctx.app.Sequelize.Op.in]: permissionIds,
|
||||
},
|
||||
status: 1,
|
||||
type: 'api',
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return permissions.map(item => item.path).filter(Boolean);
|
||||
}
|
||||
|
||||
async getBindInfo(data = {}) {
|
||||
const { ctx } = this;
|
||||
const accountId = Number(data.account_id || data.accountId || data.wms_account_id || data.wmsAccountId);
|
||||
const code = String(data.code || '').trim();
|
||||
|
||||
if (!Number.isFinite(accountId) || accountId <= 0 || !code) {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '缺少有效参数 account_id 或 code',
|
||||
};
|
||||
}
|
||||
|
||||
const account = await ctx.model.Account.findOne({
|
||||
where: { id: accountId },
|
||||
attributes: [ 'id', 'status' ],
|
||||
raw: true,
|
||||
});
|
||||
if (!account || Number(account.status) !== 1) {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '账号不存在或已禁用',
|
||||
};
|
||||
}
|
||||
|
||||
const redis = this.getPrinterRedis();
|
||||
const bindValue = await redis.get(`bind:${code}`);
|
||||
if (!bindValue) {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '无效code或未绑定',
|
||||
};
|
||||
}
|
||||
|
||||
const employeeRows = await ctx.model.AccountStoreEmployee.findAll({
|
||||
where: {
|
||||
account_id: accountId,
|
||||
status: 1,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Store,
|
||||
as: 'store',
|
||||
attributes: [ 'id', 'company_name', 'project', 'status', 'auth_end' ],
|
||||
where: {
|
||||
status: 1,
|
||||
project: 'warehouse',
|
||||
},
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
order: [[ 'created_at', 'DESC' ]],
|
||||
});
|
||||
|
||||
const now = new Date();
|
||||
const warehouseMap = new Map();
|
||||
for (const employee of employeeRows) {
|
||||
const permissions = await this.getEmployeePermissions(employee.id);
|
||||
if (!permissions.includes('printer.bind')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const store = employee.store;
|
||||
if (!store) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (store.auth_end && new Date(store.auth_end) < now) {
|
||||
continue;
|
||||
}
|
||||
|
||||
warehouseMap.set(String(store.id), {
|
||||
id: Number(store.id),
|
||||
name: store.company_name,
|
||||
});
|
||||
}
|
||||
|
||||
const warehouses = Array.from(warehouseMap.values());
|
||||
if (warehouses.length === 0) {
|
||||
return {
|
||||
success: true,
|
||||
code: 200,
|
||||
data: {
|
||||
warehouses: [],
|
||||
},
|
||||
message: '无可绑定仓库',
|
||||
};
|
||||
}
|
||||
|
||||
const tempCode = crypto.randomBytes(16).toString('hex').toUpperCase();
|
||||
const tokenPayload = {
|
||||
accountId,
|
||||
code,
|
||||
bindValue,
|
||||
createdAt: new Date().toISOString(),
|
||||
warehouses: warehouses.map(item => item.id),
|
||||
};
|
||||
await redis.setex(`binding_token:${tempCode}`, 300, JSON.stringify(tokenPayload));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
code: 200,
|
||||
data: {
|
||||
warehouses,
|
||||
tempCode,
|
||||
},
|
||||
message: '获取绑定信息成功',
|
||||
};
|
||||
}
|
||||
|
||||
async bindByTempCode(data = {}) {
|
||||
const { ctx } = this;
|
||||
const tempCode = String(data.temp_code || data.tempCode || '').trim();
|
||||
const printer = String(data.printer || data.workbench_name || data.workbenchName || '').trim();
|
||||
const warehouse = Number(data.warehouse || data.warehouse_id || data.warehouseId);
|
||||
|
||||
if (!tempCode || !printer || !Number.isFinite(warehouse) || warehouse <= 0) {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '参数缺失',
|
||||
};
|
||||
}
|
||||
|
||||
const redis = this.getPrinterRedis();
|
||||
const tokenText = await redis.get(`binding_token:${tempCode}`);
|
||||
if (!tokenText) {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '临时code无效或已过期',
|
||||
};
|
||||
}
|
||||
|
||||
let tokenData = null;
|
||||
try {
|
||||
tokenData = JSON.parse(tokenText);
|
||||
} catch (_) {
|
||||
tokenData = null;
|
||||
}
|
||||
|
||||
if (!tokenData || !tokenData.code || !Array.isArray(tokenData.warehouses)) {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '临时code数据异常',
|
||||
};
|
||||
}
|
||||
|
||||
if (!tokenData.warehouses.includes(warehouse)) {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '仓库无绑定权限',
|
||||
};
|
||||
}
|
||||
|
||||
const Store = ctx.model.Store;
|
||||
const warehouseInfo = await Store.findOne({
|
||||
where: {
|
||||
id: warehouse,
|
||||
status: 1,
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
if (!warehouseInfo || warehouseInfo.project !== 'warehouse') {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '仓库id校验失败',
|
||||
};
|
||||
}
|
||||
|
||||
const PrintComputer = ctx.model.PrintComputer;
|
||||
let computerId = null;
|
||||
const existComputer = await PrintComputer.findOne({
|
||||
where: {
|
||||
warehouse_id: warehouse,
|
||||
name: printer,
|
||||
},
|
||||
});
|
||||
if (existComputer) {
|
||||
if (Number(existComputer.status) === 1) {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: null,
|
||||
message: '该仓库下打印台名称已存在且可用',
|
||||
};
|
||||
}
|
||||
computerId = existComputer.id;
|
||||
} else {
|
||||
const newComputer = await PrintComputer.create({
|
||||
warehouse_id: warehouse,
|
||||
name: printer,
|
||||
status: 0,
|
||||
});
|
||||
computerId = newComputer.id;
|
||||
}
|
||||
|
||||
const bindValueObj = this.normalizeBindValue(tokenData.bindValue);
|
||||
const printServiceUrl = ctx.app.config.printService.url;
|
||||
let printServiceResult = null;
|
||||
try {
|
||||
const res = await ctx.curl(`${printServiceUrl}/auth/bind`, {
|
||||
method: 'POST',
|
||||
contentType: 'json',
|
||||
data: {
|
||||
code: tokenData.code,
|
||||
printer,
|
||||
warehouse,
|
||||
roomId: bindValueObj && bindValueObj.uniqueId ? bindValueObj.uniqueId : '',
|
||||
computerId,
|
||||
},
|
||||
dataType: 'json',
|
||||
});
|
||||
printServiceResult = res.data;
|
||||
} catch (err) {
|
||||
printServiceResult = { success: false, error: '打印服务通讯失败' };
|
||||
}
|
||||
|
||||
if (printServiceResult && printServiceResult.status === 'fail') {
|
||||
return {
|
||||
success: false,
|
||||
code: 0,
|
||||
data: {
|
||||
printer,
|
||||
warehouse,
|
||||
printServiceResult,
|
||||
},
|
||||
message: printServiceResult.message || '打印服务失败',
|
||||
};
|
||||
}
|
||||
|
||||
await redis.del(`binding_token:${tempCode}`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
code: 200,
|
||||
data: {
|
||||
code: tokenData.code,
|
||||
printer,
|
||||
warehouse,
|
||||
computerId,
|
||||
printServiceResult,
|
||||
},
|
||||
message: '绑定成功',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PrintApiService;
|
||||
@ -337,13 +337,14 @@ class MainService extends Service {
|
||||
|
||||
try {
|
||||
// 3. 验证JWT令牌
|
||||
const NewauthHeader = '';
|
||||
const decoded = app.jwt.verify(token, app.config.jwt.secret);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const expiresIn = decoded.exp - now;
|
||||
if (expiresIn < 14399 && expiresIn > 0) {
|
||||
// 移除过期时间(exp)和签发时间(iat),保留其他payload
|
||||
const { exp, iat, ...payload } = decoded;
|
||||
const payload = { ...decoded };
|
||||
delete payload.exp;
|
||||
delete payload.iat;
|
||||
|
||||
// 生成新的 token,使用原来的有效时间配置
|
||||
const newToken = app.jwt.sign(
|
||||
@ -373,8 +374,7 @@ class MainService extends Service {
|
||||
return result;
|
||||
}
|
||||
|
||||
if (_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1) {
|
||||
} else {
|
||||
if (!(_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1)) {
|
||||
if (user.auth_end && new Date(user.auth_end) < new Date()) {
|
||||
result.status = 406;
|
||||
result.message = '仓库有效期已过期';
|
||||
@ -434,21 +434,130 @@ class MainService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查用户是否有API访问权限(只检查类型为api的权限)
|
||||
* debug 模式下确保 API 权限存在,并绑定到 role_id=2
|
||||
* @param {string} apiPath - API路径
|
||||
* @param {Object} user - 当前用户
|
||||
* @return {Promise<{ensured:boolean, permissionId:number|null}>} 同步结果
|
||||
*/
|
||||
async ensureApiPermissionInDebugMode(apiPath, user = null) {
|
||||
const { ctx, app } = this;
|
||||
if (app.config.debug !== true) {
|
||||
return {
|
||||
ensured: false,
|
||||
permissionId: null,
|
||||
};
|
||||
}
|
||||
|
||||
const normalizedPath = String(apiPath || '').trim();
|
||||
if (!normalizedPath) {
|
||||
return {
|
||||
ensured: false,
|
||||
permissionId: null,
|
||||
};
|
||||
}
|
||||
|
||||
const template = await ctx.model.Permission.findOne({
|
||||
where: {
|
||||
type: 'api',
|
||||
},
|
||||
attributes: [
|
||||
'component',
|
||||
'name',
|
||||
'redirect',
|
||||
'meta_title',
|
||||
'meta_icon',
|
||||
'hidden',
|
||||
'always_show',
|
||||
'parent_id',
|
||||
'sort',
|
||||
'status',
|
||||
],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const [ permission, created ] = await ctx.model.Permission.findOrCreate({
|
||||
where: {
|
||||
path: normalizedPath,
|
||||
type: 'api',
|
||||
},
|
||||
defaults: {
|
||||
path: normalizedPath,
|
||||
type: 'api',
|
||||
component: template ? template.component : null,
|
||||
name: template && template.name ? template.name : normalizedPath,
|
||||
redirect: template ? template.redirect : null,
|
||||
meta_title: template && template.meta_title ? template.meta_title : `API:${normalizedPath}`,
|
||||
meta_icon: template ? template.meta_icon : null,
|
||||
hidden: template ? template.hidden : 0,
|
||||
always_show: template ? template.always_show : 0,
|
||||
parent_id: template ? template.parent_id : null,
|
||||
sort: template ? template.sort : 0,
|
||||
status: 1,
|
||||
},
|
||||
});
|
||||
|
||||
if (!permission || !permission.id) {
|
||||
return {
|
||||
ensured: false,
|
||||
permissionId: null,
|
||||
};
|
||||
}
|
||||
|
||||
await ctx.service.systems.auth.rolePermission.bulkAssign(2, [ Number(permission.id) ]);
|
||||
|
||||
// 仅在新建权限时清理当前用户缓存,避免继续使用旧权限快照。
|
||||
if (created && user && user.id) {
|
||||
await ctx.service.systems.auth.user.clearUserCache(user.id);
|
||||
}
|
||||
|
||||
return {
|
||||
ensured: true,
|
||||
permissionId: permission.id,
|
||||
};
|
||||
}
|
||||
|
||||
async hasRole2(employeeId) {
|
||||
const { ctx } = this;
|
||||
if (!employeeId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const link = await ctx.model.EmployeeRole.findOne({
|
||||
where: {
|
||||
employee_id: employeeId,
|
||||
role_id: 2,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
return !!link;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查用户是否有 API 访问权限(只检查 type=api)
|
||||
* @param {Object} user - 用户信息
|
||||
* @param {string} apiPath - API路径
|
||||
* @return {Promise<boolean>}
|
||||
* @return {Promise<boolean>} 是否有权限
|
||||
*/
|
||||
async checkApiPermission(user, apiPath) {
|
||||
const { ctx } = this;
|
||||
|
||||
console.log(user);
|
||||
try {
|
||||
// 方法1: 从用户的权限列表中检查(如果已经加载了权限)
|
||||
if (user.permissions && Array.isArray(user.permissions)) {
|
||||
// 用户权限列表中可能包含所有权限,需要过滤出api权限
|
||||
console.log('user.permissions', user.permissions);
|
||||
return user.permissions.includes(apiPath);
|
||||
if (user.permissions.includes('*') || user.permissions.includes(apiPath)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const ensureResult = await this.ensureApiPermissionInDebugMode(apiPath, user);
|
||||
if (!ensureResult.ensured) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return await this.hasRole2(user.employees_id);
|
||||
}
|
||||
return false;
|
||||
} catch (error) {
|
||||
|
||||
@ -23,8 +23,6 @@ class systemService extends Service {
|
||||
// 检查服务是否存在
|
||||
if (!systemMethods) {
|
||||
throw new Error(`服务 ${servicePath} 不存在`);
|
||||
}else{
|
||||
console.log(`调用服务: ${servicePath}, 方法: ${actionName}`);
|
||||
}
|
||||
let serviceInstance = systemMethods;
|
||||
|
||||
@ -45,7 +43,6 @@ class systemService extends Service {
|
||||
const isLog = authPass.isLog;
|
||||
if (authPass.status == 200) {
|
||||
result.data = await serviceInstance[actionName](requestData);
|
||||
console.log(result.data);
|
||||
result.status = 200;
|
||||
|
||||
} else {
|
||||
|
||||
@ -54,58 +54,6 @@ class indexService extends MainService {
|
||||
const { ctx } = this;
|
||||
const { language = 'zh-CN' } = data || ctx.query;
|
||||
|
||||
try {
|
||||
// 1. 直接查询表数据看看
|
||||
const allTranslations = await ctx.model.I18nTranslation.findAll({
|
||||
limit: 5,
|
||||
raw: true,
|
||||
});
|
||||
console.log('📊 数据库翻译表数据(前5条):', allTranslations);
|
||||
|
||||
const allKeys = await ctx.model.I18nKey.findAll({
|
||||
limit: 5,
|
||||
raw: true,
|
||||
});
|
||||
console.log('📊 数据库键值表数据(前5条):', allKeys);
|
||||
|
||||
// 2. 检查关联查询
|
||||
const testQuery = await ctx.model.I18nTranslation.findAll({
|
||||
include: [{
|
||||
model: ctx.model.I18nKey,
|
||||
as: 'key',
|
||||
required: false, // LEFT JOIN
|
||||
}],
|
||||
limit: 5,
|
||||
raw: false,
|
||||
});
|
||||
|
||||
console.log('🔍 关联查询结果:', testQuery.length);
|
||||
testQuery.forEach((item, index) => {
|
||||
console.log(`结果${index + 1}:`, {
|
||||
id: item.id,
|
||||
language: item.language,
|
||||
translation: item.translation,
|
||||
hasKey: !!item.key,
|
||||
keyName: item.key?.key_name,
|
||||
});
|
||||
});
|
||||
|
||||
// 3. 按语言查询
|
||||
const languageQuery = await ctx.model.I18nTranslation.findAll({
|
||||
where: { language },
|
||||
include: [{
|
||||
model: ctx.model.I18nKey,
|
||||
as: 'key',
|
||||
}],
|
||||
raw: false,
|
||||
});
|
||||
|
||||
console.log(`🌍 语言 ${language} 的翻译数量:`, languageQuery.length);
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 数据库查询错误:', error);
|
||||
ctx.logger.error('数据库查询错误:', error);
|
||||
}
|
||||
try {
|
||||
// 1. 查询当前项目的所有翻译(默认项目为 'wms')
|
||||
const translations = await ctx.model.I18nTranslation.findAll({
|
||||
|
||||
@ -6,9 +6,9 @@ class accountService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update';
|
||||
const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update';
|
||||
const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -29,7 +29,37 @@ class accountService extends MainService {
|
||||
* @param {*} data
|
||||
*/
|
||||
async list(data = {}) {
|
||||
return this.callSystemAccount('list', data, '获取工号列表失败');
|
||||
const { service } = this;
|
||||
try {
|
||||
this.prepareWhereContext(data, {
|
||||
specialFieldMap: {
|
||||
employee_id: {
|
||||
field: 'id',
|
||||
},
|
||||
account_id: {
|
||||
field: 'account_id',
|
||||
},
|
||||
username: {
|
||||
field: '$account.username$',
|
||||
},
|
||||
phone: {
|
||||
field: '$account.phone$',
|
||||
},
|
||||
email: {
|
||||
field: '$account.email$',
|
||||
},
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = await service.systems.setting.account.list(data);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || '获取工号列表失败', {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -55,6 +85,22 @@ class accountService extends MainService {
|
||||
async update(data = {}) {
|
||||
return this.callSystemAccount('update', data, '更新工号失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 为其他账号获取微信绑定码。
|
||||
* @param {*} data
|
||||
*/
|
||||
async getBindWechatCode(data = {}) {
|
||||
return this.callSystemAccount('getBindWechatCode', data, '获取账号绑定微信码失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 为其他账号解绑微信。
|
||||
* @param {*} data
|
||||
*/
|
||||
async unbindWechat(data = {}) {
|
||||
return this.callSystemAccount('unbindWechat', data, '解绑账号微信失败');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = accountService;
|
||||
60
app/service/systemMethods/setting/permission.js
Normal file
60
app/service/systemMethods/setting/permission.js
Normal file
@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
class permissionService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,add,delete,update';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'list,add,delete,update';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
async callSystemPermission(methodName, data, defaultMessage) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const result = await service.systems.setting.permission[methodName](data);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || defaultMessage, {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 权限列表。
|
||||
* @param {*} data
|
||||
*/
|
||||
async list(data = {}) {
|
||||
return this.callSystemPermission('list', data, '获取权限列表失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增权限。
|
||||
* @param {*} data
|
||||
*/
|
||||
async add(data = {}) {
|
||||
return this.callSystemPermission('add', data, '新增权限失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除权限。
|
||||
* @param {*} data
|
||||
*/
|
||||
async delete(data = {}) {
|
||||
return this.callSystemPermission('delete', data, '删除权限失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新权限。
|
||||
* @param {*} data
|
||||
*/
|
||||
async update(data = {}) {
|
||||
return this.callSystemPermission('update', data, '更新权限失败');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = permissionService;
|
||||
68
app/service/systemMethods/setting/role.js
Normal file
68
app/service/systemMethods/setting/role.js
Normal file
@ -0,0 +1,68 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
class roleService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,add,delete,update,permission';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'list,add,delete,update,permission';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
async callSystemRole(methodName, data, defaultMessage) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const result = await service.systems.setting.role[methodName](data);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || defaultMessage, {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 角色列表。
|
||||
* @param {*} data
|
||||
*/
|
||||
async list(data = {}) {
|
||||
return this.callSystemRole('list', data, '获取角色列表失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 角色权限列表(兼容旧入口)。
|
||||
* @param {*} data
|
||||
*/
|
||||
async permission(data = {}) {
|
||||
return this.callSystemRole('permission', data, '获取角色权限列表失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增角色。
|
||||
* @param {*} data
|
||||
*/
|
||||
async add(data = {}) {
|
||||
return this.callSystemRole('add', data, '新增角色失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除角色。
|
||||
* @param {*} data
|
||||
*/
|
||||
async delete(data = {}) {
|
||||
return this.callSystemRole('delete', data, '删除角色失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新角色。
|
||||
* @param {*} data
|
||||
*/
|
||||
async update(data = {}) {
|
||||
return this.callSystemRole('update', data, '更新角色失败');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = roleService;
|
||||
60
app/service/systemMethods/setting/store_warehouse.js
Normal file
60
app/service/systemMethods/setting/store_warehouse.js
Normal file
@ -0,0 +1,60 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../../main');
|
||||
|
||||
class storeWarehouseService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,sign,unbind,rename';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'list,sign,unbind,rename';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
async callSystemStoreWarehouse(methodName, data, defaultMessage) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const result = await service.systems.storeWarehouse[methodName](data);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || defaultMessage, {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 仓库-货主签约列表。
|
||||
* @param {*} data
|
||||
*/
|
||||
async list(data = {}) {
|
||||
return this.callSystemStoreWarehouse('list', data, '获取签约列表失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 建立/更新签约关系。
|
||||
* @param {*} data
|
||||
*/
|
||||
async sign(data = {}) {
|
||||
return this.callSystemStoreWarehouse('sign', data, '签约失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改当前主体对签约对象的名称/备注。
|
||||
* @param {*} data
|
||||
*/
|
||||
async rename(data = {}) {
|
||||
return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败');
|
||||
}
|
||||
|
||||
/**
|
||||
* 解除签约关系。
|
||||
* @param {*} data
|
||||
*/
|
||||
async unbind(data = {}) {
|
||||
return this.callSystemStoreWarehouse('unbind', data, '解除签约失败');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = storeWarehouseService;
|
||||
@ -10,9 +10,9 @@ class configService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving';
|
||||
const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange';
|
||||
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving';
|
||||
const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct';
|
||||
const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct';
|
||||
const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -73,6 +73,32 @@ class configService extends MainService {
|
||||
return this.success('创建失败', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定收货单货主。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.id 收货单ID
|
||||
* @param {number} data.store_id 货主ID
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async bindStore(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.storage.receiving.bindStore(data);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定或改绑收货单明细商品。
|
||||
* @param {Object} data 请求体
|
||||
* @param {number} data.detail_id 收货单明细ID
|
||||
* @param {number} data.system_product_id 商品ID
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
async bindDetailProduct(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.storage.receiving.bindDetailProduct(data);
|
||||
return this.success('ok', result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加收货商品(当前依赖底层 addItem 实现)。
|
||||
* @param {Object} data 请求体
|
||||
|
||||
65
app/service/systemMethods/storeWarehouse.js
Normal file
65
app/service/systemMethods/storeWarehouse.js
Normal file
@ -0,0 +1,65 @@
|
||||
'use strict';
|
||||
|
||||
const MainService = require('../main');
|
||||
|
||||
class storeWarehouseAliasService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig';
|
||||
const _noNeedLog = '*';
|
||||
const _noNeedAuth = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
this.store = this;
|
||||
}
|
||||
|
||||
async callSystemStoreWarehouse(methodName, data, defaultMessage) {
|
||||
const { service } = this;
|
||||
try {
|
||||
const result = await service.systems.storeWarehouse[methodName](data);
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
return this.fail(error.message || defaultMessage, {
|
||||
code: Number(error.code) || 500,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async list(data = {}) {
|
||||
return this.callSystemStoreWarehouse('list', data, '获取签约列表失败');
|
||||
}
|
||||
|
||||
async sign(data = {}) {
|
||||
return this.callSystemStoreWarehouse('sign', data, '签约失败');
|
||||
}
|
||||
|
||||
async rename(data = {}) {
|
||||
return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败');
|
||||
}
|
||||
|
||||
async unbind(data = {}) {
|
||||
return this.callSystemStoreWarehouse('unbind', data, '解除签约失败');
|
||||
}
|
||||
|
||||
async getPolicyConfig(data = {}) {
|
||||
return this.callSystemStoreWarehouse('getPolicyConfig', data, '获取合约策略配置失败');
|
||||
}
|
||||
|
||||
async savePolicyConfig(data = {}) {
|
||||
return this.callSystemStoreWarehouse('savePolicyConfig', data, '保存合约策略配置失败');
|
||||
}
|
||||
|
||||
async listQimenConfig(data = {}) {
|
||||
return this.callSystemStoreWarehouse('listQimenConfig', data, '获取奇门接口配置列表失败');
|
||||
}
|
||||
|
||||
async saveQimenConfig(data = {}) {
|
||||
return this.callSystemStoreWarehouse('saveQimenConfig', data, '保存奇门接口配置失败');
|
||||
}
|
||||
|
||||
async deleteQimenConfig(data = {}) {
|
||||
return this.callSystemStoreWarehouse('deleteQimenConfig', data, '删除奇门接口配置失败');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = storeWarehouseAliasService;
|
||||
3
app/service/systemMethods/storeWarehouse/store.js
Normal file
3
app/service/systemMethods/storeWarehouse/store.js
Normal file
@ -0,0 +1,3 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = require('../storeWarehouse');
|
||||
@ -5,9 +5,9 @@ const MainService = require('../main');
|
||||
class userService extends MainService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = 'login,loginByCode,register';
|
||||
const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode';
|
||||
const _noNeedRight = '*';
|
||||
const _noNeedLog = 'info,getBindWechatCode';
|
||||
const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode';
|
||||
const _noNeedAuth = '*';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
@ -25,37 +25,16 @@ class userService extends MainService {
|
||||
async loginByCode(data) {
|
||||
const { service } = this;
|
||||
const code = typeof data?.code === 'string' ? data.code.trim() : '';
|
||||
console.log('code', data.code,code);
|
||||
if (!code) {
|
||||
return this.fail('登录失败:缺少登录码 code', {
|
||||
return this.fail('1111登录失败:缺少登录码 code', {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 0,
|
||||
message: '缺少登录码 code',
|
||||
});
|
||||
}
|
||||
//code先进行base64解码,看是否为json以及json是否有uuid字段,如果有则继续执行否则返回报错
|
||||
let decoded;
|
||||
try {
|
||||
const buffer = Buffer.from(code, 'base64');
|
||||
const decodedStr = buffer.toString('utf-8');
|
||||
decoded = JSON.parse(decodedStr);
|
||||
} catch (err) {
|
||||
return this.fail('登录失败:无效的登录码格式', {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 0,
|
||||
message: '无效的登录码格式',
|
||||
});
|
||||
}
|
||||
if (!decoded || typeof decoded !== 'object' || !decoded.uuid) {
|
||||
return this.fail('登录失败:登录码缺少必要的uuid字段', {
|
||||
success: false,
|
||||
data: null,
|
||||
code: 0,
|
||||
message: '登录码缺少必要的uuid字段',
|
||||
});
|
||||
}
|
||||
const result = await service.systems.auth.user.loginByCode(code);
|
||||
const result = await service.systems.auth.user.loginByYe4sCode(code);
|
||||
if (result.code) {
|
||||
return this.success('登录成功', result);
|
||||
}
|
||||
@ -69,6 +48,14 @@ class userService extends MainService {
|
||||
}
|
||||
return this.fail('获取绑定微信码失败:' + result.message, result);
|
||||
}
|
||||
async getLoginWechatCode(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.auth.user.getLoginWechatCode(data);
|
||||
if (result.code) {
|
||||
return this.success('获取微信登录码成功', result);
|
||||
}
|
||||
return this.fail('获取微信登录码失败:' + result.message, result);
|
||||
}
|
||||
async unbindWechat(data) {
|
||||
const { service } = this;
|
||||
const result = await service.systems.auth.user.unbindWechat(data);
|
||||
|
||||
@ -57,7 +57,7 @@ class AccountPlatformService extends Service {
|
||||
role_id: roleBinding ? roleBinding.role_id : null,
|
||||
role_name: role ? role.name : '',
|
||||
role_code: role ? role.code : '',
|
||||
role_permissions: role ? role.permissions : [],
|
||||
role_permissions: role ? this.ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions) : [],
|
||||
store_id: employee.store_id,
|
||||
store_name: store ? store.name : '',
|
||||
store_code: store ? store.code : '',
|
||||
|
||||
@ -3,107 +3,352 @@
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class RolePermissionService extends Service {
|
||||
async bulkAssign(roleId, permissionIds, options = {}) {
|
||||
const { ctx } = this;
|
||||
normalizePermissionSet(rawValue) {
|
||||
if (rawValue === undefined || rawValue === null) {
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
}
|
||||
|
||||
if (!permissionIds || permissionIds.length === 0) {
|
||||
if (Array.isArray(rawValue)) {
|
||||
const normalizedItems = rawValue.map(item => typeof item === 'string' ? item.trim() : item);
|
||||
if (normalizedItems.some(item => item === '*')) {
|
||||
return { allAccess: true, permissionIds: [] };
|
||||
}
|
||||
|
||||
const permissionIds = normalizedItems
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isFinite(item) && item > 0)
|
||||
.map(item => Math.floor(item));
|
||||
|
||||
return {
|
||||
allAccess: false,
|
||||
permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b),
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof rawValue === 'number') {
|
||||
return this.normalizePermissionSet([ rawValue ]);
|
||||
}
|
||||
|
||||
if (typeof rawValue === 'string') {
|
||||
const trimmed = rawValue.trim();
|
||||
if (!trimmed) {
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
}
|
||||
if (trimmed === '*') {
|
||||
return { allAccess: true, permissionIds: [] };
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (parsed !== rawValue) {
|
||||
return this.normalizePermissionSet(parsed);
|
||||
}
|
||||
} catch (_) {
|
||||
// ignore JSON parse failure and continue with string splitting.
|
||||
}
|
||||
|
||||
if (trimmed.includes(',')) {
|
||||
return this.normalizePermissionSet(trimmed.split(','));
|
||||
}
|
||||
|
||||
return this.normalizePermissionSet([ trimmed ]);
|
||||
}
|
||||
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
}
|
||||
|
||||
toApiPermissionIds(rawValue) {
|
||||
const state = this.normalizePermissionSet(rawValue);
|
||||
return state.allAccess ? [ '*' ] : state.permissionIds;
|
||||
}
|
||||
|
||||
serializePermissionSet(rawValue) {
|
||||
const state = this.normalizePermissionSet(rawValue);
|
||||
return state.allAccess ? '*' : JSON.stringify(state.permissionIds);
|
||||
}
|
||||
|
||||
async getPermissionIdsForRoles(roleIds, options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const normalizedRoleIds = Array.from(new Set((roleIds || [])
|
||||
.map(roleId => Number(roleId))
|
||||
.filter(roleId => Number.isFinite(roleId) && roleId > 0)));
|
||||
|
||||
if (normalizedRoleIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rolePermissions = permissionIds.map(permissionId => ({
|
||||
role_id: roleId,
|
||||
permission_id: permissionId,
|
||||
}));
|
||||
|
||||
return await ctx.model.RolePermission.bulkCreate(rolePermissions, {
|
||||
ignoreDuplicates: true,
|
||||
const roleRows = await ctx.model.Role.findAll({
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: normalizedRoleIds,
|
||||
},
|
||||
...(options.includeRoleDisabled === true ? {} : { status: 1 }),
|
||||
},
|
||||
attributes: [ 'id', 'permissions' ],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
}
|
||||
|
||||
async clearRolePermissions(roleId, options = {}) {
|
||||
const { ctx } = this;
|
||||
if (!roleRows || roleRows.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return await ctx.model.RolePermission.destroy({
|
||||
where: { role_id: roleId },
|
||||
transaction: options.transaction,
|
||||
});
|
||||
}
|
||||
const directPermissionIds = [];
|
||||
let allAccess = false;
|
||||
|
||||
async getRolePermissions(roleId, includePermissionDetails = false) {
|
||||
const { ctx } = this;
|
||||
for (const row of roleRows) {
|
||||
const state = this.normalizePermissionSet(row.permissions);
|
||||
if (state.allAccess) {
|
||||
allAccess = true;
|
||||
break;
|
||||
}
|
||||
|
||||
const options = {
|
||||
where: { role_id: roleId },
|
||||
if (state.permissionIds.length > 0) {
|
||||
directPermissionIds.push(...state.permissionIds);
|
||||
}
|
||||
}
|
||||
|
||||
const permissionWhere = {
|
||||
status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1,
|
||||
};
|
||||
|
||||
if (includePermissionDetails) {
|
||||
options.include = [{
|
||||
model: ctx.model.Permission,
|
||||
as: 'permission',
|
||||
where: { status: 1 },
|
||||
required: false,
|
||||
}];
|
||||
if (options.type) {
|
||||
permissionWhere.type = options.type;
|
||||
}
|
||||
|
||||
return await ctx.model.RolePermission.findAll(options);
|
||||
}
|
||||
if (allAccess) {
|
||||
const allPermissions = await ctx.model.Permission.findAll({
|
||||
where: permissionWhere,
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
async hasPermission(roleId, permissionId) {
|
||||
const { ctx } = this;
|
||||
return Array.from(new Set(allPermissions
|
||||
.map(item => Number(item.id))
|
||||
.filter(item => Number.isFinite(item) && item > 0)));
|
||||
}
|
||||
|
||||
const rolePermission = await ctx.model.RolePermission.findOne({
|
||||
const permissionIds = Array.from(new Set(directPermissionIds
|
||||
.filter(item => Number.isFinite(item) && item > 0)));
|
||||
if (permissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const permissions = await ctx.model.Permission.findAll({
|
||||
where: {
|
||||
role_id: roleId,
|
||||
permission_id: permissionId,
|
||||
...permissionWhere,
|
||||
id: {
|
||||
[Op.in]: permissionIds,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
return !!rolePermission;
|
||||
return Array.from(new Set(permissions
|
||||
.map(item => Number(item.id))
|
||||
.filter(item => Number.isFinite(item) && item > 0)));
|
||||
}
|
||||
|
||||
async assignPermissions(roleId, permissionIds, options = {}) {
|
||||
await this.clearRolePermissions(roleId, options);
|
||||
|
||||
if (permissionIds && permissionIds.length > 0) {
|
||||
await this.bulkAssign(roleId, permissionIds, options);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async getPermissionTree(roleId, permissionType = null) {
|
||||
const { ctx } = this;
|
||||
|
||||
const rolePermissions = await this.getRolePermissions(roleId, true);
|
||||
const permissionIds = rolePermissions
|
||||
.map(rp => rp.permission && rp.permission.id)
|
||||
.filter(Boolean);
|
||||
async getPermissionPathsForRoles(roleIds, options = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const permissionIds = await this.getPermissionIdsForRoles(roleIds, {
|
||||
includeDisabled: options.includeDisabled === true,
|
||||
type: options.type || null,
|
||||
includeRoleDisabled: options.includeRoleDisabled === true,
|
||||
useLegacyFallback: options.useLegacyFallback !== false,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
if (permissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const where = {
|
||||
id: permissionIds,
|
||||
status: 1,
|
||||
id: {
|
||||
[Op.in]: permissionIds,
|
||||
},
|
||||
status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1,
|
||||
};
|
||||
|
||||
if (permissionType) {
|
||||
where.type = permissionType;
|
||||
if (options.type) {
|
||||
where.type = options.type;
|
||||
}
|
||||
|
||||
if (options.typeLike) {
|
||||
where.type = {
|
||||
[Op.like]: options.typeLike,
|
||||
};
|
||||
}
|
||||
|
||||
if (options.typeNotLike) {
|
||||
where.type = {
|
||||
[Op.notLike]: options.typeNotLike,
|
||||
};
|
||||
}
|
||||
|
||||
const rows = await ctx.model.Permission.findAll({
|
||||
where,
|
||||
attributes: [ 'path' ],
|
||||
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
return Array.from(new Set(rows
|
||||
.map(item => item && item.path)
|
||||
.filter(Boolean)));
|
||||
}
|
||||
|
||||
async bulkAssign(roleId, permissionIds, options = {}) {
|
||||
const currentRole = await this.ctx.model.Role.findOne({
|
||||
where: { id: roleId },
|
||||
attributes: [ 'permissions' ],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
const currentState = this.normalizePermissionSet(currentRole && currentRole.permissions);
|
||||
const incomingState = this.normalizePermissionSet(permissionIds);
|
||||
const nextState = incomingState.allAccess || currentState.allAccess
|
||||
? '*'
|
||||
: [ ...currentState.permissionIds, ...incomingState.permissionIds ];
|
||||
|
||||
await this.assignPermissions(roleId, nextState, options);
|
||||
return this.toApiPermissionIds(nextState);
|
||||
}
|
||||
|
||||
async clearRolePermissions(roleId, options = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
return await ctx.model.Role.update({
|
||||
permissions: JSON.stringify([]),
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: roleId },
|
||||
transaction: options.transaction,
|
||||
});
|
||||
}
|
||||
|
||||
async getRolePermissions(roleId, includePermissionDetails = false) {
|
||||
const { ctx } = this;
|
||||
const permissionIds = await this.getPermissionIds(roleId);
|
||||
if (permissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!includePermissionDetails) {
|
||||
return permissionIds.map(permissionId => ({
|
||||
role_id: Number(roleId),
|
||||
permission_id: Number(permissionId),
|
||||
}));
|
||||
}
|
||||
|
||||
const permissionRows = await ctx.model.Permission.findAll({
|
||||
where: {
|
||||
id: permissionIds,
|
||||
status: 1,
|
||||
},
|
||||
});
|
||||
const permissionMap = new Map(permissionRows.map(item => [ Number(item.id), item ]));
|
||||
|
||||
return permissionIds.map(permissionId => ({
|
||||
role_id: Number(roleId),
|
||||
permission_id: Number(permissionId),
|
||||
permission: permissionMap.get(Number(permissionId)) || null,
|
||||
}));
|
||||
}
|
||||
|
||||
async hasPermission(roleId, permissionId) {
|
||||
const permissionIds = await this.getPermissionIds(roleId, {
|
||||
includeDisabled: true,
|
||||
});
|
||||
|
||||
return permissionIds.includes(Number(permissionId));
|
||||
}
|
||||
|
||||
async assignPermissions(roleId, permissionIds, options = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
await ctx.model.Role.update({
|
||||
permissions: this.serializePermissionSet(permissionIds),
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
where: { id: roleId },
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async getPermissionTree(roleId, permissionType = null) {
|
||||
const { ctx } = this;
|
||||
const permissionIds = await this.getPermissionIds(roleId, {
|
||||
includeDisabled: false,
|
||||
type: permissionType,
|
||||
});
|
||||
|
||||
if (permissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const permissions = await ctx.model.Permission.findAll({
|
||||
where,
|
||||
where: {
|
||||
id: permissionIds,
|
||||
status: 1,
|
||||
...(permissionType ? { type: permissionType } : {}),
|
||||
},
|
||||
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
return ctx.model.Permission.buildPermissionTree(permissions);
|
||||
}
|
||||
|
||||
async getPermissionIds(roleId) {
|
||||
const rolePermissions = await this.getRolePermissions(roleId, false);
|
||||
return rolePermissions.map(rp => rp.permission_id);
|
||||
async getPermissionIds(roleId, options = {}) {
|
||||
return await this.getPermissionIdsForRoles([ roleId ], options);
|
||||
}
|
||||
|
||||
async removePermissionsFromAllRoles(permissionIds, options = {}) {
|
||||
const { ctx } = this;
|
||||
const removeSet = new Set((permissionIds || [])
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isFinite(item) && item > 0));
|
||||
|
||||
if (removeSet.size === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const roleRows = await ctx.model.Role.findAll({
|
||||
attributes: [ 'id', 'permissions' ],
|
||||
transaction: options.transaction,
|
||||
});
|
||||
|
||||
let updatedCount = 0;
|
||||
for (const role of roleRows) {
|
||||
const state = this.normalizePermissionSet(role.permissions);
|
||||
if (state.allAccess || state.permissionIds.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const nextPermissionIds = state.permissionIds.filter(permissionId => !removeSet.has(Number(permissionId)));
|
||||
if (nextPermissionIds.length === state.permissionIds.length) {
|
||||
continue;
|
||||
}
|
||||
|
||||
await role.update({
|
||||
permissions: JSON.stringify(nextPermissionIds),
|
||||
updated_at: new Date(),
|
||||
}, {
|
||||
transaction: options.transaction,
|
||||
});
|
||||
updatedCount++;
|
||||
}
|
||||
|
||||
return updatedCount;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
744
app/service/systems/excel.js
Normal file
744
app/service/systems/excel.js
Normal file
@ -0,0 +1,744 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { Readable } = require('stream');
|
||||
const Service = require('egg').Service;
|
||||
const XLSX = require('xlsx');
|
||||
const ExcelJS = require('exceljs');
|
||||
|
||||
const CONTENT_TYPE_MAP = {
|
||||
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
xls: 'application/vnd.ms-excel',
|
||||
csv: 'text/csv; charset=utf-8',
|
||||
};
|
||||
|
||||
class ExcelService extends Service {
|
||||
getContentType(bookType = 'xlsx') {
|
||||
const normalizedType = String(bookType || 'xlsx').replace('.', '').toLowerCase();
|
||||
return CONTENT_TYPE_MAP[normalizedType] || CONTENT_TYPE_MAP.xlsx;
|
||||
}
|
||||
|
||||
sanitizeSheetName(name, index = 1) {
|
||||
const safeName = String(name || `Sheet${index}`)
|
||||
.replace(/[\\/?*\[\]:]/g, '_')
|
||||
.trim();
|
||||
|
||||
return (safeName || `Sheet${index}`).slice(0, 31);
|
||||
}
|
||||
|
||||
normalizeHeaders(headerRow = []) {
|
||||
const usedNames = new Set();
|
||||
|
||||
return headerRow.map((value, index) => {
|
||||
const baseName = String(value == null ? '' : value).trim() || `column_${index + 1}`;
|
||||
let uniqueName = baseName;
|
||||
let suffix = 2;
|
||||
|
||||
while (usedNames.has(uniqueName)) {
|
||||
uniqueName = `${baseName}_${suffix}`;
|
||||
suffix += 1;
|
||||
}
|
||||
|
||||
usedNames.add(uniqueName);
|
||||
return uniqueName;
|
||||
});
|
||||
}
|
||||
|
||||
normalizeColumns(columns = []) {
|
||||
if (!Array.isArray(columns)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return columns
|
||||
.map(column => {
|
||||
if (!column) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const key = column.key || column.field || column.dataIndex || column.prop;
|
||||
const header = column.header || column.title || column.label || key;
|
||||
|
||||
if (!key && !header) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
key: key || header,
|
||||
header: header || key,
|
||||
width: Number(column.width || column.wch || 0) || undefined,
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
prepareSheetData(sheetConfig = {}) {
|
||||
const {
|
||||
rows = [],
|
||||
columns = [],
|
||||
header = [],
|
||||
skipHeader = false,
|
||||
widths = [],
|
||||
} = sheetConfig;
|
||||
|
||||
const normalizedColumns = this.normalizeColumns(columns);
|
||||
let aoaData = [];
|
||||
|
||||
if (normalizedColumns.length > 0) {
|
||||
const headerRow = normalizedColumns.map(column => column.header);
|
||||
const columnKeys = normalizedColumns.map(column => column.key);
|
||||
const bodyRows = Array.isArray(rows)
|
||||
? rows.map(row => {
|
||||
if (Array.isArray(row)) {
|
||||
return row;
|
||||
}
|
||||
|
||||
return columnKeys.map(key => (row && typeof row === 'object' ? row[key] : ''));
|
||||
})
|
||||
: [];
|
||||
aoaData = skipHeader ? bodyRows : [ headerRow, ...bodyRows ];
|
||||
} else if (Array.isArray(rows) && rows.length > 0 && Array.isArray(rows[0])) {
|
||||
aoaData = Array.isArray(header) && header.length > 0 && !skipHeader
|
||||
? [ header, ...rows ]
|
||||
: rows;
|
||||
} else if (Array.isArray(rows) && rows.length > 0) {
|
||||
const derivedHeaders = Array.isArray(header) && header.length > 0
|
||||
? header
|
||||
: Object.keys(rows[0] || {});
|
||||
const bodyRows = rows.map(row => derivedHeaders.map(key => (row && typeof row === 'object' ? row[key] : '')));
|
||||
aoaData = skipHeader ? bodyRows : [ derivedHeaders, ...bodyRows ];
|
||||
} else {
|
||||
aoaData = Array.isArray(header) && header.length > 0 ? [ header ] : [];
|
||||
}
|
||||
|
||||
const resolvedWidths = Array.isArray(widths) && widths.length > 0
|
||||
? widths.map(item => (typeof item === 'number' ? { wch: item } : item))
|
||||
: normalizedColumns
|
||||
.filter(column => column.width)
|
||||
.map(column => ({ wch: column.width }));
|
||||
|
||||
return {
|
||||
normalizedColumns,
|
||||
aoaData,
|
||||
resolvedWidths,
|
||||
skipHeader,
|
||||
originalRows: Array.isArray(rows) ? rows : [],
|
||||
};
|
||||
}
|
||||
|
||||
hasEmbeddedImages(options = {}) {
|
||||
return Array.isArray(options.sheets)
|
||||
&& options.sheets.some(sheet => Array.isArray(sheet && sheet.embeddedImages) && sheet.embeddedImages.length > 0);
|
||||
}
|
||||
|
||||
buildWorksheet(sheetConfig = {}) {
|
||||
const {
|
||||
merges = [],
|
||||
} = sheetConfig;
|
||||
const {
|
||||
aoaData,
|
||||
resolvedWidths,
|
||||
} = this.prepareSheetData(sheetConfig);
|
||||
|
||||
const worksheet = XLSX.utils.aoa_to_sheet(aoaData);
|
||||
|
||||
if (resolvedWidths.length > 0) {
|
||||
worksheet['!cols'] = resolvedWidths;
|
||||
}
|
||||
|
||||
if (Array.isArray(merges) && merges.length > 0) {
|
||||
worksheet['!merges'] = merges;
|
||||
}
|
||||
|
||||
return worksheet;
|
||||
}
|
||||
|
||||
buildWorkbook(options = {}) {
|
||||
const { sheets = [], props = {} } = options;
|
||||
|
||||
if (!Array.isArray(sheets) || sheets.length === 0) {
|
||||
throw new Error('至少需要一个 sheet 配置');
|
||||
}
|
||||
|
||||
const workbook = XLSX.utils.book_new();
|
||||
workbook.Props = {
|
||||
Company: 'WMS',
|
||||
CreatedDate: new Date(),
|
||||
...props,
|
||||
};
|
||||
|
||||
sheets.forEach((sheetConfig, index) => {
|
||||
const worksheet = this.buildWorksheet(sheetConfig || {});
|
||||
const sheetName = this.sanitizeSheetName(sheetConfig && sheetConfig.name, index + 1);
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
|
||||
});
|
||||
|
||||
return workbook;
|
||||
}
|
||||
|
||||
async buildExcelJsWorkbook(options = {}) {
|
||||
const { sheets = [], props = {} } = options;
|
||||
|
||||
if (!Array.isArray(sheets) || sheets.length === 0) {
|
||||
throw new Error('至少需要一个 sheet 配置');
|
||||
}
|
||||
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
workbook.creator = props.author || 'WMS';
|
||||
workbook.company = props.company || 'WMS';
|
||||
workbook.created = props.createdAt || new Date();
|
||||
workbook.modified = new Date();
|
||||
|
||||
for (let index = 0; index < sheets.length; index += 1) {
|
||||
const sheetConfig = sheets[index] || {};
|
||||
const sheetName = this.sanitizeSheetName(sheetConfig.name, index + 1);
|
||||
const worksheet = workbook.addWorksheet(sheetName);
|
||||
const {
|
||||
merges = [],
|
||||
embeddedImages = [],
|
||||
styledRows = [],
|
||||
} = sheetConfig;
|
||||
const {
|
||||
normalizedColumns,
|
||||
aoaData,
|
||||
resolvedWidths,
|
||||
skipHeader,
|
||||
originalRows,
|
||||
} = this.prepareSheetData(sheetConfig);
|
||||
|
||||
if (normalizedColumns.length > 0 && originalRows.length > 0 && !Array.isArray(originalRows[0])) {
|
||||
if (skipHeader) {
|
||||
aoaData.forEach(row => worksheet.addRow(row));
|
||||
} else {
|
||||
worksheet.columns = normalizedColumns.map(column => ({
|
||||
header: column.header,
|
||||
key: column.key,
|
||||
width: column.width || 18,
|
||||
}));
|
||||
originalRows.forEach(row => worksheet.addRow(row || {}));
|
||||
}
|
||||
} else if (normalizedColumns.length > 0 && originalRows.length === 0 && !skipHeader) {
|
||||
worksheet.columns = normalizedColumns.map(column => ({
|
||||
header: column.header,
|
||||
key: column.key,
|
||||
width: column.width || 18,
|
||||
}));
|
||||
} else {
|
||||
aoaData.forEach(row => worksheet.addRow(row));
|
||||
}
|
||||
|
||||
if (resolvedWidths.length > 0) {
|
||||
resolvedWidths.forEach((column, columnIndex) => {
|
||||
const width = Number(column && column.wch) || Number(column && column.width) || undefined;
|
||||
if (width) {
|
||||
worksheet.getColumn(columnIndex + 1).width = width;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (Array.isArray(merges) && merges.length > 0) {
|
||||
merges.forEach(merge => {
|
||||
if (!merge) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof merge === 'string') {
|
||||
worksheet.mergeCells(merge);
|
||||
return;
|
||||
}
|
||||
|
||||
if (merge.s && merge.e) {
|
||||
worksheet.mergeCells(merge.s.r + 1, merge.s.c + 1, merge.e.r + 1, merge.e.c + 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (Array.isArray(styledRows) && styledRows.length > 0) {
|
||||
this.applyStyledRows(worksheet, styledRows);
|
||||
}
|
||||
|
||||
if (Array.isArray(embeddedImages) && embeddedImages.length > 0) {
|
||||
await this.addEmbeddedImages(workbook, worksheet, embeddedImages);
|
||||
}
|
||||
}
|
||||
|
||||
return workbook;
|
||||
}
|
||||
|
||||
inferImageExtension(imageConfig = {}, contentType = '') {
|
||||
const preferred = String(imageConfig.extension || '').replace('.', '').toLowerCase();
|
||||
if (preferred) {
|
||||
return preferred === 'jpg' ? 'jpeg' : preferred;
|
||||
}
|
||||
|
||||
const fileSource = imageConfig.url || imageConfig.filePath || imageConfig.filename || '';
|
||||
const ext = path.extname(String(fileSource)).replace('.', '').toLowerCase();
|
||||
if (ext) {
|
||||
return ext === 'jpg' ? 'jpeg' : ext;
|
||||
}
|
||||
|
||||
if (contentType.includes('png')) return 'png';
|
||||
if (contentType.includes('gif')) return 'gif';
|
||||
if (contentType.includes('jpg') || contentType.includes('jpeg')) return 'jpeg';
|
||||
if (contentType.includes('webp')) return 'png';
|
||||
|
||||
return 'png';
|
||||
}
|
||||
|
||||
async resolveImageSource(imageConfig = {}) {
|
||||
try {
|
||||
if (imageConfig.buffer) {
|
||||
return {
|
||||
buffer: Buffer.isBuffer(imageConfig.buffer) ? imageConfig.buffer : Buffer.from(imageConfig.buffer),
|
||||
extension: this.inferImageExtension(imageConfig),
|
||||
};
|
||||
}
|
||||
|
||||
if (imageConfig.dataUrl) {
|
||||
const match = String(imageConfig.dataUrl).match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/);
|
||||
if (match) {
|
||||
return {
|
||||
buffer: Buffer.from(match[2], 'base64'),
|
||||
extension: this.inferImageExtension(imageConfig, match[1]),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (imageConfig.base64) {
|
||||
return {
|
||||
buffer: Buffer.from(String(imageConfig.base64), 'base64'),
|
||||
extension: this.inferImageExtension(imageConfig),
|
||||
};
|
||||
}
|
||||
|
||||
if (imageConfig.filePath) {
|
||||
const resolvedFilePath = path.resolve(String(imageConfig.filePath));
|
||||
const buffer = await fs.promises.readFile(resolvedFilePath);
|
||||
return {
|
||||
buffer,
|
||||
extension: this.inferImageExtension({ ...imageConfig, filePath: resolvedFilePath }),
|
||||
};
|
||||
}
|
||||
|
||||
if (imageConfig.url) {
|
||||
const imageUrl = String(imageConfig.url);
|
||||
const dataUrlMatch = imageUrl.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/);
|
||||
if (dataUrlMatch) {
|
||||
return {
|
||||
buffer: Buffer.from(dataUrlMatch[2], 'base64'),
|
||||
extension: this.inferImageExtension(imageConfig, dataUrlMatch[1]),
|
||||
};
|
||||
}
|
||||
|
||||
if (this.ctx && typeof this.ctx.curl === 'function') {
|
||||
const response = await this.ctx.curl(imageUrl, {
|
||||
method: 'GET',
|
||||
timeout: 15000,
|
||||
followRedirect: true,
|
||||
});
|
||||
const contentType = String((response.headers && (response.headers['content-type'] || response.headers['Content-Type'])) || '').toLowerCase();
|
||||
const buffer = Buffer.isBuffer(response.data) ? response.data : Buffer.from(response.data || '');
|
||||
|
||||
if (buffer.length > 0) {
|
||||
return {
|
||||
buffer,
|
||||
extension: this.inferImageExtension(imageConfig, contentType),
|
||||
};
|
||||
}
|
||||
} else if (typeof fetch === 'function' && /^https?:\/\//i.test(imageUrl)) {
|
||||
const response = await fetch(imageUrl);
|
||||
if (response && response.ok) {
|
||||
const contentType = String(response.headers.get('content-type') || '').toLowerCase();
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
|
||||
if (buffer.length > 0) {
|
||||
return {
|
||||
buffer,
|
||||
extension: this.inferImageExtension(imageConfig, contentType),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') {
|
||||
this.ctx.logger.warn('[ExcelService.resolveImageSource] 图片加载失败: %s', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
mergeCellStyle(baseStyle = {}, patchStyle = {}) {
|
||||
const mergedStyle = {
|
||||
...baseStyle,
|
||||
...patchStyle,
|
||||
};
|
||||
|
||||
if (baseStyle.font || patchStyle.font) {
|
||||
mergedStyle.font = {
|
||||
...(baseStyle.font || {}),
|
||||
...(patchStyle.font || {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (baseStyle.alignment || patchStyle.alignment) {
|
||||
mergedStyle.alignment = {
|
||||
...(baseStyle.alignment || {}),
|
||||
...(patchStyle.alignment || {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (baseStyle.protection || patchStyle.protection) {
|
||||
mergedStyle.protection = {
|
||||
...(baseStyle.protection || {}),
|
||||
...(patchStyle.protection || {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (patchStyle.fill) {
|
||||
mergedStyle.fill = patchStyle.fill;
|
||||
}
|
||||
|
||||
if (patchStyle.border) {
|
||||
mergedStyle.border = patchStyle.border;
|
||||
}
|
||||
|
||||
if (patchStyle.numFmt) {
|
||||
mergedStyle.numFmt = patchStyle.numFmt;
|
||||
}
|
||||
|
||||
return mergedStyle;
|
||||
}
|
||||
|
||||
applyStyledRows(worksheet, styledRows = []) {
|
||||
styledRows.forEach(item => {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rowNumber = Math.max(Number(item.row || 1), 1);
|
||||
const fromCol = Math.max(Number(item.fromCol || 1), 1);
|
||||
const toCol = Math.max(Number(item.toCol || fromCol), fromCol);
|
||||
const row = worksheet.getRow(rowNumber);
|
||||
|
||||
if (item.height) {
|
||||
row.height = item.height;
|
||||
}
|
||||
|
||||
if (item.style && typeof item.style === 'object') {
|
||||
for (let col = fromCol; col <= toCol; col += 1) {
|
||||
const cell = worksheet.getCell(rowNumber, col);
|
||||
cell.style = this.mergeCellStyle(cell.style || {}, item.style);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async addEmbeddedImages(workbook, worksheet, embeddedImages = []) {
|
||||
for (const imageConfig of embeddedImages) {
|
||||
if (!imageConfig) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const row = Math.max(Number(imageConfig.row || 1), 1);
|
||||
const col = Math.max(Number(imageConfig.col || imageConfig.column || 1), 1);
|
||||
const width = Math.max(Number(imageConfig.width || 120), 40);
|
||||
const height = Math.max(Number(imageConfig.height || 120), 40);
|
||||
const cell = worksheet.getCell(row, col);
|
||||
const fallbackText = imageConfig.fallbackText || imageConfig.url || '';
|
||||
const resolvedImage = await this.resolveImageSource(imageConfig);
|
||||
|
||||
if (!resolvedImage || !resolvedImage.buffer || resolvedImage.buffer.length === 0) {
|
||||
if (fallbackText) {
|
||||
cell.value = fallbackText;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const imageId = workbook.addImage({
|
||||
buffer: resolvedImage.buffer,
|
||||
extension: resolvedImage.extension,
|
||||
});
|
||||
|
||||
worksheet.addImage(imageId, {
|
||||
tl: { col: col - 1 + 0.05, row: row - 1 + 0.05 },
|
||||
ext: { width, height },
|
||||
editAs: 'oneCell',
|
||||
});
|
||||
|
||||
if (fallbackText) {
|
||||
cell.value = fallbackText;
|
||||
}
|
||||
|
||||
worksheet.getRow(row).height = Math.max(Number(worksheet.getRow(row).height || 20), Math.ceil(height * 0.75));
|
||||
worksheet.getColumn(col).width = Math.max(Number(worksheet.getColumn(col).width || 10), Math.ceil(width / 7));
|
||||
}
|
||||
}
|
||||
|
||||
async generateBuffer(options = {}) {
|
||||
const bookType = String(options.bookType || 'xlsx').replace('.', '').toLowerCase();
|
||||
|
||||
const shouldUseExcelJs = this.hasEmbeddedImages(options)
|
||||
|| (Array.isArray(options.sheets)
|
||||
&& options.sheets.some(sheet => sheet && (sheet.forceExcelJs || (Array.isArray(sheet.styledRows) && sheet.styledRows.length > 0))));
|
||||
|
||||
if (shouldUseExcelJs) {
|
||||
if (bookType !== 'xlsx') {
|
||||
throw new Error('带图片的 Excel 仅支持 xlsx 格式');
|
||||
}
|
||||
|
||||
const workbook = await this.buildExcelJsWorkbook({
|
||||
...options,
|
||||
bookType,
|
||||
});
|
||||
const buffer = await workbook.xlsx.writeBuffer();
|
||||
return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
|
||||
}
|
||||
|
||||
const workbook = this.buildWorkbook(options);
|
||||
const buffer = XLSX.write(workbook, {
|
||||
type: 'buffer',
|
||||
bookType,
|
||||
compression: true,
|
||||
});
|
||||
|
||||
return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
|
||||
}
|
||||
|
||||
async writeFile(filePath, options = {}) {
|
||||
if (!filePath) {
|
||||
throw new Error('filePath 不能为空');
|
||||
}
|
||||
|
||||
const resolvedFilePath = path.resolve(filePath);
|
||||
const ext = path.extname(resolvedFilePath).replace('.', '').toLowerCase() || options.bookType || 'xlsx';
|
||||
const buffer = await this.generateBuffer({
|
||||
...options,
|
||||
bookType: ext,
|
||||
});
|
||||
|
||||
await fs.promises.mkdir(path.dirname(resolvedFilePath), { recursive: true });
|
||||
await fs.promises.writeFile(resolvedFilePath, buffer);
|
||||
|
||||
return {
|
||||
filePath: resolvedFilePath,
|
||||
size: buffer.length,
|
||||
bookType: ext,
|
||||
};
|
||||
}
|
||||
|
||||
sanitizeFilename(filename = 'export.xlsx', fallbackExt = '.xlsx') {
|
||||
const normalizedName = String(filename || '').trim() || `export${fallbackExt}`;
|
||||
const rawExt = path.extname(normalizedName);
|
||||
const ext = rawExt || fallbackExt;
|
||||
const baseName = path.basename(normalizedName, rawExt);
|
||||
const safeBaseName = String(baseName || 'export')
|
||||
.replace(/[<>:"/\\|?*]/g, '_')
|
||||
.replace(/\s+/g, '_')
|
||||
.replace(/_+/g, '_')
|
||||
.replace(/^_+|_+$/g, '')
|
||||
.slice(0, 120) || 'export';
|
||||
|
||||
return `${safeBaseName}${ext}`;
|
||||
}
|
||||
|
||||
buildUploadKey(filename, options = {}) {
|
||||
if (options.key) {
|
||||
return String(options.key)
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/^\/+/, '')
|
||||
.replace(/\/+/g, '/');
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const dateFolder = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
|
||||
const normalizedDir = String(options.dir || 'exports/excel')
|
||||
.replace(/\\/g, '/')
|
||||
.replace(/^\/+|\/+$/g, '');
|
||||
|
||||
return path.posix.join(normalizedDir, dateFolder, filename);
|
||||
}
|
||||
|
||||
async generateAndUpload({
|
||||
filename = 'export.xlsx',
|
||||
dir = 'exports/excel',
|
||||
key,
|
||||
category = 'document',
|
||||
saveRecord = false,
|
||||
businessType,
|
||||
businessId,
|
||||
uploaderDept,
|
||||
expireTime,
|
||||
expireDays,
|
||||
onProgress,
|
||||
...options
|
||||
} = {}) {
|
||||
const uploadService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.upload;
|
||||
|
||||
if (!uploadService || typeof uploadService.uploadFile !== 'function') {
|
||||
throw new Error('上传服务不可用,无法上传 Excel 文件');
|
||||
}
|
||||
|
||||
const bookType = String(options.bookType || path.extname(filename).replace('.', '') || 'xlsx').toLowerCase();
|
||||
const safeFilename = this.sanitizeFilename(filename, `.${bookType}`);
|
||||
const contentType = this.getContentType(bookType);
|
||||
const buffer = await this.generateBuffer({
|
||||
...options,
|
||||
bookType,
|
||||
});
|
||||
const uploadKey = this.buildUploadKey(safeFilename, { dir, key });
|
||||
const uploadStream = Readable.from(buffer);
|
||||
|
||||
uploadStream.filename = safeFilename;
|
||||
uploadStream.mimeType = contentType;
|
||||
uploadStream.fileSize = buffer.length;
|
||||
|
||||
const uploadResult = await uploadService.uploadFile(uploadStream, {
|
||||
key: uploadKey,
|
||||
category,
|
||||
mimetype: 'xls,xlsx,csv',
|
||||
onProgress,
|
||||
});
|
||||
|
||||
let fileRecord = null;
|
||||
if ((saveRecord || businessType || businessId) && typeof uploadService.uploadSuccessNotify === 'function') {
|
||||
const recordResult = await uploadService.uploadSuccessNotify({
|
||||
url: uploadResult.fileName,
|
||||
fileKey: uploadResult.fileName,
|
||||
fileName: safeFilename,
|
||||
name: safeFilename,
|
||||
fileSize: buffer.length,
|
||||
size: buffer.length,
|
||||
fileType: category,
|
||||
mimeType: contentType,
|
||||
type: category,
|
||||
category,
|
||||
businessType,
|
||||
businessId,
|
||||
uploaderDept,
|
||||
expireTime,
|
||||
expireDays,
|
||||
});
|
||||
|
||||
fileRecord = recordResult && (recordResult.data || recordResult);
|
||||
}
|
||||
|
||||
return {
|
||||
filename: safeFilename,
|
||||
fileKey: uploadResult.fileName,
|
||||
size: buffer.length,
|
||||
contentType,
|
||||
...uploadResult,
|
||||
fileRecord,
|
||||
};
|
||||
}
|
||||
|
||||
async sendFile({ ctx = this.ctx, filename = 'export.xlsx', ...options } = {}) {
|
||||
if (!ctx) {
|
||||
throw new Error('ctx 不存在,无法输出下载响应');
|
||||
}
|
||||
|
||||
const ext = path.extname(filename).replace('.', '').toLowerCase() || options.bookType || 'xlsx';
|
||||
const buffer = await this.generateBuffer({
|
||||
...options,
|
||||
bookType: ext,
|
||||
});
|
||||
|
||||
ctx.set('Content-Type', this.getContentType(ext));
|
||||
ctx.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`);
|
||||
ctx.body = buffer;
|
||||
|
||||
return {
|
||||
filename,
|
||||
size: buffer.length,
|
||||
contentType: this.getContentType(ext),
|
||||
};
|
||||
}
|
||||
|
||||
async parseBuffer(buffer, options = {}) {
|
||||
if (!buffer) {
|
||||
throw new Error('buffer 不能为空');
|
||||
}
|
||||
|
||||
const workbook = XLSX.read(buffer, {
|
||||
type: 'buffer',
|
||||
raw: false,
|
||||
cellDates: true,
|
||||
...options.readOptions,
|
||||
});
|
||||
|
||||
return this.workbookToJSON(workbook, options);
|
||||
}
|
||||
|
||||
async parseFile(filePath, options = {}) {
|
||||
if (!filePath) {
|
||||
throw new Error('filePath 不能为空');
|
||||
}
|
||||
|
||||
const resolvedFilePath = path.resolve(filePath);
|
||||
const buffer = await fs.promises.readFile(resolvedFilePath);
|
||||
const result = await this.parseBuffer(buffer, options);
|
||||
|
||||
return {
|
||||
filePath: resolvedFilePath,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
workbookToJSON(workbook, options = {}) {
|
||||
const {
|
||||
headerRow = 1,
|
||||
defval = '',
|
||||
blankrows = false,
|
||||
includeRawRows = false,
|
||||
sheetNames,
|
||||
} = options;
|
||||
|
||||
const startIndex = Math.max(Number(headerRow) || 1, 1) - 1;
|
||||
const selectedSheetNames = Array.isArray(sheetNames) && sheetNames.length > 0
|
||||
? workbook.SheetNames.filter(name => sheetNames.includes(name))
|
||||
: workbook.SheetNames;
|
||||
|
||||
const sheets = selectedSheetNames.map(name => {
|
||||
const sheet = workbook.Sheets[name];
|
||||
const rawRows = XLSX.utils.sheet_to_json(sheet, {
|
||||
header: 1,
|
||||
raw: false,
|
||||
defval,
|
||||
blankrows,
|
||||
});
|
||||
const headerValues = Array.isArray(rawRows[startIndex]) ? rawRows[startIndex] : [];
|
||||
const headers = this.normalizeHeaders(headerValues);
|
||||
const dataRows = rawRows.slice(startIndex + 1)
|
||||
.filter(row => blankrows || row.some(cell => String(cell == null ? '' : cell).trim() !== ''));
|
||||
const rows = dataRows.map(row => {
|
||||
return headers.reduce((result, headerName, columnIndex) => {
|
||||
result[headerName] = row[columnIndex] == null ? defval : row[columnIndex];
|
||||
return result;
|
||||
}, {});
|
||||
});
|
||||
|
||||
const sheetResult = {
|
||||
name,
|
||||
headers,
|
||||
rows,
|
||||
rowCount: rows.length,
|
||||
};
|
||||
|
||||
if (includeRawRows) {
|
||||
sheetResult.rawRows = rawRows;
|
||||
}
|
||||
|
||||
return sheetResult;
|
||||
});
|
||||
|
||||
return {
|
||||
sheetNames: selectedSheetNames,
|
||||
sheets,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ExcelService;
|
||||
@ -1,10 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const { parseWhereConditions } = require('../../../lib/query_condition_parser');
|
||||
|
||||
const RESERVED_EMPLOYEE_NAME = '测试工号保留';
|
||||
|
||||
class SettingAccountService extends Service {
|
||||
getListWhereSpecialFieldMap() {
|
||||
return {
|
||||
employee_id: {
|
||||
field: 'id',
|
||||
},
|
||||
account_id: {
|
||||
field: 'account_id',
|
||||
},
|
||||
username: {
|
||||
field: '$account.username$',
|
||||
},
|
||||
phone: {
|
||||
field: '$account.phone$',
|
||||
},
|
||||
email: {
|
||||
field: '$account.email$',
|
||||
},
|
||||
quickWhere: {
|
||||
bucket: 'quick',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
createError(message, code = 500) {
|
||||
const error = new Error(message);
|
||||
error.code = code;
|
||||
@ -27,6 +51,14 @@ class SettingAccountService extends Service {
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
normalizeAccountId(value, fieldName = 'account_id') {
|
||||
const accountId = Number(value);
|
||||
if (!Number.isFinite(accountId) || accountId <= 0) {
|
||||
throw this.createError(`${fieldName} 参数不能为空`, 400);
|
||||
}
|
||||
return accountId;
|
||||
}
|
||||
|
||||
getWmsClient() {
|
||||
return this.ctx.app.mysql.get('wms');
|
||||
}
|
||||
@ -127,10 +159,304 @@ class SettingAccountService extends Service {
|
||||
return Number(currentRole.role_id);
|
||||
}
|
||||
|
||||
async formatEmployeeRow(employee) {
|
||||
const account = await this.getWmsClient().get('wms_account', {
|
||||
id: employee.account_id,
|
||||
normalizeRoleIds(ids) {
|
||||
if (!Array.isArray(ids) || ids.length === 0) {
|
||||
throw this.createError('ids 参数不能为空', 400);
|
||||
}
|
||||
|
||||
const roleIds = [];
|
||||
for (const roleId of ids) {
|
||||
const normalized = Number(roleId);
|
||||
if (!Number.isFinite(normalized) || normalized <= 0) {
|
||||
throw this.createError('ids 必须是正整数数组', 400);
|
||||
}
|
||||
roleIds.push(normalized);
|
||||
}
|
||||
return Array.from(new Set(roleIds));
|
||||
}
|
||||
|
||||
flattenRoleTreeMeta(roleNodes, idCollector = [], parentMap = new Map()) {
|
||||
if (!Array.isArray(roleNodes) || roleNodes.length === 0) {
|
||||
return { idCollector, parentMap };
|
||||
}
|
||||
|
||||
for (const node of roleNodes) {
|
||||
const roleId = Number(node && node.role_id);
|
||||
if (Number.isFinite(roleId) && roleId > 0) {
|
||||
idCollector.push(roleId);
|
||||
parentMap.set(roleId, Number(node && node.pid ? node.pid : 0));
|
||||
}
|
||||
|
||||
const children = Array.isArray(node && node.children) ? node.children : [];
|
||||
this.flattenRoleTreeMeta(children, idCollector, parentMap);
|
||||
}
|
||||
|
||||
return { idCollector, parentMap };
|
||||
}
|
||||
|
||||
async resolveAssignableRoleScope() {
|
||||
const roleResult = await this.ctx.service.systems.setting.role.list({
|
||||
includeDisabled: false,
|
||||
includeSystem: false,
|
||||
});
|
||||
|
||||
const roleTree = roleResult && roleResult.data && Array.isArray(roleResult.data.roles)
|
||||
? roleResult.data.roles
|
||||
: [];
|
||||
const { idCollector, parentMap } = this.flattenRoleTreeMeta(roleTree, [], new Map());
|
||||
return {
|
||||
roleIdSet: new Set(idCollector),
|
||||
parentMap,
|
||||
};
|
||||
}
|
||||
|
||||
pruneDescendantRoleIds(roleIds, parentMap) {
|
||||
const selected = new Set(roleIds);
|
||||
const pruned = [];
|
||||
|
||||
for (const roleId of roleIds) {
|
||||
let current = roleId;
|
||||
let keep = true;
|
||||
const visited = new Set();
|
||||
|
||||
while (true) {
|
||||
const parentId = Number(parentMap.get(current) || 0);
|
||||
if (!Number.isFinite(parentId) || parentId <= 0) {
|
||||
break;
|
||||
}
|
||||
if (visited.has(parentId)) {
|
||||
break;
|
||||
}
|
||||
visited.add(parentId);
|
||||
|
||||
if (selected.has(parentId)) {
|
||||
keep = false;
|
||||
break;
|
||||
}
|
||||
|
||||
current = parentId;
|
||||
}
|
||||
|
||||
if (keep) {
|
||||
pruned.push(roleId);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(new Set(pruned));
|
||||
}
|
||||
|
||||
async resolveRequestedRoleIds(data = {}, options = {}) {
|
||||
const required = options.required === true;
|
||||
const hasIds = Object.prototype.hasOwnProperty.call(data, 'ids');
|
||||
const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'role_ids');
|
||||
|
||||
if (!hasIds && !hasRoleIds) {
|
||||
if (required) {
|
||||
throw this.createError('ids 参数不能为空', 400);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const rawRoleIds = hasIds ? data.ids : data.role_ids;
|
||||
const roleIds = this.normalizeRoleIds(rawRoleIds);
|
||||
|
||||
const { roleIdSet, parentMap } = await this.resolveAssignableRoleScope();
|
||||
if (roleIdSet.size === 0) {
|
||||
throw this.createError('当前角色范围为空,无法分配角色', 400);
|
||||
}
|
||||
|
||||
const outOfScopeIds = roleIds.filter(roleId => !roleIdSet.has(roleId));
|
||||
if (outOfScopeIds.length > 0) {
|
||||
throw this.createError(`包含超出当前角色范围的角色ID:${outOfScopeIds.join(',')}`, 400);
|
||||
}
|
||||
|
||||
return this.pruneDescendantRoleIds(roleIds, parentMap);
|
||||
}
|
||||
|
||||
async replaceEmployeeRoles(employeeId, roleIds) {
|
||||
const { ctx } = this;
|
||||
|
||||
await ctx.model.EmployeeRole.destroy({
|
||||
where: {
|
||||
employee_id: employeeId,
|
||||
},
|
||||
});
|
||||
|
||||
const rows = roleIds.map(roleId => ({
|
||||
employee_id: employeeId,
|
||||
role_id: roleId,
|
||||
}));
|
||||
|
||||
await ctx.model.EmployeeRole.bulkCreate(rows);
|
||||
}
|
||||
|
||||
async buildEmployeeRoleGroupMap(employeeIds) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
if (!Array.isArray(employeeIds) || employeeIds.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const employeeRoleRows = await ctx.model.EmployeeRole.findAll({
|
||||
where: {
|
||||
employee_id: employeeIds,
|
||||
},
|
||||
attributes: [ 'employee_id', 'role_id' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
if (employeeRoleRows.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const roleIds = Array.from(new Set(employeeRoleRows
|
||||
.map(item => Number(item.role_id))
|
||||
.filter(roleId => Number.isFinite(roleId) && roleId > 0)));
|
||||
|
||||
const roleRows = await ctx.model.Role.findAll({
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: roleIds,
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'role_code', 'role_name', 'pid', 'status' ],
|
||||
raw: true,
|
||||
});
|
||||
const roleMap = new Map(roleRows.map(role => [ Number(role.id), role ]));
|
||||
|
||||
const employeeRoleMap = new Map();
|
||||
for (const row of employeeRoleRows) {
|
||||
const employeeId = Number(row.employee_id);
|
||||
const roleId = Number(row.role_id);
|
||||
if (!Number.isFinite(employeeId) || employeeId <= 0 || !Number.isFinite(roleId) || roleId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const role = roleMap.get(roleId);
|
||||
if (!employeeRoleMap.has(employeeId)) {
|
||||
employeeRoleMap.set(employeeId, {
|
||||
role_ids: [],
|
||||
roles: [],
|
||||
});
|
||||
}
|
||||
|
||||
const target = employeeRoleMap.get(employeeId);
|
||||
target.role_ids.push(roleId);
|
||||
target.roles.push({
|
||||
role_id: roleId,
|
||||
role_code: role && role.role_code ? role.role_code : '',
|
||||
role_name: role && role.role_name ? role.role_name : '',
|
||||
pid: role ? Number(role.pid || 0) : 0,
|
||||
status: role ? Number(role.status) : 0,
|
||||
});
|
||||
}
|
||||
|
||||
for (const value of employeeRoleMap.values()) {
|
||||
value.role_ids = Array.from(new Set(value.role_ids)).sort((a, b) => a - b);
|
||||
value.roles.sort((a, b) => a.role_id - b.role_id);
|
||||
}
|
||||
|
||||
return employeeRoleMap;
|
||||
}
|
||||
|
||||
async buildWechatBindingMap(accountIds) {
|
||||
if (!Array.isArray(accountIds) || accountIds.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const normalizedAccountIds = Array.from(new Set(accountIds
|
||||
.map(accountId => Number(accountId))
|
||||
.filter(accountId => Number.isFinite(accountId) && accountId > 0)));
|
||||
if (normalizedAccountIds.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const ye4sClient = this.ctx.app.mysql.get('ye4s');
|
||||
const bindingRows = await ye4sClient.select('ye4s_user', {
|
||||
where: {
|
||||
wms_account_id: normalizedAccountIds,
|
||||
},
|
||||
columns: [ 'id', 'wms_account_id' ],
|
||||
orders: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
const bindingMap = new Map();
|
||||
for (const row of bindingRows) {
|
||||
const accountId = Number(row && row.wms_account_id);
|
||||
const ye4sUserId = Number(row && row.id);
|
||||
if (!Number.isFinite(accountId) || accountId <= 0 || !Number.isFinite(ye4sUserId) || ye4sUserId <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (!bindingMap.has(accountId)) {
|
||||
bindingMap.set(accountId, {
|
||||
is_wechat_bound: true,
|
||||
ye4s_user_id: ye4sUserId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return bindingMap;
|
||||
}
|
||||
|
||||
async getOperableEmployeeByAccountId(accountId, options = {}) {
|
||||
const { ctx } = this;
|
||||
const storeId = this.getCurrentStoreId();
|
||||
const normalizedAccountId = this.normalizeAccountId(accountId, 'user_id');
|
||||
const where = {
|
||||
account_id: normalizedAccountId,
|
||||
store_id: storeId,
|
||||
};
|
||||
|
||||
if (options.includeDisabled !== true) {
|
||||
where.status = 1;
|
||||
}
|
||||
|
||||
const employees = await ctx.model.AccountStoreEmployee.findAll({
|
||||
where,
|
||||
order: [[ 'status', 'DESC' ], [ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
if (employees.length === 0) {
|
||||
throw this.createError('目标账号不存在或无权限操作', 404);
|
||||
}
|
||||
|
||||
const { roleIdSet } = await this.resolveAssignableRoleScope();
|
||||
if (roleIdSet.size === 0) {
|
||||
throw this.createError('当前角色范围为空,无法操作目标账号', 400);
|
||||
}
|
||||
|
||||
const employeeIds = employees
|
||||
.map(item => Number(item.id))
|
||||
.filter(employeeId => Number.isFinite(employeeId) && employeeId > 0);
|
||||
const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds);
|
||||
|
||||
for (const employee of employees) {
|
||||
const employeeId = Number(employee.id);
|
||||
const roleGroup = employeeRoleMap.get(employeeId) || {
|
||||
role_ids: [],
|
||||
roles: [],
|
||||
};
|
||||
const hasOutOfScopeRole = roleGroup.role_ids
|
||||
.some(roleId => !roleIdSet.has(Number(roleId)));
|
||||
if (!hasOutOfScopeRole) {
|
||||
return {
|
||||
employee,
|
||||
roleGroup,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw this.createError('目标账号超出当前操作范围', 403);
|
||||
}
|
||||
|
||||
async formatEmployeeRow(employee, options = {}) {
|
||||
let account = options.account || null;
|
||||
if (!account) {
|
||||
account = await this.getWmsClient().get('wms_account', {
|
||||
id: employee.account_id,
|
||||
});
|
||||
}
|
||||
const avatar = await this.getAvatarMeta(employee.id);
|
||||
|
||||
return {
|
||||
@ -150,28 +476,130 @@ class SettingAccountService extends Service {
|
||||
}
|
||||
|
||||
async list(data = {}) {
|
||||
const { ctx } = this;
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const storeId = this.getCurrentStoreId();
|
||||
const statusFilter = data.includeDisabled === true
|
||||
? undefined
|
||||
: (data.status === 0 || data.status === '0' ? 0 : 1);
|
||||
const currentEmployeeId = this.getCurrentEmployeeId();
|
||||
const normalizedWhere = ctx.where && typeof ctx.where === 'object'
|
||||
? { ...ctx.where }
|
||||
: (data.where && typeof data.where === 'object' ? { ...data.where } : {});
|
||||
let parsedResult = ctx.whereParsed;
|
||||
if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) {
|
||||
const parsed = parseWhereConditions({
|
||||
where: normalizedWhere,
|
||||
app,
|
||||
specialFieldMap: this.getListWhereSpecialFieldMap(),
|
||||
});
|
||||
if (!parsed.ok) {
|
||||
throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400);
|
||||
}
|
||||
parsedResult = parsed.result;
|
||||
}
|
||||
|
||||
const where = {
|
||||
store_id: storeId,
|
||||
};
|
||||
if (statusFilter === 0 || statusFilter === 1) {
|
||||
where.status = statusFilter;
|
||||
const andConditions = [
|
||||
{
|
||||
store_id: storeId,
|
||||
},
|
||||
];
|
||||
const hasWhereStatus = Object.prototype.hasOwnProperty.call(normalizedWhere, 'status');
|
||||
if (!hasWhereStatus) {
|
||||
const statusFilter = data.includeDisabled === true
|
||||
? undefined
|
||||
: (data.status === 0 || data.status === '0' ? 0 : 1);
|
||||
if (statusFilter === 0 || statusFilter === 1) {
|
||||
andConditions.push({ status: statusFilter });
|
||||
}
|
||||
}
|
||||
|
||||
const dynamicConditions = parsedResult.dynamicConditions || [];
|
||||
if (dynamicConditions.length > 0) {
|
||||
andConditions.push({ [Op.and]: dynamicConditions });
|
||||
}
|
||||
|
||||
const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere)
|
||||
|| normalizedWhere.quickWhere
|
||||
|| null;
|
||||
const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object'
|
||||
? quickWhereInput.value
|
||||
: quickWhereInput;
|
||||
if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') {
|
||||
const keyword = String(quickWhereValue).trim();
|
||||
andConditions.push({
|
||||
[Op.or]: [
|
||||
{ real_name: { [Op.like]: `%${keyword}%` } },
|
||||
{ '$account.username$': { [Op.like]: `%${keyword}%` } },
|
||||
{ '$account.phone$': { [Op.like]: `%${keyword}%` } },
|
||||
{ '$account.email$': { [Op.like]: `%${keyword}%` } },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const employees = await ctx.model.AccountStoreEmployee.findAll({
|
||||
where,
|
||||
where: {
|
||||
[Op.and]: andConditions,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Account,
|
||||
as: 'account',
|
||||
attributes: [ 'id', 'username', 'phone', 'email', 'real_name' ],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
const { roleIdSet } = await this.resolveAssignableRoleScope();
|
||||
if (roleIdSet.size === 0) {
|
||||
return {
|
||||
code: 200,
|
||||
data: [],
|
||||
};
|
||||
}
|
||||
|
||||
const employeeIds = employees
|
||||
.map(employee => Number(employee.id))
|
||||
.filter(employeeId => Number.isFinite(employeeId) && employeeId > 0);
|
||||
const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds);
|
||||
const accountIds = employees
|
||||
.map(employee => Number(employee.account_id))
|
||||
.filter(accountId => Number.isFinite(accountId) && accountId > 0);
|
||||
const wechatBindingMap = await this.buildWechatBindingMap(accountIds);
|
||||
|
||||
const list = [];
|
||||
for (const employee of employees) {
|
||||
list.push(await this.formatEmployeeRow(employee));
|
||||
const employeeId = Number(employee.id);
|
||||
if (currentEmployeeId && employeeId === currentEmployeeId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const roleGroup = employeeRoleMap.get(employeeId) || {
|
||||
role_ids: [],
|
||||
roles: [],
|
||||
};
|
||||
|
||||
// 只展示当前账号可分配范围内的工号,避免越权操作。
|
||||
const hasOutOfScopeRole = roleGroup.role_ids
|
||||
.some(roleId => !roleIdSet.has(Number(roleId)));
|
||||
if (hasOutOfScopeRole) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const wechatBinding = wechatBindingMap.get(Number(employee.account_id)) || {
|
||||
is_wechat_bound: false,
|
||||
ye4s_user_id: null,
|
||||
};
|
||||
|
||||
list.push({
|
||||
...await this.formatEmployeeRow(employee, {
|
||||
account: employee.account,
|
||||
}),
|
||||
is_wechat_bound: wechatBinding.is_wechat_bound,
|
||||
ye4s_user_id: wechatBinding.ye4s_user_id,
|
||||
role_ids: roleGroup.role_ids,
|
||||
roles: roleGroup.roles,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
@ -205,7 +633,9 @@ class SettingAccountService extends Service {
|
||||
throw this.createError(`新增工号禁止直接使用保留名称 ${RESERVED_EMPLOYEE_NAME}`, 400);
|
||||
}
|
||||
|
||||
const roleId = await this.resolveRoleId(data);
|
||||
const roleIds = await this.resolveRequestedRoleIds(data, {
|
||||
required: true,
|
||||
});
|
||||
let account = await this.findRawAccountByPhone(phone);
|
||||
|
||||
if (account && Number(account.status) !== 1) {
|
||||
@ -256,13 +686,15 @@ class SettingAccountService extends Service {
|
||||
throw this.createError('该手机号已绑定当前主体工号', 409);
|
||||
}
|
||||
|
||||
const { employee, employeeRole } = await service.systems.store.ensureEmployeeRoleBinding({
|
||||
const { employee } = await service.systems.store.ensureEmployeeRoleBinding({
|
||||
accountId: Number(account.id),
|
||||
storeId,
|
||||
roleId,
|
||||
roleId: roleIds[0],
|
||||
realName,
|
||||
});
|
||||
|
||||
await this.replaceEmployeeRoles(Number(employee.id), roleIds);
|
||||
|
||||
await service.systems.auth.user.clearUserCache(Number(account.id));
|
||||
|
||||
const formatted = await this.formatEmployeeRow(employee);
|
||||
@ -270,7 +702,8 @@ class SettingAccountService extends Service {
|
||||
code: 200,
|
||||
data: {
|
||||
...formatted,
|
||||
role_id: Number(employeeRole.role_id),
|
||||
role_id: roleIds[0],
|
||||
role_ids: roleIds,
|
||||
is_new_account: createdAccountId > 0,
|
||||
},
|
||||
};
|
||||
@ -348,14 +781,15 @@ class SettingAccountService extends Service {
|
||||
const employeeId = Number(data.employee_id || data.id || 0);
|
||||
const hasRealName = Object.prototype.hasOwnProperty.call(data, 'real_name') || Object.prototype.hasOwnProperty.call(data, 'realName');
|
||||
const hasFileId = Object.prototype.hasOwnProperty.call(data, 'file_id') || Object.prototype.hasOwnProperty.call(data, 'avatar_file_id') || Object.prototype.hasOwnProperty.call(data, 'fileId');
|
||||
const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'ids') || Object.prototype.hasOwnProperty.call(data, 'role_ids');
|
||||
const realName = this.normalizeName(data.real_name || data.realName);
|
||||
const fileId = Number(data.file_id || data.avatar_file_id || data.fileId || 0);
|
||||
|
||||
if (!employeeId) {
|
||||
throw this.createError('employee_id 参数不能为空', 400);
|
||||
}
|
||||
if (!hasRealName && !hasFileId) {
|
||||
throw this.createError('至少需要更新 real_name 或 file_id', 400);
|
||||
if (!hasRoleIds) {
|
||||
throw this.createError('ids 参数不能为空', 400);
|
||||
}
|
||||
if (hasRealName && !realName) {
|
||||
throw this.createError('real_name 参数不能为空', 400);
|
||||
@ -405,14 +839,64 @@ class SettingAccountService extends Service {
|
||||
});
|
||||
}
|
||||
|
||||
const roleIds = await this.resolveRequestedRoleIds(data, {
|
||||
required: true,
|
||||
});
|
||||
await this.replaceEmployeeRoles(employeeId, roleIds);
|
||||
|
||||
await service.systems.auth.user.clearUserCache(Number(employee.account_id));
|
||||
|
||||
const refreshed = await ctx.model.AccountStoreEmployee.findByPk(employeeId);
|
||||
const roleRows = await ctx.model.EmployeeRole.findAll({
|
||||
where: {
|
||||
employee_id: employeeId,
|
||||
},
|
||||
attributes: [ 'role_id' ],
|
||||
order: [[ 'role_id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
const boundRoleIds = roleRows
|
||||
.map(item => Number(item.role_id))
|
||||
.filter(roleId => Number.isFinite(roleId) && roleId > 0);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: await this.formatEmployeeRow(refreshed),
|
||||
data: {
|
||||
...await this.formatEmployeeRow(refreshed),
|
||||
role_ids: Array.from(new Set(boundRoleIds)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getBindWechatCode(data = {}) {
|
||||
const { service } = this.ctx;
|
||||
const accountId = data.user_id || data.account_id || data.id;
|
||||
const { employee } = await this.getOperableEmployeeByAccountId(accountId);
|
||||
const result = await service.systems.auth.user.getBindWechatCodeByAccountId(Number(employee.account_id), data, {
|
||||
missingAccountMessage: '目标账号不存在,无法生成绑定码',
|
||||
});
|
||||
|
||||
if (!result || Number(result.code) !== 200) {
|
||||
throw this.createError(result && result.message ? result.message : '获取绑定码失败', Number(result && result.code) || 500);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async unbindWechat(data = {}) {
|
||||
const { service } = this.ctx;
|
||||
const accountId = data.user_id || data.account_id || data.id;
|
||||
const { employee } = await this.getOperableEmployeeByAccountId(accountId);
|
||||
const result = await service.systems.auth.user.unbindWechatByAccountId(Number(employee.account_id), {
|
||||
missingAccountMessage: '目标账号不存在,无法解绑',
|
||||
});
|
||||
|
||||
if (!result || Number(result.code) !== 200) {
|
||||
throw this.createError(result && result.message ? result.message : '解绑失败', Number(result && result.code) || 500);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingAccountService;
|
||||
|
||||
651
app/service/systems/setting/permission.js
Normal file
651
app/service/systems/setting/permission.js
Normal file
@ -0,0 +1,651 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class SettingPermissionService extends Service {
|
||||
createError(message, code = 500) {
|
||||
const error = new Error(message);
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
|
||||
getCurrentStoreId() {
|
||||
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||
if (!Number.isFinite(storeId) || storeId <= 0) {
|
||||
throw this.createError('未识别到当前主体,无法操作权限', 400);
|
||||
}
|
||||
return storeId;
|
||||
}
|
||||
|
||||
getCurrentEmployeeId() {
|
||||
const employeeId = Number(this.ctx.user && this.ctx.user.employees_id);
|
||||
if (!Number.isFinite(employeeId) || employeeId <= 0) {
|
||||
return null;
|
||||
}
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
toPositiveNumber(value, fieldName) {
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num <= 0) {
|
||||
throw this.createError(`${fieldName} 参数不能为空`, 400);
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
async getRole(roleId) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const storeId = this.getCurrentStoreId();
|
||||
|
||||
const role = await ctx.model.Role.findOne({
|
||||
where: {
|
||||
id: roleId,
|
||||
[Op.or]: [
|
||||
{ store_id: storeId },
|
||||
{ store_id: 0 },
|
||||
{ store_id: null },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (!role) {
|
||||
throw this.createError('角色不存在或无权限操作', 404);
|
||||
}
|
||||
|
||||
return role;
|
||||
}
|
||||
|
||||
async getPermission(permissionId, includeDisabled = false) {
|
||||
const { ctx } = this;
|
||||
const where = { id: permissionId };
|
||||
if (!includeDisabled) {
|
||||
where.status = 1;
|
||||
}
|
||||
|
||||
const permission = await ctx.model.Permission.findOne({ where });
|
||||
if (!permission) {
|
||||
throw this.createError('权限不存在或已禁用', 404);
|
||||
}
|
||||
|
||||
return permission;
|
||||
}
|
||||
|
||||
normalizePermissionType(type) {
|
||||
const normalized = typeof type === 'string' ? type.trim() : '';
|
||||
if (!normalized) {
|
||||
throw this.createError('type 参数不能为空', 400);
|
||||
}
|
||||
|
||||
const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block' ]);
|
||||
if (!allowedTypes.has(normalized)) {
|
||||
throw this.createError('type 参数不合法', 400);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
normalizeOptionalString(value, fieldName, maxLength = 255) {
|
||||
if (value === undefined || value === null) {
|
||||
return null;
|
||||
}
|
||||
const normalized = String(value).trim();
|
||||
if (!normalized) {
|
||||
return '';
|
||||
}
|
||||
if (normalized.length > maxLength) {
|
||||
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
normalizeParentId(value) {
|
||||
if (value === undefined || value === null || value === '' || Number(value) === 0) {
|
||||
return null;
|
||||
}
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num <= 0) {
|
||||
throw this.createError('parent_id 参数不合法', 400);
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
normalizeSort(value) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return 0;
|
||||
}
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num < 0) {
|
||||
throw this.createError('sort 参数不合法', 400);
|
||||
}
|
||||
return Math.floor(num);
|
||||
}
|
||||
|
||||
normalizeStatus(value) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return 1;
|
||||
}
|
||||
const num = Number(value);
|
||||
if (num === 0 || num === 1) {
|
||||
return num;
|
||||
}
|
||||
throw this.createError('status 参数不合法', 400);
|
||||
}
|
||||
|
||||
normalizeBooleanFlag(value, fieldName) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return 0;
|
||||
}
|
||||
const num = Number(value);
|
||||
if (num === 0 || num === 1) {
|
||||
return num;
|
||||
}
|
||||
throw this.createError(`${fieldName} 参数不合法`, 400);
|
||||
}
|
||||
|
||||
async getAvailablePermissionIdSet({ includeDisabled = false } = {}) {
|
||||
const rows = await this.resolveVisiblePermissionRows({
|
||||
includeDisabled,
|
||||
type: null,
|
||||
keyword: '',
|
||||
});
|
||||
return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0));
|
||||
}
|
||||
|
||||
async ensureParentPermissionExists(parentId) {
|
||||
if (!parentId) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.getPermission(parentId, false);
|
||||
}
|
||||
|
||||
async ensurePermissionsExist(permissionIds) {
|
||||
const { ctx } = this;
|
||||
|
||||
const targetRows = await ctx.model.Permission.findAll({
|
||||
where: {
|
||||
id: permissionIds,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (targetRows.length !== permissionIds.length) {
|
||||
const found = new Set(targetRows.map(item => Number(item.id)));
|
||||
const missing = permissionIds.filter(id => !found.has(Number(id)));
|
||||
throw this.createError(`权限不存在:${missing.join(',')}`, 404);
|
||||
}
|
||||
|
||||
return targetRows;
|
||||
}
|
||||
|
||||
normalizePermissionIds(inputPermissionIds) {
|
||||
if (!Array.isArray(inputPermissionIds)) {
|
||||
throw this.createError('permission_ids 参数不能为空', 400);
|
||||
}
|
||||
|
||||
const permissionIds = [];
|
||||
for (const permissionId of inputPermissionIds) {
|
||||
const normalized = Number(permissionId);
|
||||
if (!Number.isFinite(normalized) || normalized <= 0) {
|
||||
throw this.createError('permission_ids 必须是正整数数组', 400);
|
||||
}
|
||||
permissionIds.push(normalized);
|
||||
}
|
||||
|
||||
return Array.from(new Set(permissionIds));
|
||||
}
|
||||
|
||||
normalizeIds(inputIds, fieldName = 'ids') {
|
||||
if (!Array.isArray(inputIds)) {
|
||||
throw this.createError(`${fieldName} 参数不能为空`, 400);
|
||||
}
|
||||
|
||||
const ids = [];
|
||||
for (const item of inputIds) {
|
||||
const normalized = Number(item);
|
||||
if (!Number.isFinite(normalized) || normalized <= 0) {
|
||||
throw this.createError(`${fieldName} 必须是正整数数组`, 400);
|
||||
}
|
||||
ids.push(normalized);
|
||||
}
|
||||
if (ids.length === 0) {
|
||||
throw this.createError(`${fieldName} 参数不能为空`, 400);
|
||||
}
|
||||
|
||||
return Array.from(new Set(ids));
|
||||
}
|
||||
|
||||
async validatePermissions(permissionIds) {
|
||||
const { ctx } = this;
|
||||
if (permissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const permissions = await ctx.model.Permission.findAll({
|
||||
where: {
|
||||
id: permissionIds,
|
||||
status: 1,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
});
|
||||
|
||||
if (permissions.length !== permissionIds.length) {
|
||||
const foundIds = permissions.map(item => Number(item.id));
|
||||
const missingIds = permissionIds.filter(item => !foundIds.includes(item));
|
||||
throw this.createError(`权限不存在或已禁用:${missingIds.join(',')}`, 400);
|
||||
}
|
||||
|
||||
return permissions;
|
||||
}
|
||||
|
||||
async clearRoleUsersCache(roleId) {
|
||||
const { ctx, service } = this;
|
||||
const storeId = this.getCurrentStoreId();
|
||||
|
||||
const employeeRoleRows = await ctx.model.EmployeeRole.findAll({
|
||||
where: {
|
||||
role_id: roleId,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.AccountStoreEmployee,
|
||||
as: 'employee',
|
||||
attributes: [ 'account_id' ],
|
||||
where: {
|
||||
store_id: storeId,
|
||||
status: 1,
|
||||
},
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
raw: false,
|
||||
});
|
||||
|
||||
const accountIds = Array.from(new Set(employeeRoleRows
|
||||
.map(item => Number(item.employee && item.employee.account_id))
|
||||
.filter(id => Number.isFinite(id) && id > 0)));
|
||||
|
||||
for (const accountId of accountIds) {
|
||||
await service.systems.auth.user.clearUserCache(accountId);
|
||||
}
|
||||
}
|
||||
|
||||
async getCurrentEmployeePermissionIds() {
|
||||
const { ctx } = this;
|
||||
const currentEmployeeId = this.getCurrentEmployeeId();
|
||||
if (!currentEmployeeId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const employeeRoles = await ctx.model.EmployeeRole.findAll({
|
||||
attributes: [ 'role_id' ],
|
||||
where: {
|
||||
employee_id: currentEmployeeId,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Role,
|
||||
as: 'role',
|
||||
attributes: [],
|
||||
where: {
|
||||
status: 1,
|
||||
},
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const roleIds = Array.from(new Set(employeeRoles
|
||||
.map(item => Number(item.role_id))
|
||||
.filter(id => Number.isFinite(id) && id > 0)));
|
||||
if (roleIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, {
|
||||
includeDisabled: false,
|
||||
});
|
||||
}
|
||||
|
||||
async getCurrentRoleId() {
|
||||
const { ctx } = this;
|
||||
const currentEmployeeId = this.getCurrentEmployeeId();
|
||||
if (!currentEmployeeId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const row = await ctx.model.EmployeeRole.findOne({
|
||||
attributes: [ 'role_id' ],
|
||||
where: {
|
||||
employee_id: currentEmployeeId,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.Role,
|
||||
as: 'role',
|
||||
attributes: [],
|
||||
where: {
|
||||
status: 1,
|
||||
},
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const roleId = Number(row && row.role_id);
|
||||
if (!Number.isFinite(roleId) || roleId <= 0) {
|
||||
return null;
|
||||
}
|
||||
return roleId;
|
||||
}
|
||||
|
||||
async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '', scopeMode = 'available' } = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const where = {
|
||||
status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1,
|
||||
};
|
||||
|
||||
if (scopeMode !== 'all') {
|
||||
const currentPermissionIds = await this.getCurrentEmployeePermissionIds();
|
||||
if (currentPermissionIds.length === 0) {
|
||||
return [];
|
||||
}
|
||||
where.id = {
|
||||
[Op.in]: currentPermissionIds,
|
||||
};
|
||||
}
|
||||
if (type) {
|
||||
where.type = type;
|
||||
}
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ path: { [Op.like]: `%${keyword}%` } },
|
||||
{ name: { [Op.like]: `%${keyword}%` } },
|
||||
{ meta_title: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
const permissionRows = await ctx.model.Permission.findAll({
|
||||
where,
|
||||
attributes: [
|
||||
'id',
|
||||
'path',
|
||||
'name',
|
||||
'type',
|
||||
'status',
|
||||
'parent_id',
|
||||
'sort',
|
||||
'component',
|
||||
'redirect',
|
||||
'meta_title',
|
||||
'meta_icon',
|
||||
'hidden',
|
||||
'always_show',
|
||||
],
|
||||
order: [
|
||||
[ 'sort', 'ASC' ],
|
||||
[ 'id', 'ASC' ],
|
||||
],
|
||||
});
|
||||
|
||||
return permissionRows;
|
||||
}
|
||||
|
||||
async list(data = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
const includeDisabled = data.includeDisabled === true;
|
||||
const roleIdRaw = data.role_id || data.roleId;
|
||||
const type = typeof data.type === 'string' && data.type.trim() ? data.type.trim() : null;
|
||||
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
|
||||
|
||||
let role = null;
|
||||
let targetRoleId = roleIdRaw;
|
||||
if (targetRoleId === undefined || targetRoleId === null || targetRoleId === '') {
|
||||
targetRoleId = await this.getCurrentRoleId();
|
||||
}
|
||||
if (targetRoleId !== undefined && targetRoleId !== null && targetRoleId !== '') {
|
||||
const roleId = this.toPositiveNumber(targetRoleId, 'role_id');
|
||||
role = await this.getRole(roleId);
|
||||
}
|
||||
|
||||
// 权限管理页需要展示全量权限树,不能再按当前登录工号已分配权限做裁剪。
|
||||
const permissionRows = await this.resolveVisiblePermissionRows({
|
||||
includeDisabled,
|
||||
type,
|
||||
keyword,
|
||||
scopeMode: 'all',
|
||||
});
|
||||
|
||||
let selectedPermissionSet = new Set();
|
||||
let selectAllPermissions = false;
|
||||
if (role) {
|
||||
const directPermissionIds = ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions);
|
||||
if (directPermissionIds.includes('*')) {
|
||||
selectAllPermissions = true;
|
||||
} else if (directPermissionIds.length > 0) {
|
||||
selectedPermissionSet = new Set(directPermissionIds.map(item => Number(item)));
|
||||
}
|
||||
}
|
||||
|
||||
const permissions = permissionRows.map(item => ({
|
||||
permission_id: Number(item.id),
|
||||
path: item.path || '',
|
||||
name: item.name || '',
|
||||
type: item.type || '',
|
||||
status: Number(item.status),
|
||||
parent_id: item.parent_id === null ? null : Number(item.parent_id),
|
||||
sort: Number(item.sort || 0),
|
||||
component: item.component || '',
|
||||
redirect: item.redirect || '',
|
||||
meta_title: item.meta_title || '',
|
||||
meta_icon: item.meta_icon || '',
|
||||
hidden: Number(item.hidden || 0),
|
||||
always_show: Number(item.always_show || 0),
|
||||
selected: role ? (selectAllPermissions || selectedPermissionSet.has(Number(item.id))) : false,
|
||||
}));
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
role_id: role ? Number(role.id) : null,
|
||||
permissions,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async add(data = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
const path = this.normalizeOptionalString(data.path, 'path', 255);
|
||||
if (!path) {
|
||||
throw this.createError('path 参数不能为空', 400);
|
||||
}
|
||||
|
||||
const permissionData = {
|
||||
path,
|
||||
type: this.normalizePermissionType(data.type),
|
||||
name: this.normalizeOptionalString(data.name, 'name', 100) || '',
|
||||
component: this.normalizeOptionalString(data.component, 'component', 255),
|
||||
redirect: this.normalizeOptionalString(data.redirect, 'redirect', 255),
|
||||
meta_title: this.normalizeOptionalString(data.meta_title, 'meta_title', 100),
|
||||
meta_icon: this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50),
|
||||
parent_id: this.normalizeParentId(data.parent_id),
|
||||
sort: this.normalizeSort(data.sort),
|
||||
hidden: this.normalizeBooleanFlag(data.hidden, 'hidden'),
|
||||
always_show: this.normalizeBooleanFlag(data.always_show, 'always_show'),
|
||||
status: this.normalizeStatus(data.status),
|
||||
};
|
||||
|
||||
await this.ensureParentPermissionExists(permissionData.parent_id);
|
||||
|
||||
let created = null;
|
||||
try {
|
||||
created = await ctx.model.Permission.create(permissionData);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
permission_id: Number(created.id),
|
||||
path: created.path || '',
|
||||
type: created.type || '',
|
||||
parent_id: created.parent_id === null ? null : Number(created.parent_id),
|
||||
status: Number(created.status),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async delete(data = {}) {
|
||||
const { ctx } = this;
|
||||
const permissionIds = this.normalizeIds(data.ids, 'ids');
|
||||
|
||||
await this.ensurePermissionsExist(permissionIds);
|
||||
|
||||
const permissions = await ctx.model.Permission.findAll({
|
||||
where: {
|
||||
id: permissionIds,
|
||||
},
|
||||
attributes: [ 'id', 'status' ],
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const deletedIds = [];
|
||||
const alreadyDeletedIds = [];
|
||||
for (const permission of permissions) {
|
||||
if (Number(permission.status) === 0) {
|
||||
alreadyDeletedIds.push(Number(permission.id));
|
||||
} else {
|
||||
deletedIds.push(Number(permission.id));
|
||||
}
|
||||
}
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
if (deletedIds.length > 0) {
|
||||
await ctx.model.Permission.update({
|
||||
status: 0,
|
||||
}, {
|
||||
where: {
|
||||
id: deletedIds,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await ctx.service.systems.auth.rolePermission.removePermissionsFromAllRoles(deletedIds, {
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
ids: permissionIds,
|
||||
deleted_ids: deletedIds,
|
||||
already_deleted_ids: alreadyDeletedIds,
|
||||
status: 'deleted',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async update(data = {}) {
|
||||
const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id');
|
||||
await this.ensurePermissionsExist([ permissionId ]);
|
||||
|
||||
const permission = await this.getPermission(permissionId, true);
|
||||
|
||||
const hasPath = Object.prototype.hasOwnProperty.call(data, 'path');
|
||||
const hasName = Object.prototype.hasOwnProperty.call(data, 'name');
|
||||
const hasType = Object.prototype.hasOwnProperty.call(data, 'type');
|
||||
const hasComponent = Object.prototype.hasOwnProperty.call(data, 'component');
|
||||
const hasRedirect = Object.prototype.hasOwnProperty.call(data, 'redirect');
|
||||
const hasMetaTitle = Object.prototype.hasOwnProperty.call(data, 'meta_title');
|
||||
const hasMetaIcon = Object.prototype.hasOwnProperty.call(data, 'meta_icon');
|
||||
const hasParentId = Object.prototype.hasOwnProperty.call(data, 'parent_id');
|
||||
const hasSort = Object.prototype.hasOwnProperty.call(data, 'sort');
|
||||
const hasHidden = Object.prototype.hasOwnProperty.call(data, 'hidden');
|
||||
const hasAlwaysShow = Object.prototype.hasOwnProperty.call(data, 'always_show');
|
||||
const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status');
|
||||
|
||||
if (!hasPath && !hasName && !hasType && !hasComponent && !hasRedirect
|
||||
&& !hasMetaTitle && !hasMetaIcon && !hasParentId && !hasSort
|
||||
&& !hasHidden && !hasAlwaysShow && !hasStatus) {
|
||||
throw this.createError('至少需要提供一个可更新字段', 400);
|
||||
}
|
||||
|
||||
const updates = {};
|
||||
if (hasPath) {
|
||||
const path = this.normalizeOptionalString(data.path, 'path', 255);
|
||||
if (!path) {
|
||||
throw this.createError('path 参数不能为空', 400);
|
||||
}
|
||||
updates.path = path;
|
||||
}
|
||||
if (hasName) {
|
||||
updates.name = this.normalizeOptionalString(data.name, 'name', 100) || '';
|
||||
}
|
||||
if (hasType) {
|
||||
updates.type = this.normalizePermissionType(data.type);
|
||||
}
|
||||
if (hasComponent) {
|
||||
updates.component = this.normalizeOptionalString(data.component, 'component', 255);
|
||||
}
|
||||
if (hasRedirect) {
|
||||
updates.redirect = this.normalizeOptionalString(data.redirect, 'redirect', 255);
|
||||
}
|
||||
if (hasMetaTitle) {
|
||||
updates.meta_title = this.normalizeOptionalString(data.meta_title, 'meta_title', 100);
|
||||
}
|
||||
if (hasMetaIcon) {
|
||||
updates.meta_icon = this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50);
|
||||
}
|
||||
if (hasParentId) {
|
||||
const parentId = this.normalizeParentId(data.parent_id);
|
||||
if (parentId && parentId === permissionId) {
|
||||
throw this.createError('parent_id 不能等于 permission_id', 400);
|
||||
}
|
||||
await this.ensureParentPermissionExists(parentId);
|
||||
updates.parent_id = parentId;
|
||||
}
|
||||
if (hasSort) {
|
||||
updates.sort = this.normalizeSort(data.sort);
|
||||
}
|
||||
if (hasHidden) {
|
||||
updates.hidden = this.normalizeBooleanFlag(data.hidden, 'hidden');
|
||||
}
|
||||
if (hasAlwaysShow) {
|
||||
updates.always_show = this.normalizeBooleanFlag(data.always_show, 'always_show');
|
||||
}
|
||||
if (hasStatus) {
|
||||
updates.status = this.normalizeStatus(data.status);
|
||||
}
|
||||
|
||||
await permission.update(updates);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
permission_id: Number(permission.id),
|
||||
path: permission.path || '',
|
||||
type: permission.type || '',
|
||||
parent_id: permission.parent_id === null ? null : Number(permission.parent_id),
|
||||
status: Number(permission.status),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingPermissionService;
|
||||
695
app/service/systems/setting/role.js
Normal file
695
app/service/systems/setting/role.js
Normal file
@ -0,0 +1,695 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
|
||||
class SettingRoleService extends Service {
|
||||
createError(message, code = 500) {
|
||||
const error = new Error(message);
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
|
||||
getCurrentStoreId() {
|
||||
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||
if (!Number.isFinite(storeId) || storeId <= 0) {
|
||||
throw this.createError('未识别到当前主体,无法操作角色', 400);
|
||||
}
|
||||
return storeId;
|
||||
}
|
||||
|
||||
getCurrentEmployeeId() {
|
||||
const employeeId = Number(this.ctx.user && this.ctx.user.employees_id);
|
||||
if (!Number.isFinite(employeeId) || employeeId <= 0) {
|
||||
return null;
|
||||
}
|
||||
return employeeId;
|
||||
}
|
||||
|
||||
toPositiveNumber(value, fieldName) {
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num <= 0) {
|
||||
throw this.createError(`${fieldName} 参数不能为空`, 400);
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
async getEmployee(employeeId, options = {}) {
|
||||
const { ctx } = this;
|
||||
const storeId = this.getCurrentStoreId();
|
||||
const includeDisabled = options.includeDisabled === true;
|
||||
const where = {
|
||||
id: employeeId,
|
||||
store_id: storeId,
|
||||
};
|
||||
if (!includeDisabled) {
|
||||
where.status = 1;
|
||||
}
|
||||
|
||||
const employee = await ctx.model.AccountStoreEmployee.findOne({ where });
|
||||
if (!employee) {
|
||||
throw this.createError('工号不存在或无权限操作', 404);
|
||||
}
|
||||
return employee;
|
||||
}
|
||||
|
||||
normalizeRoleIds(inputRoleIds) {
|
||||
if (!Array.isArray(inputRoleIds) || inputRoleIds.length === 0) {
|
||||
throw this.createError('role_ids 参数不能为空', 400);
|
||||
}
|
||||
|
||||
const roleIds = [];
|
||||
for (const roleId of inputRoleIds) {
|
||||
const normalized = Number(roleId);
|
||||
if (!Number.isFinite(normalized) || normalized <= 0) {
|
||||
throw this.createError('role_ids 必须是正整数数组', 400);
|
||||
}
|
||||
roleIds.push(normalized);
|
||||
}
|
||||
|
||||
return Array.from(new Set(roleIds));
|
||||
}
|
||||
|
||||
async findAssignableRoles(roleIds, storeId) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
|
||||
const roles = await ctx.model.Role.findAll({
|
||||
where: {
|
||||
id: roleIds,
|
||||
status: 1,
|
||||
[Op.or]: [
|
||||
{ store_id: storeId },
|
||||
{ store_id: 0 },
|
||||
{ store_id: null },
|
||||
],
|
||||
},
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
if (roles.length !== roleIds.length) {
|
||||
const foundRoleIds = roles.map(role => Number(role.id));
|
||||
const missingRoleIds = roleIds.filter(roleId => !foundRoleIds.includes(roleId));
|
||||
throw this.createError(`角色不存在、已禁用或超出当前主体范围:${missingRoleIds.join(',')}`, 400);
|
||||
}
|
||||
|
||||
return roles;
|
||||
}
|
||||
|
||||
async clearEmployeeCache(employee) {
|
||||
const { service } = this.ctx;
|
||||
await service.systems.auth.user.clearUserCache(Number(employee.account_id));
|
||||
}
|
||||
|
||||
async getCurrentEmployeeRoleIds() {
|
||||
const { ctx } = this;
|
||||
const currentEmployeeId = this.getCurrentEmployeeId();
|
||||
if (!currentEmployeeId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rows = await ctx.model.EmployeeRole.findAll({
|
||||
where: {
|
||||
employee_id: currentEmployeeId,
|
||||
},
|
||||
attributes: [ 'role_id' ],
|
||||
});
|
||||
|
||||
return Array.from(new Set(rows.map(item => Number(item.role_id)).filter(id => Number.isFinite(id) && id > 0)));
|
||||
}
|
||||
|
||||
collectDescendantRoleIds(roleRows, startRoleIds) {
|
||||
const childrenMap = new Map();
|
||||
for (const row of roleRows) {
|
||||
const parentId = Number(row.pid || 0);
|
||||
if (!childrenMap.has(parentId)) {
|
||||
childrenMap.set(parentId, []);
|
||||
}
|
||||
childrenMap.get(parentId).push(Number(row.id));
|
||||
}
|
||||
|
||||
const visited = new Set();
|
||||
const stack = Array.from(startRoleIds);
|
||||
while (stack.length > 0) {
|
||||
const roleId = Number(stack.pop());
|
||||
if (!Number.isFinite(roleId) || roleId <= 0 || visited.has(roleId)) {
|
||||
continue;
|
||||
}
|
||||
visited.add(roleId);
|
||||
const children = childrenMap.get(roleId) || [];
|
||||
for (const childId of children) {
|
||||
if (!visited.has(childId)) {
|
||||
stack.push(childId);
|
||||
}
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
|
||||
async buildRolePermissionMap(roleRows) {
|
||||
const { service } = this.ctx;
|
||||
const rows = Array.isArray(roleRows) ? roleRows : [];
|
||||
const permissionMap = new Map();
|
||||
|
||||
for (const row of rows) {
|
||||
const roleId = Number(row && row.id);
|
||||
if (!Number.isFinite(roleId) || roleId <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const directPermissionIds = service.systems.auth.rolePermission.toApiPermissionIds(row.permissions);
|
||||
permissionMap.set(roleId, directPermissionIds);
|
||||
}
|
||||
|
||||
return permissionMap;
|
||||
}
|
||||
|
||||
buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap = new Map()) {
|
||||
const nodeMap = new Map();
|
||||
for (const row of roleRows) {
|
||||
const roleId = Number(row.id);
|
||||
nodeMap.set(roleId, {
|
||||
role_id: roleId,
|
||||
role_code: row.role_code || '',
|
||||
role_name: row.role_name || '',
|
||||
description: row.description || '',
|
||||
role_type: Number(row.role_type),
|
||||
scope: Number(row.scope),
|
||||
is_system: Number(row.is_system),
|
||||
status: Number(row.status),
|
||||
store_id: row.store_id === null ? null : Number(row.store_id),
|
||||
pid: Number(row.pid || 0),
|
||||
selected: selectedRoleIdSet.has(roleId),
|
||||
permission_ids: rolePermissionMap.get(roleId) || [],
|
||||
children: [],
|
||||
});
|
||||
}
|
||||
|
||||
for (const node of nodeMap.values()) {
|
||||
const parent = nodeMap.get(node.pid);
|
||||
if (parent) {
|
||||
parent.children.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
const sortNodes = nodes => {
|
||||
nodes.sort((a, b) => a.role_id - b.role_id);
|
||||
for (const item of nodes) {
|
||||
if (item.children && item.children.length > 0) {
|
||||
sortNodes(item.children);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const roots = Array.from(rootRoleIds)
|
||||
.map(roleId => nodeMap.get(Number(roleId)))
|
||||
.filter(Boolean);
|
||||
sortNodes(roots);
|
||||
return roots;
|
||||
}
|
||||
|
||||
normalizeStoreScope(storeId) {
|
||||
if (storeId === null || storeId === undefined) {
|
||||
return 0;
|
||||
}
|
||||
const num = Number(storeId);
|
||||
if (!Number.isFinite(num) || num <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
isRoleVisibleInScope(role, currentRoleRows, currentStoreId, includeSystem) {
|
||||
const roleStoreScope = this.normalizeStoreScope(role.store_id);
|
||||
|
||||
// 当前主体角色默认可见
|
||||
if (roleStoreScope === currentStoreId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// includeSystem=true 时,可见系统角色
|
||||
if (includeSystem && roleStoreScope === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 当前工号若本身处于系统角色域,至少允许看到系统角色,避免空树。
|
||||
const hasSystemCurrentRole = currentRoleRows
|
||||
.some(item => this.normalizeStoreScope(item.store_id) === 0);
|
||||
if (hasSystemCurrentRole && roleStoreScope === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
normalizePermissionIds(inputPermissionIds) {
|
||||
if (inputPermissionIds === '*') {
|
||||
return [ '*' ];
|
||||
}
|
||||
|
||||
if (typeof inputPermissionIds === 'string') {
|
||||
const trimmed = inputPermissionIds.trim();
|
||||
if (!trimmed) {
|
||||
throw this.createError('permission_ids 参数不能为空', 400);
|
||||
}
|
||||
if (trimmed === '*') {
|
||||
return [ '*' ];
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
return this.normalizePermissionIds(parsed);
|
||||
} catch (_) {
|
||||
if (trimmed.includes(',')) {
|
||||
return this.normalizePermissionIds(trimmed.split(','));
|
||||
}
|
||||
throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400);
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(inputPermissionIds)) {
|
||||
throw this.createError('permission_ids 参数不能为空', 400);
|
||||
}
|
||||
|
||||
if (inputPermissionIds.some(item => typeof item === 'string' && item.trim() === '*')) {
|
||||
return [ '*' ];
|
||||
}
|
||||
|
||||
const permissionIds = [];
|
||||
for (const permissionId of inputPermissionIds) {
|
||||
const normalized = Number(permissionId);
|
||||
if (!Number.isFinite(normalized) || normalized <= 0) {
|
||||
throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400);
|
||||
}
|
||||
permissionIds.push(Math.floor(normalized));
|
||||
}
|
||||
|
||||
return Array.from(new Set(permissionIds));
|
||||
}
|
||||
|
||||
normalizePid(value) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return 0;
|
||||
}
|
||||
const pid = Number(value);
|
||||
if (!Number.isFinite(pid) || pid < 0) {
|
||||
throw this.createError('pid 参数不合法', 400);
|
||||
}
|
||||
return pid;
|
||||
}
|
||||
|
||||
async getManageableRole(roleId, options = {}) {
|
||||
const { ctx } = this;
|
||||
const storeId = this.getCurrentStoreId();
|
||||
const includeDisabled = options.includeDisabled === true;
|
||||
|
||||
const where = {
|
||||
id: roleId,
|
||||
store_id: storeId,
|
||||
is_system: 0,
|
||||
};
|
||||
if (!includeDisabled) {
|
||||
where.status = 1;
|
||||
}
|
||||
|
||||
const role = await ctx.model.Role.findOne({ where });
|
||||
if (!role) {
|
||||
throw this.createError('角色不存在、无权限操作或为系统预设角色', 404);
|
||||
}
|
||||
return role;
|
||||
}
|
||||
|
||||
async validatePermissionSet(permissionIds) {
|
||||
const { ctx } = this;
|
||||
if (!Array.isArray(permissionIds) || permissionIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (permissionIds.includes('*')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingPermissions = await ctx.model.Permission.findAll({
|
||||
where: {
|
||||
id: permissionIds,
|
||||
status: 1,
|
||||
},
|
||||
attributes: [ 'id' ],
|
||||
raw: true,
|
||||
});
|
||||
if (existingPermissions.length !== permissionIds.length) {
|
||||
const found = new Set(existingPermissions.map(item => Number(item.id)));
|
||||
const missing = permissionIds.filter(id => !found.has(id));
|
||||
throw this.createError(`权限不存在或已禁用:${missing.join(',')}`, 400);
|
||||
}
|
||||
}
|
||||
|
||||
async replaceRolePermissions(roleId, permissionIds, transaction) {
|
||||
return await this.ctx.service.systems.auth.rolePermission.assignPermissions(roleId, permissionIds, {
|
||||
transaction,
|
||||
});
|
||||
}
|
||||
|
||||
async clearRoleUsersCache(roleId) {
|
||||
const { ctx, service } = this;
|
||||
const storeId = this.getCurrentStoreId();
|
||||
|
||||
const employeeRoleRows = await ctx.model.EmployeeRole.findAll({
|
||||
where: {
|
||||
role_id: roleId,
|
||||
},
|
||||
include: [
|
||||
{
|
||||
model: ctx.model.AccountStoreEmployee,
|
||||
as: 'employee',
|
||||
attributes: [ 'account_id' ],
|
||||
where: {
|
||||
store_id: storeId,
|
||||
status: 1,
|
||||
},
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
raw: false,
|
||||
});
|
||||
|
||||
const accountIds = Array.from(new Set(employeeRoleRows
|
||||
.map(item => Number(item.employee && item.employee.account_id))
|
||||
.filter(id => Number.isFinite(id) && id > 0)));
|
||||
|
||||
for (const accountId of accountIds) {
|
||||
await service.systems.auth.user.clearUserCache(accountId);
|
||||
}
|
||||
}
|
||||
|
||||
async list(data = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const storeId = this.getCurrentStoreId();
|
||||
const includeDisabled = data.includeDisabled === true;
|
||||
const includeSystem = data.includeSystem === true;
|
||||
const currentEmployeeId = this.getCurrentEmployeeId();
|
||||
|
||||
let employee = null;
|
||||
if (currentEmployeeId) {
|
||||
employee = await this.getEmployee(currentEmployeeId, {
|
||||
includeDisabled: true,
|
||||
});
|
||||
}
|
||||
|
||||
// 先拉取当前主体 + 系统角色域,后续按可见规则二次收敛。
|
||||
const roleWhere = {
|
||||
status: includeDisabled ? { [Op.in]: [0, 1] } : 1,
|
||||
[Op.or]: [ { store_id: storeId }, { store_id: 0 }, { store_id: null } ],
|
||||
};
|
||||
|
||||
const roleRows = await ctx.model.Role.findAll({
|
||||
where: roleWhere,
|
||||
attributes: [
|
||||
'id',
|
||||
'role_code',
|
||||
'role_name',
|
||||
'description',
|
||||
'role_type',
|
||||
'scope',
|
||||
'is_system',
|
||||
'status',
|
||||
'store_id',
|
||||
'pid',
|
||||
'permissions',
|
||||
],
|
||||
order: [
|
||||
[ 'is_system', 'DESC' ],
|
||||
[ 'id', 'ASC' ],
|
||||
],
|
||||
});
|
||||
|
||||
const currentRoleIds = await this.getCurrentEmployeeRoleIds();
|
||||
if (currentRoleIds.length === 0) {
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
employee_id: employee ? Number(employee.id) : null,
|
||||
roles: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const roleMap = new Map(roleRows.map(item => [ Number(item.id), item ]));
|
||||
const currentRoleRows = currentRoleIds
|
||||
.map(roleId => roleMap.get(roleId))
|
||||
.filter(Boolean);
|
||||
|
||||
if (currentRoleRows.length === 0) {
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
employee_id: employee ? Number(employee.id) : null,
|
||||
roles: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id)));
|
||||
|
||||
// 仅返回当前角色的下级角色树,不返回自己及同级角色。
|
||||
const subordinateRootRoleIds = new Set(roleRows
|
||||
.filter(item => currentRoleIdSet.has(Number(item.pid || 0)))
|
||||
.filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem))
|
||||
.map(item => Number(item.id)));
|
||||
|
||||
if (subordinateRootRoleIds.size === 0) {
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
employee_id: employee ? Number(employee.id) : null,
|
||||
roles: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const visibleRoleIds = this.collectDescendantRoleIds(roleRows, Array.from(subordinateRootRoleIds));
|
||||
|
||||
const visibleRoleRows = roleRows
|
||||
.filter(item => visibleRoleIds.has(Number(item.id)))
|
||||
.filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem));
|
||||
const rootRoleIds = new Set(visibleRoleRows
|
||||
.filter(item => subordinateRootRoleIds.has(Number(item.id)))
|
||||
.map(item => Number(item.id)));
|
||||
|
||||
let selectedRoleIdSet = new Set();
|
||||
if (employee) {
|
||||
const employeeRoles = await ctx.model.EmployeeRole.findAll({
|
||||
where: {
|
||||
employee_id: employee.id,
|
||||
},
|
||||
});
|
||||
selectedRoleIdSet = new Set(employeeRoles.map(item => Number(item.role_id)));
|
||||
}
|
||||
|
||||
const rolePermissionMap = await this.buildRolePermissionMap(visibleRoleRows);
|
||||
const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
employee_id: employee ? Number(employee.id) : null,
|
||||
roles,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async permission(data = {}) {
|
||||
return this.ctx.service.systems.setting.permission.list(data);
|
||||
}
|
||||
|
||||
async add(data = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
const storeId = this.getCurrentStoreId();
|
||||
const roleCode = typeof data.role_code === 'string' ? data.role_code.trim() : '';
|
||||
const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : '';
|
||||
const description = typeof data.description === 'string' ? data.description.trim() : '';
|
||||
const roleType = Number(data.role_type || 1);
|
||||
const scope = Number(data.scope || 1);
|
||||
const status = data.status === 0 || data.status === '0' ? 0 : 1;
|
||||
const pid = this.normalizePid(data.pid);
|
||||
const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []);
|
||||
const creatorId = Number(this.ctx.user && this.ctx.user.id);
|
||||
|
||||
if (!roleCode) {
|
||||
throw this.createError('role_code 参数不能为空', 400);
|
||||
}
|
||||
if (!roleName) {
|
||||
throw this.createError('role_name 参数不能为空', 400);
|
||||
}
|
||||
if (!Number.isFinite(creatorId) || creatorId <= 0) {
|
||||
throw this.createError('未识别到当前账号,无法创建角色', 400);
|
||||
}
|
||||
|
||||
await this.validatePermissionSet(permissionIds);
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
let createdRole = null;
|
||||
try {
|
||||
createdRole = await ctx.model.Role.create({
|
||||
role_code: roleCode,
|
||||
role_name: roleName,
|
||||
description,
|
||||
role_type: roleType,
|
||||
scope,
|
||||
is_system: 0,
|
||||
status,
|
||||
created_by: creatorId,
|
||||
store_id: storeId,
|
||||
pid,
|
||||
}, { transaction });
|
||||
|
||||
await this.replaceRolePermissions(Number(createdRole.id), permissionIds, transaction);
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
if (error && error.name === 'SequelizeUniqueConstraintError') {
|
||||
throw this.createError('role_code 已存在', 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
role_id: Number(createdRole.id),
|
||||
role_code: createdRole.role_code,
|
||||
role_name: createdRole.role_name,
|
||||
permission_ids: permissionIds,
|
||||
created: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async delete(data = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
const roleIds = this.normalizeRoleIds(data.ids);
|
||||
const roles = [];
|
||||
for (const roleId of roleIds) {
|
||||
const role = await this.getManageableRole(roleId, {
|
||||
includeDisabled: true,
|
||||
});
|
||||
roles.push(role);
|
||||
}
|
||||
|
||||
const deletedIds = [];
|
||||
const alreadyDeletedIds = [];
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
for (const role of roles) {
|
||||
const roleId = Number(role.id);
|
||||
if (Number(role.status) === 0) {
|
||||
alreadyDeletedIds.push(roleId);
|
||||
continue;
|
||||
}
|
||||
|
||||
await role.update({
|
||||
status: 0,
|
||||
updated_at: new Date(),
|
||||
}, { transaction });
|
||||
deletedIds.push(roleId);
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
|
||||
for (const roleId of deletedIds) {
|
||||
await this.clearRoleUsersCache(roleId);
|
||||
}
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
ids: roleIds,
|
||||
deleted_ids: deletedIds,
|
||||
already_deleted_ids: alreadyDeletedIds,
|
||||
status: 'deleted',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async update(data = {}) {
|
||||
const { ctx } = this;
|
||||
|
||||
const roleId = this.toPositiveNumber(data.role_id || data.roleId, 'role_id');
|
||||
const role = await this.getManageableRole(roleId, {
|
||||
includeDisabled: true,
|
||||
});
|
||||
|
||||
const hasRoleName = Object.prototype.hasOwnProperty.call(data, 'role_name');
|
||||
const hasDescription = Object.prototype.hasOwnProperty.call(data, 'description');
|
||||
const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status');
|
||||
const hasPid = Object.prototype.hasOwnProperty.call(data, 'pid');
|
||||
const hasPermissionIds = Object.prototype.hasOwnProperty.call(data, 'permission_ids')
|
||||
|| Object.prototype.hasOwnProperty.call(data, 'permissionIds');
|
||||
|
||||
if (!hasRoleName && !hasDescription && !hasStatus && !hasPid && !hasPermissionIds) {
|
||||
throw this.createError('至少需要更新角色信息或 permission_ids', 400);
|
||||
}
|
||||
if (!hasPermissionIds) {
|
||||
throw this.createError('permission_ids 参数不能为空,角色权限需一次性提交', 400);
|
||||
}
|
||||
|
||||
const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []);
|
||||
await this.validatePermissionSet(permissionIds);
|
||||
|
||||
const updates = {};
|
||||
if (hasRoleName) {
|
||||
const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : '';
|
||||
if (!roleName) {
|
||||
throw this.createError('role_name 参数不能为空', 400);
|
||||
}
|
||||
updates.role_name = roleName;
|
||||
}
|
||||
if (hasDescription) {
|
||||
updates.description = typeof data.description === 'string' ? data.description.trim() : '';
|
||||
}
|
||||
if (hasStatus) {
|
||||
const status = data.status === 0 || data.status === '0' ? 0 : 1;
|
||||
updates.status = status;
|
||||
}
|
||||
if (hasPid) {
|
||||
updates.pid = this.normalizePid(data.pid);
|
||||
}
|
||||
updates.updated_at = new Date();
|
||||
|
||||
const transaction = await ctx.model.transaction();
|
||||
try {
|
||||
if (Object.keys(updates).length > 0) {
|
||||
await role.update(updates, { transaction });
|
||||
}
|
||||
|
||||
await this.replaceRolePermissions(roleId, permissionIds, transaction);
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
if (error && error.name === 'SequelizeUniqueConstraintError') {
|
||||
throw this.createError('角色信息冲突(可能 role_code 重复)', 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
await this.clearRoleUsersCache(roleId);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
role_id: roleId,
|
||||
role_name: role.role_name,
|
||||
permission_ids: permissionIds,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingRoleService;
|
||||
711
app/service/systems/setting/store_warehouse.js
Normal file
711
app/service/systems/setting/store_warehouse.js
Normal file
@ -0,0 +1,711 @@
|
||||
'use strict';
|
||||
|
||||
const crypto = require('node:crypto');
|
||||
const Service = require('egg').Service;
|
||||
|
||||
const SIGN_TEMP_EXPIRE_SECONDS = 600;
|
||||
const AUTH_STATUS_LABELS = Object.freeze({
|
||||
1: '申请中',
|
||||
2: '已通过',
|
||||
3: '已拒绝',
|
||||
4: '已解除',
|
||||
5: '已过期',
|
||||
});
|
||||
|
||||
class SettingStoreWarehouseService extends Service {
|
||||
createError(message, code = 500) {
|
||||
const error = new Error(message);
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
|
||||
getCurrentStoreId() {
|
||||
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
|
||||
if (!Number.isFinite(storeId) || storeId <= 0) {
|
||||
throw this.createError('未识别到当前主体,无法操作签约关系', 400);
|
||||
}
|
||||
return storeId;
|
||||
}
|
||||
|
||||
getCurrentAccountId() {
|
||||
const accountId = Number(this.ctx.user && this.ctx.user.id);
|
||||
if (!Number.isFinite(accountId) || accountId <= 0) {
|
||||
throw this.createError('未识别到当前登录账号', 401);
|
||||
}
|
||||
return accountId;
|
||||
}
|
||||
|
||||
toPositiveNumber(value, fieldName, options = {}) {
|
||||
const { allowEmpty = false } = options;
|
||||
if (allowEmpty && (value === undefined || value === null || value === '')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num <= 0) {
|
||||
throw this.createError(`${fieldName} 参数不能为空`, 400);
|
||||
}
|
||||
return num;
|
||||
}
|
||||
|
||||
normalizePage(value, fieldName, defaultValue, maxValue) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return defaultValue;
|
||||
}
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num <= 0) {
|
||||
throw this.createError(`${fieldName} 参数不合法`, 400);
|
||||
}
|
||||
return Math.min(Math.floor(num), maxValue);
|
||||
}
|
||||
|
||||
normalizeStatusFlag(value, fieldName, defaultValue = null) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return defaultValue;
|
||||
}
|
||||
const num = Number(value);
|
||||
if (num === 0 || num === 1) {
|
||||
return num;
|
||||
}
|
||||
throw this.createError(`${fieldName} 参数不合法`, 400);
|
||||
}
|
||||
|
||||
normalizeAuthStatus(value) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return null;
|
||||
}
|
||||
const num = Number(value);
|
||||
if ([ 1, 2, 3, 4, 5 ].includes(num)) {
|
||||
return num;
|
||||
}
|
||||
throw this.createError('auth_status 参数不合法', 400);
|
||||
}
|
||||
|
||||
normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return defaultValue;
|
||||
}
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num < 0) {
|
||||
throw this.createError(`${fieldName} 参数不合法`, 400);
|
||||
}
|
||||
return Math.floor(num);
|
||||
}
|
||||
|
||||
normalizeText(value, fieldName, maxLength = 500) {
|
||||
if (value === undefined || value === null) {
|
||||
return null;
|
||||
}
|
||||
const normalized = String(value).trim();
|
||||
if (normalized.length > maxLength) {
|
||||
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
normalizeDate(value, fieldName, options = {}) {
|
||||
const { allowNull = true } = options;
|
||||
if (value === undefined || value === null || value === '') {
|
||||
if (allowNull) {
|
||||
return null;
|
||||
}
|
||||
throw this.createError(`${fieldName} 参数不能为空`, 400);
|
||||
}
|
||||
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
throw this.createError(`${fieldName} 参数不合法`, 400);
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
normalizeSignAction(value) {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
const action = String(value).trim();
|
||||
if ([ 'preview', 'confirm' ].includes(action)) {
|
||||
return action;
|
||||
}
|
||||
throw this.createError('action 参数不合法', 400);
|
||||
}
|
||||
|
||||
normalizeTempCode(value) {
|
||||
const code = String(value || '').trim().toUpperCase();
|
||||
if (!code) {
|
||||
throw this.createError('temp_code 参数不能为空', 400);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
getTempCodeCacheKey(tempCode) {
|
||||
return `store_warehouse:sign:${tempCode}`;
|
||||
}
|
||||
|
||||
createTempCode() {
|
||||
return crypto.randomBytes(6).toString('hex').toUpperCase();
|
||||
}
|
||||
|
||||
pickRemaskField(currentSubject) {
|
||||
return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask';
|
||||
}
|
||||
|
||||
resolveRemaskValue(data, currentSubject) {
|
||||
const raw = data.remask !== undefined
|
||||
? data.remask
|
||||
: (currentSubject && currentSubject.isWarehouse ? data.store_remask : data.warehouse_remask);
|
||||
return this.normalizeText(raw, 'remask', 50);
|
||||
}
|
||||
|
||||
buildCurrentRemaskPatch(data, currentSubject) {
|
||||
const remask = this.resolveRemaskValue(data, currentSubject);
|
||||
if (remask === null) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return {
|
||||
[this.pickRemaskField(currentSubject)]: remask,
|
||||
};
|
||||
}
|
||||
|
||||
requireCurrentRemaskPatch(data, currentSubject) {
|
||||
const patch = this.buildCurrentRemaskPatch(data, currentSubject);
|
||||
if (!Object.keys(patch).length) {
|
||||
throw this.createError('remask 参数不能为空', 400);
|
||||
}
|
||||
return patch;
|
||||
}
|
||||
|
||||
async saveTempSignPayload(payload) {
|
||||
const now = Date.now();
|
||||
const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString();
|
||||
const tempCode = this.createTempCode();
|
||||
await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), {
|
||||
...payload,
|
||||
expires_at: expiresAt,
|
||||
}, SIGN_TEMP_EXPIRE_SECONDS);
|
||||
return {
|
||||
tempCode,
|
||||
expiresAt,
|
||||
expiresIn: SIGN_TEMP_EXPIRE_SECONDS,
|
||||
};
|
||||
}
|
||||
|
||||
async getTempSignPayload(tempCode) {
|
||||
const normalizedCode = this.normalizeTempCode(tempCode);
|
||||
const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode));
|
||||
if (!payload) {
|
||||
throw this.createError('临时码无效或已过期', 404);
|
||||
}
|
||||
return {
|
||||
tempCode: normalizedCode,
|
||||
payload,
|
||||
};
|
||||
}
|
||||
|
||||
async clearTempSignPayload(tempCode) {
|
||||
const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null;
|
||||
if (cacheRedis && cacheRedis.del) {
|
||||
await cacheRedis.del(this.getTempCodeCacheKey(tempCode));
|
||||
return;
|
||||
}
|
||||
await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1);
|
||||
}
|
||||
|
||||
buildTempSignView(tempCode, payload, currentSubject) {
|
||||
const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ];
|
||||
const currentSubjectId = Number(currentSubject && currentSubject.id);
|
||||
const expiresAt = payload.expires_at || null;
|
||||
const expiresMs = expiresAt ? new Date(expiresAt).getTime() : 0;
|
||||
|
||||
return {
|
||||
mode: 'preview',
|
||||
temp_code: tempCode,
|
||||
expires_at: expiresAt,
|
||||
expires_in: expiresMs ? Math.max(0, Math.ceil((expiresMs - Date.now()) / 1000)) : 0,
|
||||
is_participant: participantIds.includes(currentSubjectId),
|
||||
can_confirm: currentSubjectId > 0 && currentSubjectId === Number(payload.counterparty_id || 0),
|
||||
initiator: {
|
||||
id: Number(payload.initiator_subject_id || 0),
|
||||
role: payload.initiator_role || '',
|
||||
name: payload.initiator_name || '',
|
||||
},
|
||||
counterparty: {
|
||||
id: Number(payload.counterparty_id || 0),
|
||||
role: payload.counterparty_role || '',
|
||||
name: payload.counterparty_name || '',
|
||||
},
|
||||
sign_info: {
|
||||
store_id: Number(payload.store_id || 0),
|
||||
warehouse_id: Number(payload.warehouse_id || 0),
|
||||
auth_start: payload.auth_start || null,
|
||||
auth_end: payload.auth_end || null,
|
||||
print_quantity: Number(payload.print_quantity || 0),
|
||||
apply_reason: payload.apply_reason || '',
|
||||
remask: payload.remask || '',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getCurrentSubject() {
|
||||
const { ctx } = this;
|
||||
const storeId = this.getCurrentStoreId();
|
||||
const subject = await ctx.model.Store.findOne({
|
||||
where: {
|
||||
id: storeId,
|
||||
},
|
||||
attributes: [ 'id', 'company_name', 'project', 'status' ],
|
||||
});
|
||||
|
||||
if (!subject) {
|
||||
throw this.createError('当前主体不存在', 404);
|
||||
}
|
||||
|
||||
return {
|
||||
id: Number(subject.id),
|
||||
company_name: subject.company_name || '',
|
||||
project: subject.project || '',
|
||||
isWarehouse: subject.project === 'warehouse',
|
||||
status: Number(subject.status || 0),
|
||||
};
|
||||
}
|
||||
|
||||
async getCounterparty(counterpartyId, expectedRole) {
|
||||
const { ctx } = this;
|
||||
const counterparty = await ctx.model.Store.findOne({
|
||||
where: {
|
||||
id: counterpartyId,
|
||||
},
|
||||
attributes: [ 'id', 'company_name', 'project', 'status' ],
|
||||
});
|
||||
|
||||
if (!counterparty) {
|
||||
throw this.createError('签约对象不存在', 404);
|
||||
}
|
||||
|
||||
const isWarehouse = counterparty.project === 'warehouse';
|
||||
if (expectedRole === 'warehouse' && !isWarehouse) {
|
||||
throw this.createError('目标对象不是仓库主体,无法签约', 400);
|
||||
}
|
||||
if (expectedRole === 'store' && isWarehouse) {
|
||||
throw this.createError('目标对象不是货主主体,无法签约', 400);
|
||||
}
|
||||
|
||||
return counterparty;
|
||||
}
|
||||
|
||||
buildListWhere(data, currentSubject) {
|
||||
const where = {};
|
||||
|
||||
if (currentSubject.isWarehouse) {
|
||||
where.warehouse_id = currentSubject.id;
|
||||
} else {
|
||||
where.store_id = currentSubject.id;
|
||||
}
|
||||
|
||||
const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true });
|
||||
if (relationId) {
|
||||
where.id = relationId;
|
||||
}
|
||||
|
||||
const rawCounterpartyId = data.counterparty_id !== undefined
|
||||
? data.counterparty_id
|
||||
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
|
||||
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true });
|
||||
if (counterpartyId) {
|
||||
if (currentSubject.isWarehouse) {
|
||||
where.store_id = counterpartyId;
|
||||
} else {
|
||||
where.warehouse_id = counterpartyId;
|
||||
}
|
||||
}
|
||||
|
||||
const authStatus = this.normalizeAuthStatus(data.auth_status);
|
||||
if (authStatus !== null) {
|
||||
where.auth_status = authStatus;
|
||||
}
|
||||
|
||||
const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null);
|
||||
if (useStatus !== null) {
|
||||
where.use_status = useStatus;
|
||||
}
|
||||
|
||||
return where;
|
||||
}
|
||||
|
||||
getRelationIncludes() {
|
||||
const { ctx } = this;
|
||||
return [
|
||||
{
|
||||
model: ctx.model.Store,
|
||||
as: 'store',
|
||||
attributes: [ 'id', 'company_name', 'project', 'status' ],
|
||||
required: false,
|
||||
},
|
||||
{
|
||||
model: ctx.model.Store,
|
||||
as: 'warehouse',
|
||||
attributes: [ 'id', 'company_name', 'project', 'status' ],
|
||||
required: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
resolvePairIds(data, currentSubject) {
|
||||
const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id';
|
||||
const rawCounterpartyId = data.counterparty_id !== undefined
|
||||
? data.counterparty_id
|
||||
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
|
||||
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName);
|
||||
|
||||
if (currentSubject.isWarehouse) {
|
||||
return {
|
||||
storeId: counterpartyId,
|
||||
warehouseId: currentSubject.id,
|
||||
counterpartyId,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
storeId: currentSubject.id,
|
||||
warehouseId: counterpartyId,
|
||||
counterpartyId,
|
||||
};
|
||||
}
|
||||
|
||||
serializeRelation(relation, currentSubject) {
|
||||
const item = relation && typeof relation.get === 'function'
|
||||
? relation.get({ plain: true })
|
||||
: (relation || {});
|
||||
|
||||
const authStatus = Number(item.auth_status || 0);
|
||||
const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse);
|
||||
const counterparty = currentIsWarehouse ? item.store : item.warehouse;
|
||||
const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : '');
|
||||
const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : '');
|
||||
const counterpartyName = currentIsWarehouse ? storeName : warehouseName;
|
||||
|
||||
let isAuthValid = false;
|
||||
let remainingDays = 0;
|
||||
if (authStatus === 2 && item.auth_start && item.auth_end) {
|
||||
const now = Date.now();
|
||||
const start = new Date(item.auth_start).getTime();
|
||||
const end = new Date(item.auth_end).getTime();
|
||||
if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) {
|
||||
isAuthValid = true;
|
||||
remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24)));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: Number(item.id || 0),
|
||||
store_id: Number(item.store_id || 0),
|
||||
store_name: storeName,
|
||||
warehouse_id: Number(item.warehouse_id || 0),
|
||||
warehouse_name: warehouseName,
|
||||
counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0,
|
||||
counterparty_name: counterpartyName,
|
||||
current_subject_role: currentIsWarehouse ? 'warehouse' : 'store',
|
||||
auth_status: authStatus,
|
||||
auth_status_label: AUTH_STATUS_LABELS[authStatus] || '',
|
||||
apply_reason: item.apply_reason || '',
|
||||
review_comment: item.review_comment || '',
|
||||
apply_time: item.apply_time || null,
|
||||
review_time: item.review_time || null,
|
||||
auth_start: item.auth_start || null,
|
||||
auth_end: item.auth_end || null,
|
||||
actual_end: item.actual_end || null,
|
||||
print_quantity: Number(item.print_quantity || 0),
|
||||
applied_by: item.applied_by ? Number(item.applied_by) : null,
|
||||
reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null,
|
||||
ended_by: item.ended_by ? Number(item.ended_by) : null,
|
||||
remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''),
|
||||
use_status: Number(item.use_status || 0),
|
||||
is_auth_valid: isAuthValid,
|
||||
remaining_days: remainingDays,
|
||||
};
|
||||
}
|
||||
|
||||
async findScopedRelation(data, currentSubject, transaction) {
|
||||
const { ctx } = this;
|
||||
const where = currentSubject.isWarehouse
|
||||
? { warehouse_id: currentSubject.id }
|
||||
: { store_id: currentSubject.id };
|
||||
|
||||
const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true });
|
||||
if (relationId) {
|
||||
where.id = relationId;
|
||||
} else {
|
||||
const pair = this.resolvePairIds(data, currentSubject);
|
||||
where.store_id = pair.storeId;
|
||||
where.warehouse_id = pair.warehouseId;
|
||||
}
|
||||
|
||||
const relation = await ctx.model.StoreWarehouse.findOne({
|
||||
where,
|
||||
include: this.getRelationIncludes(),
|
||||
transaction,
|
||||
});
|
||||
|
||||
if (!relation) {
|
||||
throw this.createError('签约关系不存在或无权限操作', 404);
|
||||
}
|
||||
|
||||
return relation;
|
||||
}
|
||||
|
||||
async list(data = {}) {
|
||||
const { ctx, app } = this;
|
||||
const { Op } = app.Sequelize;
|
||||
const currentSubject = await this.getCurrentSubject();
|
||||
const page = this.normalizePage(data.page, 'page', 1, 1000000);
|
||||
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
|
||||
const offset = (page - 1) * pageSize;
|
||||
const where = this.buildListWhere(data, currentSubject);
|
||||
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
|
||||
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ store_remask: { [Op.like]: `%${keyword}%` } },
|
||||
{ warehouse_remask: { [Op.like]: `%${keyword}%` } },
|
||||
{ '$store.company_name$': { [Op.like]: `%${keyword}%` } },
|
||||
{ '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({
|
||||
where,
|
||||
include: this.getRelationIncludes(),
|
||||
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
|
||||
offset,
|
||||
limit: pageSize,
|
||||
distinct: true,
|
||||
});
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
list: rows.map(item => this.serializeRelation(item, currentSubject)),
|
||||
total: Number(count || 0),
|
||||
page,
|
||||
page_size: pageSize,
|
||||
current_subject: {
|
||||
store_id: currentSubject.id,
|
||||
company_name: currentSubject.company_name,
|
||||
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async sign(data = {}) {
|
||||
const action = this.normalizeSignAction(data.action || data.mode);
|
||||
if (data.temp_code || data.tempCode || action === 'preview') {
|
||||
const { ctx } = this;
|
||||
const transaction = await ctx.model.transaction();
|
||||
|
||||
try {
|
||||
const currentSubject = await this.getCurrentSubject();
|
||||
const accountId = this.getCurrentAccountId();
|
||||
const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode);
|
||||
const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]
|
||||
.includes(Number(currentSubject.id));
|
||||
|
||||
if (!isParticipant) {
|
||||
throw this.createError('当前主体无权使用该临时码', 403);
|
||||
}
|
||||
|
||||
if (action === 'preview' || data.preview === 1 || data.preview === '1') {
|
||||
await transaction.rollback();
|
||||
return {
|
||||
code: 200,
|
||||
data: this.buildTempSignView(tempCode, payload, currentSubject),
|
||||
};
|
||||
}
|
||||
|
||||
if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) {
|
||||
throw this.createError('需由对方主体确认后才可生效', 400);
|
||||
}
|
||||
|
||||
const relationPatch = {
|
||||
store_id: Number(payload.store_id || 0),
|
||||
warehouse_id: Number(payload.warehouse_id || 0),
|
||||
auth_status: 2,
|
||||
apply_reason: payload.apply_reason || '',
|
||||
apply_time: payload.created_at ? new Date(payload.created_at) : new Date(),
|
||||
print_quantity: Number(payload.print_quantity || 0),
|
||||
review_time: new Date(),
|
||||
auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(),
|
||||
auth_end: payload.auth_end ? new Date(payload.auth_end) : null,
|
||||
actual_end: null,
|
||||
applied_by: Number(payload.initiated_by || 0) || accountId,
|
||||
reviewed_by: accountId,
|
||||
ended_by: null,
|
||||
use_status: 1,
|
||||
};
|
||||
|
||||
if (payload.store_remask !== undefined) {
|
||||
relationPatch.store_remask = payload.store_remask;
|
||||
}
|
||||
if (payload.warehouse_remask !== undefined) {
|
||||
relationPatch.warehouse_remask = payload.warehouse_remask;
|
||||
}
|
||||
Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject));
|
||||
|
||||
let relation = await ctx.model.StoreWarehouse.findOne({
|
||||
where: {
|
||||
store_id: relationPatch.store_id,
|
||||
warehouse_id: relationPatch.warehouse_id,
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
const isCreate = !relation;
|
||||
|
||||
if (relation) {
|
||||
await relation.update(relationPatch, { transaction });
|
||||
} else {
|
||||
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
|
||||
}
|
||||
|
||||
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
|
||||
include: this.getRelationIncludes(),
|
||||
transaction,
|
||||
});
|
||||
|
||||
await this.clearTempSignPayload(tempCode);
|
||||
await transaction.commit();
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
mode: 'confirm',
|
||||
temp_code: tempCode,
|
||||
contract: this.serializeRelation(result, currentSubject),
|
||||
action: isCreate ? 'create' : 'update',
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const currentSubject = await this.getCurrentSubject();
|
||||
const accountId = this.getCurrentAccountId();
|
||||
const pair = this.resolvePairIds(data, currentSubject);
|
||||
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
|
||||
const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date();
|
||||
const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true });
|
||||
if (authEnd && authStart.getTime() > authEnd.getTime()) {
|
||||
throw this.createError('auth_end 不能早于 auth_start', 400);
|
||||
}
|
||||
|
||||
const remask = this.resolveRemaskValue(data, currentSubject);
|
||||
const payload = {
|
||||
initiated_by: accountId,
|
||||
initiator_subject_id: currentSubject.id,
|
||||
initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store',
|
||||
initiator_name: currentSubject.company_name,
|
||||
counterparty_id: Number(counterparty.id || 0),
|
||||
counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse',
|
||||
counterparty_name: counterparty.company_name || '',
|
||||
store_id: pair.storeId,
|
||||
warehouse_id: pair.warehouseId,
|
||||
auth_start: authStart.toISOString(),
|
||||
auth_end: authEnd ? authEnd.toISOString() : null,
|
||||
print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
|
||||
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000),
|
||||
remask: remask || '',
|
||||
created_at: new Date().toISOString(),
|
||||
...this.buildCurrentRemaskPatch(data, currentSubject),
|
||||
};
|
||||
|
||||
const signPayload = await this.saveTempSignPayload(payload);
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
mode: 'initiate',
|
||||
temp_code: signPayload.tempCode,
|
||||
expires_at: signPayload.expiresAt,
|
||||
expires_in: signPayload.expiresIn,
|
||||
can_confirm: false,
|
||||
current_subject: {
|
||||
store_id: currentSubject.id,
|
||||
company_name: currentSubject.company_name,
|
||||
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
|
||||
},
|
||||
counterparty: {
|
||||
id: Number(counterparty.id || 0),
|
||||
company_name: counterparty.company_name || '',
|
||||
role: currentSubject.isWarehouse ? 'store' : 'warehouse',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async rename(data = {}) {
|
||||
const { ctx } = this;
|
||||
const transaction = await ctx.model.transaction();
|
||||
|
||||
try {
|
||||
const currentSubject = await this.getCurrentSubject();
|
||||
const relation = await this.findScopedRelation(data, currentSubject, transaction);
|
||||
const relationPatch = this.requireCurrentRemaskPatch(data, currentSubject);
|
||||
|
||||
await relation.update(relationPatch, { transaction });
|
||||
|
||||
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
|
||||
include: this.getRelationIncludes(),
|
||||
transaction,
|
||||
});
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
contract: this.serializeRelation(result, currentSubject),
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async unbind(data = {}) {
|
||||
const { ctx } = this;
|
||||
const transaction = await ctx.model.transaction();
|
||||
|
||||
try {
|
||||
const currentSubject = await this.getCurrentSubject();
|
||||
const relation = await this.findScopedRelation(data, currentSubject, transaction);
|
||||
const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0);
|
||||
|
||||
await relation.update({
|
||||
use_status: nextUseStatus,
|
||||
}, { transaction });
|
||||
|
||||
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
|
||||
include: this.getRelationIncludes(),
|
||||
transaction,
|
||||
});
|
||||
|
||||
await transaction.commit();
|
||||
|
||||
return {
|
||||
code: 200,
|
||||
data: {
|
||||
contract: this.serializeRelation(result, currentSubject),
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = SettingStoreWarehouseService;
|
||||
File diff suppressed because it is too large
Load Diff
1441
app/service/systems/store_warehouse.js
Normal file
1441
app/service/systems/store_warehouse.js
Normal file
File diff suppressed because it is too large
Load Diff
@ -411,6 +411,21 @@ class UploadService extends Service {
|
||||
md5Hash = crypto.createHash('md5').update(data.fileContent).digest('hex');
|
||||
}
|
||||
|
||||
const resolvedFileType = String(data.fileType || data.category || data.type || 'document');
|
||||
const resolvedMimeType = String(data.mimeType || data.type || this.getMimeType(data.fileName || data.name || 'file.xlsx'));
|
||||
const defaultExpireDays = data.businessType === 'receivingReport' ? 90 : 0;
|
||||
const requestedExpireDays = Number(data.expireDays || defaultExpireDays || 0);
|
||||
let resolvedExpireTime = data.expireTime || data.expire_time || null;
|
||||
|
||||
if (!resolvedExpireTime && Number.isFinite(requestedExpireDays) && requestedExpireDays > 0) {
|
||||
resolvedExpireTime = new Date(Date.now() + requestedExpireDays * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
if (resolvedExpireTime) {
|
||||
const expireDate = resolvedExpireTime instanceof Date ? resolvedExpireTime : new Date(resolvedExpireTime);
|
||||
resolvedExpireTime = Number.isNaN(expireDate.getTime()) ? null : expireDate;
|
||||
}
|
||||
|
||||
// 构建数据库记录
|
||||
const fileRecord = {
|
||||
warehouse_id: warehouseId || 0, // 默认为0或使用默认仓库
|
||||
@ -418,14 +433,15 @@ class UploadService extends Service {
|
||||
file_url: fileUrl,
|
||||
file_name: data.name,
|
||||
file_size: data.size,
|
||||
file_type: data.type,
|
||||
mime_type: data.type,
|
||||
file_type: resolvedFileType,
|
||||
mime_type: resolvedMimeType,
|
||||
md5_hash: md5Hash || '',
|
||||
storage_mode: 'cos',
|
||||
storage_class: 'standard',
|
||||
uploader_id: userId?.toString() || '0',
|
||||
uploader_name: userName,
|
||||
uploader_dept: data.uploaderDept || '',
|
||||
expire_time: resolvedExpireTime || null,
|
||||
created_at: new Date(),
|
||||
};
|
||||
|
||||
@ -440,12 +456,20 @@ class UploadService extends Service {
|
||||
});
|
||||
|
||||
if (existingFile) {
|
||||
if (resolvedExpireTime && (!existingFile.expire_time || new Date(existingFile.expire_time).getTime() < resolvedExpireTime.getTime())) {
|
||||
await existingFile.update({
|
||||
expire_time: resolvedExpireTime,
|
||||
updated_at: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
this.ctx.logger.info(`文件已存在,返回已有记录: ${existingFile.file_url}`);
|
||||
return {
|
||||
fileId: existingFile.id,
|
||||
fileUrl: existingFile.file_url,
|
||||
fileKey: existingFile.file_key,
|
||||
fileName: existingFile.file_name,
|
||||
expireTime: resolvedExpireTime || existingFile.expire_time || null,
|
||||
isNew: false,
|
||||
};
|
||||
}
|
||||
|
||||
@ -172,6 +172,7 @@ module.exports = appInfo => {
|
||||
config.poloapi ={
|
||||
|
||||
}
|
||||
config.debug = false; // 生成环境默认关闭 debug,开发环境通过 config.local.js 开启
|
||||
config.printService = {
|
||||
url: 'http://printer.wms.gztbyc.com',
|
||||
};
|
||||
|
||||
83
database/config.js
Normal file
83
database/config.js
Normal file
@ -0,0 +1,83 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
function isPlainObject(value) {
|
||||
return !!value && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function mergeDeep(target, source) {
|
||||
const output = isPlainObject(target) ? { ...target } : {};
|
||||
if (!isPlainObject(source)) {
|
||||
return output;
|
||||
}
|
||||
|
||||
for (const [ key, value ] of Object.entries(source)) {
|
||||
if (isPlainObject(value) && isPlainObject(output[key])) {
|
||||
output[key] = mergeDeep(output[key], value);
|
||||
} else if (isPlainObject(value)) {
|
||||
output[key] = mergeDeep({}, value);
|
||||
} else {
|
||||
output[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
function loadEggConfig(configPath) {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const configFactory = require(configPath);
|
||||
const config = typeof configFactory === 'function'
|
||||
? configFactory({ name: 'sequelize-cli', baseDir: path.dirname(path.dirname(configPath)) })
|
||||
: configFactory;
|
||||
|
||||
return isPlainObject(config) ? config : {};
|
||||
}
|
||||
|
||||
function resolveMysqlClient(appConfig, clientName) {
|
||||
const clients = appConfig && appConfig.mysql && appConfig.mysql.clients;
|
||||
if (clients && clients[clientName]) {
|
||||
return clients[clientName];
|
||||
}
|
||||
|
||||
if (appConfig && appConfig.mysql && appConfig.mysql.host) {
|
||||
return appConfig.mysql;
|
||||
}
|
||||
|
||||
throw new Error(`MySQL client "${clientName}" not found in Egg config.`);
|
||||
}
|
||||
|
||||
const projectRoot = path.resolve(__dirname, '..');
|
||||
const defaultConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.default.js'));
|
||||
const localConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.local.js'));
|
||||
const appConfig = mergeDeep(defaultConfig, localConfig);
|
||||
const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms';
|
||||
const mysqlClient = resolveMysqlClient(appConfig, clientName);
|
||||
|
||||
const baseConfig = {
|
||||
username: mysqlClient.user,
|
||||
password: mysqlClient.password,
|
||||
database: mysqlClient.database,
|
||||
host: mysqlClient.host,
|
||||
port: Number(mysqlClient.port || 3306),
|
||||
dialect: 'mysql',
|
||||
logging: false,
|
||||
define: {
|
||||
freezeTableName: true,
|
||||
underscored: true,
|
||||
timestamps: true,
|
||||
paranoid: true,
|
||||
deletedAt: 'deleted_at',
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
development: { ...baseConfig },
|
||||
test: { ...baseConfig },
|
||||
production: { ...baseConfig },
|
||||
};
|
||||
@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'");
|
||||
if (columns.length > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn('wms_store_warehouse', 'policy_config', {
|
||||
type: Sequelize.JSON,
|
||||
allowNull: true,
|
||||
comment: '货主在仓库的配置与策略',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface, Sequelize) {
|
||||
const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'");
|
||||
if (columns.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn('wms_store_warehouse', 'policy_config');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,154 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const { BIGINT, STRING, TINYINT, DATE, JSON } = Sequelize;
|
||||
const BIGINT_UNSIGNED = BIGINT.UNSIGNED;
|
||||
|
||||
const [ tables ] = await queryInterface.sequelize.query(
|
||||
"SHOW TABLES LIKE 'wms_notification_webhook'"
|
||||
);
|
||||
|
||||
const tableExists = tables.length > 0;
|
||||
|
||||
if (!tableExists) {
|
||||
await queryInterface.createTable('wms_notification_webhook', {
|
||||
id: {
|
||||
type: BIGINT_UNSIGNED,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
allowNull: false,
|
||||
comment: '主键ID',
|
||||
},
|
||||
store_id: {
|
||||
type: BIGINT_UNSIGNED,
|
||||
allowNull: false,
|
||||
comment: '主体ID,对应 wms_store.id',
|
||||
references: {
|
||||
model: 'wms_store',
|
||||
key: 'id',
|
||||
},
|
||||
onUpdate: 'CASCADE',
|
||||
onDelete: 'CASCADE',
|
||||
},
|
||||
hook_name: {
|
||||
type: STRING(100),
|
||||
allowNull: true,
|
||||
comment: 'Webhook 名称',
|
||||
},
|
||||
hook_type: {
|
||||
type: STRING(50),
|
||||
allowNull: false,
|
||||
comment: 'Webhook 类型,用于分派不同消息结构处理类,如 dingtalk、wecom、feishu、custom',
|
||||
},
|
||||
hook_url: {
|
||||
type: STRING(500),
|
||||
allowNull: false,
|
||||
comment: 'Webhook 链接地址',
|
||||
},
|
||||
events: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '订阅事件列表',
|
||||
},
|
||||
extra_config: {
|
||||
type: JSON,
|
||||
allowNull: true,
|
||||
comment: '扩展配置,如签名、请求头、模板映射等',
|
||||
},
|
||||
status: {
|
||||
type: TINYINT(4),
|
||||
allowNull: false,
|
||||
defaultValue: 1,
|
||||
comment: '状态:0-禁用,1-启用',
|
||||
},
|
||||
remark: {
|
||||
type: STRING(255),
|
||||
allowNull: true,
|
||||
comment: '备注',
|
||||
},
|
||||
created_by: {
|
||||
type: BIGINT_UNSIGNED,
|
||||
allowNull: true,
|
||||
comment: '创建人',
|
||||
},
|
||||
created_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
|
||||
comment: '创建时间',
|
||||
},
|
||||
updated_at: {
|
||||
type: DATE,
|
||||
allowNull: false,
|
||||
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
|
||||
comment: '更新时间',
|
||||
},
|
||||
deleted_at: {
|
||||
type: DATE,
|
||||
allowNull: true,
|
||||
comment: '删除时间',
|
||||
},
|
||||
}, {
|
||||
engine: 'InnoDB',
|
||||
charset: 'utf8mb4',
|
||||
collate: 'utf8mb4_unicode_ci',
|
||||
comment: '外部通知 WebHook 配置表',
|
||||
});
|
||||
} else {
|
||||
console.log('Table wms_notification_webhook already exists, ensuring schema and indexes');
|
||||
}
|
||||
|
||||
const [ hookUrlColumns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_notification_webhook` LIKE 'hook_url'");
|
||||
if (hookUrlColumns.length > 0) {
|
||||
const currentType = String(hookUrlColumns[0].Type || '').toLowerCase();
|
||||
if (currentType.includes('varchar(1000)')) {
|
||||
await queryInterface.changeColumn('wms_notification_webhook', 'hook_url', {
|
||||
type: STRING(500),
|
||||
allowNull: false,
|
||||
comment: 'Webhook 链接地址',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const safeCreateIndex = async (tableName, fields, options) => {
|
||||
const [ existingIndexes ] = await queryInterface.sequelize.query(
|
||||
`SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'`
|
||||
);
|
||||
if (existingIndexes.length === 0) {
|
||||
await queryInterface.addIndex(tableName, fields, options);
|
||||
}
|
||||
};
|
||||
|
||||
await safeCreateIndex('wms_notification_webhook', [ 'store_id' ], {
|
||||
name: 'idx_notification_webhook_store_id',
|
||||
});
|
||||
|
||||
await safeCreateIndex('wms_notification_webhook', [ 'hook_type' ], {
|
||||
name: 'idx_notification_webhook_hook_type',
|
||||
});
|
||||
|
||||
await safeCreateIndex('wms_notification_webhook', [ 'status' ], {
|
||||
name: 'idx_notification_webhook_status',
|
||||
});
|
||||
|
||||
await safeCreateIndex('wms_notification_webhook', [ 'store_id', 'hook_type' ], {
|
||||
name: 'idx_notification_webhook_store_type',
|
||||
});
|
||||
|
||||
await safeCreateIndex('wms_notification_webhook', [ 'store_id', 'hook_type', 'hook_url' ], {
|
||||
name: 'uk_notification_webhook_store_type_url',
|
||||
unique: true,
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const [ tables ] = await queryInterface.sequelize.query(
|
||||
"SHOW TABLES LIKE 'wms_notification_webhook'"
|
||||
);
|
||||
|
||||
if (tables.length > 0) {
|
||||
await queryInterface.dropTable('wms_notification_webhook');
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_file` LIKE 'expire_time'");
|
||||
if (columns.length > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.addColumn('wms_file', 'expire_time', {
|
||||
type: Sequelize.DATE,
|
||||
allowNull: true,
|
||||
defaultValue: null,
|
||||
comment: '过期时间,为空表示永不过期',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_file` LIKE 'expire_time'");
|
||||
if (columns.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await queryInterface.removeColumn('wms_file', 'expire_time');
|
||||
},
|
||||
};
|
||||
24
docs/express-model-table-map.md
Normal file
24
docs/express-model-table-map.md
Normal file
@ -0,0 +1,24 @@
|
||||
# Express 模型与数据表整理
|
||||
|
||||
## 一览
|
||||
|
||||
| 模型文件 | Sequelize key | 数据表 | 当前状态 |
|
||||
| --- | --- | --- | --- |
|
||||
| app/model/express.js | Express | wms_express | 已补齐 |
|
||||
| app/model/express_setting.js | ExpressSetting | wms_express_setting | 已补齐 |
|
||||
| app/model/order_express.js | OrderExpress | wms_order_express | 已补齐 |
|
||||
| app/model/order_express_print_data.js | OrderExpressPrintData | wms_order_express_print_data | 已补齐 |
|
||||
| app/model/express_print_record.js | ExpressPrintRecord | wms_express_print_record | 已补齐 |
|
||||
| app/model/print_station_express.js | PrintStationExpress | wms_print_station_express | 已存在 |
|
||||
|
||||
## 关键说明
|
||||
|
||||
- 本次仅整理模型与真实数据表对齐,不改动业务逻辑与接口行为。
|
||||
- 通过 `script/db-query.ps1` 实查,数据库中包含 6 张 express 相关表,上述模型已全部覆盖。
|
||||
- 既有字段型快递信息(如 `wms_entry_order.express_code`、`wms_order_delivery.express_code`)仍保留为业务字段,不属于独立主数据表。
|
||||
|
||||
## 建议的后续收敛
|
||||
|
||||
- 将 `index.getExpressList` 的配置源(`app.config.expressList`)逐步收敛到 `wms_express`,避免配置与数据表双源。
|
||||
- 若后续存在统一查询需求,可新增 `systems/express.js`,统一对 `Express / ExpressSetting / OrderExpress` 的读写入口。
|
||||
- 打印链路可逐步将 `wms_print_station_express` 与 `wms_express_print_record` 做关联查询封装,减少 systemMethods 层的散落操作。
|
||||
@ -1,8 +1,8 @@
|
||||
{
|
||||
"module": "gateway",
|
||||
"description": "内部网关接口,供内网系统间调用,统一使用 POST 请求",
|
||||
"version": "0.1.0",
|
||||
"updatedAt": "2026-03-24",
|
||||
"version": "0.2.0",
|
||||
"updatedAt": "2026-03-29",
|
||||
"headers": [],
|
||||
"methods": {
|
||||
"groups": [
|
||||
@ -12,7 +12,7 @@
|
||||
"list": [
|
||||
{
|
||||
"method": "user.getUserByTempCode",
|
||||
"description": "根据绑定码反查WMS账号ID(供 ye4s 扫码绑定调用)",
|
||||
"description": "根据绑定码反查WMS账号ID并写入扫码状态(扫描即视为已确认,状态缓存3分钟)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
@ -22,7 +22,7 @@
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "绑定码(由 user.getBindWechatCode 生成)"
|
||||
"description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
@ -32,24 +32,30 @@
|
||||
"required": true,
|
||||
"description": "匹配到的 WMS 账号ID"
|
||||
},
|
||||
{
|
||||
"name": "real_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "WMS 账号表中的真实姓名,用于扫码绑定前确认账号"
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "当前绑定状态,如 pending/bound"
|
||||
"description": "当前扫码状态,成功扫码后固定为 scanned"
|
||||
},
|
||||
{
|
||||
"name": "source",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "数据来源,如 cache/db"
|
||||
"description": "数据来源,如 scan-cache"
|
||||
}
|
||||
],
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"method": "user.bindAccountByTempCode",
|
||||
"description": "根据绑定码将 ye4s 用户绑定到 WMS 账号(供 ye4s 扫码后回调)",
|
||||
"description": "根据绑定码对应的扫码状态缓存将 ye4s 用户绑定到 WMS 账号(需先调用扫码反查接口)",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
@ -59,7 +65,7 @@
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "绑定码(由 user.getBindWechatCode 生成)"
|
||||
"description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)"
|
||||
},
|
||||
{
|
||||
"name": "ye4s_user_id",
|
||||
@ -92,6 +98,141 @@
|
||||
"errors": []
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"groupName": "打印绑定模块",
|
||||
"module": "print",
|
||||
"list": [
|
||||
{
|
||||
"method": "print.getBindInfo",
|
||||
"description": "根据 WMS 账号ID和扫码 code 返回可绑定仓库列表;有可绑定仓库时下发 300 秒临时凭据 tempCode,无可绑定仓库时返回空数组且不返回 tempCode",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
"params": [
|
||||
{
|
||||
"name": "account_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "WMS 账号ID"
|
||||
},
|
||||
{
|
||||
"name": "code",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "打印端提供的绑定 code"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "warehouses",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "可绑定仓库列表,元素结构为 { id, name }"
|
||||
},
|
||||
{
|
||||
"name": "tempCode",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "临时绑定凭据,仅当 warehouses 非空时返回"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": 0,
|
||||
"message": "缺少有效参数 account_id 或 code"
|
||||
},
|
||||
{
|
||||
"code": 0,
|
||||
"message": "账号不存在或已禁用"
|
||||
},
|
||||
{
|
||||
"code": 0,
|
||||
"message": "无效code或未绑定"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "print.bindByTempCode",
|
||||
"description": "根据第一步返回的临时凭据执行打印台绑定,提交工作台名称和仓库ID后完成真实绑定",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": false,
|
||||
"headers": [],
|
||||
"params": [
|
||||
{
|
||||
"name": "temp_code",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "第一步返回的临时凭据,300 秒有效"
|
||||
},
|
||||
{
|
||||
"name": "printer",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "工作台名称"
|
||||
},
|
||||
{
|
||||
"name": "warehouse",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"source": "body",
|
||||
"description": "仓库ID"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "code",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "真实绑定 code"
|
||||
},
|
||||
{
|
||||
"name": "printer",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "工作台名称"
|
||||
},
|
||||
{
|
||||
"name": "warehouse",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "仓库ID"
|
||||
},
|
||||
{
|
||||
"name": "computerId",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "打印台电脑ID"
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": 0,
|
||||
"message": "参数缺失"
|
||||
},
|
||||
{
|
||||
"code": 0,
|
||||
"message": "临时code无效或已过期"
|
||||
},
|
||||
{
|
||||
"code": 0,
|
||||
"message": "仓库无绑定权限"
|
||||
},
|
||||
{
|
||||
"code": 0,
|
||||
"message": "仓库id校验失败"
|
||||
},
|
||||
{
|
||||
"code": 0,
|
||||
"message": "该仓库下打印台名称已存在且可用"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
9302
methods/system.json
9302
methods/system.json
File diff suppressed because it is too large
Load Diff
898
package-lock.json
generated
898
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -20,12 +20,14 @@
|
||||
"egg-sequelize": "^6.0.0",
|
||||
"egg-view-ejs": "^3.0.0",
|
||||
"ejs": "^5.0.1",
|
||||
"exceljs": "^4.4.0",
|
||||
"fast-xml-parser": "^5.3.1",
|
||||
"mysql2": "^3.15.3",
|
||||
"path": "^0.12.7",
|
||||
"qiniu-js": "^3.4.3",
|
||||
"soap": "^1.8.0",
|
||||
"spark-md5": "^3.0.2"
|
||||
"spark-md5": "^3.0.2",
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"egg-bin": "6",
|
||||
@ -64,6 +66,7 @@
|
||||
"test:local": "egg-bin test",
|
||||
"cov": "egg-bin cov",
|
||||
"lint": "eslint .",
|
||||
"permission:sync:system-api": "node ./script/sync-system-api-permission.cjs",
|
||||
"check:model-boundary": "node ./script/model-boundary-check.cjs",
|
||||
"ci": "npm run lint && npm run check:model-boundary && npm run cov"
|
||||
},
|
||||
|
||||
224
script/backfill-role-permissions.cjs
Normal file
224
script/backfill-role-permissions.cjs
Normal file
@ -0,0 +1,224 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const ROOT = process.cwd();
|
||||
const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {
|
||||
dryRun: false,
|
||||
dbClient: 'wms',
|
||||
configPath: DEFAULT_CONFIG_PATH,
|
||||
};
|
||||
|
||||
for (const item of argv) {
|
||||
if (item === '--dry-run') {
|
||||
args.dryRun = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.startsWith('--db-client=')) {
|
||||
args.dbClient = String(item.split('=')[1] || '').trim() || 'wms';
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.startsWith('--config-path=')) {
|
||||
const raw = String(item.split('=')[1] || '').trim();
|
||||
args.configPath = path.resolve(ROOT, raw);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
function loadConfig(configPath) {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
throw new Error(`Config file not found: ${configPath}`);
|
||||
}
|
||||
|
||||
const configFactory = require(configPath);
|
||||
return typeof configFactory === 'function'
|
||||
? configFactory({ name: 'wms-role-permissions-backfill' })
|
||||
: configFactory;
|
||||
}
|
||||
|
||||
function normalizeRolePermissions(rawValue) {
|
||||
if (rawValue === undefined || rawValue === null) {
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
}
|
||||
|
||||
if (Array.isArray(rawValue)) {
|
||||
const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item));
|
||||
if (normalizedItems.some(item => item === '*')) {
|
||||
return { allAccess: true, permissionIds: [] };
|
||||
}
|
||||
|
||||
const permissionIds = normalizedItems
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isFinite(item) && item > 0)
|
||||
.map(item => Math.floor(item));
|
||||
|
||||
return {
|
||||
allAccess: false,
|
||||
permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b),
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof rawValue === 'number') {
|
||||
return normalizeRolePermissions([ rawValue ]);
|
||||
}
|
||||
|
||||
if (typeof rawValue === 'string') {
|
||||
const trimmed = rawValue.trim();
|
||||
if (!trimmed) {
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
}
|
||||
if (trimmed === '*') {
|
||||
return { allAccess: true, permissionIds: [] };
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (parsed !== rawValue) {
|
||||
return normalizeRolePermissions(parsed);
|
||||
}
|
||||
} catch (_) {
|
||||
// ignore parse failure and continue.
|
||||
}
|
||||
|
||||
if (trimmed.includes(',')) {
|
||||
return normalizeRolePermissions(trimmed.split(','));
|
||||
}
|
||||
|
||||
return normalizeRolePermissions([ trimmed ]);
|
||||
}
|
||||
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
}
|
||||
|
||||
function serializeRolePermissions(rawValue) {
|
||||
const state = normalizeRolePermissions(rawValue);
|
||||
return state.allAccess ? '*' : JSON.stringify(state.permissionIds);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const cfg = loadConfig(args.configPath);
|
||||
const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient];
|
||||
|
||||
if (!dbClient) {
|
||||
throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`);
|
||||
}
|
||||
|
||||
const conn = await mysql.createConnection({
|
||||
host: dbClient.host,
|
||||
port: Number(dbClient.port),
|
||||
user: dbClient.user,
|
||||
password: dbClient.password,
|
||||
database: dbClient.database,
|
||||
charset: dbClient.charset || 'utf8mb4',
|
||||
});
|
||||
|
||||
try {
|
||||
const [ roleRows ] = await conn.query(
|
||||
'SELECT id, role_code, permissions FROM wms_role ORDER BY id ASC'
|
||||
);
|
||||
const [ legacyRows ] = await conn.query(
|
||||
'SELECT role_id, permission_id FROM wms_role_permission ORDER BY role_id ASC, permission_id ASC'
|
||||
);
|
||||
|
||||
const legacyMap = new Map();
|
||||
for (const row of legacyRows) {
|
||||
const roleId = Number(row.role_id);
|
||||
const permissionId = Number(row.permission_id);
|
||||
if (!Number.isFinite(roleId) || roleId <= 0 || !Number.isFinite(permissionId) || permissionId <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (!legacyMap.has(roleId)) {
|
||||
legacyMap.set(roleId, []);
|
||||
}
|
||||
legacyMap.get(roleId).push(permissionId);
|
||||
}
|
||||
|
||||
const updates = [];
|
||||
for (const row of roleRows) {
|
||||
const roleId = Number(row.id);
|
||||
const legacyPermissionIds = Array.from(new Set((legacyMap.get(roleId) || [])
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isFinite(item) && item > 0)))
|
||||
.sort((a, b) => a - b);
|
||||
|
||||
if (legacyPermissionIds.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const currentState = normalizeRolePermissions(row.permissions);
|
||||
const nextValue = currentState.allAccess
|
||||
? '*'
|
||||
: serializeRolePermissions([ ...currentState.permissionIds, ...legacyPermissionIds ]);
|
||||
const currentValue = currentState.allAccess
|
||||
? '*'
|
||||
: serializeRolePermissions(currentState.permissionIds);
|
||||
|
||||
if (nextValue !== currentValue) {
|
||||
updates.push({
|
||||
roleId,
|
||||
roleCode: row.role_code || '',
|
||||
before: row.permissions,
|
||||
after: nextValue,
|
||||
legacyCount: legacyPermissionIds.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (args.dryRun) {
|
||||
console.log('[backfill-role-permissions] dry-run summary');
|
||||
console.log(JSON.stringify({
|
||||
mode: 'dry-run',
|
||||
totalRoles: roleRows.length,
|
||||
legacyRelationCount: legacyRows.length,
|
||||
affectedRoleCount: updates.length,
|
||||
sample: updates.slice(0, 20),
|
||||
}, null, 2));
|
||||
return;
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
console.log('[backfill-role-permissions] nothing to update');
|
||||
return;
|
||||
}
|
||||
|
||||
await conn.beginTransaction();
|
||||
try {
|
||||
for (const item of updates) {
|
||||
await conn.query(
|
||||
'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?',
|
||||
[ item.after, item.roleId ]
|
||||
);
|
||||
}
|
||||
await conn.commit();
|
||||
} catch (error) {
|
||||
await conn.rollback();
|
||||
throw error;
|
||||
}
|
||||
|
||||
console.log('[backfill-role-permissions] apply summary');
|
||||
console.log(JSON.stringify({
|
||||
mode: 'apply',
|
||||
totalRoles: roleRows.length,
|
||||
legacyRelationCount: legacyRows.length,
|
||||
updatedRoleCount: updates.length,
|
||||
sample: updates.slice(0, 20),
|
||||
}, null, 2));
|
||||
} finally {
|
||||
await conn.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error('[backfill-role-permissions] failed');
|
||||
console.error(error && error.stack ? error.stack : String(error));
|
||||
process.exit(1);
|
||||
});
|
||||
@ -232,17 +232,20 @@ function pathMatchesRule(filePath, rule) {
|
||||
}
|
||||
|
||||
function listDeployableFiles(config) {
|
||||
const output = runCommand('git', [ 'ls-files', '--cached' ]);
|
||||
const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]);
|
||||
const includeRules = Array.isArray(config && config.deployIncludePaths) ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS;
|
||||
const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ];
|
||||
|
||||
return output
|
||||
.split(/\r?\n/)
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean)
|
||||
.filter(item => !item.startsWith('.git/'))
|
||||
.filter(item => includeRules.some(rule => pathMatchesRule(item, rule)))
|
||||
.filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule)));
|
||||
return Array.from(new Set(
|
||||
output
|
||||
.split(/\r?\n/)
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean)
|
||||
.filter(item => !item.startsWith('.git/'))
|
||||
.filter(item => fs.existsSync(path.join(ROOT, item)))
|
||||
.filter(item => includeRules.some(rule => pathMatchesRule(item, rule)))
|
||||
.filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule)))
|
||||
));
|
||||
}
|
||||
|
||||
function buildArchive(stamp, config) {
|
||||
|
||||
362
script/sync-system-api-permission.cjs
Normal file
362
script/sync-system-api-permission.cjs
Normal file
@ -0,0 +1,362 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
const ROOT = process.cwd();
|
||||
const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js');
|
||||
const DEFAULT_METHOD_DOC_PATH = path.join(ROOT, 'methods', 'system.json');
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {
|
||||
dryRun: false,
|
||||
roleId: 2,
|
||||
dbClient: 'wms',
|
||||
configPath: DEFAULT_CONFIG_PATH,
|
||||
methodDocPath: DEFAULT_METHOD_DOC_PATH,
|
||||
};
|
||||
|
||||
for (const item of argv) {
|
||||
if (item === '--dry-run') {
|
||||
args.dryRun = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.startsWith('--role-id=')) {
|
||||
args.roleId = Number(item.split('=')[1]);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.startsWith('--db-client=')) {
|
||||
args.dbClient = String(item.split('=')[1] || '').trim() || 'wms';
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.startsWith('--config-path=')) {
|
||||
const raw = String(item.split('=')[1] || '').trim();
|
||||
args.configPath = path.resolve(ROOT, raw);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item.startsWith('--method-doc=')) {
|
||||
const raw = String(item.split('=')[1] || '').trim();
|
||||
args.methodDocPath = path.resolve(ROOT, raw);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (!Number.isInteger(args.roleId) || args.roleId <= 0) {
|
||||
throw new Error('Invalid --role-id, must be a positive integer.');
|
||||
}
|
||||
|
||||
return args;
|
||||
}
|
||||
|
||||
function loadConfig(configPath) {
|
||||
if (!fs.existsSync(configPath)) {
|
||||
throw new Error(`Config file not found: ${configPath}`);
|
||||
}
|
||||
|
||||
const configFactory = require(configPath);
|
||||
const config = typeof configFactory === 'function'
|
||||
? configFactory({ name: 'wms-permission-sync' })
|
||||
: configFactory;
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
function loadAuthRequiredMethods(methodDocPath) {
|
||||
if (!fs.existsSync(methodDocPath)) {
|
||||
throw new Error(`Method doc not found: ${methodDocPath}`);
|
||||
}
|
||||
|
||||
const json = JSON.parse(fs.readFileSync(methodDocPath, 'utf8'));
|
||||
const groups = json && json.methods && Array.isArray(json.methods.groups)
|
||||
? json.methods.groups
|
||||
: [];
|
||||
|
||||
const methodSet = new Set();
|
||||
for (const group of groups) {
|
||||
const list = group && Array.isArray(group.list) ? group.list : [];
|
||||
for (const item of list) {
|
||||
if (!item || !item.method || item.isNeedAuth !== true) continue;
|
||||
methodSet.add(String(item.method).trim());
|
||||
}
|
||||
}
|
||||
|
||||
return [ ...methodSet ].sort();
|
||||
}
|
||||
|
||||
function normalizeRolePermissions(rawValue) {
|
||||
if (rawValue === undefined || rawValue === null) {
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
}
|
||||
|
||||
if (Array.isArray(rawValue)) {
|
||||
const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item));
|
||||
if (normalizedItems.some(item => item === '*')) {
|
||||
return { allAccess: true, permissionIds: [] };
|
||||
}
|
||||
|
||||
const permissionIds = normalizedItems
|
||||
.map(item => Number(item))
|
||||
.filter(item => Number.isFinite(item) && item > 0)
|
||||
.map(item => Math.floor(item));
|
||||
|
||||
return {
|
||||
allAccess: false,
|
||||
permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b),
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof rawValue === 'number') {
|
||||
return normalizeRolePermissions([ rawValue ]);
|
||||
}
|
||||
|
||||
if (typeof rawValue === 'string') {
|
||||
const trimmed = rawValue.trim();
|
||||
if (!trimmed) {
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
}
|
||||
if (trimmed === '*') {
|
||||
return { allAccess: true, permissionIds: [] };
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
if (parsed !== rawValue) {
|
||||
return normalizeRolePermissions(parsed);
|
||||
}
|
||||
} catch (_) {
|
||||
// ignore parse errors and continue.
|
||||
}
|
||||
|
||||
if (trimmed.includes(',')) {
|
||||
return normalizeRolePermissions(trimmed.split(','));
|
||||
}
|
||||
|
||||
return normalizeRolePermissions([ trimmed ]);
|
||||
}
|
||||
|
||||
return { allAccess: false, permissionIds: [] };
|
||||
}
|
||||
|
||||
function serializeRolePermissions(rawValue) {
|
||||
const state = normalizeRolePermissions(rawValue);
|
||||
return state.allAccess ? '*' : JSON.stringify(state.permissionIds);
|
||||
}
|
||||
|
||||
function buildPermissionDefaults(methodPath, templateRow) {
|
||||
return {
|
||||
path: methodPath,
|
||||
type: 'api',
|
||||
component: templateRow ? templateRow.component : null,
|
||||
name: templateRow && templateRow.name ? templateRow.name : methodPath,
|
||||
redirect: templateRow ? templateRow.redirect : null,
|
||||
meta_title: templateRow && templateRow.meta_title ? templateRow.meta_title : `API:${methodPath}`,
|
||||
meta_icon: templateRow ? templateRow.meta_icon : null,
|
||||
hidden: templateRow ? Number(templateRow.hidden || 0) : 0,
|
||||
always_show: templateRow ? Number(templateRow.always_show || 0) : 0,
|
||||
parent_id: templateRow && templateRow.parent_id ? Number(templateRow.parent_id) : null,
|
||||
sort: templateRow ? Number(templateRow.sort || 0) : 0,
|
||||
status: templateRow ? Number(templateRow.status || 1) : 1,
|
||||
};
|
||||
}
|
||||
|
||||
async function queryPermissionTemplate(conn) {
|
||||
const [ rows ] = await conn.query(`
|
||||
SELECT component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status
|
||||
FROM wms_permission
|
||||
WHERE type = 'api'
|
||||
ORDER BY id ASC
|
||||
LIMIT 1
|
||||
`);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
async function queryExistingPermissions(conn, methodPaths) {
|
||||
if (methodPaths.length === 0) return new Map();
|
||||
|
||||
const placeholders = methodPaths.map(() => '?').join(',');
|
||||
const [ rows ] = await conn.query(
|
||||
`SELECT id, path, status FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`,
|
||||
methodPaths
|
||||
);
|
||||
|
||||
const result = new Map();
|
||||
for (const row of rows) {
|
||||
result.set(row.path, {
|
||||
id: Number(row.id),
|
||||
status: Number(row.status),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function insertPermission(conn, defaults) {
|
||||
const [ result ] = await conn.query(
|
||||
`INSERT INTO wms_permission
|
||||
(path, type, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
|
||||
[
|
||||
defaults.path,
|
||||
defaults.type,
|
||||
defaults.component,
|
||||
defaults.name,
|
||||
defaults.redirect,
|
||||
defaults.meta_title,
|
||||
defaults.meta_icon,
|
||||
defaults.hidden,
|
||||
defaults.always_show,
|
||||
defaults.parent_id,
|
||||
defaults.sort,
|
||||
defaults.status,
|
||||
]
|
||||
);
|
||||
|
||||
return result.insertId;
|
||||
}
|
||||
|
||||
async function activatePermission(conn, permissionId) {
|
||||
const [ result ] = await conn.query(
|
||||
'UPDATE wms_permission SET status = 1, update_at = NOW() WHERE id = ? AND status <> 1',
|
||||
[ permissionId ]
|
||||
);
|
||||
return result.affectedRows > 0;
|
||||
}
|
||||
|
||||
async function bindRolePermission(conn, roleId, permissionId) {
|
||||
const [ roleRows ] = await conn.query(
|
||||
'SELECT permissions FROM wms_role WHERE id = ? LIMIT 1',
|
||||
[ roleId ]
|
||||
);
|
||||
const roleRow = roleRows[0];
|
||||
if (!roleRow) {
|
||||
throw new Error(`Role not found: ${roleId}`);
|
||||
}
|
||||
|
||||
const currentState = normalizeRolePermissions(roleRow.permissions);
|
||||
|
||||
if (currentState.allAccess || currentState.permissionIds.includes(Number(permissionId))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const nextPermissions = [ ...currentState.permissionIds, Number(permissionId) ];
|
||||
const [ result ] = await conn.query(
|
||||
'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?',
|
||||
[ serializeRolePermissions(nextPermissions), roleId ]
|
||||
);
|
||||
return result.affectedRows > 0;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const cfg = loadConfig(args.configPath);
|
||||
const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient];
|
||||
|
||||
if (!dbClient) {
|
||||
throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`);
|
||||
}
|
||||
|
||||
const methodPaths = loadAuthRequiredMethods(args.methodDocPath);
|
||||
if (methodPaths.length === 0) {
|
||||
console.log('[sync-system-api-permission] no isNeedAuth=true methods found.');
|
||||
return;
|
||||
}
|
||||
|
||||
const conn = await mysql.createConnection({
|
||||
host: dbClient.host,
|
||||
port: Number(dbClient.port),
|
||||
user: dbClient.user,
|
||||
password: dbClient.password,
|
||||
database: dbClient.database,
|
||||
charset: dbClient.charset || 'utf8mb4',
|
||||
});
|
||||
|
||||
try {
|
||||
const templateRow = await queryPermissionTemplate(conn);
|
||||
const existingMap = await queryExistingPermissions(conn, methodPaths);
|
||||
|
||||
const missingPaths = methodPaths.filter(item => !existingMap.has(item));
|
||||
const disabledPaths = methodPaths.filter(item => {
|
||||
const row = existingMap.get(item);
|
||||
return row && Number(row.status) !== 1;
|
||||
});
|
||||
const created = [];
|
||||
const reactivated = [];
|
||||
const touchedPermissionIds = [];
|
||||
|
||||
if (!args.dryRun && (missingPaths.length > 0 || disabledPaths.length > 0)) {
|
||||
await conn.beginTransaction();
|
||||
try {
|
||||
for (const methodPath of missingPaths) {
|
||||
const defaults = buildPermissionDefaults(methodPath, templateRow);
|
||||
const permissionId = await insertPermission(conn, defaults);
|
||||
created.push({ methodPath, permissionId });
|
||||
touchedPermissionIds.push(permissionId);
|
||||
}
|
||||
|
||||
for (const methodPath of disabledPaths) {
|
||||
const permissionRow = existingMap.get(methodPath);
|
||||
if (!permissionRow || !permissionRow.id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const updated = await activatePermission(conn, permissionRow.id);
|
||||
if (updated) {
|
||||
reactivated.push({ methodPath, permissionId: permissionRow.id });
|
||||
}
|
||||
touchedPermissionIds.push(permissionRow.id);
|
||||
}
|
||||
|
||||
await conn.commit();
|
||||
} catch (error) {
|
||||
await conn.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const latestMap = args.dryRun
|
||||
? existingMap
|
||||
: await queryExistingPermissions(conn, methodPaths);
|
||||
|
||||
for (const methodPath of methodPaths) {
|
||||
const permissionRow = latestMap.get(methodPath);
|
||||
if (permissionRow && permissionRow.id) touchedPermissionIds.push(permissionRow.id);
|
||||
}
|
||||
|
||||
const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ];
|
||||
let roleBindingCreated = 0;
|
||||
|
||||
if (!args.dryRun) {
|
||||
for (const permissionId of uniquePermissionIds) {
|
||||
const createdBinding = await bindRolePermission(conn, args.roleId, permissionId);
|
||||
if (createdBinding) roleBindingCreated++;
|
||||
}
|
||||
}
|
||||
|
||||
const summary = {
|
||||
mode: args.dryRun ? 'dry-run' : 'apply',
|
||||
roleId: args.roleId,
|
||||
totalAuthMethods: methodPaths.length,
|
||||
existingPermissionCount: existingMap.size,
|
||||
missingPermissionCount: missingPaths.length,
|
||||
disabledPermissionCount: disabledPaths.length,
|
||||
createdPermissionCount: created.length,
|
||||
reactivatedPermissionCount: reactivated.length,
|
||||
roleBindingCreated,
|
||||
sampleMissing: missingPaths.slice(0, 20),
|
||||
sampleDisabled: disabledPaths.slice(0, 20),
|
||||
};
|
||||
|
||||
console.log('[sync-system-api-permission] summary');
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
} finally {
|
||||
await conn.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error('[sync-system-api-permission] failed');
|
||||
console.error(error && error.stack ? error.stack : String(error));
|
||||
process.exit(1);
|
||||
});
|
||||
112
stock.todo
112
stock.todo
@ -1,112 +0,0 @@
|
||||
# stock.todo
|
||||
|
||||
## 任务目标
|
||||
- 提取 `app/service/systemMethods/stock/warehouse.js` 迁移前 method 的历史测试请求记录。
|
||||
- 精简并保留新接口(`stock.warehouse.*`)的测试入口。
|
||||
- 根据输入/输出补全 `warehouse.js` 方法头注释和 API 文档 `description`。
|
||||
|
||||
## 迁移方法映射(旧 -> 新)
|
||||
- `stock.stockWarehouse` -> `stock.warehouse.list`
|
||||
- `stock.getProhibitedType` -> `stock.warehouse.getProhibitedType`
|
||||
- `stock.getInfo` -> `stock.warehouse.getInfo`
|
||||
- `stock.saveWarehouseStock` -> `stock.warehouse.saveWarehouseStock`
|
||||
- `stock.createWarehouseStock` -> `stock.warehouse.createWarehouseStock`
|
||||
- `stock.getBarcodes` -> `stock.warehouse.getBarcodes`
|
||||
- `stock.saveWarehouseStockBarcode` -> `stock.warehouse.saveWarehouseStockBarcode`
|
||||
- `stock.getStoreStocks` -> `stock.warehouse.getStoreStocks`
|
||||
- `stock.bindItem` -> `stock.warehouse.bindItem`
|
||||
- `stock.unbindItem` -> `stock.warehouse.unbindItem`
|
||||
- `stock.checkItemCodeUnique` -> `stock.warehouse.checkItemCodeUnique`
|
||||
- `stock.queryStockLogs` -> `stock.warehouse.queryStockLogs`
|
||||
- `stock.handleBatchDelete` -> `stock.warehouse.handleBatchDelete`
|
||||
- `stock.deleteUnit` -> `stock.warehouse.deleteUnit`
|
||||
- `stock.deleteProhibited` -> `stock.warehouse.deleteProhibited`
|
||||
- `stock.handleBatchChange` -> `stock.warehouse.handleBatchChange`
|
||||
- `stock.getStockUnits` -> `stock.warehouse.getStockUnits`
|
||||
- `stock.getUnitList` -> `stock.warehouse.getUnitList`
|
||||
- `stock.createProhibited` -> `stock.warehouse.createProhibited`
|
||||
- `stock.createUnit` -> `stock.warehouse.createUnit`
|
||||
- `stock.search` -> `stock.warehouse.search`
|
||||
|
||||
## 历史测试请求记录提取(迁移前/过渡期)
|
||||
来源:`node_modules/.mochawesome-reports/mochawesome.json`(2026-03-25)
|
||||
|
||||
### 记录1:新列表接口请求
|
||||
- case: `system.stock.warehouse.namespaced.test.js`
|
||||
- method: `stock.warehouse.list`
|
||||
- request:
|
||||
```json
|
||||
{
|
||||
"pagination": { "page": 1, "pageSize": 5 },
|
||||
"where": {}
|
||||
}
|
||||
```
|
||||
- expected:
|
||||
```json
|
||||
{
|
||||
"httpStatus": 200,
|
||||
"flag": "success",
|
||||
"code": 200,
|
||||
"data": {
|
||||
"list": "Array",
|
||||
"pagination": "Object"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 记录2:旧入口退场验证请求(历史)
|
||||
- case: `system.stock.warehouse.namespaced.test.js`(精简前)
|
||||
- method: `stock.stockWarehouse`
|
||||
- request:
|
||||
```json
|
||||
{
|
||||
"pagination": { "page": 1, "pageSize": 5 },
|
||||
"where": {}
|
||||
}
|
||||
```
|
||||
- expected:
|
||||
```json
|
||||
{
|
||||
"httpStatus": 500,
|
||||
"flag": "failure",
|
||||
"code": 500,
|
||||
"message": "方法 stockWarehouse 不存在"
|
||||
}
|
||||
```
|
||||
|
||||
### 记录3:where 条件解析服务级样本
|
||||
来源:`test/app/service/systems/stock_store.stockWarehouse.conditions.test.js`
|
||||
- input:
|
||||
```json
|
||||
{
|
||||
"where": {
|
||||
"item_code": { "operator": "like", "value": "SKU" },
|
||||
"barcode": { "operator": "like", "value": "BC" },
|
||||
"prohibited_type": { "operator": "eq", "value": 2 },
|
||||
"quantity": { "operator": "ge", "type": "number", "value": "2" }
|
||||
},
|
||||
"pagination": { "page": 1, "pageSize": 10 },
|
||||
"sort": { "sortField": "quantity", "sortOrder": "ASC" }
|
||||
}
|
||||
```
|
||||
- expected:
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "查询成功",
|
||||
"data.pagination.page": 1,
|
||||
"data.pagination.pageSize": 10,
|
||||
"data.queryInfo.hasBarcodeSearch": true
|
||||
}
|
||||
```
|
||||
|
||||
## 新接口精简测试方案
|
||||
- 保留:`test/app/controller/system.stock.warehouse.namespaced.test.js`
|
||||
- 用例:只验证 `stock.warehouse.list` 请求成功与核心返回结构。
|
||||
- 下沉:复杂 where/operator 组合继续由 service 级测试覆盖。
|
||||
|
||||
## 执行结果
|
||||
- [x] `warehouse.js` 方法头注释补充(输入/输出声明)
|
||||
- [x] 新接口测试用例精简
|
||||
- [x] `methods/system.json` 的 `stock.warehouse.*` description 语义化更新(21项)
|
||||
- [x] 回归测试复跑并记录结果(`8 passing`)
|
||||
@ -10,23 +10,49 @@ const {
|
||||
const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28);
|
||||
|
||||
describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => {
|
||||
it('should bind, unbind, and bind again for ye4s user', async () => {
|
||||
it('should scan, bind, unbind, and bind again for ye4s user', async () => {
|
||||
const { token } = await getAuthToken();
|
||||
|
||||
const ensurePendingCode = async () => {
|
||||
let bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token);
|
||||
assert.equal(bindCodeRes.status, 200);
|
||||
assert.equal(bindCodeRes.body.flag, 'success');
|
||||
|
||||
if (bindCodeRes.body?.data?.status === 'bound') {
|
||||
const unbindFirst = await invokeSystemMethod('user.unbindWechat', {}, token);
|
||||
assert.equal(unbindFirst.status, 200);
|
||||
assert.equal(unbindFirst.body.flag, 'success');
|
||||
bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token);
|
||||
assert.equal(bindCodeRes.status, 200);
|
||||
assert.equal(bindCodeRes.body.flag, 'success');
|
||||
}
|
||||
|
||||
const nextCode = String(bindCodeRes.body?.data?.code || '');
|
||||
assert.match(nextCode, /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
|
||||
return nextCode;
|
||||
};
|
||||
|
||||
const infoRes = await invokeSystemMethod('user.info', {}, token);
|
||||
assert.equal(infoRes.status, 200);
|
||||
assert.equal(infoRes.body.flag, 'success');
|
||||
const accountId = Number(infoRes.body?.data?.id);
|
||||
assert.ok(Number.isFinite(accountId) && accountId > 0);
|
||||
|
||||
const bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {
|
||||
forceRefresh: true,
|
||||
init: true,
|
||||
}, token);
|
||||
assert.equal(bindCodeRes.status, 200);
|
||||
assert.equal(bindCodeRes.body.flag, 'success');
|
||||
const code = String(bindCodeRes.body?.data?.code || '');
|
||||
assert.ok(code.length > 10);
|
||||
const code = await ensurePendingCode();
|
||||
|
||||
const scanRes1 = await invokeGatewayMethod('user.getUserByTempCode', { code });
|
||||
assert.equal(scanRes1.status, 200);
|
||||
assert.equal(scanRes1.body.flag, 'success');
|
||||
assert.equal(scanRes1.body.code, 200);
|
||||
assert.equal(Number(scanRes1.body?.data?.account_id), accountId);
|
||||
assert.ok(String(scanRes1.body?.data?.real_name || ''));
|
||||
assert.equal(scanRes1.body?.data?.status, 'scanned');
|
||||
|
||||
const scannedStateRes1 = await invokeSystemMethod('user.getBindWechatCode', {}, token);
|
||||
assert.equal(scannedStateRes1.status, 200);
|
||||
assert.equal(scannedStateRes1.body.flag, 'success');
|
||||
assert.equal(scannedStateRes1.body?.data?.status, 'scanned');
|
||||
assert.equal(String(scannedStateRes1.body?.data?.code || ''), code);
|
||||
|
||||
const bindRes1 = await invokeGatewayMethod('user.bindAccountByTempCode', {
|
||||
code,
|
||||
@ -46,8 +72,18 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () =>
|
||||
assert.equal(unbindRes.body?.data?.status, 'unbound');
|
||||
assert.equal(Number(unbindRes.body?.data?.account_id), accountId);
|
||||
|
||||
const code2 = await ensurePendingCode();
|
||||
|
||||
const scanRes2 = await invokeGatewayMethod('user.getUserByTempCode', { code: code2 });
|
||||
assert.equal(scanRes2.status, 200);
|
||||
assert.equal(scanRes2.body.flag, 'success');
|
||||
assert.equal(scanRes2.body.code, 200);
|
||||
assert.equal(Number(scanRes2.body?.data?.account_id), accountId);
|
||||
assert.ok(String(scanRes2.body?.data?.real_name || ''));
|
||||
assert.equal(scanRes2.body?.data?.status, 'scanned');
|
||||
|
||||
const bindRes2 = await invokeGatewayMethod('user.bindAccountByTempCode', {
|
||||
code,
|
||||
code: code2,
|
||||
ye4s_user_id: YE4S_TEST_USER_ID,
|
||||
});
|
||||
assert.equal(bindRes2.status, 200);
|
||||
@ -57,11 +93,10 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () =>
|
||||
assert.equal(Number(bindRes2.body?.data?.ye4s_user_id), YE4S_TEST_USER_ID);
|
||||
assert.equal(bindRes2.body?.data?.status, 'bound');
|
||||
|
||||
const verifyRes = await invokeGatewayMethod('user.getUserByTempCode', { code });
|
||||
assert.equal(verifyRes.status, 200);
|
||||
assert.equal(verifyRes.body.flag, 'success');
|
||||
assert.equal(verifyRes.body.code, 200);
|
||||
assert.equal(Number(verifyRes.body?.data?.account_id), accountId);
|
||||
assert.equal(verifyRes.body?.data?.status, 'bound');
|
||||
const boundStateRes = await invokeSystemMethod('user.getBindWechatCode', {}, token);
|
||||
assert.equal(boundStateRes.status, 200);
|
||||
assert.equal(boundStateRes.body.flag, 'success');
|
||||
assert.equal(boundStateRes.body?.data?.status, 'bound');
|
||||
assert.equal(String(boundStateRes.body?.data?.code || ''), '');
|
||||
});
|
||||
});
|
||||
|
||||
@ -0,0 +1,195 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
getAuthToken,
|
||||
invokeSystemMethod,
|
||||
invokeGatewayMethod,
|
||||
} = require('../../support/system_method_client');
|
||||
|
||||
const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28);
|
||||
|
||||
const EXTRA_HEADERS = {
|
||||
platform: 'web',
|
||||
project: 'all',
|
||||
};
|
||||
|
||||
function buildTempPhone() {
|
||||
return `139${String(Date.now()).slice(-8)}`;
|
||||
}
|
||||
|
||||
function flattenRoleIds(roleNodes, collector = []) {
|
||||
if (!Array.isArray(roleNodes)) {
|
||||
return collector;
|
||||
}
|
||||
for (const item of roleNodes) {
|
||||
const roleId = Number(item && item.role_id);
|
||||
if (Number.isFinite(roleId) && roleId > 0) {
|
||||
collector.push(roleId);
|
||||
}
|
||||
flattenRoleIds(item && item.children, collector);
|
||||
}
|
||||
return collector;
|
||||
}
|
||||
|
||||
describe('test/app/controller/system.setting.account.getBindWechatCode.test.js', () => {
|
||||
let token = '';
|
||||
let tempEmployeeId = 0;
|
||||
let tempAccountId = 0;
|
||||
|
||||
async function getAssignableRoleIds() {
|
||||
const res = await invokeSystemMethod('setting.role.list', {
|
||||
includeDisabled: false,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
|
||||
const roleIds = Array.from(new Set(flattenRoleIds(res.body?.data?.roles || [])));
|
||||
assert.ok(roleIds.length > 0, '当前账号没有可分配角色,无法创建测试账号');
|
||||
return [ roleIds[0] ];
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
const auth = await getAuthToken();
|
||||
token = auth.token;
|
||||
|
||||
const roleIds = await getAssignableRoleIds();
|
||||
const addRes = await invokeSystemMethod('setting.account.add', {
|
||||
phone: buildTempPhone(),
|
||||
username: `autotest_bind_wechat_${Date.now()}`,
|
||||
password: '111111',
|
||||
real_name: `微信代绑测试_${Date.now()}`,
|
||||
ids: roleIds,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(addRes.status, 200);
|
||||
assert.equal(addRes.body.flag, 'success');
|
||||
assert.equal(addRes.body.code, 200);
|
||||
|
||||
tempEmployeeId = Number(addRes.body?.data?.employee_id || 0);
|
||||
tempAccountId = Number(addRes.body?.data?.account_id || 0);
|
||||
assert.ok(tempEmployeeId > 0);
|
||||
assert.ok(tempAccountId > 0);
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (!token || !tempEmployeeId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const deleteRes = await invokeSystemMethod('setting.account.delete', {
|
||||
employee_id: tempEmployeeId,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(deleteRes.status, 200);
|
||||
assert.equal(deleteRes.body.code, 200);
|
||||
});
|
||||
|
||||
it('should get bind wechat code for an operable account by user_id', async () => {
|
||||
const res = await invokeSystemMethod('setting.account.getBindWechatCode', {
|
||||
user_id: tempAccountId,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
assert.equal(Number(res.body?.data?.account_id || 0), tempAccountId);
|
||||
assert.equal(res.body?.data?.status, 'pending');
|
||||
assert.equal(res.body?.data?.is_bound, false);
|
||||
assert.match(String(res.body?.data?.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
|
||||
assert.ok(Number(res.body?.data?.expire_after_ms || 0) > 0);
|
||||
});
|
||||
|
||||
it('should include wechat bind status in setting.account.list rows', async () => {
|
||||
const res = await invokeSystemMethod('setting.account.list', {
|
||||
where: {
|
||||
account_id: tempAccountId,
|
||||
},
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
|
||||
const list = Array.isArray(res.body?.data) ? res.body.data : [];
|
||||
const target = list.find(item => Number(item && item.account_id) === tempAccountId);
|
||||
assert.ok(target, '新建账号未出现在列表中');
|
||||
assert.equal(typeof target.is_wechat_bound, 'boolean');
|
||||
assert.equal(target.is_wechat_bound, false);
|
||||
assert.equal(target.ye4s_user_id, null);
|
||||
});
|
||||
|
||||
it('should unbind wechat for an operable account', async () => {
|
||||
const bindCodeRes = await invokeSystemMethod('setting.account.getBindWechatCode', {
|
||||
user_id: tempAccountId,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(bindCodeRes.status, 200);
|
||||
assert.equal(bindCodeRes.body.flag, 'success');
|
||||
const code = String(bindCodeRes.body?.data?.code || '');
|
||||
assert.match(code, /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
|
||||
|
||||
const scanRes = await invokeGatewayMethod('user.getUserByTempCode', {
|
||||
code,
|
||||
});
|
||||
assert.equal(scanRes.status, 200);
|
||||
assert.equal(scanRes.body.flag, 'success');
|
||||
assert.equal(scanRes.body.code, 200);
|
||||
assert.equal(Number(scanRes.body?.data?.account_id || 0), tempAccountId);
|
||||
assert.equal(scanRes.body?.data?.status, 'scanned');
|
||||
|
||||
const bindRes = await invokeGatewayMethod('user.bindAccountByTempCode', {
|
||||
code,
|
||||
ye4s_user_id: YE4S_TEST_USER_ID,
|
||||
});
|
||||
assert.equal(bindRes.status, 200);
|
||||
assert.equal(bindRes.body.flag, 'success');
|
||||
assert.equal(bindRes.body.code, 200);
|
||||
assert.equal(Number(bindRes.body?.data?.account_id || 0), tempAccountId);
|
||||
|
||||
const unbindRes = await invokeSystemMethod('setting.account.unbindWechat', {
|
||||
user_id: tempAccountId,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(unbindRes.status, 200);
|
||||
assert.equal(unbindRes.body.flag, 'success');
|
||||
assert.equal(unbindRes.body.code, 200);
|
||||
assert.equal(Number(unbindRes.body?.data?.account_id || 0), tempAccountId);
|
||||
assert.equal(unbindRes.body?.data?.status, 'unbound');
|
||||
assert.ok(Number(unbindRes.body?.data?.matched_rows || 0) >= 1);
|
||||
|
||||
const listRes = await invokeSystemMethod('setting.account.list', {
|
||||
where: {
|
||||
account_id: tempAccountId,
|
||||
},
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
const list = Array.isArray(listRes.body?.data) ? listRes.body.data : [];
|
||||
const target = list.find(item => Number(item && item.account_id) === tempAccountId);
|
||||
assert.ok(target, '解绑后账号未出现在列表中');
|
||||
assert.equal(target.is_wechat_bound, false);
|
||||
assert.equal(target.ye4s_user_id, null);
|
||||
});
|
||||
|
||||
it('should reject when user_id is missing', async () => {
|
||||
const res = await invokeSystemMethod('setting.account.getBindWechatCode', {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 400);
|
||||
assert.match(String(res.body?.message || ''), /user_id 参数不能为空/);
|
||||
});
|
||||
|
||||
it('should reject unbind when user_id is missing', async () => {
|
||||
const res = await invokeSystemMethod('setting.account.unbindWechat', {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 400);
|
||||
assert.match(String(res.body?.message || ''), /user_id 参数不能为空/);
|
||||
});
|
||||
});
|
||||
343
test/app/controller/system.setting.permission.test.js
Normal file
343
test/app/controller/system.setting.permission.test.js
Normal file
@ -0,0 +1,343 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
getAuthToken,
|
||||
invokeSystemMethod,
|
||||
} = require('../../support/system_method_client');
|
||||
|
||||
const EXTRA_HEADERS = {
|
||||
platform: 'web',
|
||||
project: 'all',
|
||||
};
|
||||
|
||||
describe('test/app/controller/system.setting.permission.test.js', () => {
|
||||
let token = '';
|
||||
let anchorPermissionId = 0;
|
||||
let createdPermissionId = 0;
|
||||
|
||||
before(async () => {
|
||||
const auth = await getAuthToken({ forceLogin: true });
|
||||
token = auth.token;
|
||||
|
||||
const listRes = await invokeSystemMethod('setting.permission.list', {}, token, EXTRA_HEADERS);
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
|
||||
const permissions = Array.isArray(listRes.body?.data?.permissions) ? listRes.body.data.permissions : [];
|
||||
assert.ok(permissions.length > 0, '当前账号无可用权限,无法执行回归');
|
||||
anchorPermissionId = Number(permissions[0].permission_id || 0);
|
||||
assert.ok(anchorPermissionId > 0, '锚点权限ID无效');
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (createdPermissionId > 0) {
|
||||
await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ createdPermissionId ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
}
|
||||
});
|
||||
|
||||
it('should expose setting.role.permission as alias of setting.permission.list', async () => {
|
||||
const requestData = {
|
||||
type: 'api',
|
||||
includeDisabled: false,
|
||||
};
|
||||
|
||||
const listRes = await invokeSystemMethod('setting.permission.list', requestData, token, EXTRA_HEADERS);
|
||||
const aliasRes = await invokeSystemMethod('setting.role.permission', requestData, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(aliasRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(aliasRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
assert.equal(aliasRes.body.code, 200);
|
||||
assert.deepEqual(aliasRes.body.data, listRes.body.data);
|
||||
});
|
||||
|
||||
it('should include route presentation fields in permission list response', async () => {
|
||||
const suffix = Date.now();
|
||||
const path = `autotest.permission.route.${suffix}`;
|
||||
let tempPermissionId = 0;
|
||||
|
||||
try {
|
||||
const addRes = await invokeSystemMethod('setting.permission.add', {
|
||||
path,
|
||||
type: 'btns',
|
||||
name: `autotest_route_${suffix}`,
|
||||
component: 'layout/RouteComponent',
|
||||
redirect: '/autotest/redirect',
|
||||
meta_title: `autotest_route_meta_${suffix}`,
|
||||
meta_icon: 'Setting',
|
||||
parent_id: anchorPermissionId,
|
||||
hidden: 1,
|
||||
always_show: 1,
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(addRes.status, 200);
|
||||
assert.equal(addRes.body.flag, 'success');
|
||||
assert.equal(addRes.body.code, 200);
|
||||
tempPermissionId = Number(addRes.body?.data?.permission_id || 0);
|
||||
assert.ok(tempPermissionId > 0, '新增路由权限失败');
|
||||
|
||||
const listRes = await invokeSystemMethod('setting.permission.list', {
|
||||
keyword: path,
|
||||
includeDisabled: false,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
|
||||
const permissions = Array.isArray(listRes.body?.data?.permissions) ? listRes.body.data.permissions : [];
|
||||
const target = permissions.find(item => Number(item && item.permission_id) === tempPermissionId);
|
||||
assert.ok(target, '新建权限未出现在权限列表中');
|
||||
assert.equal(target.component, 'layout/RouteComponent');
|
||||
assert.equal(target.redirect, '/autotest/redirect');
|
||||
assert.equal(target.meta_icon, 'Setting');
|
||||
assert.equal(Number(target.hidden), 1);
|
||||
assert.equal(Number(target.always_show), 1);
|
||||
} finally {
|
||||
if (tempPermissionId > 0) {
|
||||
await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ tempPermissionId ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should show newly created permission in list for admin management', async () => {
|
||||
const suffix = Date.now();
|
||||
const path = `autotest.permission.visible.${suffix}`;
|
||||
let tempPermissionId = 0;
|
||||
|
||||
try {
|
||||
const addRes = await invokeSystemMethod('setting.permission.add', {
|
||||
path,
|
||||
type: 'btns',
|
||||
name: `autotest_visible_${suffix}`,
|
||||
parent_id: anchorPermissionId,
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(addRes.status, 200);
|
||||
assert.equal(addRes.body.flag, 'success');
|
||||
assert.equal(addRes.body.code, 200);
|
||||
tempPermissionId = Number(addRes.body?.data?.permission_id || 0);
|
||||
assert.ok(tempPermissionId > 0, '新增测试权限失败');
|
||||
|
||||
const res = await invokeSystemMethod('setting.permission.list', {
|
||||
includeDisabled: false,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
|
||||
const permissions = Array.isArray(res.body?.data?.permissions) ? res.body.data.permissions : [];
|
||||
assert.ok(permissions.some(item => Number(item && item.permission_id) === tempPermissionId), '新建权限未出现在权限列表中');
|
||||
} finally {
|
||||
if (tempPermissionId > 0) {
|
||||
await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ tempPermissionId ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject permission update when target permission does not exist', async () => {
|
||||
const updateRes = await invokeSystemMethod('setting.permission.update', {
|
||||
permission_id: 999999999,
|
||||
name: 'not_found_update',
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(updateRes.status, 200);
|
||||
assert.equal(updateRes.body.flag, 'failure');
|
||||
assert.equal(Number(updateRes.body.code), 404);
|
||||
assert.match(String(updateRes.body.message || ''), /权限不存在/);
|
||||
});
|
||||
|
||||
it('should create then update then delete permission successfully', async () => {
|
||||
const suffix = Date.now();
|
||||
const path = `autotest.permission.${suffix}`;
|
||||
|
||||
const addRes = await invokeSystemMethod('setting.permission.add', {
|
||||
path,
|
||||
type: 'btns',
|
||||
name: `autotest_add_${suffix}`,
|
||||
parent_id: anchorPermissionId,
|
||||
meta_title: `autotest_meta_${suffix}`,
|
||||
sort: 0,
|
||||
hidden: 0,
|
||||
always_show: 0,
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(addRes.status, 200);
|
||||
assert.equal(addRes.body.flag, 'success');
|
||||
assert.equal(addRes.body.code, 200);
|
||||
createdPermissionId = Number(addRes.body?.data?.permission_id || 0);
|
||||
assert.ok(createdPermissionId > 0, '新增权限失败,permission_id 无效');
|
||||
|
||||
const updateRes = await invokeSystemMethod('setting.permission.update', {
|
||||
permission_id: createdPermissionId,
|
||||
name: `autotest_update_${suffix}`,
|
||||
meta_title: `autotest_meta_update_${suffix}`,
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(updateRes.status, 200);
|
||||
assert.equal(updateRes.body.flag, 'success');
|
||||
assert.equal(updateRes.body.code, 200);
|
||||
assert.equal(Number(updateRes.body?.data?.permission_id), createdPermissionId);
|
||||
|
||||
const deleteRes = await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ createdPermissionId ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(deleteRes.status, 200);
|
||||
assert.equal(deleteRes.body.flag, 'success');
|
||||
assert.equal(deleteRes.body.code, 200);
|
||||
const deletedIds = Array.isArray(deleteRes.body?.data?.deleted_ids) ? deleteRes.body.data.deleted_ids : [];
|
||||
assert.ok(deletedIds.includes(createdPermissionId), '删除结果中未包含新建权限ID');
|
||||
|
||||
const deleteAgainRes = await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ createdPermissionId ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
assert.equal(deleteAgainRes.status, 200);
|
||||
assert.equal(deleteAgainRes.body.flag, 'success');
|
||||
assert.equal(deleteAgainRes.body.code, 200);
|
||||
const alreadyDeletedIds = Array.isArray(deleteAgainRes.body?.data?.already_deleted_ids)
|
||||
? deleteAgainRes.body.data.already_deleted_ids
|
||||
: [];
|
||||
assert.ok(alreadyDeletedIds.includes(createdPermissionId), '二次删除未返回 already_deleted_ids');
|
||||
|
||||
createdPermissionId = 0;
|
||||
});
|
||||
|
||||
it('should split deleted_ids and already_deleted_ids in mixed batch delete', async () => {
|
||||
const suffix = Date.now();
|
||||
const firstPath = `autotest.permission.mixed.first.${suffix}`;
|
||||
const secondPath = `autotest.permission.mixed.second.${suffix}`;
|
||||
let firstPermissionId = 0;
|
||||
let secondPermissionId = 0;
|
||||
|
||||
try {
|
||||
const addFirstRes = await invokeSystemMethod('setting.permission.add', {
|
||||
path: firstPath,
|
||||
type: 'btns',
|
||||
name: `autotest_mixed_first_${suffix}`,
|
||||
parent_id: anchorPermissionId,
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
assert.equal(addFirstRes.status, 200);
|
||||
assert.equal(addFirstRes.body.flag, 'success');
|
||||
assert.equal(addFirstRes.body.code, 200);
|
||||
firstPermissionId = Number(addFirstRes.body?.data?.permission_id || 0);
|
||||
assert.ok(firstPermissionId > 0, 'first permission_id 无效');
|
||||
|
||||
const addSecondRes = await invokeSystemMethod('setting.permission.add', {
|
||||
path: secondPath,
|
||||
type: 'btns',
|
||||
name: `autotest_mixed_second_${suffix}`,
|
||||
parent_id: anchorPermissionId,
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
assert.equal(addSecondRes.status, 200);
|
||||
assert.equal(addSecondRes.body.flag, 'success');
|
||||
assert.equal(addSecondRes.body.code, 200);
|
||||
secondPermissionId = Number(addSecondRes.body?.data?.permission_id || 0);
|
||||
assert.ok(secondPermissionId > 0, 'second permission_id 无效');
|
||||
|
||||
const preDeleteRes = await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ firstPermissionId ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
assert.equal(preDeleteRes.status, 200);
|
||||
assert.equal(preDeleteRes.body.flag, 'success');
|
||||
assert.equal(preDeleteRes.body.code, 200);
|
||||
|
||||
const mixedDeleteRes = await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ firstPermissionId, secondPermissionId ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(mixedDeleteRes.status, 200);
|
||||
assert.equal(mixedDeleteRes.body.flag, 'success');
|
||||
assert.equal(mixedDeleteRes.body.code, 200);
|
||||
|
||||
const deletedIds = Array.isArray(mixedDeleteRes.body?.data?.deleted_ids)
|
||||
? mixedDeleteRes.body.data.deleted_ids
|
||||
: [];
|
||||
const alreadyDeletedIds = Array.isArray(mixedDeleteRes.body?.data?.already_deleted_ids)
|
||||
? mixedDeleteRes.body.data.already_deleted_ids
|
||||
: [];
|
||||
|
||||
assert.ok(deletedIds.includes(secondPermissionId), 'mixed 删除结果中缺少启用权限ID');
|
||||
assert.ok(alreadyDeletedIds.includes(firstPermissionId), 'mixed 删除结果中缺少已删除权限ID');
|
||||
|
||||
firstPermissionId = 0;
|
||||
secondPermissionId = 0;
|
||||
} finally {
|
||||
const cleanupIds = [ firstPermissionId, secondPermissionId ].filter(id => Number(id) > 0);
|
||||
if (cleanupIds.length > 0) {
|
||||
await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: cleanupIds,
|
||||
}, token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject mixed delete when ids contain non-existent permission', async () => {
|
||||
const suffix = Date.now();
|
||||
const path = `autotest.permission.mixed.outscope.${suffix}`;
|
||||
let permissionId = 0;
|
||||
|
||||
try {
|
||||
const addRes = await invokeSystemMethod('setting.permission.add', {
|
||||
path,
|
||||
type: 'btns',
|
||||
name: `autotest_mixed_outscope_${suffix}`,
|
||||
parent_id: anchorPermissionId,
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(addRes.status, 200);
|
||||
assert.equal(addRes.body.flag, 'success');
|
||||
assert.equal(addRes.body.code, 200);
|
||||
permissionId = Number(addRes.body?.data?.permission_id || 0);
|
||||
assert.ok(permissionId > 0, 'permission_id 无效');
|
||||
|
||||
const mixedRes = await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ permissionId, 999999999 ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(mixedRes.status, 200);
|
||||
assert.equal(mixedRes.body.flag, 'failure');
|
||||
assert.equal(Number(mixedRes.body.code), 404);
|
||||
assert.match(String(mixedRes.body.message || ''), /权限不存在/);
|
||||
|
||||
// 失败后应保持原子性:合法权限仍可被正常删除(说明前一次未误删)
|
||||
const verifyDeleteRes = await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ permissionId ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(verifyDeleteRes.status, 200);
|
||||
assert.equal(verifyDeleteRes.body.flag, 'success');
|
||||
assert.equal(verifyDeleteRes.body.code, 200);
|
||||
const deletedIds = Array.isArray(verifyDeleteRes.body?.data?.deleted_ids)
|
||||
? verifyDeleteRes.body.data.deleted_ids
|
||||
: [];
|
||||
assert.ok(deletedIds.includes(permissionId), '混入越权ID失败后,合法权限不应被提前删除');
|
||||
|
||||
permissionId = 0;
|
||||
} finally {
|
||||
if (permissionId > 0) {
|
||||
await invokeSystemMethod('setting.permission.delete', {
|
||||
ids: [ permissionId ],
|
||||
}, token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
198
test/app/controller/system.setting.role.test.js
Normal file
198
test/app/controller/system.setting.role.test.js
Normal file
@ -0,0 +1,198 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
getAuthToken,
|
||||
invokeSystemMethod,
|
||||
} = require('../../support/system_method_client');
|
||||
|
||||
const EXTRA_HEADERS = {
|
||||
platform: 'web',
|
||||
project: 'all',
|
||||
};
|
||||
|
||||
function findRoleNode(roleNodes, targetRoleId) {
|
||||
if (!Array.isArray(roleNodes) || !Number.isFinite(Number(targetRoleId))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const item of roleNodes) {
|
||||
if (Number(item && item.role_id) === Number(targetRoleId)) {
|
||||
return item;
|
||||
}
|
||||
|
||||
const childMatch = findRoleNode(item && item.children, targetRoleId);
|
||||
if (childMatch) {
|
||||
return childMatch;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
describe('test/app/controller/system.setting.role.test.js', () => {
|
||||
let token = '';
|
||||
let anchorPermissionId = 0;
|
||||
let currentRoleId = 0;
|
||||
const cleanupRoleIds = [];
|
||||
|
||||
before(async () => {
|
||||
const auth = await getAuthToken({ forceLogin: true });
|
||||
token = auth.token;
|
||||
|
||||
const permissionRes = await invokeSystemMethod('setting.permission.list', {
|
||||
includeDisabled: false,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(permissionRes.status, 200);
|
||||
assert.equal(permissionRes.body.flag, 'success');
|
||||
assert.equal(permissionRes.body.code, 200);
|
||||
|
||||
const permissions = Array.isArray(permissionRes.body?.data?.permissions)
|
||||
? permissionRes.body.data.permissions
|
||||
: [];
|
||||
assert.ok(permissions.length > 0, '当前系统没有可用权限,无法创建测试角色');
|
||||
anchorPermissionId = Number(permissions[0].permission_id || 0);
|
||||
assert.ok(anchorPermissionId > 0, '锚点权限ID无效');
|
||||
|
||||
currentRoleId = Number(permissionRes.body?.data?.role_id || 0);
|
||||
assert.ok(currentRoleId > 0, '当前角色ID无效');
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
if (!token || cleanupRoleIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await invokeSystemMethod('setting.role.delete', {
|
||||
ids: cleanupRoleIds,
|
||||
}, token, EXTRA_HEADERS);
|
||||
});
|
||||
|
||||
it('should support wildcard role permissions via ["*"]', async () => {
|
||||
const suffix = Date.now();
|
||||
const wildcardAddRes = await invokeSystemMethod('setting.role.add', {
|
||||
role_code: `autotest_role_all_${suffix}`,
|
||||
role_name: `autotest_role_all_${suffix}`,
|
||||
description: 'role wildcard regression',
|
||||
pid: currentRoleId,
|
||||
permission_ids: [ '*' ],
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(wildcardAddRes.status, 200);
|
||||
assert.equal(wildcardAddRes.body.flag, 'success');
|
||||
assert.equal(wildcardAddRes.body.code, 200);
|
||||
|
||||
const wildcardRoleId = Number(wildcardAddRes.body?.data?.role_id || 0);
|
||||
assert.ok(wildcardRoleId > 0, '创建全权限角色失败');
|
||||
cleanupRoleIds.push(wildcardRoleId);
|
||||
|
||||
const permissionRes = await invokeSystemMethod('setting.role.permission', {
|
||||
role_id: wildcardRoleId,
|
||||
includeDisabled: false,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(permissionRes.status, 200);
|
||||
assert.equal(permissionRes.body.flag, 'success');
|
||||
assert.equal(permissionRes.body.code, 200);
|
||||
|
||||
const permissions = Array.isArray(permissionRes.body?.data?.permissions)
|
||||
? permissionRes.body.data.permissions
|
||||
: [];
|
||||
assert.ok(permissions.length > 0, '全权限角色应能看到权限列表');
|
||||
assert.ok(permissions.every(item => item && item.selected === true), '当 permission_ids=["*"] 时,所有权限都应为选中状态');
|
||||
|
||||
const listRes = await invokeSystemMethod('setting.role.list', {
|
||||
includeDisabled: false,
|
||||
includeSystem: true,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
|
||||
const roots = Array.isArray(listRes.body?.data?.roles)
|
||||
? listRes.body.data.roles
|
||||
: [];
|
||||
const wildcardNode = findRoleNode(roots, wildcardRoleId);
|
||||
assert.ok(wildcardNode, '返回结果中未包含新建的全权限角色');
|
||||
assert.ok(Array.isArray(wildcardNode.permission_ids), '全权限角色应返回 permission_ids');
|
||||
assert.ok(wildcardNode.permission_ids.includes('*'), '全权限角色应以 ["*"] 表示拥有全部权限');
|
||||
});
|
||||
|
||||
it('should only return descendant roles and keep their children', async () => {
|
||||
const suffix = Date.now();
|
||||
|
||||
const childAddRes = await invokeSystemMethod('setting.role.add', {
|
||||
role_code: `autotest_role_child_${suffix}`,
|
||||
role_name: `autotest_role_child_${suffix}`,
|
||||
description: 'role tree child regression',
|
||||
pid: currentRoleId,
|
||||
permission_ids: [ anchorPermissionId ],
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(childAddRes.status, 200);
|
||||
assert.equal(childAddRes.body.flag, 'success');
|
||||
assert.equal(childAddRes.body.code, 200);
|
||||
|
||||
const createdChildRoleId = Number(childAddRes.body?.data?.role_id || 0);
|
||||
assert.ok(createdChildRoleId > 0, '创建下级角色失败');
|
||||
cleanupRoleIds.push(createdChildRoleId);
|
||||
|
||||
const grandChildAddRes = await invokeSystemMethod('setting.role.add', {
|
||||
role_code: `autotest_role_grandchild_${suffix}`,
|
||||
role_name: `autotest_role_grandchild_${suffix}`,
|
||||
description: 'role tree grandchild regression',
|
||||
pid: createdChildRoleId,
|
||||
permission_ids: [ anchorPermissionId ],
|
||||
status: 1,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(grandChildAddRes.status, 200);
|
||||
assert.equal(grandChildAddRes.body.flag, 'success');
|
||||
assert.equal(grandChildAddRes.body.code, 200);
|
||||
|
||||
const createdGrandChildRoleId = Number(grandChildAddRes.body?.data?.role_id || 0);
|
||||
assert.ok(createdGrandChildRoleId > 0, '创建孙级角色失败');
|
||||
cleanupRoleIds.unshift(createdGrandChildRoleId);
|
||||
|
||||
const listRes = await invokeSystemMethod('setting.role.list', {
|
||||
includeDisabled: false,
|
||||
includeSystem: true,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
|
||||
const roots = Array.isArray(listRes.body?.data?.roles)
|
||||
? listRes.body.data.roles
|
||||
: [];
|
||||
assert.ok(roots.length > 0, '应返回至少一层下级角色');
|
||||
assert.ok(
|
||||
roots.every(item => Number(item && item.pid) === currentRoleId),
|
||||
'setting.role.list 第一层只应返回当前角色的直接下级角色'
|
||||
);
|
||||
assert.ok(
|
||||
!roots.some(item => Number(item && item.role_id) === currentRoleId),
|
||||
'setting.role.list 不应返回当前角色本身'
|
||||
);
|
||||
|
||||
const createdChildNode = findRoleNode(roots, createdChildRoleId);
|
||||
assert.ok(createdChildNode, '返回结果中未包含新建的下级角色');
|
||||
assert.ok(
|
||||
Array.isArray(createdChildNode.children)
|
||||
&& createdChildNode.children.some(item => Number(item && item.role_id) === createdGrandChildRoleId),
|
||||
'下级角色的 children 组装异常:新建孙级角色未挂到对应父角色下'
|
||||
);
|
||||
assert.ok(Array.isArray(createdChildNode.permission_ids), '下级角色节点应返回 permission_ids 权限集');
|
||||
assert.ok(createdChildNode.permission_ids.includes(anchorPermissionId), '下级角色未返回已绑定权限集');
|
||||
|
||||
const createdGrandChildNode = findRoleNode(roots, createdGrandChildRoleId);
|
||||
assert.ok(createdGrandChildNode, '返回结果中未包含新建的孙级角色');
|
||||
assert.ok(Array.isArray(createdGrandChildNode.permission_ids), '孙级角色节点应返回 permission_ids 权限集');
|
||||
assert.ok(createdGrandChildNode.permission_ids.includes(anchorPermissionId), '孙级角色未返回已绑定权限集');
|
||||
});
|
||||
});
|
||||
413
test/app/controller/system.setting.storeWarehouse.test.js
Normal file
413
test/app/controller/system.setting.storeWarehouse.test.js
Normal file
@ -0,0 +1,413 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
getAuthToken,
|
||||
invokeSystemMethod,
|
||||
} = require('../../support/system_method_client');
|
||||
|
||||
const EXTRA_HEADERS = {
|
||||
platform: 'web',
|
||||
project: 'all',
|
||||
};
|
||||
|
||||
describe('test/app/controller/system.setting.storeWarehouse.test.js', () => {
|
||||
const METHOD_PREFIX = 'storeWarehouse.store';
|
||||
let token = '';
|
||||
let sampleRelation = null;
|
||||
|
||||
before(async () => {
|
||||
const auth = await getAuthToken({ forceLogin: true });
|
||||
token = auth.token;
|
||||
});
|
||||
|
||||
it('should list store-warehouse contracts in current subject scope', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
page: 1,
|
||||
page_size: 10,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
assert.ok(Array.isArray(res.body?.data?.list), 'list 应返回数组');
|
||||
assert.ok(res.body?.data?.current_subject, '应返回当前主体信息');
|
||||
sampleRelation = Array.isArray(res.body?.data?.list) && res.body.data.list.length > 0
|
||||
? res.body.data.list[0]
|
||||
: null;
|
||||
});
|
||||
|
||||
it('should allow renaming current-side remask and reflect it in list display', async () => {
|
||||
assert.ok(sampleRelation, '需要至少一条现有签约关系用于改名回归');
|
||||
|
||||
const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
page: 1,
|
||||
page_size: 30,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
|
||||
const currentRole = String(listRes.body?.data?.current_subject?.role || '');
|
||||
const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : [];
|
||||
const candidate = candidates.find(item => Number(item.id) > 0);
|
||||
assert.ok(candidate, '需要至少一条签约关系用于改名回归');
|
||||
|
||||
const isWarehouse = currentRole === 'warehouse';
|
||||
const originRemask = String(candidate.remask || '');
|
||||
const nextRemask = `autotest_alias_${Date.now()}`;
|
||||
|
||||
try {
|
||||
const renameRes = await invokeSystemMethod(`${METHOD_PREFIX}.rename`, {
|
||||
id: Number(candidate.id),
|
||||
remask: nextRemask,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(renameRes.status, 200);
|
||||
assert.equal(renameRes.body.flag, 'success');
|
||||
assert.equal(renameRes.body.code, 200);
|
||||
assert.equal(String(renameRes.body?.data?.contract?.remask), nextRemask);
|
||||
assert.equal(
|
||||
String(isWarehouse ? renameRes.body?.data?.contract?.store_name : renameRes.body?.data?.contract?.warehouse_name),
|
||||
nextRemask
|
||||
);
|
||||
|
||||
const verifyRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
id: Number(candidate.id),
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(verifyRes.status, 200);
|
||||
assert.equal(verifyRes.body.flag, 'success');
|
||||
assert.equal(verifyRes.body.code, 200);
|
||||
|
||||
const verified = Array.isArray(verifyRes.body?.data?.list) ? verifyRes.body.data.list[0] : null;
|
||||
assert.ok(verified, '改名后应能查到对应签约关系');
|
||||
assert.equal(
|
||||
String(isWarehouse ? verified.store_name : verified.warehouse_name),
|
||||
nextRemask
|
||||
);
|
||||
} finally {
|
||||
await invokeSystemMethod(`${METHOD_PREFIX}.rename`, {
|
||||
id: Number(candidate.id),
|
||||
remask: originRemask,
|
||||
}, token, EXTRA_HEADERS);
|
||||
}
|
||||
});
|
||||
|
||||
it('should generate a temp code and support preview before confirmation', async () => {
|
||||
assert.ok(sampleRelation, '需要至少一条现有签约关系用于临时码回归');
|
||||
|
||||
const candidateRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
page: 1,
|
||||
page_size: 30,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(candidateRes.status, 200);
|
||||
assert.equal(candidateRes.body.flag, 'success');
|
||||
assert.equal(candidateRes.body.code, 200);
|
||||
|
||||
const candidates = Array.isArray(candidateRes.body?.data?.list) ? candidateRes.body.data.list : [];
|
||||
assert.ok(candidates.length > 0, '需要至少一条签约关系用于临时码回归');
|
||||
|
||||
let initRes = null;
|
||||
for (const item of candidates) {
|
||||
const attempt = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, {
|
||||
counterparty_id: Number(item.counterparty_id),
|
||||
apply_reason: 'autotest temp sign flow',
|
||||
remask: `autotest_remask_${Date.now()}`,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
if (attempt.status === 200 && attempt.body && attempt.body.flag === 'success') {
|
||||
initRes = attempt;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assert.ok(initRes, '未找到可发起临时码签约的对方主体,请确认测试账号签约数据');
|
||||
|
||||
assert.equal(initRes.status, 200);
|
||||
assert.equal(initRes.body.flag, 'success');
|
||||
assert.equal(initRes.body.code, 200);
|
||||
assert.equal(initRes.body?.data?.mode, 'initiate');
|
||||
assert.ok(String(initRes.body?.data?.temp_code || '').length >= 8, '发起签约后应返回临时码');
|
||||
|
||||
const previewRes = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, {
|
||||
temp_code: initRes.body.data.temp_code,
|
||||
action: 'preview',
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(previewRes.status, 200);
|
||||
assert.equal(previewRes.body.flag, 'success');
|
||||
assert.equal(previewRes.body.code, 200);
|
||||
assert.equal(previewRes.body?.data?.mode, 'preview');
|
||||
assert.equal(String(previewRes.body?.data?.temp_code || ''), String(initRes.body?.data?.temp_code || ''));
|
||||
assert.equal(Boolean(previewRes.body?.data?.can_confirm), false, '同一发起方不应直接确认自己的临时码');
|
||||
});
|
||||
|
||||
it('should only change use_status when unbinding', async () => {
|
||||
assert.ok(sampleRelation, '需要至少一条现有签约关系用于解除回归');
|
||||
|
||||
const originalAuthStatus = Number(sampleRelation.auth_status || 0);
|
||||
const originalUseStatus = Number(sampleRelation.use_status || 0);
|
||||
const targetUseStatus = originalUseStatus === 1 ? 0 : 1;
|
||||
|
||||
try {
|
||||
const unbindRes = await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, {
|
||||
id: Number(sampleRelation.id),
|
||||
use_status: targetUseStatus,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(unbindRes.status, 200);
|
||||
assert.equal(unbindRes.body.flag, 'success');
|
||||
assert.equal(unbindRes.body.code, 200);
|
||||
assert.equal(Number(unbindRes.body?.data?.contract?.use_status), targetUseStatus);
|
||||
assert.equal(Number(unbindRes.body?.data?.contract?.auth_status), originalAuthStatus, '解除接口不应改动 auth_status');
|
||||
} finally {
|
||||
await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, {
|
||||
id: Number(sampleRelation.id),
|
||||
use_status: originalUseStatus,
|
||||
}, token, EXTRA_HEADERS);
|
||||
}
|
||||
});
|
||||
|
||||
it('should allow warehouse side to save and get policy config on a contract', async function() {
|
||||
const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
page: 1,
|
||||
page_size: 30,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
|
||||
const currentRole = String(listRes.body?.data?.current_subject?.role || '');
|
||||
if (currentRole !== 'warehouse') {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : [];
|
||||
const candidate = candidates.find(item => Number(item.id) > 0);
|
||||
assert.ok(candidate, '需要至少一条签约关系用于策略配置回归');
|
||||
|
||||
const originalPolicyConfig = candidate.policy_config && typeof candidate.policy_config === 'object'
|
||||
? { ...candidate.policy_config }
|
||||
: null;
|
||||
const nextPolicyConfig = {
|
||||
receive_mode: 'strict',
|
||||
sku_visibility: 'whitelist',
|
||||
auto_allocate_bin: 1,
|
||||
allow_mix_batch: 0,
|
||||
max_daily_inbound: 5000,
|
||||
remark: `autotest_${Date.now()}`,
|
||||
};
|
||||
|
||||
try {
|
||||
const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, {
|
||||
id: Number(candidate.id),
|
||||
policy_config: nextPolicyConfig,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(saveRes.status, 200);
|
||||
assert.equal(saveRes.body.flag, 'success');
|
||||
assert.equal(saveRes.body.code, 200);
|
||||
assert.equal(Number(saveRes.body?.data?.contract_id || 0), Number(candidate.id));
|
||||
assert.equal(String(saveRes.body?.data?.policy_config?.receive_mode || ''), 'strict');
|
||||
assert.equal(Number(saveRes.body?.data?.policy_config?.auto_allocate_bin || 0), 1);
|
||||
|
||||
const getRes = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, {
|
||||
id: Number(candidate.id),
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(getRes.status, 200);
|
||||
assert.equal(getRes.body.flag, 'success');
|
||||
assert.equal(getRes.body.code, 200);
|
||||
assert.equal(Number(getRes.body?.data?.contract_id || 0), Number(candidate.id));
|
||||
assert.equal(String(getRes.body?.data?.policy_config?.sku_visibility || ''), 'whitelist');
|
||||
assert.equal(Number(getRes.body?.data?.policy_config?.max_daily_inbound || 0), 5000);
|
||||
} finally {
|
||||
if (originalPolicyConfig) {
|
||||
await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, {
|
||||
id: Number(candidate.id),
|
||||
policy_config: originalPolicyConfig,
|
||||
}, token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject unsupported policy config fields on a contract', async function() {
|
||||
const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
page: 1,
|
||||
page_size: 30,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
|
||||
const currentRole = String(listRes.body?.data?.current_subject?.role || '');
|
||||
if (currentRole !== 'warehouse') {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : [];
|
||||
const candidate = candidates.find(item => Number(item.id) > 0);
|
||||
assert.ok(candidate, '需要至少一条签约关系用于策略字段限制回归');
|
||||
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, {
|
||||
id: Number(candidate.id),
|
||||
policy_config: {
|
||||
receive_mode: 'strict',
|
||||
unexpected_field: 'blocked',
|
||||
},
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /unexpected_field|不支持字段/);
|
||||
});
|
||||
|
||||
it('should allow warehouse side to save, update and delete qimen config on a contract', async function() {
|
||||
const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
page: 1,
|
||||
page_size: 30,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
|
||||
const currentRole = String(listRes.body?.data?.current_subject?.role || '');
|
||||
if (currentRole !== 'warehouse') {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : [];
|
||||
const candidate = candidates.find(item => Number(item.id) > 0);
|
||||
assert.ok(candidate, '需要至少一条签约关系用于奇门配置回归');
|
||||
|
||||
const originalQimenConfig = candidate.qimen_config ? { ...candidate.qimen_config } : null;
|
||||
const seed = Date.now();
|
||||
const createPayload = {
|
||||
id: Number(candidate.id),
|
||||
app_name: `autotest_qimen_${seed}`,
|
||||
qimen_app_key: `autotest_app_${seed}`,
|
||||
qimen_customer_id: `autotest_customer_${seed}`,
|
||||
qimen_warehouse_code: `autotest_wh_${seed}`,
|
||||
contact_person: 'autotest',
|
||||
contact_phone: '13800138000',
|
||||
email: `autotest_${seed}@example.com`,
|
||||
is_enabled: 1,
|
||||
};
|
||||
|
||||
try {
|
||||
const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, createPayload, token, EXTRA_HEADERS);
|
||||
assert.equal(saveRes.status, 200);
|
||||
assert.equal(saveRes.body.flag, 'success');
|
||||
assert.equal(saveRes.body.code, 200);
|
||||
assert.match(String(saveRes.body?.data?.action || ''), /create|update/);
|
||||
assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_app_key || ''), createPayload.qimen_app_key);
|
||||
assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_customer_id || ''), createPayload.qimen_customer_id);
|
||||
assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), createPayload.qimen_warehouse_code);
|
||||
|
||||
const updatePayload = {
|
||||
...createPayload,
|
||||
app_name: `${createPayload.app_name}_updated`,
|
||||
qimen_customer_id: `${createPayload.qimen_customer_id}_updated`,
|
||||
qimen_warehouse_code: `${createPayload.qimen_warehouse_code}_updated`,
|
||||
is_enabled: 0,
|
||||
};
|
||||
const updateRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, updatePayload, token, EXTRA_HEADERS);
|
||||
assert.equal(updateRes.status, 200);
|
||||
assert.equal(updateRes.body.flag, 'success');
|
||||
assert.equal(updateRes.body.code, 200);
|
||||
assert.equal(String(updateRes.body?.data?.action || ''), 'update');
|
||||
assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id);
|
||||
assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), updatePayload.qimen_warehouse_code);
|
||||
assert.equal(Number(updateRes.body?.data?.qimen_config?.is_enabled), 0);
|
||||
|
||||
const verifyRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
id: Number(candidate.id),
|
||||
}, token, EXTRA_HEADERS);
|
||||
assert.equal(verifyRes.status, 200);
|
||||
assert.equal(verifyRes.body.flag, 'success');
|
||||
assert.equal(verifyRes.body.code, 200);
|
||||
const verified = Array.isArray(verifyRes.body?.data?.list) ? verifyRes.body.data.list[0] : null;
|
||||
assert.ok(verified, '保存奇门配置后应能查询到签约关系');
|
||||
assert.equal(String(verified?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id);
|
||||
|
||||
const configListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, {
|
||||
id: Number(candidate.id),
|
||||
}, token, EXTRA_HEADERS);
|
||||
assert.equal(configListRes.status, 200);
|
||||
assert.equal(configListRes.body.flag, 'success');
|
||||
assert.equal(configListRes.body.code, 200);
|
||||
assert.equal(Number(configListRes.body?.data?.contract_id || 0), Number(candidate.id));
|
||||
assert.ok(Array.isArray(configListRes.body?.data?.list), '应返回奇门配置列表');
|
||||
assert.ok((configListRes.body?.data?.list || []).length >= 1, '保存后应至少返回一条奇门配置');
|
||||
assert.equal(String(configListRes.body?.data?.list?.[0]?.qimen_customer_id || ''), updatePayload.qimen_customer_id);
|
||||
|
||||
const deleteRes = await invokeSystemMethod(`${METHOD_PREFIX}.deleteQimenConfig`, {
|
||||
id: Number(candidate.id),
|
||||
}, token, EXTRA_HEADERS);
|
||||
assert.equal(deleteRes.status, 200);
|
||||
assert.equal(deleteRes.body.flag, 'success');
|
||||
assert.equal(deleteRes.body.code, 200);
|
||||
assert.equal(Boolean(deleteRes.body?.data?.deleted), true);
|
||||
|
||||
const verifyDeleteRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
id: Number(candidate.id),
|
||||
}, token, EXTRA_HEADERS);
|
||||
assert.equal(verifyDeleteRes.status, 200);
|
||||
assert.equal(verifyDeleteRes.body.flag, 'success');
|
||||
assert.equal(verifyDeleteRes.body.code, 200);
|
||||
const deletedView = Array.isArray(verifyDeleteRes.body?.data?.list) ? verifyDeleteRes.body.data.list[0] : null;
|
||||
assert.ok(deletedView, '删除奇门配置后仍应能查询到签约关系');
|
||||
assert.equal(deletedView?.qimen_config || null, null);
|
||||
|
||||
const emptyListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, {
|
||||
id: Number(candidate.id),
|
||||
}, token, EXTRA_HEADERS);
|
||||
assert.equal(emptyListRes.status, 200);
|
||||
assert.equal(emptyListRes.body.flag, 'success');
|
||||
assert.equal(emptyListRes.body.code, 200);
|
||||
assert.ok(Array.isArray(emptyListRes.body?.data?.list), '删除后仍应返回列表结构');
|
||||
assert.equal(Number(emptyListRes.body?.data?.total || 0), 0);
|
||||
} finally {
|
||||
if (originalQimenConfig) {
|
||||
await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, {
|
||||
id: Number(candidate.id),
|
||||
app_name: originalQimenConfig.app_name,
|
||||
qimen_app_key: originalQimenConfig.qimen_app_key,
|
||||
qimen_customer_id: originalQimenConfig.qimen_customer_id,
|
||||
qimen_warehouse_code: originalQimenConfig.qimen_warehouse_code,
|
||||
contact_person: originalQimenConfig.contact_person,
|
||||
contact_phone: originalQimenConfig.contact_phone,
|
||||
email: originalQimenConfig.email,
|
||||
is_enabled: Number(originalQimenConfig.is_enabled || 0),
|
||||
}, token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject sign when counterparty is missing', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, {
|
||||
print_quantity: 0,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /counterparty_id|store_id|warehouse_id/);
|
||||
});
|
||||
|
||||
it('should reject unbind when no target relation is provided', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/);
|
||||
});
|
||||
});
|
||||
@ -70,6 +70,52 @@ async function switchToWarehouseRole(token) {
|
||||
throw new Error('未找到可访问收货单的仓库角色');
|
||||
}
|
||||
|
||||
async function getBindableStoreInfo(token) {
|
||||
const res = await invokeSystemMethod('storeWarehouse.store.list', {
|
||||
page: 1,
|
||||
page_size: 20,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
|
||||
const list = Array.isArray(res.body?.data?.list) ? res.body.data.list : [];
|
||||
const candidate = list.find(item => Number(item?.counterparty_id || item?.store_id || 0) > 0);
|
||||
|
||||
if (!candidate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
store_id: Number(candidate.counterparty_id || candidate.store_id || 0),
|
||||
store_name: String(candidate.store_name || candidate.counterparty_name || ''),
|
||||
};
|
||||
}
|
||||
|
||||
async function getBindableSystemProducts(token) {
|
||||
const res = await invokeSystemMethod('stock.warehouse.list', {
|
||||
pagination: {
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
},
|
||||
where: {},
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
|
||||
const payload = normalizeListPayload(res.body.data);
|
||||
const list = Array.isArray(payload?.list) ? payload.list : [];
|
||||
return list
|
||||
.filter(item => Number(item?.id || 0) > 0)
|
||||
.map(item => ({
|
||||
id: Number(item.id),
|
||||
product_name: String(item.item_name || item.name || item.product_name || ''),
|
||||
}));
|
||||
}
|
||||
|
||||
describe('test/app/controller/system.storage.receiving.test.js', () => {
|
||||
it('should query receiving list', async () => {
|
||||
const { token } = await getAuthToken();
|
||||
@ -135,6 +181,192 @@ describe('test/app/controller/system.storage.receiving.test.js', () => {
|
||||
assert.ok(detailPayload, '返回结构中缺少收货单详情 payload');
|
||||
assert.ok(detailPayload.receiving, 'receiving 字段缺失');
|
||||
assert.equal(Number(detailPayload.receiving.id), Number(first.id));
|
||||
assert.ok(Array.isArray(detailPayload.receiving.details), 'receiving.details 应为数组');
|
||||
|
||||
const detailWithImages = detailPayload.receiving.details.find(item => Array.isArray(item.images) && item.images.length > 0);
|
||||
if (detailWithImages) {
|
||||
const firstImage = detailWithImages.images[0];
|
||||
assert.equal(typeof firstImage, 'object', '明细图片应返回对象结构');
|
||||
assert.equal(typeof firstImage.url, 'string', '明细图片应返回实际链接');
|
||||
assert.ok(firstImage.url.length > 0, '明细图片链接不能为空');
|
||||
assert.ok(!Object.prototype.hasOwnProperty.call(firstImage, 'business_type'), '不应返回 FileReference 原始字段');
|
||||
}
|
||||
});
|
||||
|
||||
it('should bind store to receiving and reject rebinding when owner already exists', async function() {
|
||||
const { token } = await getAuthToken();
|
||||
const switched = await switchToWarehouseRole(token);
|
||||
const bindableStore = await getBindableStoreInfo(switched.token);
|
||||
let createdId = 0;
|
||||
|
||||
if (!bindableStore || bindableStore.store_id <= 0) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
try {
|
||||
const createRes = await invokeSystemMethod('storage.receiving.create', {
|
||||
delivery_method: 'truck',
|
||||
license_plate: `ITEST-BIND-${Date.now().toString().slice(-6)}`,
|
||||
loading_method: 'with_pallet',
|
||||
remark: 'bind-store-regression',
|
||||
total_boxes: 0,
|
||||
total_pallets: 0,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(createRes.status, 200);
|
||||
assert.equal(createRes.body.flag, 'success');
|
||||
assert.equal(createRes.body.code, 200);
|
||||
createdId = Number(createRes.body.id || createRes.body?.data?.id || 0);
|
||||
assert.ok(createdId > 0, '创建收货单失败,无法执行货主绑定回归');
|
||||
|
||||
const bindRes = await invokeSystemMethod('storage.receiving.bindStore', {
|
||||
id: createdId,
|
||||
store_id: bindableStore.store_id,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(bindRes.status, 200);
|
||||
assert.equal(bindRes.body.flag, 'success');
|
||||
assert.equal(bindRes.body.code, 200);
|
||||
assert.equal(Number(bindRes.body?.data?.store_id || 0), Number(bindableStore.store_id));
|
||||
|
||||
const repeatRes = await invokeSystemMethod('storage.receiving.bindStore', {
|
||||
id: createdId,
|
||||
store_id: bindableStore.store_id,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(repeatRes.status, 200);
|
||||
assert.equal(repeatRes.body.flag, 'success');
|
||||
assert.equal(Number(repeatRes.body.code), 400);
|
||||
assert.match(String(repeatRes.body.message || ''), /已绑定|重复绑定|已有货主/);
|
||||
} finally {
|
||||
if (createdId > 0) {
|
||||
await invokeSystemMethod('storage.receiving.batchCancelReceiving', {
|
||||
ids: [ createdId ],
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject bindStore when receiving is cancelled', async function() {
|
||||
const { token } = await getAuthToken();
|
||||
const switched = await switchToWarehouseRole(token);
|
||||
const bindableStore = await getBindableStoreInfo(switched.token);
|
||||
let createdId = 0;
|
||||
|
||||
if (!bindableStore || bindableStore.store_id <= 0) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
try {
|
||||
const createRes = await invokeSystemMethod('storage.receiving.create', {
|
||||
delivery_method: 'truck',
|
||||
license_plate: `ICB-${Date.now().toString().slice(-6)}`,
|
||||
loading_method: 'with_pallet',
|
||||
remark: 'bind-store-cancelled-regression',
|
||||
total_boxes: 0,
|
||||
total_pallets: 0,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(createRes.status, 200);
|
||||
assert.equal(createRes.body.flag, 'success');
|
||||
assert.equal(createRes.body.code, 200);
|
||||
createdId = Number(createRes.body.id || createRes.body?.data?.id || 0);
|
||||
assert.ok(createdId > 0, '创建收货单失败,无法执行取消状态绑定回归');
|
||||
|
||||
const cancelRes = await invokeSystemMethod('storage.receiving.batchCancelReceiving', {
|
||||
ids: [ createdId ],
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
assert.equal(cancelRes.status, 200);
|
||||
assert.equal(cancelRes.body.flag, 'success');
|
||||
assert.ok([ 0, 200 ].includes(Number(cancelRes.body.code)), `取消收货单返回异常: ${JSON.stringify(cancelRes.body)}`);
|
||||
|
||||
const bindRes = await invokeSystemMethod('storage.receiving.bindStore', {
|
||||
id: createdId,
|
||||
store_id: bindableStore.store_id,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(bindRes.status, 200);
|
||||
assert.equal(bindRes.body.flag, 'success');
|
||||
assert.equal(Number(bindRes.body.code), 400);
|
||||
assert.match(String(bindRes.body.message || ''), /取消|作废|不允许绑定/);
|
||||
} finally {
|
||||
if (createdId > 0) {
|
||||
await invokeSystemMethod('storage.receiving.batchCancelReceiving', {
|
||||
ids: [ createdId ],
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should bind and rebind system product for a receiving detail', async function() {
|
||||
const { token } = await getAuthToken();
|
||||
const switched = await switchToWarehouseRole(token);
|
||||
const systemProducts = await getBindableSystemProducts(switched.token);
|
||||
let createdId = 0;
|
||||
|
||||
if (!Array.isArray(systemProducts) || systemProducts.length === 0) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
try {
|
||||
const createRes = await invokeSystemMethod('storage.receiving.create', {
|
||||
delivery_method: 'truck',
|
||||
license_plate: `IDB-${Date.now().toString().slice(-6)}`,
|
||||
loading_method: 'with_pallet',
|
||||
remark: 'bind-detail-product-regression',
|
||||
total_boxes: 0,
|
||||
total_pallets: 0,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(createRes.status, 200);
|
||||
assert.equal(createRes.body.flag, 'success');
|
||||
assert.equal(createRes.body.code, 200);
|
||||
createdId = Number(createRes.body.id || createRes.body?.data?.id || 0);
|
||||
assert.ok(createdId > 0, '创建收货单失败,无法执行明细绑定商品回归');
|
||||
|
||||
const addDetailRes = await invokeSystemMethod('storage.receiving.addDetail', {
|
||||
receiving_id: createdId,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(addDetailRes.status, 200);
|
||||
assert.equal(addDetailRes.body.flag, 'success');
|
||||
assert.equal(Number(addDetailRes.body.code), 200);
|
||||
|
||||
const detailId = Number(addDetailRes.body?.data?.data?.selectId || addDetailRes.body?.data?.selectId || 0);
|
||||
assert.ok(detailId > 0, '新增收货单明细后未返回有效 detail_id');
|
||||
|
||||
const firstProduct = systemProducts[0];
|
||||
const bindRes = await invokeSystemMethod('storage.receiving.bindDetailProduct', {
|
||||
detail_id: detailId,
|
||||
system_product_id: firstProduct.id,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(bindRes.status, 200);
|
||||
assert.equal(bindRes.body.flag, 'success');
|
||||
assert.equal(Number(bindRes.body.code), 200);
|
||||
assert.equal(Number(bindRes.body?.data?.detail_id || 0), detailId);
|
||||
assert.equal(Number(bindRes.body?.data?.system_product_id || 0), Number(firstProduct.id));
|
||||
assert.ok(String(bindRes.body?.data?.product_name || '').length > 0, '绑定后应回填商品名称');
|
||||
|
||||
const secondProduct = systemProducts.find(item => Number(item.id) !== Number(firstProduct.id)) || firstProduct;
|
||||
const rebindRes = await invokeSystemMethod('storage.receiving.bindDetailProduct', {
|
||||
detail_id: detailId,
|
||||
system_product_id: secondProduct.id,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(rebindRes.status, 200);
|
||||
assert.equal(rebindRes.body.flag, 'success');
|
||||
assert.equal(Number(rebindRes.body.code), 200);
|
||||
assert.equal(Number(rebindRes.body?.data?.detail_id || 0), detailId);
|
||||
assert.equal(Number(rebindRes.body?.data?.system_product_id || 0), Number(secondProduct.id));
|
||||
assert.ok(String(rebindRes.body?.data?.product_name || '').length > 0, '改绑后应返回商品名称');
|
||||
} finally {
|
||||
if (createdId > 0) {
|
||||
await invokeSystemMethod('storage.receiving.batchCancelReceiving', {
|
||||
ids: [ createdId ],
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should create and then batch cancel receiving order', async () => {
|
||||
@ -177,6 +409,104 @@ describe('test/app/controller/system.storage.receiving.test.js', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('should generate unique receiving numbers under concurrent create requests', async () => {
|
||||
const { token } = await getAuthToken();
|
||||
const switched = await switchToWarehouseRole(token);
|
||||
const suffix = Date.now().toString().slice(-6);
|
||||
const createdIds = [];
|
||||
|
||||
try {
|
||||
const requests = [ 1, 2 ].map(index => invokeSystemMethod('storage.receiving.create', {
|
||||
delivery_method: 'truck',
|
||||
license_plate: `ITEST-C${index}-${suffix}`,
|
||||
loading_method: 'with_pallet',
|
||||
remark: `integration-concurrent-${index}`,
|
||||
total_boxes: 0,
|
||||
total_pallets: 0,
|
||||
}, switched.token, EXTRA_HEADERS));
|
||||
|
||||
const responses = await Promise.all(requests);
|
||||
responses.forEach((res, index) => {
|
||||
assert.equal(res.status, 200, `第 ${index + 1} 个并发请求 HTTP 状态异常`);
|
||||
assert.equal(res.body.flag, 'success', `第 ${index + 1} 个并发请求应成功: ${JSON.stringify(res.body)}`);
|
||||
assert.equal(res.body.code, 200, `第 ${index + 1} 个并发请求 code 应为 200`);
|
||||
});
|
||||
|
||||
const ids = responses.map(res => Number(res.body.id || res.body?.data?.id || 0));
|
||||
const receivingNumbers = responses.map(res => String(res.body.receiving_number || res.body?.data?.receiving_number || ''));
|
||||
|
||||
ids.forEach(id => {
|
||||
assert.ok(id > 0, '并发创建成功但未返回有效 id');
|
||||
createdIds.push(id);
|
||||
});
|
||||
receivingNumbers.forEach(number => {
|
||||
assert.ok(number.startsWith('R'), `收货单号格式异常: ${number}`);
|
||||
});
|
||||
assert.equal(new Set(receivingNumbers).size, receivingNumbers.length, '并发创建时 receiving_number 应保持唯一');
|
||||
} finally {
|
||||
if (createdIds.length > 0) {
|
||||
await invokeSystemMethod('storage.receiving.batchCancelReceiving', {
|
||||
ids: createdIds,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should include same-day records when created_at uses daterange filter', async () => {
|
||||
const { token } = await getAuthToken();
|
||||
const switched = await switchToWarehouseRole(token);
|
||||
let createdId = 0;
|
||||
|
||||
try {
|
||||
const uniquePlate = `ITEST-DATE-${Date.now().toString().slice(-6)}`;
|
||||
const createRes = await invokeSystemMethod('storage.receiving.create', {
|
||||
delivery_method: 'truck',
|
||||
license_plate: uniquePlate,
|
||||
loading_method: 'with_pallet',
|
||||
remark: 'date-range-regression',
|
||||
total_boxes: 0,
|
||||
total_pallets: 0,
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(createRes.status, 200);
|
||||
assert.equal(createRes.body.flag, 'success');
|
||||
assert.equal(createRes.body.code, 200);
|
||||
createdId = Number(createRes.body.id || createRes.body?.data?.id || 0);
|
||||
assert.ok(createdId > 0, '创建收货单失败,无法执行日期范围回归');
|
||||
|
||||
const now = new Date();
|
||||
const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
|
||||
const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', {
|
||||
pagination: {
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
},
|
||||
where: {
|
||||
created_at: {
|
||||
operator: 'between',
|
||||
value: [ startOfDay, startOfDay ],
|
||||
type: 'daterange',
|
||||
},
|
||||
},
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(listRes.status, 200);
|
||||
assert.equal(listRes.body.flag, 'success');
|
||||
assert.equal(listRes.body.code, 200);
|
||||
|
||||
const payload = normalizeListPayload(listRes.body.data);
|
||||
assert.ok(payload, '日期范围查询返回结构缺少列表 payload');
|
||||
const ids = Array.isArray(payload.list) ? payload.list.map(item => Number(item && item.id)) : [];
|
||||
assert.ok(ids.includes(createdId), '同日创建的收货单应命中 created_at daterange 查询');
|
||||
} finally {
|
||||
if (createdId > 0) {
|
||||
await invokeSystemMethod('storage.receiving.batchCancelReceiving', {
|
||||
ids: [ createdId ],
|
||||
}, switched.token, EXTRA_HEADERS);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('should reject getReceivingDetail with invalid id', async () => {
|
||||
const { token } = await getAuthToken();
|
||||
const switched = await switchToWarehouseRole(token);
|
||||
|
||||
122
test/app/controller/system.storeWarehouse.test.js
Normal file
122
test/app/controller/system.storeWarehouse.test.js
Normal file
@ -0,0 +1,122 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
getAuthToken,
|
||||
invokeSystemMethod,
|
||||
} = require('../../support/system_method_client');
|
||||
|
||||
const EXTRA_HEADERS = {
|
||||
platform: 'web',
|
||||
project: 'all',
|
||||
};
|
||||
|
||||
describe('test/app/controller/system.storeWarehouse.test.js', () => {
|
||||
const METHOD_PREFIX = 'storeWarehouse.store';
|
||||
const REMOVED_SETTING_METHOD_PREFIX = 'setting.storeWarehouse.store';
|
||||
let token = '';
|
||||
|
||||
before(async () => {
|
||||
const auth = await getAuthToken({ forceLogin: true });
|
||||
token = auth.token;
|
||||
});
|
||||
|
||||
it('should expose standalone storeWarehouse.store.list', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.list`, {
|
||||
page: 1,
|
||||
page_size: 10,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
assert.ok(Array.isArray(res.body?.data?.list), 'storeWarehouse.store.list 应返回 list');
|
||||
assert.equal(typeof res.body?.data?.total, 'number');
|
||||
});
|
||||
|
||||
it('should not expose removed setting.storeWarehouse.store.list alias', async () => {
|
||||
const removedRes = await invokeSystemMethod(`${REMOVED_SETTING_METHOD_PREFIX}.list`, {
|
||||
page: 1,
|
||||
page_size: 10,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(removedRes.status, 500);
|
||||
assert.equal(removedRes.body.flag, 'failure');
|
||||
assert.equal(Number(removedRes.body.code), 500);
|
||||
assert.match(String(removedRes.body.message || ''), /服务 setting\.storeWarehouse\.store 不存在/);
|
||||
});
|
||||
|
||||
it('should expose standalone storeWarehouse.store.sign parameter validation', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, {
|
||||
print_quantity: 0,
|
||||
}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /counterparty_id|store_id|warehouse_id/);
|
||||
});
|
||||
|
||||
it('should expose standalone storeWarehouse.store.unbind parameter validation', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/);
|
||||
});
|
||||
|
||||
it('should expose standalone storeWarehouse.store.rename parameter validation', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.rename`, {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /remask|id|counterparty_id|store_id|warehouse_id/);
|
||||
});
|
||||
|
||||
it('should expose standalone storeWarehouse.store.getPolicyConfig parameter validation', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/);
|
||||
});
|
||||
|
||||
it('should expose standalone storeWarehouse.store.savePolicyConfig parameter validation', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/);
|
||||
});
|
||||
|
||||
it('should expose standalone storeWarehouse.store.saveQimenConfig parameter validation', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id|qimen_app_key|qimen_customer_id|qimen_warehouse_code/);
|
||||
});
|
||||
|
||||
it('should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.deleteQimenConfig`, {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/);
|
||||
});
|
||||
|
||||
it('should expose standalone storeWarehouse.store.listQimenConfig parameter validation', async () => {
|
||||
const res = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, {}, token, EXTRA_HEADERS);
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(Number(res.body.code), 400);
|
||||
assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/);
|
||||
});
|
||||
});
|
||||
17
test/app/controller/system.user.getLoginWechatCode.test.js
Normal file
17
test/app/controller/system.user.getLoginWechatCode.test.js
Normal file
@ -0,0 +1,17 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { invokeSystemMethod } = require('../../support/system_method_client');
|
||||
|
||||
describe('test/app/controller/system.user.getLoginWechatCode.test.js', () => {
|
||||
it('should return login code without Authorization token', async () => {
|
||||
const res = await invokeSystemMethod('user.getLoginWechatCode', {});
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'success');
|
||||
assert.equal(res.body.code, 200);
|
||||
assert.match(String(res.body?.data?.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
|
||||
assert.match(String(res.body?.data?.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
|
||||
assert.equal(res.body?.data?.status, 'pending');
|
||||
});
|
||||
});
|
||||
@ -3,11 +3,14 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const { invokeSystemMethod } = require('../../support/system_method_client');
|
||||
|
||||
const VALID_LOGIN_CODE = process.env.SYSTEM_TEST_LOGIN_CODE
|
||||
|| 'eyJ1dWlkIjoiMDg2MTk4MzQtY2FhYS00OTIyLWJmNjctODc5M2U2Y2MwYzJkIn0=';
|
||||
const VALID_LOGIN_CODE = String(process.env.SYSTEM_TEST_LOGIN_CODE || '').trim();
|
||||
|
||||
describe('test/app/controller/system.user.loginByCode.test.js', () => {
|
||||
it('should login successfully when code is valid', async () => {
|
||||
it('should login successfully when code is valid', async function() {
|
||||
if (!VALID_LOGIN_CODE) {
|
||||
this.skip();
|
||||
}
|
||||
|
||||
const res = await invokeSystemMethod('user.loginByCode', {
|
||||
code: VALID_LOGIN_CODE,
|
||||
});
|
||||
@ -30,23 +33,23 @@ describe('test/app/controller/system.user.loginByCode.test.js', () => {
|
||||
assert.match(String(res.body.message || ''), /code/);
|
||||
});
|
||||
|
||||
it('should fail when code is not valid base64 json', async () => {
|
||||
it('should fail when code does not exist', async () => {
|
||||
const code = `INVALID_CODE_${Date.now()}`;
|
||||
const res = await invokeSystemMethod('user.loginByCode', { code });
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 0);
|
||||
assert.match(String(res.body.message || ''), /无效的登录码格式/);
|
||||
assert.match(String(res.body.message || ''), /登录码不存在|登录失败/);
|
||||
});
|
||||
|
||||
it('should fail when decoded payload does not contain uuid', async () => {
|
||||
const code = Buffer.from(JSON.stringify({ foo: 'bar' }), 'utf8').toString('base64');
|
||||
it('should fail when code format is valid but not matched', async () => {
|
||||
const code = 'A1B2C3';
|
||||
const res = await invokeSystemMethod('user.loginByCode', { code });
|
||||
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.flag, 'failure');
|
||||
assert.equal(res.body.code, 0);
|
||||
assert.match(String(res.body.message || ''), /uuid/);
|
||||
assert.match(String(res.body.message || ''), /登录码不存在|登录失败/);
|
||||
});
|
||||
});
|
||||
|
||||
152
test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js
Normal file
152
test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js
Normal file
@ -0,0 +1,152 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const UserService = require('../../../../app/service/systems/auth/user');
|
||||
|
||||
function createServiceHarness() {
|
||||
const cacheWrites = [];
|
||||
const cacheStore = new Map();
|
||||
|
||||
const app = {
|
||||
async setCacheAsync(cacheKey, data, expireSeconds = 300) {
|
||||
cacheWrites.push({
|
||||
cacheKey,
|
||||
data,
|
||||
expireSeconds,
|
||||
});
|
||||
|
||||
if (data === null || data === undefined || expireSeconds <= 1) {
|
||||
cacheStore.delete(cacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
cacheStore.set(cacheKey, data);
|
||||
},
|
||||
async getCacheAsync(cacheKey) {
|
||||
return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null;
|
||||
},
|
||||
coreLogger: {
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app,
|
||||
userId: 1001,
|
||||
user: {
|
||||
id: 1001,
|
||||
},
|
||||
};
|
||||
|
||||
const service = new UserService(ctx);
|
||||
|
||||
return {
|
||||
app,
|
||||
ctx,
|
||||
service,
|
||||
cacheWrites,
|
||||
cacheStore,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js', () => {
|
||||
it('should generate pending code with fixed 60s ttl and keep same code without extending', async () => {
|
||||
const fixedNow = 1760000000000;
|
||||
const originalNow = Date.now;
|
||||
Date.now = () => fixedNow;
|
||||
|
||||
try {
|
||||
const { service, cacheWrites } = createServiceHarness();
|
||||
service.findYe4sBindingByAccountId = async () => null;
|
||||
|
||||
const first = await service.refreshWechatBindState(1001, null, {
|
||||
forceNewCode: false,
|
||||
});
|
||||
|
||||
assert.equal(first.state.status, 'pending');
|
||||
assert.match(String(first.state.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
|
||||
assert.equal(first.state.expires_at, fixedNow + 60000);
|
||||
|
||||
const firstWriteCount = cacheWrites.length;
|
||||
assert.equal(firstWriteCount, 2);
|
||||
for (const write of cacheWrites) {
|
||||
assert.equal(write.expireSeconds, 60);
|
||||
}
|
||||
|
||||
const second = await service.refreshWechatBindState(1001, first.state, {
|
||||
forceNewCode: false,
|
||||
});
|
||||
|
||||
assert.equal(second.state.code, first.state.code);
|
||||
assert.equal(second.state.status, 'pending');
|
||||
assert.equal(cacheWrites.length, firstWriteCount);
|
||||
} finally {
|
||||
Date.now = originalNow;
|
||||
}
|
||||
});
|
||||
|
||||
it('should return scanned status when scan key exists', async () => {
|
||||
const fixedNow = 1760000000000;
|
||||
const originalNow = Date.now;
|
||||
Date.now = () => fixedNow;
|
||||
|
||||
try {
|
||||
const { service, cacheStore } = createServiceHarness();
|
||||
service.findYe4sBindingByAccountId = async () => null;
|
||||
|
||||
const pending = await service.refreshWechatBindState(1001, null, {
|
||||
forceNewCode: false,
|
||||
});
|
||||
const code = pending.state.code;
|
||||
|
||||
cacheStore.set(`user:wechat:bind:scan:${code}`, {
|
||||
account_id: 1001,
|
||||
code,
|
||||
status: 'scanned',
|
||||
scanned_at: new Date(fixedNow + 1000).toISOString(),
|
||||
});
|
||||
|
||||
const result = await service.refreshWechatBindState(1001, pending.state, {
|
||||
forceNewCode: false,
|
||||
});
|
||||
|
||||
assert.equal(result.state.status, 'scanned');
|
||||
assert.equal(result.state.code, code);
|
||||
assert.ok(result.state.scanned_at);
|
||||
} finally {
|
||||
Date.now = originalNow;
|
||||
}
|
||||
});
|
||||
|
||||
it('should rotate code when forceNewCode is enabled', async () => {
|
||||
const fixedNow = 1760000000000;
|
||||
const originalNow = Date.now;
|
||||
Date.now = () => fixedNow;
|
||||
|
||||
try {
|
||||
const { service, cacheWrites } = createServiceHarness();
|
||||
service.findYe4sBindingByAccountId = async () => null;
|
||||
|
||||
const oldState = {
|
||||
account_id: 1001,
|
||||
status: 'pending',
|
||||
code: 'A1B2C3',
|
||||
expires_at: fixedNow + 30000,
|
||||
};
|
||||
|
||||
const result = await service.refreshWechatBindState(1001, oldState, {
|
||||
forceNewCode: true,
|
||||
});
|
||||
|
||||
assert.equal(result.state.status, 'pending');
|
||||
assert.notEqual(result.state.code, oldState.code);
|
||||
assert.equal(result.state.expires_at, fixedNow + 60000);
|
||||
|
||||
const oldCodeInvalidation = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1);
|
||||
assert.ok(oldCodeInvalidation);
|
||||
} finally {
|
||||
Date.now = originalNow;
|
||||
}
|
||||
});
|
||||
});
|
||||
103
test/app/service/systems/auth.user.loginWechatCode.test.js
Normal file
103
test/app/service/systems/auth.user.loginWechatCode.test.js
Normal file
@ -0,0 +1,103 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const UserService = require('../../../../app/service/systems/auth/user');
|
||||
|
||||
function createServiceHarness() {
|
||||
const cacheWrites = [];
|
||||
const cacheStore = new Map();
|
||||
|
||||
const app = {
|
||||
async setCacheAsync(cacheKey, data, expireSeconds = 300) {
|
||||
cacheWrites.push({
|
||||
cacheKey,
|
||||
data,
|
||||
expireSeconds,
|
||||
});
|
||||
|
||||
if (data === null || data === undefined || expireSeconds <= 1) {
|
||||
cacheStore.delete(cacheKey);
|
||||
return;
|
||||
}
|
||||
|
||||
cacheStore.set(cacheKey, data);
|
||||
},
|
||||
async getCacheAsync(cacheKey) {
|
||||
return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null;
|
||||
},
|
||||
coreLogger: {
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app,
|
||||
};
|
||||
|
||||
const service = new UserService(ctx);
|
||||
|
||||
return {
|
||||
app,
|
||||
ctx,
|
||||
service,
|
||||
cacheWrites,
|
||||
cacheStore,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/auth.user.loginWechatCode.test.js', () => {
|
||||
it('should generate client code and login code when client code is missing', async () => {
|
||||
const { service, cacheWrites } = createServiceHarness();
|
||||
|
||||
const result = await service.getLoginWechatCode({});
|
||||
|
||||
assert.equal(result.success, true);
|
||||
assert.equal(result.code, 200);
|
||||
assert.match(String(result.data.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
|
||||
assert.match(String(result.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
|
||||
assert.equal(result.data.status, 'pending');
|
||||
assert.ok(String(result.message || '').includes('客户端编码'));
|
||||
|
||||
const writesWithState = cacheWrites.filter(item => item && item.data && item.data.client_code === result.data.client_code);
|
||||
assert.equal(writesWithState.length, 2);
|
||||
for (const write of writesWithState) {
|
||||
assert.equal(write.expireSeconds, 60);
|
||||
}
|
||||
});
|
||||
|
||||
it('should refresh login code after long poll when client code is provided', async () => {
|
||||
const { service, cacheWrites } = createServiceHarness();
|
||||
service.waitForLoginCodeRefresh = async () => {};
|
||||
|
||||
const first = await service.getLoginWechatCode({});
|
||||
const firstCode = String(first.data.code || '');
|
||||
const clientCode = String(first.data.client_code || '');
|
||||
|
||||
const second = await service.getLoginWechatCode({
|
||||
clientCode,
|
||||
});
|
||||
|
||||
assert.equal(second.success, true);
|
||||
assert.equal(second.code, 200);
|
||||
assert.equal(String(second.data.client_code || ''), clientCode);
|
||||
assert.match(String(second.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/);
|
||||
assert.notEqual(String(second.data.code || ''), firstCode);
|
||||
assert.ok(String(second.message || '').includes('长轮询结束'));
|
||||
|
||||
const invalidationWrite = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1);
|
||||
assert.ok(invalidationWrite);
|
||||
});
|
||||
|
||||
it('should fail when provided client code format is invalid', async () => {
|
||||
const { service } = createServiceHarness();
|
||||
|
||||
const result = await service.getLoginWechatCode({
|
||||
clientCode: 'abc',
|
||||
});
|
||||
|
||||
assert.equal(result.success, false);
|
||||
assert.equal(result.code, 0);
|
||||
assert.match(String(result.message || ''), /客户端编码/);
|
||||
});
|
||||
});
|
||||
257
test/app/service/systems/excel.test.js
Normal file
257
test/app/service/systems/excel.test.js
Normal file
@ -0,0 +1,257 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const XLSX = require('xlsx');
|
||||
const ExcelService = require('../../../../app/service/systems/excel');
|
||||
|
||||
function createService(overrides = {}) {
|
||||
const uploads = [];
|
||||
const notifyCalls = [];
|
||||
const ctx = {
|
||||
app: {
|
||||
config: {},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
error() {},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
upload: {
|
||||
async uploadFile(fileStream, options = {}) {
|
||||
const chunks = [];
|
||||
for await (const chunk of fileStream) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
}
|
||||
|
||||
const body = Buffer.concat(chunks);
|
||||
uploads.push({
|
||||
filename: fileStream.filename,
|
||||
mimeType: fileStream.mimeType,
|
||||
fileSize: fileStream.fileSize,
|
||||
options,
|
||||
body,
|
||||
});
|
||||
|
||||
return {
|
||||
fileName: options.key,
|
||||
cosUrl: `https://cos.example.com/${options.key}`,
|
||||
cdnUrl: `https://cdn.example.com/${options.key}`,
|
||||
url: `https://cdn.example.com/${options.key}`,
|
||||
};
|
||||
},
|
||||
async uploadSuccessNotify(data) {
|
||||
notifyCalls.push(data);
|
||||
return {
|
||||
code: 0,
|
||||
data: {
|
||||
fileId: 9527,
|
||||
fileKey: data.url,
|
||||
fileUrl: `https://cdn.example.com/${data.url}`,
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
|
||||
const service = new ExcelService(ctx);
|
||||
return {
|
||||
service,
|
||||
uploads,
|
||||
notifyCalls,
|
||||
ctx,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/excel.test.js', () => {
|
||||
it('should generate workbook buffer and parse rows back', async () => {
|
||||
const { service } = createService();
|
||||
|
||||
const buffer = await service.generateBuffer({
|
||||
sheets: [
|
||||
{
|
||||
name: '入库单',
|
||||
columns: [
|
||||
{ header: '单号', key: 'order_no', width: 20 },
|
||||
{ header: '货主', key: 'owner_name', width: 18 },
|
||||
{ header: '箱数', key: 'total_boxes', width: 10 },
|
||||
],
|
||||
rows: [
|
||||
{
|
||||
order_no: 'RK20260404001',
|
||||
owner_name: '测试货主',
|
||||
total_boxes: 12,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.ok(Buffer.isBuffer(buffer));
|
||||
assert.ok(buffer.length > 0);
|
||||
|
||||
const parsed = await service.parseBuffer(buffer);
|
||||
assert.deepEqual(parsed.sheetNames, [ '入库单' ]);
|
||||
assert.equal(parsed.sheets[0].rows[0].单号, 'RK20260404001');
|
||||
assert.equal(parsed.sheets[0].rows[0].货主, '测试货主');
|
||||
assert.equal(parsed.sheets[0].rows[0].箱数, '12');
|
||||
});
|
||||
|
||||
it('should normalize duplicated or empty headers when parsing', async () => {
|
||||
const { service } = createService();
|
||||
|
||||
const buffer = await service.generateBuffer({
|
||||
sheets: [
|
||||
{
|
||||
name: '重复表头',
|
||||
rows: [
|
||||
[ '名称', '名称', '' ],
|
||||
[ 'A', 'B', 'C' ],
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const parsed = await service.parseBuffer(buffer);
|
||||
assert.deepEqual(parsed.sheets[0].headers, [ '名称', '名称_2', 'column_3' ]);
|
||||
assert.equal(parsed.sheets[0].rows[0].名称, 'A');
|
||||
assert.equal(parsed.sheets[0].rows[0].名称_2, 'B');
|
||||
assert.equal(parsed.sheets[0].rows[0].column_3, 'C');
|
||||
});
|
||||
|
||||
it('should generate excel and upload to custom directory', async () => {
|
||||
const { service, uploads, notifyCalls } = createService();
|
||||
|
||||
const result = await service.generateAndUpload({
|
||||
filename: '收货报表.xlsx',
|
||||
dir: 'exports/receiving',
|
||||
saveRecord: true,
|
||||
businessType: 'receiving',
|
||||
businessId: 1001,
|
||||
expireDays: 90,
|
||||
sheets: [
|
||||
{
|
||||
name: '报表',
|
||||
columns: [
|
||||
{ header: '单号', key: 'order_no' },
|
||||
],
|
||||
rows: [
|
||||
{ order_no: 'RK1001' },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(uploads.length, 1);
|
||||
assert.equal(uploads[0].filename, '收货报表.xlsx');
|
||||
assert.equal(uploads[0].mimeType, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
assert.ok(uploads[0].options.key.includes('exports/receiving/'));
|
||||
assert.ok(Buffer.isBuffer(uploads[0].body));
|
||||
assert.ok(uploads[0].body.length > 0);
|
||||
assert.equal(notifyCalls[0].expireDays, 90);
|
||||
assert.ok(String(result.fileKey || '').includes('exports/receiving/'));
|
||||
assert.equal(result.fileRecord.fileId, 9527);
|
||||
});
|
||||
|
||||
it('should honor skipHeader when object rows are used', async () => {
|
||||
const { service } = createService();
|
||||
|
||||
const buffer = await service.generateBuffer({
|
||||
sheets: [
|
||||
{
|
||||
name: '跳过首表头',
|
||||
columns: [
|
||||
{ header: '分区', key: 'section', width: 12 },
|
||||
{ header: '字段', key: 'field', width: 16 },
|
||||
{ header: '值', key: 'value', width: 18 },
|
||||
],
|
||||
rows: [
|
||||
{ section: '主表', field: '收货单号', value: 'R001' },
|
||||
{ section: '明细表头', field: '字段', value: '值' },
|
||||
],
|
||||
skipHeader: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const workbook = XLSX.read(buffer, { type: 'buffer' });
|
||||
const rawRows = XLSX.utils.sheet_to_json(workbook.Sheets['跳过首表头'], {
|
||||
header: 1,
|
||||
defval: '',
|
||||
});
|
||||
|
||||
assert.deepEqual(rawRows[0], [ '主表', '收货单号', 'R001' ]);
|
||||
assert.deepEqual(rawRows[1], [ '明细表头', '字段', '值' ]);
|
||||
});
|
||||
|
||||
it('should support embedded images when url is a data URL', async () => {
|
||||
const { service } = createService();
|
||||
const imageDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9WnR8i8AAAAASUVORK5CYII=';
|
||||
|
||||
const buffer = await service.generateBuffer({
|
||||
sheets: [
|
||||
{
|
||||
name: 'URL图片',
|
||||
rows: [ [ '图片', '见右侧' ] ],
|
||||
embeddedImages: [
|
||||
{
|
||||
row: 1,
|
||||
col: 2,
|
||||
url: imageDataUrl,
|
||||
width: 40,
|
||||
height: 40,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.ok(Buffer.isBuffer(buffer));
|
||||
assert.ok(buffer.length > 0);
|
||||
});
|
||||
|
||||
it('should generate workbook with embedded image previews when image config exists', async () => {
|
||||
const { service } = createService();
|
||||
const imageDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9WnR8i8AAAAASUVORK5CYII=';
|
||||
|
||||
const buffer = await service.generateBuffer({
|
||||
sheets: [
|
||||
{
|
||||
name: '图片预览',
|
||||
columns: [
|
||||
{ header: '名称', key: 'name', width: 20 },
|
||||
{ header: '链接', key: 'url', width: 30 },
|
||||
{ header: '图片', key: 'preview', width: 22 },
|
||||
],
|
||||
rows: [
|
||||
{
|
||||
name: '示例图片',
|
||||
url: 'https://example.com/demo.png',
|
||||
preview: '见右侧',
|
||||
},
|
||||
],
|
||||
embeddedImages: [
|
||||
{
|
||||
row: 2,
|
||||
col: 3,
|
||||
dataUrl: imageDataUrl,
|
||||
width: 60,
|
||||
height: 60,
|
||||
fallbackText: '示例图片',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.ok(Buffer.isBuffer(buffer));
|
||||
assert.ok(buffer.length > 0);
|
||||
|
||||
const parsed = await service.parseBuffer(buffer);
|
||||
assert.deepEqual(parsed.sheetNames, [ '图片预览' ]);
|
||||
assert.equal(parsed.sheets[0].rows[0].名称, '示例图片');
|
||||
});
|
||||
});
|
||||
@ -194,7 +194,7 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js
|
||||
|
||||
assert.deepEqual(between, {
|
||||
create_at: {
|
||||
[Op.between]: [ '2026-03-01', '2026-03-31' ],
|
||||
[Op.between]: [ '2026-03-01 00:00:00', '2026-03-31 23:59:59' ],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
127
test/app/service/systems/storage.receiving.report.test.js
Normal file
127
test/app/service/systems/storage.receiving.report.test.js
Normal file
@ -0,0 +1,127 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const ReceivingService = require('../../../../app/service/systems/storage/receiving');
|
||||
|
||||
function createService() {
|
||||
const excelCalls = [];
|
||||
const ctx = {
|
||||
app: {
|
||||
config: {},
|
||||
Sequelize: {
|
||||
Op: {},
|
||||
},
|
||||
},
|
||||
user: {
|
||||
store_id: 2001,
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
excel: {
|
||||
async generateAndUpload(options) {
|
||||
excelCalls.push(options);
|
||||
return {
|
||||
fileKey: options.filename,
|
||||
url: `https://cdn.example.com/${options.filename}`,
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const service = new ReceivingService(ctx);
|
||||
return {
|
||||
service,
|
||||
excelCalls,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/storage.receiving.report.test.js', () => {
|
||||
it('should build and upload completion excel in a single sheet with one preview column', async () => {
|
||||
const { service, excelCalls } = createService();
|
||||
|
||||
const result = await service.uploadCompletionExcelReport({
|
||||
receiving: {
|
||||
id: 123,
|
||||
receiving_number: 'RCV202604040001',
|
||||
store_name: '测试货主',
|
||||
warehouse_id: 2001,
|
||||
delivery_method: 'truck',
|
||||
license_plate: '粤A12345',
|
||||
tracking_number: 'YT123456789',
|
||||
total_boxes: 3,
|
||||
total_pallets: 1,
|
||||
remark: '完成收货测试',
|
||||
receiving_end_time: new Date('2026-04-04T12:30:00Z'),
|
||||
details: [
|
||||
{
|
||||
id: 501,
|
||||
product_name: '测试商品A',
|
||||
system_product_id: 9001,
|
||||
barcode: 'SKU-001',
|
||||
actual_quantity: 8,
|
||||
weight: 12,
|
||||
},
|
||||
],
|
||||
},
|
||||
operator: {
|
||||
employees_name: '测试员',
|
||||
},
|
||||
stats: {
|
||||
total_details: 1,
|
||||
matched_details: 1,
|
||||
unmatched_details: 0,
|
||||
total_quantity: 8,
|
||||
},
|
||||
detailImageMap: new Map([
|
||||
[ '501', [
|
||||
{ url: 'https://example.com/image-1.png' },
|
||||
{ url: 'https://example.com/image-2.png' },
|
||||
]],
|
||||
]),
|
||||
receivingImages: [
|
||||
{ url: 'https://example.com/main-image.png' },
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(excelCalls.length, 1);
|
||||
const [ options ] = excelCalls;
|
||||
assert.equal(options.filename, '收货完成_RCV202604040001.xlsx');
|
||||
assert.ok(String(options.dir || '').includes('receiving/completed'));
|
||||
assert.equal(options.expireDays, 90);
|
||||
assert.ok(Array.isArray(options.sheets));
|
||||
assert.equal(options.sheets.length, 1);
|
||||
|
||||
const [ sheet ] = options.sheets;
|
||||
assert.equal(sheet.name, '收货清单');
|
||||
assert.ok(Array.isArray(sheet.rows));
|
||||
assert.equal(sheet.skipHeader, true);
|
||||
|
||||
const receivingNumberRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货单号');
|
||||
assert.ok(receivingNumberRow, '应在主表区域包含收货单号行');
|
||||
|
||||
const summaryImageRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货图片');
|
||||
assert.ok(summaryImageRow, '应在主表区域包含收货图片行');
|
||||
assert.match(String(summaryImageRow[1]?.text || summaryImageRow[1] || ''), /main-image/);
|
||||
|
||||
const detailHeaderRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '序号' && item[1] === '商品名称');
|
||||
assert.ok(detailHeaderRow, '明细表头应出现在下方明细区开始处');
|
||||
|
||||
const detailRow = sheet.rows.find(item => Array.isArray(item) && item[1] === '测试商品A');
|
||||
assert.ok(detailRow, '应在单 sheet 中包含明细行');
|
||||
assert.match(String(detailRow[11]?.text || detailRow[11] || ''), /image-1\.png/);
|
||||
assert.equal(detailRow[10], '');
|
||||
|
||||
assert.ok(Array.isArray(sheet.styledRows));
|
||||
assert.ok(sheet.styledRows.some(item => item && item.style && item.style.font && item.style.font.bold), '应包含表头加粗样式');
|
||||
assert.ok(Array.isArray(sheet.embeddedImages));
|
||||
assert.equal(sheet.embeddedImages.length, 3);
|
||||
assert.equal(result.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx');
|
||||
});
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user