diff --git a/.sequelizerc b/.sequelizerc index 4dbbd8d..694d16d 100644 --- a/.sequelizerc +++ b/.sequelizerc @@ -3,8 +3,8 @@ const path = require('path'); module.exports = { - "config": path.join(__dirname, 'database/config.json'), - "migrations-path": path.join(__dirname, 'database/migrations'), - "seeders-path": path.join(__dirname, 'database/seeders'), - "models-path": path.join(__dirname, 'app/model'), + config: path.join(__dirname, 'database/config.js'), + 'migrations-path': path.join(__dirname, 'database/migrations'), + 'seeders-path': path.join(__dirname, 'database/seeders'), + 'models-path': path.join(__dirname, 'app/model'), }; \ No newline at end of file diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index 2ecaf48..94e36d6 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -1,6 +1,6 @@ # AI 工具箱(WMS) -本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。 +本文件用于统一 AI 协助开发/调试时可直接使用的方法,减少重复沟通成本。AI每次应答文尾加喵~以判断是否丢失上下文 ## 1. 适用范围 @@ -591,4 +591,46 @@ npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/contr - `print.getList` - `storage.entry.list` - `stock.warehouse.list` + +## 15. system API 权限映射规则(wms_permission) + +适用范围:`/system` 入口,权限类型为 `type=api`。 + +### 15.1 映射规则 + +- `wms_permission.path` 作为 system method 的权限标识(例如:`setting.account.list`)。 +- 同步来源以 `methods/system.json` 为准:`isNeedAuth=true` 的 method 必须存在对应 `wms_permission(type=api,path=method)`。 +- 角色权限不再以 `wms_role_permission` 作为主存储,统一写入 `wms_role.permissions`。 +- `wms_role.permissions` 支持两种值: + - JSON 数组:如 `[1,2,3]` + - `"*"`:表示拥有所有权限 +- 新增 API 权限后,`role_id=2` 的授权应同步更新其 `permissions` 字段;若该字段为 `"*"` 则无需额外追加。 + +### 15.2 外部脚本(批量补齐) + +固定命令: + +```powershell +# 预览差异(不写库) +npm run permission:sync:system-api -- --dry-run + +# 执行补齐(写库) +npm run permission:sync:system-api +``` + +可选参数: + +- `--role-id=2`:绑定角色 ID(默认 `2`) +- `--db-client=wms`:数据库客户端名(默认 `wms`) +- `--config-path=./config/config.local.js`:配置文件路径 +- `--method-doc=./methods/system.json`:method 文档路径 + +### 15.3 运行时兜底(仅 debug) + +- 入口:`app/service/main.js` 的 `checkApiPermission`。 +- 逻辑:当用户权限列表不包含目标 method 时,若 `app.config.debug === true`,自动: + 1. 参考现有 `type=api` 权限行构建缺失权限行; + 2. 更新 `wms_role(id=2).permissions`,将新权限 ID 追加到 JSON 数组;若该字段为 `"*"` 则保持不变。 +- 生产建议:保持 `app.config.debug=false`,避免运行时自动写库。 + \ No newline at end of file diff --git a/README.md b/README.md index 94f9f59..0389d75 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,11 @@ # 奇门WMS(qimen-wms) -基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。基于AI协助管理项目开发,配置了AI能力脚本和完整的项目地图 +基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。 ## 文档导航 -- AI项目协作工具箱:`AI_TOOLBOX.md` +- 项目协作工具箱:`AI_TOOLBOX.md` - Method 路由映射说明:`AI_METHOD_ROUTING.md` -- stock.warehouse.list 前端查询规则:`docs/stock-stockWarehouse-query-rules.md` - system 接口文档源:`methods/system.json` - qimen 接口文档源:`methods/qimen.json` - 日报:`day.log` @@ -24,7 +23,6 @@ ├── config/ # 配置(poloapi、redis、数据库等) ├── database/ # 迁移与数据库配置 ├── methods/ # 接口文档数据源(JSON) -├── native/ # 原生扩展目录(Node.js C++ addon) ├── script/ # 调试与文档生成脚本 ├── logs/ # 日志 ├── run/ # 运行时/元数据 @@ -39,7 +37,6 @@ - `README.md`:项目入口文档,提供整体说明与规范入口。 - `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。 - `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 -- `docs/stock-stockWarehouse-query-rules.md`:stock.warehouse.list 的 where 构造规则与失败返回说明。 - `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 - `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 - `day.log`:每日工作留痕。 @@ -57,121 +54,10 @@ npm run dev - `npm run dev`:本地开发 - `npm start`:启动生产服务 -- `npm stop`:仅停止当前目录对应的 Egg 生产进程 -- `npm run deploy:prod`:按 `config/deploy.config.local.cjs` 通过 SSH 发布到生产目录 `/www/wwwroot/qimen` -- `npm run deploy:init`:首次发布初始化远端目录与 `config/` 基础文件(不覆盖已有配置) -- `npm run rollback:prod`:按最近一次备份回退生产目录(可加 `-- --backup=backup-时间戳.tar.gz` 指定备份) -- `npm run deploy:precheck`:只读预检 SSH 连通、目录权限、远端 Node/npm/tar 与健康检查,不改动远端文件 -- `npm run deploy:version`:查询当前线上版本号(读取远端 `.deploy/state/current-release.json`) -- `npm run deploy:version:history`:查询最近 20 次线上版本历史 -- `npm run deploy:inspect`:查看远端 `.deploy/state`、`latest-backup.txt` 与备份目录清单 -- `npm run deploy:smoke`:在远端机器本机对 `/`、`/api/docs`、`/internal/v1/gateway`、`/system` 做最小连通冒烟 -- `npm run deploy:verify`:组合执行 `deploy:inspect` + `deploy:smoke` -- `npm run deploy:cleanup-backups -- `:按文件名清理远端 `.deploy/backups` 中指定备份 -- `npm run deploy:gateway-probe -- [payloadJson]`:调用 `/internal/v1/gateway` 做 method 级连通探针 -- `npm run version:record`:记录一次本地包版本快照(写入 `versioning/`,用于回退追溯) -- `npm run version:history`:查询最近 50 条本地版本快照记录 -- `npm run guard:git`:检查当前暂存区是否包含禁止提交的本地机密/运行产物 -- `npm run setup:hooks`:将仓库 pre-commit hook 固化到 `.githooks/pre-commit` +- `npm stop`:停止生产服务 - `npm run lint`:代码风格检查 - `npm test`:单元测试 -## 外部 Method 测试(Egg.js test 规范) - -测试文件按“暴露出口 + method”命名,位于 `test/app/controller/`: - -- `system.user.login.test.js` -- `system.user.info.test.js` - -测试辅助客户端位于: - -- `test/support/system_method_client.js` - -默认测试账号(可通过环境变量覆盖): - -- `SYSTEM_TEST_USERNAME=liufumingren` -- `SYSTEM_TEST_PASSWORD=111111` - -Token 暂存机制: - -- 登录 token 会写入 `test/.runtime/system_user_token.json`。 -- 每次执行测试会优先读取本地 token;若 token 可用,则跳过 `user.login` 调用。 -- 当 token 不存在或过期时,测试脚本会自动调用 `user.login` 并刷新缓存。 - -常用命令: - -```bash -npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js -``` - -可选环境变量: - -- `SYSTEM_TEST_BASE_URL`:默认 `http://127.0.0.1:6060` -- `SYSTEM_TEST_TOKEN_FILE`:默认 `test/.runtime/system_user_token.json` - -## Method 输出一致性回归(新规则) - -目标: - -- 在模型/关联/服务改动前后,确保关键 method 输出结果一致。 - -强制规则: - -1. 改动前先执行 baseline(生成修改前输出快照)。 -2. 改动后执行 compare(对同一批 method 回放并比对)。 -3. compare 结果必须 `mismatch=0` 才可交付。 - -测试账号(默认): - -- `liufumingren / 111111` -- 可通过环境变量覆盖: - - `WMS_TEST_USER` - - `WMS_TEST_PASS` - -method 来源与样本来源: - -- method 配置来源:`methods/system.json` -- 样本数据来源(优先最新日志):`wms_system_log` -- 参考日志来源:`wms_api_log`、`wms_operation_log`、`wms_account_login_log` - -执行脚本: - -- `script/method-output-regression.cjs` -- `script/tmp-generate-method-regression-test.cjs`(根据 baseline 自动生成 Egg.js 标注测试) - -临时文件目录规则: - -- 所有临时产物统一输出到 `temp/`。 -- `temp/` 已加入 git 忽略,不纳入提交。 - -执行命令: - -```powershell -# 修改前:生成基线(默认抽样 8 条) -node .\script\method-output-regression.cjs baseline 8 - -# 修改后:执行对比 -node .\script\method-output-regression.cjs compare - -# 生成 Egg.js 标注测试脚本 -node .\script\tmp-generate-method-regression-test.cjs - -# 执行生成的回归测试 -npx egg-bin test temp/generated-tests/system.method-output.generated.test.js -``` - -输出文件: - -- `temp/method-output/method-output-baseline.json` -- `temp/method-output/method-output-baseline.md` -- `temp/method-output/method-output-compare.json` - -一致性比对说明: - -- 为避免误报,脚本会标准化以下波动字段:`token`、`timestamp`、`last_login_at`、`created_at`、`updated_at`、`iat`、`exp`。 -- 403 权限响应同样参与一致性对比,用于防止权限链路被意外改动。 -- 后续所有接口返回数据检测,统一以生成的 Egg.js 标注测试结果为准。 - ## 主要依赖 - egg.js 3.x @@ -184,6 +70,8 @@ npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - `GET /`:健康检查 - `POST /qimen`:奇门接口 - `POST /system`:system 统一入口 +- `POST /api/v1`:旧版 API +- `POST /api/v2`:新版 API - `GET /template/xml/:id`:打印模板 - `GET|POST /auth/printSetting/:code`:打印台设置 @@ -200,70 +88,6 @@ npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - 全局业务 Header(如 `platform`、`project`)设置 - 方法级在线 POST 调试 -### user.getBindWechatCode 调用约定(微信绑定码) - -- 默认行为:立即返回当前状态(不会长等待,适合页面初始化)。 -- 显式长轮询:仅当 body 传 `waitForChange=true`(或兼容字段 `longPoll=true`)时启用。 -- 长轮询时长:后端单次最长等待 60 秒;60 秒内状态变化会立即返回。 -- 超时返回:若 60 秒内无变化,返回当前状态并提示超时。 -- 初始化强制立即返回:可传 `init=true`(兼容 `isInit=true`、`firstLoad=true`)。 -- 可选等待参数:`waitTimeoutMs`,后端自动封顶 60000。 -- 前端超时建议:HTTP 超时设置为 120000ms(2 分钟),覆盖网络抖动与重试开销。 - -## 接口响应规范(system) - -更新时间:2026-03-22 -适用范围: - -- `POST /system` - -统一目标: - -- 统一 `/system` 入口的响应结构与错误码口径,降低调用方分支判断成本。 - -成功响应示例: - -```json -{ - "flag": "success", - "code": 1, - "message": "ok", - "data": {}, - "timestamp": 1773386721 -} -``` - -失败响应示例: - -```json -{ - "flag": "failure", - "code": 401, - "message": "Unauthorized", - "data": null, - "timestamp": 1773386721 -} -``` - -说明: - -- 业务层若已返回 `flag/code/message` 标准结构,将保留并补齐 `timestamp`。 -- 业务层若返回普通对象或数组,控制器将自动包裹到 `data` 字段。 -- HTTP 状态码保持语义(如 400/401/403/500),业务 `code` 默认与 HTTP 状态码一致。 - -当前错误码口径: - -- 400:请求参数错误(缺少 `method`、`v`、`timestamp`、非法 `method`) -- 401:未登录/令牌无效/无令牌 -- 403:无权限访问 -- 406:业务授权状态异常(如仓库有效期) -- 500:服务内部错误 - -实现位置: - -- 响应封装:`app/lib/api_response.js` -- 控制器接入:`app/controller/home.js`(system/pda) - ## 接口文档联动维护(强制) 当出现以下任一变更时,必须同步更新 `methods` 下对应文档: @@ -284,163 +108,12 @@ node .\script\tmp-struct-system-params.cjs ``` 4. 补充自动提取无法覆盖的信息(description/response/errors/枚举约束) -5. 执行 method 输出一致性对比: - -```powershell -node .\script\method-output-regression.cjs compare -``` ## 配置说明 - 主要配置文件在 `config/`(如 `config.default.js`、`config.local.js`、`poloapi.js`) - 数据库、Redis、平台配置在对应配置文件中维护 - 敏感信息不要提交到仓库 -- 远程发布配置模板:`config/deploy.config.example.cjs` -- 本地 SSH 发布配置:`config/deploy.config.local.cjs`(已加入 git ignore,仅本机保留) - -## 远程发布与回退(SSH) - -生产目录固定为:`/www/wwwroot/qimen` - -约定: - -- 发布脚本通过本机 `ssh/scp/tar/git` 执行,不依赖额外 npm 包。 -- 每次发布前会在服务器上生成一份当前目录备份,保存到 `/www/wwwroot/qimen/.deploy/backups/`。 -- 回退默认使用最近一次发布前备份,也支持显式传入备份名。 -- 发布和回退都会保留 `.deploy`、`logs`、`run`、`temp` 目录,避免误删运行态目录。 -- 发布与回退阶段的停服务操作只会匹配当前 `deployRoot` 对应的 Egg 进程,不再直接调用全局 `egg-scripts stop` 扫描整机进程。 - -首次配置: - -1. 完善 `config/deploy.config.local.cjs` 中的 `host`、`username`、`privateKeyPath`。 -2. 执行 `npm run setup:hooks`,启用本地 pre-commit 安全检查。 -3. 确认远端机器存在 Node.js、npm、tar,且 SSH 用户对 `/www/wwwroot/qimen` 有读写权限。 -4. 执行 `npm run deploy:init` 完成首次初始化(只在远端 `config/` 缺失或为空时写入基础文件)。 - -发布命令: - -```powershell -npm run deploy:init -npm run deploy:prod -``` - -回退命令: - -```powershell -npm run rollback:prod -npm run rollback:prod -- --backup=backup-20260324123045.tar.gz -``` - -脚本行为: - -- 发布时按 Egg.js 最小运行集打包(默认仅 `app.js`、`app/**`、`methods/**`、`native/addons/**`、`package*.json`)。 -- 打包文件来自已跟踪 git 文件(`git ls-files --cached`),不会带入本地未跟踪文件。 -- `config/` 目录不参与发布包覆盖,远端发布与回退过程都会保留现有 `config/`。 -- 首次发布若远端不存在 `config/`,发布会中止并提示先创建生产配置。 -- 默认发布后执行:`npm install --production`、定点停止当前部署目录进程、`npm start`。 -- 若配置了 `healthCheckUrl`,发布与回退后会执行一次健康检查。 -- 每次发布会自动生成线上版本号,格式:`v{package.version}-{yyyyMMddHHmmss}-{gitShortCommit}`。 -- 发布会写入版本元数据到远端: - - 当前版本:`/www/wwwroot/qimen/.deploy/state/current-release.json` - - 历史版本:`/www/wwwroot/qimen/.deploy/state/release-history.jsonl` - -版本查询命令: - -```powershell -npm run deploy:version -npm run deploy:version:history -``` - -运维检查与清理命令: - -```powershell -npm run deploy:inspect -npm run deploy:smoke -npm run deploy:verify -npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz -npm run deploy:gateway-probe -- releaseProbe.ping "{}" -``` - -## 本地版本管理目录(回退辅助) - -目录:`versioning/` - -用途: - -- 记录每次更新时的包版本、提交号、分支、时间。 -- 部署成功后会自动追加一条记录(source=`deploy:prod`)。 -- 也可手动记录一次快照(source=`version:record`)。 - -文件: - -- `versioning/package-version-current.json`:当前最近一条本地版本记录 -- `versioning/package-version-history.jsonl`:本地版本历史(JSONL) - -说明: - -- `versioning/` 目录内容默认不提交到 git(仅保留目录占位)。 -- 回退前可先通过本地历史快速定位目标版本,再结合远端备份名执行回退。 - -本地命令: - -```powershell -# 手动记录一次本地版本快照 -npm run version:record - -# 查询本地版本历史 -npm run version:history -``` - -当前等待项: - -- 由于 SSH 目标主机、账号、私钥路径仍是占位值,完成这些字段前不要执行发布/回退测试。 - -## App 能力清单(汇总) - -能力入口文件: - -- `app.js` -- `app/extend/application.js` - -### A. 应用启动能力(app.js) - -- 设置应用根路径:`global.APP_ROOT`、`app.appRoot` -- 启动前初始化动态工厂: - - `OrderDeliveryFactory` - - `OrderItemsFactory` -- 启动时自检扩展能力: - - 缓存方法可用性(`app.setCacheAsync` / `app.getCacheAsync`) - - Message 能力类型检查(`app.Message`) -- 扩展全局日期格式化:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')` - -### B. Application 扩展能力(app/extend/application.js) - -- 业务字典访问能力: - - `businessDict` getter - - `getBusinessTypeName(code)` - - `getOperationCodeName(code)` - - `getPlatformName(code)` - - `getExternalLogTypeName(type)` -- 外部 SOAP 调用能力: - - `wsdl(methodName, args)` -- Redis 缓存能力(cache client): - - `setCacheAsync(cacheKey, data, expireSeconds = 300)` - - `getCacheAsync(cacheKey)` -- Message 扩展能力: - - `Message` getter(返回 MessageClass) - -### C. 迁移完成确认 - -- 原先在 `app.js` 直接挂载的字典映射方法已迁移到 `app/extend/application.js`。 -- 当前 `app.js` 仅保留启动初始化与非方法迁移逻辑,避免双源实现。 - -### D. Method 输出回归能力(质量门禁) - -- 回归脚本:`script/method-output-regression.cjs` -- 基线文件:`temp/method-output/method-output-baseline.json`、`temp/method-output/method-output-baseline.md` -- 对比文件:`temp/method-output/method-output-compare.json` -- 使用方式:先 `baseline`,后 `compare` -- 门禁标准:`mismatch=0` 才允许交付 ## 功能模块 @@ -449,41 +122,55 @@ npm run version:history - 打印与打印台管理 - 仓库/门店管理 - 权限与角色管理 -- 原生扩展算法能力(native/addons) +- Excel 表格生成、导入与解析 -## Native 原生扩展能力 +## Excel 服务能力 -目录:`native/addons/` +系统已提供服务类:`app/service/systems/excel.js`,可通过 `ctx.service.systems.excel` 调用。 -当前已存在的原生模块: +支持能力: -- `subset_selector.node`(已在业务代码接入) - - 接入位置:`app/service/apiMethods/test.js` - - 已使用能力:`selectOrders(orders, n, type)` - - 业务用途:对订单及 SKU 集合进行子集筛选/组合选择(用于加速 JS 侧大批量集合计算) +- 生成单 sheet / 多 sheet Excel +- 按 `columns + rows` 输出表格 +- 输出 `Buffer`、写入本地文件、直接作为下载响应返回 +- 解析 `.xlsx` / `.xls` 文件内容为 JSON +- 自动处理空表头、重复表头 -- `fibonacci_addon.node`(当前未检索到业务调用) - - 现状:仓库中存在产物文件,但暂无 controller/service 调用链路 +常用方法: -当前接入状态说明: +- `generateBuffer(options)`:生成 Excel 二进制内容 +- `writeFile(filePath, options)`:写入本地文件 +- `sendFile({ filename, sheets })`:HTTP 下载输出 +- `parseBuffer(buffer, options)`:解析上传后的文件流 +- `parseFile(filePath, options)`:解析本地 Excel 文件 -- `subset_selector.node` 在 service 构造时通过 `require(app.appRoot + '/native/addons/subset_selector.node')` 动态加载。 -- 若加载失败,日志会记录“C++插件加载失败”,对应方法会因 addon 不可用而无法执行原生算法分支。 +示例: -兼容性提示: +```js +const buffer = await ctx.service.systems.excel.generateBuffer({ + sheets: [ + { + name: '入库单', + columns: [ + { header: '单号', key: 'order_no', width: 20 }, + { header: '货主', key: 'owner_name', width: 18 }, + ], + rows: [ + { order_no: 'RK20260404001', owner_name: '测试货主' }, + ], + }, + ], +}); -- Node.js 原生 addon 与运行环境强相关(系统、架构、Node ABI 版本)。 -- 当出现 `ERR_DLOPEN_FAILED` / `is not a valid Win32 application` 时,通常表示 addon 与当前 Node 版本或构建目标不匹配,需要使用目标环境重新编译 addon。 +const parsed = await ctx.service.systems.excel.parseFile('D:/tmp/demo.xlsx'); +``` ## 常见问题 - 启动端口默认 6060,可在配置中调整 - 数据库/Redis 连接失败优先检查 `config/config.local.js` - 接口路由映射可查阅 `AI_METHOD_ROUTING.md` -- native addon 加载失败(`ERR_DLOPEN_FAILED`)时,优先检查 Node 版本与 addon 构建目标是否一致 -- `npm run deploy:prod` 提示 SSH 配置未完善时,先补齐 `config/deploy.config.local.cjs` 中的 `host/username/privateKeyPath` -- `npm run guard:git` 或 pre-commit 拦截提交时,说明暂存区包含本地机密文件或运行产物 -- system接口的日志在数据库wms中的表wms_system_log + ## 日报维护 - 日报统一记录在 `day.log` diff --git a/app/lib/query_condition_parser.js b/app/lib/query_condition_parser.js index 72737d4..baeac5b 100644 --- a/app/lib/query_condition_parser.js +++ b/app/lib/query_condition_parser.js @@ -20,24 +20,51 @@ function isEmptyValue(value) { return false; } -function normalizeDate(value) { +function formatLocalDateTime(date, isEnd = false) { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${year}-${month}-${day} ${isEnd ? '23:59:59' : '00:00:00'}`; +} + +function normalizeDate(value, options = {}) { + const { isEnd = false } = options; + if (value === undefined || value === null) { return value; } - if (typeof value === 'string') { - return value.trim(); - } - if (value instanceof Date) { if (isNaN(value.getTime())) return value; - return value.toISOString().slice(0, 19).replace('T', ' '); + return formatLocalDateTime(value, isEnd); } if (typeof value === 'number') { const date = new Date(value); if (isNaN(date.getTime())) return value; - return date.toISOString().slice(0, 19).replace('T', ' '); + return formatLocalDateTime(date, isEnd); + } + + if (typeof value === 'string') { + const trimmed = value.trim(); + if (!trimmed) { + return trimmed; + } + + if (/^\d+$/.test(trimmed)) { + const date = new Date(Number(trimmed)); + if (!isNaN(date.getTime())) { + return formatLocalDateTime(date, isEnd); + } + return trimmed; + } + + const parsed = new Date(trimmed); + if (!isNaN(parsed.getTime())) { + return formatLocalDateTime(parsed, isEnd); + } + + return trimmed; } return value; @@ -59,11 +86,13 @@ function processConditionValue(value, type) { return value; case 'date': + return normalizeDate(value, { isEnd: false }); + case 'daterange': if (Array.isArray(value)) { - return value.map(v => normalizeDate(v)); + return value.map((v, index) => normalizeDate(v, { isEnd: index === value.length - 1 })); } - return normalizeDate(value); + return normalizeDate(value, { isEnd: false }); case 'number': { const num = parseFloat(value); diff --git a/app/model/api_app.js b/app/model/api_app.js index 51e9cfe..d0540e3 100644 --- a/app/model/api_app.js +++ b/app/model/api_app.js @@ -177,6 +177,7 @@ module.exports = app => { freezeTableName: true, underscored: true, timestamps: true, + paranoid: false, createdAt: 'created_at', updatedAt: 'updated_at', comment: 'API应用配置表', diff --git a/app/model/express.js b/app/model/express.js new file mode 100644 index 0000000..bda9b96 --- /dev/null +++ b/app/model/express.js @@ -0,0 +1,27 @@ +'use strict'; + +module.exports = app => { + const { STRING } = app.Sequelize; + + const Express = app.model.define('express', { + code: { + type: STRING(50), + primaryKey: true, + allowNull: false, + comment: '快递编码', + }, + name: { + type: STRING(255), + allowNull: true, + comment: '快递名称', + }, + }, { + tableName: 'wms_express', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '快递基础信息表', + }); + + return Express; +}; diff --git a/app/model/express_print_record.js b/app/model/express_print_record.js new file mode 100644 index 0000000..85ce1a6 --- /dev/null +++ b/app/model/express_print_record.js @@ -0,0 +1,204 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE, TEXT, JSON } = app.Sequelize; + + const ExpressPrintRecord = app.model.define('express_print_record', { + id: { + type: BIGINT(20), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_id: { + type: BIGINT(20), + allowNull: false, + comment: '快递记录ID', + }, + order_id: { + type: STRING(50), + allowNull: false, + comment: '订单ID', + }, + express_no: { + type: STRING(50), + allowNull: false, + comment: '快递单号', + }, + platform: { + type: STRING(50), + allowNull: false, + comment: '平台编码', + }, + template_id: { + type: BIGINT(20), + allowNull: false, + comment: '模板ID', + }, + template_url: { + type: STRING(500), + allowNull: true, + comment: '模板URL', + }, + printer_name: { + type: STRING(100), + allowNull: true, + comment: '打印机名称', + }, + printer_config_id: { + type: BIGINT(20), + allowNull: true, + comment: '打印配置ID', + }, + print_data: { + type: JSON, + allowNull: false, + comment: '打印请求数据', + }, + encrypted_data: { + type: TEXT, + allowNull: true, + comment: '加密数据', + }, + signature: { + type: STRING(500), + allowNull: true, + comment: '签名', + }, + add_data: { + type: JSON, + allowNull: true, + comment: '附加数据', + }, + custom_data: { + type: JSON, + allowNull: true, + comment: '自定义数据', + }, + print_status: { + type: STRING(20), + allowNull: false, + defaultValue: 'PENDING', + comment: '打印状态', + }, + print_count: { + type: INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '打印次数', + }, + last_print_time: { + type: DATE, + allowNull: true, + comment: '最近打印时间', + }, + next_retry_time: { + type: DATE, + allowNull: true, + comment: '下次重试时间', + }, + request_id: { + type: STRING(100), + allowNull: true, + comment: '请求ID', + }, + document_id: { + type: STRING(100), + allowNull: true, + comment: '文档ID', + }, + batch_no: { + type: STRING(50), + allowNull: true, + comment: '批次号', + }, + print_result: { + type: TEXT, + allowNull: true, + comment: '打印结果', + }, + error_message: { + type: STRING(500), + allowNull: true, + comment: '错误信息', + }, + print_cost_time: { + type: INTEGER(11), + allowNull: true, + comment: '打印耗时(ms)', + }, + create_interface: { + type: STRING(100), + allowNull: true, + comment: '创建接口名', + }, + print_interface: { + type: STRING(100), + allowNull: true, + comment: '打印接口名', + }, + operator_id: { + type: BIGINT(20), + allowNull: true, + comment: '操作人ID', + }, + warehouse_id: { + type: BIGINT(20), + allowNull: true, + comment: '仓库ID', + }, + create_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + print_time: { + type: DATE, + allowNull: true, + comment: '打印时间', + }, + update_time: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }, { + tableName: 'wms_express_print_record', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '快递面单打印记录表', + indexes: [ + { + name: 'idx_express_id', + fields: [ 'express_id' ], + }, + { + name: 'idx_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_express_no', + fields: [ 'express_no' ], + }, + { + name: 'uk_request_id', + unique: true, + fields: [ 'request_id' ], + }, + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + { + name: 'idx_print_status', + fields: [ 'print_status' ], + }, + ], + }); + + return ExpressPrintRecord; +}; diff --git a/app/model/express_setting.js b/app/model/express_setting.js new file mode 100644 index 0000000..9256d5e --- /dev/null +++ b/app/model/express_setting.js @@ -0,0 +1,48 @@ +'use strict'; + +module.exports = app => { + const { INTEGER, STRING, BIGINT } = app.Sequelize; + + const ExpressSetting = app.model.define('express_setting', { + id: { + type: INTEGER(11), + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_code: { + type: STRING(50), + allowNull: true, + comment: '快递编码', + }, + code: { + type: STRING(50), + allowNull: true, + comment: '设置项编码', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '仓库主体ID', + }, + }, { + tableName: 'wms_express_setting', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '快递配置表', + indexes: [ + { + name: 'idx_express_code', + fields: [ 'express_code' ], + }, + { + name: 'idx_warehouse_id', + fields: [ 'warehouse_id' ], + }, + ], + }); + + return ExpressSetting; +}; diff --git a/app/model/file.js b/app/model/file.js index ab10e36..2499a4a 100644 --- a/app/model/file.js +++ b/app/model/file.js @@ -102,6 +102,12 @@ module.exports = app => { defaultValue: null, comment: '更新时间', }, + expire_time: { + type: DATE, + allowNull: true, + defaultValue: null, + comment: '过期时间,为空表示永不过期', + }, is_deleted: { type: BOOLEAN, allowNull: false, diff --git a/app/model/interface_type.js b/app/model/interface_type.js index 06f1b59..2e845e2 100644 --- a/app/model/interface_type.js +++ b/app/model/interface_type.js @@ -76,6 +76,7 @@ module.exports = app => { freezeTableName: true, underscored: true, timestamps: true, + paranoid: false, createdAt: 'created_at', updatedAt: 'updated_at', comment: '接口类型配置表', diff --git a/app/model/notification_webhook.js b/app/model/notification_webhook.js new file mode 100644 index 0000000..c0a6037 --- /dev/null +++ b/app/model/notification_webhook.js @@ -0,0 +1,162 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, TINYINT, DATE, JSON } = app.Sequelize; + + const NotificationWebhook = app.model.define('notification_webhook', { + id: { + type: BIGINT.UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + store_id: { + type: BIGINT.UNSIGNED, + allowNull: false, + comment: '主体ID,对应 wms_store.id', + references: { + model: 'store', + key: 'id', + }, + }, + hook_name: { + type: STRING(100), + allowNull: true, + comment: 'Webhook 名称', + }, + hook_type: { + type: STRING(50), + allowNull: false, + validate: { + notEmpty: { + msg: 'hook_type 不能为空', + }, + len: { + args: [ 1, 50 ], + msg: 'hook_type 长度应在1-50个字符之间', + }, + }, + comment: 'Webhook 类型,用于按类型分派通知结构处理逻辑', + }, + hook_url: { + type: STRING(500), + allowNull: false, + validate: { + notEmpty: { + msg: 'hook_url 不能为空', + }, + len: { + args: [ 1, 500 ], + msg: 'hook_url 长度应在1-500个字符之间', + }, + }, + comment: 'Webhook 链接地址', + }, + events: { + type: JSON, + allowNull: true, + comment: '订阅事件列表', + }, + extra_config: { + type: JSON, + allowNull: true, + comment: '扩展配置,如签名、请求头、模板映射等', + }, + status: { + type: TINYINT(4), + allowNull: false, + defaultValue: 1, + validate: { + isIn: { + args: [[ 0, 1 ]], + msg: '状态值不合法,0-禁用,1-启用', + }, + }, + comment: '状态:0-禁用,1-启用', + }, + remark: { + type: STRING(255), + allowNull: true, + comment: '备注', + }, + created_by: { + type: BIGINT.UNSIGNED, + allowNull: true, + comment: '创建人', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + tableName: 'wms_notification_webhook', + freezeTableName: true, + underscored: true, + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: true, + deletedAt: 'deleted_at', + comment: '外部通知 WebHook 配置表', + indexes: [ + { + name: 'idx_notification_webhook_store_id', + fields: [ 'store_id' ], + }, + { + name: 'idx_notification_webhook_hook_type', + fields: [ 'hook_type' ], + }, + { + name: 'idx_notification_webhook_status', + fields: [ 'status' ], + }, + { + name: 'idx_notification_webhook_store_type', + fields: [ 'store_id', 'hook_type' ], + }, + { + name: 'uk_notification_webhook_store_type_url', + unique: true, + fields: [ 'store_id', 'hook_type', 'hook_url' ], + }, + ], + }); + + NotificationWebhook.associate = function() { + const { Store, Account } = app.model; + + NotificationWebhook.belongsTo(Store, { + foreignKey: 'store_id', + targetKey: 'id', + as: 'store', + }); + + NotificationWebhook.belongsTo(Account, { + foreignKey: 'created_by', + targetKey: 'id', + as: 'creator', + constraints: false, + }); + }; + + NotificationWebhook.prototype.isEnabled = function() { + return Number(this.status) === 1; + }; + + return NotificationWebhook; +}; diff --git a/app/model/order_express.js b/app/model/order_express.js new file mode 100644 index 0000000..a02f461 --- /dev/null +++ b/app/model/order_express.js @@ -0,0 +1,89 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, STRING, DATE, ENUM } = app.Sequelize; + + const OrderExpress = app.model.define('order_express', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + waybill_code: { + type: STRING(50), + allowNull: true, + comment: '运单号', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '订单ID', + }, + create_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + delete_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + is_galaxy_receive: { + type: ENUM('Y', 'N'), + allowNull: true, + comment: '是否星河签收', + }, + is_back: { + type: ENUM('Y', 'N'), + allowNull: true, + comment: '是否退回', + }, + is_intercept: { + type: ENUM('Y', 'N'), + allowNull: true, + comment: '是否拦截', + }, + logistics_code: { + type: STRING(50), + allowNull: true, + comment: '物流编码', + }, + logistics_interface_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '物流接口ID', + }, + logistics_name: { + type: STRING(50), + allowNull: true, + comment: '物流名称', + }, + logistics_interface_name: { + type: STRING(50), + allowNull: true, + comment: '物流接口名称', + }, + platform_code: { + type: STRING(50), + allowNull: true, + comment: '平台编码', + }, + }, { + tableName: 'wms_order_express', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单快递信息表', + indexes: [ + { + name: 'idx_order_id', + fields: [ 'order_id' ], + }, + ], + }); + + return OrderExpress; +}; diff --git a/app/model/order_express_print_data.js b/app/model/order_express_print_data.js new file mode 100644 index 0000000..8f68d14 --- /dev/null +++ b/app/model/order_express_print_data.js @@ -0,0 +1,54 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, DATE, TEXT } = app.Sequelize; + + const OrderExpressPrintData = app.model.define('order_express_print_data', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + express_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '快递记录ID', + }, + data: { + type: TEXT, + allowNull: true, + comment: '打印数据', + }, + create_at: { + type: DATE, + allowNull: true, + comment: '创建时间', + }, + delete_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + update_at: { + type: DATE, + allowNull: true, + comment: '更新时间', + }, + }, { + tableName: 'wms_order_express_print_data', + freezeTableName: true, + underscored: true, + timestamps: false, + comment: '订单快递打印数据表', + indexes: [ + { + name: 'idx_express_id', + fields: [ 'express_id' ], + }, + ], + }); + + return OrderExpressPrintData; +}; diff --git a/app/model/permission.js b/app/model/permission.js index 795c2bf..9d0ee55 100644 --- a/app/model/permission.js +++ b/app/model/permission.js @@ -135,8 +135,8 @@ module.exports = app => { }); // 关联关系 - 自关联,构建树形结构 - Permission.associate = function(models) { - const { Role, Permission, RolePermission } = app.model; + Permission.associate = function() { + const { Permission } = app.model; // 子权限 Permission.hasMany(Permission, { foreignKey: 'parent_id', @@ -152,13 +152,6 @@ module.exports = app => { as: 'parent', }); - // 角色权限关联 - Permission.belongsToMany(Role, { - through: RolePermission, - foreignKey: 'permission_id', - otherKey: 'role_id', - as: 'roles', - }); }; // 实例方法:获取类型对应的中文名称 diff --git a/app/model/role.js b/app/model/role.js index 16d2af5..05521c2 100644 --- a/app/model/role.js +++ b/app/model/role.js @@ -49,6 +49,11 @@ module.exports = app => { allowNull: true, comment: '角色描述', }, + permissions: { + type: TEXT, + allowNull: true, + comment: '角色权限集,JSON数组;* 表示所有权限', + }, role_type: { type: TINYINT(4), allowNull: false, @@ -117,6 +122,12 @@ module.exports = app => { allowNull: true, comment: '所属仓库ID', }, + pid: { + type: BIGINT.UNSIGNED, + allowNull: false, + defaultValue: 0, + comment: '父级角色ID,顶级为0', + }, }, { tableName: 'wms_role', freezeTableName: true, @@ -143,12 +154,16 @@ module.exports = app => { name: 'idx_status', fields: [ 'status' ], }, + { + name: 'idx_pid', + fields: [ 'pid' ], + }, ], }); // 关联关系 - Role.associate = function(models) { - const { Account, Store, Permission, RolePermission, EmployeeRole } = app.model; + Role.associate = function() { + const { Account, Store, EmployeeRole } = app.model; // 创建人 Role.belongsTo(Account, { foreignKey: 'created_by', @@ -161,13 +176,6 @@ module.exports = app => { as: 'store', }); - // 权限关联 - Role.belongsToMany(Permission, { - through: RolePermission, - foreignKey: 'role_id', - otherKey: 'permission_id', - as: 'permissions', - }); Role.hasMany(EmployeeRole, { foreignKey: 'role_id', sourceKey: 'id', diff --git a/app/model/role_permission.js b/app/model/role_permission.js deleted file mode 100644 index 1bfd6aa..0000000 --- a/app/model/role_permission.js +++ /dev/null @@ -1,78 +0,0 @@ -'use strict'; - -module.exports = app => { - const { BIGINT, INTEGER, DATE } = app.Sequelize; - - const RolePermission = app.model.define('role_permission', { - id: { - type: BIGINT.UNSIGNED, - primaryKey: true, - autoIncrement: true, - allowNull: false, - comment: '关联ID', - }, - role_id: { - type: BIGINT.UNSIGNED, - allowNull: false, - comment: '角色ID', - }, - permission_id: { - type: INTEGER, - allowNull: false, - comment: '权限ID', - }, - created_at: { - type: DATE, - allowNull: false, - comment: '创建时间', - }, - }, { - tableName: 'wms_role_permission', - freezeTableName: true, - underscored: true, - timestamps: true, - paranoid: false, // 明确禁用软删除 - createdAt: 'created_at', - updatedAt: false, - comment: '角色权限关联表', - indexes: [ - { - name: 'uk_role_permission', - fields: [ 'role_id', 'permission_id' ], - unique: true, - }, - { - name: 'idx_role_id', - fields: [ 'role_id' ], - }, - { - name: 'idx_permission_id', - fields: [ 'permission_id' ], - }, - ], - }); - - // 关联关系 - RolePermission.associate = function(models) { - const { Role, Permission } = app.model; - // 关联角色 - RolePermission.belongsTo(Role, { - foreignKey: 'role_id', - as: 'role', - }); - - // 关联权限 - RolePermission.belongsTo(Permission, { - foreignKey: 'permission_id', - as: 'permission', - }); - }; - - // 实例方法:检查关联是否有效 - RolePermission.prototype.isValid = function() { - // 这里可以添加更多的有效性检查 - return this.role_id && this.permission_id; - }; - - return RolePermission; -}; diff --git a/app/model/store.js b/app/model/store.js index a3839a2..25057f1 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { BIGINT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize; + const { BIGINT, STRING, DATE, TINYINT } = app.Sequelize; const Store = app.model.define('store', { id: { @@ -179,7 +179,7 @@ module.exports = app => { // 关联关系 - 使用您推荐的方式 Store.associate = function() { - const { Account, Role, AccountStoreEmployee, ProhibitedType } = app.model; + const { Account, Role, AccountStoreEmployee, ProhibitedType, NotificationWebhook } = app.model; // 关联创建人 Store.belongsTo(Account, { @@ -209,6 +209,11 @@ module.exports = app => { foreignKey: 'warehouse_id', as: 'prohibitedTypes', }); + + Store.hasMany(NotificationWebhook, { + foreignKey: 'store_id', + as: 'notificationWebhooks', + }); }; // 实例方法:检查商家是否启用 diff --git a/app/service/apiMethods/print.js b/app/service/apiMethods/print.js new file mode 100644 index 0000000..689c6de --- /dev/null +++ b/app/service/apiMethods/print.js @@ -0,0 +1,334 @@ +'use strict'; + +const Service = require('egg').Service; +const crypto = require('node:crypto'); + +class PrintApiService extends Service { + getPrinterRedis() { + return this.app.redis.get('printer'); + } + + normalizeBindValue(bindValue) { + let bindValueObj = bindValue; + try { + bindValueObj = JSON.parse(bindValue); + } catch (_) { + bindValueObj = bindValue; + } + return bindValueObj; + } + + async getEmployeePermissions(employeeId) { + const { ctx } = this; + const roleRows = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: employeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + if (!roleRows || roleRows.length === 0) { + return []; + } + + const roleIds = [ ...new Set(roleRows.map(item => item.role_id).filter(Boolean)) ]; + if (roleIds.length === 0) { + return []; + } + + const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, + }); + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + attributes: [ 'path' ], + where: { + id: { + [ctx.app.Sequelize.Op.in]: permissionIds, + }, + status: 1, + type: 'api', + }, + raw: true, + }); + + return permissions.map(item => item.path).filter(Boolean); + } + + async getBindInfo(data = {}) { + const { ctx } = this; + const accountId = Number(data.account_id || data.accountId || data.wms_account_id || data.wmsAccountId); + const code = String(data.code || '').trim(); + + if (!Number.isFinite(accountId) || accountId <= 0 || !code) { + return { + success: false, + code: 0, + data: null, + message: '缺少有效参数 account_id 或 code', + }; + } + + const account = await ctx.model.Account.findOne({ + where: { id: accountId }, + attributes: [ 'id', 'status' ], + raw: true, + }); + if (!account || Number(account.status) !== 1) { + return { + success: false, + code: 0, + data: null, + message: '账号不存在或已禁用', + }; + } + + const redis = this.getPrinterRedis(); + const bindValue = await redis.get(`bind:${code}`); + if (!bindValue) { + return { + success: false, + code: 0, + data: null, + message: '无效code或未绑定', + }; + } + + const employeeRows = await ctx.model.AccountStoreEmployee.findAll({ + where: { + account_id: accountId, + status: 1, + }, + include: [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status', 'auth_end' ], + where: { + status: 1, + project: 'warehouse', + }, + required: true, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + + const now = new Date(); + const warehouseMap = new Map(); + for (const employee of employeeRows) { + const permissions = await this.getEmployeePermissions(employee.id); + if (!permissions.includes('printer.bind')) { + continue; + } + + const store = employee.store; + if (!store) { + continue; + } + + if (store.auth_end && new Date(store.auth_end) < now) { + continue; + } + + warehouseMap.set(String(store.id), { + id: Number(store.id), + name: store.company_name, + }); + } + + const warehouses = Array.from(warehouseMap.values()); + if (warehouses.length === 0) { + return { + success: true, + code: 200, + data: { + warehouses: [], + }, + message: '无可绑定仓库', + }; + } + + const tempCode = crypto.randomBytes(16).toString('hex').toUpperCase(); + const tokenPayload = { + accountId, + code, + bindValue, + createdAt: new Date().toISOString(), + warehouses: warehouses.map(item => item.id), + }; + await redis.setex(`binding_token:${tempCode}`, 300, JSON.stringify(tokenPayload)); + + return { + success: true, + code: 200, + data: { + warehouses, + tempCode, + }, + message: '获取绑定信息成功', + }; + } + + async bindByTempCode(data = {}) { + const { ctx } = this; + const tempCode = String(data.temp_code || data.tempCode || '').trim(); + const printer = String(data.printer || data.workbench_name || data.workbenchName || '').trim(); + const warehouse = Number(data.warehouse || data.warehouse_id || data.warehouseId); + + if (!tempCode || !printer || !Number.isFinite(warehouse) || warehouse <= 0) { + return { + success: false, + code: 0, + data: null, + message: '参数缺失', + }; + } + + const redis = this.getPrinterRedis(); + const tokenText = await redis.get(`binding_token:${tempCode}`); + if (!tokenText) { + return { + success: false, + code: 0, + data: null, + message: '临时code无效或已过期', + }; + } + + let tokenData = null; + try { + tokenData = JSON.parse(tokenText); + } catch (_) { + tokenData = null; + } + + if (!tokenData || !tokenData.code || !Array.isArray(tokenData.warehouses)) { + return { + success: false, + code: 0, + data: null, + message: '临时code数据异常', + }; + } + + if (!tokenData.warehouses.includes(warehouse)) { + return { + success: false, + code: 0, + data: null, + message: '仓库无绑定权限', + }; + } + + const Store = ctx.model.Store; + const warehouseInfo = await Store.findOne({ + where: { + id: warehouse, + status: 1, + }, + raw: true, + }); + if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { + return { + success: false, + code: 0, + data: null, + message: '仓库id校验失败', + }; + } + + const PrintComputer = ctx.model.PrintComputer; + let computerId = null; + const existComputer = await PrintComputer.findOne({ + where: { + warehouse_id: warehouse, + name: printer, + }, + }); + if (existComputer) { + if (Number(existComputer.status) === 1) { + return { + success: false, + code: 0, + data: null, + message: '该仓库下打印台名称已存在且可用', + }; + } + computerId = existComputer.id; + } else { + const newComputer = await PrintComputer.create({ + warehouse_id: warehouse, + name: printer, + status: 0, + }); + computerId = newComputer.id; + } + + const bindValueObj = this.normalizeBindValue(tokenData.bindValue); + const printServiceUrl = ctx.app.config.printService.url; + let printServiceResult = null; + try { + const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { + method: 'POST', + contentType: 'json', + data: { + code: tokenData.code, + printer, + warehouse, + roomId: bindValueObj && bindValueObj.uniqueId ? bindValueObj.uniqueId : '', + computerId, + }, + dataType: 'json', + }); + printServiceResult = res.data; + } catch (err) { + printServiceResult = { success: false, error: '打印服务通讯失败' }; + } + + if (printServiceResult && printServiceResult.status === 'fail') { + return { + success: false, + code: 0, + data: { + printer, + warehouse, + printServiceResult, + }, + message: printServiceResult.message || '打印服务失败', + }; + } + + await redis.del(`binding_token:${tempCode}`); + + return { + success: true, + code: 200, + data: { + code: tokenData.code, + printer, + warehouse, + computerId, + printServiceResult, + }, + message: '绑定成功', + }; + } +} + +module.exports = PrintApiService; \ No newline at end of file diff --git a/app/service/main.js b/app/service/main.js index e0e518f..1644c26 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -337,13 +337,14 @@ class MainService extends Service { try { // 3. 验证JWT令牌 - const NewauthHeader = ''; const decoded = app.jwt.verify(token, app.config.jwt.secret); const now = Math.floor(Date.now() / 1000); const expiresIn = decoded.exp - now; if (expiresIn < 14399 && expiresIn > 0) { // 移除过期时间(exp)和签发时间(iat),保留其他payload - const { exp, iat, ...payload } = decoded; + const payload = { ...decoded }; + delete payload.exp; + delete payload.iat; // 生成新的 token,使用原来的有效时间配置 const newToken = app.jwt.sign( @@ -373,8 +374,7 @@ class MainService extends Service { return result; } - if (_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1) { - } else { + if (!(_noNeedAuth.indexOf('*') > -1 || _noNeedAuth.indexOf(actionName) > -1)) { if (user.auth_end && new Date(user.auth_end) < new Date()) { result.status = 406; result.message = '仓库有效期已过期'; @@ -434,21 +434,130 @@ class MainService extends Service { } /** - * 检查用户是否有API访问权限(只检查类型为api的权限) + * debug 模式下确保 API 权限存在,并绑定到 role_id=2 + * @param {string} apiPath - API路径 + * @param {Object} user - 当前用户 + * @return {Promise<{ensured:boolean, permissionId:number|null}>} 同步结果 + */ + async ensureApiPermissionInDebugMode(apiPath, user = null) { + const { ctx, app } = this; + if (app.config.debug !== true) { + return { + ensured: false, + permissionId: null, + }; + } + + const normalizedPath = String(apiPath || '').trim(); + if (!normalizedPath) { + return { + ensured: false, + permissionId: null, + }; + } + + const template = await ctx.model.Permission.findOne({ + where: { + type: 'api', + }, + attributes: [ + 'component', + 'name', + 'redirect', + 'meta_title', + 'meta_icon', + 'hidden', + 'always_show', + 'parent_id', + 'sort', + 'status', + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const [ permission, created ] = await ctx.model.Permission.findOrCreate({ + where: { + path: normalizedPath, + type: 'api', + }, + defaults: { + path: normalizedPath, + type: 'api', + component: template ? template.component : null, + name: template && template.name ? template.name : normalizedPath, + redirect: template ? template.redirect : null, + meta_title: template && template.meta_title ? template.meta_title : `API:${normalizedPath}`, + meta_icon: template ? template.meta_icon : null, + hidden: template ? template.hidden : 0, + always_show: template ? template.always_show : 0, + parent_id: template ? template.parent_id : null, + sort: template ? template.sort : 0, + status: 1, + }, + }); + + if (!permission || !permission.id) { + return { + ensured: false, + permissionId: null, + }; + } + + await ctx.service.systems.auth.rolePermission.bulkAssign(2, [ Number(permission.id) ]); + + // 仅在新建权限时清理当前用户缓存,避免继续使用旧权限快照。 + if (created && user && user.id) { + await ctx.service.systems.auth.user.clearUserCache(user.id); + } + + return { + ensured: true, + permissionId: permission.id, + }; + } + + async hasRole2(employeeId) { + const { ctx } = this; + if (!employeeId) { + return false; + } + + const link = await ctx.model.EmployeeRole.findOne({ + where: { + employee_id: employeeId, + role_id: 2, + }, + attributes: [ 'id' ], + raw: true, + }); + + return !!link; + } + + /** + * 检查用户是否有 API 访问权限(只检查 type=api) * @param {Object} user - 用户信息 * @param {string} apiPath - API路径 - * @return {Promise} + * @return {Promise} 是否有权限 */ async checkApiPermission(user, apiPath) { - const { ctx } = this; - console.log(user); try { // 方法1: 从用户的权限列表中检查(如果已经加载了权限) if (user.permissions && Array.isArray(user.permissions)) { // 用户权限列表中可能包含所有权限,需要过滤出api权限 console.log('user.permissions', user.permissions); - return user.permissions.includes(apiPath); + if (user.permissions.includes('*') || user.permissions.includes(apiPath)) { + return true; + } + + const ensureResult = await this.ensureApiPermissionInDebugMode(apiPath, user); + if (!ensureResult.ensured) { + return false; + } + + return await this.hasRole2(user.employees_id); } return false; } catch (error) { diff --git a/app/service/system.js b/app/service/system.js index 02fd9eb..3b1ccad 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -23,8 +23,6 @@ class systemService extends Service { // 检查服务是否存在 if (!systemMethods) { throw new Error(`服务 ${servicePath} 不存在`); - }else{ - console.log(`调用服务: ${servicePath}, 方法: ${actionName}`); } let serviceInstance = systemMethods; @@ -45,7 +43,6 @@ class systemService extends Service { const isLog = authPass.isLog; if (authPass.status == 200) { result.data = await serviceInstance[actionName](requestData); - console.log(result.data); result.status = 200; } else { diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 50557c4..8d5c965 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -54,58 +54,6 @@ class indexService extends MainService { const { ctx } = this; const { language = 'zh-CN' } = data || ctx.query; - try { - // 1. 直接查询表数据看看 - const allTranslations = await ctx.model.I18nTranslation.findAll({ - limit: 5, - raw: true, - }); - console.log('📊 数据库翻译表数据(前5条):', allTranslations); - - const allKeys = await ctx.model.I18nKey.findAll({ - limit: 5, - raw: true, - }); - console.log('📊 数据库键值表数据(前5条):', allKeys); - - // 2. 检查关联查询 - const testQuery = await ctx.model.I18nTranslation.findAll({ - include: [{ - model: ctx.model.I18nKey, - as: 'key', - required: false, // LEFT JOIN - }], - limit: 5, - raw: false, - }); - - console.log('🔍 关联查询结果:', testQuery.length); - testQuery.forEach((item, index) => { - console.log(`结果${index + 1}:`, { - id: item.id, - language: item.language, - translation: item.translation, - hasKey: !!item.key, - keyName: item.key?.key_name, - }); - }); - - // 3. 按语言查询 - const languageQuery = await ctx.model.I18nTranslation.findAll({ - where: { language }, - include: [{ - model: ctx.model.I18nKey, - as: 'key', - }], - raw: false, - }); - - console.log(`🌍 语言 ${language} 的翻译数量:`, languageQuery.length); - - } catch (error) { - console.error('❌ 数据库查询错误:', error); - ctx.logger.error('数据库查询错误:', error); - } try { // 1. 查询当前项目的所有翻译(默认项目为 'wms') const translations = await ctx.model.I18nTranslation.findAll({ diff --git a/app/service/systemMethods/setting/account.js b/app/service/systemMethods/setting/account.js index cf89f05..450d584 100644 --- a/app/service/systemMethods/setting/account.js +++ b/app/service/systemMethods/setting/account.js @@ -6,9 +6,9 @@ class accountService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update'; + const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat'; const _noNeedLog = '*'; - const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update'; + const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -29,7 +29,37 @@ class accountService extends MainService { * @param {*} data */ async list(data = {}) { - return this.callSystemAccount('list', data, '获取工号列表失败'); + const { service } = this; + try { + this.prepareWhereContext(data, { + specialFieldMap: { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }, + }); + const result = await service.systems.setting.account.list(data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || '获取工号列表失败', { + code: Number(error.code) || 500, + }); + } } /** @@ -55,6 +85,22 @@ class accountService extends MainService { async update(data = {}) { return this.callSystemAccount('update', data, '更新工号失败'); } + + /** + * 为其他账号获取微信绑定码。 + * @param {*} data + */ + async getBindWechatCode(data = {}) { + return this.callSystemAccount('getBindWechatCode', data, '获取账号绑定微信码失败'); + } + + /** + * 为其他账号解绑微信。 + * @param {*} data + */ + async unbindWechat(data = {}) { + return this.callSystemAccount('unbindWechat', data, '解绑账号微信失败'); + } } module.exports = accountService; \ No newline at end of file diff --git a/app/service/systemMethods/setting/permission.js b/app/service/systemMethods/setting/permission.js new file mode 100644 index 0000000..c6159ee --- /dev/null +++ b/app/service/systemMethods/setting/permission.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class permissionService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,add,delete,update'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,add,delete,update'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemPermission(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.permission[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 权限列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemPermission('list', data, '获取权限列表失败'); + } + + /** + * 新增权限。 + * @param {*} data + */ + async add(data = {}) { + return this.callSystemPermission('add', data, '新增权限失败'); + } + + /** + * 删除权限。 + * @param {*} data + */ + async delete(data = {}) { + return this.callSystemPermission('delete', data, '删除权限失败'); + } + + /** + * 更新权限。 + * @param {*} data + */ + async update(data = {}) { + return this.callSystemPermission('update', data, '更新权限失败'); + } +} + +module.exports = permissionService; diff --git a/app/service/systemMethods/setting/role.js b/app/service/systemMethods/setting/role.js new file mode 100644 index 0000000..5128999 --- /dev/null +++ b/app/service/systemMethods/setting/role.js @@ -0,0 +1,68 @@ +'use strict'; + +const MainService = require('../../main'); + +class roleService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,add,delete,update,permission'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,add,delete,update,permission'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemRole(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.setting.role[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 角色列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemRole('list', data, '获取角色列表失败'); + } + + /** + * 角色权限列表(兼容旧入口)。 + * @param {*} data + */ + async permission(data = {}) { + return this.callSystemRole('permission', data, '获取角色权限列表失败'); + } + + /** + * 新增角色。 + * @param {*} data + */ + async add(data = {}) { + return this.callSystemRole('add', data, '新增角色失败'); + } + + /** + * 删除角色。 + * @param {*} data + */ + async delete(data = {}) { + return this.callSystemRole('delete', data, '删除角色失败'); + } + + /** + * 更新角色。 + * @param {*} data + */ + async update(data = {}) { + return this.callSystemRole('update', data, '更新角色失败'); + } +} + +module.exports = roleService; diff --git a/app/service/systemMethods/setting/store_warehouse.js b/app/service/systemMethods/setting/store_warehouse.js new file mode 100644 index 0000000..c6442c6 --- /dev/null +++ b/app/service/systemMethods/setting/store_warehouse.js @@ -0,0 +1,60 @@ +'use strict'; + +const MainService = require('../../main'); + +class storeWarehouseService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,sign,unbind,rename'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,sign,unbind,rename'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + async callSystemStoreWarehouse(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.storeWarehouse[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + /** + * 仓库-货主签约列表。 + * @param {*} data + */ + async list(data = {}) { + return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); + } + + /** + * 建立/更新签约关系。 + * @param {*} data + */ + async sign(data = {}) { + return this.callSystemStoreWarehouse('sign', data, '签约失败'); + } + + /** + * 修改当前主体对签约对象的名称/备注。 + * @param {*} data + */ + async rename(data = {}) { + return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); + } + + /** + * 解除签约关系。 + * @param {*} data + */ + async unbind(data = {}) { + return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + } +} + +module.exports = storeWarehouseService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 839b8ee..ecb384b 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -10,9 +10,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving'; + const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct'; + const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct'; + const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -73,6 +73,32 @@ class configService extends MainService { return this.success('创建失败', result); } + /** + * 绑定收货单货主。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {number} data.store_id 货主ID + * @return {Promise} 统一成功包装响应 + */ + async bindStore(data) { + const { service } = this; + const result = await service.systems.storage.receiving.bindStore(data); + return this.success('ok', result); + } + + /** + * 绑定或改绑收货单明细商品。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 收货单明细ID + * @param {number} data.system_product_id 商品ID + * @return {Promise} 统一成功包装响应 + */ + async bindDetailProduct(data) { + const { service } = this; + const result = await service.systems.storage.receiving.bindDetailProduct(data); + return this.success('ok', result); + } + /** * 添加收货商品(当前依赖底层 addItem 实现)。 * @param {Object} data 请求体 diff --git a/app/service/systemMethods/storeWarehouse.js b/app/service/systemMethods/storeWarehouse.js new file mode 100644 index 0000000..761210a --- /dev/null +++ b/app/service/systemMethods/storeWarehouse.js @@ -0,0 +1,65 @@ +'use strict'; + +const MainService = require('../main'); + +class storeWarehouseAliasService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig'; + const _noNeedLog = '*'; + const _noNeedAuth = 'list,sign,unbind,rename,getPolicyConfig,savePolicyConfig,listQimenConfig,saveQimenConfig,deleteQimenConfig'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + this.store = this; + } + + async callSystemStoreWarehouse(methodName, data, defaultMessage) { + const { service } = this; + try { + const result = await service.systems.storeWarehouse[methodName](data); + return this.success('ok', result); + } catch (error) { + return this.fail(error.message || defaultMessage, { + code: Number(error.code) || 500, + }); + } + } + + async list(data = {}) { + return this.callSystemStoreWarehouse('list', data, '获取签约列表失败'); + } + + async sign(data = {}) { + return this.callSystemStoreWarehouse('sign', data, '签约失败'); + } + + async rename(data = {}) { + return this.callSystemStoreWarehouse('rename', data, '修改签约名称失败'); + } + + async unbind(data = {}) { + return this.callSystemStoreWarehouse('unbind', data, '解除签约失败'); + } + + async getPolicyConfig(data = {}) { + return this.callSystemStoreWarehouse('getPolicyConfig', data, '获取合约策略配置失败'); + } + + async savePolicyConfig(data = {}) { + return this.callSystemStoreWarehouse('savePolicyConfig', data, '保存合约策略配置失败'); + } + + async listQimenConfig(data = {}) { + return this.callSystemStoreWarehouse('listQimenConfig', data, '获取奇门接口配置列表失败'); + } + + async saveQimenConfig(data = {}) { + return this.callSystemStoreWarehouse('saveQimenConfig', data, '保存奇门接口配置失败'); + } + + async deleteQimenConfig(data = {}) { + return this.callSystemStoreWarehouse('deleteQimenConfig', data, '删除奇门接口配置失败'); + } +} + +module.exports = storeWarehouseAliasService; diff --git a/app/service/systemMethods/storeWarehouse/store.js b/app/service/systemMethods/storeWarehouse/store.js new file mode 100644 index 0000000..c012bd3 --- /dev/null +++ b/app/service/systemMethods/storeWarehouse/store.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = require('../storeWarehouse'); diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index efa3bc2..b7b901c 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -5,9 +5,9 @@ const MainService = require('../main'); class userService extends MainService { constructor(ctx) { super(ctx); - const _noNeedLogin = 'login,loginByCode,register'; + const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode'; const _noNeedRight = '*'; - const _noNeedLog = 'info,getBindWechatCode'; + const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode'; const _noNeedAuth = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -25,37 +25,16 @@ class userService extends MainService { async loginByCode(data) { const { service } = this; const code = typeof data?.code === 'string' ? data.code.trim() : ''; + console.log('code', data.code,code); if (!code) { - return this.fail('登录失败:缺少登录码 code', { + return this.fail('1111登录失败:缺少登录码 code', { success: false, data: null, code: 0, message: '缺少登录码 code', }); } - //code先进行base64解码,看是否为json以及json是否有uuid字段,如果有则继续执行否则返回报错 - let decoded; - try { - const buffer = Buffer.from(code, 'base64'); - const decodedStr = buffer.toString('utf-8'); - decoded = JSON.parse(decodedStr); - } catch (err) { - return this.fail('登录失败:无效的登录码格式', { - success: false, - data: null, - code: 0, - message: '无效的登录码格式', - }); - } - if (!decoded || typeof decoded !== 'object' || !decoded.uuid) { - return this.fail('登录失败:登录码缺少必要的uuid字段', { - success: false, - data: null, - code: 0, - message: '登录码缺少必要的uuid字段', - }); - } - const result = await service.systems.auth.user.loginByCode(code); + const result = await service.systems.auth.user.loginByYe4sCode(code); if (result.code) { return this.success('登录成功', result); } @@ -69,6 +48,14 @@ class userService extends MainService { } return this.fail('获取绑定微信码失败:' + result.message, result); } + async getLoginWechatCode(data) { + const { service } = this; + const result = await service.systems.auth.user.getLoginWechatCode(data); + if (result.code) { + return this.success('获取微信登录码成功', result); + } + return this.fail('获取微信登录码失败:' + result.message, result); + } async unbindWechat(data) { const { service } = this; const result = await service.systems.auth.user.unbindWechat(data); diff --git a/app/service/systems/account_platform.js b/app/service/systems/account_platform.js index c0e2627..bcab6b9 100644 --- a/app/service/systems/account_platform.js +++ b/app/service/systems/account_platform.js @@ -57,7 +57,7 @@ class AccountPlatformService extends Service { role_id: roleBinding ? roleBinding.role_id : null, role_name: role ? role.name : '', role_code: role ? role.code : '', - role_permissions: role ? role.permissions : [], + role_permissions: role ? this.ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions) : [], store_id: employee.store_id, store_name: store ? store.name : '', store_code: store ? store.code : '', diff --git a/app/service/systems/auth/role_permission.js b/app/service/systems/auth/role_permission.js index f8880a3..19274cf 100644 --- a/app/service/systems/auth/role_permission.js +++ b/app/service/systems/auth/role_permission.js @@ -3,107 +3,352 @@ const Service = require('egg').Service; class RolePermissionService extends Service { - async bulkAssign(roleId, permissionIds, options = {}) { - const { ctx } = this; + normalizePermissionSet(rawValue) { + if (rawValue === undefined || rawValue === null) { + return { allAccess: false, permissionIds: [] }; + } - if (!permissionIds || permissionIds.length === 0) { + if (Array.isArray(rawValue)) { + const normalizedItems = rawValue.map(item => typeof item === 'string' ? item.trim() : item); + if (normalizedItems.some(item => item === '*')) { + return { allAccess: true, permissionIds: [] }; + } + + const permissionIds = normalizedItems + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0) + .map(item => Math.floor(item)); + + return { + allAccess: false, + permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b), + }; + } + + if (typeof rawValue === 'number') { + return this.normalizePermissionSet([ rawValue ]); + } + + if (typeof rawValue === 'string') { + const trimmed = rawValue.trim(); + if (!trimmed) { + return { allAccess: false, permissionIds: [] }; + } + if (trimmed === '*') { + return { allAccess: true, permissionIds: [] }; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawValue) { + return this.normalizePermissionSet(parsed); + } + } catch (_) { + // ignore JSON parse failure and continue with string splitting. + } + + if (trimmed.includes(',')) { + return this.normalizePermissionSet(trimmed.split(',')); + } + + return this.normalizePermissionSet([ trimmed ]); + } + + return { allAccess: false, permissionIds: [] }; + } + + toApiPermissionIds(rawValue) { + const state = this.normalizePermissionSet(rawValue); + return state.allAccess ? [ '*' ] : state.permissionIds; + } + + serializePermissionSet(rawValue) { + const state = this.normalizePermissionSet(rawValue); + return state.allAccess ? '*' : JSON.stringify(state.permissionIds); + } + + async getPermissionIdsForRoles(roleIds, options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const normalizedRoleIds = Array.from(new Set((roleIds || []) + .map(roleId => Number(roleId)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0))); + + if (normalizedRoleIds.length === 0) { return []; } - const rolePermissions = permissionIds.map(permissionId => ({ - role_id: roleId, - permission_id: permissionId, - })); - - return await ctx.model.RolePermission.bulkCreate(rolePermissions, { - ignoreDuplicates: true, + const roleRows = await ctx.model.Role.findAll({ + where: { + id: { + [Op.in]: normalizedRoleIds, + }, + ...(options.includeRoleDisabled === true ? {} : { status: 1 }), + }, + attributes: [ 'id', 'permissions' ], + raw: true, transaction: options.transaction, }); - } - async clearRolePermissions(roleId, options = {}) { - const { ctx } = this; + if (!roleRows || roleRows.length === 0) { + return []; + } - return await ctx.model.RolePermission.destroy({ - where: { role_id: roleId }, - transaction: options.transaction, - }); - } + const directPermissionIds = []; + let allAccess = false; - async getRolePermissions(roleId, includePermissionDetails = false) { - const { ctx } = this; + for (const row of roleRows) { + const state = this.normalizePermissionSet(row.permissions); + if (state.allAccess) { + allAccess = true; + break; + } - const options = { - where: { role_id: roleId }, + if (state.permissionIds.length > 0) { + directPermissionIds.push(...state.permissionIds); + } + } + + const permissionWhere = { + status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1, }; - if (includePermissionDetails) { - options.include = [{ - model: ctx.model.Permission, - as: 'permission', - where: { status: 1 }, - required: false, - }]; + if (options.type) { + permissionWhere.type = options.type; } - return await ctx.model.RolePermission.findAll(options); - } + if (allAccess) { + const allPermissions = await ctx.model.Permission.findAll({ + where: permissionWhere, + attributes: [ 'id' ], + raw: true, + transaction: options.transaction, + }); - async hasPermission(roleId, permissionId) { - const { ctx } = this; + return Array.from(new Set(allPermissions + .map(item => Number(item.id)) + .filter(item => Number.isFinite(item) && item > 0))); + } - const rolePermission = await ctx.model.RolePermission.findOne({ + const permissionIds = Array.from(new Set(directPermissionIds + .filter(item => Number.isFinite(item) && item > 0))); + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ where: { - role_id: roleId, - permission_id: permissionId, + ...permissionWhere, + id: { + [Op.in]: permissionIds, + }, }, + attributes: [ 'id' ], + raw: true, + transaction: options.transaction, }); - return !!rolePermission; + return Array.from(new Set(permissions + .map(item => Number(item.id)) + .filter(item => Number.isFinite(item) && item > 0))); } - async assignPermissions(roleId, permissionIds, options = {}) { - await this.clearRolePermissions(roleId, options); - - if (permissionIds && permissionIds.length > 0) { - await this.bulkAssign(roleId, permissionIds, options); - } - - return true; - } - - async getPermissionTree(roleId, permissionType = null) { - const { ctx } = this; - - const rolePermissions = await this.getRolePermissions(roleId, true); - const permissionIds = rolePermissions - .map(rp => rp.permission && rp.permission.id) - .filter(Boolean); + async getPermissionPathsForRoles(roleIds, options = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const permissionIds = await this.getPermissionIdsForRoles(roleIds, { + includeDisabled: options.includeDisabled === true, + type: options.type || null, + includeRoleDisabled: options.includeRoleDisabled === true, + useLegacyFallback: options.useLegacyFallback !== false, + transaction: options.transaction, + }); if (permissionIds.length === 0) { return []; } const where = { - id: permissionIds, - status: 1, + id: { + [Op.in]: permissionIds, + }, + status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1, }; - if (permissionType) { - where.type = permissionType; + if (options.type) { + where.type = options.type; + } + + if (options.typeLike) { + where.type = { + [Op.like]: options.typeLike, + }; + } + + if (options.typeNotLike) { + where.type = { + [Op.notLike]: options.typeNotLike, + }; + } + + const rows = await ctx.model.Permission.findAll({ + where, + attributes: [ 'path' ], + order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + transaction: options.transaction, + }); + + return Array.from(new Set(rows + .map(item => item && item.path) + .filter(Boolean))); + } + + async bulkAssign(roleId, permissionIds, options = {}) { + const currentRole = await this.ctx.model.Role.findOne({ + where: { id: roleId }, + attributes: [ 'permissions' ], + raw: true, + transaction: options.transaction, + }); + + const currentState = this.normalizePermissionSet(currentRole && currentRole.permissions); + const incomingState = this.normalizePermissionSet(permissionIds); + const nextState = incomingState.allAccess || currentState.allAccess + ? '*' + : [ ...currentState.permissionIds, ...incomingState.permissionIds ]; + + await this.assignPermissions(roleId, nextState, options); + return this.toApiPermissionIds(nextState); + } + + async clearRolePermissions(roleId, options = {}) { + const { ctx } = this; + + return await ctx.model.Role.update({ + permissions: JSON.stringify([]), + updated_at: new Date(), + }, { + where: { id: roleId }, + transaction: options.transaction, + }); + } + + async getRolePermissions(roleId, includePermissionDetails = false) { + const { ctx } = this; + const permissionIds = await this.getPermissionIds(roleId); + if (permissionIds.length === 0) { + return []; + } + + if (!includePermissionDetails) { + return permissionIds.map(permissionId => ({ + role_id: Number(roleId), + permission_id: Number(permissionId), + })); + } + + const permissionRows = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + }); + const permissionMap = new Map(permissionRows.map(item => [ Number(item.id), item ])); + + return permissionIds.map(permissionId => ({ + role_id: Number(roleId), + permission_id: Number(permissionId), + permission: permissionMap.get(Number(permissionId)) || null, + })); + } + + async hasPermission(roleId, permissionId) { + const permissionIds = await this.getPermissionIds(roleId, { + includeDisabled: true, + }); + + return permissionIds.includes(Number(permissionId)); + } + + async assignPermissions(roleId, permissionIds, options = {}) { + const { ctx } = this; + + await ctx.model.Role.update({ + permissions: this.serializePermissionSet(permissionIds), + updated_at: new Date(), + }, { + where: { id: roleId }, + transaction: options.transaction, + }); + + return true; + } + + async getPermissionTree(roleId, permissionType = null) { + const { ctx } = this; + const permissionIds = await this.getPermissionIds(roleId, { + includeDisabled: false, + type: permissionType, + }); + + if (permissionIds.length === 0) { + return []; } const permissions = await ctx.model.Permission.findAll({ - where, + where: { + id: permissionIds, + status: 1, + ...(permissionType ? { type: permissionType } : {}), + }, order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], }); return ctx.model.Permission.buildPermissionTree(permissions); } - async getPermissionIds(roleId) { - const rolePermissions = await this.getRolePermissions(roleId, false); - return rolePermissions.map(rp => rp.permission_id); + async getPermissionIds(roleId, options = {}) { + return await this.getPermissionIdsForRoles([ roleId ], options); + } + + async removePermissionsFromAllRoles(permissionIds, options = {}) { + const { ctx } = this; + const removeSet = new Set((permissionIds || []) + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0)); + + if (removeSet.size === 0) { + return 0; + } + + const roleRows = await ctx.model.Role.findAll({ + attributes: [ 'id', 'permissions' ], + transaction: options.transaction, + }); + + let updatedCount = 0; + for (const role of roleRows) { + const state = this.normalizePermissionSet(role.permissions); + if (state.allAccess || state.permissionIds.length === 0) { + continue; + } + + const nextPermissionIds = state.permissionIds.filter(permissionId => !removeSet.has(Number(permissionId))); + if (nextPermissionIds.length === state.permissionIds.length) { + continue; + } + + await role.update({ + permissions: JSON.stringify(nextPermissionIds), + updated_at: new Date(), + }, { + transaction: options.transaction, + }); + updatedCount++; + } + + return updatedCount; } } diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index ea88807..4fa7d94 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -5,10 +5,15 @@ const crypto = require('node:crypto'); const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:'; const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:'; -const WECHAT_BIND_CACHE_TTL_SECONDS = 600; -const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000; +const WECHAT_BIND_SCAN_CACHE_PREFIX = 'user:wechat:bind:scan:'; +const WECHAT_BIND_CACHE_TTL_SECONDS = 60; +const WECHAT_BIND_SCAN_CACHE_TTL_SECONDS = 180; const WECHAT_BIND_EVENT_CHANNEL_PREFIX = 'user:wechat:bind:event:'; const WECHAT_BIND_LONG_POLL_TIMEOUT_MS = 60000; +const WECHAT_LOGIN_CLIENT_CACHE_PREFIX = 'user:wechat:login:client:'; +const WECHAT_LOGIN_CODE_CACHE_PREFIX = 'user:wechat:login:code:'; +const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:'; +const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60; class UserService extends Service { constructor(ctx) { @@ -33,45 +38,114 @@ class UserService extends Service { return `${WECHAT_BIND_CODE_CACHE_PREFIX}${code}`; } - createWechatBindCode() { - const payload = { - uuid: `${Date.now().toString(36)}-${crypto.randomBytes(8).toString('hex')}`, - }; - return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'); + getWechatBindScanCacheKey(code) { + return `${WECHAT_BIND_SCAN_CACHE_PREFIX}${code}`; + } + + getWechatLoginClientCacheKey(clientCode) { + return `${WECHAT_LOGIN_CLIENT_CACHE_PREFIX}${clientCode}`; + } + + getWechatLoginCodeCacheKey(code) { + return `${WECHAT_LOGIN_CODE_CACHE_PREFIX}${code}`; + } + + getWechatLoginEventChannel(clientCode) { + return `${WECHAT_LOGIN_EVENT_CHANNEL_PREFIX}${clientCode}`; + } + + createWechatBindCodeCandidate() { + const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + let code = ''; + for (let i = 0; i < 6; i++) { + const index = crypto.randomInt(0, charset.length); + code += charset[index]; + } + return code; + } + + async createUniqueSixCode(getCacheKey, maxAttempts = 200) { + for (let attempt = 0; attempt < maxAttempts; attempt++) { + const code = this.createWechatBindCodeCandidate(); + if (!this.parseWechatBindCode(code)) { + continue; + } + + const cacheKey = getCacheKey(code); + const existsState = await this.app.getCacheAsync(cacheKey); + if (!existsState) { + return code; + } + } + + throw new Error('生成登录码失败,请稍后重试'); + } + + async createWechatBindCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatBindCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginCodeCacheKey.bind(this), maxAttempts); + } + + async createWechatLoginClientCode(maxAttempts = 200) { + return await this.createUniqueSixCode(this.getWechatLoginClientCacheKey.bind(this), maxAttempts); } parseWechatBindCode(code) { - if (!code) { + const normalized = typeof code === 'string' ? code.trim().toUpperCase() : ''; + if (!normalized) { return null; } - try { - const decodedStr = Buffer.from(code, 'base64').toString('utf8'); - const parsed = JSON.parse(decodedStr); - if (!parsed || typeof parsed !== 'object' || !parsed.uuid) { - return null; - } - return parsed; - } catch (error) { + if (!/^[A-Z0-9]{6}$/.test(normalized)) { return null; } + if (!/[A-Z]/.test(normalized) || !/[0-9]/.test(normalized)) { + return null; + } + + return normalized; } formatBindWechatData(state, source = 'db') { - const nextCheckAt = Number(state.next_db_check_at || 0); + const expiresAt = Number(state.expires_at || 0); return { account_id: state.account_id, code: state.code || '', status: state.status || 'pending', is_bound: state.status === 'bound', updated_at: state.updated_at || new Date().toISOString(), - next_db_check_at: nextCheckAt, - next_poll_after_ms: Math.max(0, nextCheckAt - Date.now()), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + scanned_at: state.scanned_at || null, source, ye4s_user_id: state.ye4s_user_id || null, }; } + formatLoginWechatData(state, source = 'cache') { + const expiresAt = Number(state.expires_at || 0); + return { + client_code: state.client_code || '', + code: state.code || '', + status: state.status || 'pending', + updated_at: state.updated_at || new Date().toISOString(), + expires_at: expiresAt > 0 ? expiresAt : null, + expire_after_ms: expiresAt > 0 ? Math.max(0, expiresAt - Date.now()) : 0, + source, + }; + } + + getRemainingSecondsByExpiresAt(expiresAt, fallbackTtl = WECHAT_BIND_CACHE_TTL_SECONDS) { + const ts = Number(expiresAt); + if (!Number.isFinite(ts) || ts <= 0) { + return fallbackTtl; + } + return Math.max(1, Math.ceil((ts - Date.now()) / 1000)); + } + async setWechatBindCache(cacheKey, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { await this.app.setCacheAsync(cacheKey, state, ttl); } @@ -84,6 +158,38 @@ class UserService extends Service { await this.app.setCacheAsync(codeCacheKey, state, ttl); } + async setWechatBindScanCache(code, state, ttl = WECHAT_BIND_SCAN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + await this.app.setCacheAsync(scanCacheKey, state, ttl); + } + + async getWechatBindScanCache(code) { + if (!code) { + return null; + } + const scanCacheKey = this.getWechatBindScanCacheKey(code); + return await this.app.getCacheAsync(scanCacheKey); + } + + async setWechatLoginClientCache(clientCode, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!clientCode) { + return; + } + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + await this.app.setCacheAsync(clientCacheKey, state, ttl); + } + + async setWechatLoginCodeCache(code, state, ttl = WECHAT_LOGIN_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const codeCacheKey = this.getWechatLoginCodeCacheKey(code); + await this.app.setCacheAsync(codeCacheKey, state, ttl); + } + async findYe4sBindingByAccountId(accountId) { const { ctx } = this; const ye4sClient = ctx.app.mysql.get('ye4s'); @@ -105,27 +211,16 @@ class UserService extends Service { return `${WECHAT_BIND_EVENT_CHANNEL_PREFIX}${accountId}`; } - getWechatLongPollTimeoutMs(rawTimeoutMs) { - const timeoutMs = Number(rawTimeoutMs); - if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) { - return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; + getWechatLongPollTimeoutMs(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = Number(timeoutMs); + if (Number.isFinite(waitMs) && waitMs > 0) { + return Math.floor(waitMs); } - return Math.min(timeoutMs, WECHAT_BIND_LONG_POLL_TIMEOUT_MS); + return WECHAT_BIND_LONG_POLL_TIMEOUT_MS; } - shouldUseWechatBindLongPoll(data = {}, state = null) { - if (!state || state.status === 'bound') { - return false; - } - if (data.forceRefresh) { - return false; - } - if (data.isInit === true || data.init === true || data.firstLoad === true) { - return false; - } - - const explicitEnable = data.longPoll === true || data.waitForChange === true; - return explicitEnable; + shouldUseWechatBindLongPoll(data = {}) { + return data.longPoll === true; } async publishWechatBindEvent(accountId, payload = {}) { @@ -246,62 +341,99 @@ class UserService extends Service { }); } - async refreshWechatBindState(accountId, cachedState = null) { + async refreshWechatBindState(accountId, cachedState = null, options = {}) { const now = Date.now(); const cacheKey = this.getWechatBindCacheKey(accountId); + const forceNewCode = options.forceNewCode === true; const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); if (ye4sBinding) { - const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : ''; - const bindState = { + const boundState = { account_id: accountId, status: 'bound', - code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(), + code: '', updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: ye4sBinding.id || null, + expires_at: null, + scanned_at: null, }; - await Promise.all([ - this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); + await this.setWechatBindCache(cacheKey, boundState, WECHAT_BIND_CACHE_TTL_SECONDS); - const hasChanged = !cachedState || cachedState.status !== 'bound' || cachedState.code !== bindState.code; + const hasChanged = !cachedState || cachedState.status !== 'bound' || Number(cachedState.ye4s_user_id || 0) !== Number(boundState.ye4s_user_id || 0); if (hasChanged) { await this.publishWechatBindEvent(accountId, { status: 'bound', - code: bindState.code, + code: '', source: 'db', }); } return { - state: bindState, + state: boundState, source: 'db', message: '账号已绑定微信', }; } - const code = (cachedState && cachedState.code) || this.createWechatBindCode(); + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + let codeState = null; + if (!forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode)) { + const codeCacheKey = this.getWechatBindCodeCacheKey(cachedCode); + codeState = await this.app.getCacheAsync(codeCacheKey); + } + + const codeAccountId = Number(codeState && codeState.account_id); + const cachedExpiresAt = Number((codeState && codeState.expires_at) || (cachedState && cachedState.expires_at)); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(codeAccountId) && codeAccountId === accountId && (Number.isFinite(cachedExpiresAt) ? cachedExpiresAt > now : !!codeState); + + if (cachedCodeValid) { + const scanState = await this.getWechatBindScanCache(cachedCode); + const normalizedStatus = scanState ? 'scanned' : 'pending'; + const state = { + account_id: accountId, + status: normalizedStatus, + code: cachedCode, + updated_at: cachedState.updated_at || new Date().toISOString(), + ye4s_user_id: null, + expires_at: Number.isFinite(cachedExpiresAt) ? cachedExpiresAt : null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, + }; + return { + state, + source: 'cache', + message: normalizedStatus === 'scanned' ? '二维码已被扫码,请继续绑定' : '获取绑定码成功(缓存)', + }; + } + + const nextCode = await this.createWechatBindCode(); + const expiresAt = now + WECHAT_BIND_CACHE_TTL_SECONDS * 1000; const pendingState = { account_id: accountId, status: 'pending', - code, + code: nextCode, updated_at: new Date().toISOString(), - next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: null, + expires_at: expiresAt, + scanned_at: null, }; - await Promise.all([ + const tasks = [ this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); + this.setWechatBindCodeCache(nextCode, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatBindCodeCache(cachedCode, null, 1)); + tasks.push(this.setWechatBindScanCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); return { state: pendingState, - source: code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated', - message: '账号未绑定,已生成绑定码', + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? '长轮询超时,已刷新绑定码' : '账号未绑定,已生成绑定码', }; } @@ -361,75 +493,83 @@ class UserService extends Service { } /** - * 登录码登录:使用 ye4s_user.tmp_code 绑定的 wms_account_id 登录 - * @param {string} code 登录码(ye4s_user.tmp_code) + * 登录码登录:使用Ye4s登录码进行登录 + * @param {string} code 登录码(WECHAT_LOGIN_CODE) * @return {Object} 登录结果 */ - async loginByCode(code) { + async loginByYe4sCode(code) { const { ctx, app } = this; try { - const normalizedCode = typeof code === 'string' ? code.trim() : ''; - if (!normalizedCode) { + const rawCode = typeof code === 'string' ? code.trim() : ''; + if (!rawCode) { return { success: false, data: null, code: 0, - message: '缺少登录码 code', + message: '缺少或无效的登录码 code', + }; + } + + const candidateSet = new Set([ rawCode ]); + try { + const decoded = Buffer.from(rawCode, 'base64').toString('utf8').trim(); + if (decoded) { + candidateSet.add(decoded); + if (decoded.startsWith('{') && decoded.endsWith('}')) { + const parsed = JSON.parse(decoded); + const possibleCode = [ parsed && parsed.uuid, parsed && parsed.tmp_code, parsed && parsed.code ] + .map(item => (typeof item === 'string' ? item.trim() : '')) + .filter(Boolean); + for (const item of possibleCode) { + candidateSet.add(item); + } + } + } + } catch (decodeErr) { + // 非 base64/JSON 登录码时忽略解码失败,继续使用原始 code。 + } + + const codeCandidates = Array.from(candidateSet).filter(item => typeof item === 'string' && item.length > 0); + if (codeCandidates.length === 0) { + return { + success: false, + data: null, + code: 0, + message: '缺少或无效的登录码 code', }; } const ye4sClient = ctx.app.mysql.get('ye4s'); - const ye4sUser = await ye4sClient.get('ye4s_user', { - tmp_code: normalizedCode, + const rows = await ye4sClient.select('ye4s_user', { + where: { + tmp_code: codeCandidates, + }, + columns: [ 'id', 'tmp_code', 'wms_account_id' ], + orders: [[ 'id', 'DESC' ]], + limit: 1, }); - if (!ye4sUser) { + if (!rows || rows.length === 0) { return { success: false, data: null, code: 0, - message: '登录码不存在', + message: '登录码不存在或已过期', }; } - const wmsAccountId = Number(ye4sUser.wms_account_id); - if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { + const ye4sUserId = Number(rows[0].id); + if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { return { success: false, data: null, code: 0, - message: '该登录码未绑定WMS账号', + message: '登录码对应用户无效', }; } - const user = await ctx.model.Account.findOne({ - where: { id: wmsAccountId }, - }); - - if (!user) { - return { - success: false, - data: null, - code: 0, - message: '绑定的WMS账号不存在', - }; - } - - try { - this.checkUserStatus(user); - } catch (statusError) { - app.coreLogger.warn(`登录码登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); - return { - success: false, - data: null, - code: 0, - message: '绑定账号状态异常', - }; - } - - await this.updateLastLoginTime(user.id); - return this.buildLoginResult(user); + return await this.loginByYe4sUserId(ye4sUserId); } catch (error) { app.coreLogger.error(`登录码登录异常: ${error.message}`); return { @@ -441,28 +581,475 @@ class UserService extends Service { } } + async waitForLoginCodeRefresh(timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + await new Promise(resolve => { + setTimeout(resolve, waitMs); + }); + } + + isTransientWechatLoginError(error) { + if (!error) { + return false; + } + const code = typeof error.code === 'string' ? error.code : ''; + const message = typeof error.message === 'string' ? error.message.toLowerCase() : ''; + const transientCodes = new Set([ 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'PROTOCOL_CONNECTION_LOST', 'ECONNREFUSED' ]); + if (transientCodes.has(code)) { + return true; + } + return message.includes('econnreset') || message.includes('read econnreset') || message.includes('connection lost') || message.includes('timeout'); + } + + extractYe4sUserIdFromLoginEvent(eventData) { + if (!eventData) { + return null; + } + + if (typeof eventData === 'number' || typeof eventData === 'string') { + const id = Number(eventData); + return Number.isFinite(id) && id > 0 ? id : null; + } + + if (typeof eventData !== 'object') { + return null; + } + + const rawId = eventData.ye4s_user_id ?? eventData.ye4sUserId ?? eventData.user_id ?? eventData.userId ?? eventData.value; + const ye4sUserId = Number(rawId); + return Number.isFinite(ye4sUserId) && ye4sUserId > 0 ? ye4sUserId : null; + } + + async waitForWechatLoginEvent(clientCode, timeoutMs = WECHAT_BIND_LONG_POLL_TIMEOUT_MS) { + const { app } = this; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + const cacheRedis = app.redis && app.redis.get ? app.redis.get('cache') : null; + if (!cacheRedis || !normalizedClientCode || typeof cacheRedis.duplicate !== 'function') { + return { + timed_out: true, + reason: 'redis_not_available', + event: null, + }; + } + + const channel = this.getWechatLoginEventChannel(normalizedClientCode); + const waitMs = this.getWechatLongPollTimeoutMs(timeoutMs); + const subscriber = cacheRedis.duplicate(); + + return await new Promise(resolve => { + let settled = false; + let timer = null; + + const cleanup = () => { + subscriber.removeListener('message', onMessage); + subscriber.removeListener('error', onError); + Promise.resolve(subscriber.unsubscribe(channel)).catch(() => null).finally(() => { + if (typeof subscriber.quit === 'function') { + Promise.resolve(subscriber.quit()).catch(() => { + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + return; + } + if (typeof subscriber.disconnect === 'function') { + subscriber.disconnect(); + } + }); + }; + + const finalize = result => { + if (settled) { + return; + } + settled = true; + if (timer) { + clearTimeout(timer); + } + cleanup(); + resolve(result); + }; + + const onMessage = (messageChannel, message) => { + if (messageChannel !== channel) { + return; + } + let eventData = null; + try { + eventData = message ? JSON.parse(message) : null; + } catch (error) { + eventData = message; + } + const ye4sUserId = this.extractYe4sUserIdFromLoginEvent(eventData); + finalize({ + timed_out: false, + reason: 'event', + event: eventData, + ye4s_user_id: ye4sUserId, + }); + }; + + const onError = error => { + app.coreLogger.warn(`订阅微信登录事件失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_error', + event: null, + }); + }; + + timer = setTimeout(() => { + finalize({ + timed_out: true, + reason: 'timeout', + event: null, + }); + }, waitMs); + + subscriber.on('message', onMessage); + subscriber.on('error', onError); + + Promise.resolve(subscriber.subscribe(channel)).catch(error => { + app.coreLogger.warn(`订阅微信登录频道失败: ${error.message}`); + finalize({ + timed_out: true, + reason: 'subscribe_failed', + event: null, + }); + }); + }); + } + + async loginByYe4sUserId(ye4sUserId) { + const { ctx, app } = this; + + const normalizedYe4sUserId = Number(ye4sUserId); + if (!Number.isFinite(normalizedYe4sUserId) || normalizedYe4sUserId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '登录事件缺少有效的 ye4s_user_id', + }; + } + + const maxAttempts = 2; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { id: normalizedYe4sUserId }); + if (!ye4sUser) { + return { + success: false, + code: 0, + data: null, + message: 'ye4s 用户不存在', + }; + } + + const wmsAccountId = Number(ye4sUser.wms_account_id); + if (!Number.isFinite(wmsAccountId) || wmsAccountId <= 0) { + return { + success: false, + code: 0, + data: null, + message: '该 ye4s 用户未绑定WMS账号', + }; + } + + const user = await ctx.model.Account.findOne({ + where: { id: wmsAccountId }, + }); + + if (!user) { + return { + success: false, + code: 0, + data: null, + message: '绑定的WMS账号不存在', + }; + } + + try { + this.checkUserStatus(user); + } catch (statusError) { + app.coreLogger.warn(`微信事件登录失败: 账号状态异常 [${user.id}] - ${statusError.message}`); + return { + success: false, + code: 0, + data: null, + message: '绑定账号状态异常', + }; + } + + await this.updateLastLoginTime(user.id); + const loginResult = await this.buildLoginResult(user, { includeUser: false }); + return loginResult; + } catch (error) { + const isTransient = this.isTransientWechatLoginError(error); + if (isTransient && attempt < maxAttempts) { + app.coreLogger.warn(`微信事件登录异常,准备重试(${attempt}/${maxAttempts}): ${error.message}`); + await this.waitForLoginCodeRefresh(200); + continue; + } + + app.coreLogger.error(`微信事件登录异常: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + } + + return { + success: false, + code: 0, + data: null, + message: '登录失败,请稍后重试', + }; + } + + async tryBuildWechatLoginTokenFromState(clientCode, state) { + const eventYe4sUserId = this.extractYe4sUserIdFromLoginEvent(state); + if (!Number.isFinite(Number(eventYe4sUserId)) || Number(eventYe4sUserId) <= 0) { + return null; + } + + const loginResult = await this.loginByYe4sUserId(eventYe4sUserId); + if (!loginResult || !loginResult.success || !loginResult.data || !loginResult.data.token) { + return { + success: false, + code: 0, + data: null, + message: loginResult && loginResult.message ? loginResult.message : '登录事件处理失败', + }; + } + + const cleanupCode = state && typeof state.code === 'string' ? state.code.trim().toUpperCase() : ''; + await Promise.all([ + this.setWechatLoginClientCache(clientCode, null, 1), + cleanupCode ? this.setWechatLoginCodeCache(cleanupCode, null, 1) : Promise.resolve(), + ]); + + return { + success: true, + code: 200, + data: { + client_code: clientCode, + status: 'authorized', + source: 'event', + ye4s_user_id: Number(eventYe4sUserId), + loginToken: loginResult.data.token, + }, + message: '已收到登录事件并签发登录令牌', + }; + } + + async refreshWechatLoginState(clientCode, cachedState = null, options = {}) { + const now = Date.now(); + const forceNewCode = options.forceNewCode === true; + const normalizedClientCode = this.parseWechatBindCode(clientCode); + + if (!normalizedClientCode) { + throw new Error('无效的客户端编码格式'); + } + + const cachedCode = cachedState && typeof cachedState.code === 'string' ? cachedState.code.trim().toUpperCase() : ''; + const cachedExpiresAt = Number(cachedState && cachedState.expires_at); + const cachedCodeValid = !forceNewCode && cachedCode && this.parseWechatBindCode(cachedCode) && Number.isFinite(cachedExpiresAt) && cachedExpiresAt > now; + + if (cachedCodeValid) { + return { + state: { + client_code: normalizedClientCode, + code: cachedCode, + status: 'pending', + updated_at: cachedState.updated_at || new Date().toISOString(), + expires_at: cachedExpiresAt, + }, + source: 'cache', + message: `客户端编码 ${normalizedClientCode} 已命中缓存登录码`, + }; + } + + const nextCode = await this.createWechatLoginCode(); + const expiresAt = now + WECHAT_LOGIN_CACHE_TTL_SECONDS * 1000; + const loginState = { + client_code: normalizedClientCode, + code: nextCode, + status: 'pending', + updated_at: new Date().toISOString(), + expires_at: expiresAt, + }; + + const tasks = [ + this.setWechatLoginClientCache(normalizedClientCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + this.setWechatLoginCodeCache(nextCode, loginState, WECHAT_LOGIN_CACHE_TTL_SECONDS), + ]; + + if (cachedCode && cachedCode !== nextCode) { + tasks.push(this.setWechatLoginCodeCache(cachedCode, null, 1)); + } + + await Promise.all(tasks); + + return { + state: loginState, + source: forceNewCode ? 'refreshed' : 'generated', + message: forceNewCode ? + `客户端编码 ${normalizedClientCode} 长轮询结束,已刷新登录码` : + `客户端编码 ${normalizedClientCode} 已生成登录码`, + }; + } + + /** + * 获取微信扫码登录码 + * @param {Object} data + * @return {Object} + */ + async getLoginWechatCode(data = {}) { + const { app } = this; + try { + const rawClientCode = typeof data.clientCode === 'string' ? data.clientCode : (typeof data.client_code === 'string' ? data.client_code : ''); + const hasInputClientCode = !!rawClientCode && rawClientCode.trim().length > 0; + + let clientCode = ''; + let shouldWaitRefresh = false; + let cachedState = null; + + if (hasInputClientCode) { + const normalizedClientCode = this.parseWechatBindCode(rawClientCode); + if (!normalizedClientCode) { + return { + success: false, + code: 0, + data: null, + message: '无效的客户端编码格式', + }; + } + + const inputClientCacheKey = this.getWechatLoginClientCacheKey(normalizedClientCode); + try { + cachedState = await this.app.getCacheAsync(inputClientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + // 传入 clientCode 但缓存不存在时,按空值处理,重新分配新的客户端编码。 + if (cachedState) { + clientCode = normalizedClientCode; + shouldWaitRefresh = true; + } else { + clientCode = await this.createWechatLoginClientCode(); + } + } else { + clientCode = await this.createWechatLoginClientCode(); + } + + const clientCacheKey = this.getWechatLoginClientCacheKey(clientCode); + if (!cachedState) { + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + } + + // 若外部已将 ye4s_user_id 写入 clientCode 对应缓存,直接登录并返回,不再等待长轮询。 + if (hasInputClientCode && cachedState) { + const immediateLoginResult = await this.tryBuildWechatLoginTokenFromState(clientCode, cachedState); + if (immediateLoginResult && immediateLoginResult.success) { + return immediateLoginResult; + } + if (immediateLoginResult && immediateLoginResult.success === false) { + app.coreLogger.warn(`微信登录缓存态直登失败,继续轮询: ${immediateLoginResult.message}`); + } + } + + if (shouldWaitRefresh) { + const waitResult = await this.waitForWechatLoginEvent(clientCode, this.getWechatLongPollTimeoutMs()); + const eventYe4sUserId = Number(waitResult && waitResult.ye4s_user_id); + if (!waitResult.timed_out && Number.isFinite(eventYe4sUserId) && eventYe4sUserId > 0) { + const eventState = { + ...(cachedState || {}), + ye4s_user_id: eventYe4sUserId, + }; + const loginResponse = await this.tryBuildWechatLoginTokenFromState(clientCode, eventState); + if (loginResponse && loginResponse.success) { + return loginResponse; + } + app.coreLogger.warn(`微信事件登录未成功,降级为刷新登录码: ${loginResponse && loginResponse.message ? loginResponse.message : 'unknown_error'}`); + } + + try { + cachedState = await this.app.getCacheAsync(clientCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信登录码缓存失败: ${cacheErr.message}`); + } + + const refreshed = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: true, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(refreshed.state, refreshed.source), + message: refreshed.message, + }; + } + + const generated = await this.refreshWechatLoginState(clientCode, cachedState, { + forceNewCode: false, + }); + + return { + success: true, + code: 200, + data: this.formatLoginWechatData(generated.state, generated.source), + message: generated.message, + }; + } catch (error) { + app.coreLogger.error(`获取微信登录码失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取微信登录码失败,请稍后重试', + }; + } + } + /** * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) * @param {Object} data * @return {Object} */ async getBindWechatCode(data = {}) { + const accountId = this.getCurrentAccountId(); + return await this.getBindWechatCodeByAccountId(accountId, data, { + missingAccountMessage: '未识别到登录账号,无法生成绑定码', + }); + } + + async getBindWechatCodeByAccountId(accountId, data = {}, options = {}) { const { app } = this; try { - const accountId = this.getCurrentAccountId(); - if (!accountId) { + const normalizedAccountId = Number(accountId); + if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) { return { success: false, code: 0, data: null, - message: '未识别到登录账号,无法生成绑定码', + message: options.missingAccountMessage || '未识别到目标账号,无法生成绑定码', }; } - const cacheKey = this.getWechatBindCacheKey(accountId); - const forceRefresh = !!data.forceRefresh; - const now = Date.now(); - const waitTimeoutMs = this.getWechatLongPollTimeoutMs(data.waitTimeoutMs); + const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); + const useLongPoll = this.shouldUseWechatBindLongPoll(data); + const waitTimeoutMs = this.getWechatLongPollTimeoutMs(); let cachedState = null; try { @@ -471,57 +1058,44 @@ class UserService extends Service { app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); } - if (cachedState && !forceRefresh) { - const nextCheckAt = Number(cachedState.next_db_check_at || 0); - let refreshedState = null; - if (nextCheckAt <= now) { - refreshedState = await this.refreshWechatBindState(accountId, cachedState); - cachedState = refreshedState.state; - } - - if (this.shouldUseWechatBindLongPoll(data, cachedState)) { - const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs); - try { - cachedState = await this.app.getCacheAsync(cacheKey); - } catch (cacheErr) { - app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); - } - - const nextState = await this.refreshWechatBindState(accountId, cachedState); - const timeoutMessage = waitResult.timed_out ? '等待绑定状态变化超时,返回当前状态' : nextState.message; - - return { - success: true, - code: 200, - data: this.formatBindWechatData(nextState.state, nextState.source), - message: timeoutMessage, - }; - } - - if (refreshedState) { - return { - success: true, - code: 200, - data: this.formatBindWechatData(refreshedState.state, refreshedState.source), - message: refreshedState.message, - }; - } + const refreshed = await this.refreshWechatBindState(normalizedAccountId, cachedState, { + forceNewCode: false, + }); + if (refreshed.state.status === 'bound' || !useLongPoll) { return { success: true, code: 200, - data: this.formatBindWechatData(cachedState, 'cache'), - message: '获取绑定码成功(缓存)', + data: this.formatBindWechatData(refreshed.state, refreshed.source), + message: refreshed.message, }; } - const refreshed = await this.refreshWechatBindState(accountId, cachedState); + const waitResult = await this.waitForWechatBindEvent(normalizedAccountId, waitTimeoutMs); + try { + cachedState = await this.app.getCacheAsync(cacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); + } + + const nextState = await this.refreshWechatBindState(normalizedAccountId, cachedState, { + forceNewCode: waitResult.timed_out, + }); + + if (waitResult.timed_out) { + return { + success: true, + code: 200, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: '长轮询结束未检测到状态变化,已刷新绑定码', + }; + } return { success: true, code: 200, - data: this.formatBindWechatData(refreshed.state, refreshed.source), - message: refreshed.message, + data: this.formatBindWechatData(nextState.state, nextState.source), + message: nextState.message, }; } catch (error) { app.coreLogger.error(`获取微信绑定码失败: ${error.message}`); @@ -542,8 +1116,19 @@ class UserService extends Service { async getUserByTempCode(data = {}) { const { ctx, app } = this; try { - const code = typeof data.code === 'string' ? data.code.trim() : ''; - if (!code) { + const loadAccountRealName = async accountId => { + const account = await ctx.model.Account.findOne({ + where: { + id: accountId, + }, + attributes: [ 'id', 'real_name' ], + raw: true, + }); + return account && account.real_name ? account.real_name : ''; + }; + + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; + if (!rawCode) { return { success: false, code: 0, @@ -552,7 +1137,8 @@ class UserService extends Service { }; } - if (!this.parseWechatBindCode(code)) { + const code = this.parseWechatBindCode(rawCode); + if (!code) { return { success: false, code: 0, @@ -570,65 +1156,60 @@ class UserService extends Service { } const cachedAccountId = Number(codeState && codeState.account_id); - if (Number.isFinite(cachedAccountId) && cachedAccountId > 0) { + if (!Number.isFinite(cachedAccountId) || cachedAccountId <= 0) { return { - success: true, - code: 200, - data: { - account_id: cachedAccountId, - code, - status: codeState.status || 'pending', - source: 'cache', - updated_at: codeState.updated_at || new Date().toISOString(), - }, - message: '获取账号成功', + success: false, + code: 0, + data: null, + message: '绑定码不存在或已过期', }; } - const ye4sClient = ctx.app.mysql.get('ye4s'); - const ye4sUser = await ye4sClient.get('ye4s_user', { - tmp_code: code, + const realName = await loadAccountRealName(cachedAccountId); + const scanState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: new Date().toISOString(), + source: 'gateway-scan', + }; + + const codeExpiresAt = Number(codeState && codeState.expires_at); + const scannedBindState = { + account_id: cachedAccountId, + code, + status: 'scanned', + scanned_at: scanState.scanned_at, + updated_at: scanState.scanned_at, + ye4s_user_id: null, + expires_at: Number.isFinite(codeExpiresAt) ? codeExpiresAt : null, + }; + const bindCacheTtl = this.getRemainingSecondsByExpiresAt(codeExpiresAt, WECHAT_BIND_CACHE_TTL_SECONDS); + + await Promise.all([ + this.setWechatBindScanCache(code, scanState, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), + this.setWechatBindCache(this.getWechatBindCacheKey(cachedAccountId), scannedBindState, bindCacheTtl), + ]); + await this.publishWechatBindEvent(cachedAccountId, { + status: 'scanned', + code, + scanned_at: scanState.scanned_at, + source: 'gateway-scan', }); - const wmsAccountId = Number(ye4sUser && ye4sUser.wms_account_id); - if (Number.isFinite(wmsAccountId) && wmsAccountId > 0) { - const boundState = { - account_id: wmsAccountId, - status: 'bound', - code, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: ye4sUser.id || null, - }; - await Promise.all([ - this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), - this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), - ]); - await this.publishWechatBindEvent(wmsAccountId, { - status: 'bound', - code, - source: 'api', - }); - - return { - success: true, - code: 200, - data: { - account_id: wmsAccountId, - code, - status: 'bound', - source: 'db', - updated_at: boundState.updated_at, - }, - message: '获取账号成功', - }; - } - return { - success: false, - code: 0, - data: null, - message: '绑定码不存在或已过期', + success: true, + code: 200, + data: { + account_id: cachedAccountId, + real_name: realName, + code, + status: 'scanned', + source: 'scan-cache', + scanned_at: scanState.scanned_at, + updated_at: codeState && codeState.updated_at ? codeState.updated_at : scanState.scanned_at, + }, + message: '扫码状态已记录', }; } catch (error) { app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`); @@ -649,11 +1230,11 @@ class UserService extends Service { async bindAccountByTempCode(data = {}) { const { ctx, app } = this; try { - const code = typeof data.code === 'string' ? data.code.trim() : ''; + const rawCode = typeof data.code === 'string' ? data.code.trim() : ''; const rawYe4sUserId = data.ye4s_user_id ?? data.ye4sUserId; const ye4sUserId = Number(rawYe4sUserId); - if (!code) { + if (!rawCode) { return { success: false, code: 0, @@ -662,7 +1243,8 @@ class UserService extends Service { }; } - if (!this.parseWechatBindCode(code)) { + const code = this.parseWechatBindCode(rawCode); + if (!code) { return { success: false, code: 0, @@ -680,23 +1262,14 @@ class UserService extends Service { }; } - const userResult = await this.getUserByTempCode({ code }); - if (!userResult || !userResult.success) { - return { - success: false, - code: 0, - data: null, - message: userResult && userResult.message ? userResult.message : '绑定码不存在或已过期', - }; - } - - const accountId = Number(userResult.data && userResult.data.account_id); + const scanState = await this.getWechatBindScanCache(code); + const accountId = Number(scanState && scanState.account_id); if (!Number.isFinite(accountId) || accountId <= 0) { return { success: false, code: 0, data: null, - message: '绑定码未匹配到有效账号', + message: '未检测到扫码记录或扫码状态已过期,请重新扫码', }; } @@ -714,26 +1287,32 @@ class UserService extends Service { const updateRet = await ye4sClient.update('ye4s_user', { id: ye4sUserId, wms_account_id: accountId, - tmp_code: code, }); const boundState = { account_id: accountId, status: 'bound', - code, + code: '', updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, ye4s_user_id: ye4sUserId, + expires_at: null, + scanned_at: scanState && scanState.scanned_at ? scanState.scanned_at : null, }; await Promise.all([ - this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS), this.setWechatBindCache(this.getWechatBindCacheKey(accountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS), + this.setWechatBindCodeCache(code, null, 1), + this.setWechatBindScanCache(code, { + ...scanState, + status: 'bound', + ye4s_user_id: ye4sUserId, + bound_at: boundState.updated_at, + }, WECHAT_BIND_SCAN_CACHE_TTL_SECONDS), ]); await this.publishWechatBindEvent(accountId, { status: 'bound', - code, + code: '', source: 'gateway-bind', }); @@ -767,22 +1346,29 @@ class UserService extends Service { * @return {Object} */ async unbindWechat() { + const accountId = this.getCurrentAccountId(); + return await this.unbindWechatByAccountId(accountId, { + missingAccountMessage: '未识别到登录账号,无法解绑', + }); + } + + async unbindWechatByAccountId(accountId, options = {}) { const { ctx, app } = this; try { - const accountId = this.getCurrentAccountId(); - if (!accountId) { + const normalizedAccountId = Number(accountId); + if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) { return { success: false, code: 0, data: null, - message: '未识别到登录账号,无法解绑', + message: options.missingAccountMessage || '未识别到目标账号,无法解绑', }; } const ye4sClient = ctx.app.mysql.get('ye4s'); const bindRows = await ye4sClient.select('ye4s_user', { where: { - wms_account_id: accountId, + wms_account_id: normalizedAccountId, }, columns: [ 'id', 'tmp_code', 'wms_account_id' ], orders: [[ 'id', 'desc' ]], @@ -791,17 +1377,6 @@ class UserService extends Service { let affectedRows = 0; for (const row of bindRows) { - const rowCode = typeof row.tmp_code === 'string' ? row.tmp_code.trim() : ''; - if (rowCode) { - await this.setWechatBindCodeCache(rowCode, { - account_id: accountId, - status: 'unbound', - code: rowCode, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: row.id || null, - }, WECHAT_BIND_CACHE_TTL_SECONDS); - } try { const ret = await ye4sClient.update('ye4s_user', { id: row.id, @@ -809,7 +1384,6 @@ class UserService extends Service { }); affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); } catch (err) { - // 兼容不允许 NULL 的旧表结构 const ret = await ye4sClient.update('ye4s_user', { id: row.id, wms_account_id: 0, @@ -818,20 +1392,9 @@ class UserService extends Service { } } - const cacheKey = this.getWechatBindCacheKey(accountId); - const cachedState = await this.app.getCacheAsync(cacheKey); - if (cachedState && cachedState.code) { - await this.setWechatBindCodeCache(cachedState.code, { - account_id: accountId, - status: 'unbound', - code: cachedState.code, - updated_at: new Date().toISOString(), - next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, - ye4s_user_id: cachedState.ye4s_user_id || null, - }, WECHAT_BIND_CACHE_TTL_SECONDS); - } + const cacheKey = this.getWechatBindCacheKey(normalizedAccountId); await this.setWechatBindCache(cacheKey, null, 1); - await this.publishWechatBindEvent(accountId, { + await this.publishWechatBindEvent(normalizedAccountId, { status: 'unbound', source: 'unbind', }); @@ -840,7 +1403,7 @@ class UserService extends Service { success: true, code: 200, data: { - account_id: accountId, + account_id: normalizedAccountId, status: 'unbound', matched_rows: bindRows.length, affected_rows: affectedRows, @@ -1426,20 +1989,10 @@ class UserService extends Service { return []; } - // 2. 获取角色的权限 - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { - role_id: { - [Op.in]: roleIds, - }, - }, - raw: true, + // 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表) + const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, }); - if (!rolePermissions || rolePermissions.length === 0) { - return []; - } - - const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ]; if (permissionIds.length === 0) { return []; } @@ -1512,20 +2065,10 @@ class UserService extends Service { return []; } - // 2. 获取角色的权限 - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { - role_id: { - [Op.in]: roleIds, - }, - }, - raw: true, + // 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表) + const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, }); - if (!rolePermissions || rolePermissions.length === 0) { - return []; - } - - const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ]; if (permissionIds.length === 0) { return []; } diff --git a/app/service/systems/excel.js b/app/service/systems/excel.js new file mode 100644 index 0000000..88f1adf --- /dev/null +++ b/app/service/systems/excel.js @@ -0,0 +1,744 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { Readable } = require('stream'); +const Service = require('egg').Service; +const XLSX = require('xlsx'); +const ExcelJS = require('exceljs'); + +const CONTENT_TYPE_MAP = { + xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + xls: 'application/vnd.ms-excel', + csv: 'text/csv; charset=utf-8', +}; + +class ExcelService extends Service { + getContentType(bookType = 'xlsx') { + const normalizedType = String(bookType || 'xlsx').replace('.', '').toLowerCase(); + return CONTENT_TYPE_MAP[normalizedType] || CONTENT_TYPE_MAP.xlsx; + } + + sanitizeSheetName(name, index = 1) { + const safeName = String(name || `Sheet${index}`) + .replace(/[\\/?*\[\]:]/g, '_') + .trim(); + + return (safeName || `Sheet${index}`).slice(0, 31); + } + + normalizeHeaders(headerRow = []) { + const usedNames = new Set(); + + return headerRow.map((value, index) => { + const baseName = String(value == null ? '' : value).trim() || `column_${index + 1}`; + let uniqueName = baseName; + let suffix = 2; + + while (usedNames.has(uniqueName)) { + uniqueName = `${baseName}_${suffix}`; + suffix += 1; + } + + usedNames.add(uniqueName); + return uniqueName; + }); + } + + normalizeColumns(columns = []) { + if (!Array.isArray(columns)) { + return []; + } + + return columns + .map(column => { + if (!column) { + return null; + } + + const key = column.key || column.field || column.dataIndex || column.prop; + const header = column.header || column.title || column.label || key; + + if (!key && !header) { + return null; + } + + return { + key: key || header, + header: header || key, + width: Number(column.width || column.wch || 0) || undefined, + }; + }) + .filter(Boolean); + } + + prepareSheetData(sheetConfig = {}) { + const { + rows = [], + columns = [], + header = [], + skipHeader = false, + widths = [], + } = sheetConfig; + + const normalizedColumns = this.normalizeColumns(columns); + let aoaData = []; + + if (normalizedColumns.length > 0) { + const headerRow = normalizedColumns.map(column => column.header); + const columnKeys = normalizedColumns.map(column => column.key); + const bodyRows = Array.isArray(rows) + ? rows.map(row => { + if (Array.isArray(row)) { + return row; + } + + return columnKeys.map(key => (row && typeof row === 'object' ? row[key] : '')); + }) + : []; + aoaData = skipHeader ? bodyRows : [ headerRow, ...bodyRows ]; + } else if (Array.isArray(rows) && rows.length > 0 && Array.isArray(rows[0])) { + aoaData = Array.isArray(header) && header.length > 0 && !skipHeader + ? [ header, ...rows ] + : rows; + } else if (Array.isArray(rows) && rows.length > 0) { + const derivedHeaders = Array.isArray(header) && header.length > 0 + ? header + : Object.keys(rows[0] || {}); + const bodyRows = rows.map(row => derivedHeaders.map(key => (row && typeof row === 'object' ? row[key] : ''))); + aoaData = skipHeader ? bodyRows : [ derivedHeaders, ...bodyRows ]; + } else { + aoaData = Array.isArray(header) && header.length > 0 ? [ header ] : []; + } + + const resolvedWidths = Array.isArray(widths) && widths.length > 0 + ? widths.map(item => (typeof item === 'number' ? { wch: item } : item)) + : normalizedColumns + .filter(column => column.width) + .map(column => ({ wch: column.width })); + + return { + normalizedColumns, + aoaData, + resolvedWidths, + skipHeader, + originalRows: Array.isArray(rows) ? rows : [], + }; + } + + hasEmbeddedImages(options = {}) { + return Array.isArray(options.sheets) + && options.sheets.some(sheet => Array.isArray(sheet && sheet.embeddedImages) && sheet.embeddedImages.length > 0); + } + + buildWorksheet(sheetConfig = {}) { + const { + merges = [], + } = sheetConfig; + const { + aoaData, + resolvedWidths, + } = this.prepareSheetData(sheetConfig); + + const worksheet = XLSX.utils.aoa_to_sheet(aoaData); + + if (resolvedWidths.length > 0) { + worksheet['!cols'] = resolvedWidths; + } + + if (Array.isArray(merges) && merges.length > 0) { + worksheet['!merges'] = merges; + } + + return worksheet; + } + + buildWorkbook(options = {}) { + const { sheets = [], props = {} } = options; + + if (!Array.isArray(sheets) || sheets.length === 0) { + throw new Error('至少需要一个 sheet 配置'); + } + + const workbook = XLSX.utils.book_new(); + workbook.Props = { + Company: 'WMS', + CreatedDate: new Date(), + ...props, + }; + + sheets.forEach((sheetConfig, index) => { + const worksheet = this.buildWorksheet(sheetConfig || {}); + const sheetName = this.sanitizeSheetName(sheetConfig && sheetConfig.name, index + 1); + XLSX.utils.book_append_sheet(workbook, worksheet, sheetName); + }); + + return workbook; + } + + async buildExcelJsWorkbook(options = {}) { + const { sheets = [], props = {} } = options; + + if (!Array.isArray(sheets) || sheets.length === 0) { + throw new Error('至少需要一个 sheet 配置'); + } + + const workbook = new ExcelJS.Workbook(); + workbook.creator = props.author || 'WMS'; + workbook.company = props.company || 'WMS'; + workbook.created = props.createdAt || new Date(); + workbook.modified = new Date(); + + for (let index = 0; index < sheets.length; index += 1) { + const sheetConfig = sheets[index] || {}; + const sheetName = this.sanitizeSheetName(sheetConfig.name, index + 1); + const worksheet = workbook.addWorksheet(sheetName); + const { + merges = [], + embeddedImages = [], + styledRows = [], + } = sheetConfig; + const { + normalizedColumns, + aoaData, + resolvedWidths, + skipHeader, + originalRows, + } = this.prepareSheetData(sheetConfig); + + if (normalizedColumns.length > 0 && originalRows.length > 0 && !Array.isArray(originalRows[0])) { + if (skipHeader) { + aoaData.forEach(row => worksheet.addRow(row)); + } else { + worksheet.columns = normalizedColumns.map(column => ({ + header: column.header, + key: column.key, + width: column.width || 18, + })); + originalRows.forEach(row => worksheet.addRow(row || {})); + } + } else if (normalizedColumns.length > 0 && originalRows.length === 0 && !skipHeader) { + worksheet.columns = normalizedColumns.map(column => ({ + header: column.header, + key: column.key, + width: column.width || 18, + })); + } else { + aoaData.forEach(row => worksheet.addRow(row)); + } + + if (resolvedWidths.length > 0) { + resolvedWidths.forEach((column, columnIndex) => { + const width = Number(column && column.wch) || Number(column && column.width) || undefined; + if (width) { + worksheet.getColumn(columnIndex + 1).width = width; + } + }); + } + + if (Array.isArray(merges) && merges.length > 0) { + merges.forEach(merge => { + if (!merge) { + return; + } + + if (typeof merge === 'string') { + worksheet.mergeCells(merge); + return; + } + + if (merge.s && merge.e) { + worksheet.mergeCells(merge.s.r + 1, merge.s.c + 1, merge.e.r + 1, merge.e.c + 1); + } + }); + } + + if (Array.isArray(styledRows) && styledRows.length > 0) { + this.applyStyledRows(worksheet, styledRows); + } + + if (Array.isArray(embeddedImages) && embeddedImages.length > 0) { + await this.addEmbeddedImages(workbook, worksheet, embeddedImages); + } + } + + return workbook; + } + + inferImageExtension(imageConfig = {}, contentType = '') { + const preferred = String(imageConfig.extension || '').replace('.', '').toLowerCase(); + if (preferred) { + return preferred === 'jpg' ? 'jpeg' : preferred; + } + + const fileSource = imageConfig.url || imageConfig.filePath || imageConfig.filename || ''; + const ext = path.extname(String(fileSource)).replace('.', '').toLowerCase(); + if (ext) { + return ext === 'jpg' ? 'jpeg' : ext; + } + + if (contentType.includes('png')) return 'png'; + if (contentType.includes('gif')) return 'gif'; + if (contentType.includes('jpg') || contentType.includes('jpeg')) return 'jpeg'; + if (contentType.includes('webp')) return 'png'; + + return 'png'; + } + + async resolveImageSource(imageConfig = {}) { + try { + if (imageConfig.buffer) { + return { + buffer: Buffer.isBuffer(imageConfig.buffer) ? imageConfig.buffer : Buffer.from(imageConfig.buffer), + extension: this.inferImageExtension(imageConfig), + }; + } + + if (imageConfig.dataUrl) { + const match = String(imageConfig.dataUrl).match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/); + if (match) { + return { + buffer: Buffer.from(match[2], 'base64'), + extension: this.inferImageExtension(imageConfig, match[1]), + }; + } + } + + if (imageConfig.base64) { + return { + buffer: Buffer.from(String(imageConfig.base64), 'base64'), + extension: this.inferImageExtension(imageConfig), + }; + } + + if (imageConfig.filePath) { + const resolvedFilePath = path.resolve(String(imageConfig.filePath)); + const buffer = await fs.promises.readFile(resolvedFilePath); + return { + buffer, + extension: this.inferImageExtension({ ...imageConfig, filePath: resolvedFilePath }), + }; + } + + if (imageConfig.url) { + const imageUrl = String(imageConfig.url); + const dataUrlMatch = imageUrl.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,(.+)$/); + if (dataUrlMatch) { + return { + buffer: Buffer.from(dataUrlMatch[2], 'base64'), + extension: this.inferImageExtension(imageConfig, dataUrlMatch[1]), + }; + } + + if (this.ctx && typeof this.ctx.curl === 'function') { + const response = await this.ctx.curl(imageUrl, { + method: 'GET', + timeout: 15000, + followRedirect: true, + }); + const contentType = String((response.headers && (response.headers['content-type'] || response.headers['Content-Type'])) || '').toLowerCase(); + const buffer = Buffer.isBuffer(response.data) ? response.data : Buffer.from(response.data || ''); + + if (buffer.length > 0) { + return { + buffer, + extension: this.inferImageExtension(imageConfig, contentType), + }; + } + } else if (typeof fetch === 'function' && /^https?:\/\//i.test(imageUrl)) { + const response = await fetch(imageUrl); + if (response && response.ok) { + const contentType = String(response.headers.get('content-type') || '').toLowerCase(); + const arrayBuffer = await response.arrayBuffer(); + const buffer = Buffer.from(arrayBuffer); + + if (buffer.length > 0) { + return { + buffer, + extension: this.inferImageExtension(imageConfig, contentType), + }; + } + } + } + } + } catch (error) { + if (this.ctx && this.ctx.logger && typeof this.ctx.logger.warn === 'function') { + this.ctx.logger.warn('[ExcelService.resolveImageSource] 图片加载失败: %s', error.message); + } + } + + return null; + } + + mergeCellStyle(baseStyle = {}, patchStyle = {}) { + const mergedStyle = { + ...baseStyle, + ...patchStyle, + }; + + if (baseStyle.font || patchStyle.font) { + mergedStyle.font = { + ...(baseStyle.font || {}), + ...(patchStyle.font || {}), + }; + } + + if (baseStyle.alignment || patchStyle.alignment) { + mergedStyle.alignment = { + ...(baseStyle.alignment || {}), + ...(patchStyle.alignment || {}), + }; + } + + if (baseStyle.protection || patchStyle.protection) { + mergedStyle.protection = { + ...(baseStyle.protection || {}), + ...(patchStyle.protection || {}), + }; + } + + if (patchStyle.fill) { + mergedStyle.fill = patchStyle.fill; + } + + if (patchStyle.border) { + mergedStyle.border = patchStyle.border; + } + + if (patchStyle.numFmt) { + mergedStyle.numFmt = patchStyle.numFmt; + } + + return mergedStyle; + } + + applyStyledRows(worksheet, styledRows = []) { + styledRows.forEach(item => { + if (!item) { + return; + } + + const rowNumber = Math.max(Number(item.row || 1), 1); + const fromCol = Math.max(Number(item.fromCol || 1), 1); + const toCol = Math.max(Number(item.toCol || fromCol), fromCol); + const row = worksheet.getRow(rowNumber); + + if (item.height) { + row.height = item.height; + } + + if (item.style && typeof item.style === 'object') { + for (let col = fromCol; col <= toCol; col += 1) { + const cell = worksheet.getCell(rowNumber, col); + cell.style = this.mergeCellStyle(cell.style || {}, item.style); + } + } + }); + } + + async addEmbeddedImages(workbook, worksheet, embeddedImages = []) { + for (const imageConfig of embeddedImages) { + if (!imageConfig) { + continue; + } + + const row = Math.max(Number(imageConfig.row || 1), 1); + const col = Math.max(Number(imageConfig.col || imageConfig.column || 1), 1); + const width = Math.max(Number(imageConfig.width || 120), 40); + const height = Math.max(Number(imageConfig.height || 120), 40); + const cell = worksheet.getCell(row, col); + const fallbackText = imageConfig.fallbackText || imageConfig.url || ''; + const resolvedImage = await this.resolveImageSource(imageConfig); + + if (!resolvedImage || !resolvedImage.buffer || resolvedImage.buffer.length === 0) { + if (fallbackText) { + cell.value = fallbackText; + } + continue; + } + + const imageId = workbook.addImage({ + buffer: resolvedImage.buffer, + extension: resolvedImage.extension, + }); + + worksheet.addImage(imageId, { + tl: { col: col - 1 + 0.05, row: row - 1 + 0.05 }, + ext: { width, height }, + editAs: 'oneCell', + }); + + if (fallbackText) { + cell.value = fallbackText; + } + + worksheet.getRow(row).height = Math.max(Number(worksheet.getRow(row).height || 20), Math.ceil(height * 0.75)); + worksheet.getColumn(col).width = Math.max(Number(worksheet.getColumn(col).width || 10), Math.ceil(width / 7)); + } + } + + async generateBuffer(options = {}) { + const bookType = String(options.bookType || 'xlsx').replace('.', '').toLowerCase(); + + const shouldUseExcelJs = this.hasEmbeddedImages(options) + || (Array.isArray(options.sheets) + && options.sheets.some(sheet => sheet && (sheet.forceExcelJs || (Array.isArray(sheet.styledRows) && sheet.styledRows.length > 0)))); + + if (shouldUseExcelJs) { + if (bookType !== 'xlsx') { + throw new Error('带图片的 Excel 仅支持 xlsx 格式'); + } + + const workbook = await this.buildExcelJsWorkbook({ + ...options, + bookType, + }); + const buffer = await workbook.xlsx.writeBuffer(); + return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer); + } + + const workbook = this.buildWorkbook(options); + const buffer = XLSX.write(workbook, { + type: 'buffer', + bookType, + compression: true, + }); + + return Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer); + } + + async writeFile(filePath, options = {}) { + if (!filePath) { + throw new Error('filePath 不能为空'); + } + + const resolvedFilePath = path.resolve(filePath); + const ext = path.extname(resolvedFilePath).replace('.', '').toLowerCase() || options.bookType || 'xlsx'; + const buffer = await this.generateBuffer({ + ...options, + bookType: ext, + }); + + await fs.promises.mkdir(path.dirname(resolvedFilePath), { recursive: true }); + await fs.promises.writeFile(resolvedFilePath, buffer); + + return { + filePath: resolvedFilePath, + size: buffer.length, + bookType: ext, + }; + } + + sanitizeFilename(filename = 'export.xlsx', fallbackExt = '.xlsx') { + const normalizedName = String(filename || '').trim() || `export${fallbackExt}`; + const rawExt = path.extname(normalizedName); + const ext = rawExt || fallbackExt; + const baseName = path.basename(normalizedName, rawExt); + const safeBaseName = String(baseName || 'export') + .replace(/[<>:"/\\|?*]/g, '_') + .replace(/\s+/g, '_') + .replace(/_+/g, '_') + .replace(/^_+|_+$/g, '') + .slice(0, 120) || 'export'; + + return `${safeBaseName}${ext}`; + } + + buildUploadKey(filename, options = {}) { + if (options.key) { + return String(options.key) + .replace(/\\/g, '/') + .replace(/^\/+/, '') + .replace(/\/+/g, '/'); + } + + const now = new Date(); + const dateFolder = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; + const normalizedDir = String(options.dir || 'exports/excel') + .replace(/\\/g, '/') + .replace(/^\/+|\/+$/g, ''); + + return path.posix.join(normalizedDir, dateFolder, filename); + } + + async generateAndUpload({ + filename = 'export.xlsx', + dir = 'exports/excel', + key, + category = 'document', + saveRecord = false, + businessType, + businessId, + uploaderDept, + expireTime, + expireDays, + onProgress, + ...options + } = {}) { + const uploadService = this.ctx && this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.upload; + + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用,无法上传 Excel 文件'); + } + + const bookType = String(options.bookType || path.extname(filename).replace('.', '') || 'xlsx').toLowerCase(); + const safeFilename = this.sanitizeFilename(filename, `.${bookType}`); + const contentType = this.getContentType(bookType); + const buffer = await this.generateBuffer({ + ...options, + bookType, + }); + const uploadKey = this.buildUploadKey(safeFilename, { dir, key }); + const uploadStream = Readable.from(buffer); + + uploadStream.filename = safeFilename; + uploadStream.mimeType = contentType; + uploadStream.fileSize = buffer.length; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category, + mimetype: 'xls,xlsx,csv', + onProgress, + }); + + let fileRecord = null; + if ((saveRecord || businessType || businessId) && typeof uploadService.uploadSuccessNotify === 'function') { + const recordResult = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: safeFilename, + name: safeFilename, + fileSize: buffer.length, + size: buffer.length, + fileType: category, + mimeType: contentType, + type: category, + category, + businessType, + businessId, + uploaderDept, + expireTime, + expireDays, + }); + + fileRecord = recordResult && (recordResult.data || recordResult); + } + + return { + filename: safeFilename, + fileKey: uploadResult.fileName, + size: buffer.length, + contentType, + ...uploadResult, + fileRecord, + }; + } + + async sendFile({ ctx = this.ctx, filename = 'export.xlsx', ...options } = {}) { + if (!ctx) { + throw new Error('ctx 不存在,无法输出下载响应'); + } + + const ext = path.extname(filename).replace('.', '').toLowerCase() || options.bookType || 'xlsx'; + const buffer = await this.generateBuffer({ + ...options, + bookType: ext, + }); + + ctx.set('Content-Type', this.getContentType(ext)); + ctx.set('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`); + ctx.body = buffer; + + return { + filename, + size: buffer.length, + contentType: this.getContentType(ext), + }; + } + + async parseBuffer(buffer, options = {}) { + if (!buffer) { + throw new Error('buffer 不能为空'); + } + + const workbook = XLSX.read(buffer, { + type: 'buffer', + raw: false, + cellDates: true, + ...options.readOptions, + }); + + return this.workbookToJSON(workbook, options); + } + + async parseFile(filePath, options = {}) { + if (!filePath) { + throw new Error('filePath 不能为空'); + } + + const resolvedFilePath = path.resolve(filePath); + const buffer = await fs.promises.readFile(resolvedFilePath); + const result = await this.parseBuffer(buffer, options); + + return { + filePath: resolvedFilePath, + ...result, + }; + } + + workbookToJSON(workbook, options = {}) { + const { + headerRow = 1, + defval = '', + blankrows = false, + includeRawRows = false, + sheetNames, + } = options; + + const startIndex = Math.max(Number(headerRow) || 1, 1) - 1; + const selectedSheetNames = Array.isArray(sheetNames) && sheetNames.length > 0 + ? workbook.SheetNames.filter(name => sheetNames.includes(name)) + : workbook.SheetNames; + + const sheets = selectedSheetNames.map(name => { + const sheet = workbook.Sheets[name]; + const rawRows = XLSX.utils.sheet_to_json(sheet, { + header: 1, + raw: false, + defval, + blankrows, + }); + const headerValues = Array.isArray(rawRows[startIndex]) ? rawRows[startIndex] : []; + const headers = this.normalizeHeaders(headerValues); + const dataRows = rawRows.slice(startIndex + 1) + .filter(row => blankrows || row.some(cell => String(cell == null ? '' : cell).trim() !== '')); + const rows = dataRows.map(row => { + return headers.reduce((result, headerName, columnIndex) => { + result[headerName] = row[columnIndex] == null ? defval : row[columnIndex]; + return result; + }, {}); + }); + + const sheetResult = { + name, + headers, + rows, + rowCount: rows.length, + }; + + if (includeRawRows) { + sheetResult.rawRows = rawRows; + } + + return sheetResult; + }); + + return { + sheetNames: selectedSheetNames, + sheets, + }; + } +} + +module.exports = ExcelService; diff --git a/app/service/systems/setting/account.js b/app/service/systems/setting/account.js index 27f273e..6cd2314 100644 --- a/app/service/systems/setting/account.js +++ b/app/service/systems/setting/account.js @@ -1,10 +1,34 @@ 'use strict'; const Service = require('egg').Service; +const { parseWhereConditions } = require('../../../lib/query_condition_parser'); const RESERVED_EMPLOYEE_NAME = '测试工号保留'; class SettingAccountService extends Service { + getListWhereSpecialFieldMap() { + return { + employee_id: { + field: 'id', + }, + account_id: { + field: 'account_id', + }, + username: { + field: '$account.username$', + }, + phone: { + field: '$account.phone$', + }, + email: { + field: '$account.email$', + }, + quickWhere: { + bucket: 'quick', + }, + }; + } + createError(message, code = 500) { const error = new Error(message); error.code = code; @@ -27,6 +51,14 @@ class SettingAccountService extends Service { return employeeId; } + normalizeAccountId(value, fieldName = 'account_id') { + const accountId = Number(value); + if (!Number.isFinite(accountId) || accountId <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return accountId; + } + getWmsClient() { return this.ctx.app.mysql.get('wms'); } @@ -127,10 +159,304 @@ class SettingAccountService extends Service { return Number(currentRole.role_id); } - async formatEmployeeRow(employee) { - const account = await this.getWmsClient().get('wms_account', { - id: employee.account_id, + normalizeRoleIds(ids) { + if (!Array.isArray(ids) || ids.length === 0) { + throw this.createError('ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of ids) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + return Array.from(new Set(roleIds)); + } + + flattenRoleTreeMeta(roleNodes, idCollector = [], parentMap = new Map()) { + if (!Array.isArray(roleNodes) || roleNodes.length === 0) { + return { idCollector, parentMap }; + } + + for (const node of roleNodes) { + const roleId = Number(node && node.role_id); + if (Number.isFinite(roleId) && roleId > 0) { + idCollector.push(roleId); + parentMap.set(roleId, Number(node && node.pid ? node.pid : 0)); + } + + const children = Array.isArray(node && node.children) ? node.children : []; + this.flattenRoleTreeMeta(children, idCollector, parentMap); + } + + return { idCollector, parentMap }; + } + + async resolveAssignableRoleScope() { + const roleResult = await this.ctx.service.systems.setting.role.list({ + includeDisabled: false, + includeSystem: false, }); + + const roleTree = roleResult && roleResult.data && Array.isArray(roleResult.data.roles) + ? roleResult.data.roles + : []; + const { idCollector, parentMap } = this.flattenRoleTreeMeta(roleTree, [], new Map()); + return { + roleIdSet: new Set(idCollector), + parentMap, + }; + } + + pruneDescendantRoleIds(roleIds, parentMap) { + const selected = new Set(roleIds); + const pruned = []; + + for (const roleId of roleIds) { + let current = roleId; + let keep = true; + const visited = new Set(); + + while (true) { + const parentId = Number(parentMap.get(current) || 0); + if (!Number.isFinite(parentId) || parentId <= 0) { + break; + } + if (visited.has(parentId)) { + break; + } + visited.add(parentId); + + if (selected.has(parentId)) { + keep = false; + break; + } + + current = parentId; + } + + if (keep) { + pruned.push(roleId); + } + } + + return Array.from(new Set(pruned)); + } + + async resolveRequestedRoleIds(data = {}, options = {}) { + const required = options.required === true; + const hasIds = Object.prototype.hasOwnProperty.call(data, 'ids'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'role_ids'); + + if (!hasIds && !hasRoleIds) { + if (required) { + throw this.createError('ids 参数不能为空', 400); + } + return null; + } + + const rawRoleIds = hasIds ? data.ids : data.role_ids; + const roleIds = this.normalizeRoleIds(rawRoleIds); + + const { roleIdSet, parentMap } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + throw this.createError('当前角色范围为空,无法分配角色', 400); + } + + const outOfScopeIds = roleIds.filter(roleId => !roleIdSet.has(roleId)); + if (outOfScopeIds.length > 0) { + throw this.createError(`包含超出当前角色范围的角色ID:${outOfScopeIds.join(',')}`, 400); + } + + return this.pruneDescendantRoleIds(roleIds, parentMap); + } + + async replaceEmployeeRoles(employeeId, roleIds) { + const { ctx } = this; + + await ctx.model.EmployeeRole.destroy({ + where: { + employee_id: employeeId, + }, + }); + + const rows = roleIds.map(roleId => ({ + employee_id: employeeId, + role_id: roleId, + })); + + await ctx.model.EmployeeRole.bulkCreate(rows); + } + + async buildEmployeeRoleGroupMap(employeeIds) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + if (!Array.isArray(employeeIds) || employeeIds.length === 0) { + return new Map(); + } + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeIds, + }, + attributes: [ 'employee_id', 'role_id' ], + raw: true, + }); + + if (employeeRoleRows.length === 0) { + return new Map(); + } + + const roleIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0))); + + const roleRows = await ctx.model.Role.findAll({ + where: { + id: { + [Op.in]: roleIds, + }, + }, + attributes: [ 'id', 'role_code', 'role_name', 'pid', 'status' ], + raw: true, + }); + const roleMap = new Map(roleRows.map(role => [ Number(role.id), role ])); + + const employeeRoleMap = new Map(); + for (const row of employeeRoleRows) { + const employeeId = Number(row.employee_id); + const roleId = Number(row.role_id); + if (!Number.isFinite(employeeId) || employeeId <= 0 || !Number.isFinite(roleId) || roleId <= 0) { + continue; + } + + const role = roleMap.get(roleId); + if (!employeeRoleMap.has(employeeId)) { + employeeRoleMap.set(employeeId, { + role_ids: [], + roles: [], + }); + } + + const target = employeeRoleMap.get(employeeId); + target.role_ids.push(roleId); + target.roles.push({ + role_id: roleId, + role_code: role && role.role_code ? role.role_code : '', + role_name: role && role.role_name ? role.role_name : '', + pid: role ? Number(role.pid || 0) : 0, + status: role ? Number(role.status) : 0, + }); + } + + for (const value of employeeRoleMap.values()) { + value.role_ids = Array.from(new Set(value.role_ids)).sort((a, b) => a - b); + value.roles.sort((a, b) => a.role_id - b.role_id); + } + + return employeeRoleMap; + } + + async buildWechatBindingMap(accountIds) { + if (!Array.isArray(accountIds) || accountIds.length === 0) { + return new Map(); + } + + const normalizedAccountIds = Array.from(new Set(accountIds + .map(accountId => Number(accountId)) + .filter(accountId => Number.isFinite(accountId) && accountId > 0))); + if (normalizedAccountIds.length === 0) { + return new Map(); + } + + const ye4sClient = this.ctx.app.mysql.get('ye4s'); + const bindingRows = await ye4sClient.select('ye4s_user', { + where: { + wms_account_id: normalizedAccountIds, + }, + columns: [ 'id', 'wms_account_id' ], + orders: [[ 'id', 'DESC' ]], + }); + + const bindingMap = new Map(); + for (const row of bindingRows) { + const accountId = Number(row && row.wms_account_id); + const ye4sUserId = Number(row && row.id); + if (!Number.isFinite(accountId) || accountId <= 0 || !Number.isFinite(ye4sUserId) || ye4sUserId <= 0) { + continue; + } + if (!bindingMap.has(accountId)) { + bindingMap.set(accountId, { + is_wechat_bound: true, + ye4s_user_id: ye4sUserId, + }); + } + } + + return bindingMap; + } + + async getOperableEmployeeByAccountId(accountId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const normalizedAccountId = this.normalizeAccountId(accountId, 'user_id'); + const where = { + account_id: normalizedAccountId, + store_id: storeId, + }; + + if (options.includeDisabled !== true) { + where.status = 1; + } + + const employees = await ctx.model.AccountStoreEmployee.findAll({ + where, + order: [[ 'status', 'DESC' ], [ 'id', 'ASC' ]], + }); + + if (employees.length === 0) { + throw this.createError('目标账号不存在或无权限操作', 404); + } + + const { roleIdSet } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + throw this.createError('当前角色范围为空,无法操作目标账号', 400); + } + + const employeeIds = employees + .map(item => Number(item.id)) + .filter(employeeId => Number.isFinite(employeeId) && employeeId > 0); + const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds); + + for (const employee of employees) { + const employeeId = Number(employee.id); + const roleGroup = employeeRoleMap.get(employeeId) || { + role_ids: [], + roles: [], + }; + const hasOutOfScopeRole = roleGroup.role_ids + .some(roleId => !roleIdSet.has(Number(roleId))); + if (!hasOutOfScopeRole) { + return { + employee, + roleGroup, + }; + } + } + + throw this.createError('目标账号超出当前操作范围', 403); + } + + async formatEmployeeRow(employee, options = {}) { + let account = options.account || null; + if (!account) { + account = await this.getWmsClient().get('wms_account', { + id: employee.account_id, + }); + } const avatar = await this.getAvatarMeta(employee.id); return { @@ -150,28 +476,130 @@ class SettingAccountService extends Service { } async list(data = {}) { - const { ctx } = this; + const { ctx, app } = this; + const { Op } = app.Sequelize; const storeId = this.getCurrentStoreId(); - const statusFilter = data.includeDisabled === true - ? undefined - : (data.status === 0 || data.status === '0' ? 0 : 1); + const currentEmployeeId = this.getCurrentEmployeeId(); + const normalizedWhere = ctx.where && typeof ctx.where === 'object' + ? { ...ctx.where } + : (data.where && typeof data.where === 'object' ? { ...data.where } : {}); + let parsedResult = ctx.whereParsed; + if (!parsedResult || !Array.isArray(parsedResult.dynamicConditions)) { + const parsed = parseWhereConditions({ + where: normalizedWhere, + app, + specialFieldMap: this.getListWhereSpecialFieldMap(), + }); + if (!parsed.ok) { + throw this.createError(`where 参数解析失败: ${parsed.reason}`, 400); + } + parsedResult = parsed.result; + } - const where = { - store_id: storeId, - }; - if (statusFilter === 0 || statusFilter === 1) { - where.status = statusFilter; + const andConditions = [ + { + store_id: storeId, + }, + ]; + const hasWhereStatus = Object.prototype.hasOwnProperty.call(normalizedWhere, 'status'); + if (!hasWhereStatus) { + const statusFilter = data.includeDisabled === true + ? undefined + : (data.status === 0 || data.status === '0' ? 0 : 1); + if (statusFilter === 0 || statusFilter === 1) { + andConditions.push({ status: statusFilter }); + } + } + + const dynamicConditions = parsedResult.dynamicConditions || []; + if (dynamicConditions.length > 0) { + andConditions.push({ [Op.and]: dynamicConditions }); + } + + const quickWhereInput = (parsedResult.rawConditionsByField && parsedResult.rawConditionsByField.quickWhere) + || normalizedWhere.quickWhere + || null; + const quickWhereValue = quickWhereInput && typeof quickWhereInput === 'object' + ? quickWhereInput.value + : quickWhereInput; + if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { + const keyword = String(quickWhereValue).trim(); + andConditions.push({ + [Op.or]: [ + { real_name: { [Op.like]: `%${keyword}%` } }, + { '$account.username$': { [Op.like]: `%${keyword}%` } }, + { '$account.phone$': { [Op.like]: `%${keyword}%` } }, + { '$account.email$': { [Op.like]: `%${keyword}%` } }, + ], + }); } const employees = await ctx.model.AccountStoreEmployee.findAll({ - where, + where: { + [Op.and]: andConditions, + }, + include: [ + { + model: ctx.model.Account, + as: 'account', + attributes: [ 'id', 'username', 'phone', 'email', 'real_name' ], + required: false, + }, + ], order: [[ 'created_at', 'DESC' ], [ 'id', 'DESC' ]], }); + const { roleIdSet } = await this.resolveAssignableRoleScope(); + if (roleIdSet.size === 0) { + return { + code: 200, + data: [], + }; + } + + const employeeIds = employees + .map(employee => Number(employee.id)) + .filter(employeeId => Number.isFinite(employeeId) && employeeId > 0); + const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds); + const accountIds = employees + .map(employee => Number(employee.account_id)) + .filter(accountId => Number.isFinite(accountId) && accountId > 0); + const wechatBindingMap = await this.buildWechatBindingMap(accountIds); + const list = []; for (const employee of employees) { - list.push(await this.formatEmployeeRow(employee)); + const employeeId = Number(employee.id); + if (currentEmployeeId && employeeId === currentEmployeeId) { + continue; + } + + const roleGroup = employeeRoleMap.get(employeeId) || { + role_ids: [], + roles: [], + }; + + // 只展示当前账号可分配范围内的工号,避免越权操作。 + const hasOutOfScopeRole = roleGroup.role_ids + .some(roleId => !roleIdSet.has(Number(roleId))); + if (hasOutOfScopeRole) { + continue; + } + + const wechatBinding = wechatBindingMap.get(Number(employee.account_id)) || { + is_wechat_bound: false, + ye4s_user_id: null, + }; + + list.push({ + ...await this.formatEmployeeRow(employee, { + account: employee.account, + }), + is_wechat_bound: wechatBinding.is_wechat_bound, + ye4s_user_id: wechatBinding.ye4s_user_id, + role_ids: roleGroup.role_ids, + roles: roleGroup.roles, + }); } return { @@ -205,7 +633,9 @@ class SettingAccountService extends Service { throw this.createError(`新增工号禁止直接使用保留名称 ${RESERVED_EMPLOYEE_NAME}`, 400); } - const roleId = await this.resolveRoleId(data); + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); let account = await this.findRawAccountByPhone(phone); if (account && Number(account.status) !== 1) { @@ -256,13 +686,15 @@ class SettingAccountService extends Service { throw this.createError('该手机号已绑定当前主体工号', 409); } - const { employee, employeeRole } = await service.systems.store.ensureEmployeeRoleBinding({ + const { employee } = await service.systems.store.ensureEmployeeRoleBinding({ accountId: Number(account.id), storeId, - roleId, + roleId: roleIds[0], realName, }); + await this.replaceEmployeeRoles(Number(employee.id), roleIds); + await service.systems.auth.user.clearUserCache(Number(account.id)); const formatted = await this.formatEmployeeRow(employee); @@ -270,7 +702,8 @@ class SettingAccountService extends Service { code: 200, data: { ...formatted, - role_id: Number(employeeRole.role_id), + role_id: roleIds[0], + role_ids: roleIds, is_new_account: createdAccountId > 0, }, }; @@ -348,14 +781,15 @@ class SettingAccountService extends Service { const employeeId = Number(data.employee_id || data.id || 0); const hasRealName = Object.prototype.hasOwnProperty.call(data, 'real_name') || Object.prototype.hasOwnProperty.call(data, 'realName'); const hasFileId = Object.prototype.hasOwnProperty.call(data, 'file_id') || Object.prototype.hasOwnProperty.call(data, 'avatar_file_id') || Object.prototype.hasOwnProperty.call(data, 'fileId'); + const hasRoleIds = Object.prototype.hasOwnProperty.call(data, 'ids') || Object.prototype.hasOwnProperty.call(data, 'role_ids'); const realName = this.normalizeName(data.real_name || data.realName); const fileId = Number(data.file_id || data.avatar_file_id || data.fileId || 0); if (!employeeId) { throw this.createError('employee_id 参数不能为空', 400); } - if (!hasRealName && !hasFileId) { - throw this.createError('至少需要更新 real_name 或 file_id', 400); + if (!hasRoleIds) { + throw this.createError('ids 参数不能为空', 400); } if (hasRealName && !realName) { throw this.createError('real_name 参数不能为空', 400); @@ -405,14 +839,64 @@ class SettingAccountService extends Service { }); } + const roleIds = await this.resolveRequestedRoleIds(data, { + required: true, + }); + await this.replaceEmployeeRoles(employeeId, roleIds); + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); const refreshed = await ctx.model.AccountStoreEmployee.findByPk(employeeId); + const roleRows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employeeId, + }, + attributes: [ 'role_id' ], + order: [[ 'role_id', 'ASC' ]], + raw: true, + }); + const boundRoleIds = roleRows + .map(item => Number(item.role_id)) + .filter(roleId => Number.isFinite(roleId) && roleId > 0); + return { code: 200, - data: await this.formatEmployeeRow(refreshed), + data: { + ...await this.formatEmployeeRow(refreshed), + role_ids: Array.from(new Set(boundRoleIds)), + }, }; } + + async getBindWechatCode(data = {}) { + const { service } = this.ctx; + const accountId = data.user_id || data.account_id || data.id; + const { employee } = await this.getOperableEmployeeByAccountId(accountId); + const result = await service.systems.auth.user.getBindWechatCodeByAccountId(Number(employee.account_id), data, { + missingAccountMessage: '目标账号不存在,无法生成绑定码', + }); + + if (!result || Number(result.code) !== 200) { + throw this.createError(result && result.message ? result.message : '获取绑定码失败', Number(result && result.code) || 500); + } + + return result; + } + + async unbindWechat(data = {}) { + const { service } = this.ctx; + const accountId = data.user_id || data.account_id || data.id; + const { employee } = await this.getOperableEmployeeByAccountId(accountId); + const result = await service.systems.auth.user.unbindWechatByAccountId(Number(employee.account_id), { + missingAccountMessage: '目标账号不存在,无法解绑', + }); + + if (!result || Number(result.code) !== 200) { + throw this.createError(result && result.message ? result.message : '解绑失败', Number(result && result.code) || 500); + } + + return result; + } } module.exports = SettingAccountService; diff --git a/app/service/systems/setting/permission.js b/app/service/systems/setting/permission.js new file mode 100644 index 0000000..1b5d03b --- /dev/null +++ b/app/service/systems/setting/permission.js @@ -0,0 +1,651 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingPermissionService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作权限', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getRole(roleId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + + const role = await ctx.model.Role.findOne({ + where: { + id: roleId, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + }); + + if (!role) { + throw this.createError('角色不存在或无权限操作', 404); + } + + return role; + } + + async getPermission(permissionId, includeDisabled = false) { + const { ctx } = this; + const where = { id: permissionId }; + if (!includeDisabled) { + where.status = 1; + } + + const permission = await ctx.model.Permission.findOne({ where }); + if (!permission) { + throw this.createError('权限不存在或已禁用', 404); + } + + return permission; + } + + normalizePermissionType(type) { + const normalized = typeof type === 'string' ? type.trim() : ''; + if (!normalized) { + throw this.createError('type 参数不能为空', 400); + } + + const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block' ]); + if (!allowedTypes.has(normalized)) { + throw this.createError('type 参数不合法', 400); + } + return normalized; + } + + normalizeOptionalString(value, fieldName, maxLength = 255) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (!normalized) { + return ''; + } + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeParentId(value) { + if (value === undefined || value === null || value === '' || Number(value) === 0) { + return null; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError('parent_id 参数不合法', 400); + } + return num; + } + + normalizeSort(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError('sort 参数不合法', 400); + } + return Math.floor(num); + } + + normalizeStatus(value) { + if (value === undefined || value === null || value === '') { + return 1; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError('status 参数不合法', 400); + } + + normalizeBooleanFlag(value, fieldName) { + if (value === undefined || value === null || value === '') { + return 0; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + async getAvailablePermissionIdSet({ includeDisabled = false } = {}) { + const rows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type: null, + keyword: '', + }); + return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0)); + } + + async ensureParentPermissionExists(parentId) { + if (!parentId) { + return; + } + + await this.getPermission(parentId, false); + } + + async ensurePermissionsExist(permissionIds) { + const { ctx } = this; + + const targetRows = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id' ], + raw: true, + }); + if (targetRows.length !== permissionIds.length) { + const found = new Set(targetRows.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(Number(id))); + throw this.createError(`权限不存在:${missing.join(',')}`, 404); + } + + return targetRows; + } + + normalizePermissionIds(inputPermissionIds) { + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组', 400); + } + permissionIds.push(normalized); + } + + return Array.from(new Set(permissionIds)); + } + + normalizeIds(inputIds, fieldName = 'ids') { + if (!Array.isArray(inputIds)) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const ids = []; + for (const item of inputIds) { + const normalized = Number(item); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError(`${fieldName} 必须是正整数数组`, 400); + } + ids.push(normalized); + } + if (ids.length === 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + return Array.from(new Set(ids)); + } + + async validatePermissions(permissionIds) { + const { ctx } = this; + if (permissionIds.length === 0) { + return []; + } + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + }); + + if (permissions.length !== permissionIds.length) { + const foundIds = permissions.map(item => Number(item.id)); + const missingIds = permissionIds.filter(item => !foundIds.includes(item)); + throw this.createError(`权限不存在或已禁用:${missingIds.join(',')}`, 400); + } + + return permissions; + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async getCurrentEmployeePermissionIds() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + raw: true, + }); + + const roleIds = Array.from(new Set(employeeRoles + .map(item => Number(item.role_id)) + .filter(id => Number.isFinite(id) && id > 0))); + if (roleIds.length === 0) { + return []; + } + + return await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, { + includeDisabled: false, + }); + } + + async getCurrentRoleId() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return null; + } + + const row = await ctx.model.EmployeeRole.findOne({ + attributes: [ 'role_id' ], + where: { + employee_id: currentEmployeeId, + }, + include: [ + { + model: ctx.model.Role, + as: 'role', + attributes: [], + where: { + status: 1, + }, + required: true, + }, + ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const roleId = Number(row && row.role_id); + if (!Number.isFinite(roleId) || roleId <= 0) { + return null; + } + return roleId; + } + + async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '', scopeMode = 'available' } = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const where = { + status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1, + }; + + if (scopeMode !== 'all') { + const currentPermissionIds = await this.getCurrentEmployeePermissionIds(); + if (currentPermissionIds.length === 0) { + return []; + } + where.id = { + [Op.in]: currentPermissionIds, + }; + } + if (type) { + where.type = type; + } + if (keyword) { + where[Op.or] = [ + { path: { [Op.like]: `%${keyword}%` } }, + { name: { [Op.like]: `%${keyword}%` } }, + { meta_title: { [Op.like]: `%${keyword}%` } }, + ]; + } + + const permissionRows = await ctx.model.Permission.findAll({ + where, + attributes: [ + 'id', + 'path', + 'name', + 'type', + 'status', + 'parent_id', + 'sort', + 'component', + 'redirect', + 'meta_title', + 'meta_icon', + 'hidden', + 'always_show', + ], + order: [ + [ 'sort', 'ASC' ], + [ 'id', 'ASC' ], + ], + }); + + return permissionRows; + } + + async list(data = {}) { + const { ctx } = this; + + const includeDisabled = data.includeDisabled === true; + const roleIdRaw = data.role_id || data.roleId; + const type = typeof data.type === 'string' && data.type.trim() ? data.type.trim() : null; + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + let role = null; + let targetRoleId = roleIdRaw; + if (targetRoleId === undefined || targetRoleId === null || targetRoleId === '') { + targetRoleId = await this.getCurrentRoleId(); + } + if (targetRoleId !== undefined && targetRoleId !== null && targetRoleId !== '') { + const roleId = this.toPositiveNumber(targetRoleId, 'role_id'); + role = await this.getRole(roleId); + } + + // 权限管理页需要展示全量权限树,不能再按当前登录工号已分配权限做裁剪。 + const permissionRows = await this.resolveVisiblePermissionRows({ + includeDisabled, + type, + keyword, + scopeMode: 'all', + }); + + let selectedPermissionSet = new Set(); + let selectAllPermissions = false; + if (role) { + const directPermissionIds = ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions); + if (directPermissionIds.includes('*')) { + selectAllPermissions = true; + } else if (directPermissionIds.length > 0) { + selectedPermissionSet = new Set(directPermissionIds.map(item => Number(item))); + } + } + + const permissions = permissionRows.map(item => ({ + permission_id: Number(item.id), + path: item.path || '', + name: item.name || '', + type: item.type || '', + status: Number(item.status), + parent_id: item.parent_id === null ? null : Number(item.parent_id), + sort: Number(item.sort || 0), + component: item.component || '', + redirect: item.redirect || '', + meta_title: item.meta_title || '', + meta_icon: item.meta_icon || '', + hidden: Number(item.hidden || 0), + always_show: Number(item.always_show || 0), + selected: role ? (selectAllPermissions || selectedPermissionSet.has(Number(item.id))) : false, + })); + + return { + code: 200, + data: { + role_id: role ? Number(role.id) : null, + permissions, + }, + }; + } + + async add(data = {}) { + const { ctx } = this; + + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + + const permissionData = { + path, + type: this.normalizePermissionType(data.type), + name: this.normalizeOptionalString(data.name, 'name', 100) || '', + component: this.normalizeOptionalString(data.component, 'component', 255), + redirect: this.normalizeOptionalString(data.redirect, 'redirect', 255), + meta_title: this.normalizeOptionalString(data.meta_title, 'meta_title', 100), + meta_icon: this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50), + parent_id: this.normalizeParentId(data.parent_id), + sort: this.normalizeSort(data.sort), + hidden: this.normalizeBooleanFlag(data.hidden, 'hidden'), + always_show: this.normalizeBooleanFlag(data.always_show, 'always_show'), + status: this.normalizeStatus(data.status), + }; + + await this.ensureParentPermissionExists(permissionData.parent_id); + + let created = null; + try { + created = await ctx.model.Permission.create(permissionData); + } catch (error) { + throw error; + } + + return { + code: 200, + data: { + permission_id: Number(created.id), + path: created.path || '', + type: created.type || '', + parent_id: created.parent_id === null ? null : Number(created.parent_id), + status: Number(created.status), + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + const permissionIds = this.normalizeIds(data.ids, 'ids'); + + await this.ensurePermissionsExist(permissionIds); + + const permissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + }, + attributes: [ 'id', 'status' ], + raw: true, + }); + + const deletedIds = []; + const alreadyDeletedIds = []; + for (const permission of permissions) { + if (Number(permission.status) === 0) { + alreadyDeletedIds.push(Number(permission.id)); + } else { + deletedIds.push(Number(permission.id)); + } + } + + const transaction = await ctx.model.transaction(); + try { + if (deletedIds.length > 0) { + await ctx.model.Permission.update({ + status: 0, + }, { + where: { + id: deletedIds, + }, + transaction, + }); + + await ctx.service.systems.auth.rolePermission.removePermissionsFromAllRoles(deletedIds, { + transaction, + }); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + return { + code: 200, + data: { + ids: permissionIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id'); + await this.ensurePermissionsExist([ permissionId ]); + + const permission = await this.getPermission(permissionId, true); + + const hasPath = Object.prototype.hasOwnProperty.call(data, 'path'); + const hasName = Object.prototype.hasOwnProperty.call(data, 'name'); + const hasType = Object.prototype.hasOwnProperty.call(data, 'type'); + const hasComponent = Object.prototype.hasOwnProperty.call(data, 'component'); + const hasRedirect = Object.prototype.hasOwnProperty.call(data, 'redirect'); + const hasMetaTitle = Object.prototype.hasOwnProperty.call(data, 'meta_title'); + const hasMetaIcon = Object.prototype.hasOwnProperty.call(data, 'meta_icon'); + const hasParentId = Object.prototype.hasOwnProperty.call(data, 'parent_id'); + const hasSort = Object.prototype.hasOwnProperty.call(data, 'sort'); + const hasHidden = Object.prototype.hasOwnProperty.call(data, 'hidden'); + const hasAlwaysShow = Object.prototype.hasOwnProperty.call(data, 'always_show'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + + if (!hasPath && !hasName && !hasType && !hasComponent && !hasRedirect + && !hasMetaTitle && !hasMetaIcon && !hasParentId && !hasSort + && !hasHidden && !hasAlwaysShow && !hasStatus) { + throw this.createError('至少需要提供一个可更新字段', 400); + } + + const updates = {}; + if (hasPath) { + const path = this.normalizeOptionalString(data.path, 'path', 255); + if (!path) { + throw this.createError('path 参数不能为空', 400); + } + updates.path = path; + } + if (hasName) { + updates.name = this.normalizeOptionalString(data.name, 'name', 100) || ''; + } + if (hasType) { + updates.type = this.normalizePermissionType(data.type); + } + if (hasComponent) { + updates.component = this.normalizeOptionalString(data.component, 'component', 255); + } + if (hasRedirect) { + updates.redirect = this.normalizeOptionalString(data.redirect, 'redirect', 255); + } + if (hasMetaTitle) { + updates.meta_title = this.normalizeOptionalString(data.meta_title, 'meta_title', 100); + } + if (hasMetaIcon) { + updates.meta_icon = this.normalizeOptionalString(data.meta_icon, 'meta_icon', 50); + } + if (hasParentId) { + const parentId = this.normalizeParentId(data.parent_id); + if (parentId && parentId === permissionId) { + throw this.createError('parent_id 不能等于 permission_id', 400); + } + await this.ensureParentPermissionExists(parentId); + updates.parent_id = parentId; + } + if (hasSort) { + updates.sort = this.normalizeSort(data.sort); + } + if (hasHidden) { + updates.hidden = this.normalizeBooleanFlag(data.hidden, 'hidden'); + } + if (hasAlwaysShow) { + updates.always_show = this.normalizeBooleanFlag(data.always_show, 'always_show'); + } + if (hasStatus) { + updates.status = this.normalizeStatus(data.status); + } + + await permission.update(updates); + + return { + code: 200, + data: { + permission_id: Number(permission.id), + path: permission.path || '', + type: permission.type || '', + parent_id: permission.parent_id === null ? null : Number(permission.parent_id), + status: Number(permission.status), + }, + }; + } +} + +module.exports = SettingPermissionService; diff --git a/app/service/systems/setting/role.js b/app/service/systems/setting/role.js new file mode 100644 index 0000000..2103bf6 --- /dev/null +++ b/app/service/systems/setting/role.js @@ -0,0 +1,695 @@ +'use strict'; + +const Service = require('egg').Service; + +class SettingRoleService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作角色', 400); + } + return storeId; + } + + getCurrentEmployeeId() { + const employeeId = Number(this.ctx.user && this.ctx.user.employees_id); + if (!Number.isFinite(employeeId) || employeeId <= 0) { + return null; + } + return employeeId; + } + + toPositiveNumber(value, fieldName) { + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + async getEmployee(employeeId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + const where = { + id: employeeId, + store_id: storeId, + }; + if (!includeDisabled) { + where.status = 1; + } + + const employee = await ctx.model.AccountStoreEmployee.findOne({ where }); + if (!employee) { + throw this.createError('工号不存在或无权限操作', 404); + } + return employee; + } + + normalizeRoleIds(inputRoleIds) { + if (!Array.isArray(inputRoleIds) || inputRoleIds.length === 0) { + throw this.createError('role_ids 参数不能为空', 400); + } + + const roleIds = []; + for (const roleId of inputRoleIds) { + const normalized = Number(roleId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('role_ids 必须是正整数数组', 400); + } + roleIds.push(normalized); + } + + return Array.from(new Set(roleIds)); + } + + async findAssignableRoles(roleIds, storeId) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const roles = await ctx.model.Role.findAll({ + where: { + id: roleIds, + status: 1, + [Op.or]: [ + { store_id: storeId }, + { store_id: 0 }, + { store_id: null }, + ], + }, + order: [[ 'id', 'ASC' ]], + }); + + if (roles.length !== roleIds.length) { + const foundRoleIds = roles.map(role => Number(role.id)); + const missingRoleIds = roleIds.filter(roleId => !foundRoleIds.includes(roleId)); + throw this.createError(`角色不存在、已禁用或超出当前主体范围:${missingRoleIds.join(',')}`, 400); + } + + return roles; + } + + async clearEmployeeCache(employee) { + const { service } = this.ctx; + await service.systems.auth.user.clearUserCache(Number(employee.account_id)); + } + + async getCurrentEmployeeRoleIds() { + const { ctx } = this; + const currentEmployeeId = this.getCurrentEmployeeId(); + if (!currentEmployeeId) { + return []; + } + + const rows = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: currentEmployeeId, + }, + attributes: [ 'role_id' ], + }); + + return Array.from(new Set(rows.map(item => Number(item.role_id)).filter(id => Number.isFinite(id) && id > 0))); + } + + collectDescendantRoleIds(roleRows, startRoleIds) { + const childrenMap = new Map(); + for (const row of roleRows) { + const parentId = Number(row.pid || 0); + if (!childrenMap.has(parentId)) { + childrenMap.set(parentId, []); + } + childrenMap.get(parentId).push(Number(row.id)); + } + + const visited = new Set(); + const stack = Array.from(startRoleIds); + while (stack.length > 0) { + const roleId = Number(stack.pop()); + if (!Number.isFinite(roleId) || roleId <= 0 || visited.has(roleId)) { + continue; + } + visited.add(roleId); + const children = childrenMap.get(roleId) || []; + for (const childId of children) { + if (!visited.has(childId)) { + stack.push(childId); + } + } + } + return visited; + } + + async buildRolePermissionMap(roleRows) { + const { service } = this.ctx; + const rows = Array.isArray(roleRows) ? roleRows : []; + const permissionMap = new Map(); + + for (const row of rows) { + const roleId = Number(row && row.id); + if (!Number.isFinite(roleId) || roleId <= 0) { + continue; + } + + const directPermissionIds = service.systems.auth.rolePermission.toApiPermissionIds(row.permissions); + permissionMap.set(roleId, directPermissionIds); + } + + return permissionMap; + } + + buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap = new Map()) { + const nodeMap = new Map(); + for (const row of roleRows) { + const roleId = Number(row.id); + nodeMap.set(roleId, { + role_id: roleId, + role_code: row.role_code || '', + role_name: row.role_name || '', + description: row.description || '', + role_type: Number(row.role_type), + scope: Number(row.scope), + is_system: Number(row.is_system), + status: Number(row.status), + store_id: row.store_id === null ? null : Number(row.store_id), + pid: Number(row.pid || 0), + selected: selectedRoleIdSet.has(roleId), + permission_ids: rolePermissionMap.get(roleId) || [], + children: [], + }); + } + + for (const node of nodeMap.values()) { + const parent = nodeMap.get(node.pid); + if (parent) { + parent.children.push(node); + } + } + + const sortNodes = nodes => { + nodes.sort((a, b) => a.role_id - b.role_id); + for (const item of nodes) { + if (item.children && item.children.length > 0) { + sortNodes(item.children); + } + } + }; + + const roots = Array.from(rootRoleIds) + .map(roleId => nodeMap.get(Number(roleId))) + .filter(Boolean); + sortNodes(roots); + return roots; + } + + normalizeStoreScope(storeId) { + if (storeId === null || storeId === undefined) { + return 0; + } + const num = Number(storeId); + if (!Number.isFinite(num) || num <= 0) { + return 0; + } + return num; + } + + isRoleVisibleInScope(role, currentRoleRows, currentStoreId, includeSystem) { + const roleStoreScope = this.normalizeStoreScope(role.store_id); + + // 当前主体角色默认可见 + if (roleStoreScope === currentStoreId) { + return true; + } + + // includeSystem=true 时,可见系统角色 + if (includeSystem && roleStoreScope === 0) { + return true; + } + + // 当前工号若本身处于系统角色域,至少允许看到系统角色,避免空树。 + const hasSystemCurrentRole = currentRoleRows + .some(item => this.normalizeStoreScope(item.store_id) === 0); + if (hasSystemCurrentRole && roleStoreScope === 0) { + return true; + } + + return false; + } + + normalizePermissionIds(inputPermissionIds) { + if (inputPermissionIds === '*') { + return [ '*' ]; + } + + if (typeof inputPermissionIds === 'string') { + const trimmed = inputPermissionIds.trim(); + if (!trimmed) { + throw this.createError('permission_ids 参数不能为空', 400); + } + if (trimmed === '*') { + return [ '*' ]; + } + + try { + const parsed = JSON.parse(trimmed); + return this.normalizePermissionIds(parsed); + } catch (_) { + if (trimmed.includes(',')) { + return this.normalizePermissionIds(trimmed.split(',')); + } + throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400); + } + } + + if (!Array.isArray(inputPermissionIds)) { + throw this.createError('permission_ids 参数不能为空', 400); + } + + if (inputPermissionIds.some(item => typeof item === 'string' && item.trim() === '*')) { + return [ '*' ]; + } + + const permissionIds = []; + for (const permissionId of inputPermissionIds) { + const normalized = Number(permissionId); + if (!Number.isFinite(normalized) || normalized <= 0) { + throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400); + } + permissionIds.push(Math.floor(normalized)); + } + + return Array.from(new Set(permissionIds)); + } + + normalizePid(value) { + if (value === undefined || value === null || value === '') { + return 0; + } + const pid = Number(value); + if (!Number.isFinite(pid) || pid < 0) { + throw this.createError('pid 参数不合法', 400); + } + return pid; + } + + async getManageableRole(roleId, options = {}) { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const includeDisabled = options.includeDisabled === true; + + const where = { + id: roleId, + store_id: storeId, + is_system: 0, + }; + if (!includeDisabled) { + where.status = 1; + } + + const role = await ctx.model.Role.findOne({ where }); + if (!role) { + throw this.createError('角色不存在、无权限操作或为系统预设角色', 404); + } + return role; + } + + async validatePermissionSet(permissionIds) { + const { ctx } = this; + if (!Array.isArray(permissionIds) || permissionIds.length === 0) { + return; + } + + if (permissionIds.includes('*')) { + return; + } + + const existingPermissions = await ctx.model.Permission.findAll({ + where: { + id: permissionIds, + status: 1, + }, + attributes: [ 'id' ], + raw: true, + }); + if (existingPermissions.length !== permissionIds.length) { + const found = new Set(existingPermissions.map(item => Number(item.id))); + const missing = permissionIds.filter(id => !found.has(id)); + throw this.createError(`权限不存在或已禁用:${missing.join(',')}`, 400); + } + } + + async replaceRolePermissions(roleId, permissionIds, transaction) { + return await this.ctx.service.systems.auth.rolePermission.assignPermissions(roleId, permissionIds, { + transaction, + }); + } + + async clearRoleUsersCache(roleId) { + const { ctx, service } = this; + const storeId = this.getCurrentStoreId(); + + const employeeRoleRows = await ctx.model.EmployeeRole.findAll({ + where: { + role_id: roleId, + }, + include: [ + { + model: ctx.model.AccountStoreEmployee, + as: 'employee', + attributes: [ 'account_id' ], + where: { + store_id: storeId, + status: 1, + }, + required: true, + }, + ], + raw: false, + }); + + const accountIds = Array.from(new Set(employeeRoleRows + .map(item => Number(item.employee && item.employee.account_id)) + .filter(id => Number.isFinite(id) && id > 0))); + + for (const accountId of accountIds) { + await service.systems.auth.user.clearUserCache(accountId); + } + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const storeId = this.getCurrentStoreId(); + const includeDisabled = data.includeDisabled === true; + const includeSystem = data.includeSystem === true; + const currentEmployeeId = this.getCurrentEmployeeId(); + + let employee = null; + if (currentEmployeeId) { + employee = await this.getEmployee(currentEmployeeId, { + includeDisabled: true, + }); + } + + // 先拉取当前主体 + 系统角色域,后续按可见规则二次收敛。 + const roleWhere = { + status: includeDisabled ? { [Op.in]: [0, 1] } : 1, + [Op.or]: [ { store_id: storeId }, { store_id: 0 }, { store_id: null } ], + }; + + const roleRows = await ctx.model.Role.findAll({ + where: roleWhere, + attributes: [ + 'id', + 'role_code', + 'role_name', + 'description', + 'role_type', + 'scope', + 'is_system', + 'status', + 'store_id', + 'pid', + 'permissions', + ], + order: [ + [ 'is_system', 'DESC' ], + [ 'id', 'ASC' ], + ], + }); + + const currentRoleIds = await this.getCurrentEmployeeRoleIds(); + if (currentRoleIds.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const roleMap = new Map(roleRows.map(item => [ Number(item.id), item ])); + const currentRoleRows = currentRoleIds + .map(roleId => roleMap.get(roleId)) + .filter(Boolean); + + if (currentRoleRows.length === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id))); + + // 仅返回当前角色的下级角色树,不返回自己及同级角色。 + const subordinateRootRoleIds = new Set(roleRows + .filter(item => currentRoleIdSet.has(Number(item.pid || 0))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)) + .map(item => Number(item.id))); + + if (subordinateRootRoleIds.size === 0) { + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles: [], + }, + }; + } + + const visibleRoleIds = this.collectDescendantRoleIds(roleRows, Array.from(subordinateRootRoleIds)); + + const visibleRoleRows = roleRows + .filter(item => visibleRoleIds.has(Number(item.id))) + .filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem)); + const rootRoleIds = new Set(visibleRoleRows + .filter(item => subordinateRootRoleIds.has(Number(item.id))) + .map(item => Number(item.id))); + + let selectedRoleIdSet = new Set(); + if (employee) { + const employeeRoles = await ctx.model.EmployeeRole.findAll({ + where: { + employee_id: employee.id, + }, + }); + selectedRoleIdSet = new Set(employeeRoles.map(item => Number(item.role_id))); + } + + const rolePermissionMap = await this.buildRolePermissionMap(visibleRoleRows); + const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap); + + return { + code: 200, + data: { + employee_id: employee ? Number(employee.id) : null, + roles, + }, + }; + } + + async permission(data = {}) { + return this.ctx.service.systems.setting.permission.list(data); + } + + async add(data = {}) { + const { ctx } = this; + + const storeId = this.getCurrentStoreId(); + const roleCode = typeof data.role_code === 'string' ? data.role_code.trim() : ''; + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + const description = typeof data.description === 'string' ? data.description.trim() : ''; + const roleType = Number(data.role_type || 1); + const scope = Number(data.scope || 1); + const status = data.status === 0 || data.status === '0' ? 0 : 1; + const pid = this.normalizePid(data.pid); + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + const creatorId = Number(this.ctx.user && this.ctx.user.id); + + if (!roleCode) { + throw this.createError('role_code 参数不能为空', 400); + } + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + if (!Number.isFinite(creatorId) || creatorId <= 0) { + throw this.createError('未识别到当前账号,无法创建角色', 400); + } + + await this.validatePermissionSet(permissionIds); + + const transaction = await ctx.model.transaction(); + let createdRole = null; + try { + createdRole = await ctx.model.Role.create({ + role_code: roleCode, + role_name: roleName, + description, + role_type: roleType, + scope, + is_system: 0, + status, + created_by: creatorId, + store_id: storeId, + pid, + }, { transaction }); + + await this.replaceRolePermissions(Number(createdRole.id), permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('role_code 已存在', 409); + } + throw error; + } + + return { + code: 200, + data: { + role_id: Number(createdRole.id), + role_code: createdRole.role_code, + role_name: createdRole.role_name, + permission_ids: permissionIds, + created: true, + }, + }; + } + + async delete(data = {}) { + const { ctx } = this; + + const roleIds = this.normalizeRoleIds(data.ids); + const roles = []; + for (const roleId of roleIds) { + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + roles.push(role); + } + + const deletedIds = []; + const alreadyDeletedIds = []; + + const transaction = await ctx.model.transaction(); + try { + for (const role of roles) { + const roleId = Number(role.id); + if (Number(role.status) === 0) { + alreadyDeletedIds.push(roleId); + continue; + } + + await role.update({ + status: 0, + updated_at: new Date(), + }, { transaction }); + deletedIds.push(roleId); + } + + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + throw error; + } + + for (const roleId of deletedIds) { + await this.clearRoleUsersCache(roleId); + } + + return { + code: 200, + data: { + ids: roleIds, + deleted_ids: deletedIds, + already_deleted_ids: alreadyDeletedIds, + status: 'deleted', + }, + }; + } + + async update(data = {}) { + const { ctx } = this; + + const roleId = this.toPositiveNumber(data.role_id || data.roleId, 'role_id'); + const role = await this.getManageableRole(roleId, { + includeDisabled: true, + }); + + const hasRoleName = Object.prototype.hasOwnProperty.call(data, 'role_name'); + const hasDescription = Object.prototype.hasOwnProperty.call(data, 'description'); + const hasStatus = Object.prototype.hasOwnProperty.call(data, 'status'); + const hasPid = Object.prototype.hasOwnProperty.call(data, 'pid'); + const hasPermissionIds = Object.prototype.hasOwnProperty.call(data, 'permission_ids') + || Object.prototype.hasOwnProperty.call(data, 'permissionIds'); + + if (!hasRoleName && !hasDescription && !hasStatus && !hasPid && !hasPermissionIds) { + throw this.createError('至少需要更新角色信息或 permission_ids', 400); + } + if (!hasPermissionIds) { + throw this.createError('permission_ids 参数不能为空,角色权限需一次性提交', 400); + } + + const permissionIds = this.normalizePermissionIds(data.permission_ids || data.permissionIds || []); + await this.validatePermissionSet(permissionIds); + + const updates = {}; + if (hasRoleName) { + const roleName = typeof data.role_name === 'string' ? data.role_name.trim() : ''; + if (!roleName) { + throw this.createError('role_name 参数不能为空', 400); + } + updates.role_name = roleName; + } + if (hasDescription) { + updates.description = typeof data.description === 'string' ? data.description.trim() : ''; + } + if (hasStatus) { + const status = data.status === 0 || data.status === '0' ? 0 : 1; + updates.status = status; + } + if (hasPid) { + updates.pid = this.normalizePid(data.pid); + } + updates.updated_at = new Date(); + + const transaction = await ctx.model.transaction(); + try { + if (Object.keys(updates).length > 0) { + await role.update(updates, { transaction }); + } + + await this.replaceRolePermissions(roleId, permissionIds, transaction); + await transaction.commit(); + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('角色信息冲突(可能 role_code 重复)', 409); + } + throw error; + } + + await this.clearRoleUsersCache(roleId); + + return { + code: 200, + data: { + role_id: roleId, + role_name: role.role_name, + permission_ids: permissionIds, + }, + }; + } +} + +module.exports = SettingRoleService; diff --git a/app/service/systems/setting/store_warehouse.js b/app/service/systems/setting/store_warehouse.js new file mode 100644 index 0000000..53e464a --- /dev/null +++ b/app/service/systems/setting/store_warehouse.js @@ -0,0 +1,711 @@ +'use strict'; + +const crypto = require('node:crypto'); +const Service = require('egg').Service; + +const SIGN_TEMP_EXPIRE_SECONDS = 600; +const AUTH_STATUS_LABELS = Object.freeze({ + 1: '申请中', + 2: '已通过', + 3: '已拒绝', + 4: '已解除', + 5: '已过期', +}); + +class SettingStoreWarehouseService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作签约关系', 400); + } + return storeId; + } + + getCurrentAccountId() { + const accountId = Number(this.ctx.user && this.ctx.user.id); + if (!Number.isFinite(accountId) || accountId <= 0) { + throw this.createError('未识别到当前登录账号', 401); + } + return accountId; + } + + toPositiveNumber(value, fieldName, options = {}) { + const { allowEmpty = false } = options; + if (allowEmpty && (value === undefined || value === null || value === '')) { + return null; + } + + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.min(Math.floor(num), maxValue); + } + + normalizeStatusFlag(value, fieldName, defaultValue = null) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + normalizeAuthStatus(value) { + if (value === undefined || value === null || value === '') { + return null; + } + const num = Number(value); + if ([ 1, 2, 3, 4, 5 ].includes(num)) { + return num; + } + throw this.createError('auth_status 参数不合法', 400); + } + + normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.floor(num); + } + + normalizeText(value, fieldName, maxLength = 500) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeDate(value, fieldName, options = {}) { + const { allowNull = true } = options; + if (value === undefined || value === null || value === '') { + if (allowNull) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return date; + } + + normalizeSignAction(value) { + if (value === undefined || value === null || value === '') { + return ''; + } + + const action = String(value).trim(); + if ([ 'preview', 'confirm' ].includes(action)) { + return action; + } + throw this.createError('action 参数不合法', 400); + } + + normalizeTempCode(value) { + const code = String(value || '').trim().toUpperCase(); + if (!code) { + throw this.createError('temp_code 参数不能为空', 400); + } + return code; + } + + getTempCodeCacheKey(tempCode) { + return `store_warehouse:sign:${tempCode}`; + } + + createTempCode() { + return crypto.randomBytes(6).toString('hex').toUpperCase(); + } + + pickRemaskField(currentSubject) { + return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask'; + } + + resolveRemaskValue(data, currentSubject) { + const raw = data.remask !== undefined + ? data.remask + : (currentSubject && currentSubject.isWarehouse ? data.store_remask : data.warehouse_remask); + return this.normalizeText(raw, 'remask', 50); + } + + buildCurrentRemaskPatch(data, currentSubject) { + const remask = this.resolveRemaskValue(data, currentSubject); + if (remask === null) { + return {}; + } + + return { + [this.pickRemaskField(currentSubject)]: remask, + }; + } + + requireCurrentRemaskPatch(data, currentSubject) { + const patch = this.buildCurrentRemaskPatch(data, currentSubject); + if (!Object.keys(patch).length) { + throw this.createError('remask 参数不能为空', 400); + } + return patch; + } + + async saveTempSignPayload(payload) { + const now = Date.now(); + const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString(); + const tempCode = this.createTempCode(); + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { + ...payload, + expires_at: expiresAt, + }, SIGN_TEMP_EXPIRE_SECONDS); + return { + tempCode, + expiresAt, + expiresIn: SIGN_TEMP_EXPIRE_SECONDS, + }; + } + + async getTempSignPayload(tempCode) { + const normalizedCode = this.normalizeTempCode(tempCode); + const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode)); + if (!payload) { + throw this.createError('临时码无效或已过期', 404); + } + return { + tempCode: normalizedCode, + payload, + }; + } + + async clearTempSignPayload(tempCode) { + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + if (cacheRedis && cacheRedis.del) { + await cacheRedis.del(this.getTempCodeCacheKey(tempCode)); + return; + } + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1); + } + + buildTempSignView(tempCode, payload, currentSubject) { + const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]; + const currentSubjectId = Number(currentSubject && currentSubject.id); + const expiresAt = payload.expires_at || null; + const expiresMs = expiresAt ? new Date(expiresAt).getTime() : 0; + + return { + mode: 'preview', + temp_code: tempCode, + expires_at: expiresAt, + expires_in: expiresMs ? Math.max(0, Math.ceil((expiresMs - Date.now()) / 1000)) : 0, + is_participant: participantIds.includes(currentSubjectId), + can_confirm: currentSubjectId > 0 && currentSubjectId === Number(payload.counterparty_id || 0), + initiator: { + id: Number(payload.initiator_subject_id || 0), + role: payload.initiator_role || '', + name: payload.initiator_name || '', + }, + counterparty: { + id: Number(payload.counterparty_id || 0), + role: payload.counterparty_role || '', + name: payload.counterparty_name || '', + }, + sign_info: { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_start: payload.auth_start || null, + auth_end: payload.auth_end || null, + print_quantity: Number(payload.print_quantity || 0), + apply_reason: payload.apply_reason || '', + remask: payload.remask || '', + }, + }; + } + + async getCurrentSubject() { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const subject = await ctx.model.Store.findOne({ + where: { + id: storeId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!subject) { + throw this.createError('当前主体不存在', 404); + } + + return { + id: Number(subject.id), + company_name: subject.company_name || '', + project: subject.project || '', + isWarehouse: subject.project === 'warehouse', + status: Number(subject.status || 0), + }; + } + + async getCounterparty(counterpartyId, expectedRole) { + const { ctx } = this; + const counterparty = await ctx.model.Store.findOne({ + where: { + id: counterpartyId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!counterparty) { + throw this.createError('签约对象不存在', 404); + } + + const isWarehouse = counterparty.project === 'warehouse'; + if (expectedRole === 'warehouse' && !isWarehouse) { + throw this.createError('目标对象不是仓库主体,无法签约', 400); + } + if (expectedRole === 'store' && isWarehouse) { + throw this.createError('目标对象不是货主主体,无法签约', 400); + } + + return counterparty; + } + + buildListWhere(data, currentSubject) { + const where = {}; + + if (currentSubject.isWarehouse) { + where.warehouse_id = currentSubject.id; + } else { + where.store_id = currentSubject.id; + } + + const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true }); + if (relationId) { + where.id = relationId; + } + + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + if (currentSubject.isWarehouse) { + where.store_id = counterpartyId; + } else { + where.warehouse_id = counterpartyId; + } + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null); + if (useStatus !== null) { + where.use_status = useStatus; + } + + return where; + } + + getRelationIncludes() { + const { ctx } = this; + return [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + ]; + } + + resolvePairIds(data, currentSubject) { + const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id'; + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName); + + if (currentSubject.isWarehouse) { + return { + storeId: counterpartyId, + warehouseId: currentSubject.id, + counterpartyId, + }; + } + + return { + storeId: currentSubject.id, + warehouseId: counterpartyId, + counterpartyId, + }; + } + + serializeRelation(relation, currentSubject) { + const item = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : (relation || {}); + + const authStatus = Number(item.auth_status || 0); + const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse); + const counterparty = currentIsWarehouse ? item.store : item.warehouse; + const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); + const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : ''); + const counterpartyName = currentIsWarehouse ? storeName : warehouseName; + + let isAuthValid = false; + let remainingDays = 0; + if (authStatus === 2 && item.auth_start && item.auth_end) { + const now = Date.now(); + const start = new Date(item.auth_start).getTime(); + const end = new Date(item.auth_end).getTime(); + if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) { + isAuthValid = true; + remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24))); + } + } + + return { + id: Number(item.id || 0), + store_id: Number(item.store_id || 0), + store_name: storeName, + warehouse_id: Number(item.warehouse_id || 0), + warehouse_name: warehouseName, + counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0, + counterparty_name: counterpartyName, + current_subject_role: currentIsWarehouse ? 'warehouse' : 'store', + auth_status: authStatus, + auth_status_label: AUTH_STATUS_LABELS[authStatus] || '', + apply_reason: item.apply_reason || '', + review_comment: item.review_comment || '', + apply_time: item.apply_time || null, + review_time: item.review_time || null, + auth_start: item.auth_start || null, + auth_end: item.auth_end || null, + actual_end: item.actual_end || null, + print_quantity: Number(item.print_quantity || 0), + applied_by: item.applied_by ? Number(item.applied_by) : null, + reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, + ended_by: item.ended_by ? Number(item.ended_by) : null, + remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), + use_status: Number(item.use_status || 0), + is_auth_valid: isAuthValid, + remaining_days: remainingDays, + }; + } + + async findScopedRelation(data, currentSubject, transaction) { + const { ctx } = this; + const where = currentSubject.isWarehouse + ? { warehouse_id: currentSubject.id } + : { store_id: currentSubject.id }; + + const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true }); + if (relationId) { + where.id = relationId; + } else { + const pair = this.resolvePairIds(data, currentSubject); + where.store_id = pair.storeId; + where.warehouse_id = pair.warehouseId; + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where, + include: this.getRelationIncludes(), + transaction, + }); + + if (!relation) { + throw this.createError('签约关系不存在或无权限操作', 404); + } + + return relation; + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + const where = this.buildListWhere(data, currentSubject); + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + + return { + code: 200, + data: { + list: rows.map(item => this.serializeRelation(item, currentSubject)), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + async sign(data = {}) { + const action = this.normalizeSignAction(data.action || data.mode); + if (data.temp_code || data.tempCode || action === 'preview') { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode); + const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ] + .includes(Number(currentSubject.id)); + + if (!isParticipant) { + throw this.createError('当前主体无权使用该临时码', 403); + } + + if (action === 'preview' || data.preview === 1 || data.preview === '1') { + await transaction.rollback(); + return { + code: 200, + data: this.buildTempSignView(tempCode, payload, currentSubject), + }; + } + + if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) { + throw this.createError('需由对方主体确认后才可生效', 400); + } + + const relationPatch = { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_status: 2, + apply_reason: payload.apply_reason || '', + apply_time: payload.created_at ? new Date(payload.created_at) : new Date(), + print_quantity: Number(payload.print_quantity || 0), + review_time: new Date(), + auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(), + auth_end: payload.auth_end ? new Date(payload.auth_end) : null, + actual_end: null, + applied_by: Number(payload.initiated_by || 0) || accountId, + reviewed_by: accountId, + ended_by: null, + use_status: 1, + }; + + if (payload.store_remask !== undefined) { + relationPatch.store_remask = payload.store_remask; + } + if (payload.warehouse_remask !== undefined) { + relationPatch.warehouse_remask = payload.warehouse_remask; + } + Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); + + let relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: relationPatch.store_id, + warehouse_id: relationPatch.warehouse_id, + }, + transaction, + }); + const isCreate = !relation; + + if (relation) { + await relation.update(relationPatch, { transaction }); + } else { + relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); + } + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await this.clearTempSignPayload(tempCode); + await transaction.commit(); + + return { + code: 200, + data: { + mode: 'confirm', + temp_code: tempCode, + contract: this.serializeRelation(result, currentSubject), + action: isCreate ? 'create' : 'update', + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + if (authEnd && authStart.getTime() > authEnd.getTime()) { + throw this.createError('auth_end 不能早于 auth_start', 400); + } + + const remask = this.resolveRemaskValue(data, currentSubject); + const payload = { + initiated_by: accountId, + initiator_subject_id: currentSubject.id, + initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store', + initiator_name: currentSubject.company_name, + counterparty_id: Number(counterparty.id || 0), + counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse', + counterparty_name: counterparty.company_name || '', + store_id: pair.storeId, + warehouse_id: pair.warehouseId, + auth_start: authStart.toISOString(), + auth_end: authEnd ? authEnd.toISOString() : null, + print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), + remask: remask || '', + created_at: new Date().toISOString(), + ...this.buildCurrentRemaskPatch(data, currentSubject), + }; + + const signPayload = await this.saveTempSignPayload(payload); + + return { + code: 200, + data: { + mode: 'initiate', + temp_code: signPayload.tempCode, + expires_at: signPayload.expiresAt, + expires_in: signPayload.expiresIn, + can_confirm: false, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + counterparty: { + id: Number(counterparty.id || 0), + company_name: counterparty.company_name || '', + role: currentSubject.isWarehouse ? 'store' : 'warehouse', + }, + }, + }; + } + + async rename(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const relationPatch = this.requireCurrentRemaskPatch(data, currentSubject); + + await relation.update(relationPatch, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async unbind(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0); + + await relation.update({ + use_status: nextUseStatus, + }, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } +} + +module.exports = SettingStoreWarehouseService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index 28f8d6f..4a899a8 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -313,14 +313,23 @@ class ReceivingService extends Service { where: { business_type: 'receivingItem', business_id: { [Op.in]: receivingItemsIds }, - } + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: ['file_url'], + required: true, + }], }); - // 将图片按明细ID分组,eggjs 不能使用forEach异步处理,所以改为同步处理 + // 将图片按明细ID分组,并转换为前端可直接使用的链接 for (const image of receivingItemsImages) { if (!itemImagesMap[image.business_id]) { itemImagesMap[image.business_id] = []; } - itemImagesMap[image.business_id].push(image); + itemImagesMap[image.business_id].push({ + id: image.file_id, + url: image.file.file_url, + }); } } // 5. 将图片合并到对应的明细中 @@ -335,11 +344,20 @@ class ReceivingService extends Service { where: { business_type: 'receiving', business_id: id, - } + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: ['file_url'], + required: true, + }], }); // 7. 组装返回数据 - receiving.dataValues.details = items; // 包含图片的明细数据 - receiving.dataValues.images = receivingImages; // 包含主表图片 + receiving.dataValues.details = items; // 包含图片链接的明细数据 + receiving.dataValues.images = receivingImages.map(image => ({ + id: image.file_id, + url: image.file.file_url, + })); // 包含主表图片链接 receiving.dataValues.pagination = pagination; // 包含分页信息 return { code: 200, message: '查询成功', data: { receiving } }; @@ -634,6 +652,48 @@ class ReceivingService extends Service { } } + buildReceivingPrefix(date = new Date()) { + const dateStr = Math.floor(date.getTime() / (1000 * 60 * 60 * 24)); + return `R${dateStr}`; + } + + async generateNextReceivingNumber(prefix) { + const { app } = this.ctx; + const suffixStartIndex = prefix.length + 1; + + const maxReceiving = await app.model.Receiving.findOne({ + attributes: [ 'receiving_number' ], + where: { + receiving_number: { + [app.Sequelize.Op.like]: `${prefix}%`, + }, + }, + order: [ + [app.Sequelize.literal(`CAST(SUBSTRING(receiving_number, ${suffixStartIndex}) AS UNSIGNED)`), 'DESC'], + [ 'receiving_number', 'DESC' ], + ], + }); + + let sequence = 1; + if (maxReceiving && maxReceiving.receiving_number) { + const lastNumStr = String(maxReceiving.receiving_number).slice(prefix.length); + const lastNum = Number.parseInt(lastNumStr, 10); + if (Number.isFinite(lastNum) && lastNum > 0) { + sequence = lastNum + 1; + } + } + + const seqLen = Math.max(3, String(sequence).length); + return `${prefix}${String(sequence).padStart(seqLen, '0')}`; + } + + isReceivingNumberDuplicateError(error) { + const parentCode = error && error.parent && error.parent.code; + const sqlMessage = String((error && error.parent && error.parent.sqlMessage) || error.message || ''); + return parentCode === 'ER_DUP_ENTRY' + && /uk_receiving_number|receiving_number/i.test(sqlMessage); + } + /** * 创建收货单并生成收货单号。 * @param {Object} data 创建参数 @@ -666,36 +726,12 @@ class ReceivingService extends Service { id: creator_id, }; - // 2. 生成收货单号 (格式: R + 时间戳的day + 3位序列号,如: RR20231215001) + // 2. 生成收货单号。注意:`wms_receiving.receiving_number` 在数据库中是全局唯一索引, + // 不能按 warehouse_id 各自从 001 开始,否则跨仓会撞号;并发创建时也需要重试兜底。 const now = new Date(); console.log('当前时间:', now); - const dateStr = Math.floor(now.getTime() / (1000 * 60 * 60 * 24)); // 时间戳到今日的天数 - const prefix = `R${dateStr}`; + const prefix = this.buildReceivingPrefix(now); - // 查找当天最大的收货单号 - const maxReceiving = await app.model.Receiving.findOne({ - where: { - receiving_number: { - [app.Sequelize.Op.like]: `${prefix}%`, - }, - warehouse_id - }, - order: [['receiving_number', 'DESC']], - }); - - let sequence = 1; - if (maxReceiving) { - // 提取最大收货单号的序号部分 - const lastNumStr = maxReceiving.receiving_number.replace(prefix, ''); - const lastNum = parseInt(lastNumStr); - sequence = lastNum + 1; - } - - // 序号动态长度:<1000用3位,<10000用4位,>=10000用5位 - let seqLen = 3; - if (sequence >= 1000 && sequence < 10000) seqLen = 4; - if (sequence >= 10000) seqLen = 5; - const receiving_number = `${prefix}${sequence.toString().padStart(seqLen, '0')}`; // 3. 获取店铺名称(如果有货主) let store_name = null; if (store_id) { @@ -711,33 +747,56 @@ class ReceivingService extends Service { } } - // 4. 创建收货单记录 - const receivingData = { - receiving_number, - creator_id, - creator_snapshot: JSON.stringify(creator_snapshot), - status: status || 'receiving', - detail_status: 'unmatched', - storage_status: 'none', - delivery_method, - license_plate: delivery_method === 'truck' ? license_plate : null, - tracking_number: delivery_method !== 'truck' && delivery_method !== 'other' ? tracking_number : null, - loading_method, - video_device_id: video_device_id || null, - total_boxes: parseInt(total_boxes) || 0, - total_pallets: parseInt(total_pallets) || 0, - total_items: 0, - total_quantity: 0, - warehouse_id, - remark: remark || null, - store_name, - store_id: store_id || null, - receiving_start_time: new Date(), - is_deleted: false, - }; + // 4. 创建收货单记录(并发下若撞到唯一键则自动重试取下一个号) + const maxCreateRetries = 5; + let result = null; + let lastCreateError = null; - // 5. 保存到数据库 - const result = await app.model.Receiving.create(receivingData); + for (let attempt = 1; attempt <= maxCreateRetries; attempt++) { + const receiving_number = await this.generateNextReceivingNumber(prefix); + const receivingData = { + receiving_number, + creator_id, + creator_snapshot: JSON.stringify(creator_snapshot), + status: status || 'receiving', + detail_status: 'unmatched', + storage_status: 'none', + delivery_method, + license_plate: delivery_method === 'truck' ? license_plate : null, + tracking_number: delivery_method !== 'truck' && delivery_method !== 'other' ? tracking_number : null, + loading_method, + video_device_id: video_device_id || null, + total_boxes: parseInt(total_boxes) || 0, + total_pallets: parseInt(total_pallets) || 0, + total_items: 0, + total_quantity: 0, + warehouse_id, + remark: remark || null, + store_name, + store_id: store_id || null, + receiving_start_time: new Date(), + is_deleted: false, + }; + + try { + result = await app.model.Receiving.create(receivingData); + break; + } catch (error) { + lastCreateError = error; + if (this.isReceivingNumberDuplicateError(error) && attempt < maxCreateRetries) { + ctx.logger.warn(`[ReceivingCreateRetry] receiving_number 冲突,准备重试第 ${attempt + 1} 次`, { + prefix, + warehouse_id, + }); + continue; + } + throw error; + } + } + + if (!result) { + throw lastCreateError || new Error('创建收货任务失败'); + } return { code: 200, @@ -755,6 +814,135 @@ class ReceivingService extends Service { } } + /** + * 绑定收货单货主。 + * 规则: + * 1. 已取消收货单禁止绑定; + * 2. 收货中/已完成状态下,若已存在货主,则禁止重复绑定; + * 3. 仅允许绑定与当前仓库存在有效签约关系的货主。 + * @param {Object} data 请求体 + * @param {number} data.id 收货单ID + * @param {number} data.store_id 货主ID + * @return {Promise} 绑定结果 + */ + async bindStore(data) { + const { ctx } = this; + const { id, store_id } = data || {}; + const warehouseId = Number(ctx.user && ctx.user.store_id); + const receivingId = Number(id || 0); + const storeId = Number(store_id || 0); + + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库', + }; + } + + if (receivingId <= 0) { + return { + code: 400, + message: '收货单ID不能为空', + }; + } + + if (storeId <= 0) { + return { + code: 400, + message: '货主ID不能为空', + }; + } + + const transaction = await ctx.model.transaction(); + + try { + const receiving = await ctx.model.Receiving.findOne({ + where: { + id: receivingId, + warehouse_id: warehouseId, + is_deleted: false, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!receiving) { + await transaction.rollback(); + return { + code: 404, + message: '收货单不存在或无权访问', + }; + } + + if (receiving.status === 'cancelled') { + await transaction.rollback(); + return { + code: 400, + message: '已取消的收货单不允许绑定货主', + }; + } + + if ([ 'receiving', 'completed' ].includes(receiving.status) && Number(receiving.store_id || 0) > 0) { + await transaction.rollback(); + return { + code: 400, + message: '当前收货单已有货主,拒绝重复绑定', + }; + } + + const storeRelation = await ctx.model.StoreWarehouse.findOne({ + where: { + warehouse_id: warehouseId, + store_id: storeId, + use_status: 1, + }, + attributes: [ 'store_id', 'store_remask' ], + transaction, + }); + + if (!storeRelation) { + await transaction.rollback(); + return { + code: 404, + message: '货主不存在或未与当前仓库建立有效签约关系', + }; + } + + const storeName = storeRelation.store_remask || null; + await ctx.model.Receiving.update({ + store_id: storeId, + store_name: storeName, + updated_at: new Date(), + }, { + where: { + id: receivingId, + warehouse_id: warehouseId, + }, + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + message: '绑定货主成功', + data: { + id: receivingId, + store_id: storeId, + store_name: storeName, + status: receiving.status, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('绑定收货单货主失败:', error); + return { + code: 500, + message: `绑定货主失败: ${error.message}`, + }; + } + } + /** * 查询单个收货单完整信息(含明细、图片)。 * @param {Object} data 请求体 @@ -991,6 +1179,164 @@ class ReceivingService extends Service { } } + /** + * 绑定或改绑收货单明细的系统商品。 + * @param {Object} data 请求体 + * @param {number} data.detail_id 收货单明细ID(兼容 `id`) + * @param {number} data.system_product_id 商品ID + * @return {Promise} 绑定结果 + */ + async bindDetailProduct(data) { + const { ctx, app } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id); + const detailId = Number((data && (data.detail_id || data.id)) || 0); + const systemProductId = Number((data && data.system_product_id) || 0); + + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库', + }; + } + + if (detailId <= 0) { + return { + code: 400, + message: '收货单明细ID不能为空', + }; + } + + if (systemProductId <= 0) { + return { + code: 400, + message: '商品ID不能为空', + }; + } + + try { + const receivingDetail = await app.model.ReceivingDetail.findOne({ + where: { id: detailId }, + include: [ + { + model: app.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'warehouse_id', 'store_id', 'store_name', 'status' ], + where: { + warehouse_id: warehouseId, + }, + required: true, + }, + ], + }); + + if (!receivingDetail) { + return { + code: 404, + message: '收货单明细不存在', + }; + } + + if (receivingDetail.receiving && receivingDetail.receiving.status !== 'receiving') { + return { + code: 400, + message: '收货单状态不允许绑定或改绑商品', + }; + } + + const stockWarehouse = await app.model.StockWarehouse.findOne({ + where: { + id: systemProductId, + warehouse_id: warehouseId, + }, + include: [ + app.model.StoreWarehouse.buildStoreStockInclude({ + warehouseId, + required: false, + attributes: [ 'store_id', 'store_remask' ], + }), + { + model: app.model.StockBarcode, + as: 'barcodes', + attributes: [ 'barcode' ], + required: false, + }, + ], + }); + + if (!stockWarehouse) { + return { + code: 404, + message: '商品不存在或不属于当前仓库', + }; + } + + const productStoreId = Number(stockWarehouse.store_stock?.store_id || 0); + + const barcodes = Array.isArray(stockWarehouse.barcodes) + ? stockWarehouse.barcodes.map(item => item && item.barcode).filter(Boolean) + : []; + + let productSnapshot = {}; + if (receivingDetail.product_snapshot) { + try { + productSnapshot = JSON.parse(receivingDetail.product_snapshot) || {}; + } catch { + productSnapshot = {}; + } + } + + const productName = stockWarehouse.item_name || stockWarehouse.name || receivingDetail.product_name || '未命名商品'; + const updateData = { + system_product_id: systemProductId, + product_name: productName, + product_snapshot: JSON.stringify({ + ...productSnapshot, + system_product_id: systemProductId, + product_name: productName, + store_id: productStoreId || productSnapshot.store_id || null, + store_name: stockWarehouse.store_stock?.store_remask || productSnapshot.store_name || null, + updated_at: new Date(), + }), + }; + + if (barcodes.length > 0) { + updateData.barcode = barcodes.join(';'); + } + if (stockWarehouse.gross_weight !== undefined && stockWarehouse.gross_weight !== null) { + updateData.weight = stockWarehouse.gross_weight; + } + if (stockWarehouse.enable_box_spec) { + updateData.boxes_per_pallet = stockWarehouse.quantity_per_box || receivingDetail.boxes_per_pallet || 0; + updateData.box_height = stockWarehouse.box_height || receivingDetail.box_height || 0; + updateData.box_width = stockWarehouse.box_width || receivingDetail.box_width || 0; + updateData.box_length = stockWarehouse.box_length || receivingDetail.box_length || 0; + } + + await ctx.model.ReceivingDetail.update(updateData, { + where: { id: detailId }, + }); + + await this.updateReceivingStats(receivingDetail.receiving_id); + + return { + code: 200, + message: '绑定商品成功', + data: { + detail_id: detailId, + receiving_id: receivingDetail.receiving_id, + system_product_id: systemProductId, + product_name: productName, + }, + }; + } catch (error) { + ctx.logger.error('绑定收货单明细商品失败:', error); + return { + code: 500, + message: `绑定商品失败: ${error.message}`, + }; + } + } + async updateDetail(data) { const ctx = this.ctx; const { id, ...updateData } = data; @@ -1778,6 +2124,270 @@ class ReceivingService extends Service { throw error; } } + formatReportDate(value) { + if (!value) { + return ''; + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + return ''; + } + + return date.toLocaleString('zh-CN', { hour12: false }); + } + + buildCompletionReportSheets({ + receiving, + operator = {}, + stats = {}, + detailImageMap = new Map(), + receivingImages = [], + }) { + const details = Array.isArray(receiving && receiving.details) + ? receiving.details.map(item => (typeof item.toJSON === 'function' ? item.toJSON() : item)) + : []; + const mainImageUrls = (Array.isArray(receivingImages) ? receivingImages : []) + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + + const rows = []; + const embeddedImages = []; + const styledRows = []; + const summaryImageColumnIndex = 3; + const detailColumns = [ + '序号', '商品名称', '条码', + '数量', '重量', '箱数', '托数', + '批次号', '生产日期', '到期日期', '备注', '图片链接', '图片', + ]; + const detailImageColumnIndex = detailColumns.length; + const maxDetailImageCount = Math.max( + 1, + ...details.map(detail => { + const detailImages = Array.isArray(detailImageMap.get(String(detail.id))) + ? detailImageMap.get(String(detail.id)) + : []; + const detailImageUrls = detailImages + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + return detailImageUrls.length; + }) + ); + + const buildLinkCell = urls => { + const normalizedUrls = (Array.isArray(urls) ? urls : [ urls ]) + .map(item => String(item || '').trim()) + .filter(Boolean); + + if (normalizedUrls.length === 0) { + return ''; + } + + return { + text: normalizedUrls.join('\n'), + hyperlink: normalizedUrls[0], + tooltip: normalizedUrls.join('\n'), + }; + }; + + const pushReportRow = (cells = [], options = {}) => { + rows.push(cells); + const rowIndex = rows.length; + const maxCol = Math.max(Number(options.toCol || cells.length || 1), 1); + + if (options.style || options.height) { + styledRows.push({ + row: rowIndex, + fromCol: Math.max(Number(options.fromCol || 1), 1), + toCol: maxCol, + style: options.style || null, + height: options.height || null, + }); + } + + return rowIndex; + }; + + pushReportRow([]); + + [ + [ '收货单ID', receiving && receiving.id ], + [ '收货单号', receiving && receiving.receiving_number ], + [ '状态', receiving && receiving.status ], + [ '货主', receiving && receiving.store_name ], + [ '仓库ID', receiving && receiving.warehouse_id ], + [ '来货方式', receiving && receiving.delivery_method ], + [ '车牌号', receiving && receiving.license_plate ], + [ '物流单号', receiving && receiving.tracking_number ], + [ '总明细数', stats.total_details || details.length ], + [ '已匹配明细数', stats.matched_details || 0 ], + [ '未匹配明细数', stats.unmatched_details || 0 ], + [ '总数量', stats.total_quantity || 0 ], + [ '总箱数', receiving && receiving.total_boxes ], + [ '总托盘数', receiving && receiving.total_pallets ], + [ '完成人', operator.employees_name || operator.real_name || operator.name || '' ], + [ '完成时间', this.formatReportDate(receiving && receiving.receiving_end_time) ], + [ '备注', receiving && receiving.remark ], + ].forEach(([ field, value ]) => { + pushReportRow([ field, value ], { + toCol: 2, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + }); + + if (mainImageUrls.length === 0) { + pushReportRow([ '收货图片', '无' ], { + toCol: 2, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + } else { + const summaryLinkCell = buildLinkCell(mainImageUrls); + const imagePlaceholders = Array(Math.max(mainImageUrls.length, 1)).fill(''); + const firstImageRowIndex = pushReportRow([ '收货图片', summaryLinkCell, ...imagePlaceholders ], { + toCol: 2 + imagePlaceholders.length, + height: 88, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + + mainImageUrls.forEach((imageUrl, index) => { + embeddedImages.push({ + row: firstImageRowIndex, + col: summaryImageColumnIndex + index, + url: imageUrl, + width: 96, + height: 96, + fallbackText: `收货图片${index + 1}`, + }); + }); + } + + pushReportRow([]); + + pushReportRow(detailColumns, { + toCol: detailColumns.length, + height: 22, + style: { + font: { bold: true, color: { argb: 'FF1F1F1F' } }, + fill: { + type: 'pattern', + pattern: 'solid', + fgColor: { argb: 'FFD9EAF7' }, + }, + alignment: { horizontal: 'center', vertical: 'middle', wrapText: true }, + }, + }); + + if (details.length === 0) { + pushReportRow([ '', '', '无明细' ], { + toCol: detailColumns.length, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + } else { + details.forEach((detail, index) => { + const detailImages = Array.isArray(detailImageMap.get(String(detail.id))) + ? detailImageMap.get(String(detail.id)) + : []; + const detailImageUrls = detailImages + .map(item => (item && (item.url || item.file_url || (item.file && item.file.file_url))) || '') + .filter(Boolean); + const imageSlotCount = Math.max(detailImageUrls.length, 1); + const linkCell = buildLinkCell(detailImageUrls); + + const rowCells = [ + index + 1, + detail.product_name || '', + detail.barcode || '', + detail.actual_quantity || 0, + detail.weight || 0, + detail.box_quantity || 0, + detail.pallet_quantity || 0, + detail.batch_number || '', + this.formatReportDate(detail.production_date), + this.formatReportDate(detail.expiry_date), + detail.remark || '', + linkCell, + ...Array(imageSlotCount).fill(''), + ]; + + const targetRow = pushReportRow(rowCells, { + toCol: rowCells.length, + height: detailImageUrls.length > 0 ? 88 : null, + style: { + alignment: { vertical: 'top', wrapText: true }, + }, + }); + + detailImageUrls.forEach((imageUrl, imageIndex) => { + embeddedImages.push({ + row: targetRow, + col: detailImageColumnIndex + imageIndex, + url: imageUrl, + width: 96, + height: 96, + fallbackText: `图片${imageIndex + 1}`, + }); + }); + }); + } + + return [ + { + name: '收货清单', + rows, + widths: [ + 16, 28, 18, 10, 10, 10, 10, 18, 18, 18, 24, 42, 18, + ...Array(Math.max(maxDetailImageCount - 1, 0)).fill(18), + ], + embeddedImages, + styledRows, + skipHeader: true, + forceExcelJs: true, + }, + ]; + } + + async uploadCompletionExcelReport({ + receiving, + operator = {}, + stats = {}, + detailImageMap = new Map(), + receivingImages = [], + }) { + const { ctx } = this; + const excelService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.excel; + + if (!receiving || !receiving.id || !excelService || typeof excelService.generateAndUpload !== 'function') { + return null; + } + + const receivingNumber = String(receiving.receiving_number || receiving.id).replace(/[\\/:*?"<>|]/g, '_'); + + return await excelService.generateAndUpload({ + filename: `收货完成_${receivingNumber}.xlsx`, + dir: `exports/receiving/completed/${ctx.user.store_id || receiving.warehouse_id || 'common'}`, + category: 'document', + saveRecord: true, + businessType: 'receivingReport', + businessId: receiving.id, + expireDays: 90, + sheets: this.buildCompletionReportSheets({ + receiving, + operator, + stats, + detailImageMap, + receivingImages, + }), + }); + } + /** * 完成收货单:校验明细、更新状态并写入库存。 * @param {Object} data 请求体 @@ -1806,7 +2416,11 @@ class ReceivingService extends Service { model: ctx.model.ReceivingDetail, as: 'details', required: false, - attributes: ['id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight'], + attributes: [ + 'id', 'system_product_id', 'product_name', 'barcode', 'actual_quantity', 'weight', + 'box_quantity', 'pallet_quantity', 'receiving_status', 'storage_status', + 'batch_number', 'production_date', 'expiry_date', 'remark', + ], }], }); @@ -1820,6 +2434,7 @@ class ReceivingService extends Service { // 2. 状态检查 if (receiving.status === 'completed') { + await transaction.rollback(); return { code: 200, message: '收货单已完成', @@ -1846,10 +2461,8 @@ class ReceivingService extends Service { // 4. 校验所有明细的完成条件 const invalidDetails = []; const unmatchedDetails = receiving.details.filter(d => !d.system_product_id); - - // 只有存在未绑定系统商品的明细时,才需要查询照片 - const detailsIds = receiving.details.map(item => item.id); + const images = await ctx.model.FileReference.findAll({ where: { business_type: 'receivingItem', @@ -1857,41 +2470,56 @@ class ReceivingService extends Service { [Op.in]: detailsIds, }, }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], transaction, }); - // 按照业务ID分组照片 const imageMap = new Map(); images.forEach(image => { const businessId = String(image.business_id).trim(); if (!imageMap.has(businessId)) { imageMap.set(businessId, []); } - imageMap.get(businessId).push(image); + + imageMap.get(businessId).push({ + id: image.file_id, + url: (image.file && image.file.file_url) || image.file_url || image.url || image.file_path || '', + }); }); - console.log('imageMap', imageMap); + const receivingImages = await ctx.model.FileReference.findAll({ + where: { + business_type: 'receiving', + business_id: id, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: false, + }], + transaction, + }); + + const receivingImageList = receivingImages + .map(image => ({ + id: image.file_id, + url: (image.file && image.file.file_url) || image.file_url || image.url || '', + })) + .filter(item => item.url); - // 检查未绑定系统商品的明细 for (const detail of receiving.details) { - // 先检查是否有对应的图片数组 const businessId = String(detail.id).trim(); - const imageArray = imageMap.get(businessId); - - // 这里的关键修复:不仅要检查数组是否存在且有长度,还要检查数组中的元素是否有实际的数据 - const hasPhoto = imageArray && - imageArray.length > 0 && - imageArray.some(img => { - // 检查图片对象是否有实际的数据 - return img.dataValues || - img.file_path || - img.url || - (img._options && Object.keys(img._options).length > 0); - }); + const imageArray = imageMap.get(businessId) || []; + const hasPhoto = imageArray.some(img => !!(img && img.url)); const hasBarcode = !!detail.barcode && detail.barcode.trim() !== ''; - const hasWeight = detail.weight > 0; - const hasCount = detail.actual_quantity > 0; - console.log('detailInfo', hasBarcode, hasWeight, hasCount); + const hasWeight = Number(detail.weight || 0) > 0; + const hasCount = Number(detail.actual_quantity || 0) > 0; if (!hasPhoto || !hasBarcode || !hasWeight || !hasCount) { const itemName = detail.product_name || '未命名商品'; @@ -1929,7 +2557,6 @@ class ReceivingService extends Service { }; } - // 7. 获取操作人信息 const operator = ctx.user; @@ -1941,7 +2568,6 @@ class ReceivingService extends Service { updated_at: now, }; - // 更新备注 if (remark) { const remarkPrefix = receiving.remark ? `${receiving.remark}\n` : ''; updateData.remark = `${remarkPrefix}【完成收货】${now.toLocaleString()} ${operator.employees_name} ${remark}`; @@ -1963,30 +2589,60 @@ class ReceivingService extends Service { total_quantity: receiving.details.reduce((sum, d) => sum + (d.actual_quantity || 0), 0), }; - if (stats.matched_details > 0) { - // 通知 - await ctx.service.systems.notification.send({ - type: 'system', - title: `收货单${receiving.receiving_number}已完成`, - content: `收货单${receiving.receiving_number}已完成,匹配商品${stats.matched_details}件,未匹配商品${stats.unmatched_details}件。`, - bussinessType: 'receiving', - bussinessId: receiving.id, + // 10. 提交事务 + await transaction.commit(); + + const receivingSnapshot = { + ...(typeof receiving.toJSON === 'function' ? receiving.toJSON() : receiving), + ...updateData, + }; + + let completionReport = null; + try { + completionReport = await this.uploadCompletionExcelReport({ + receiving: receivingSnapshot, + operator, + stats, + detailImageMap: imageMap, + receivingImages: receivingImageList, + }); + } catch (reportError) { + ctx.logger.error(`收货完成报表上传失败: ${reportError.message}`, { + receiving_id: id, + warehouseId, + error: reportError.stack, }); } - // 11. 提交事务 - await transaction.commit(); + if (stats.matched_details > 0) { + try { + await ctx.service.systems.notification.send({ + type: 'system', + title: `收货单${receiving.receiving_number}已完成`, + content: `收货单${receiving.receiving_number}已完成,匹配商品${stats.matched_details}件,未匹配商品${stats.unmatched_details}件。`, + bussinessType: 'receiving', + bussinessId: receiving.id, + }); + } catch (notifyError) { + ctx.logger.error(`收货完成通知发送失败: ${notifyError.message}`, { + receiving_id: id, + warehouseId, + error: notifyError.stack, + }); + } + } - // 记录操作日志 ctx.logger.info('收货单已完成', { receiving_id: id, receiving_number: receiving.receiving_number, completed_by: operator.employees_name, stats, + completion_report: completionReport && completionReport.url, }); return { success: true, + code: 200, message: '收货完成成功', data: { receiving_id: id, @@ -1994,12 +2650,16 @@ class ReceivingService extends Service { completed_at: now, completed_by: operator.employees_name, stats, + completion_report: completionReport ? { + fileKey: completionReport.fileKey || '', + url: completionReport.url || completionReport.cdnUrl || completionReport.cosUrl || '', + fileRecord: completionReport.fileRecord || null, + } : null, }, }; } catch (error) { - // 12. 回滚事务 - if (transaction) { + if (transaction && !transaction.finished) { await transaction.rollback(); } @@ -2009,7 +2669,6 @@ class ReceivingService extends Service { error: error.stack, }); - // 如果是已知的业务错误,返回具体信息 if (error.code && error.code.startsWith('DETAIL_')) { return { success: false, @@ -2018,7 +2677,6 @@ class ReceivingService extends Service { }; } - // 其他错误 return { success: false, code: 'SYSTEM_ERROR', diff --git a/app/service/systems/store_warehouse.js b/app/service/systems/store_warehouse.js new file mode 100644 index 0000000..a73c73b --- /dev/null +++ b/app/service/systems/store_warehouse.js @@ -0,0 +1,1441 @@ +'use strict'; + +const crypto = require('node:crypto'); +const Service = require('egg').Service; + +const SIGN_TEMP_EXPIRE_SECONDS = 600; +const AUTH_STATUS_LABELS = Object.freeze({ + 1: '申请中', + 2: '已通过', + 3: '已拒绝', + 4: '已解除', + 5: '已过期', +}); +const POLICY_CONFIG_FIELD_RULES = Object.freeze({ + receive_mode: { + type: 'enum', + values: [ 'standard', 'strict', 'manual' ], + }, + sku_visibility: { + type: 'enum', + values: [ 'all', 'whitelist', 'blacklist' ], + }, + auto_allocate_bin: { + type: 'flag', + }, + allow_mix_batch: { + type: 'flag', + }, + allow_temp_storage: { + type: 'flag', + }, + max_daily_inbound: { + type: 'integer', + min: 0, + max: 1000000, + }, + remark: { + type: 'string', + maxLength: 200, + }, +}); + +class SettingStoreWarehouseService extends Service { + createError(message, code = 500) { + const error = new Error(message); + error.code = code; + return error; + } + + getCurrentStoreId() { + const storeId = Number(this.ctx.user && this.ctx.user.store_id); + if (!Number.isFinite(storeId) || storeId <= 0) { + throw this.createError('未识别到当前主体,无法操作签约关系', 400); + } + return storeId; + } + + getCurrentAccountId() { + const accountId = Number(this.ctx.user && this.ctx.user.id); + if (!Number.isFinite(accountId) || accountId <= 0) { + throw this.createError('未识别到当前登录账号', 401); + } + return accountId; + } + + toPositiveNumber(value, fieldName, options = {}) { + const { allowEmpty = false } = options; + if (allowEmpty && (value === undefined || value === null || value === '')) { + return null; + } + + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + return num; + } + + normalizePage(value, fieldName, defaultValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num <= 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.min(Math.floor(num), maxValue); + } + + normalizeStatusFlag(value, fieldName, defaultValue = null) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (num === 0 || num === 1) { + return num; + } + throw this.createError(`${fieldName} 参数不合法`, 400); + } + + normalizeAuthStatus(value) { + if (value === undefined || value === null || value === '') { + return null; + } + const num = Number(value); + if ([ 1, 2, 3, 4, 5 ].includes(num)) { + return num; + } + throw this.createError('auth_status 参数不合法', 400); + } + + normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num < 0) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.floor(num); + } + + normalizeText(value, fieldName, maxLength = 500) { + if (value === undefined || value === null) { + return null; + } + const normalized = String(value).trim(); + if (normalized.length > maxLength) { + throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400); + } + return normalized; + } + + normalizeIntegerRange(value, fieldName, defaultValue, minValue, maxValue) { + if (value === undefined || value === null || value === '') { + return defaultValue; + } + const num = Number(value); + if (!Number.isFinite(num) || num < minValue || num > maxValue) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return Math.floor(num); + } + + normalizeEmail(value) { + const email = this.normalizeText(value, 'email', 100); + if (!email) { + return null; + } + + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + throw this.createError('email 参数不合法', 400); + } + return email; + } + + normalizePolicyConfig(value, fieldName = 'policy_config', options = {}) { + const { allowEmpty = false } = options; + if (value === undefined || value === null || value === '') { + if (allowEmpty) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const parsed = typeof value === 'string' ? (() => { + try { + return JSON.parse(value); + } catch { + throw this.createError(`${fieldName} 不是合法JSON`, 400); + } + })() : value; + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw this.createError(`${fieldName} 必须为对象`, 400); + } + + const allowedKeys = Object.keys(POLICY_CONFIG_FIELD_RULES); + const unsupportedKeys = Object.keys(parsed).filter(key => !allowedKeys.includes(key)); + if (unsupportedKeys.length) { + throw this.createError(`${fieldName} 包含不支持字段: ${unsupportedKeys.join(', ')};仅允许字段: ${allowedKeys.join(', ')}`, 400); + } + + const normalized = {}; + for (const [ key, rawValue ] of Object.entries(parsed)) { + const rule = POLICY_CONFIG_FIELD_RULES[key]; + if (!rule) { + continue; + } + + if (rule.type === 'enum') { + const valueText = String(rawValue || '').trim(); + if (!rule.values.includes(valueText)) { + throw this.createError(`${fieldName}.${key} 参数不合法`, 400); + } + normalized[key] = valueText; + continue; + } + + if (rule.type === 'flag') { + if (rawValue === true || rawValue === 1 || rawValue === '1') { + normalized[key] = 1; + continue; + } + if (rawValue === false || rawValue === 0 || rawValue === '0') { + normalized[key] = 0; + continue; + } + throw this.createError(`${fieldName}.${key} 参数不合法`, 400); + } + + if (rule.type === 'integer') { + const num = Number(rawValue); + if (!Number.isFinite(num) || num < rule.min || num > rule.max) { + throw this.createError(`${fieldName}.${key} 参数不合法`, 400); + } + normalized[key] = Math.floor(num); + continue; + } + + if (rule.type === 'string') { + const text = this.normalizeText(rawValue, `${fieldName}.${key}`, rule.maxLength); + normalized[key] = text || ''; + } + } + + return normalized; + } + + getPolicyConfigCacheKey(contractId) { + return `store_warehouse:policy:${contractId}`; + } + + async hasPolicyConfigColumn() { + if (this._hasPolicyConfigColumn !== undefined) { + return this._hasPolicyConfigColumn; + } + + try { + const [ columns ] = await this.app.model.query( + "SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'" + ); + this._hasPolicyConfigColumn = Array.isArray(columns) && columns.length > 0; + } catch { + this._hasPolicyConfigColumn = false; + } + return this._hasPolicyConfigColumn; + } + + async loadPolicyConfigByContractId(contractId, transaction = null) { + const normalizedId = Number(contractId || 0); + if (normalizedId <= 0) { + return null; + } + + if (await this.hasPolicyConfigColumn()) { + const [ rows ] = await this.app.model.query( + 'SELECT policy_config FROM wms_store_warehouse WHERE id = :id LIMIT 1', + { + replacements: { id: normalizedId }, + transaction, + } + ); + const row = Array.isArray(rows) ? rows[0] : null; + const raw = row ? row.policy_config : null; + + if (raw === null || raw === undefined || raw === '') { + return null; + } + if (typeof raw === 'object') { + return raw; + } + + try { + return JSON.parse(raw); + } catch { + return null; + } + } + + const cached = await this.app.getCacheAsync(this.getPolicyConfigCacheKey(normalizedId)); + return cached && typeof cached === 'object' ? cached : null; + } + + async savePolicyConfigByContractId(contractId, policyConfig, transaction = null) { + const normalizedId = Number(contractId || 0); + if (normalizedId <= 0) { + throw this.createError('id 参数不能为空', 400); + } + + if (await this.hasPolicyConfigColumn()) { + await this.app.model.query( + 'UPDATE wms_store_warehouse SET policy_config = :policy_config, updated_at = NOW() WHERE id = :id', + { + replacements: { + id: normalizedId, + policy_config: JSON.stringify(policyConfig), + }, + transaction, + } + ); + return; + } + + await this.app.setCacheAsync(this.getPolicyConfigCacheKey(normalizedId), policyConfig, 86400 * 30); + } + + ensureWarehouseSubject(currentSubject) { + if (!currentSubject || !currentSubject.isWarehouse) { + throw this.createError('仅仓库主体可维护奇门接口配置', 403); + } + } + + resolveRelationId(data = {}) { + return this.toPositiveNumber( + data.id !== undefined ? data.id : (data.contract_id !== undefined ? data.contract_id : data.relation_id), + 'id', + { allowEmpty: true } + ); + } + + normalizeDate(value, fieldName, options = {}) { + const { allowNull = true } = options; + if (value === undefined || value === null || value === '') { + if (allowNull) { + return null; + } + throw this.createError(`${fieldName} 参数不能为空`, 400); + } + + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + throw this.createError(`${fieldName} 参数不合法`, 400); + } + return date; + } + + normalizeSignAction(value) { + if (value === undefined || value === null || value === '') { + return ''; + } + + const action = String(value).trim(); + if ([ 'preview', 'confirm' ].includes(action)) { + return action; + } + throw this.createError('action 参数不合法', 400); + } + + normalizeTempCode(value) { + const code = String(value || '').trim().toUpperCase(); + if (!code) { + throw this.createError('temp_code 参数不能为空', 400); + } + return code; + } + + getTempCodeCacheKey(tempCode) { + return `store_warehouse:sign:${tempCode}`; + } + + createTempCode() { + return crypto.randomBytes(6).toString('hex').toUpperCase(); + } + + pickRemaskField(currentSubject) { + return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask'; + } + + resolveRemaskValue(data, currentSubject) { + const raw = data.remask !== undefined + ? data.remask + : (currentSubject && currentSubject.isWarehouse ? data.store_remask : data.warehouse_remask); + return this.normalizeText(raw, 'remask', 50); + } + + buildCurrentRemaskPatch(data, currentSubject) { + const remask = this.resolveRemaskValue(data, currentSubject); + if (remask === null) { + return {}; + } + + return { + [this.pickRemaskField(currentSubject)]: remask, + }; + } + + requireCurrentRemaskPatch(data, currentSubject) { + const patch = this.buildCurrentRemaskPatch(data, currentSubject); + if (!Object.keys(patch).length) { + throw this.createError('remask 参数不能为空', 400); + } + return patch; + } + + async saveTempSignPayload(payload) { + const now = Date.now(); + const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString(); + const tempCode = this.createTempCode(); + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { + ...payload, + expires_at: expiresAt, + }, SIGN_TEMP_EXPIRE_SECONDS); + return { + tempCode, + expiresAt, + expiresIn: SIGN_TEMP_EXPIRE_SECONDS, + }; + } + + async getTempSignPayload(tempCode) { + const normalizedCode = this.normalizeTempCode(tempCode); + const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode)); + if (!payload) { + throw this.createError('临时码无效或已过期', 404); + } + return { + tempCode: normalizedCode, + payload, + }; + } + + async clearTempSignPayload(tempCode) { + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + if (cacheRedis && cacheRedis.del) { + await cacheRedis.del(this.getTempCodeCacheKey(tempCode)); + return; + } + await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1); + } + + buildTempSignView(tempCode, payload, currentSubject) { + const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]; + const currentSubjectId = Number(currentSubject && currentSubject.id); + const expiresAt = payload.expires_at || null; + const expiresMs = expiresAt ? new Date(expiresAt).getTime() : 0; + + return { + mode: 'preview', + temp_code: tempCode, + expires_at: expiresAt, + expires_in: expiresMs ? Math.max(0, Math.ceil((expiresMs - Date.now()) / 1000)) : 0, + is_participant: participantIds.includes(currentSubjectId), + can_confirm: currentSubjectId > 0 && currentSubjectId === Number(payload.counterparty_id || 0), + initiator: { + id: Number(payload.initiator_subject_id || 0), + role: payload.initiator_role || '', + name: payload.initiator_name || '', + }, + counterparty: { + id: Number(payload.counterparty_id || 0), + role: payload.counterparty_role || '', + name: payload.counterparty_name || '', + }, + sign_info: { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_start: payload.auth_start || null, + auth_end: payload.auth_end || null, + print_quantity: Number(payload.print_quantity || 0), + apply_reason: payload.apply_reason || '', + remask: payload.remask || '', + }, + }; + } + + async getCurrentSubject() { + const { ctx } = this; + const storeId = this.getCurrentStoreId(); + const subject = await ctx.model.Store.findOne({ + where: { + id: storeId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!subject) { + throw this.createError('当前主体不存在', 404); + } + + return { + id: Number(subject.id), + company_name: subject.company_name || '', + project: subject.project || '', + isWarehouse: subject.project === 'warehouse', + status: Number(subject.status || 0), + }; + } + + async getCounterparty(counterpartyId, expectedRole) { + const { ctx } = this; + const counterparty = await ctx.model.Store.findOne({ + where: { + id: counterpartyId, + }, + attributes: [ 'id', 'company_name', 'project', 'status' ], + }); + + if (!counterparty) { + throw this.createError('签约对象不存在', 404); + } + + const isWarehouse = counterparty.project === 'warehouse'; + if (expectedRole === 'warehouse' && !isWarehouse) { + throw this.createError('目标对象不是仓库主体,无法签约', 400); + } + if (expectedRole === 'store' && isWarehouse) { + throw this.createError('目标对象不是货主主体,无法签约', 400); + } + + return counterparty; + } + + buildListWhere(data, currentSubject) { + const where = {}; + + if (currentSubject.isWarehouse) { + where.warehouse_id = currentSubject.id; + } else { + where.store_id = currentSubject.id; + } + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } + + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true }); + if (counterpartyId) { + if (currentSubject.isWarehouse) { + where.store_id = counterpartyId; + } else { + where.warehouse_id = counterpartyId; + } + } + + const authStatus = this.normalizeAuthStatus(data.auth_status); + if (authStatus !== null) { + where.auth_status = authStatus; + } + + const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null); + if (useStatus !== null) { + where.use_status = useStatus; + } + + return where; + } + + getRelationIncludes() { + const { ctx } = this; + return [ + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + { + model: ctx.model.Store, + as: 'warehouse', + attributes: [ 'id', 'company_name', 'project', 'status' ], + required: false, + }, + ]; + } + + getQimenContractCacheKey(appKey, customerId, warehouseCode) { + return `contract:${appKey}:${customerId}:${warehouseCode}`; + } + + async clearQimenContractCache(configs = []) { + const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null; + const keys = [ ...new Set(configs.map(item => { + const record = item && typeof item.get === 'function' + ? item.get({ plain: true }) + : item; + if (!record) { + return ''; + } + + const appKey = String(record.qimen_app_key || '').trim(); + const customerId = String(record.qimen_customer_id || '').trim(); + const warehouseCode = String(record.qimen_warehouse_code || '').trim(); + if (!appKey || !customerId || !warehouseCode) { + return ''; + } + return this.getQimenContractCacheKey(appKey, customerId, warehouseCode); + }).filter(Boolean)) ]; + + if (!keys.length) { + return; + } + + if (cacheRedis && cacheRedis.del) { + await cacheRedis.del(...keys); + return; + } + + await Promise.all(keys.map(key => this.app.setCacheAsync(key, null, 1).catch(() => null))); + } + + async getQimenInterfaceType(data = {}, options = {}) { + const { ctx } = this; + const { allowDisabled = false, transaction = null } = options; + const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); + const where = { + interface_category: 'QM_WMS', + }; + + if (!allowDisabled) { + where.is_enabled = 1; + } + if (interfaceTypeId) { + where.id = interfaceTypeId; + } + + const interfaceType = await ctx.model.InterfaceType.findOne({ + where, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + order: [[ 'id', 'ASC' ]], + transaction, + }); + + if (!interfaceType) { + throw this.createError(interfaceTypeId ? '指定的奇门接口类型不存在或不可用' : '未配置可用的奇门接口类型', 404); + } + + return interfaceType; + } + + serializeQimenConfig(config) { + if (!config) { + return null; + } + + const item = config && typeof config.get === 'function' + ? config.get({ plain: true }) + : config; + const interfaceType = item.interface_type || {}; + + return { + id: Number(item.id || 0), + interface_type_id: Number(item.interface_type_id || 0), + interface_code: interfaceType.interface_code || item.interface_code || '', + interface_name: interfaceType.interface_name || item.interface_name || '', + interface_category: interfaceType.interface_category || item.interface_category || '', + contract_id: Number(item.contract_id || 0), + warehouse_id: item.warehouse_id ? Number(item.warehouse_id) : null, + app_name: item.app_name || '', + qimen_app_key: item.qimen_app_key || '', + qimen_customer_id: item.qimen_customer_id || '', + qimen_warehouse_code: item.qimen_warehouse_code || '', + api_version: item.api_version || '', + sign_method: item.sign_method || '', + rate_limit: Number(item.rate_limit || 0), + timeout_seconds: Number(item.timeout_seconds || 0), + contact_person: item.contact_person || '', + contact_phone: item.contact_phone || '', + email: item.email || '', + is_enabled: Number(item.is_enabled || 0), + created_at: item.created_at || null, + updated_at: item.updated_at || null, + }; + } + + async getQimenConfigMap(contractIds = [], options = {}) { + const { ctx } = this; + const { allowDisabled = true, interfaceTypeId = null, transaction = null } = options; + const normalizedContractIds = [ ...new Set(contractIds.map(value => Number(value)).filter(value => Number.isFinite(value) && value > 0)) ]; + + if (!normalizedContractIds.length || !ctx.model.ApiApp || !ctx.model.InterfaceType) { + return new Map(); + } + + let interfaceTypeIds = []; + if (interfaceTypeId) { + interfaceTypeIds = [ Number(interfaceTypeId) ]; + } else { + const interfaceWhere = { + interface_category: 'QM_WMS', + }; + if (!allowDisabled) { + interfaceWhere.is_enabled = 1; + } + + const interfaceTypes = await ctx.model.InterfaceType.findAll({ + where: interfaceWhere, + attributes: [ 'id' ], + transaction, + }); + interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean); + } + + if (!interfaceTypeIds.length) { + return new Map(); + } + + const rows = await ctx.model.ApiApp.findAll({ + where: { + contract_id: normalizedContractIds, + interface_type_id: interfaceTypeIds, + }, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + transaction, + }); + + const configMap = new Map(); + for (const row of rows) { + const contractId = Number(row.contract_id || 0); + if (!contractId || configMap.has(contractId)) { + continue; + } + configMap.set(contractId, this.serializeQimenConfig(row)); + } + + return configMap; + } + + async getSingleQimenConfig(contractId, options = {}) { + const configMap = await this.getQimenConfigMap([ contractId ], options); + return configMap.get(Number(contractId)) || null; + } + + resolvePairIds(data, currentSubject) { + const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id'; + const rawCounterpartyId = data.counterparty_id !== undefined + ? data.counterparty_id + : (currentSubject.isWarehouse ? data.store_id : data.warehouse_id); + const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName); + + if (currentSubject.isWarehouse) { + return { + storeId: counterpartyId, + warehouseId: currentSubject.id, + counterpartyId, + }; + } + + return { + storeId: currentSubject.id, + warehouseId: counterpartyId, + counterpartyId, + }; + } + + serializeRelation(relation, currentSubject, qimenConfig = null) { + const item = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : (relation || {}); + const normalizedQimenConfig = qimenConfig !== null + ? qimenConfig + : (item.qimen_config ? this.serializeQimenConfig(item.qimen_config) : null); + + const authStatus = Number(item.auth_status || 0); + const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse); + const counterparty = currentIsWarehouse ? item.store : item.warehouse; + const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : ''); + const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : ''); + const counterpartyName = currentIsWarehouse ? storeName : warehouseName; + + let isAuthValid = false; + let remainingDays = 0; + if (authStatus === 2 && item.auth_start && item.auth_end) { + const now = Date.now(); + const start = new Date(item.auth_start).getTime(); + const end = new Date(item.auth_end).getTime(); + if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) { + isAuthValid = true; + remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24))); + } + } + + return { + id: Number(item.id || 0), + store_id: Number(item.store_id || 0), + store_name: storeName, + warehouse_id: Number(item.warehouse_id || 0), + warehouse_name: warehouseName, + counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0, + counterparty_name: counterpartyName, + current_subject_role: currentIsWarehouse ? 'warehouse' : 'store', + auth_status: authStatus, + auth_status_label: AUTH_STATUS_LABELS[authStatus] || '', + apply_reason: item.apply_reason || '', + review_comment: item.review_comment || '', + apply_time: item.apply_time || null, + review_time: item.review_time || null, + auth_start: item.auth_start || null, + auth_end: item.auth_end || null, + actual_end: item.actual_end || null, + print_quantity: Number(item.print_quantity || 0), + applied_by: item.applied_by ? Number(item.applied_by) : null, + reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null, + ended_by: item.ended_by ? Number(item.ended_by) : null, + remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''), + use_status: Number(item.use_status || 0), + policy_config: item.policy_config && typeof item.policy_config === 'object' ? item.policy_config : null, + is_auth_valid: isAuthValid, + remaining_days: remainingDays, + qimen_config: normalizedQimenConfig || null, + }; + } + + async findScopedRelation(data, currentSubject, transaction) { + const { ctx } = this; + const where = currentSubject.isWarehouse + ? { warehouse_id: currentSubject.id } + : { store_id: currentSubject.id }; + + const relationId = this.resolveRelationId(data); + if (relationId) { + where.id = relationId; + } else { + const pair = this.resolvePairIds(data, currentSubject); + where.store_id = pair.storeId; + where.warehouse_id = pair.warehouseId; + } + + const relation = await ctx.model.StoreWarehouse.findOne({ + where, + include: this.getRelationIncludes(), + transaction, + }); + + if (!relation) { + throw this.createError('签约关系不存在或无权限操作', 404); + } + + return relation; + } + + async list(data = {}) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const currentSubject = await this.getCurrentSubject(); + const page = this.normalizePage(data.page, 'page', 1, 1000000); + const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200); + const offset = (page - 1) * pageSize; + const where = this.buildListWhere(data, currentSubject); + const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : ''; + + if (keyword) { + where[Op.or] = [ + { store_remask: { [Op.like]: `%${keyword}%` } }, + { warehouse_remask: { [Op.like]: `%${keyword}%` } }, + { '$store.company_name$': { [Op.like]: `%${keyword}%` } }, + { '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } }, + ]; + } + + const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({ + where, + include: this.getRelationIncludes(), + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + offset, + limit: pageSize, + distinct: true, + }); + const qimenConfigMap = await this.getQimenConfigMap(rows.map(item => Number(item.id || 0)), { + allowDisabled: true, + }); + + return { + code: 200, + data: { + list: rows.map(item => this.serializeRelation(item, currentSubject, qimenConfigMap.get(Number(item.id || 0)) || null)), + total: Number(count || 0), + page, + page_size: pageSize, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + }, + }; + } + + async sign(data = {}) { + const action = this.normalizeSignAction(data.action || data.mode); + if (data.temp_code || data.tempCode || action === 'preview') { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode); + const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ] + .includes(Number(currentSubject.id)); + + if (!isParticipant) { + throw this.createError('当前主体无权使用该临时码', 403); + } + + if (action === 'preview' || data.preview === 1 || data.preview === '1') { + await transaction.rollback(); + return { + code: 200, + data: this.buildTempSignView(tempCode, payload, currentSubject), + }; + } + + if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) { + throw this.createError('需由对方主体确认后才可生效', 400); + } + + const relationPatch = { + store_id: Number(payload.store_id || 0), + warehouse_id: Number(payload.warehouse_id || 0), + auth_status: 2, + apply_reason: payload.apply_reason || '', + apply_time: payload.created_at ? new Date(payload.created_at) : new Date(), + print_quantity: Number(payload.print_quantity || 0), + review_time: new Date(), + auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(), + auth_end: payload.auth_end ? new Date(payload.auth_end) : null, + actual_end: null, + applied_by: Number(payload.initiated_by || 0) || accountId, + reviewed_by: accountId, + ended_by: null, + use_status: 1, + }; + + if (payload.store_remask !== undefined) { + relationPatch.store_remask = payload.store_remask; + } + if (payload.warehouse_remask !== undefined) { + relationPatch.warehouse_remask = payload.warehouse_remask; + } + Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject)); + + let relation = await ctx.model.StoreWarehouse.findOne({ + where: { + store_id: relationPatch.store_id, + warehouse_id: relationPatch.warehouse_id, + }, + transaction, + }); + const isCreate = !relation; + + if (relation) { + await relation.update(relationPatch, { transaction }); + } else { + relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction }); + } + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await this.clearTempSignPayload(tempCode); + await transaction.commit(); + + return { + code: 200, + data: { + mode: 'confirm', + temp_code: tempCode, + contract: this.serializeRelation(result, currentSubject, qimenConfig), + action: isCreate ? 'create' : 'update', + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + const currentSubject = await this.getCurrentSubject(); + const accountId = this.getCurrentAccountId(); + const pair = this.resolvePairIds(data, currentSubject); + const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse'); + const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date(); + const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true }); + if (authEnd && authStart.getTime() > authEnd.getTime()) { + throw this.createError('auth_end 不能早于 auth_start', 400); + } + + const remask = this.resolveRemaskValue(data, currentSubject); + const payload = { + initiated_by: accountId, + initiator_subject_id: currentSubject.id, + initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store', + initiator_name: currentSubject.company_name, + counterparty_id: Number(counterparty.id || 0), + counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse', + counterparty_name: counterparty.company_name || '', + store_id: pair.storeId, + warehouse_id: pair.warehouseId, + auth_start: authStart.toISOString(), + auth_end: authEnd ? authEnd.toISOString() : null, + print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0), + apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000), + remask: remask || '', + created_at: new Date().toISOString(), + ...this.buildCurrentRemaskPatch(data, currentSubject), + }; + + const signPayload = await this.saveTempSignPayload(payload); + + return { + code: 200, + data: { + mode: 'initiate', + temp_code: signPayload.tempCode, + expires_at: signPayload.expiresAt, + expires_in: signPayload.expiresIn, + can_confirm: false, + current_subject: { + store_id: currentSubject.id, + company_name: currentSubject.company_name, + role: currentSubject.isWarehouse ? 'warehouse' : 'store', + }, + counterparty: { + id: Number(counterparty.id || 0), + company_name: counterparty.company_name || '', + role: currentSubject.isWarehouse ? 'store' : 'warehouse', + }, + }, + }; + } + + async rename(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const relationPatch = this.requireCurrentRemaskPatch(data, currentSubject); + + await relation.update(relationPatch, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject, qimenConfig), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async getPolicyConfig(data = {}) { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + }); + const policyConfig = await this.loadPolicyConfigByContractId(relation.id); + + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + policy_config: policyConfig, + contract: this.serializeRelation(relation, currentSubject, qimenConfig), + }, + }; + } + + async savePolicyConfig(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + this.ensureWarehouseSubject(currentSubject); + const policyConfig = this.normalizePolicyConfig( + data.policy_config !== undefined ? data.policy_config : data.policy + ); + await this.savePolicyConfigByContractId(relation.id, policyConfig, transaction); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + policy_config: policyConfig, + contract: this.serializeRelation(result, currentSubject, qimenConfig), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async listQimenConfig(data = {}) { + const { ctx } = this; + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject); + const interfaceTypeId = this.toPositiveNumber(data.interface_type_id, 'interface_type_id', { allowEmpty: true }); + + const interfaceWhere = { + interface_category: 'QM_WMS', + }; + if (interfaceTypeId) { + interfaceWhere.id = interfaceTypeId; + } + + const interfaceTypes = await ctx.model.InterfaceType.findAll({ + where: interfaceWhere, + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + order: [[ 'id', 'ASC' ]], + }); + const interfaceTypeIds = interfaceTypes.map(item => Number(item.id)).filter(Boolean); + + if (!interfaceTypeIds.length) { + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + contract: this.serializeRelation(relation, currentSubject, null), + list: [], + total: 0, + }, + }; + } + + const rows = await ctx.model.ApiApp.findAll({ + where: { + contract_id: Number(relation.id || 0), + interface_type_id: interfaceTypeIds, + }, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]], + }); + + const list = rows.map(item => this.serializeQimenConfig(item)); + const primaryQimenConfig = list.length ? list[0] : null; + + return { + code: 200, + data: { + contract_id: Number(relation.id || 0), + contract: this.serializeRelation(relation, currentSubject, primaryQimenConfig), + list, + total: list.length, + }, + }; + } + + async saveQimenConfig(data = {}) { + const { ctx, app } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + this.ensureWarehouseSubject(currentSubject); + const interfaceType = await this.getQimenInterfaceType(data, { transaction }); + const qimenAppKey = this.normalizeText(data.qimen_app_key, 'qimen_app_key', 100); + if (!qimenAppKey) { + throw this.createError('qimen_app_key 参数不能为空', 400); + } + const qimenCustomerId = this.normalizeText(data.qimen_customer_id, 'qimen_customer_id', 100); + if (!qimenCustomerId) { + throw this.createError('qimen_customer_id 参数不能为空', 400); + } + const qimenWarehouseCode = this.normalizeText(data.qimen_warehouse_code, 'qimen_warehouse_code', 100); + if (!qimenWarehouseCode) { + throw this.createError('qimen_warehouse_code 参数不能为空', 400); + } + + const relationPlain = relation && typeof relation.get === 'function' + ? relation.get({ plain: true }) + : relation; + const defaultAppName = [ + relationPlain && relationPlain.store_remask ? relationPlain.store_remask : currentSubject.company_name, + relationPlain && relationPlain.warehouse_remask + ? relationPlain.warehouse_remask + : (relationPlain && relationPlain.warehouse && relationPlain.warehouse.company_name ? relationPlain.warehouse.company_name : `contract-${relation.id}`), + '奇门接口', + ].filter(Boolean).join('-').slice(0, 200); + const appName = this.normalizeText(data.app_name, 'app_name', 200) || defaultAppName; + const apiVersion = this.normalizeText(data.api_version, 'api_version', 50) || '1.0'; + const signMethod = (this.normalizeText(data.sign_method, 'sign_method', 50) || 'md5').toLowerCase(); + if (![ 'md5', 'hmac', 'sha256' ].includes(signMethod)) { + throw this.createError('sign_method 参数不合法', 400); + } + + const rateLimit = this.normalizeIntegerRange(data.rate_limit, 'rate_limit', 1000, 1, 100000); + const timeoutSeconds = this.normalizeIntegerRange(data.timeout_seconds, 'timeout_seconds', 30, 1, 300); + const contactPerson = this.normalizeText(data.contact_person, 'contact_person', 100); + const contactPhone = this.normalizeText(data.contact_phone, 'contact_phone', 20); + const email = this.normalizeEmail(data.email); + const isEnabled = this.normalizeStatusFlag(data.is_enabled, 'is_enabled', 1); + + const where = { + interface_type_id: Number(interfaceType.id || 0), + contract_id: Number(relation.id || 0), + }; + let config = await ctx.model.ApiApp.findOne({ + where, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + transaction, + }); + + const { Op } = app.Sequelize; + const duplicateWhere = { + interface_type_id: Number(interfaceType.id || 0), + qimen_app_key: qimenAppKey, + qimen_customer_id: qimenCustomerId, + }; + if (config && config.id) { + duplicateWhere.id = { [Op.ne]: config.id }; + } + const duplicateConfig = await ctx.model.ApiApp.findOne({ + where: duplicateWhere, + attributes: [ 'id', 'contract_id' ], + transaction, + }); + if (duplicateConfig) { + throw this.createError('该奇门 AppKey 和客户ID 已绑定其他签约关系', 409); + } + + const configPayload = { + app_name: appName, + interface_type_id: Number(interfaceType.id || 0), + contract_id: Number(relation.id || 0), + warehouse_id: relation.warehouse_id ? Number(relation.warehouse_id) : null, + qimen_app_key: qimenAppKey, + qimen_customer_id: qimenCustomerId, + qimen_warehouse_code: qimenWarehouseCode, + api_version: apiVersion, + sign_method: signMethod, + rate_limit: rateLimit, + timeout_seconds: timeoutSeconds, + contact_person: contactPerson || null, + contact_phone: contactPhone || null, + email, + is_enabled: isEnabled, + }; + + const previousConfig = config ? this.serializeQimenConfig(config) : null; + const action = config ? 'update' : 'create'; + if (config) { + await config.update(configPayload, { transaction }); + } else { + config = await ctx.model.ApiApp.create(configPayload, { transaction }); + } + + const savedConfig = await ctx.model.ApiApp.findByPk(config.id, { + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + transaction, + }); + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = this.serializeQimenConfig(savedConfig); + + await transaction.commit(); + await this.clearQimenContractCache([ previousConfig, qimenConfig ]).catch(error => { + ctx.logger.warn('[storeWarehouse.saveQimenConfig] 清理奇门缓存失败: %s', error.message); + }); + + return { + code: 200, + data: { + action, + contract: this.serializeRelation(result, currentSubject, qimenConfig), + qimen_config: qimenConfig, + }, + }; + } catch (error) { + await transaction.rollback(); + if (error && error.name === 'SequelizeUniqueConstraintError') { + throw this.createError('奇门接口配置已存在,请检查应用名或 AppKey / 客户ID 是否重复', 409); + } + if (error && error.name === 'SequelizeValidationError') { + const message = error.errors && error.errors.length ? error.errors[0].message : '奇门接口配置参数校验失败'; + throw this.createError(message, 400); + } + throw error; + } + } + + async deleteQimenConfig(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + this.ensureWarehouseSubject(currentSubject); + const interfaceType = await this.getQimenInterfaceType(data, { + allowDisabled: true, + transaction, + }); + const config = await ctx.model.ApiApp.findOne({ + where: { + contract_id: Number(relation.id || 0), + interface_type_id: Number(interfaceType.id || 0), + }, + include: [ + { + model: ctx.model.InterfaceType, + as: 'interface_type', + attributes: [ 'id', 'interface_code', 'interface_name', 'interface_category', 'is_enabled' ], + required: false, + }, + ], + transaction, + }); + + if (!config) { + throw this.createError('奇门接口配置不存在', 404); + } + + const removedConfig = this.serializeQimenConfig(config); + await config.destroy({ transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + + await transaction.commit(); + await this.clearQimenContractCache([ removedConfig ]).catch(error => { + ctx.logger.warn('[storeWarehouse.deleteQimenConfig] 清理奇门缓存失败: %s', error.message); + }); + + return { + code: 200, + data: { + deleted: true, + contract: this.serializeRelation(result, currentSubject, null), + qimen_config: null, + removed: removedConfig, + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } + + async unbind(data = {}) { + const { ctx } = this; + const transaction = await ctx.model.transaction(); + + try { + const currentSubject = await this.getCurrentSubject(); + const relation = await this.findScopedRelation(data, currentSubject, transaction); + const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0); + + await relation.update({ + use_status: nextUseStatus, + }, { transaction }); + + const result = await ctx.model.StoreWarehouse.findByPk(relation.id, { + include: this.getRelationIncludes(), + transaction, + }); + const qimenConfig = await this.getSingleQimenConfig(relation.id, { + allowDisabled: true, + transaction, + }); + + await transaction.commit(); + + return { + code: 200, + data: { + contract: this.serializeRelation(result, currentSubject, qimenConfig), + }, + }; + } catch (error) { + await transaction.rollback(); + throw error; + } + } +} + +module.exports = SettingStoreWarehouseService; diff --git a/app/service/systems/upload.js b/app/service/systems/upload.js index b25a8e2..763d2c7 100644 --- a/app/service/systems/upload.js +++ b/app/service/systems/upload.js @@ -411,6 +411,21 @@ class UploadService extends Service { md5Hash = crypto.createHash('md5').update(data.fileContent).digest('hex'); } + const resolvedFileType = String(data.fileType || data.category || data.type || 'document'); + const resolvedMimeType = String(data.mimeType || data.type || this.getMimeType(data.fileName || data.name || 'file.xlsx')); + const defaultExpireDays = data.businessType === 'receivingReport' ? 90 : 0; + const requestedExpireDays = Number(data.expireDays || defaultExpireDays || 0); + let resolvedExpireTime = data.expireTime || data.expire_time || null; + + if (!resolvedExpireTime && Number.isFinite(requestedExpireDays) && requestedExpireDays > 0) { + resolvedExpireTime = new Date(Date.now() + requestedExpireDays * 24 * 60 * 60 * 1000); + } + + if (resolvedExpireTime) { + const expireDate = resolvedExpireTime instanceof Date ? resolvedExpireTime : new Date(resolvedExpireTime); + resolvedExpireTime = Number.isNaN(expireDate.getTime()) ? null : expireDate; + } + // 构建数据库记录 const fileRecord = { warehouse_id: warehouseId || 0, // 默认为0或使用默认仓库 @@ -418,14 +433,15 @@ class UploadService extends Service { file_url: fileUrl, file_name: data.name, file_size: data.size, - file_type: data.type, - mime_type: data.type, + file_type: resolvedFileType, + mime_type: resolvedMimeType, md5_hash: md5Hash || '', storage_mode: 'cos', storage_class: 'standard', uploader_id: userId?.toString() || '0', uploader_name: userName, uploader_dept: data.uploaderDept || '', + expire_time: resolvedExpireTime || null, created_at: new Date(), }; @@ -440,12 +456,20 @@ class UploadService extends Service { }); if (existingFile) { + if (resolvedExpireTime && (!existingFile.expire_time || new Date(existingFile.expire_time).getTime() < resolvedExpireTime.getTime())) { + await existingFile.update({ + expire_time: resolvedExpireTime, + updated_at: new Date(), + }); + } + this.ctx.logger.info(`文件已存在,返回已有记录: ${existingFile.file_url}`); return { fileId: existingFile.id, fileUrl: existingFile.file_url, fileKey: existingFile.file_key, fileName: existingFile.file_name, + expireTime: resolvedExpireTime || existingFile.expire_time || null, isNew: false, }; } diff --git a/config/config.default.js b/config/config.default.js index 4c783ee..9c88140 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -172,6 +172,7 @@ module.exports = appInfo => { config.poloapi ={ } + config.debug = false; // 生成环境默认关闭 debug,开发环境通过 config.local.js 开启 config.printService = { url: 'http://printer.wms.gztbyc.com', }; diff --git a/database/config.js b/database/config.js new file mode 100644 index 0000000..852d9fd --- /dev/null +++ b/database/config.js @@ -0,0 +1,83 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); + +function isPlainObject(value) { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +function mergeDeep(target, source) { + const output = isPlainObject(target) ? { ...target } : {}; + if (!isPlainObject(source)) { + return output; + } + + for (const [ key, value ] of Object.entries(source)) { + if (isPlainObject(value) && isPlainObject(output[key])) { + output[key] = mergeDeep(output[key], value); + } else if (isPlainObject(value)) { + output[key] = mergeDeep({}, value); + } else { + output[key] = value; + } + } + + return output; +} + +function loadEggConfig(configPath) { + if (!fs.existsSync(configPath)) { + return {}; + } + + const configFactory = require(configPath); + const config = typeof configFactory === 'function' + ? configFactory({ name: 'sequelize-cli', baseDir: path.dirname(path.dirname(configPath)) }) + : configFactory; + + return isPlainObject(config) ? config : {}; +} + +function resolveMysqlClient(appConfig, clientName) { + const clients = appConfig && appConfig.mysql && appConfig.mysql.clients; + if (clients && clients[clientName]) { + return clients[clientName]; + } + + if (appConfig && appConfig.mysql && appConfig.mysql.host) { + return appConfig.mysql; + } + + throw new Error(`MySQL client "${clientName}" not found in Egg config.`); +} + +const projectRoot = path.resolve(__dirname, '..'); +const defaultConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.default.js')); +const localConfig = loadEggConfig(path.join(projectRoot, 'config', 'config.local.js')); +const appConfig = mergeDeep(defaultConfig, localConfig); +const clientName = process.env.SEQUELIZE_DB_CLIENT || 'wms'; +const mysqlClient = resolveMysqlClient(appConfig, clientName); + +const baseConfig = { + username: mysqlClient.user, + password: mysqlClient.password, + database: mysqlClient.database, + host: mysqlClient.host, + port: Number(mysqlClient.port || 3306), + dialect: 'mysql', + logging: false, + define: { + freezeTableName: true, + underscored: true, + timestamps: true, + paranoid: true, + deletedAt: 'deleted_at', + }, +}; + +module.exports = { + development: { ...baseConfig }, + test: { ...baseConfig }, + production: { ...baseConfig }, +}; diff --git a/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js b/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js new file mode 100644 index 0000000..3ba7243 --- /dev/null +++ b/database/migrations/20260404093000-add-policy-config-to-wms-store-warehouse.js @@ -0,0 +1,25 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_store_warehouse', 'policy_config', { + type: Sequelize.JSON, + allowNull: true, + comment: '货主在仓库的配置与策略', + }); + }, + + async down(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_store_warehouse` LIKE 'policy_config'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_store_warehouse', 'policy_config'); + }, +}; diff --git a/database/migrations/20260404113000-create-wms-notification-webhook.js b/database/migrations/20260404113000-create-wms-notification-webhook.js new file mode 100644 index 0000000..77e274f --- /dev/null +++ b/database/migrations/20260404113000-create-wms-notification-webhook.js @@ -0,0 +1,154 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const { BIGINT, STRING, TINYINT, DATE, JSON } = Sequelize; + const BIGINT_UNSIGNED = BIGINT.UNSIGNED; + + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_webhook'" + ); + + const tableExists = tables.length > 0; + + if (!tableExists) { + await queryInterface.createTable('wms_notification_webhook', { + id: { + type: BIGINT_UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + store_id: { + type: BIGINT_UNSIGNED, + allowNull: false, + comment: '主体ID,对应 wms_store.id', + references: { + model: 'wms_store', + key: 'id', + }, + onUpdate: 'CASCADE', + onDelete: 'CASCADE', + }, + hook_name: { + type: STRING(100), + allowNull: true, + comment: 'Webhook 名称', + }, + hook_type: { + type: STRING(50), + allowNull: false, + comment: 'Webhook 类型,用于分派不同消息结构处理类,如 dingtalk、wecom、feishu、custom', + }, + hook_url: { + type: STRING(500), + allowNull: false, + comment: 'Webhook 链接地址', + }, + events: { + type: JSON, + allowNull: true, + comment: '订阅事件列表', + }, + extra_config: { + type: JSON, + allowNull: true, + comment: '扩展配置,如签名、请求头、模板映射等', + }, + status: { + type: TINYINT(4), + allowNull: false, + defaultValue: 1, + comment: '状态:0-禁用,1-启用', + }, + remark: { + type: STRING(255), + allowNull: true, + comment: '备注', + }, + created_by: { + type: BIGINT_UNSIGNED, + allowNull: true, + comment: '创建人', + }, + created_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '删除时间', + }, + }, { + engine: 'InnoDB', + charset: 'utf8mb4', + collate: 'utf8mb4_unicode_ci', + comment: '外部通知 WebHook 配置表', + }); + } else { + console.log('Table wms_notification_webhook already exists, ensuring schema and indexes'); + } + + const [ hookUrlColumns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_notification_webhook` LIKE 'hook_url'"); + if (hookUrlColumns.length > 0) { + const currentType = String(hookUrlColumns[0].Type || '').toLowerCase(); + if (currentType.includes('varchar(1000)')) { + await queryInterface.changeColumn('wms_notification_webhook', 'hook_url', { + type: STRING(500), + allowNull: false, + comment: 'Webhook 链接地址', + }); + } + } + + const safeCreateIndex = async (tableName, fields, options) => { + const [ existingIndexes ] = await queryInterface.sequelize.query( + `SHOW INDEX FROM ${tableName} WHERE Key_name = '${options.name}'` + ); + if (existingIndexes.length === 0) { + await queryInterface.addIndex(tableName, fields, options); + } + }; + + await safeCreateIndex('wms_notification_webhook', [ 'store_id' ], { + name: 'idx_notification_webhook_store_id', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'hook_type' ], { + name: 'idx_notification_webhook_hook_type', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'status' ], { + name: 'idx_notification_webhook_status', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'store_id', 'hook_type' ], { + name: 'idx_notification_webhook_store_type', + }); + + await safeCreateIndex('wms_notification_webhook', [ 'store_id', 'hook_type', 'hook_url' ], { + name: 'uk_notification_webhook_store_type_url', + unique: true, + }); + }, + + async down(queryInterface) { + const [ tables ] = await queryInterface.sequelize.query( + "SHOW TABLES LIKE 'wms_notification_webhook'" + ); + + if (tables.length > 0) { + await queryInterface.dropTable('wms_notification_webhook'); + } + }, +}; diff --git a/database/migrations/20260405002000-add-expire-time-to-wms-file.js b/database/migrations/20260405002000-add-expire-time-to-wms-file.js new file mode 100644 index 0000000..fb3a9e8 --- /dev/null +++ b/database/migrations/20260405002000-add-expire-time-to-wms-file.js @@ -0,0 +1,26 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_file` LIKE 'expire_time'"); + if (columns.length > 0) { + return; + } + + await queryInterface.addColumn('wms_file', 'expire_time', { + type: Sequelize.DATE, + allowNull: true, + defaultValue: null, + comment: '过期时间,为空表示永不过期', + }); + }, + + async down(queryInterface) { + const [ columns ] = await queryInterface.sequelize.query("SHOW COLUMNS FROM `wms_file` LIKE 'expire_time'"); + if (columns.length === 0) { + return; + } + + await queryInterface.removeColumn('wms_file', 'expire_time'); + }, +}; diff --git a/docs/express-model-table-map.md b/docs/express-model-table-map.md new file mode 100644 index 0000000..72f403b --- /dev/null +++ b/docs/express-model-table-map.md @@ -0,0 +1,24 @@ +# Express 模型与数据表整理 + +## 一览 + +| 模型文件 | Sequelize key | 数据表 | 当前状态 | +| --- | --- | --- | --- | +| app/model/express.js | Express | wms_express | 已补齐 | +| app/model/express_setting.js | ExpressSetting | wms_express_setting | 已补齐 | +| app/model/order_express.js | OrderExpress | wms_order_express | 已补齐 | +| app/model/order_express_print_data.js | OrderExpressPrintData | wms_order_express_print_data | 已补齐 | +| app/model/express_print_record.js | ExpressPrintRecord | wms_express_print_record | 已补齐 | +| app/model/print_station_express.js | PrintStationExpress | wms_print_station_express | 已存在 | + +## 关键说明 + +- 本次仅整理模型与真实数据表对齐,不改动业务逻辑与接口行为。 +- 通过 `script/db-query.ps1` 实查,数据库中包含 6 张 express 相关表,上述模型已全部覆盖。 +- 既有字段型快递信息(如 `wms_entry_order.express_code`、`wms_order_delivery.express_code`)仍保留为业务字段,不属于独立主数据表。 + +## 建议的后续收敛 + +- 将 `index.getExpressList` 的配置源(`app.config.expressList`)逐步收敛到 `wms_express`,避免配置与数据表双源。 +- 若后续存在统一查询需求,可新增 `systems/express.js`,统一对 `Express / ExpressSetting / OrderExpress` 的读写入口。 +- 打印链路可逐步将 `wms_print_station_express` 与 `wms_express_print_record` 做关联查询封装,减少 systemMethods 层的散落操作。 diff --git a/methods/gateway.json b/methods/gateway.json index 1ddc55f..c39b061 100644 --- a/methods/gateway.json +++ b/methods/gateway.json @@ -1,8 +1,8 @@ { "module": "gateway", "description": "内部网关接口,供内网系统间调用,统一使用 POST 请求", - "version": "0.1.0", - "updatedAt": "2026-03-24", + "version": "0.2.0", + "updatedAt": "2026-03-29", "headers": [], "methods": { "groups": [ @@ -12,7 +12,7 @@ "list": [ { "method": "user.getUserByTempCode", - "description": "根据绑定码反查WMS账号ID(供 ye4s 扫码绑定调用)", + "description": "根据绑定码反查WMS账号ID并写入扫码状态(扫描即视为已确认,状态缓存3分钟)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -22,7 +22,7 @@ "type": "string", "required": true, "source": "body", - "description": "绑定码(由 user.getBindWechatCode 生成)" + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" } ], "response": [ @@ -32,24 +32,30 @@ "required": true, "description": "匹配到的 WMS 账号ID" }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "WMS 账号表中的真实姓名,用于扫码绑定前确认账号" + }, { "name": "status", "type": "string", "required": true, - "description": "当前绑定状态,如 pending/bound" + "description": "当前扫码状态,成功扫码后固定为 scanned" }, { "name": "source", "type": "string", "required": true, - "description": "数据来源,如 cache/db" + "description": "数据来源,如 scan-cache" } ], "errors": [] }, { "method": "user.bindAccountByTempCode", - "description": "根据绑定码将 ye4s 用户绑定到 WMS 账号(供 ye4s 扫码后回调)", + "description": "根据绑定码对应的扫码状态缓存将 ye4s 用户绑定到 WMS 账号(需先调用扫码反查接口)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -59,7 +65,7 @@ "type": "string", "required": true, "source": "body", - "description": "绑定码(由 user.getBindWechatCode 生成)" + "description": "绑定码(由 user.getBindWechatCode 生成,6位字母数字混合)" }, { "name": "ye4s_user_id", @@ -92,6 +98,141 @@ "errors": [] } ] + }, + { + "groupName": "打印绑定模块", + "module": "print", + "list": [ + { + "method": "print.getBindInfo", + "description": "根据 WMS 账号ID和扫码 code 返回可绑定仓库列表;有可绑定仓库时下发 300 秒临时凭据 tempCode,无可绑定仓库时返回空数组且不返回 tempCode", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "account_id", + "type": "number", + "required": true, + "source": "body", + "description": "WMS 账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "打印端提供的绑定 code" + } + ], + "response": [ + { + "name": "warehouses", + "type": "array", + "required": true, + "description": "可绑定仓库列表,元素结构为 { id, name }" + }, + { + "name": "tempCode", + "type": "string", + "required": false, + "description": "临时绑定凭据,仅当 warehouses 非空时返回" + } + ], + "errors": [ + { + "code": 0, + "message": "缺少有效参数 account_id 或 code" + }, + { + "code": 0, + "message": "账号不存在或已禁用" + }, + { + "code": 0, + "message": "无效code或未绑定" + } + ] + }, + { + "method": "print.bindByTempCode", + "description": "根据第一步返回的临时凭据执行打印台绑定,提交工作台名称和仓库ID后完成真实绑定", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "temp_code", + "type": "string", + "required": true, + "source": "body", + "description": "第一步返回的临时凭据,300 秒有效" + }, + { + "name": "printer", + "type": "string", + "required": true, + "source": "body", + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "source": "body", + "description": "仓库ID" + } + ], + "response": [ + { + "name": "code", + "type": "string", + "required": true, + "description": "真实绑定 code" + }, + { + "name": "printer", + "type": "string", + "required": true, + "description": "工作台名称" + }, + { + "name": "warehouse", + "type": "number", + "required": true, + "description": "仓库ID" + }, + { + "name": "computerId", + "type": "number", + "required": true, + "description": "打印台电脑ID" + } + ], + "errors": [ + { + "code": 0, + "message": "参数缺失" + }, + { + "code": 0, + "message": "临时code无效或已过期" + }, + { + "code": 0, + "message": "仓库无绑定权限" + }, + { + "code": 0, + "message": "仓库id校验失败" + }, + { + "code": 0, + "message": "该仓库下打印台名称已存在且可用" + } + ] + } + ] } ] } diff --git a/methods/system.json b/methods/system.json index d7c9e13..67c9e18 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,4419 +1,4897 @@ { - "module": "system", - "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.0", - "updatedAt": "2026-03-23", - "headers": [ + "module": "system", + "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", + "version": "0.3.0", + "updatedAt": "2026-03-22", + "headers": [ + { + "name": "platform", + "type": "string", + "required": true, + "description": "客户端平台标识,如 web/pda/app", + "list": [ { - "name": "platform", - "type": "string", - "required": true, - "description": "客户端平台标识,如 web/pda/app", - "list": [ - { - "value": "web", - "name": "网页端" - }, - { - "value": "pda", - "name": "PDA端" - }, - { - "value": "app", - "name": "APP端" - }, - { - "value": "wx", - "name": "微信端" - }, - { - "value": "miniProgram", - "name": "小程序端" - }, - { - "value": "other", - "name": "其他" - } - ] + "value": "web", + "name": "网页端" }, { - "type": "string", - "required": true, - "name": "project", - "description": "项目标识,如 all/warehouse/store/tms", - "list": [ - { - "value": "all", - "name": "全部" - }, - { - "value": "warehouse", - "name": "仓库" - }, - { - "value": "store", - "name": "货主" - }, - { - "value": "tms", - "name": "物流" - } - ] + "value": "pda", + "name": "PDA端" + }, + { + "value": "app", + "name": "APP端" + }, + { + "value": "wx", + "name": "微信端" + }, + { + "value": "miniProgram", + "name": "小程序端" + }, + { + "value": "other", + "name": "其他" } - ], - "methods": { - "groups": [ - { - "groupName": "配置模块", - "module": "config", - "list": [ - { - "method": "config.list", - "description": "config.list 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "看板模块", - "module": "dashboard", - "list": [ - { - "method": "dashboard.storeStats", - "description": "dashboard.storeStats 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.warehouseStats", - "description": "dashboard.warehouseStats 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.hot_order_rank", - "description": "dashboard.hot_order_rank 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.express_ratio", - "description": "dashboard.express_ratio 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.platform_distribution", - "description": "dashboard.platform_distribution 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "dashboard.order_trend", - "description": "dashboard.order_trend 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "基础模块", - "module": "index", - "list": [ - { - "method": "index.fastWhereTree", - "description": "index.fastWhereTree 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "type", - "type": "string", - "required": false, - "source": "body", - "description": "type 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "index.loadStores", - "description": "index.loadStores 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.getCOSUploadConfig", - "description": "index.getCOSUploadConfig 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "data", - "type": "object", - "required": false, - "source": "body", - "description": "data 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "index.getImages", - "description": "index.getImages 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.uploadSuccessNotify", - "description": "index.uploadSuccessNotify 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.ReferenceFile", - "description": "index.ReferenceFile 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.getMessageDetail", - "description": "index.getMessageDetail 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.getI18nMessage", - "description": "index.getI18nMessage 接口", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "language", - "type": "string", - "required": false, - "source": "body|query", - "description": "language 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "index.putI18nCollect", - "description": "index.putI18nCollect 接口", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "keys", - "type": "array", - "required": false, - "source": "body", - "description": "keys 参数" - }, - { - "name": "locale", - "type": "string", - "required": false, - "source": "body", - "description": "locale 参数" - }, - { - "name": "project", - "type": "string", - "required": false, - "source": "body", - "description": "project 参数" - }, - { - "name": "source", - "type": "string", - "required": false, - "source": "body", - "description": "source 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "index.tryAutoTranslateNewKeys", - "description": "index.tryAutoTranslateNewKeys 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.searchSpace", - "description": "index.searchSpace 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "index.getExpressList", - "description": "index.getExpressList 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "订单模块", - "module": "order", - "list": [ - { - "method": "order.getOrderModels", - "description": "order.getOrderModels 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "order.list", - "description": "分页查询订单列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;常用字段包括 delivery_order_code、status、outbound_status、buyer_nick、mobile 与日期区间字段。示例:where.delivery_order_code={operator:like,value:SO202603}; where.status={operator:in,value:[created,pedding]}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.detail", - "description": "查询订单详情", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.listItems", - "description": "查询订单商品明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "order_id", - "type": "number", - "required": false, - "source": "body", - "description": "order_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.stats", - "description": "订单统计", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;统计口径与 order.list 共用筛选字段。示例:where.status={operator:eq,value:fin}; where.create_time_start={value:2026-03-01}; where.create_time_end={value:2026-03-31}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.getreviewOrderlist", - "description": "分页查询订单审核列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、operator_name、operate_time_start、operate_time_end 等字段。示例:where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.updateStatus", - "description": "更新订单状态", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "claim_status", - "type": "string", - "required": false, - "source": "body", - "description": "claim_status 参数" - }, - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "delivery_time", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_time 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "inspection_status", - "type": "string", - "required": false, - "source": "body", - "description": "inspection_status 参数" - }, - { - "name": "intercept_status", - "type": "string", - "required": false, - "source": "body", - "description": "intercept_status 参数" - }, - { - "name": "lock_status", - "type": "string", - "required": false, - "source": "body", - "description": "lock_status 参数" - }, - { - "name": "outbound_status", - "type": "string", - "required": false, - "source": "body", - "description": "outbound_status 参数" - }, - { - "name": "pack_status", - "type": "string", - "required": false, - "source": "body", - "description": "pack_status 参数" - }, - { - "name": "pick_status", - "type": "string", - "required": false, - "source": "body", - "description": "pick_status 参数" - }, - { - "name": "post_status", - "type": "string", - "required": false, - "source": "body", - "description": "post_status 参数" - }, - { - "name": "print_status", - "type": "string", - "required": false, - "source": "body", - "description": "print_status 参数" - }, - { - "name": "status", - "type": "string", - "required": false, - "source": "body", - "description": "status 参数" - }, - { - "name": "storage_status", - "type": "string", - "required": false, - "source": "body", - "description": "storage_status 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.updateDeliveryTime", - "description": "更新发货时间", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_time", - "type": "string", - "required": true, - "source": "body", - "description": "delivery_time 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder", - "description": "订单审核", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "inspection_status", - "type": "string", - "required": false, - "source": "body", - "description": "inspection_status 参数(兼容入参)" - }, - { - "name": "review_status", - "type": "string", - "required": false, - "source": "body", - "description": "review_status 参数,默认 fin" - }, - { - "name": "operator_name", - "type": "string", - "required": false, - "source": "body", - "description": "operator_name 参数" - }, - { - "name": "operate_time", - "type": "string", - "required": false, - "source": "body", - "description": "operate_time 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder.getreviewOrderlist", - "description": "分页查询订单审核列表(目录化路由)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;支持 inspection_status、operator_name、operate_time_start、operate_time_end 等字段。示例:where.inspection_status={operator:eq,value:pending}; where.operator_name={operator:like,value:张}; where.operate_time_start={value:2026-03-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.reviewOrder.reviewOrder", - "description": "订单审核(目录化路由)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "delivery_order_code 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "inspection_status", - "type": "string", - "required": false, - "source": "body", - "description": "inspection_status 参数(兼容入参)" - }, - { - "name": "review_status", - "type": "string", - "required": false, - "source": "body", - "description": "review_status 参数,默认 fin" - }, - { - "name": "operator_name", - "type": "string", - "required": false, - "source": "body", - "description": "operator_name 参数" - }, - { - "name": "operate_time", - "type": "string", - "required": false, - "source": "body", - "description": "operate_time 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.deliveryOrder.getdeliveryOrderlist", - "description": "分页查询已进入出库流程的订单列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status != none。示例:where.outbound_status={operator:in,value:[created,processing]}; where.store_id={operator:eq,value:1001}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.pendingOrder.getpendingOrderlist", - "description": "分页查询待处理订单列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认 status in [pedding, created] 且 outbound_status = none。示例:where.status={operator:in,value:[pedding,created]}; where.outbound_status={operator:eq,value:none}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.expectionOrder.getexpectionOrderlist", - "description": "分页查询异常订单列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传时默认筛选各流程 error 或拦截 exception。示例:where.status={operator:eq,value:error}; where.outbound_status={operator:eq,value:exception}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "order.archiveOrder.getarchiveOrderlist", - "description": "分页查询归档订单列表(暂使用当前订单表完成态数据)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构;未传 outbound_status 时默认过滤 outbound_status = fin。示例:where.outbound_status={operator:eq,value:fin}; where.store_id={operator:eq,value:1001}。" - } - ], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "打印模块", - "module": "print", - "list": [ - { - "method": "print.send", - "description": "print.send 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "computerId", - "type": "string", - "required": false, - "source": "body", - "description": "computerId 参数" - }, - { - "name": "count", - "type": "number", - "required": false, - "source": "body", - "description": "count 参数" - }, - { - "name": "data", - "type": "object", - "required": false, - "source": "body", - "description": "data 参数" - }, - { - "name": "printer", - "type": "string", - "required": false, - "source": "body", - "description": "printer 参数" - }, - { - "name": "template", - "type": "object", - "required": false, - "source": "body", - "description": "template 参数" - }, - { - "name": "timestamp", - "type": "string", - "required": false, - "source": "body", - "description": "timestamp 参数" - }, - { - "name": "type", - "type": "string", - "required": false, - "source": "body", - "description": "type 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getPrintResult", - "description": "print.getPrintResult 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "printId", - "type": "string", - "required": true, - "source": "body", - "description": "printId 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getPrintRecordItem", - "description": "print.getPrintRecordItem 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getList", - "description": "print.getList 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "page", - "type": "number", - "required": false, - "source": "body", - "description": "page 参数" - }, - { - "name": "pageSize", - "type": "number", - "required": false, - "source": "body", - "description": "pageSize 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;当前支持 id、name、computer_id、custom_barcode。示例:where.name={operator:like,value:热敏}; where.computer_id={operator:eq,value:PC-01}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getItem", - "description": "print.getItem 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.add", - "description": "print.add 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "computer_id", - "type": "number", - "required": true, - "source": "body", - "description": "computer_id 参数" - }, - { - "name": "name", - "type": "string", - "required": true, - "source": "body", - "description": "name 参数" - }, - { - "name": "custom_barcode", - "type": "string", - "required": false, - "source": "body", - "description": "custom_barcode 参数" - }, - { - "name": "default_printer_name", - "type": "string", - "required": false, - "source": "body", - "description": "default_printer_name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.hasName", - "description": "print.hasName 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "name", - "type": "string", - "required": true, - "source": "body", - "description": "name 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.updateItem", - "description": "print.updateItem 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - }, - { - "name": "computer_id", - "type": "number", - "required": false, - "source": "body", - "description": "computer_id 参数" - }, - { - "name": "custom_barcode", - "type": "string", - "required": false, - "source": "body", - "description": "custom_barcode 参数" - }, - { - "name": "name", - "type": "string", - "required": false, - "source": "body", - "description": "name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.del", - "description": "print.del 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "ids", - "type": "array", - "required": false, - "source": "body", - "description": "ids 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.getComputer", - "description": "print.getComputer 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "print.getComputerPrinter", - "description": "print.getComputerPrinter 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "print.savePrinters", - "description": "print.savePrinters 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "defaultPrinter", - "type": "string", - "required": true, - "source": "body", - "description": "defaultPrinter 参数" - }, - { - "name": "express", - "type": "array", - "required": false, - "source": "body", - "description": "express 参数" - }, - { - "name": "print_station_id", - "type": "number", - "required": false, - "source": "body", - "description": "print_station_id 参数" - } - ], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "打印机站点模块", - "module": "printer.station", - "list": [ - { - "method": "printer.station.list", - "description": "获取打印站点列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "打印模板模块", - "module": "setting.printTemplate", - "list": [ - { - "method": "setting.printTemplate.list", - "description": "获取打印模板树", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "setting.printTemplate.save", - "description": "保存打印模板", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "setting.printTemplate.create", - "description": "创建打印模板(platform 固定为 default,template_type 固定为 CUSTOM,template_url 固定为空字符串)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "template_name", - "type": "string", - "required": true, - "source": "body", - "description": "模板名称" - }, - { - "name": "business_type", - "type": "string", - "required": true, - "source": "body", - "description": "业务类型" - }, - { - "name": "page_width", - "type": "number", - "required": true, - "source": "body", - "description": "页面宽度(mm)" - }, - { - "name": "page_height", - "type": "number", - "required": true, - "source": "body", - "description": "页面高度(mm)" - }, - { - "name": "template_content", - "type": "array", - "required": false, - "source": "body", - "description": "模板内容,可省略;省略时默认创建空模板内容" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建模板ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误(缺少 template_name、business_type、page_width 或 page_height)" - }, - { - "code": "409", - "description": "同一业务类型和平台下已存在自定义模板" - } - ] - }, - { - "method": "setting.printTemplate.delete", - "description": "删除打印模板(软删除)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "模板ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "删除的模板ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误(缺少 id)" - }, - { - "code": "404", - "description": "模板不存在或无权限" - } - ] - }, - { - "method": "setting.printTemplate.listTemplatesByType", - "description": "按业务类型查询模板", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "businessType", - "type": "string", - "required": true, - "source": "body", - "description": "businessType 参数" - } - ], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "账号管理模块", - "module": "setting.account", - "list": [ - { - "method": "setting.account.list", - "description": "查询当前主体下的工号基础信息列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "status", - "type": "number", - "required": false, - "source": "body", - "description": "状态筛选,默认 1,仅查有效工号" - }, - { - "name": "includeDisabled", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否包含已删除工号" - } - ], - "response": [ - { - "name": "data[]", - "type": "object", - "required": true, - "description": "工号列表项" - }, - { - "name": "data[].employee_id", - "type": "number", - "required": true, - "description": "工号ID" - }, - { - "name": "data[].account_id", - "type": "number", - "required": true, - "description": "账号ID" - }, - { - "name": "data[].store_id", - "type": "number", - "required": true, - "description": "主体ID" - }, - { - "name": "data[].real_name", - "type": "string", - "required": true, - "description": "工号姓名" - }, - { - "name": "data[].status", - "type": "number", - "required": true, - "description": "工号状态:1=启用,0=停用" - }, - { - "name": "data[].username", - "type": "string", - "required": true, - "description": "账号用户名" - }, - { - "name": "data[].phone", - "type": "string", - "required": true, - "description": "账号手机号" - }, - { - "name": "data[].email", - "type": "string", - "required": true, - "description": "账号邮箱" - }, - { - "name": "data[].avatar_file_id", - "type": "number", - "required": false, - "description": "头像文件ID,为空表示未设置" - }, - { - "name": "data[].avatar_url", - "type": "string", - "required": true, - "description": "头像访问地址" - } - ], - "errors": [ - { - "code": "400", - "description": "当前登录态缺少主体上下文(store_id)" - }, - { - "code": "500", - "description": "查询失败" - } - ] - }, - { - "method": "setting.account.add", - "description": "新增工号,按手机号复用或创建账号后绑定到当前主体", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "phone", - "type": "string", - "required": true, - "source": "body", - "description": "手机号,作为账号复用/创建依据" - }, - { - "name": "real_name", - "type": "string", - "required": true, - "source": "body", - "description": "工号姓名,新增时禁止直接使用保留名称" - }, - { - "name": "username", - "type": "string", - "required": false, - "source": "body", - "description": "新账号用户名,不传时系统自动生成" - }, - { - "name": "password", - "type": "string", - "required": false, - "source": "body", - "description": "新账号密码,不传默认 111111" - }, - { - "name": "role_id", - "type": "number", - "required": false, - "source": "body", - "description": "工号角色,不传时继承当前操作人工号角色" - }, - { - "name": "email", - "type": "string", - "required": false, - "source": "body", - "description": "新账号邮箱,不传时按 username 自动生成" - } - ], - "response": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "description": "新增或复用后的工号ID" - }, - { - "name": "account_id", - "type": "number", - "required": true, - "description": "绑定账号ID" - }, - { - "name": "role_id", - "type": "number", - "required": true, - "description": "绑定后的角色ID" - }, - { - "name": "is_new_account", - "type": "boolean", - "required": true, - "description": "是否为本次新建账号" - }, - { - "name": "phone", - "type": "string", - "required": true, - "description": "绑定账号手机号" - }, - { - "name": "username", - "type": "string", - "required": true, - "description": "绑定账号用户名" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误、手机号格式错误、或直接使用保留名称" - }, - { - "code": "409", - "description": "手机号对应账号已禁用、手机号已绑定当前主体工号、或用户名重复" - }, - { - "code": "500", - "description": "新增失败" - } - ] - }, - { - "method": "setting.account.delete", - "description": "删除工号绑定关系,仅停用工号,不删除账号", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "source": "body", - "description": "要删除的工号ID" - } - ], - "response": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "description": "被停用的工号ID" - }, - { - "name": "account_id", - "type": "number", - "required": true, - "description": "关联账号ID" - }, - { - "name": "status", - "type": "string", - "required": true, - "description": "固定返回 deleted" - }, - { - "name": "already_deleted", - "type": "boolean", - "required": false, - "description": "可选,true 表示该工号原本已停用" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误或尝试删除当前登录工号" - }, - { - "code": "404", - "description": "工号不存在或无权限删除" - }, - { - "code": "500", - "description": "删除失败" - } - ] - }, - { - "method": "setting.account.update", - "description": "更新工号姓名和头像引用", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "source": "body", - "description": "要更新的工号ID" - }, - { - "name": "real_name", - "type": "string", - "required": false, - "source": "body", - "description": "更新后的工号姓名" - }, - { - "name": "file_id", - "type": "number", - "required": false, - "source": "body", - "description": "已有文件ID,作为头像引用" - } - ], - "response": [ - { - "name": "employee_id", - "type": "number", - "required": true, - "description": "更新后的工号ID" - }, - { - "name": "real_name", - "type": "string", - "required": true, - "description": "更新后的工号姓名" - }, - { - "name": "avatar_file_id", - "type": "number", - "required": false, - "description": "更新后的头像文件ID" - }, - { - "name": "avatar_url", - "type": "string", - "required": true, - "description": "更新后的头像地址" - } - ], - "errors": [ - { - "code": "400", - "description": "参数错误,未提供更新项" - }, - { - "code": "404", - "description": "工号或头像文件不存在" - }, - { - "code": "500", - "description": "更新失败" - } - ] - } - ] - }, - { - "groupName": "商品模块", - "module": "stock", - "list": [ - { - "method": "stock.warehouse.list", - "description": "仓库商品列表查询(支持 where 条件与分页)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "pagination 参数" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、barcode、prohibited_type 等商品筛选字段。示例:where.barcode={operator:like,value:69}; where.prohibited_type={operator:eq,value:liquid}。" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getProhibitedType", - "description": "查询违禁品类型列表(系统预设+仓库自定义)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getInfo", - "description": "查询仓库商品详情", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.saveWarehouseStock", - "description": "更新仓库商品资料", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.createWarehouseStock", - "description": "新建仓库商品资料", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getBarcodes", - "description": "查询商品条码列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.saveWarehouseStockBarcode", - "description": "保存商品条码信息", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getStoreStocks", - "description": "查询仓库商品与货主关联列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.bindItem", - "description": "绑定货主商品关系", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.unbindItem", - "description": "解绑货主商品关系", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.checkItemCodeUnique", - "description": "校验商品编码在货主维度唯一性", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "item_code", - "type": "string", - "required": true, - "source": "body", - "description": "item_code 参数" - }, - { - "name": "store_id", - "type": "number", - "required": true, - "source": "body", - "description": "store_id 参数" - }, - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.queryStockLogs", - "description": "查询库存操作日志", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouseId", - "type": "string", - "required": false, - "source": "body", - "description": "warehouseId 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.handleBatchDelete", - "description": "批量删除仓库商品资料", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.deleteUnit", - "description": "删除库存单位", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.deleteProhibited", - "description": "删除违禁品类型", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.handleBatchChange", - "description": "批量修改仓库商品字段", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getStockUnits", - "description": "查询可用库存单位(系统+仓库)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.getUnitList", - "description": "查询当前仓库自定义单位列表", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.createProhibited", - "description": "新增违禁品类型", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "name", - "type": "string", - "required": true, - "source": "body", - "description": "name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.createUnit", - "description": "新增库存单位", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "name", - "type": "string", - "required": true, - "source": "body", - "description": "name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "stock.warehouse.search", - "description": "仓库商品关键字搜索", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "库存模块", - "module": "storage", - "list": [ - { - "method": "storage.receiving.getReceivingList", - "description": "storage.receiving.getReceivingList 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数,支持 page/pageSize" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、status、store_id、日期区间等字段。示例:where.status={operator:eq,value:finished}; where.store_id={operator:eq,value:1001}; where.create_time_start={value:2026-03-01}。" - } - ], - "response": [ - { - "name": "list", - "type": "array", - "required": true, - "description": "收货单列表" - }, - { - "name": "pagination", - "type": "object", - "required": true, - "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "汇总信息(total_quantity、total_locked、total_available、total_items)" - } - ], - "errors": [ - { - "code": "500", - "description": "查询失败" - } - ] - }, - { - "method": "storage.receiving.getReceivingDetail", - "description": "storage.receiving.getReceivingDetail 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "收货单ID" - }, - { - "name": "pagination", - "type": "object", - "required": true, - "source": "body", - "description": "明细分页参数,支持 page/pageSize" - } - ], - "response": [ - { - "name": "receiving", - "type": "object", - "required": true, - "description": "收货单详情(含 details、images、pagination)" - } - ], - "errors": [ - { - "code": "0", - "description": "无记录或无权访问" - }, - { - "code": "500", - "description": "服务器错误" - } - ] - }, - { - "method": "storage.receiving.batchCancelReceiving", - "description": "storage.receiving.batchCancelReceiving 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "ids", - "type": "array", - "required": true, - "source": "body", - "description": "待作废收货单ID数组" - } - ], - "response": [ - { - "name": "message", - "type": "string", - "required": true, - "description": "批量作废处理结果" - } - ], - "errors": [ - { - "code": "0", - "description": "部分单据不存在、无权访问或状态不允许作废" - }, - { - "code": "500", - "description": "服务器错误" - } - ] - }, - { - "method": "storage.receiving.create", - "description": "storage.receiving.create 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "delivery_method", - "type": "string", - "required": true, - "source": "body", - "description": "到货方式:truck/express/air_freight/sea_freight/other" - }, - { - "name": "loading_method", - "type": "string", - "required": true, - "source": "body", - "description": "装卸方式:with_pallet/without_pallet" - }, - { - "name": "license_plate", - "type": "string", - "required": false, - "source": "body", - "description": "车牌号(delivery_method=truck 时建议传)" - }, - { - "name": "tracking_number", - "type": "string", - "required": false, - "source": "body", - "description": "物流单号(非 truck/other 场景建议传)" - }, - { - "name": "store_id", - "type": "number", - "required": false, - "source": "body", - "description": "货主ID" - }, - { - "name": "total_boxes", - "type": "number", - "required": false, - "source": "body", - "description": "总箱数" - }, - { - "name": "total_pallets", - "type": "number", - "required": false, - "source": "body", - "description": "总托盘数" - }, - { - "name": "remark", - "type": "string", - "required": false, - "source": "body", - "description": "备注" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建收货单ID" - }, - { - "name": "receiving_number", - "type": "string", - "required": true, - "description": "收货单号" - } - ], - "errors": [ - { - "code": "0", - "description": "创建失败(如字段枚举不合法、数据库约束异常)" - } - ] - }, - { - "method": "storage.receiving.addItem", - "description": "storage.receiving.addItem 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "item", - "type": "object", - "required": false, - "source": "body", - "description": "item 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.removeItem", - "description": "storage.receiving.removeItem 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - }, - { - "name": "item_id", - "type": "number", - "required": false, - "source": "body", - "description": "item_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.saveReceiving", - "description": "storage.receiving.saveReceiving 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.get", - "description": "storage.receiving.get 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.addDetail", - "description": "storage.receiving.addDetail 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.deleteDetail", - "description": "storage.receiving.deleteDetail 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.detailChange", - "description": "storage.receiving.detailChange 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.cancel", - "description": "storage.receiving.cancel 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.receiving.completeReceiving", - "description": "storage.receiving.completeReceiving 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "storage.entry.list", - "description": "入库单列表查询", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数,支持 page/pageSize" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status、store_id、order_type、日期区间等字段。示例:where.order_status={operator:eq,value:waiting}; where.order_type={operator:eq,value:purchase}; where.create_time_start={value:2026-03-01}。" - }, - { - "name": "sort", - "type": "object", - "required": false, - "source": "body", - "description": "排序参数,支持 sortField/sortOrder" - } - ], - "response": [ - { - "name": "list", - "type": "array", - "required": true, - "description": "入库单列表" - }, - { - "name": "pagination", - "type": "object", - "required": true, - "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "状态汇总(total、pending、creating、created、completed、cancelled)" - } - ], - "errors": [ - { - "code": "400", - "description": "筛选条件格式错误" - }, - { - "code": "500", - "description": "查询失败" - } - ] - }, - { - "method": "storage.entry.get", - "description": "查询入库单详情", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "入库单ID,与 entry_order_code 二选一" - }, - { - "name": "entry_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "入库单号,与 id 二选一" - } - ], - "response": [ - { - "name": "entryOrder", - "type": "object", - "required": true, - "description": "入库单详情(含 items 明细)" - } - ], - "errors": [ - { - "code": "400", - "description": "id 与 entry_order_code 均未传" - }, - { - "code": "0", - "description": "无记录或无权访问" - } - ] - }, - { - "method": "storage.entry.create", - "description": "创建入库单", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "order_type", - "type": "string", - "required": true, - "source": "body", - "description": "业务类型:SCRK/LYRK/CCRK/CGRK/DBRK/QTRK/B2BRK/XNRK" - }, - { - "name": "store_id", - "type": "number", - "required": false, - "source": "body", - "description": "货主ID,不传默认使用当前用户 store_id" - }, - { - "name": "entry_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "入库单号,不传时系统自动生成" - }, - { - "name": "purchase_order_code", - "type": "string", - "required": false, - "source": "body", - "description": "采购单号" - }, - { - "name": "remark", - "type": "string", - "required": false, - "source": "body", - "description": "备注" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建入库单ID" - }, - { - "name": "entry_order_code", - "type": "string", - "required": true, - "description": "入库单号" - } - ], - "errors": [ - { - "code": "400", - "description": "参数缺失或业务类型不合法" - }, - { - "code": "409", - "description": "入库单号已存在" - } - ] - }, - { - "method": "storage.entry.addDetail", - "description": "新增入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "order_id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - }, - { - "name": "count", - "type": "number", - "required": true, - "source": "body", - "description": "计划入库数量,必须大于0" - }, - { - "name": "item_code", - "type": "string", - "required": false, - "source": "body", - "description": "商品编码" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "新建明细ID" - }, - { - "name": "order_id", - "type": "number", - "required": true, - "description": "所属入库单ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或状态不允许新增明细" - }, - { - "code": "404", - "description": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.entry.deleteDetail", - "description": "删除入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "明细ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "删除成功的明细ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或明细已有收货数量" - }, - { - "code": "404", - "description": "明细或入库单不存在" - } - ] - }, - { - "method": "storage.entry.detailChange", - "description": "修改入库明细", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "明细ID" - }, - { - "name": "count", - "type": "number", - "required": false, - "source": "body", - "description": "计划入库数量,必须大于0且不能小于已收货数量" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "修改成功的明细ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或没有可更新字段" - }, - { - "code": "404", - "description": "明细或入库单不存在" - } - ] - }, - { - "method": "storage.entry.cancel", - "description": "作废入库单", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "作废成功的入库单ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法或已完成单据不允许作废" - }, - { - "code": "404", - "description": "入库单不存在或无权访问" - } - ] - }, - { - "method": "storage.entry.completeEntry", - "description": "完成入库单", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "入库单ID" - } - ], - "response": [ - { - "name": "id", - "type": "number", - "required": true, - "description": "完成成功的入库单ID" - } - ], - "errors": [ - { - "code": "400", - "description": "参数不合法、已作废或缺少明细" - }, - { - "code": "404", - "description": "入库单不存在或无权访问" - } - ] - } - ] - }, - { - "groupName": "主体模块", - "module": "store", - "list": [ - { - "method": "store.createStore", - "description": "store.createStore 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "store.createWarehouse", - "description": "store.createWarehouse 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "store.joinStore", - "description": "store.joinStore 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "store.joinWarehouse", - "description": "store.joinWarehouse 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "store.getStoreRoles", - "description": "store.getStoreRoles 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "code", - "type": "string", - "required": true, - "source": "body", - "description": "申请码(join_token)" - } - ], - "response": [], - "errors": [] - }, - { - "method": "store.auditApply", - "description": "store.auditApply 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "audit_status", - "type": "string", - "required": true, - "source": "body", - "description": "审核状态(approved/rejected)" - }, - { - "name": "code", - "type": "string", - "required": true, - "source": "body", - "description": "申请码(join_token)" - }, - { - "name": "store_id", - "type": "number", - "required": true, - "source": "body", - "description": "当前审批门店ID" - }, - { - "name": "role_ids", - "type": "array", - "required": true, - "source": "body", - "description": "分配角色ID数组" - }, - { - "name": "reject_reason", - "type": "string", - "required": false, - "source": "body", - "description": "拒绝原因(audit_status=rejected 时可传)" - } - ], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "用户模块", - "module": "user", - "list": [ - { - "method": "user.login", - "description": "用户登录(仅返回 token)", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "password", - "type": "string", - "required": false, - "source": "body", - "description": "password 参数" - }, - { - "name": "username", - "type": "string", - "required": false, - "source": "body", - "description": "username 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "user.loginByCode", - "description": "登录码登录(使用 ye4s_user.tmp_code)", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [ - { - "name": "code", - "type": "string", - "required": true, - "source": "body", - "description": "登录码,对应 ye4s_user.tmp_code" - } - ], - "response": [], - "errors": [] - }, - { - "method": "user.getBindWechatCode", - "description": "获取微信绑定码(默认立即返回;显式开启长轮询后,最长等待60秒,状态变化立即返回)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "forceRefresh", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否强制刷新状态,true 时跳过缓存等待窗口" - }, - { - "name": "waitForChange", - "type": "boolean", - "required": false, - "source": "body", - "description": "是否显式开启长轮询等待(推荐字段);true 时进入最长60秒等待" - }, - { - "name": "longPoll", - "type": "boolean", - "required": false, - "source": "body", - "description": "长轮询开关(兼容字段);true 时进入最长60秒等待" - }, - { - "name": "waitTimeoutMs", - "type": "number", - "required": false, - "source": "body", - "description": "等待超时毫秒数;后端自动封顶60000" - }, - { - "name": "init", - "type": "boolean", - "required": false, - "source": "body", - "description": "初始化请求标记;true 时强制立即返回,不进入长等待" - } - ], - "response": [], - "errors": [] - }, - { - "method": "user.unbindWechat", - "description": "解绑微信账号(清理 ye4s 关联账号数据)", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "user.logout", - "description": "用户登出", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "user.info", - "description": "获取当前用户信息", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "user.changeRole", - "description": "user.changeRole 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "user.register", - "description": "user.register 接口", - "isNeedAuth": false, - "isNeedLogin": false, - "headers": [], - "params": [], - "response": [], - "errors": [] - } - ] - }, - { - "groupName": "仓库模块", - "module": "warehouse", - "list": [ - { - "method": "warehouse.getWarehouseZones", - "description": "warehouse.getWarehouseZones 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getWarehouseTree", - "description": "warehouse.getWarehouseTree 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouseId", - "type": "number", - "required": true, - "source": "body", - "description": "warehouseId 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getChildren", - "description": "warehouse.getChildren 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "zoneId", - "type": "number", - "required": true, - "source": "body", - "description": "zoneId 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.create", - "description": "warehouse.create 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [], - "response": [], - "errors": [] - }, - { - "method": "warehouse.update", - "description": "warehouse.update 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - }, - { - "name": "aisles", - "type": "string", - "required": false, - "source": "body", - "description": "aisles 参数" - }, - { - "name": "cell_height", - "type": "string", - "required": false, - "source": "body", - "description": "cell_height 参数" - }, - { - "name": "cell_length", - "type": "string", - "required": false, - "source": "body", - "description": "cell_length 参数" - }, - { - "name": "cell_width", - "type": "string", - "required": false, - "source": "body", - "description": "cell_width 参数" - }, - { - "name": "direction", - "type": "string", - "required": false, - "source": "body", - "description": "direction 参数" - }, - { - "name": "height", - "type": "number", - "required": false, - "source": "body", - "description": "height 参数" - }, - { - "name": "length", - "type": "number", - "required": false, - "source": "body", - "description": "length 参数" - }, - { - "name": "rack_columns", - "type": "string", - "required": false, - "source": "body", - "description": "rack_columns 参数" - }, - { - "name": "rack_levels", - "type": "string", - "required": false, - "source": "body", - "description": "rack_levels 参数" - }, - { - "name": "rack_rows", - "type": "string", - "required": false, - "source": "body", - "description": "rack_rows 参数" - }, - { - "name": "width", - "type": "number", - "required": false, - "source": "body", - "description": "width 参数" - }, - { - "name": "x", - "type": "number", - "required": false, - "source": "body", - "description": "x 参数" - }, - { - "name": "y", - "type": "number", - "required": false, - "source": "body", - "description": "y 参数" - }, - { - "name": "z", - "type": "number", - "required": false, - "source": "body", - "description": "z 参数" - }, - { - "name": "zone_code", - "type": "string", - "required": false, - "source": "body", - "description": "zone_code 参数" - }, - { - "name": "zone_name", - "type": "string", - "required": false, - "source": "body", - "description": "zone_name 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.delete", - "description": "warehouse.delete 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.detail", - "description": "warehouse.detail 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.checkBarcodeUnique", - "description": "warehouse.checkBarcodeUnique 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "barcode", - "type": "string", - "required": true, - "source": "body", - "description": "barcode 参数" - }, - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.toggleActive", - "description": "warehouse.toggleActive 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - }, - { - "name": "isActive", - "type": "string", - "required": false, - "source": "body", - "description": "isActive 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getPath", - "description": "warehouse.getPath 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.createRack", - "description": "warehouse.createRack 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "height", - "type": "number", - "required": true, - "source": "body", - "description": "height 参数" - }, - { - "name": "length", - "type": "number", - "required": true, - "source": "body", - "description": "length 参数" - }, - { - "name": "rack_columns", - "type": "number", - "required": true, - "source": "body", - "description": "rack_columns 参数" - }, - { - "name": "rack_levels", - "type": "number", - "required": true, - "source": "body", - "description": "rack_levels 参数" - }, - { - "name": "rack_rows", - "type": "number", - "required": true, - "source": "body", - "description": "rack_rows 参数" - }, - { - "name": "warehouse_id", - "type": "number", - "required": true, - "source": "body", - "description": "warehouse_id 参数" - }, - { - "name": "width", - "type": "number", - "required": true, - "source": "body", - "description": "width 参数" - }, - { - "name": "x", - "type": "number", - "required": true, - "source": "body", - "description": "x 参数" - }, - { - "name": "y", - "type": "number", - "required": true, - "source": "body", - "description": "y 参数" - }, - { - "name": "zone_code", - "type": "string", - "required": true, - "source": "body", - "description": "zone_code 参数" - }, - { - "name": "zone_name", - "type": "string", - "required": true, - "source": "body", - "description": "zone_name 参数" - }, - { - "name": "color", - "type": "string", - "required": false, - "source": "body", - "description": "color 参数" - }, - { - "name": "direction", - "type": "string", - "required": false, - "source": "body", - "description": "direction 参数" - }, - { - "name": "parent_id", - "type": "number", - "required": false, - "source": "body", - "description": "parent_id 参数" - }, - { - "name": "z", - "type": "number", - "required": false, - "source": "body", - "description": "z 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getPickPath", - "description": "warehouse.getPickPath 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouse_id", - "type": "number", - "required": true, - "source": "query", - "description": "warehouse_id 参数" - }, - { - "name": "include_spaces", - "type": "string", - "required": false, - "source": "query", - "description": "include_spaces 参数" - }, - { - "name": "limit", - "type": "number", - "required": false, - "source": "query", - "description": "limit 参数" - }, - { - "name": "sort_by", - "type": "string", - "required": false, - "source": "query", - "description": "sort_by 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.updateRackPosition", - "description": "warehouse.updateRackPosition 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "x", - "type": "number", - "required": true, - "source": "body", - "description": "x 参数" - }, - { - "name": "y", - "type": "number", - "required": true, - "source": "body", - "description": "y 参数" - }, - { - "name": "rack_id", - "type": "number", - "required": false, - "source": "path", - "description": "rack_id 参数" - }, - { - "name": "z", - "type": "number", - "required": false, - "source": "body", - "description": "z 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.recalculatePickPath", - "description": "warehouse.recalculatePickPath 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouse_id", - "type": "number", - "required": true, - "source": "body", - "description": "warehouse_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.updateNeighbors", - "description": "warehouse.updateNeighbors 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "warehouse_id", - "type": "number", - "required": true, - "source": "body", - "description": "warehouse_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getAreaRacks", - "description": "warehouse.getAreaRacks 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "area_id", - "type": "number", - "required": true, - "source": "query", - "description": "area_id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getSpacesByRack", - "description": "warehouse.getSpacesByRack 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.createRackWithSpaces", - "description": "warehouse.createRackWithSpaces 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.getSpaceInfo", - "description": "warehouse.getSpaceInfo 接口", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": false, - "source": "body", - "description": "id 参数" - } - ], - "response": [], - "errors": [] - }, - { - "method": "warehouse.updateSpaceInfo", - "description": "warehouse.updateSpaceInfo 接口", - "isNeedAuth": true, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "id", - "type": "number", - "required": true, - "source": "body", - "description": "id 参数" - }, - { - "name": "custom_barcode", - "type": "string", - "required": false, - "source": "body", - "description": "custom_barcode 参数" - }, - { - "name": "custom_name", - "type": "string", - "required": false, - "source": "body", - "description": "custom_name 参数" - }, - { - "name": "location_type_id", - "type": "number", - "required": false, - "source": "body", - "description": "location_type_id 参数" - }, - { - "name": "pick_sequence", - "type": "string", - "required": false, - "source": "body", - "description": "pick_sequence 参数" - }, - { - "name": "space_status", - "type": "string", - "required": false, - "source": "body", - "description": "space_status 参数" - } - ], - "response": [], - "errors": [] - } - ] - } - ] + ] + }, + { + "type": "string", + "required": true, + "name": "project", + "description": "项目标识,如 all/warehouse/store/tms", + "list": [ + { + "value": "all", + "name": "全部" + }, + { + "value": "warehouse", + "name": "仓库" + }, + { + "value": "store", + "name": "货主" + }, + { + "value": "tms", + "name": "物流" + } + ] } + ], + "methods": { + "groups": [ + { + "groupName": "配置模块", + "module": "config", + "list": [ + { + "method": "config.list", + "description": "config.list 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "看板模块", + "module": "dashboard", + "list": [ + { + "method": "dashboard.storeStats", + "description": "dashboard.storeStats 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.warehouseStats", + "description": "dashboard.warehouseStats 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.hot_order_rank", + "description": "dashboard.hot_order_rank 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.express_ratio", + "description": "dashboard.express_ratio 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.platform_distribution", + "description": "dashboard.platform_distribution 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "dashboard.order_trend", + "description": "dashboard.order_trend 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "基础模块", + "module": "index", + "list": [ + { + "method": "index.fastWhereTree", + "description": "index.fastWhereTree 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "type 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.loadStores", + "description": "index.loadStores 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getCOSUploadConfig", + "description": "index.getCOSUploadConfig 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "data 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.getImages", + "description": "index.getImages 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.uploadSuccessNotify", + "description": "index.uploadSuccessNotify 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.ReferenceFile", + "description": "index.ReferenceFile 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getMessageDetail", + "description": "index.getMessageDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getI18nMessage", + "description": "index.getI18nMessage 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "language", + "type": "string", + "required": false, + "source": "body|query", + "description": "language 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.putI18nCollect", + "description": "index.putI18nCollect 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "keys", + "type": "array", + "required": false, + "source": "body", + "description": "keys 参数" + }, + { + "name": "locale", + "type": "string", + "required": false, + "source": "body", + "description": "locale 参数" + }, + { + "name": "project", + "type": "string", + "required": false, + "source": "body", + "description": "project 参数" + }, + { + "name": "source", + "type": "string", + "required": false, + "source": "body", + "description": "source 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "index.tryAutoTranslateNewKeys", + "description": "index.tryAutoTranslateNewKeys 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.searchSpace", + "description": "index.searchSpace 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "index.getExpressList", + "description": "index.getExpressList 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "订单模块", + "module": "order", + "list": [ + { + "method": "order.getOrderModels", + "description": "order.getOrderModels 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.list", + "description": "分页查询订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.detail", + "description": "查询订单详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.listItems", + "description": "查询订单商品明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.stats", + "description": "订单统计", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.getreviewOrderlist", + "description": "分页查询订单审核列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.updateStatus", + "description": "更新订单状态", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.updateDeliveryTime", + "description": "更新发货时间", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.reviewOrder", + "description": "订单审核", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "order.reviewOrder.getreviewOrderlist", + "description": "分页查询订单审核列表(目录化路由)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.reviewOrder.reviewOrder", + "description": "订单审核(目录化路由)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "inspection_status", + "type": "string", + "required": false, + "source": "body", + "description": "inspection_status 参数" + }, + { + "name": "operate_time", + "type": "string", + "required": false, + "source": "body", + "description": "operate_time 参数" + }, + { + "name": "operator_name", + "type": "string", + "required": false, + "source": "body", + "description": "operator_name 参数" + }, + { + "name": "review_status", + "type": "string", + "required": false, + "source": "body", + "description": "review_status 参数" + }, + { + "name": "reviewStatus", + "type": "string", + "required": false, + "source": "body", + "description": "reviewStatus 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.deliveryOrder.getdeliveryOrderlist", + "description": "分页查询已进入出库流程的订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.pendingOrder.getpendingOrderlist", + "description": "分页查询待处理订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.expectionOrder.getexpectionOrderlist", + "description": "分页查询异常订单列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "order.archiveOrder.getarchiveOrderlist", + "description": "分页查询归档订单列表(暂使用当前订单表完成态数据)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印模块", + "module": "print", + "list": [ + { + "method": "print.send", + "description": "print.send 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "computerId", + "type": "string", + "required": false, + "source": "body", + "description": "computerId 参数" + }, + { + "name": "count", + "type": "number", + "required": false, + "source": "body", + "description": "count 参数" + }, + { + "name": "data", + "type": "object", + "required": false, + "source": "body", + "description": "data 参数" + }, + { + "name": "printer", + "type": "string", + "required": false, + "source": "body", + "description": "printer 参数" + }, + { + "name": "template", + "type": "object", + "required": false, + "source": "body", + "description": "template 参数" + }, + { + "name": "timestamp", + "type": "string", + "required": false, + "source": "body", + "description": "timestamp 参数" + }, + { + "name": "type", + "type": "string", + "required": false, + "source": "body", + "description": "type 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getPrintResult", + "description": "print.getPrintResult 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "printId", + "type": "string", + "required": true, + "source": "body", + "description": "printId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getPrintRecordItem", + "description": "print.getPrintRecordItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getList", + "description": "print.getList 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "print.getItem", + "description": "print.getItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.add", + "description": "print.add 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "computer_id", + "type": "number", + "required": true, + "source": "body", + "description": "computer_id 参数" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "default_printer_name", + "type": "string", + "required": false, + "source": "body", + "description": "default_printer_name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.hasName", + "description": "print.hasName 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.updateItem", + "description": "print.updateItem 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "computer_id", + "type": "number", + "required": false, + "source": "body", + "description": "computer_id 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.del", + "description": "print.del 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "ids 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.getComputer", + "description": "print.getComputer 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "print.getComputerPrinter", + "description": "print.getComputerPrinter 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "print.savePrinters", + "description": "print.savePrinters 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "defaultPrinter", + "type": "string", + "required": true, + "source": "body", + "description": "defaultPrinter 参数" + }, + { + "name": "express", + "type": "array", + "required": false, + "source": "body", + "description": "express 参数" + }, + { + "name": "print_station_id", + "type": "number", + "required": false, + "source": "body", + "description": "print_station_id 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印机站点模块", + "module": "printer.station", + "list": [ + { + "method": "printer.station.list", + "description": "获取打印站点列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "打印模板模块", + "module": "setting.printTemplate", + "list": [ + { + "method": "setting.printTemplate.list", + "description": "获取打印模板树", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.printTemplate.save", + "description": "保存打印模板", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "setting.printTemplate.create", + "description": "创建打印模板(platform 固定为 default,template_type 固定为 CUSTOM,template_url 固定为空字符串)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "business_type", + "type": "string", + "required": true, + "source": "body", + "description": "business_type 参数" + }, + { + "name": "template_name", + "type": "string", + "required": true, + "source": "body", + "description": "template_name 参数" + }, + { + "name": "page_height", + "type": "string", + "required": false, + "source": "body", + "description": "page_height 参数" + }, + { + "name": "page_width", + "type": "string", + "required": false, + "source": "body", + "description": "page_width 参数" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建模板ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误(缺少 template_name、business_type、page_width 或 page_height)" + }, + { + "code": "409", + "description": "同一业务类型和平台下已存在自定义模板" + } + ] + }, + { + "method": "setting.printTemplate.delete", + "description": "删除打印模板(软删除)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "删除的模板ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误(缺少 id)" + }, + { + "code": "404", + "description": "模板不存在或无权限" + } + ] + }, + { + "method": "setting.printTemplate.listTemplatesByType", + "description": "按业务类型查询模板", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "businessType", + "type": "string", + "required": true, + "source": "body", + "description": "businessType 参数" + } + ], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "账号管理模块", + "module": "setting.account", + "list": [ + { + "method": "setting.account.list", + "description": "查询当前主体下且在当前账号角色组可操作范围内的工号列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "data[]", + "type": "object", + "required": true, + "description": "工号列表项" + }, + { + "name": "data[].employee_id", + "type": "number", + "required": true, + "description": "工号ID" + }, + { + "name": "data[].account_id", + "type": "number", + "required": true, + "description": "账号ID" + }, + { + "name": "data[].store_id", + "type": "number", + "required": true, + "description": "主体ID" + }, + { + "name": "data[].real_name", + "type": "string", + "required": true, + "description": "工号姓名" + }, + { + "name": "data[].status", + "type": "number", + "required": true, + "description": "工号状态:1=启用,0=停用" + }, + { + "name": "data[].username", + "type": "string", + "required": true, + "description": "账号用户名" + }, + { + "name": "data[].phone", + "type": "string", + "required": true, + "description": "账号手机号" + }, + { + "name": "data[].email", + "type": "string", + "required": true, + "description": "账号邮箱" + }, + { + "name": "data[].avatar_file_id", + "type": "number", + "required": false, + "description": "头像文件ID,为空表示未设置" + }, + { + "name": "data[].avatar_url", + "type": "string", + "required": true, + "description": "头像访问地址" + }, + { + "name": "data[].is_wechat_bound", + "type": "boolean", + "required": true, + "description": "账号是否已绑定微信" + }, + { + "name": "data[].ye4s_user_id", + "type": "number", + "required": false, + "description": "已绑定时对应的 ye4s 用户ID,未绑定为空" + }, + { + "name": "data[].role_ids", + "type": "number[]", + "required": true, + "description": "工号绑定的角色ID数组" + }, + { + "name": "data[].roles[]", + "type": "object", + "required": true, + "description": "工号绑定的角色组详情" + }, + { + "name": "data[].roles[].role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "data[].roles[].role_code", + "type": "string", + "required": true, + "description": "角色编码" + }, + { + "name": "data[].roles[].role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "data[].roles[].pid", + "type": "number", + "required": true, + "description": "父级角色ID" + }, + { + "name": "data[].roles[].status", + "type": "number", + "required": true, + "description": "角色状态:1=启用,0=停用" + } + ], + "errors": [ + { + "code": "400", + "description": "当前登录态缺少主体上下文(store_id)或 where 参数解析失败" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.account.add", + "description": "新增工号,按手机号复用或创建账号后绑定到当前主体,并校验角色组 ids 不超出当前角色范围", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "新增或复用后的工号ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "绑定账号ID" + }, + { + "name": "role_id", + "type": "number", + "required": true, + "description": "绑定后的角色ID" + }, + { + "name": "role_ids", + "type": "number[]", + "required": true, + "description": "绑定后的角色组ID数组" + }, + { + "name": "is_new_account", + "type": "boolean", + "required": true, + "description": "是否为本次新建账号" + }, + { + "name": "phone", + "type": "string", + "required": true, + "description": "绑定账号手机号" + }, + { + "name": "username", + "type": "string", + "required": true, + "description": "绑定账号用户名" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、手机号格式错误、直接使用保留名称、或 ids 超出当前角色范围" + }, + { + "code": "409", + "description": "手机号对应账号已禁用、手机号已绑定当前主体工号、或用户名重复" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.account.delete", + "description": "删除工号绑定关系,仅停用工号,不删除账号", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "被停用的工号ID" + }, + { + "name": "account_id", + "type": "number", + "required": true, + "description": "关联账号ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + }, + { + "name": "already_deleted", + "type": "boolean", + "required": false, + "description": "可选,true 表示该工号原本已停用" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或尝试删除当前登录工号" + }, + { + "code": "404", + "description": "工号不存在或无权限删除" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.account.update", + "description": "更新工号姓名、头像引用和角色组 ids(含当前角色范围校验)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": true, + "description": "更新后的工号ID" + }, + { + "name": "real_name", + "type": "string", + "required": true, + "description": "更新后的工号姓名" + }, + { + "name": "avatar_file_id", + "type": "number", + "required": false, + "description": "更新后的头像文件ID" + }, + { + "name": "avatar_url", + "type": "string", + "required": true, + "description": "更新后的头像地址" + }, + { + "name": "role_ids", + "type": "number[]", + "required": true, + "description": "更新后的角色组ID数组" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、未传 ids、或 ids 超出当前角色范围" + }, + { + "code": "404", + "description": "工号或头像文件不存在" + }, + { + "code": "500", + "description": "更新失败" + } + ] + }, + { + "method": "setting.account.getBindWechatCode", + "description": "为当前账号可操作范围内的其他账号获取微信绑定状态与绑定码,复用个人绑定微信逻辑", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "目标账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "description": "绑定码(已绑定时为空字符串)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "绑定状态:pending/scanned/bound" + }, + { + "name": "is_bound", + "type": "boolean", + "required": true, + "description": "是否已绑定微信" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒),bound 状态可为空" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": true, + "description": "距离过期剩余毫秒数" + }, + { + "name": "scanned_at", + "type": "string", + "required": false, + "description": "扫码时间(未扫码可为空)" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 cache/generated/refreshed/db" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "已绑定的 ye4s 用户ID(未绑定可为空)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少 user_id 或当前账号角色范围为空" + }, + { + "code": "403", + "description": "目标账号超出当前操作范围" + }, + { + "code": "404", + "description": "目标账号不存在或不在当前主体下" + }, + { + "code": "500", + "description": "获取绑定码失败" + } + ] + }, + { + "method": "setting.account.unbindWechat", + "description": "为当前账号可操作范围内的其他账号解除微信绑定,复用个人解绑微信逻辑", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "目标账号ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 unbound" + }, + { + "name": "matched_rows", + "type": "number", + "required": true, + "description": "匹配到的 ye4s 绑定记录数" + }, + { + "name": "affected_rows", + "type": "number", + "required": true, + "description": "实际更新的 ye4s 记录数" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "解绑时间(ISO 时间)" + } + ], + "errors": [ + { + "code": "400", + "description": "缺少 user_id 或当前账号角色范围为空" + }, + { + "code": "403", + "description": "目标账号超出当前操作范围" + }, + { + "code": "404", + "description": "目标账号不存在或不在当前主体下" + }, + { + "code": "500", + "description": "解绑失败" + } + ] + } + ] + }, + { + "groupName": "角色管理模块", + "module": "setting.role", + "list": [ + { + "method": "setting.role.list", + "description": "查询当前登录工号的下级角色列表,不返回自己及同级角色,并携带各角色的 permission_ids 权限集;返回 [\"*\"] 表示拥有全部权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "employee_id", + "type": "number", + "required": false, + "description": "当前登录工号ID,未识别到登录工号时为 null" + }, + { + "name": "roles[]", + "type": "object", + "required": true, + "description": "下级角色树列表(第一层为当前登录工号角色的直接下级)" + }, + { + "name": "roles[].role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "roles[].role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "roles[].selected", + "type": "boolean", + "required": true, + "description": "表示当前登录工号是否已绑定该角色" + }, + { + "name": "roles[].permission_ids", + "type": "number[]|string[]", + "required": true, + "description": "该角色已绑定的权限ID集合;返回 [\"*\"] 表示拥有全部权限,嵌套 children 节点结构相同" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "工号不存在或无权限" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.role.permission", + "description": "查询全量角色权限列表(不按当前登录工号权限集筛选),兼容旧入口,用于总管理员管理权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "role_id", + "type": "number", + "required": false, + "description": "查询目标角色ID,未传 role_id 时返回当前登录工号的当前角色ID" + }, + { + "name": "permissions[]", + "type": "object[]", + "required": true, + "description": "全量权限列表(不按当前登录工号权限集裁剪)" + }, + { + "name": "permissions[].permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "permissions[].selected", + "type": "boolean", + "required": true, + "description": "当传入或解析出 role_id 时,表示该角色是否已绑定该权限" + } + ], + "errors": [ + { + "code": "400", + "description": "role_id/type 参数错误或当前主体无可用权限" + }, + { + "code": "404", + "description": "角色不存在或无权限操作" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.role.add", + "description": "新增角色并一次性提交权限集(permission_ids);传 [\"*\"] 表示所有权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "role_id", + "type": "number", + "required": true, + "description": "新建角色ID" + }, + { + "name": "role_code", + "type": "string", + "required": true, + "description": "角色编码" + }, + { + "name": "role_name", + "type": "string", + "required": true, + "description": "角色名称" + }, + { + "name": "permission_ids", + "type": "number[]|string[]", + "required": true, + "description": "提交后的权限ID集合;返回 [\"*\"] 表示所有权限" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、permission_ids 非法,或目标权限不存在/已禁用" + }, + { + "code": "409", + "description": "role_code 冲突" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.role.delete", + "description": "批量删除角色(软删除)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的角色ID数组" + }, + { + "name": "deleted_ids", + "type": "number[]", + "required": true, + "description": "本次实际删除(由启用变为停用)的角色ID数组" + }, + { + "name": "already_deleted_ids", + "type": "number[]", + "required": true, + "description": "本就处于删除状态的角色ID数组" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,ids 必须为正整数数组" + }, + { + "code": "404", + "description": "角色不存在、无权限操作或为系统预设角色(任一ID不满足即失败)" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.role.update", + "description": "更新角色信息并一次性重置角色权限(permission_ids);传 [\"*\"] 表示所有权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "role_id", + "type": "number", + "required": true, + "description": "角色ID" + }, + { + "name": "permission_ids", + "type": "number[]|string[]", + "required": true, + "description": "更新后的权限ID集合;返回 [\"*\"] 表示所有权限" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、permission_ids 非法,或目标权限不存在/已禁用" + }, + { + "code": "404", + "description": "角色不存在、无权限操作或为系统预设角色" + }, + { + "code": "409", + "description": "角色信息冲突" + }, + { + "code": "500", + "description": "更新失败" + } + ] + } + ] + }, + { + "groupName": "权限管理模块", + "module": "setting.permission", + "list": [ + { + "method": "setting.permission.list", + "description": "查询全量权限集合(不按当前登录工号权限集筛选),可选按角色返回已绑定权限选中状态,用于总管理员管理权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "role_id", + "type": "number", + "required": false, + "description": "查询目标角色ID,未传 role_id 时返回当前登录工号的当前角色ID" + }, + { + "name": "permissions[]", + "type": "object", + "required": true, + "description": "全量权限列表(不按当前登录工号权限集裁剪)" + }, + { + "name": "permissions[].permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "permissions[].path", + "type": "string", + "required": true, + "description": "权限路径" + }, + { + "name": "permissions[].name", + "type": "string", + "required": true, + "description": "权限名称" + }, + { + "name": "permissions[].type", + "type": "string", + "required": true, + "description": "权限类型" + }, + { + "name": "permissions[].component", + "type": "string", + "required": false, + "description": "前端路由组件路径" + }, + { + "name": "permissions[].redirect", + "type": "string", + "required": false, + "description": "前端路由重定向路径" + }, + { + "name": "permissions[].meta_title", + "type": "string", + "required": false, + "description": "菜单/页面标题" + }, + { + "name": "permissions[].meta_icon", + "type": "string", + "required": false, + "description": "菜单图标" + }, + { + "name": "permissions[].hidden", + "type": "number", + "required": true, + "description": "是否隐藏菜单:1=隐藏,0=显示" + }, + { + "name": "permissions[].always_show", + "type": "number", + "required": true, + "description": "是否总是显示父级菜单:1=是,0=否" + }, + { + "name": "permissions[].selected", + "type": "boolean", + "required": true, + "description": "当传入 role_id 时,表示该权限是否已绑定" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "角色不存在或无权限" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "setting.permission.add", + "description": "新增权限;仅校验请求参数与父级权限是否存在,不再校验当前账号是否覆盖该权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "path", + "type": "string", + "required": true, + "description": "权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "权限类型" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或 parent_id 不存在/不可用" + }, + { + "code": "404", + "description": "父级权限不存在" + }, + { + "code": "500", + "description": "新增失败" + } + ] + }, + { + "method": "setting.permission.delete", + "description": "批量删除权限(软删除);仅校验请求中的权限ID是否合法且存在", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "ids", + "type": "number[]", + "required": true, + "description": "请求的权限ID数组" + }, + { + "name": "deleted_ids", + "type": "number[]", + "required": true, + "description": "本次实际删除(由启用变为停用)的权限ID数组" + }, + { + "name": "already_deleted_ids", + "type": "number[]", + "required": true, + "description": "本就处于删除状态的权限ID数组" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "固定返回 deleted" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误,ids 非法或包含不存在的权限ID" + }, + { + "code": "404", + "description": "权限不存在" + }, + { + "code": "500", + "description": "删除失败" + } + ] + }, + { + "method": "setting.permission.update", + "description": "更新权限;仅校验请求参数、目标权限及父级权限是否存在,不再校验当前账号是否覆盖该权限", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "permission_id", + "type": "number", + "required": true, + "description": "权限ID" + }, + { + "name": "path", + "type": "string", + "required": true, + "description": "更新后的权限路径" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "更新后的权限类型" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误、未提供更新项,或目标/父级权限不存在或不可用" + }, + { + "code": "404", + "description": "权限不存在" + }, + { + "code": "500", + "description": "更新失败" + } + ] + } + ] + }, + { + "groupName": "货主管理模块", + "module": "storeWarehouse", + "list": [ + { + "method": "storeWarehouse.store.list", + "description": "查询当前主体下的仓库-货主签约列表;当前主体是仓库时默认查看本仓下货主,当前主体是货主时默认查看本货主下签约仓库,`remask` 表示当前主体给对方设置的通用名/备注", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "签约关系数据列表" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "总条数" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storeWarehouse.store.sign", + "description": "签约接口,支持双阶段流程:1)不传 `temp_code` 时由当前主体发起签约并生成临时码;2)对方主体携带 `temp_code` 预览或确认后,立即写入签约表并生效", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "mode", + "type": "string", + "required": true, + "description": "initiate / preview / confirm" + }, + { + "name": "temp_code", + "type": "string", + "required": false, + "description": "临时码" + }, + { + "name": "contract", + "type": "object", + "required": false, + "description": "确认签约后返回签约关系" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或确认方不合法" + }, + { + "code": "403", + "description": "当前主体无权使用临时码" + }, + { + "code": "404", + "description": "签约对象不存在或临时码失效" + }, + { + "code": "500", + "description": "签约失败" + } + ] + }, + { + "method": "storeWarehouse.store.unbind", + "description": "解除/恢复仓库-货主签约可用状态;双方均可执行,本接口只变更 `use_status`", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "contract", + "type": "object", + "required": true, + "description": "更新后的关系对象" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误" + }, + { + "code": "404", + "description": "签约关系不存在或无权限操作" + }, + { + "code": "500", + "description": "更新失败" + } + ] + }, + { + "method": "storeWarehouse.store.rename", + "description": "修改当前主体给对方设置的签约显示名称/备注;当前主体为仓库时会更新 `store_remask`,当前主体为货主时会更新 `warehouse_remask`", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "contract", + "type": "object", + "required": true, + "description": "更新后的签约关系" + } + ], + "errors": [ + { + "code": "400", + "description": "参数错误或未提供 `remask`" + }, + { + "code": "404", + "description": "签约关系不存在或无权限操作" + }, + { + "code": "500", + "description": "修改签约名称失败" + } + ] + } + ] + }, + { + "groupName": "商品模块", + "module": "stock", + "list": [ + { + "method": "stock.warehouse.list", + "description": "仓库商品列表查询(支持 where 条件与分页)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getProhibitedType", + "description": "查询违禁品类型列表(系统预设+仓库自定义)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getInfo", + "description": "查询仓库商品详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.saveWarehouseStock", + "description": "更新仓库商品资料", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.createWarehouseStock", + "description": "新建仓库商品资料", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getBarcodes", + "description": "查询商品条码列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.saveWarehouseStockBarcode", + "description": "保存商品条码信息", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getStoreStocks", + "description": "查询仓库商品与货主关联列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.bindItem", + "description": "绑定货主商品关系", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.unbindItem", + "description": "解绑货主商品关系", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.checkItemCodeUnique", + "description": "校验商品编码在货主维度唯一性", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "item_code", + "type": "string", + "required": true, + "source": "body", + "description": "item_code 参数" + }, + { + "name": "store_id", + "type": "number", + "required": true, + "source": "body", + "description": "store_id 参数" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.queryStockLogs", + "description": "查询库存操作日志", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "string", + "required": false, + "source": "body", + "description": "warehouseId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.handleBatchDelete", + "description": "批量删除仓库商品资料", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.deleteUnit", + "description": "删除库存单位", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.deleteProhibited", + "description": "删除违禁品类型", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.handleBatchChange", + "description": "批量修改仓库商品字段", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getStockUnits", + "description": "查询可用库存单位(系统+仓库)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.getUnitList", + "description": "查询当前仓库自定义单位列表", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.createProhibited", + "description": "新增违禁品类型", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.createUnit", + "description": "新增库存单位", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "stock.warehouse.search", + "description": "仓库商品关键字搜索", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "库存模块", + "module": "storage", + "list": [ + { + "method": "storage.receiving.getReceivingList", + "description": "storage.receiving.getReceivingList 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "sort", + "type": "string", + "required": false, + "source": "body", + "description": "sort 参数" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "收货单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "汇总信息(total_quantity、total_locked、total_available、total_items)" + } + ], + "errors": [ + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storage.receiving.getReceivingDetail", + "description": "storage.receiving.getReceivingDetail 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "receiving", + "type": "object", + "required": true, + "description": "收货单详情(含 details、images、pagination)" + } + ], + "errors": [ + { + "code": "0", + "description": "无记录或无权访问" + }, + { + "code": "500", + "description": "服务器错误" + } + ] + }, + { + "method": "storage.receiving.batchCancelReceiving", + "description": "storage.receiving.batchCancelReceiving 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "message", + "type": "string", + "required": true, + "description": "批量作废处理结果" + } + ], + "errors": [ + { + "code": "0", + "description": "部分单据不存在、无权访问或状态不允许作废" + }, + { + "code": "500", + "description": "服务器错误" + } + ] + }, + { + "method": "storage.receiving.create", + "description": "storage.receiving.create 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + } + ], + "errors": [ + { + "code": "0", + "description": "创建失败(如字段枚举不合法、数据库约束异常)" + } + ] + }, + { + "method": "storage.receiving.addItem", + "description": "storage.receiving.addItem 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "item", + "type": "object", + "required": false, + "source": "body", + "description": "item 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.removeItem", + "description": "storage.receiving.removeItem 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + }, + { + "name": "item_id", + "type": "number", + "required": false, + "source": "body", + "description": "item_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.saveReceiving", + "description": "storage.receiving.saveReceiving 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.get", + "description": "storage.receiving.get 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.addDetail", + "description": "storage.receiving.addDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.bindDetailProduct", + "description": "绑定或改绑收货单明细商品,入参为收货单明细ID和商品ID;会更新明细的 `system_product_id` 与 `product_name`。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单明细ID" + }, + { + "name": "system_product_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品ID,必须属于当前仓库" + } + ], + "response": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "description": "收货单明细ID" + }, + { + "name": "system_product_id", + "type": "number", + "required": true, + "description": "绑定后的商品ID" + }, + { + "name": "product_name", + "type": "string", + "required": true, + "description": "绑定后回填的商品名称" + } + ], + "errors": [ + { + "code": "400", + "description": "参数缺失或收货单状态不允许绑定/改绑商品" + }, + { + "code": "404", + "description": "收货单明细不存在,或商品不存在/不属于当前仓库" + }, + { + "code": "500", + "description": "绑定商品失败" + } + ] + }, + { + "method": "storage.receiving.deleteDetail", + "description": "storage.receiving.deleteDetail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.detailChange", + "description": "storage.receiving.detailChange 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.cancel", + "description": "storage.receiving.cancel 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.receiving.completeReceiving", + "description": "storage.receiving.completeReceiving 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "storage.entry.list", + "description": "入库单列表查询", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "pagination 参数" + }, + { + "name": "sort", + "type": "string", + "required": false, + "source": "body", + "description": "sort 参数" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "入库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "状态汇总(total、pending、creating、created、completed、cancelled)" + } + ], + "errors": [ + { + "code": "400", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "description": "查询失败" + } + ] + }, + { + "method": "storage.entry.get", + "description": "查询入库单详情", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "entryOrder", + "type": "object", + "required": true, + "description": "入库单详情(含 items 明细)" + } + ], + "errors": [ + { + "code": "400", + "description": "id 与 entry_order_code 均未传" + }, + { + "code": "0", + "description": "无记录或无权访问" + } + ] + }, + { + "method": "storage.entry.create", + "description": "创建入库单", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + } + ], + "errors": [ + { + "code": "400", + "description": "参数缺失或业务类型不合法" + }, + { + "code": "409", + "description": "入库单号已存在" + } + ] + }, + { + "method": "storage.entry.addDetail", + "description": "新增入库明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "新建明细ID" + }, + { + "name": "order_id", + "type": "number", + "required": true, + "description": "所属入库单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或状态不允许新增明细" + }, + { + "code": "404", + "description": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.deleteDetail", + "description": "删除入库明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "删除成功的明细ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或明细已有收货数量" + }, + { + "code": "404", + "description": "明细或入库单不存在" + } + ] + }, + { + "method": "storage.entry.detailChange", + "description": "修改入库明细", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "修改成功的明细ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或没有可更新字段" + }, + { + "code": "404", + "description": "明细或入库单不存在" + } + ] + }, + { + "method": "storage.entry.cancel", + "description": "作废入库单", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "作废成功的入库单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法或已完成单据不允许作废" + }, + { + "code": "404", + "description": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.completeEntry", + "description": "完成入库单", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "完成成功的入库单ID" + } + ], + "errors": [ + { + "code": "400", + "description": "参数不合法、已作废或缺少明细" + }, + { + "code": "404", + "description": "入库单不存在或无权访问" + } + ] + } + ] + }, + { + "groupName": "主体模块", + "module": "store", + "list": [ + { + "method": "store.createStore", + "description": "store.createStore 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.createWarehouse", + "description": "store.createWarehouse 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.joinStore", + "description": "store.joinStore 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.joinWarehouse", + "description": "store.joinWarehouse 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.getStoreRoles", + "description": "store.getStoreRoles 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "store.auditApply", + "description": "store.auditApply 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "用户模块", + "module": "user", + "list": [ + { + "method": "user.login", + "description": "用户登录(仅返回 token)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "password", + "type": "string", + "required": false, + "source": "body", + "description": "password 参数" + }, + { + "name": "username", + "type": "string", + "required": false, + "source": "body", + "description": "username 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.loginByCode", + "description": "登录码登录(使用本系统缓存登录码,不依赖 ye4s_user.tmp_code)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "code 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.getLoginWechatCode", + "description": "获取微信扫码登录码:不传客户端编码时生成新的6位客户端编码与登录码;传客户端编码且缓存命中时进入长轮询,优先监听 Redis 登录事件,收到 ye4s_user_id 后立即签发登录 token;未收到事件则刷新登录码返回", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [ + { + "name": "client_code", + "type": "string", + "required": true, + "description": "客户端编码(6位字母数字混合)" + }, + { + "name": "code", + "type": "string", + "required": false, + "description": "微信扫码登录码(6位字母数字混合)。当 status=authorized 时可能为空" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "登录状态:pending(等待扫码)或 authorized(已完成登录)" + }, + { + "name": "updated_at", + "type": "string", + "required": false, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒)" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": false, + "description": "距离过期剩余毫秒数" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 generated/refreshed/cache/event" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "当 status=authorized 时返回的 ye4s 用户ID" + }, + { + "name": "loginToken", + "type": "string", + "required": false, + "description": "当 status=authorized 时返回的本地登录 token" + } + ], + "errors": [] + }, + { + "method": "user.getBindWechatCode", + "description": "获取微信绑定状态与绑定码:绑定码为6位字母数字混合且固定60秒有效,默认立即返回;longPoll=true 时最长等待60秒,若无事件则自动刷新新码返回", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "WMS 账号ID" + }, + { + "name": "code", + "type": "string", + "required": true, + "description": "绑定码(已绑定时为空字符串)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "绑定状态:pending/scanned/bound" + }, + { + "name": "is_bound", + "type": "boolean", + "required": true, + "description": "是否已绑定微信" + }, + { + "name": "updated_at", + "type": "string", + "required": true, + "description": "状态更新时间(ISO 时间)" + }, + { + "name": "expires_at", + "type": "number", + "required": false, + "description": "过期时间戳(毫秒),bound 状态可为空" + }, + { + "name": "expire_after_ms", + "type": "number", + "required": true, + "description": "距离过期剩余毫秒数" + }, + { + "name": "scanned_at", + "type": "string", + "required": false, + "description": "扫码时间(未扫码可为空)" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 cache/generated/refreshed/db" + }, + { + "name": "ye4s_user_id", + "type": "number", + "required": false, + "description": "已绑定的 ye4s 用户ID(未绑定可为空)" + } + ], + "errors": [] + }, + { + "method": "user.unbindWechat", + "description": "解绑微信账号(清理 ye4s 关联账号数据)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.logout", + "description": "用户登出", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.info", + "description": "获取当前用户信息", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.changeRole", + "description": "user.changeRole 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "user.register", + "description": "user.register 接口", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [], + "response": [], + "errors": [] + } + ] + }, + { + "groupName": "仓库模块", + "module": "warehouse", + "list": [ + { + "method": "warehouse.getWarehouseZones", + "description": "warehouse.getWarehouseZones 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getWarehouseTree", + "description": "warehouse.getWarehouseTree 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouseId", + "type": "number", + "required": true, + "source": "body", + "description": "warehouseId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getChildren", + "description": "warehouse.getChildren 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "zoneId", + "type": "number", + "required": true, + "source": "body", + "description": "zoneId 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.create", + "description": "warehouse.create 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, + { + "method": "warehouse.update", + "description": "warehouse.update 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "aisles", + "type": "string", + "required": false, + "source": "body", + "description": "aisles 参数" + }, + { + "name": "cell_height", + "type": "string", + "required": false, + "source": "body", + "description": "cell_height 参数" + }, + { + "name": "cell_length", + "type": "string", + "required": false, + "source": "body", + "description": "cell_length 参数" + }, + { + "name": "cell_width", + "type": "string", + "required": false, + "source": "body", + "description": "cell_width 参数" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "direction 参数" + }, + { + "name": "height", + "type": "number", + "required": false, + "source": "body", + "description": "height 参数" + }, + { + "name": "length", + "type": "number", + "required": false, + "source": "body", + "description": "length 参数" + }, + { + "name": "rack_columns", + "type": "string", + "required": false, + "source": "body", + "description": "rack_columns 参数" + }, + { + "name": "rack_levels", + "type": "string", + "required": false, + "source": "body", + "description": "rack_levels 参数" + }, + { + "name": "rack_rows", + "type": "string", + "required": false, + "source": "body", + "description": "rack_rows 参数" + }, + { + "name": "width", + "type": "number", + "required": false, + "source": "body", + "description": "width 参数" + }, + { + "name": "x", + "type": "number", + "required": false, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": false, + "source": "body", + "description": "y 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + }, + { + "name": "zone_code", + "type": "string", + "required": false, + "source": "body", + "description": "zone_code 参数" + }, + { + "name": "zone_name", + "type": "string", + "required": false, + "source": "body", + "description": "zone_name 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.delete", + "description": "warehouse.delete 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.detail", + "description": "warehouse.detail 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.checkBarcodeUnique", + "description": "warehouse.checkBarcodeUnique 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "barcode 参数" + }, + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.toggleActive", + "description": "warehouse.toggleActive 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "isActive", + "type": "string", + "required": false, + "source": "body", + "description": "isActive 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getPath", + "description": "warehouse.getPath 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.createRack", + "description": "warehouse.createRack 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "height", + "type": "number", + "required": true, + "source": "body", + "description": "height 参数" + }, + { + "name": "length", + "type": "number", + "required": true, + "source": "body", + "description": "length 参数" + }, + { + "name": "rack_columns", + "type": "number", + "required": true, + "source": "body", + "description": "rack_columns 参数" + }, + { + "name": "rack_levels", + "type": "number", + "required": true, + "source": "body", + "description": "rack_levels 参数" + }, + { + "name": "rack_rows", + "type": "number", + "required": true, + "source": "body", + "description": "rack_rows 参数" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + }, + { + "name": "width", + "type": "number", + "required": true, + "source": "body", + "description": "width 参数" + }, + { + "name": "x", + "type": "number", + "required": true, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": true, + "source": "body", + "description": "y 参数" + }, + { + "name": "zone_code", + "type": "string", + "required": true, + "source": "body", + "description": "zone_code 参数" + }, + { + "name": "zone_name", + "type": "string", + "required": true, + "source": "body", + "description": "zone_name 参数" + }, + { + "name": "color", + "type": "string", + "required": false, + "source": "body", + "description": "color 参数" + }, + { + "name": "direction", + "type": "string", + "required": false, + "source": "body", + "description": "direction 参数" + }, + { + "name": "parent_id", + "type": "number", + "required": false, + "source": "body", + "description": "parent_id 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getPickPath", + "description": "warehouse.getPickPath 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "query", + "description": "warehouse_id 参数" + }, + { + "name": "include_spaces", + "type": "string", + "required": false, + "source": "query", + "description": "include_spaces 参数" + }, + { + "name": "limit", + "type": "number", + "required": false, + "source": "query", + "description": "limit 参数" + }, + { + "name": "sort_by", + "type": "string", + "required": false, + "source": "query", + "description": "sort_by 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateRackPosition", + "description": "warehouse.updateRackPosition 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "x", + "type": "number", + "required": true, + "source": "body", + "description": "x 参数" + }, + { + "name": "y", + "type": "number", + "required": true, + "source": "body", + "description": "y 参数" + }, + { + "name": "rack_id", + "type": "number", + "required": false, + "source": "path", + "description": "rack_id 参数" + }, + { + "name": "z", + "type": "number", + "required": false, + "source": "body", + "description": "z 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.recalculatePickPath", + "description": "warehouse.recalculatePickPath 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateNeighbors", + "description": "warehouse.updateNeighbors 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "warehouse_id", + "type": "number", + "required": true, + "source": "body", + "description": "warehouse_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getAreaRacks", + "description": "warehouse.getAreaRacks 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "area_id", + "type": "number", + "required": true, + "source": "query", + "description": "area_id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getSpacesByRack", + "description": "warehouse.getSpacesByRack 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.createRackWithSpaces", + "description": "warehouse.createRackWithSpaces 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.getSpaceInfo", + "description": "warehouse.getSpaceInfo 接口", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "id 参数" + } + ], + "response": [], + "errors": [] + }, + { + "method": "warehouse.updateSpaceInfo", + "description": "warehouse.updateSpaceInfo 接口", + "isNeedAuth": true, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "id 参数" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "custom_barcode 参数" + }, + { + "name": "custom_name", + "type": "string", + "required": false, + "source": "body", + "description": "custom_name 参数" + }, + { + "name": "location_type_id", + "type": "number", + "required": false, + "source": "body", + "description": "location_type_id 参数" + }, + { + "name": "pick_sequence", + "type": "string", + "required": false, + "source": "body", + "description": "pick_sequence 参数" + }, + { + "name": "space_status", + "type": "string", + "required": false, + "source": "body", + "description": "space_status 参数" + } + ], + "response": [], + "errors": [] + } + ] + } + ] + } } diff --git a/package-lock.json b/package-lock.json index 05547a6..b51cb5b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,12 +22,14 @@ "egg-sequelize": "^6.0.0", "egg-view-ejs": "^3.0.0", "ejs": "^5.0.1", + "exceljs": "^4.4.0", "fast-xml-parser": "^5.3.1", "mysql2": "^3.15.3", "path": "^0.12.7", "qiniu-js": "^3.4.3", "soap": "^1.8.0", - "spark-md5": "^3.0.2" + "spark-md5": "^3.0.2", + "xlsx": "^0.18.5" }, "devDependencies": { "egg-bin": "6", @@ -706,6 +708,47 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/@fast-csv/format": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@fast-csv/format/-/format-4.3.5.tgz", + "integrity": "sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A==", + "license": "MIT", + "dependencies": { + "@types/node": "^14.0.1", + "lodash.escaperegexp": "^4.1.2", + "lodash.isboolean": "^3.0.3", + "lodash.isequal": "^4.5.0", + "lodash.isfunction": "^3.0.9", + "lodash.isnil": "^4.0.0" + } + }, + "node_modules/@fast-csv/format/node_modules/@types/node": { + "version": "14.18.63", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", + "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", + "license": "MIT" + }, + "node_modules/@fast-csv/parse": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/@fast-csv/parse/-/parse-4.3.6.tgz", + "integrity": "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA==", + "license": "MIT", + "dependencies": { + "@types/node": "^14.0.1", + "lodash.escaperegexp": "^4.1.2", + "lodash.groupby": "^4.6.0", + "lodash.isfunction": "^3.0.9", + "lodash.isnil": "^4.0.0", + "lodash.isundefined": "^3.0.1", + "lodash.uniq": "^4.5.0" + } + }, + "node_modules/@fast-csv/parse/node_modules/@types/node": { + "version": "14.18.63", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", + "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", + "license": "MIT" + }, "node_modules/@fastify/busboy": { "version": "2.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/@fastify/busboy/-/busboy-2.1.1.tgz", @@ -2059,6 +2102,15 @@ "node": ">= 16.0.0" } }, + "node_modules/adler-32": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/adler-32/-/adler-32-1.3.1.tgz", + "integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/agentkeepalive": { "version": "4.6.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/agentkeepalive/-/agentkeepalive-4.6.0.tgz", @@ -2205,6 +2257,130 @@ "node": ">= 8" } }, + "node_modules/archiver": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/archiver/-/archiver-5.3.2.tgz", + "integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==", + "license": "MIT", + "dependencies": { + "archiver-utils": "^2.1.0", + "async": "^3.2.4", + "buffer-crc32": "^0.2.1", + "readable-stream": "^3.6.0", + "readdir-glob": "^1.1.2", + "tar-stream": "^2.2.0", + "zip-stream": "^4.1.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/archiver-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-2.1.0.tgz", + "integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==", + "license": "MIT", + "dependencies": { + "glob": "^7.1.4", + "graceful-fs": "^4.2.0", + "lazystream": "^1.0.0", + "lodash.defaults": "^4.2.0", + "lodash.difference": "^4.5.0", + "lodash.flatten": "^4.4.0", + "lodash.isplainobject": "^4.0.6", + "lodash.union": "^4.6.0", + "normalize-path": "^3.0.0", + "readable-stream": "^2.0.0" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/archiver-utils/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/archiver-utils/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/archiver-utils/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/archiver-utils/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/archiver-utils/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/archiver-utils/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/archiver-utils/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/archiver/node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", + "license": "MIT" + }, "node_modules/are-docs-informative": { "version": "0.0.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/are-docs-informative/-/are-docs-informative-0.0.2.tgz", @@ -2663,6 +2839,28 @@ "tweetnacl": "^0.14.3" } }, + "node_modules/big-integer": { + "version": "1.6.52", + "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz", + "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==", + "license": "Unlicense", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/binary": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/binary/-/binary-0.3.0.tgz", + "integrity": "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg==", + "license": "MIT", + "dependencies": { + "buffers": "~0.1.1", + "chainsaw": "~0.1.0" + }, + "engines": { + "node": "*" + } + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -2680,7 +2878,6 @@ "version": "4.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/bl/-/bl-4.1.0.tgz", "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "dev": true, "license": "MIT", "dependencies": { "buffer": "^5.5.0", @@ -2787,6 +2984,15 @@ "ieee754": "^1.1.13" } }, + "node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, "node_modules/buffer-equal-constant-time": { "version": "1.0.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", @@ -2799,6 +3005,23 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", "license": "MIT" }, + "node_modules/buffer-indexof-polyfill": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz", + "integrity": "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A==", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/buffers": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/buffers/-/buffers-0.1.1.tgz", + "integrity": "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==", + "engines": { + "node": ">=0.2.0" + } + }, "node_modules/builtin-modules": { "version": "3.3.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/builtin-modules/-/builtin-modules-3.3.0.tgz", @@ -3009,6 +3232,19 @@ "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==", "license": "Apache-2.0" }, + "node_modules/cfb": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cfb/-/cfb-1.2.2.tgz", + "integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "crc-32": "~1.2.0" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/cfork": { "version": "1.11.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/cfork/-/cfork-1.11.0.tgz", @@ -3037,6 +3273,18 @@ "node": ">= 0.12.0" } }, + "node_modules/chainsaw": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz", + "integrity": "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==", + "license": "MIT/X11", + "dependencies": { + "traverse": ">=0.3.0 <0.4" + }, + "engines": { + "node": "*" + } + }, "node_modules/chalk": { "version": "2.4.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/chalk/-/chalk-2.4.2.tgz", @@ -3343,6 +3591,15 @@ "node": ">= 14.0.0" } }, + "node_modules/codepage": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/codepage/-/codepage-1.15.0.tgz", + "integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/coffee": { "version": "5.5.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/coffee/-/coffee-5.5.1.tgz", @@ -3693,6 +3950,21 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/compress-commons": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-4.1.2.tgz", + "integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==", + "license": "MIT", + "dependencies": { + "buffer-crc32": "^0.2.13", + "crc32-stream": "^4.0.2", + "normalize-path": "^3.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, "node_modules/compressible": { "version": "2.0.18", "resolved": "https://mirrors.huaweicloud.com/repository/npm/compressible/-/compressible-2.0.18.tgz", @@ -4018,6 +4290,31 @@ "buffer": "^5.1.0" } }, + "node_modules/crc-32": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz", + "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==", + "license": "Apache-2.0", + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/crc32-stream": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-4.0.3.tgz", + "integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==", + "license": "MIT", + "dependencies": { + "crc-32": "^1.2.0", + "readable-stream": "^3.4.0" + }, + "engines": { + "node": ">= 10" + } + }, "node_modules/create-require": { "version": "1.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/create-require/-/create-require-1.1.1.tgz", @@ -4500,6 +4797,51 @@ "integrity": "sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==", "license": "MIT" }, + "node_modules/duplexer2": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/duplexer2/-/duplexer2-0.1.4.tgz", + "integrity": "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==", + "license": "BSD-3-Clause", + "dependencies": { + "readable-stream": "^2.0.2" + } + }, + "node_modules/duplexer2/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/duplexer2/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/duplexer2/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/duplexer2/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/duplexify": { "version": "3.7.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/duplexify/-/duplexify-3.7.1.tgz", @@ -6736,6 +7078,26 @@ "through": "~2.3.1" } }, + "node_modules/exceljs": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/exceljs/-/exceljs-4.4.0.tgz", + "integrity": "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==", + "license": "MIT", + "dependencies": { + "archiver": "^5.0.0", + "dayjs": "^1.8.34", + "fast-csv": "^4.3.1", + "jszip": "^3.10.1", + "readable-stream": "^3.6.0", + "saxes": "^5.0.1", + "tmp": "^0.2.0", + "unzipper": "^0.10.11", + "uuid": "^8.3.0" + }, + "engines": { + "node": ">=8.3.0" + } + }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/execa/-/execa-5.1.1.tgz", @@ -6864,6 +7226,19 @@ ], "license": "MIT" }, + "node_modules/fast-csv": { + "version": "4.3.6", + "resolved": "https://registry.npmjs.org/fast-csv/-/fast-csv-4.3.6.tgz", + "integrity": "sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw==", + "license": "MIT", + "dependencies": { + "@fast-csv/format": "4.3.5", + "@fast-csv/parse": "4.3.6" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://mirrors.huaweicloud.com/repository/npm/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -7221,6 +7596,15 @@ "pause-stream": "~0.0.11" } }, + "node_modules/frac": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/frac/-/frac-1.1.2.tgz", + "integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/fresh": { "version": "0.5.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/fresh/-/fresh-0.5.2.tgz", @@ -7236,6 +7620,12 @@ "integrity": "sha512-twe20eF1OxVxp/ML/kq2p1uc6KvFK/+vs8WjEbeKmV2He22MKm7YF2ANIt+EOqhJ5L3K/SuuPhk0hWQDjOM23g==", "license": "MIT" }, + "node_modules/fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", + "license": "MIT" + }, "node_modules/fs-extra": { "version": "10.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/fs-extra/-/fs-extra-10.1.0.tgz", @@ -7278,6 +7668,78 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/fstream": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz", + "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==", + "deprecated": "This package is no longer supported.", + "license": "ISC", + "dependencies": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + }, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/fstream/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/fstream/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fstream/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/fstream/node_modules/rimraf": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.7.1.tgz", + "integrity": "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, "node_modules/fsu": { "version": "1.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/fsu/-/fsu-1.1.1.tgz", @@ -7599,7 +8061,6 @@ "version": "4.2.11", "resolved": "https://mirrors.huaweicloud.com/repository/npm/graceful-fs/-/graceful-fs-4.2.11.tgz", "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, "license": "ISC" }, "node_modules/graceful-process": { @@ -7900,6 +8361,12 @@ "node": ">= 4" } }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "license": "MIT" + }, "node_modules/import-fresh": { "version": "3.3.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/import-fresh/-/import-fresh-3.3.1.tgz", @@ -9184,6 +9651,54 @@ "node": ">=4.0" } }, + "node_modules/jszip": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", + "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "license": "(MIT OR GPL-3.0-or-later)", + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "setimmediate": "^1.0.5" + } + }, + "node_modules/jszip/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/jszip/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/jszip/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/jszip/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/jwa": { "version": "1.4.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/jwa/-/jwa-1.4.2.tgz", @@ -9526,6 +10041,54 @@ "node": ">=0.10" } }, + "node_modules/lazystream": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz", + "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==", + "license": "MIT", + "dependencies": { + "readable-stream": "^2.0.5" + }, + "engines": { + "node": ">= 0.6.3" + } + }, + "node_modules/lazystream/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/lazystream/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/lazystream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/lazystream/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/levn": { "version": "0.4.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/levn/-/levn-0.4.1.tgz", @@ -9540,6 +10103,21 @@ "node": ">= 0.8.0" } }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, + "node_modules/listenercount": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz", + "integrity": "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ==", + "license": "ISC" + }, "node_modules/locate-path": { "version": "6.0.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/locate-path/-/locate-path-6.0.0.tgz", @@ -9568,12 +10146,30 @@ "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", "license": "MIT" }, + "node_modules/lodash.difference": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz", + "integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==", + "license": "MIT" + }, + "node_modules/lodash.escaperegexp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz", + "integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==", + "license": "MIT" + }, "node_modules/lodash.flatten": { "version": "4.4.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.flatten/-/lodash.flatten-4.4.0.tgz", "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==", "license": "MIT" }, + "node_modules/lodash.groupby": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz", + "integrity": "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==", + "license": "MIT" + }, "node_modules/lodash.includes": { "version": "4.3.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.includes/-/lodash.includes-4.3.0.tgz", @@ -9599,6 +10195,13 @@ "dev": true, "license": "MIT" }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", + "license": "MIT" + }, "node_modules/lodash.isfunction": { "version": "3.0.9", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.isfunction/-/lodash.isfunction-3.0.9.tgz", @@ -9611,6 +10214,12 @@ "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", "license": "MIT" }, + "node_modules/lodash.isnil": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/lodash.isnil/-/lodash.isnil-4.0.0.tgz", + "integrity": "sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng==", + "license": "MIT" + }, "node_modules/lodash.isnumber": { "version": "3.0.3", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", @@ -9636,6 +10245,12 @@ "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", "license": "MIT" }, + "node_modules/lodash.isundefined": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/lodash.isundefined/-/lodash.isundefined-3.0.1.tgz", + "integrity": "sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA==", + "license": "MIT" + }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -9655,6 +10270,18 @@ "integrity": "sha512-4hNPN5jlm/N/HLMCO43v8BXKq9Z7QdAGc/VGrRD61w8gN9g/6jF9A4L1pbUgBLCffi0w9VsXfTOij5x8iTyFvg==", "license": "MIT" }, + "node_modules/lodash.union": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz", + "integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==", + "license": "MIT" + }, + "node_modules/lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==", + "license": "MIT" + }, "node_modules/log-symbols": { "version": "4.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/log-symbols/-/log-symbols-4.1.0.tgz", @@ -10827,7 +11454,6 @@ "version": "3.0.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/normalize-path/-/normalize-path-3.0.0.tgz", "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -11278,6 +11904,12 @@ "dev": true, "license": "BlueOak-1.0.0" }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, "node_modules/param-case": { "version": "2.1.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/param-case/-/param-case-2.1.1.tgz", @@ -11811,7 +12443,6 @@ "version": "3.6.2", "resolved": "https://mirrors.huaweicloud.com/repository/npm/readable-stream/-/readable-stream-3.6.2.tgz", "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dev": true, "license": "MIT", "dependencies": { "inherits": "^2.0.3", @@ -11822,6 +12453,15 @@ "node": ">= 6" } }, + "node_modules/readdir-glob": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz", + "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==", + "license": "Apache-2.0", + "dependencies": { + "minimatch": "^5.1.0" + } + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/readdirp/-/readdirp-3.6.0.tgz", @@ -12352,6 +12992,18 @@ "node": ">=11.0.0" } }, + "node_modules/saxes": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz", + "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==", + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/scmp": { "version": "2.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/scmp/-/scmp-2.1.0.tgz", @@ -12742,6 +13394,12 @@ "node": ">= 0.4" } }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "license": "MIT" + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -13013,6 +13671,18 @@ "node": ">= 0.6" } }, + "node_modules/ssf": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/ssf/-/ssf-0.11.2.tgz", + "integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==", + "license": "Apache-2.0", + "dependencies": { + "frac": "~1.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/sshpk": { "version": "1.18.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/sshpk/-/sshpk-1.18.0.tgz", @@ -13118,7 +13788,6 @@ "version": "1.3.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/string_decoder/-/string_decoder-1.3.0.tgz", "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "dev": true, "license": "MIT", "dependencies": { "safe-buffer": "~5.2.0" @@ -13507,6 +14176,22 @@ "node": ">=8.0.0" } }, + "node_modules/tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/tcomb": { "version": "3.2.29", "resolved": "https://mirrors.huaweicloud.com/repository/npm/tcomb/-/tcomb-3.2.29.tgz", @@ -13718,6 +14403,15 @@ "upper-case": "^1.0.3" } }, + "node_modules/tmp": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", + "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", + "license": "MIT", + "engines": { + "node": ">=14.14" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://mirrors.huaweicloud.com/repository/npm/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -13758,6 +14452,15 @@ "node": ">=0.8" } }, + "node_modules/traverse": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.9.tgz", + "integrity": "sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ==", + "license": "MIT/X11", + "engines": { + "node": "*" + } + }, "node_modules/ts-api-utils": { "version": "1.4.3", "resolved": "https://mirrors.huaweicloud.com/repository/npm/ts-api-utils/-/ts-api-utils-1.4.3.tgz", @@ -14107,6 +14810,66 @@ "node": ">= 0.8" } }, + "node_modules/unzipper": { + "version": "0.10.14", + "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.10.14.tgz", + "integrity": "sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g==", + "license": "MIT", + "dependencies": { + "big-integer": "^1.6.17", + "binary": "~0.3.0", + "bluebird": "~3.4.1", + "buffer-indexof-polyfill": "~1.0.0", + "duplexer2": "~0.1.4", + "fstream": "^1.0.12", + "graceful-fs": "^4.2.2", + "listenercount": "~1.0.1", + "readable-stream": "~2.3.6", + "setimmediate": "~1.0.4" + } + }, + "node_modules/unzipper/node_modules/bluebird": { + "version": "3.4.7", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz", + "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==", + "license": "MIT" + }, + "node_modules/unzipper/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/unzipper/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/unzipper/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/unzipper/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, "node_modules/update-browserslist-db": { "version": "1.1.4", "resolved": "https://mirrors.huaweicloud.com/repository/npm/update-browserslist-db/-/update-browserslist-db-1.1.4.tgz", @@ -14585,6 +15348,24 @@ "@types/node": "*" } }, + "node_modules/wmf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wmf/-/wmf-1.0.2.tgz", + "integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/word": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/word/-/word-0.3.0.tgz", + "integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==", + "license": "Apache-2.0", + "engines": { + "node": ">=0.8" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://mirrors.huaweicloud.com/repository/npm/word-wrap/-/word-wrap-1.2.5.tgz", @@ -14772,6 +15553,27 @@ "get-ready": "~1.0.0" } }, + "node_modules/xlsx": { + "version": "0.18.5", + "resolved": "https://registry.npmjs.org/xlsx/-/xlsx-0.18.5.tgz", + "integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==", + "license": "Apache-2.0", + "dependencies": { + "adler-32": "~1.3.0", + "cfb": "~1.2.1", + "codepage": "~1.15.0", + "crc-32": "~1.2.1", + "ssf": "~0.11.2", + "wmf": "~1.0.1", + "word": "~0.3.0" + }, + "bin": { + "xlsx": "bin/xlsx.njs" + }, + "engines": { + "node": ">=0.8" + } + }, "node_modules/xml-crypto": { "version": "6.1.2", "resolved": "https://mirrors.cloud.tencent.com/npm/xml-crypto/-/xml-crypto-6.1.2.tgz", @@ -14786,6 +15588,12 @@ "node": ">=16" } }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "license": "MIT" + }, "node_modules/xpath": { "version": "0.0.33", "resolved": "https://mirrors.cloud.tencent.com/npm/xpath/-/xpath-0.0.33.tgz", @@ -14927,6 +15735,84 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/zip-stream": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz", + "integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==", + "license": "MIT", + "dependencies": { + "archiver-utils": "^3.0.4", + "compress-commons": "^4.1.2", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/zip-stream/node_modules/archiver-utils": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-3.0.4.tgz", + "integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==", + "license": "MIT", + "dependencies": { + "glob": "^7.2.3", + "graceful-fs": "^4.2.0", + "lazystream": "^1.0.0", + "lodash.defaults": "^4.2.0", + "lodash.difference": "^4.5.0", + "lodash.flatten": "^4.4.0", + "lodash.isplainobject": "^4.0.6", + "lodash.union": "^4.6.0", + "normalize-path": "^3.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/zip-stream/node_modules/brace-expansion": { + "version": "1.1.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz", + "integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/zip-stream/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/zip-stream/node_modules/minimatch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", + "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, "node_modules/zlogger": { "version": "1.1.0", "resolved": "https://mirrors.huaweicloud.com/repository/npm/zlogger/-/zlogger-1.1.0.tgz", diff --git a/package.json b/package.json index 2129eed..be8a5c9 100644 --- a/package.json +++ b/package.json @@ -20,12 +20,14 @@ "egg-sequelize": "^6.0.0", "egg-view-ejs": "^3.0.0", "ejs": "^5.0.1", + "exceljs": "^4.4.0", "fast-xml-parser": "^5.3.1", "mysql2": "^3.15.3", "path": "^0.12.7", "qiniu-js": "^3.4.3", "soap": "^1.8.0", - "spark-md5": "^3.0.2" + "spark-md5": "^3.0.2", + "xlsx": "^0.18.5" }, "devDependencies": { "egg-bin": "6", @@ -64,6 +66,7 @@ "test:local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", + "permission:sync:system-api": "node ./script/sync-system-api-permission.cjs", "check:model-boundary": "node ./script/model-boundary-check.cjs", "ci": "npm run lint && npm run check:model-boundary && npm run cov" }, diff --git a/script/backfill-role-permissions.cjs b/script/backfill-role-permissions.cjs new file mode 100644 index 0000000..1a37157 --- /dev/null +++ b/script/backfill-role-permissions.cjs @@ -0,0 +1,224 @@ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); + +function parseArgs(argv) { + const args = { + dryRun: false, + dbClient: 'wms', + configPath: DEFAULT_CONFIG_PATH, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + + if (item.startsWith('--db-client=')) { + args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; + continue; + } + + if (item.startsWith('--config-path=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.configPath = path.resolve(ROOT, raw); + continue; + } + } + + return args; +} + +function loadConfig(configPath) { + if (!fs.existsSync(configPath)) { + throw new Error(`Config file not found: ${configPath}`); + } + + const configFactory = require(configPath); + return typeof configFactory === 'function' + ? configFactory({ name: 'wms-role-permissions-backfill' }) + : configFactory; +} + +function normalizeRolePermissions(rawValue) { + if (rawValue === undefined || rawValue === null) { + return { allAccess: false, permissionIds: [] }; + } + + if (Array.isArray(rawValue)) { + const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item)); + if (normalizedItems.some(item => item === '*')) { + return { allAccess: true, permissionIds: [] }; + } + + const permissionIds = normalizedItems + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0) + .map(item => Math.floor(item)); + + return { + allAccess: false, + permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b), + }; + } + + if (typeof rawValue === 'number') { + return normalizeRolePermissions([ rawValue ]); + } + + if (typeof rawValue === 'string') { + const trimmed = rawValue.trim(); + if (!trimmed) { + return { allAccess: false, permissionIds: [] }; + } + if (trimmed === '*') { + return { allAccess: true, permissionIds: [] }; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawValue) { + return normalizeRolePermissions(parsed); + } + } catch (_) { + // ignore parse failure and continue. + } + + if (trimmed.includes(',')) { + return normalizeRolePermissions(trimmed.split(',')); + } + + return normalizeRolePermissions([ trimmed ]); + } + + return { allAccess: false, permissionIds: [] }; +} + +function serializeRolePermissions(rawValue) { + const state = normalizeRolePermissions(rawValue); + return state.allAccess ? '*' : JSON.stringify(state.permissionIds); +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const cfg = loadConfig(args.configPath); + const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient]; + + if (!dbClient) { + throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`); + } + + const conn = await mysql.createConnection({ + host: dbClient.host, + port: Number(dbClient.port), + user: dbClient.user, + password: dbClient.password, + database: dbClient.database, + charset: dbClient.charset || 'utf8mb4', + }); + + try { + const [ roleRows ] = await conn.query( + 'SELECT id, role_code, permissions FROM wms_role ORDER BY id ASC' + ); + const [ legacyRows ] = await conn.query( + 'SELECT role_id, permission_id FROM wms_role_permission ORDER BY role_id ASC, permission_id ASC' + ); + + const legacyMap = new Map(); + for (const row of legacyRows) { + const roleId = Number(row.role_id); + const permissionId = Number(row.permission_id); + if (!Number.isFinite(roleId) || roleId <= 0 || !Number.isFinite(permissionId) || permissionId <= 0) { + continue; + } + if (!legacyMap.has(roleId)) { + legacyMap.set(roleId, []); + } + legacyMap.get(roleId).push(permissionId); + } + + const updates = []; + for (const row of roleRows) { + const roleId = Number(row.id); + const legacyPermissionIds = Array.from(new Set((legacyMap.get(roleId) || []) + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0))) + .sort((a, b) => a - b); + + if (legacyPermissionIds.length === 0) { + continue; + } + + const currentState = normalizeRolePermissions(row.permissions); + const nextValue = currentState.allAccess + ? '*' + : serializeRolePermissions([ ...currentState.permissionIds, ...legacyPermissionIds ]); + const currentValue = currentState.allAccess + ? '*' + : serializeRolePermissions(currentState.permissionIds); + + if (nextValue !== currentValue) { + updates.push({ + roleId, + roleCode: row.role_code || '', + before: row.permissions, + after: nextValue, + legacyCount: legacyPermissionIds.length, + }); + } + } + + if (args.dryRun) { + console.log('[backfill-role-permissions] dry-run summary'); + console.log(JSON.stringify({ + mode: 'dry-run', + totalRoles: roleRows.length, + legacyRelationCount: legacyRows.length, + affectedRoleCount: updates.length, + sample: updates.slice(0, 20), + }, null, 2)); + return; + } + + if (updates.length === 0) { + console.log('[backfill-role-permissions] nothing to update'); + return; + } + + await conn.beginTransaction(); + try { + for (const item of updates) { + await conn.query( + 'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?', + [ item.after, item.roleId ] + ); + } + await conn.commit(); + } catch (error) { + await conn.rollback(); + throw error; + } + + console.log('[backfill-role-permissions] apply summary'); + console.log(JSON.stringify({ + mode: 'apply', + totalRoles: roleRows.length, + legacyRelationCount: legacyRows.length, + updatedRoleCount: updates.length, + sample: updates.slice(0, 20), + }, null, 2)); + } finally { + await conn.end(); + } +} + +main().catch(error => { + console.error('[backfill-role-permissions] failed'); + console.error(error && error.stack ? error.stack : String(error)); + process.exit(1); +}); diff --git a/script/deploy-lib.cjs b/script/deploy-lib.cjs index b724435..72af166 100644 --- a/script/deploy-lib.cjs +++ b/script/deploy-lib.cjs @@ -232,17 +232,20 @@ function pathMatchesRule(filePath, rule) { } function listDeployableFiles(config) { - const output = runCommand('git', [ 'ls-files', '--cached' ]); + const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]); const includeRules = Array.isArray(config && config.deployIncludePaths) ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS; const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ]; - return output - .split(/\r?\n/) - .map(item => item.trim()) - .filter(Boolean) - .filter(item => !item.startsWith('.git/')) - .filter(item => includeRules.some(rule => pathMatchesRule(item, rule))) - .filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule))); + return Array.from(new Set( + output + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean) + .filter(item => !item.startsWith('.git/')) + .filter(item => fs.existsSync(path.join(ROOT, item))) + .filter(item => includeRules.some(rule => pathMatchesRule(item, rule))) + .filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule))) + )); } function buildArchive(stamp, config) { diff --git a/script/sync-system-api-permission.cjs b/script/sync-system-api-permission.cjs new file mode 100644 index 0000000..c4b3553 --- /dev/null +++ b/script/sync-system-api-permission.cjs @@ -0,0 +1,362 @@ +const fs = require('fs'); +const path = require('path'); +const mysql = require('mysql2/promise'); + +const ROOT = process.cwd(); +const DEFAULT_CONFIG_PATH = path.join(ROOT, 'config', 'config.local.js'); +const DEFAULT_METHOD_DOC_PATH = path.join(ROOT, 'methods', 'system.json'); + +function parseArgs(argv) { + const args = { + dryRun: false, + roleId: 2, + dbClient: 'wms', + configPath: DEFAULT_CONFIG_PATH, + methodDocPath: DEFAULT_METHOD_DOC_PATH, + }; + + for (const item of argv) { + if (item === '--dry-run') { + args.dryRun = true; + continue; + } + + if (item.startsWith('--role-id=')) { + args.roleId = Number(item.split('=')[1]); + continue; + } + + if (item.startsWith('--db-client=')) { + args.dbClient = String(item.split('=')[1] || '').trim() || 'wms'; + continue; + } + + if (item.startsWith('--config-path=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.configPath = path.resolve(ROOT, raw); + continue; + } + + if (item.startsWith('--method-doc=')) { + const raw = String(item.split('=')[1] || '').trim(); + args.methodDocPath = path.resolve(ROOT, raw); + continue; + } + } + + if (!Number.isInteger(args.roleId) || args.roleId <= 0) { + throw new Error('Invalid --role-id, must be a positive integer.'); + } + + return args; +} + +function loadConfig(configPath) { + if (!fs.existsSync(configPath)) { + throw new Error(`Config file not found: ${configPath}`); + } + + const configFactory = require(configPath); + const config = typeof configFactory === 'function' + ? configFactory({ name: 'wms-permission-sync' }) + : configFactory; + + return config; +} + +function loadAuthRequiredMethods(methodDocPath) { + if (!fs.existsSync(methodDocPath)) { + throw new Error(`Method doc not found: ${methodDocPath}`); + } + + const json = JSON.parse(fs.readFileSync(methodDocPath, 'utf8')); + const groups = json && json.methods && Array.isArray(json.methods.groups) + ? json.methods.groups + : []; + + const methodSet = new Set(); + for (const group of groups) { + const list = group && Array.isArray(group.list) ? group.list : []; + for (const item of list) { + if (!item || !item.method || item.isNeedAuth !== true) continue; + methodSet.add(String(item.method).trim()); + } + } + + return [ ...methodSet ].sort(); +} + +function normalizeRolePermissions(rawValue) { + if (rawValue === undefined || rawValue === null) { + return { allAccess: false, permissionIds: [] }; + } + + if (Array.isArray(rawValue)) { + const normalizedItems = rawValue.map(item => (typeof item === 'string' ? item.trim() : item)); + if (normalizedItems.some(item => item === '*')) { + return { allAccess: true, permissionIds: [] }; + } + + const permissionIds = normalizedItems + .map(item => Number(item)) + .filter(item => Number.isFinite(item) && item > 0) + .map(item => Math.floor(item)); + + return { + allAccess: false, + permissionIds: Array.from(new Set(permissionIds)).sort((a, b) => a - b), + }; + } + + if (typeof rawValue === 'number') { + return normalizeRolePermissions([ rawValue ]); + } + + if (typeof rawValue === 'string') { + const trimmed = rawValue.trim(); + if (!trimmed) { + return { allAccess: false, permissionIds: [] }; + } + if (trimmed === '*') { + return { allAccess: true, permissionIds: [] }; + } + + try { + const parsed = JSON.parse(trimmed); + if (parsed !== rawValue) { + return normalizeRolePermissions(parsed); + } + } catch (_) { + // ignore parse errors and continue. + } + + if (trimmed.includes(',')) { + return normalizeRolePermissions(trimmed.split(',')); + } + + return normalizeRolePermissions([ trimmed ]); + } + + return { allAccess: false, permissionIds: [] }; +} + +function serializeRolePermissions(rawValue) { + const state = normalizeRolePermissions(rawValue); + return state.allAccess ? '*' : JSON.stringify(state.permissionIds); +} + +function buildPermissionDefaults(methodPath, templateRow) { + return { + path: methodPath, + type: 'api', + component: templateRow ? templateRow.component : null, + name: templateRow && templateRow.name ? templateRow.name : methodPath, + redirect: templateRow ? templateRow.redirect : null, + meta_title: templateRow && templateRow.meta_title ? templateRow.meta_title : `API:${methodPath}`, + meta_icon: templateRow ? templateRow.meta_icon : null, + hidden: templateRow ? Number(templateRow.hidden || 0) : 0, + always_show: templateRow ? Number(templateRow.always_show || 0) : 0, + parent_id: templateRow && templateRow.parent_id ? Number(templateRow.parent_id) : null, + sort: templateRow ? Number(templateRow.sort || 0) : 0, + status: templateRow ? Number(templateRow.status || 1) : 1, + }; +} + +async function queryPermissionTemplate(conn) { + const [ rows ] = await conn.query(` + SELECT component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status + FROM wms_permission + WHERE type = 'api' + ORDER BY id ASC + LIMIT 1 + `); + return rows[0] || null; +} + +async function queryExistingPermissions(conn, methodPaths) { + if (methodPaths.length === 0) return new Map(); + + const placeholders = methodPaths.map(() => '?').join(','); + const [ rows ] = await conn.query( + `SELECT id, path, status FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`, + methodPaths + ); + + const result = new Map(); + for (const row of rows) { + result.set(row.path, { + id: Number(row.id), + status: Number(row.status), + }); + } + return result; +} + +async function insertPermission(conn, defaults) { + const [ result ] = await conn.query( + `INSERT INTO wms_permission + (path, type, component, name, redirect, meta_title, meta_icon, hidden, always_show, parent_id, sort, status, created_at, update_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`, + [ + defaults.path, + defaults.type, + defaults.component, + defaults.name, + defaults.redirect, + defaults.meta_title, + defaults.meta_icon, + defaults.hidden, + defaults.always_show, + defaults.parent_id, + defaults.sort, + defaults.status, + ] + ); + + return result.insertId; +} + +async function activatePermission(conn, permissionId) { + const [ result ] = await conn.query( + 'UPDATE wms_permission SET status = 1, update_at = NOW() WHERE id = ? AND status <> 1', + [ permissionId ] + ); + return result.affectedRows > 0; +} + +async function bindRolePermission(conn, roleId, permissionId) { + const [ roleRows ] = await conn.query( + 'SELECT permissions FROM wms_role WHERE id = ? LIMIT 1', + [ roleId ] + ); + const roleRow = roleRows[0]; + if (!roleRow) { + throw new Error(`Role not found: ${roleId}`); + } + + const currentState = normalizeRolePermissions(roleRow.permissions); + + if (currentState.allAccess || currentState.permissionIds.includes(Number(permissionId))) { + return false; + } + + const nextPermissions = [ ...currentState.permissionIds, Number(permissionId) ]; + const [ result ] = await conn.query( + 'UPDATE wms_role SET permissions = ?, updated_at = NOW() WHERE id = ?', + [ serializeRolePermissions(nextPermissions), roleId ] + ); + return result.affectedRows > 0; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const cfg = loadConfig(args.configPath); + const dbClient = cfg && cfg.mysql && cfg.mysql.clients && cfg.mysql.clients[args.dbClient]; + + if (!dbClient) { + throw new Error(`MySQL client not found in config.mysql.clients: ${args.dbClient}`); + } + + const methodPaths = loadAuthRequiredMethods(args.methodDocPath); + if (methodPaths.length === 0) { + console.log('[sync-system-api-permission] no isNeedAuth=true methods found.'); + return; + } + + const conn = await mysql.createConnection({ + host: dbClient.host, + port: Number(dbClient.port), + user: dbClient.user, + password: dbClient.password, + database: dbClient.database, + charset: dbClient.charset || 'utf8mb4', + }); + + try { + const templateRow = await queryPermissionTemplate(conn); + const existingMap = await queryExistingPermissions(conn, methodPaths); + + const missingPaths = methodPaths.filter(item => !existingMap.has(item)); + const disabledPaths = methodPaths.filter(item => { + const row = existingMap.get(item); + return row && Number(row.status) !== 1; + }); + const created = []; + const reactivated = []; + const touchedPermissionIds = []; + + if (!args.dryRun && (missingPaths.length > 0 || disabledPaths.length > 0)) { + await conn.beginTransaction(); + try { + for (const methodPath of missingPaths) { + const defaults = buildPermissionDefaults(methodPath, templateRow); + const permissionId = await insertPermission(conn, defaults); + created.push({ methodPath, permissionId }); + touchedPermissionIds.push(permissionId); + } + + for (const methodPath of disabledPaths) { + const permissionRow = existingMap.get(methodPath); + if (!permissionRow || !permissionRow.id) { + continue; + } + + const updated = await activatePermission(conn, permissionRow.id); + if (updated) { + reactivated.push({ methodPath, permissionId: permissionRow.id }); + } + touchedPermissionIds.push(permissionRow.id); + } + + await conn.commit(); + } catch (error) { + await conn.rollback(); + throw error; + } + } + + const latestMap = args.dryRun + ? existingMap + : await queryExistingPermissions(conn, methodPaths); + + for (const methodPath of methodPaths) { + const permissionRow = latestMap.get(methodPath); + if (permissionRow && permissionRow.id) touchedPermissionIds.push(permissionRow.id); + } + + const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ]; + let roleBindingCreated = 0; + + if (!args.dryRun) { + for (const permissionId of uniquePermissionIds) { + const createdBinding = await bindRolePermission(conn, args.roleId, permissionId); + if (createdBinding) roleBindingCreated++; + } + } + + const summary = { + mode: args.dryRun ? 'dry-run' : 'apply', + roleId: args.roleId, + totalAuthMethods: methodPaths.length, + existingPermissionCount: existingMap.size, + missingPermissionCount: missingPaths.length, + disabledPermissionCount: disabledPaths.length, + createdPermissionCount: created.length, + reactivatedPermissionCount: reactivated.length, + roleBindingCreated, + sampleMissing: missingPaths.slice(0, 20), + sampleDisabled: disabledPaths.slice(0, 20), + }; + + console.log('[sync-system-api-permission] summary'); + console.log(JSON.stringify(summary, null, 2)); + } finally { + await conn.end(); + } +} + +main().catch(error => { + console.error('[sync-system-api-permission] failed'); + console.error(error && error.stack ? error.stack : String(error)); + process.exit(1); +}); diff --git a/stock.todo b/stock.todo deleted file mode 100644 index 658f66d..0000000 --- a/stock.todo +++ /dev/null @@ -1,112 +0,0 @@ -# stock.todo - -## 任务目标 -- 提取 `app/service/systemMethods/stock/warehouse.js` 迁移前 method 的历史测试请求记录。 -- 精简并保留新接口(`stock.warehouse.*`)的测试入口。 -- 根据输入/输出补全 `warehouse.js` 方法头注释和 API 文档 `description`。 - -## 迁移方法映射(旧 -> 新) -- `stock.stockWarehouse` -> `stock.warehouse.list` -- `stock.getProhibitedType` -> `stock.warehouse.getProhibitedType` -- `stock.getInfo` -> `stock.warehouse.getInfo` -- `stock.saveWarehouseStock` -> `stock.warehouse.saveWarehouseStock` -- `stock.createWarehouseStock` -> `stock.warehouse.createWarehouseStock` -- `stock.getBarcodes` -> `stock.warehouse.getBarcodes` -- `stock.saveWarehouseStockBarcode` -> `stock.warehouse.saveWarehouseStockBarcode` -- `stock.getStoreStocks` -> `stock.warehouse.getStoreStocks` -- `stock.bindItem` -> `stock.warehouse.bindItem` -- `stock.unbindItem` -> `stock.warehouse.unbindItem` -- `stock.checkItemCodeUnique` -> `stock.warehouse.checkItemCodeUnique` -- `stock.queryStockLogs` -> `stock.warehouse.queryStockLogs` -- `stock.handleBatchDelete` -> `stock.warehouse.handleBatchDelete` -- `stock.deleteUnit` -> `stock.warehouse.deleteUnit` -- `stock.deleteProhibited` -> `stock.warehouse.deleteProhibited` -- `stock.handleBatchChange` -> `stock.warehouse.handleBatchChange` -- `stock.getStockUnits` -> `stock.warehouse.getStockUnits` -- `stock.getUnitList` -> `stock.warehouse.getUnitList` -- `stock.createProhibited` -> `stock.warehouse.createProhibited` -- `stock.createUnit` -> `stock.warehouse.createUnit` -- `stock.search` -> `stock.warehouse.search` - -## 历史测试请求记录提取(迁移前/过渡期) -来源:`node_modules/.mochawesome-reports/mochawesome.json`(2026-03-25) - -### 记录1:新列表接口请求 -- case: `system.stock.warehouse.namespaced.test.js` -- method: `stock.warehouse.list` -- request: -```json -{ - "pagination": { "page": 1, "pageSize": 5 }, - "where": {} -} -``` -- expected: -```json -{ - "httpStatus": 200, - "flag": "success", - "code": 200, - "data": { - "list": "Array", - "pagination": "Object" - } -} -``` - -### 记录2:旧入口退场验证请求(历史) -- case: `system.stock.warehouse.namespaced.test.js`(精简前) -- method: `stock.stockWarehouse` -- request: -```json -{ - "pagination": { "page": 1, "pageSize": 5 }, - "where": {} -} -``` -- expected: -```json -{ - "httpStatus": 500, - "flag": "failure", - "code": 500, - "message": "方法 stockWarehouse 不存在" -} -``` - -### 记录3:where 条件解析服务级样本 -来源:`test/app/service/systems/stock_store.stockWarehouse.conditions.test.js` -- input: -```json -{ - "where": { - "item_code": { "operator": "like", "value": "SKU" }, - "barcode": { "operator": "like", "value": "BC" }, - "prohibited_type": { "operator": "eq", "value": 2 }, - "quantity": { "operator": "ge", "type": "number", "value": "2" } - }, - "pagination": { "page": 1, "pageSize": 10 }, - "sort": { "sortField": "quantity", "sortOrder": "ASC" } -} -``` -- expected: -```json -{ - "code": 200, - "message": "查询成功", - "data.pagination.page": 1, - "data.pagination.pageSize": 10, - "data.queryInfo.hasBarcodeSearch": true -} -``` - -## 新接口精简测试方案 -- 保留:`test/app/controller/system.stock.warehouse.namespaced.test.js` -- 用例:只验证 `stock.warehouse.list` 请求成功与核心返回结构。 -- 下沉:复杂 where/operator 组合继续由 service 级测试覆盖。 - -## 执行结果 -- [x] `warehouse.js` 方法头注释补充(输入/输出声明) -- [x] 新接口测试用例精简 -- [x] `methods/system.json` 的 `stock.warehouse.*` description 语义化更新(21项) -- [x] 回归测试复跑并记录结果(`8 passing`) diff --git a/test/app/controller/gateway.user.bindAccountByTempCode.test.js b/test/app/controller/gateway.user.bindAccountByTempCode.test.js index 36246ef..64ed022 100644 --- a/test/app/controller/gateway.user.bindAccountByTempCode.test.js +++ b/test/app/controller/gateway.user.bindAccountByTempCode.test.js @@ -10,23 +10,49 @@ const { const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28); describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => { - it('should bind, unbind, and bind again for ye4s user', async () => { + it('should scan, bind, unbind, and bind again for ye4s user', async () => { const { token } = await getAuthToken(); + const ensurePendingCode = async () => { + let bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + + if (bindCodeRes.body?.data?.status === 'bound') { + const unbindFirst = await invokeSystemMethod('user.unbindWechat', {}, token); + assert.equal(unbindFirst.status, 200); + assert.equal(unbindFirst.body.flag, 'success'); + bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + } + + const nextCode = String(bindCodeRes.body?.data?.code || ''); + assert.match(nextCode, /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + return nextCode; + }; + const infoRes = await invokeSystemMethod('user.info', {}, token); assert.equal(infoRes.status, 200); assert.equal(infoRes.body.flag, 'success'); const accountId = Number(infoRes.body?.data?.id); assert.ok(Number.isFinite(accountId) && accountId > 0); - const bindCodeRes = await invokeSystemMethod('user.getBindWechatCode', { - forceRefresh: true, - init: true, - }, token); - assert.equal(bindCodeRes.status, 200); - assert.equal(bindCodeRes.body.flag, 'success'); - const code = String(bindCodeRes.body?.data?.code || ''); - assert.ok(code.length > 10); + const code = await ensurePendingCode(); + + const scanRes1 = await invokeGatewayMethod('user.getUserByTempCode', { code }); + assert.equal(scanRes1.status, 200); + assert.equal(scanRes1.body.flag, 'success'); + assert.equal(scanRes1.body.code, 200); + assert.equal(Number(scanRes1.body?.data?.account_id), accountId); + assert.ok(String(scanRes1.body?.data?.real_name || '')); + assert.equal(scanRes1.body?.data?.status, 'scanned'); + + const scannedStateRes1 = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(scannedStateRes1.status, 200); + assert.equal(scannedStateRes1.body.flag, 'success'); + assert.equal(scannedStateRes1.body?.data?.status, 'scanned'); + assert.equal(String(scannedStateRes1.body?.data?.code || ''), code); const bindRes1 = await invokeGatewayMethod('user.bindAccountByTempCode', { code, @@ -46,8 +72,18 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => assert.equal(unbindRes.body?.data?.status, 'unbound'); assert.equal(Number(unbindRes.body?.data?.account_id), accountId); + const code2 = await ensurePendingCode(); + + const scanRes2 = await invokeGatewayMethod('user.getUserByTempCode', { code: code2 }); + assert.equal(scanRes2.status, 200); + assert.equal(scanRes2.body.flag, 'success'); + assert.equal(scanRes2.body.code, 200); + assert.equal(Number(scanRes2.body?.data?.account_id), accountId); + assert.ok(String(scanRes2.body?.data?.real_name || '')); + assert.equal(scanRes2.body?.data?.status, 'scanned'); + const bindRes2 = await invokeGatewayMethod('user.bindAccountByTempCode', { - code, + code: code2, ye4s_user_id: YE4S_TEST_USER_ID, }); assert.equal(bindRes2.status, 200); @@ -57,11 +93,10 @@ describe('test/app/controller/gateway.user.bindAccountByTempCode.test.js', () => assert.equal(Number(bindRes2.body?.data?.ye4s_user_id), YE4S_TEST_USER_ID); assert.equal(bindRes2.body?.data?.status, 'bound'); - const verifyRes = await invokeGatewayMethod('user.getUserByTempCode', { code }); - assert.equal(verifyRes.status, 200); - assert.equal(verifyRes.body.flag, 'success'); - assert.equal(verifyRes.body.code, 200); - assert.equal(Number(verifyRes.body?.data?.account_id), accountId); - assert.equal(verifyRes.body?.data?.status, 'bound'); + const boundStateRes = await invokeSystemMethod('user.getBindWechatCode', {}, token); + assert.equal(boundStateRes.status, 200); + assert.equal(boundStateRes.body.flag, 'success'); + assert.equal(boundStateRes.body?.data?.status, 'bound'); + assert.equal(String(boundStateRes.body?.data?.code || ''), ''); }); }); diff --git a/test/app/controller/system.setting.account.getBindWechatCode.test.js b/test/app/controller/system.setting.account.getBindWechatCode.test.js new file mode 100644 index 0000000..c5b34ee --- /dev/null +++ b/test/app/controller/system.setting.account.getBindWechatCode.test.js @@ -0,0 +1,195 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, + invokeGatewayMethod, +} = require('../../support/system_method_client'); + +const YE4S_TEST_USER_ID = Number(process.env.SYSTEM_TEST_YE4S_USER_ID || 28); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +function buildTempPhone() { + return `139${String(Date.now()).slice(-8)}`; +} + +function flattenRoleIds(roleNodes, collector = []) { + if (!Array.isArray(roleNodes)) { + return collector; + } + for (const item of roleNodes) { + const roleId = Number(item && item.role_id); + if (Number.isFinite(roleId) && roleId > 0) { + collector.push(roleId); + } + flattenRoleIds(item && item.children, collector); + } + return collector; +} + +describe('test/app/controller/system.setting.account.getBindWechatCode.test.js', () => { + let token = ''; + let tempEmployeeId = 0; + let tempAccountId = 0; + + async function getAssignableRoleIds() { + const res = await invokeSystemMethod('setting.role.list', { + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const roleIds = Array.from(new Set(flattenRoleIds(res.body?.data?.roles || []))); + assert.ok(roleIds.length > 0, '当前账号没有可分配角色,无法创建测试账号'); + return [ roleIds[0] ]; + } + + before(async () => { + const auth = await getAuthToken(); + token = auth.token; + + const roleIds = await getAssignableRoleIds(); + const addRes = await invokeSystemMethod('setting.account.add', { + phone: buildTempPhone(), + username: `autotest_bind_wechat_${Date.now()}`, + password: '111111', + real_name: `微信代绑测试_${Date.now()}`, + ids: roleIds, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + + tempEmployeeId = Number(addRes.body?.data?.employee_id || 0); + tempAccountId = Number(addRes.body?.data?.account_id || 0); + assert.ok(tempEmployeeId > 0); + assert.ok(tempAccountId > 0); + }); + + after(async () => { + if (!token || !tempEmployeeId) { + return; + } + + const deleteRes = await invokeSystemMethod('setting.account.delete', { + employee_id: tempEmployeeId, + }, token, EXTRA_HEADERS); + + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.code, 200); + }); + + it('should get bind wechat code for an operable account by user_id', async () => { + const res = await invokeSystemMethod('setting.account.getBindWechatCode', { + user_id: tempAccountId, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.equal(Number(res.body?.data?.account_id || 0), tempAccountId); + assert.equal(res.body?.data?.status, 'pending'); + assert.equal(res.body?.data?.is_bound, false); + assert.match(String(res.body?.data?.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.ok(Number(res.body?.data?.expire_after_ms || 0) > 0); + }); + + it('should include wechat bind status in setting.account.list rows', async () => { + const res = await invokeSystemMethod('setting.account.list', { + where: { + account_id: tempAccountId, + }, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const list = Array.isArray(res.body?.data) ? res.body.data : []; + const target = list.find(item => Number(item && item.account_id) === tempAccountId); + assert.ok(target, '新建账号未出现在列表中'); + assert.equal(typeof target.is_wechat_bound, 'boolean'); + assert.equal(target.is_wechat_bound, false); + assert.equal(target.ye4s_user_id, null); + }); + + it('should unbind wechat for an operable account', async () => { + const bindCodeRes = await invokeSystemMethod('setting.account.getBindWechatCode', { + user_id: tempAccountId, + }, token, EXTRA_HEADERS); + + assert.equal(bindCodeRes.status, 200); + assert.equal(bindCodeRes.body.flag, 'success'); + const code = String(bindCodeRes.body?.data?.code || ''); + assert.match(code, /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + + const scanRes = await invokeGatewayMethod('user.getUserByTempCode', { + code, + }); + assert.equal(scanRes.status, 200); + assert.equal(scanRes.body.flag, 'success'); + assert.equal(scanRes.body.code, 200); + assert.equal(Number(scanRes.body?.data?.account_id || 0), tempAccountId); + assert.equal(scanRes.body?.data?.status, 'scanned'); + + const bindRes = await invokeGatewayMethod('user.bindAccountByTempCode', { + code, + ye4s_user_id: YE4S_TEST_USER_ID, + }); + assert.equal(bindRes.status, 200); + assert.equal(bindRes.body.flag, 'success'); + assert.equal(bindRes.body.code, 200); + assert.equal(Number(bindRes.body?.data?.account_id || 0), tempAccountId); + + const unbindRes = await invokeSystemMethod('setting.account.unbindWechat', { + user_id: tempAccountId, + }, token, EXTRA_HEADERS); + + assert.equal(unbindRes.status, 200); + assert.equal(unbindRes.body.flag, 'success'); + assert.equal(unbindRes.body.code, 200); + assert.equal(Number(unbindRes.body?.data?.account_id || 0), tempAccountId); + assert.equal(unbindRes.body?.data?.status, 'unbound'); + assert.ok(Number(unbindRes.body?.data?.matched_rows || 0) >= 1); + + const listRes = await invokeSystemMethod('setting.account.list', { + where: { + account_id: tempAccountId, + }, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + const list = Array.isArray(listRes.body?.data) ? listRes.body.data : []; + const target = list.find(item => Number(item && item.account_id) === tempAccountId); + assert.ok(target, '解绑后账号未出现在列表中'); + assert.equal(target.is_wechat_bound, false); + assert.equal(target.ye4s_user_id, null); + }); + + it('should reject when user_id is missing', async () => { + const res = await invokeSystemMethod('setting.account.getBindWechatCode', {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 400); + assert.match(String(res.body?.message || ''), /user_id 参数不能为空/); + }); + + it('should reject unbind when user_id is missing', async () => { + const res = await invokeSystemMethod('setting.account.unbindWechat', {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(res.body.code, 400); + assert.match(String(res.body?.message || ''), /user_id 参数不能为空/); + }); +}); \ No newline at end of file diff --git a/test/app/controller/system.setting.permission.test.js b/test/app/controller/system.setting.permission.test.js new file mode 100644 index 0000000..af6053a --- /dev/null +++ b/test/app/controller/system.setting.permission.test.js @@ -0,0 +1,343 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +describe('test/app/controller/system.setting.permission.test.js', () => { + let token = ''; + let anchorPermissionId = 0; + let createdPermissionId = 0; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + + const listRes = await invokeSystemMethod('setting.permission.list', {}, token, EXTRA_HEADERS); + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const permissions = Array.isArray(listRes.body?.data?.permissions) ? listRes.body.data.permissions : []; + assert.ok(permissions.length > 0, '当前账号无可用权限,无法执行回归'); + anchorPermissionId = Number(permissions[0].permission_id || 0); + assert.ok(anchorPermissionId > 0, '锚点权限ID无效'); + }); + + after(async () => { + if (createdPermissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + } + }); + + it('should expose setting.role.permission as alias of setting.permission.list', async () => { + const requestData = { + type: 'api', + includeDisabled: false, + }; + + const listRes = await invokeSystemMethod('setting.permission.list', requestData, token, EXTRA_HEADERS); + const aliasRes = await invokeSystemMethod('setting.role.permission', requestData, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(aliasRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(aliasRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + assert.equal(aliasRes.body.code, 200); + assert.deepEqual(aliasRes.body.data, listRes.body.data); + }); + + it('should include route presentation fields in permission list response', async () => { + const suffix = Date.now(); + const path = `autotest.permission.route.${suffix}`; + let tempPermissionId = 0; + + try { + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_route_${suffix}`, + component: 'layout/RouteComponent', + redirect: '/autotest/redirect', + meta_title: `autotest_route_meta_${suffix}`, + meta_icon: 'Setting', + parent_id: anchorPermissionId, + hidden: 1, + always_show: 1, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + tempPermissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(tempPermissionId > 0, '新增路由权限失败'); + + const listRes = await invokeSystemMethod('setting.permission.list', { + keyword: path, + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const permissions = Array.isArray(listRes.body?.data?.permissions) ? listRes.body.data.permissions : []; + const target = permissions.find(item => Number(item && item.permission_id) === tempPermissionId); + assert.ok(target, '新建权限未出现在权限列表中'); + assert.equal(target.component, 'layout/RouteComponent'); + assert.equal(target.redirect, '/autotest/redirect'); + assert.equal(target.meta_icon, 'Setting'); + assert.equal(Number(target.hidden), 1); + assert.equal(Number(target.always_show), 1); + } finally { + if (tempPermissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ tempPermissionId ], + }, token, EXTRA_HEADERS); + } + } + }); + + it('should show newly created permission in list for admin management', async () => { + const suffix = Date.now(); + const path = `autotest.permission.visible.${suffix}`; + let tempPermissionId = 0; + + try { + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_visible_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + tempPermissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(tempPermissionId > 0, '新增测试权限失败'); + + const res = await invokeSystemMethod('setting.permission.list', { + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const permissions = Array.isArray(res.body?.data?.permissions) ? res.body.data.permissions : []; + assert.ok(permissions.some(item => Number(item && item.permission_id) === tempPermissionId), '新建权限未出现在权限列表中'); + } finally { + if (tempPermissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ tempPermissionId ], + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject permission update when target permission does not exist', async () => { + const updateRes = await invokeSystemMethod('setting.permission.update', { + permission_id: 999999999, + name: 'not_found_update', + }, token, EXTRA_HEADERS); + + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'failure'); + assert.equal(Number(updateRes.body.code), 404); + assert.match(String(updateRes.body.message || ''), /权限不存在/); + }); + + it('should create then update then delete permission successfully', async () => { + const suffix = Date.now(); + const path = `autotest.permission.${suffix}`; + + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_add_${suffix}`, + parent_id: anchorPermissionId, + meta_title: `autotest_meta_${suffix}`, + sort: 0, + hidden: 0, + always_show: 0, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + createdPermissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(createdPermissionId > 0, '新增权限失败,permission_id 无效'); + + const updateRes = await invokeSystemMethod('setting.permission.update', { + permission_id: createdPermissionId, + name: `autotest_update_${suffix}`, + meta_title: `autotest_meta_update_${suffix}`, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'success'); + assert.equal(updateRes.body.code, 200); + assert.equal(Number(updateRes.body?.data?.permission_id), createdPermissionId); + + const deleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.flag, 'success'); + assert.equal(deleteRes.body.code, 200); + const deletedIds = Array.isArray(deleteRes.body?.data?.deleted_ids) ? deleteRes.body.data.deleted_ids : []; + assert.ok(deletedIds.includes(createdPermissionId), '删除结果中未包含新建权限ID'); + + const deleteAgainRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ createdPermissionId ], + }, token, EXTRA_HEADERS); + assert.equal(deleteAgainRes.status, 200); + assert.equal(deleteAgainRes.body.flag, 'success'); + assert.equal(deleteAgainRes.body.code, 200); + const alreadyDeletedIds = Array.isArray(deleteAgainRes.body?.data?.already_deleted_ids) + ? deleteAgainRes.body.data.already_deleted_ids + : []; + assert.ok(alreadyDeletedIds.includes(createdPermissionId), '二次删除未返回 already_deleted_ids'); + + createdPermissionId = 0; + }); + + it('should split deleted_ids and already_deleted_ids in mixed batch delete', async () => { + const suffix = Date.now(); + const firstPath = `autotest.permission.mixed.first.${suffix}`; + const secondPath = `autotest.permission.mixed.second.${suffix}`; + let firstPermissionId = 0; + let secondPermissionId = 0; + + try { + const addFirstRes = await invokeSystemMethod('setting.permission.add', { + path: firstPath, + type: 'btns', + name: `autotest_mixed_first_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + assert.equal(addFirstRes.status, 200); + assert.equal(addFirstRes.body.flag, 'success'); + assert.equal(addFirstRes.body.code, 200); + firstPermissionId = Number(addFirstRes.body?.data?.permission_id || 0); + assert.ok(firstPermissionId > 0, 'first permission_id 无效'); + + const addSecondRes = await invokeSystemMethod('setting.permission.add', { + path: secondPath, + type: 'btns', + name: `autotest_mixed_second_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + assert.equal(addSecondRes.status, 200); + assert.equal(addSecondRes.body.flag, 'success'); + assert.equal(addSecondRes.body.code, 200); + secondPermissionId = Number(addSecondRes.body?.data?.permission_id || 0); + assert.ok(secondPermissionId > 0, 'second permission_id 无效'); + + const preDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ firstPermissionId ], + }, token, EXTRA_HEADERS); + assert.equal(preDeleteRes.status, 200); + assert.equal(preDeleteRes.body.flag, 'success'); + assert.equal(preDeleteRes.body.code, 200); + + const mixedDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ firstPermissionId, secondPermissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(mixedDeleteRes.status, 200); + assert.equal(mixedDeleteRes.body.flag, 'success'); + assert.equal(mixedDeleteRes.body.code, 200); + + const deletedIds = Array.isArray(mixedDeleteRes.body?.data?.deleted_ids) + ? mixedDeleteRes.body.data.deleted_ids + : []; + const alreadyDeletedIds = Array.isArray(mixedDeleteRes.body?.data?.already_deleted_ids) + ? mixedDeleteRes.body.data.already_deleted_ids + : []; + + assert.ok(deletedIds.includes(secondPermissionId), 'mixed 删除结果中缺少启用权限ID'); + assert.ok(alreadyDeletedIds.includes(firstPermissionId), 'mixed 删除结果中缺少已删除权限ID'); + + firstPermissionId = 0; + secondPermissionId = 0; + } finally { + const cleanupIds = [ firstPermissionId, secondPermissionId ].filter(id => Number(id) > 0); + if (cleanupIds.length > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: cleanupIds, + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject mixed delete when ids contain non-existent permission', async () => { + const suffix = Date.now(); + const path = `autotest.permission.mixed.outscope.${suffix}`; + let permissionId = 0; + + try { + const addRes = await invokeSystemMethod('setting.permission.add', { + path, + type: 'btns', + name: `autotest_mixed_outscope_${suffix}`, + parent_id: anchorPermissionId, + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(addRes.status, 200); + assert.equal(addRes.body.flag, 'success'); + assert.equal(addRes.body.code, 200); + permissionId = Number(addRes.body?.data?.permission_id || 0); + assert.ok(permissionId > 0, 'permission_id 无效'); + + const mixedRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId, 999999999 ], + }, token, EXTRA_HEADERS); + + assert.equal(mixedRes.status, 200); + assert.equal(mixedRes.body.flag, 'failure'); + assert.equal(Number(mixedRes.body.code), 404); + assert.match(String(mixedRes.body.message || ''), /权限不存在/); + + // 失败后应保持原子性:合法权限仍可被正常删除(说明前一次未误删) + const verifyDeleteRes = await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId ], + }, token, EXTRA_HEADERS); + + assert.equal(verifyDeleteRes.status, 200); + assert.equal(verifyDeleteRes.body.flag, 'success'); + assert.equal(verifyDeleteRes.body.code, 200); + const deletedIds = Array.isArray(verifyDeleteRes.body?.data?.deleted_ids) + ? verifyDeleteRes.body.data.deleted_ids + : []; + assert.ok(deletedIds.includes(permissionId), '混入越权ID失败后,合法权限不应被提前删除'); + + permissionId = 0; + } finally { + if (permissionId > 0) { + await invokeSystemMethod('setting.permission.delete', { + ids: [ permissionId ], + }, token, EXTRA_HEADERS); + } + } + }); +}); diff --git a/test/app/controller/system.setting.role.test.js b/test/app/controller/system.setting.role.test.js new file mode 100644 index 0000000..16372b0 --- /dev/null +++ b/test/app/controller/system.setting.role.test.js @@ -0,0 +1,198 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +function findRoleNode(roleNodes, targetRoleId) { + if (!Array.isArray(roleNodes) || !Number.isFinite(Number(targetRoleId))) { + return null; + } + + for (const item of roleNodes) { + if (Number(item && item.role_id) === Number(targetRoleId)) { + return item; + } + + const childMatch = findRoleNode(item && item.children, targetRoleId); + if (childMatch) { + return childMatch; + } + } + + return null; +} + +describe('test/app/controller/system.setting.role.test.js', () => { + let token = ''; + let anchorPermissionId = 0; + let currentRoleId = 0; + const cleanupRoleIds = []; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + + const permissionRes = await invokeSystemMethod('setting.permission.list', { + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(permissionRes.status, 200); + assert.equal(permissionRes.body.flag, 'success'); + assert.equal(permissionRes.body.code, 200); + + const permissions = Array.isArray(permissionRes.body?.data?.permissions) + ? permissionRes.body.data.permissions + : []; + assert.ok(permissions.length > 0, '当前系统没有可用权限,无法创建测试角色'); + anchorPermissionId = Number(permissions[0].permission_id || 0); + assert.ok(anchorPermissionId > 0, '锚点权限ID无效'); + + currentRoleId = Number(permissionRes.body?.data?.role_id || 0); + assert.ok(currentRoleId > 0, '当前角色ID无效'); + }); + + after(async () => { + if (!token || cleanupRoleIds.length === 0) { + return; + } + + await invokeSystemMethod('setting.role.delete', { + ids: cleanupRoleIds, + }, token, EXTRA_HEADERS); + }); + + it('should support wildcard role permissions via ["*"]', async () => { + const suffix = Date.now(); + const wildcardAddRes = await invokeSystemMethod('setting.role.add', { + role_code: `autotest_role_all_${suffix}`, + role_name: `autotest_role_all_${suffix}`, + description: 'role wildcard regression', + pid: currentRoleId, + permission_ids: [ '*' ], + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(wildcardAddRes.status, 200); + assert.equal(wildcardAddRes.body.flag, 'success'); + assert.equal(wildcardAddRes.body.code, 200); + + const wildcardRoleId = Number(wildcardAddRes.body?.data?.role_id || 0); + assert.ok(wildcardRoleId > 0, '创建全权限角色失败'); + cleanupRoleIds.push(wildcardRoleId); + + const permissionRes = await invokeSystemMethod('setting.role.permission', { + role_id: wildcardRoleId, + includeDisabled: false, + }, token, EXTRA_HEADERS); + + assert.equal(permissionRes.status, 200); + assert.equal(permissionRes.body.flag, 'success'); + assert.equal(permissionRes.body.code, 200); + + const permissions = Array.isArray(permissionRes.body?.data?.permissions) + ? permissionRes.body.data.permissions + : []; + assert.ok(permissions.length > 0, '全权限角色应能看到权限列表'); + assert.ok(permissions.every(item => item && item.selected === true), '当 permission_ids=["*"] 时,所有权限都应为选中状态'); + + const listRes = await invokeSystemMethod('setting.role.list', { + includeDisabled: false, + includeSystem: true, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const roots = Array.isArray(listRes.body?.data?.roles) + ? listRes.body.data.roles + : []; + const wildcardNode = findRoleNode(roots, wildcardRoleId); + assert.ok(wildcardNode, '返回结果中未包含新建的全权限角色'); + assert.ok(Array.isArray(wildcardNode.permission_ids), '全权限角色应返回 permission_ids'); + assert.ok(wildcardNode.permission_ids.includes('*'), '全权限角色应以 ["*"] 表示拥有全部权限'); + }); + + it('should only return descendant roles and keep their children', async () => { + const suffix = Date.now(); + + const childAddRes = await invokeSystemMethod('setting.role.add', { + role_code: `autotest_role_child_${suffix}`, + role_name: `autotest_role_child_${suffix}`, + description: 'role tree child regression', + pid: currentRoleId, + permission_ids: [ anchorPermissionId ], + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(childAddRes.status, 200); + assert.equal(childAddRes.body.flag, 'success'); + assert.equal(childAddRes.body.code, 200); + + const createdChildRoleId = Number(childAddRes.body?.data?.role_id || 0); + assert.ok(createdChildRoleId > 0, '创建下级角色失败'); + cleanupRoleIds.push(createdChildRoleId); + + const grandChildAddRes = await invokeSystemMethod('setting.role.add', { + role_code: `autotest_role_grandchild_${suffix}`, + role_name: `autotest_role_grandchild_${suffix}`, + description: 'role tree grandchild regression', + pid: createdChildRoleId, + permission_ids: [ anchorPermissionId ], + status: 1, + }, token, EXTRA_HEADERS); + + assert.equal(grandChildAddRes.status, 200); + assert.equal(grandChildAddRes.body.flag, 'success'); + assert.equal(grandChildAddRes.body.code, 200); + + const createdGrandChildRoleId = Number(grandChildAddRes.body?.data?.role_id || 0); + assert.ok(createdGrandChildRoleId > 0, '创建孙级角色失败'); + cleanupRoleIds.unshift(createdGrandChildRoleId); + + const listRes = await invokeSystemMethod('setting.role.list', { + includeDisabled: false, + includeSystem: true, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const roots = Array.isArray(listRes.body?.data?.roles) + ? listRes.body.data.roles + : []; + assert.ok(roots.length > 0, '应返回至少一层下级角色'); + assert.ok( + roots.every(item => Number(item && item.pid) === currentRoleId), + 'setting.role.list 第一层只应返回当前角色的直接下级角色' + ); + assert.ok( + !roots.some(item => Number(item && item.role_id) === currentRoleId), + 'setting.role.list 不应返回当前角色本身' + ); + + const createdChildNode = findRoleNode(roots, createdChildRoleId); + assert.ok(createdChildNode, '返回结果中未包含新建的下级角色'); + assert.ok( + Array.isArray(createdChildNode.children) + && createdChildNode.children.some(item => Number(item && item.role_id) === createdGrandChildRoleId), + '下级角色的 children 组装异常:新建孙级角色未挂到对应父角色下' + ); + assert.ok(Array.isArray(createdChildNode.permission_ids), '下级角色节点应返回 permission_ids 权限集'); + assert.ok(createdChildNode.permission_ids.includes(anchorPermissionId), '下级角色未返回已绑定权限集'); + + const createdGrandChildNode = findRoleNode(roots, createdGrandChildRoleId); + assert.ok(createdGrandChildNode, '返回结果中未包含新建的孙级角色'); + assert.ok(Array.isArray(createdGrandChildNode.permission_ids), '孙级角色节点应返回 permission_ids 权限集'); + assert.ok(createdGrandChildNode.permission_ids.includes(anchorPermissionId), '孙级角色未返回已绑定权限集'); + }); +}); diff --git a/test/app/controller/system.setting.storeWarehouse.test.js b/test/app/controller/system.setting.storeWarehouse.test.js new file mode 100644 index 0000000..c645e65 --- /dev/null +++ b/test/app/controller/system.setting.storeWarehouse.test.js @@ -0,0 +1,413 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +describe('test/app/controller/system.setting.storeWarehouse.test.js', () => { + const METHOD_PREFIX = 'storeWarehouse.store'; + let token = ''; + let sampleRelation = null; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + }); + + it('should list store-warehouse contracts in current subject scope', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.ok(Array.isArray(res.body?.data?.list), 'list 应返回数组'); + assert.ok(res.body?.data?.current_subject, '应返回当前主体信息'); + sampleRelation = Array.isArray(res.body?.data?.list) && res.body.data.list.length > 0 + ? res.body.data.list[0] + : null; + }); + + it('should allow renaming current-side remask and reflect it in list display', async () => { + assert.ok(sampleRelation, '需要至少一条现有签约关系用于改名回归'); + + const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const currentRole = String(listRes.body?.data?.current_subject?.role || ''); + const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; + const candidate = candidates.find(item => Number(item.id) > 0); + assert.ok(candidate, '需要至少一条签约关系用于改名回归'); + + const isWarehouse = currentRole === 'warehouse'; + const originRemask = String(candidate.remask || ''); + const nextRemask = `autotest_alias_${Date.now()}`; + + try { + const renameRes = await invokeSystemMethod(`${METHOD_PREFIX}.rename`, { + id: Number(candidate.id), + remask: nextRemask, + }, token, EXTRA_HEADERS); + + assert.equal(renameRes.status, 200); + assert.equal(renameRes.body.flag, 'success'); + assert.equal(renameRes.body.code, 200); + assert.equal(String(renameRes.body?.data?.contract?.remask), nextRemask); + assert.equal( + String(isWarehouse ? renameRes.body?.data?.contract?.store_name : renameRes.body?.data?.contract?.warehouse_name), + nextRemask + ); + + const verifyRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + + assert.equal(verifyRes.status, 200); + assert.equal(verifyRes.body.flag, 'success'); + assert.equal(verifyRes.body.code, 200); + + const verified = Array.isArray(verifyRes.body?.data?.list) ? verifyRes.body.data.list[0] : null; + assert.ok(verified, '改名后应能查到对应签约关系'); + assert.equal( + String(isWarehouse ? verified.store_name : verified.warehouse_name), + nextRemask + ); + } finally { + await invokeSystemMethod(`${METHOD_PREFIX}.rename`, { + id: Number(candidate.id), + remask: originRemask, + }, token, EXTRA_HEADERS); + } + }); + + it('should generate a temp code and support preview before confirmation', async () => { + assert.ok(sampleRelation, '需要至少一条现有签约关系用于临时码回归'); + + const candidateRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(candidateRes.status, 200); + assert.equal(candidateRes.body.flag, 'success'); + assert.equal(candidateRes.body.code, 200); + + const candidates = Array.isArray(candidateRes.body?.data?.list) ? candidateRes.body.data.list : []; + assert.ok(candidates.length > 0, '需要至少一条签约关系用于临时码回归'); + + let initRes = null; + for (const item of candidates) { + const attempt = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { + counterparty_id: Number(item.counterparty_id), + apply_reason: 'autotest temp sign flow', + remask: `autotest_remask_${Date.now()}`, + }, token, EXTRA_HEADERS); + + if (attempt.status === 200 && attempt.body && attempt.body.flag === 'success') { + initRes = attempt; + break; + } + } + + assert.ok(initRes, '未找到可发起临时码签约的对方主体,请确认测试账号签约数据'); + + assert.equal(initRes.status, 200); + assert.equal(initRes.body.flag, 'success'); + assert.equal(initRes.body.code, 200); + assert.equal(initRes.body?.data?.mode, 'initiate'); + assert.ok(String(initRes.body?.data?.temp_code || '').length >= 8, '发起签约后应返回临时码'); + + const previewRes = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { + temp_code: initRes.body.data.temp_code, + action: 'preview', + }, token, EXTRA_HEADERS); + + assert.equal(previewRes.status, 200); + assert.equal(previewRes.body.flag, 'success'); + assert.equal(previewRes.body.code, 200); + assert.equal(previewRes.body?.data?.mode, 'preview'); + assert.equal(String(previewRes.body?.data?.temp_code || ''), String(initRes.body?.data?.temp_code || '')); + assert.equal(Boolean(previewRes.body?.data?.can_confirm), false, '同一发起方不应直接确认自己的临时码'); + }); + + it('should only change use_status when unbinding', async () => { + assert.ok(sampleRelation, '需要至少一条现有签约关系用于解除回归'); + + const originalAuthStatus = Number(sampleRelation.auth_status || 0); + const originalUseStatus = Number(sampleRelation.use_status || 0); + const targetUseStatus = originalUseStatus === 1 ? 0 : 1; + + try { + const unbindRes = await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, { + id: Number(sampleRelation.id), + use_status: targetUseStatus, + }, token, EXTRA_HEADERS); + + assert.equal(unbindRes.status, 200); + assert.equal(unbindRes.body.flag, 'success'); + assert.equal(unbindRes.body.code, 200); + assert.equal(Number(unbindRes.body?.data?.contract?.use_status), targetUseStatus); + assert.equal(Number(unbindRes.body?.data?.contract?.auth_status), originalAuthStatus, '解除接口不应改动 auth_status'); + } finally { + await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, { + id: Number(sampleRelation.id), + use_status: originalUseStatus, + }, token, EXTRA_HEADERS); + } + }); + + it('should allow warehouse side to save and get policy config on a contract', async function() { + const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const currentRole = String(listRes.body?.data?.current_subject?.role || ''); + if (currentRole !== 'warehouse') { + this.skip(); + } + + const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; + const candidate = candidates.find(item => Number(item.id) > 0); + assert.ok(candidate, '需要至少一条签约关系用于策略配置回归'); + + const originalPolicyConfig = candidate.policy_config && typeof candidate.policy_config === 'object' + ? { ...candidate.policy_config } + : null; + const nextPolicyConfig = { + receive_mode: 'strict', + sku_visibility: 'whitelist', + auto_allocate_bin: 1, + allow_mix_batch: 0, + max_daily_inbound: 5000, + remark: `autotest_${Date.now()}`, + }; + + try { + const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, { + id: Number(candidate.id), + policy_config: nextPolicyConfig, + }, token, EXTRA_HEADERS); + + assert.equal(saveRes.status, 200); + assert.equal(saveRes.body.flag, 'success'); + assert.equal(saveRes.body.code, 200); + assert.equal(Number(saveRes.body?.data?.contract_id || 0), Number(candidate.id)); + assert.equal(String(saveRes.body?.data?.policy_config?.receive_mode || ''), 'strict'); + assert.equal(Number(saveRes.body?.data?.policy_config?.auto_allocate_bin || 0), 1); + + const getRes = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + + assert.equal(getRes.status, 200); + assert.equal(getRes.body.flag, 'success'); + assert.equal(getRes.body.code, 200); + assert.equal(Number(getRes.body?.data?.contract_id || 0), Number(candidate.id)); + assert.equal(String(getRes.body?.data?.policy_config?.sku_visibility || ''), 'whitelist'); + assert.equal(Number(getRes.body?.data?.policy_config?.max_daily_inbound || 0), 5000); + } finally { + if (originalPolicyConfig) { + await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, { + id: Number(candidate.id), + policy_config: originalPolicyConfig, + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject unsupported policy config fields on a contract', async function() { + const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const currentRole = String(listRes.body?.data?.current_subject?.role || ''); + if (currentRole !== 'warehouse') { + this.skip(); + } + + const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; + const candidate = candidates.find(item => Number(item.id) > 0); + assert.ok(candidate, '需要至少一条签约关系用于策略字段限制回归'); + + const res = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, { + id: Number(candidate.id), + policy_config: { + receive_mode: 'strict', + unexpected_field: 'blocked', + }, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /unexpected_field|不支持字段/); + }); + + it('should allow warehouse side to save, update and delete qimen config on a contract', async function() { + const listRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 30, + }, token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const currentRole = String(listRes.body?.data?.current_subject?.role || ''); + if (currentRole !== 'warehouse') { + this.skip(); + } + + const candidates = Array.isArray(listRes.body?.data?.list) ? listRes.body.data.list : []; + const candidate = candidates.find(item => Number(item.id) > 0); + assert.ok(candidate, '需要至少一条签约关系用于奇门配置回归'); + + const originalQimenConfig = candidate.qimen_config ? { ...candidate.qimen_config } : null; + const seed = Date.now(); + const createPayload = { + id: Number(candidate.id), + app_name: `autotest_qimen_${seed}`, + qimen_app_key: `autotest_app_${seed}`, + qimen_customer_id: `autotest_customer_${seed}`, + qimen_warehouse_code: `autotest_wh_${seed}`, + contact_person: 'autotest', + contact_phone: '13800138000', + email: `autotest_${seed}@example.com`, + is_enabled: 1, + }; + + try { + const saveRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, createPayload, token, EXTRA_HEADERS); + assert.equal(saveRes.status, 200); + assert.equal(saveRes.body.flag, 'success'); + assert.equal(saveRes.body.code, 200); + assert.match(String(saveRes.body?.data?.action || ''), /create|update/); + assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_app_key || ''), createPayload.qimen_app_key); + assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_customer_id || ''), createPayload.qimen_customer_id); + assert.equal(String(saveRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), createPayload.qimen_warehouse_code); + + const updatePayload = { + ...createPayload, + app_name: `${createPayload.app_name}_updated`, + qimen_customer_id: `${createPayload.qimen_customer_id}_updated`, + qimen_warehouse_code: `${createPayload.qimen_warehouse_code}_updated`, + is_enabled: 0, + }; + const updateRes = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, updatePayload, token, EXTRA_HEADERS); + assert.equal(updateRes.status, 200); + assert.equal(updateRes.body.flag, 'success'); + assert.equal(updateRes.body.code, 200); + assert.equal(String(updateRes.body?.data?.action || ''), 'update'); + assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + assert.equal(String(updateRes.body?.data?.qimen_config?.qimen_warehouse_code || ''), updatePayload.qimen_warehouse_code); + assert.equal(Number(updateRes.body?.data?.qimen_config?.is_enabled), 0); + + const verifyRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(verifyRes.status, 200); + assert.equal(verifyRes.body.flag, 'success'); + assert.equal(verifyRes.body.code, 200); + const verified = Array.isArray(verifyRes.body?.data?.list) ? verifyRes.body.data.list[0] : null; + assert.ok(verified, '保存奇门配置后应能查询到签约关系'); + assert.equal(String(verified?.qimen_config?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + + const configListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(configListRes.status, 200); + assert.equal(configListRes.body.flag, 'success'); + assert.equal(configListRes.body.code, 200); + assert.equal(Number(configListRes.body?.data?.contract_id || 0), Number(candidate.id)); + assert.ok(Array.isArray(configListRes.body?.data?.list), '应返回奇门配置列表'); + assert.ok((configListRes.body?.data?.list || []).length >= 1, '保存后应至少返回一条奇门配置'); + assert.equal(String(configListRes.body?.data?.list?.[0]?.qimen_customer_id || ''), updatePayload.qimen_customer_id); + + const deleteRes = await invokeSystemMethod(`${METHOD_PREFIX}.deleteQimenConfig`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(deleteRes.status, 200); + assert.equal(deleteRes.body.flag, 'success'); + assert.equal(deleteRes.body.code, 200); + assert.equal(Boolean(deleteRes.body?.data?.deleted), true); + + const verifyDeleteRes = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(verifyDeleteRes.status, 200); + assert.equal(verifyDeleteRes.body.flag, 'success'); + assert.equal(verifyDeleteRes.body.code, 200); + const deletedView = Array.isArray(verifyDeleteRes.body?.data?.list) ? verifyDeleteRes.body.data.list[0] : null; + assert.ok(deletedView, '删除奇门配置后仍应能查询到签约关系'); + assert.equal(deletedView?.qimen_config || null, null); + + const emptyListRes = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, { + id: Number(candidate.id), + }, token, EXTRA_HEADERS); + assert.equal(emptyListRes.status, 200); + assert.equal(emptyListRes.body.flag, 'success'); + assert.equal(emptyListRes.body.code, 200); + assert.ok(Array.isArray(emptyListRes.body?.data?.list), '删除后仍应返回列表结构'); + assert.equal(Number(emptyListRes.body?.data?.total || 0), 0); + } finally { + if (originalQimenConfig) { + await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, { + id: Number(candidate.id), + app_name: originalQimenConfig.app_name, + qimen_app_key: originalQimenConfig.qimen_app_key, + qimen_customer_id: originalQimenConfig.qimen_customer_id, + qimen_warehouse_code: originalQimenConfig.qimen_warehouse_code, + contact_person: originalQimenConfig.contact_person, + contact_phone: originalQimenConfig.contact_phone, + email: originalQimenConfig.email, + is_enabled: Number(originalQimenConfig.is_enabled || 0), + }, token, EXTRA_HEADERS); + } + } + }); + + it('should reject sign when counterparty is missing', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { + print_quantity: 0, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /counterparty_id|store_id|warehouse_id/); + }); + + it('should reject unbind when no target relation is provided', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); +}); diff --git a/test/app/controller/system.storage.receiving.test.js b/test/app/controller/system.storage.receiving.test.js index 86e49c5..cb3e94f 100644 --- a/test/app/controller/system.storage.receiving.test.js +++ b/test/app/controller/system.storage.receiving.test.js @@ -70,6 +70,52 @@ async function switchToWarehouseRole(token) { throw new Error('未找到可访问收货单的仓库角色'); } +async function getBindableStoreInfo(token) { + const res = await invokeSystemMethod('storeWarehouse.store.list', { + page: 1, + page_size: 20, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const list = Array.isArray(res.body?.data?.list) ? res.body.data.list : []; + const candidate = list.find(item => Number(item?.counterparty_id || item?.store_id || 0) > 0); + + if (!candidate) { + return null; + } + + return { + store_id: Number(candidate.counterparty_id || candidate.store_id || 0), + store_name: String(candidate.store_name || candidate.counterparty_name || ''), + }; +} + +async function getBindableSystemProducts(token) { + const res = await invokeSystemMethod('stock.warehouse.list', { + pagination: { + page: 1, + pageSize: 10, + }, + where: {}, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + + const payload = normalizeListPayload(res.body.data); + const list = Array.isArray(payload?.list) ? payload.list : []; + return list + .filter(item => Number(item?.id || 0) > 0) + .map(item => ({ + id: Number(item.id), + product_name: String(item.item_name || item.name || item.product_name || ''), + })); +} + describe('test/app/controller/system.storage.receiving.test.js', () => { it('should query receiving list', async () => { const { token } = await getAuthToken(); @@ -135,6 +181,192 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { assert.ok(detailPayload, '返回结构中缺少收货单详情 payload'); assert.ok(detailPayload.receiving, 'receiving 字段缺失'); assert.equal(Number(detailPayload.receiving.id), Number(first.id)); + assert.ok(Array.isArray(detailPayload.receiving.details), 'receiving.details 应为数组'); + + const detailWithImages = detailPayload.receiving.details.find(item => Array.isArray(item.images) && item.images.length > 0); + if (detailWithImages) { + const firstImage = detailWithImages.images[0]; + assert.equal(typeof firstImage, 'object', '明细图片应返回对象结构'); + assert.equal(typeof firstImage.url, 'string', '明细图片应返回实际链接'); + assert.ok(firstImage.url.length > 0, '明细图片链接不能为空'); + assert.ok(!Object.prototype.hasOwnProperty.call(firstImage, 'business_type'), '不应返回 FileReference 原始字段'); + } + }); + + it('should bind store to receiving and reject rebinding when owner already exists', async function() { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + const bindableStore = await getBindableStoreInfo(switched.token); + let createdId = 0; + + if (!bindableStore || bindableStore.store_id <= 0) { + this.skip(); + } + + try { + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-BIND-${Date.now().toString().slice(-6)}`, + loading_method: 'with_pallet', + remark: 'bind-store-regression', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, '创建收货单失败,无法执行货主绑定回归'); + + const bindRes = await invokeSystemMethod('storage.receiving.bindStore', { + id: createdId, + store_id: bindableStore.store_id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(bindRes.status, 200); + assert.equal(bindRes.body.flag, 'success'); + assert.equal(bindRes.body.code, 200); + assert.equal(Number(bindRes.body?.data?.store_id || 0), Number(bindableStore.store_id)); + + const repeatRes = await invokeSystemMethod('storage.receiving.bindStore', { + id: createdId, + store_id: bindableStore.store_id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(repeatRes.status, 200); + assert.equal(repeatRes.body.flag, 'success'); + assert.equal(Number(repeatRes.body.code), 400); + assert.match(String(repeatRes.body.message || ''), /已绑定|重复绑定|已有货主/); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } + }); + + it('should reject bindStore when receiving is cancelled', async function() { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + const bindableStore = await getBindableStoreInfo(switched.token); + let createdId = 0; + + if (!bindableStore || bindableStore.store_id <= 0) { + this.skip(); + } + + try { + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ICB-${Date.now().toString().slice(-6)}`, + loading_method: 'with_pallet', + remark: 'bind-store-cancelled-regression', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, '创建收货单失败,无法执行取消状态绑定回归'); + + const cancelRes = await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + assert.equal(cancelRes.status, 200); + assert.equal(cancelRes.body.flag, 'success'); + assert.ok([ 0, 200 ].includes(Number(cancelRes.body.code)), `取消收货单返回异常: ${JSON.stringify(cancelRes.body)}`); + + const bindRes = await invokeSystemMethod('storage.receiving.bindStore', { + id: createdId, + store_id: bindableStore.store_id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(bindRes.status, 200); + assert.equal(bindRes.body.flag, 'success'); + assert.equal(Number(bindRes.body.code), 400); + assert.match(String(bindRes.body.message || ''), /取消|作废|不允许绑定/); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } + }); + + it('should bind and rebind system product for a receiving detail', async function() { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + const systemProducts = await getBindableSystemProducts(switched.token); + let createdId = 0; + + if (!Array.isArray(systemProducts) || systemProducts.length === 0) { + this.skip(); + } + + try { + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `IDB-${Date.now().toString().slice(-6)}`, + loading_method: 'with_pallet', + remark: 'bind-detail-product-regression', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, '创建收货单失败,无法执行明细绑定商品回归'); + + const addDetailRes = await invokeSystemMethod('storage.receiving.addDetail', { + receiving_id: createdId, + }, switched.token, EXTRA_HEADERS); + + assert.equal(addDetailRes.status, 200); + assert.equal(addDetailRes.body.flag, 'success'); + assert.equal(Number(addDetailRes.body.code), 200); + + const detailId = Number(addDetailRes.body?.data?.data?.selectId || addDetailRes.body?.data?.selectId || 0); + assert.ok(detailId > 0, '新增收货单明细后未返回有效 detail_id'); + + const firstProduct = systemProducts[0]; + const bindRes = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: firstProduct.id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(bindRes.status, 200); + assert.equal(bindRes.body.flag, 'success'); + assert.equal(Number(bindRes.body.code), 200); + assert.equal(Number(bindRes.body?.data?.detail_id || 0), detailId); + assert.equal(Number(bindRes.body?.data?.system_product_id || 0), Number(firstProduct.id)); + assert.ok(String(bindRes.body?.data?.product_name || '').length > 0, '绑定后应回填商品名称'); + + const secondProduct = systemProducts.find(item => Number(item.id) !== Number(firstProduct.id)) || firstProduct; + const rebindRes = await invokeSystemMethod('storage.receiving.bindDetailProduct', { + detail_id: detailId, + system_product_id: secondProduct.id, + }, switched.token, EXTRA_HEADERS); + + assert.equal(rebindRes.status, 200); + assert.equal(rebindRes.body.flag, 'success'); + assert.equal(Number(rebindRes.body.code), 200); + assert.equal(Number(rebindRes.body?.data?.detail_id || 0), detailId); + assert.equal(Number(rebindRes.body?.data?.system_product_id || 0), Number(secondProduct.id)); + assert.ok(String(rebindRes.body?.data?.product_name || '').length > 0, '改绑后应返回商品名称'); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } }); it('should create and then batch cancel receiving order', async () => { @@ -177,6 +409,104 @@ describe('test/app/controller/system.storage.receiving.test.js', () => { } }); + it('should generate unique receiving numbers under concurrent create requests', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + const suffix = Date.now().toString().slice(-6); + const createdIds = []; + + try { + const requests = [ 1, 2 ].map(index => invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: `ITEST-C${index}-${suffix}`, + loading_method: 'with_pallet', + remark: `integration-concurrent-${index}`, + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS)); + + const responses = await Promise.all(requests); + responses.forEach((res, index) => { + assert.equal(res.status, 200, `第 ${index + 1} 个并发请求 HTTP 状态异常`); + assert.equal(res.body.flag, 'success', `第 ${index + 1} 个并发请求应成功: ${JSON.stringify(res.body)}`); + assert.equal(res.body.code, 200, `第 ${index + 1} 个并发请求 code 应为 200`); + }); + + const ids = responses.map(res => Number(res.body.id || res.body?.data?.id || 0)); + const receivingNumbers = responses.map(res => String(res.body.receiving_number || res.body?.data?.receiving_number || '')); + + ids.forEach(id => { + assert.ok(id > 0, '并发创建成功但未返回有效 id'); + createdIds.push(id); + }); + receivingNumbers.forEach(number => { + assert.ok(number.startsWith('R'), `收货单号格式异常: ${number}`); + }); + assert.equal(new Set(receivingNumbers).size, receivingNumbers.length, '并发创建时 receiving_number 应保持唯一'); + } finally { + if (createdIds.length > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: createdIds, + }, switched.token, EXTRA_HEADERS); + } + } + }); + + it('should include same-day records when created_at uses daterange filter', async () => { + const { token } = await getAuthToken(); + const switched = await switchToWarehouseRole(token); + let createdId = 0; + + try { + const uniquePlate = `ITEST-DATE-${Date.now().toString().slice(-6)}`; + const createRes = await invokeSystemMethod('storage.receiving.create', { + delivery_method: 'truck', + license_plate: uniquePlate, + loading_method: 'with_pallet', + remark: 'date-range-regression', + total_boxes: 0, + total_pallets: 0, + }, switched.token, EXTRA_HEADERS); + + assert.equal(createRes.status, 200); + assert.equal(createRes.body.flag, 'success'); + assert.equal(createRes.body.code, 200); + createdId = Number(createRes.body.id || createRes.body?.data?.id || 0); + assert.ok(createdId > 0, '创建收货单失败,无法执行日期范围回归'); + + const now = new Date(); + const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); + const listRes = await invokeSystemMethod('storage.receiving.getReceivingList', { + pagination: { + page: 1, + pageSize: 20, + }, + where: { + created_at: { + operator: 'between', + value: [ startOfDay, startOfDay ], + type: 'daterange', + }, + }, + }, switched.token, EXTRA_HEADERS); + + assert.equal(listRes.status, 200); + assert.equal(listRes.body.flag, 'success'); + assert.equal(listRes.body.code, 200); + + const payload = normalizeListPayload(listRes.body.data); + assert.ok(payload, '日期范围查询返回结构缺少列表 payload'); + const ids = Array.isArray(payload.list) ? payload.list.map(item => Number(item && item.id)) : []; + assert.ok(ids.includes(createdId), '同日创建的收货单应命中 created_at daterange 查询'); + } finally { + if (createdId > 0) { + await invokeSystemMethod('storage.receiving.batchCancelReceiving', { + ids: [ createdId ], + }, switched.token, EXTRA_HEADERS); + } + } + }); + it('should reject getReceivingDetail with invalid id', async () => { const { token } = await getAuthToken(); const switched = await switchToWarehouseRole(token); diff --git a/test/app/controller/system.storeWarehouse.test.js b/test/app/controller/system.storeWarehouse.test.js new file mode 100644 index 0000000..b948613 --- /dev/null +++ b/test/app/controller/system.storeWarehouse.test.js @@ -0,0 +1,122 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { + getAuthToken, + invokeSystemMethod, +} = require('../../support/system_method_client'); + +const EXTRA_HEADERS = { + platform: 'web', + project: 'all', +}; + +describe('test/app/controller/system.storeWarehouse.test.js', () => { + const METHOD_PREFIX = 'storeWarehouse.store'; + const REMOVED_SETTING_METHOD_PREFIX = 'setting.storeWarehouse.store'; + let token = ''; + + before(async () => { + const auth = await getAuthToken({ forceLogin: true }); + token = auth.token; + }); + + it('should expose standalone storeWarehouse.store.list', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.list`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.ok(Array.isArray(res.body?.data?.list), 'storeWarehouse.store.list 应返回 list'); + assert.equal(typeof res.body?.data?.total, 'number'); + }); + + it('should not expose removed setting.storeWarehouse.store.list alias', async () => { + const removedRes = await invokeSystemMethod(`${REMOVED_SETTING_METHOD_PREFIX}.list`, { + page: 1, + page_size: 10, + }, token, EXTRA_HEADERS); + + assert.equal(removedRes.status, 500); + assert.equal(removedRes.body.flag, 'failure'); + assert.equal(Number(removedRes.body.code), 500); + assert.match(String(removedRes.body.message || ''), /服务 setting\.storeWarehouse\.store 不存在/); + }); + + it('should expose standalone storeWarehouse.store.sign parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.sign`, { + print_quantity: 0, + }, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.unbind parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.unbind`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.rename parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.rename`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /remask|id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.getPolicyConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.getPolicyConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.savePolicyConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.savePolicyConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.saveQimenConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.saveQimenConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id|qimen_app_key|qimen_customer_id|qimen_warehouse_code/); + }); + + it('should expose standalone storeWarehouse.store.deleteQimenConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.deleteQimenConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); + + it('should expose standalone storeWarehouse.store.listQimenConfig parameter validation', async () => { + const res = await invokeSystemMethod(`${METHOD_PREFIX}.listQimenConfig`, {}, token, EXTRA_HEADERS); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'failure'); + assert.equal(Number(res.body.code), 400); + assert.match(String(res.body.message || ''), /id|counterparty_id|store_id|warehouse_id/); + }); +}); diff --git a/test/app/controller/system.user.getLoginWechatCode.test.js b/test/app/controller/system.user.getLoginWechatCode.test.js new file mode 100644 index 0000000..0507107 --- /dev/null +++ b/test/app/controller/system.user.getLoginWechatCode.test.js @@ -0,0 +1,17 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const { invokeSystemMethod } = require('../../support/system_method_client'); + +describe('test/app/controller/system.user.getLoginWechatCode.test.js', () => { + it('should return login code without Authorization token', async () => { + const res = await invokeSystemMethod('user.getLoginWechatCode', {}); + + assert.equal(res.status, 200); + assert.equal(res.body.flag, 'success'); + assert.equal(res.body.code, 200); + assert.match(String(res.body?.data?.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.match(String(res.body?.data?.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(res.body?.data?.status, 'pending'); + }); +}); diff --git a/test/app/controller/system.user.loginByCode.test.js b/test/app/controller/system.user.loginByCode.test.js index 928ff74..af3dad0 100644 --- a/test/app/controller/system.user.loginByCode.test.js +++ b/test/app/controller/system.user.loginByCode.test.js @@ -3,11 +3,14 @@ const assert = require('node:assert/strict'); const { invokeSystemMethod } = require('../../support/system_method_client'); -const VALID_LOGIN_CODE = process.env.SYSTEM_TEST_LOGIN_CODE - || 'eyJ1dWlkIjoiMDg2MTk4MzQtY2FhYS00OTIyLWJmNjctODc5M2U2Y2MwYzJkIn0='; +const VALID_LOGIN_CODE = String(process.env.SYSTEM_TEST_LOGIN_CODE || '').trim(); describe('test/app/controller/system.user.loginByCode.test.js', () => { - it('should login successfully when code is valid', async () => { + it('should login successfully when code is valid', async function() { + if (!VALID_LOGIN_CODE) { + this.skip(); + } + const res = await invokeSystemMethod('user.loginByCode', { code: VALID_LOGIN_CODE, }); @@ -30,23 +33,23 @@ describe('test/app/controller/system.user.loginByCode.test.js', () => { assert.match(String(res.body.message || ''), /code/); }); - it('should fail when code is not valid base64 json', async () => { + it('should fail when code does not exist', async () => { const code = `INVALID_CODE_${Date.now()}`; const res = await invokeSystemMethod('user.loginByCode', { code }); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(res.body.code, 0); - assert.match(String(res.body.message || ''), /无效的登录码格式/); + assert.match(String(res.body.message || ''), /登录码不存在|登录失败/); }); - it('should fail when decoded payload does not contain uuid', async () => { - const code = Buffer.from(JSON.stringify({ foo: 'bar' }), 'utf8').toString('base64'); + it('should fail when code format is valid but not matched', async () => { + const code = 'A1B2C3'; const res = await invokeSystemMethod('user.loginByCode', { code }); assert.equal(res.status, 200); assert.equal(res.body.flag, 'failure'); assert.equal(res.body.code, 0); - assert.match(String(res.body.message || ''), /uuid/); + assert.match(String(res.body.message || ''), /登录码不存在|登录失败/); }); }); diff --git a/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js b/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js new file mode 100644 index 0000000..620c21e --- /dev/null +++ b/test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js @@ -0,0 +1,152 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UserService = require('../../../../app/service/systems/auth/user'); + +function createServiceHarness() { + const cacheWrites = []; + const cacheStore = new Map(); + + const app = { + async setCacheAsync(cacheKey, data, expireSeconds = 300) { + cacheWrites.push({ + cacheKey, + data, + expireSeconds, + }); + + if (data === null || data === undefined || expireSeconds <= 1) { + cacheStore.delete(cacheKey); + return; + } + + cacheStore.set(cacheKey, data); + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + coreLogger: { + warn() {}, + error() {}, + }, + }; + + const ctx = { + app, + userId: 1001, + user: { + id: 1001, + }, + }; + + const service = new UserService(ctx); + + return { + app, + ctx, + service, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/service/systems/auth.user.bindWechatCacheExpiry.test.js', () => { + it('should generate pending code with fixed 60s ttl and keep same code without extending', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheWrites } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const first = await service.refreshWechatBindState(1001, null, { + forceNewCode: false, + }); + + assert.equal(first.state.status, 'pending'); + assert.match(String(first.state.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(first.state.expires_at, fixedNow + 60000); + + const firstWriteCount = cacheWrites.length; + assert.equal(firstWriteCount, 2); + for (const write of cacheWrites) { + assert.equal(write.expireSeconds, 60); + } + + const second = await service.refreshWechatBindState(1001, first.state, { + forceNewCode: false, + }); + + assert.equal(second.state.code, first.state.code); + assert.equal(second.state.status, 'pending'); + assert.equal(cacheWrites.length, firstWriteCount); + } finally { + Date.now = originalNow; + } + }); + + it('should return scanned status when scan key exists', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheStore } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const pending = await service.refreshWechatBindState(1001, null, { + forceNewCode: false, + }); + const code = pending.state.code; + + cacheStore.set(`user:wechat:bind:scan:${code}`, { + account_id: 1001, + code, + status: 'scanned', + scanned_at: new Date(fixedNow + 1000).toISOString(), + }); + + const result = await service.refreshWechatBindState(1001, pending.state, { + forceNewCode: false, + }); + + assert.equal(result.state.status, 'scanned'); + assert.equal(result.state.code, code); + assert.ok(result.state.scanned_at); + } finally { + Date.now = originalNow; + } + }); + + it('should rotate code when forceNewCode is enabled', async () => { + const fixedNow = 1760000000000; + const originalNow = Date.now; + Date.now = () => fixedNow; + + try { + const { service, cacheWrites } = createServiceHarness(); + service.findYe4sBindingByAccountId = async () => null; + + const oldState = { + account_id: 1001, + status: 'pending', + code: 'A1B2C3', + expires_at: fixedNow + 30000, + }; + + const result = await service.refreshWechatBindState(1001, oldState, { + forceNewCode: true, + }); + + assert.equal(result.state.status, 'pending'); + assert.notEqual(result.state.code, oldState.code); + assert.equal(result.state.expires_at, fixedNow + 60000); + + const oldCodeInvalidation = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1); + assert.ok(oldCodeInvalidation); + } finally { + Date.now = originalNow; + } + }); +}); diff --git a/test/app/service/systems/auth.user.loginWechatCode.test.js b/test/app/service/systems/auth.user.loginWechatCode.test.js new file mode 100644 index 0000000..7d559fd --- /dev/null +++ b/test/app/service/systems/auth.user.loginWechatCode.test.js @@ -0,0 +1,103 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const UserService = require('../../../../app/service/systems/auth/user'); + +function createServiceHarness() { + const cacheWrites = []; + const cacheStore = new Map(); + + const app = { + async setCacheAsync(cacheKey, data, expireSeconds = 300) { + cacheWrites.push({ + cacheKey, + data, + expireSeconds, + }); + + if (data === null || data === undefined || expireSeconds <= 1) { + cacheStore.delete(cacheKey); + return; + } + + cacheStore.set(cacheKey, data); + }, + async getCacheAsync(cacheKey) { + return cacheStore.has(cacheKey) ? cacheStore.get(cacheKey) : null; + }, + coreLogger: { + warn() {}, + error() {}, + }, + }; + + const ctx = { + app, + }; + + const service = new UserService(ctx); + + return { + app, + ctx, + service, + cacheWrites, + cacheStore, + }; +} + +describe('test/app/service/systems/auth.user.loginWechatCode.test.js', () => { + it('should generate client code and login code when client code is missing', async () => { + const { service, cacheWrites } = createServiceHarness(); + + const result = await service.getLoginWechatCode({}); + + assert.equal(result.success, true); + assert.equal(result.code, 200); + assert.match(String(result.data.client_code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.match(String(result.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.equal(result.data.status, 'pending'); + assert.ok(String(result.message || '').includes('客户端编码')); + + const writesWithState = cacheWrites.filter(item => item && item.data && item.data.client_code === result.data.client_code); + assert.equal(writesWithState.length, 2); + for (const write of writesWithState) { + assert.equal(write.expireSeconds, 60); + } + }); + + it('should refresh login code after long poll when client code is provided', async () => { + const { service, cacheWrites } = createServiceHarness(); + service.waitForLoginCodeRefresh = async () => {}; + + const first = await service.getLoginWechatCode({}); + const firstCode = String(first.data.code || ''); + const clientCode = String(first.data.client_code || ''); + + const second = await service.getLoginWechatCode({ + clientCode, + }); + + assert.equal(second.success, true); + assert.equal(second.code, 200); + assert.equal(String(second.data.client_code || ''), clientCode); + assert.match(String(second.data.code || ''), /^(?=.*[A-Z])(?=.*\d)[A-Z\d]{6}$/); + assert.notEqual(String(second.data.code || ''), firstCode); + assert.ok(String(second.message || '').includes('长轮询结束')); + + const invalidationWrite = cacheWrites.find(item => item && item.data === null && item.expireSeconds === 1); + assert.ok(invalidationWrite); + }); + + it('should fail when provided client code format is invalid', async () => { + const { service } = createServiceHarness(); + + const result = await service.getLoginWechatCode({ + clientCode: 'abc', + }); + + assert.equal(result.success, false); + assert.equal(result.code, 0); + assert.match(String(result.message || ''), /客户端编码/); + }); +}); diff --git a/test/app/service/systems/excel.test.js b/test/app/service/systems/excel.test.js new file mode 100644 index 0000000..b057bb3 --- /dev/null +++ b/test/app/service/systems/excel.test.js @@ -0,0 +1,257 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const XLSX = require('xlsx'); +const ExcelService = require('../../../../app/service/systems/excel'); + +function createService(overrides = {}) { + const uploads = []; + const notifyCalls = []; + const ctx = { + app: { + config: {}, + }, + logger: { + info() {}, + error() {}, + }, + service: { + systems: { + upload: { + async uploadFile(fileStream, options = {}) { + const chunks = []; + for await (const chunk of fileStream) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + + const body = Buffer.concat(chunks); + uploads.push({ + filename: fileStream.filename, + mimeType: fileStream.mimeType, + fileSize: fileStream.fileSize, + options, + body, + }); + + return { + fileName: options.key, + cosUrl: `https://cos.example.com/${options.key}`, + cdnUrl: `https://cdn.example.com/${options.key}`, + url: `https://cdn.example.com/${options.key}`, + }; + }, + async uploadSuccessNotify(data) { + notifyCalls.push(data); + return { + code: 0, + data: { + fileId: 9527, + fileKey: data.url, + fileUrl: `https://cdn.example.com/${data.url}`, + }, + }; + }, + }, + }, + }, + ...overrides, + }; + + const service = new ExcelService(ctx); + return { + service, + uploads, + notifyCalls, + ctx, + }; +} + +describe('test/app/service/systems/excel.test.js', () => { + it('should generate workbook buffer and parse rows back', async () => { + const { service } = createService(); + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: '入库单', + columns: [ + { header: '单号', key: 'order_no', width: 20 }, + { header: '货主', key: 'owner_name', width: 18 }, + { header: '箱数', key: 'total_boxes', width: 10 }, + ], + rows: [ + { + order_no: 'RK20260404001', + owner_name: '测试货主', + total_boxes: 12, + }, + ], + }, + ], + }); + + assert.ok(Buffer.isBuffer(buffer)); + assert.ok(buffer.length > 0); + + const parsed = await service.parseBuffer(buffer); + assert.deepEqual(parsed.sheetNames, [ '入库单' ]); + assert.equal(parsed.sheets[0].rows[0].单号, 'RK20260404001'); + assert.equal(parsed.sheets[0].rows[0].货主, '测试货主'); + assert.equal(parsed.sheets[0].rows[0].箱数, '12'); + }); + + it('should normalize duplicated or empty headers when parsing', async () => { + const { service } = createService(); + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: '重复表头', + rows: [ + [ '名称', '名称', '' ], + [ 'A', 'B', 'C' ], + ], + }, + ], + }); + + const parsed = await service.parseBuffer(buffer); + assert.deepEqual(parsed.sheets[0].headers, [ '名称', '名称_2', 'column_3' ]); + assert.equal(parsed.sheets[0].rows[0].名称, 'A'); + assert.equal(parsed.sheets[0].rows[0].名称_2, 'B'); + assert.equal(parsed.sheets[0].rows[0].column_3, 'C'); + }); + + it('should generate excel and upload to custom directory', async () => { + const { service, uploads, notifyCalls } = createService(); + + const result = await service.generateAndUpload({ + filename: '收货报表.xlsx', + dir: 'exports/receiving', + saveRecord: true, + businessType: 'receiving', + businessId: 1001, + expireDays: 90, + sheets: [ + { + name: '报表', + columns: [ + { header: '单号', key: 'order_no' }, + ], + rows: [ + { order_no: 'RK1001' }, + ], + }, + ], + }); + + assert.equal(uploads.length, 1); + assert.equal(uploads[0].filename, '收货报表.xlsx'); + assert.equal(uploads[0].mimeType, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); + assert.ok(uploads[0].options.key.includes('exports/receiving/')); + assert.ok(Buffer.isBuffer(uploads[0].body)); + assert.ok(uploads[0].body.length > 0); + assert.equal(notifyCalls[0].expireDays, 90); + assert.ok(String(result.fileKey || '').includes('exports/receiving/')); + assert.equal(result.fileRecord.fileId, 9527); + }); + + it('should honor skipHeader when object rows are used', async () => { + const { service } = createService(); + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: '跳过首表头', + columns: [ + { header: '分区', key: 'section', width: 12 }, + { header: '字段', key: 'field', width: 16 }, + { header: '值', key: 'value', width: 18 }, + ], + rows: [ + { section: '主表', field: '收货单号', value: 'R001' }, + { section: '明细表头', field: '字段', value: '值' }, + ], + skipHeader: true, + }, + ], + }); + + const workbook = XLSX.read(buffer, { type: 'buffer' }); + const rawRows = XLSX.utils.sheet_to_json(workbook.Sheets['跳过首表头'], { + header: 1, + defval: '', + }); + + assert.deepEqual(rawRows[0], [ '主表', '收货单号', 'R001' ]); + assert.deepEqual(rawRows[1], [ '明细表头', '字段', '值' ]); + }); + + it('should support embedded images when url is a data URL', async () => { + const { service } = createService(); + const imageDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9WnR8i8AAAAASUVORK5CYII='; + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: 'URL图片', + rows: [ [ '图片', '见右侧' ] ], + embeddedImages: [ + { + row: 1, + col: 2, + url: imageDataUrl, + width: 40, + height: 40, + }, + ], + }, + ], + }); + + assert.ok(Buffer.isBuffer(buffer)); + assert.ok(buffer.length > 0); + }); + + it('should generate workbook with embedded image previews when image config exists', async () => { + const { service } = createService(); + const imageDataUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9WnR8i8AAAAASUVORK5CYII='; + + const buffer = await service.generateBuffer({ + sheets: [ + { + name: '图片预览', + columns: [ + { header: '名称', key: 'name', width: 20 }, + { header: '链接', key: 'url', width: 30 }, + { header: '图片', key: 'preview', width: 22 }, + ], + rows: [ + { + name: '示例图片', + url: 'https://example.com/demo.png', + preview: '见右侧', + }, + ], + embeddedImages: [ + { + row: 2, + col: 3, + dataUrl: imageDataUrl, + width: 60, + height: 60, + fallbackText: '示例图片', + }, + ], + }, + ], + }); + + assert.ok(Buffer.isBuffer(buffer)); + assert.ok(buffer.length > 0); + + const parsed = await service.parseBuffer(buffer); + assert.deepEqual(parsed.sheetNames, [ '图片预览' ]); + assert.equal(parsed.sheets[0].rows[0].名称, '示例图片'); + }); +}); diff --git a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js index deb0c0e..f602ede 100644 --- a/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js +++ b/test/app/service/systems/stock_store.stockWarehouse.conditions.test.js @@ -194,7 +194,7 @@ describe('test/app/service/systems/stock_store.stockWarehouse.conditions.test.js assert.deepEqual(between, { create_at: { - [Op.between]: [ '2026-03-01', '2026-03-31' ], + [Op.between]: [ '2026-03-01 00:00:00', '2026-03-31 23:59:59' ], }, }); }); diff --git a/test/app/service/systems/storage.receiving.report.test.js b/test/app/service/systems/storage.receiving.report.test.js new file mode 100644 index 0000000..7078232 --- /dev/null +++ b/test/app/service/systems/storage.receiving.report.test.js @@ -0,0 +1,127 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const ReceivingService = require('../../../../app/service/systems/storage/receiving'); + +function createService() { + const excelCalls = []; + const ctx = { + app: { + config: {}, + Sequelize: { + Op: {}, + }, + }, + user: { + store_id: 2001, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + excel: { + async generateAndUpload(options) { + excelCalls.push(options); + return { + fileKey: options.filename, + url: `https://cdn.example.com/${options.filename}`, + }; + }, + }, + }, + }, + }; + + const service = new ReceivingService(ctx); + return { + service, + excelCalls, + }; +} + +describe('test/app/service/systems/storage.receiving.report.test.js', () => { + it('should build and upload completion excel in a single sheet with one preview column', async () => { + const { service, excelCalls } = createService(); + + const result = await service.uploadCompletionExcelReport({ + receiving: { + id: 123, + receiving_number: 'RCV202604040001', + store_name: '测试货主', + warehouse_id: 2001, + delivery_method: 'truck', + license_plate: '粤A12345', + tracking_number: 'YT123456789', + total_boxes: 3, + total_pallets: 1, + remark: '完成收货测试', + receiving_end_time: new Date('2026-04-04T12:30:00Z'), + details: [ + { + id: 501, + product_name: '测试商品A', + system_product_id: 9001, + barcode: 'SKU-001', + actual_quantity: 8, + weight: 12, + }, + ], + }, + operator: { + employees_name: '测试员', + }, + stats: { + total_details: 1, + matched_details: 1, + unmatched_details: 0, + total_quantity: 8, + }, + detailImageMap: new Map([ + [ '501', [ + { url: 'https://example.com/image-1.png' }, + { url: 'https://example.com/image-2.png' }, + ]], + ]), + receivingImages: [ + { url: 'https://example.com/main-image.png' }, + ], + }); + + assert.equal(excelCalls.length, 1); + const [ options ] = excelCalls; + assert.equal(options.filename, '收货完成_RCV202604040001.xlsx'); + assert.ok(String(options.dir || '').includes('receiving/completed')); + assert.equal(options.expireDays, 90); + assert.ok(Array.isArray(options.sheets)); + assert.equal(options.sheets.length, 1); + + const [ sheet ] = options.sheets; + assert.equal(sheet.name, '收货清单'); + assert.ok(Array.isArray(sheet.rows)); + assert.equal(sheet.skipHeader, true); + + const receivingNumberRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货单号'); + assert.ok(receivingNumberRow, '应在主表区域包含收货单号行'); + + const summaryImageRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '收货图片'); + assert.ok(summaryImageRow, '应在主表区域包含收货图片行'); + assert.match(String(summaryImageRow[1]?.text || summaryImageRow[1] || ''), /main-image/); + + const detailHeaderRow = sheet.rows.find(item => Array.isArray(item) && item[0] === '序号' && item[1] === '商品名称'); + assert.ok(detailHeaderRow, '明细表头应出现在下方明细区开始处'); + + const detailRow = sheet.rows.find(item => Array.isArray(item) && item[1] === '测试商品A'); + assert.ok(detailRow, '应在单 sheet 中包含明细行'); + assert.match(String(detailRow[11]?.text || detailRow[11] || ''), /image-1\.png/); + assert.equal(detailRow[10], ''); + + assert.ok(Array.isArray(sheet.styledRows)); + assert.ok(sheet.styledRows.some(item => item && item.style && item.style.font && item.style.font.bold), '应包含表头加粗样式'); + assert.ok(Array.isArray(sheet.embeddedImages)); + assert.equal(sheet.embeddedImages.length, 3); + assert.equal(result.url, 'https://cdn.example.com/收货完成_RCV202604040001.xlsx'); + }); +});