Compare commits

..

No commits in common. "de9c5c0ab6438d4bf3cd8fa2f22ccc18d2a0bcf2" and "26af1a7039685344b2ea591cc28e63080c1b8893" have entirely different histories.

60 changed files with 1777 additions and 8811 deletions

View File

@ -3,8 +3,8 @@
const path = require('path');
module.exports = {
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'),
"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'),
};

View File

@ -600,11 +600,7 @@ npx egg-bin test test/app/controller/system.user.info.web.test.js test/app/contr
- `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` 字段;若该字段为 `"*"` 则无需额外追加。
- 新增权限后,必须在 `wms_role_permission` 绑定 `role_id=2`。
### 15.2 外部脚本(批量补齐)
@ -630,7 +626,7 @@ npm run permission:sync:system-api
- 入口:`app/service/main.js` 的 `checkApiPermission`。
- 逻辑:当用户权限列表不包含目标 method 时,若 `app.config.debug === true`,自动:
1. 参考现有 `type=api` 权限行构建缺失权限行;
2. 更新 `wms_role(id=2).permissions`,将新权限 ID 追加到 JSON 数组;若该字段为 `"*"` 则保持不变。
2. 绑定 `wms_role_permission(role_id=2, permission_id=新权限ID)`。
- 生产建议:保持 `app.config.debug=false`,避免运行时自动写库。

391
README.md
View File

@ -1,11 +1,12 @@
# 奇门WMS(qimen-wms)
基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。
基于 Egg.js 的仓储管理系统(WMS),支持多快递平台对接、订单管理、打印、权限、配置等功能,适合中小型电商与仓储企业二次开发。基于AI协助管理项目开发,配置了AI能力脚本和完整的项目地图
## 文档导航
- 项目协作工具箱:`AI_TOOLBOX.md`
- AI项目协作工具箱:`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`
@ -23,6 +24,7 @@
├── config/ # 配置(poloapi、redis、数据库等)
├── database/ # 迁移与数据库配置
├── methods/ # 接口文档数据源(JSON)
├── native/ # 原生扩展目录(Node.js C++ addon)
├── script/ # 调试与文档生成脚本
├── logs/ # 日志
├── run/ # 运行时/元数据
@ -37,6 +39,7 @@
- `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`:每日工作留痕。
@ -54,10 +57,121 @@ npm run dev
- `npm run dev`:本地开发
- `npm start`:启动生产服务
- `npm stop`:停止生产服务
- `npm stop`:仅停止当前目录对应的 Egg 生产进程
- `npm run deploy:prod`:按 `config/deploy.config.local.cjs` 通过 SSH 发布到生产目录 `/www/wwwroot/qimen`
- `npm run deploy:init`:首次发布初始化远端目录与 `config/` 基础文件(不覆盖已有配置)
- `npm run rollback:prod`:按最近一次备份回退生产目录(可加 `-- --backup=backup-时间戳.tar.gz` 指定备份)
- `npm run deploy:precheck`:只读预检 SSH 连通、目录权限、远端 Node/npm/tar 与健康检查,不改动远端文件
- `npm run deploy:version`:查询当前线上版本号(读取远端 `.deploy/state/current-release.json`)
- `npm run deploy:version:history`:查询最近 20 次线上版本历史
- `npm run deploy:inspect`:查看远端 `.deploy/state`、`latest-backup.txt` 与备份目录清单
- `npm run deploy:smoke`:在远端机器本机对 `/`、`/api/docs`、`/internal/v1/gateway`、`/system` 做最小连通冒烟
- `npm run deploy:verify`:组合执行 `deploy:inspect` + `deploy:smoke`
- `npm run deploy:cleanup-backups -- <backup-file...>`:按文件名清理远端 `.deploy/backups` 中指定备份
- `npm run deploy:gateway-probe -- <method> [payloadJson]`:调用 `/internal/v1/gateway` 做 method 级连通探针
- `npm run version:record`:记录一次本地包版本快照(写入 `versioning/`,用于回退追溯)
- `npm run version:history`:查询最近 50 条本地版本快照记录
- `npm run guard:git`:检查当前暂存区是否包含禁止提交的本地机密/运行产物
- `npm run setup:hooks`:将仓库 pre-commit hook 固化到 `.githooks/pre-commit`
- `npm run lint`:代码风格检查
- `npm test`:单元测试
## 外部 Method 测试(Egg.js test 规范)
测试文件按“暴露出口 + method”命名,位于 `test/app/controller/`:
- `system.user.login.test.js`
- `system.user.info.test.js`
测试辅助客户端位于:
- `test/support/system_method_client.js`
默认测试账号(可通过环境变量覆盖):
- `SYSTEM_TEST_USERNAME=liufumingren`
- `SYSTEM_TEST_PASSWORD=111111`
Token 暂存机制:
- 登录 token 会写入 `test/.runtime/system_user_token.json`。
- 每次执行测试会优先读取本地 token;若 token 可用,则跳过 `user.login` 调用。
- 当 token 不存在或过期时,测试脚本会自动调用 `user.login` 并刷新缓存。
常用命令:
```bash
npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js
```
可选环境变量:
- `SYSTEM_TEST_BASE_URL`:默认 `http://127.0.0.1:6060`
- `SYSTEM_TEST_TOKEN_FILE`:默认 `test/.runtime/system_user_token.json`
## Method 输出一致性回归(新规则)
目标:
- 在模型/关联/服务改动前后,确保关键 method 输出结果一致。
强制规则:
1. 改动前先执行 baseline(生成修改前输出快照)。
2. 改动后执行 compare(对同一批 method 回放并比对)。
3. compare 结果必须 `mismatch=0` 才可交付。
测试账号(默认):
- `liufumingren / 111111`
- 可通过环境变量覆盖:
- `WMS_TEST_USER`
- `WMS_TEST_PASS`
method 来源与样本来源:
- method 配置来源:`methods/system.json`
- 样本数据来源(优先最新日志):`wms_system_log`
- 参考日志来源:`wms_api_log`、`wms_operation_log`、`wms_account_login_log`
执行脚本:
- `script/method-output-regression.cjs`
- `script/tmp-generate-method-regression-test.cjs`(根据 baseline 自动生成 Egg.js 标注测试)
临时文件目录规则:
- 所有临时产物统一输出到 `temp/`。
- `temp/` 已加入 git 忽略,不纳入提交。
执行命令:
```powershell
# 修改前:生成基线(默认抽样 8 条)
node .\script\method-output-regression.cjs baseline 8
# 修改后:执行对比
node .\script\method-output-regression.cjs compare
# 生成 Egg.js 标注测试脚本
node .\script\tmp-generate-method-regression-test.cjs
# 执行生成的回归测试
npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
```
输出文件:
- `temp/method-output/method-output-baseline.json`
- `temp/method-output/method-output-baseline.md`
- `temp/method-output/method-output-compare.json`
一致性比对说明:
- 为避免误报,脚本会标准化以下波动字段:`token`、`timestamp`、`last_login_at`、`created_at`、`updated_at`、`iat`、`exp`。
- 403 权限响应同样参与一致性对比,用于防止权限链路被意外改动。
- 后续所有接口返回数据检测,统一以生成的 Egg.js 标注测试结果为准。
## 主要依赖
- egg.js 3.x
@ -70,8 +184,6 @@ npm run dev
- `GET /`:健康检查
- `POST /qimen`:奇门接口
- `POST /system`:system 统一入口
- `POST /api/v1`:旧版 API
- `POST /api/v2`:新版 API
- `GET /template/xml/:id`:打印模板
- `GET|POST /auth/printSetting/:code`:打印台设置
@ -88,6 +200,70 @@ npm run dev
- 全局业务 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` 下对应文档:
@ -108,12 +284,163 @@ 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` 才允许交付
## 功能模块
@ -122,55 +449,41 @@ node .\script\tmp-struct-system-params.cjs
- 打印与打印台管理
- 仓库/门店管理
- 权限与角色管理
- Excel 表格生成、导入与解析
- 原生扩展算法能力(native/addons)
## Excel 服务能力
## Native 原生扩展能力
系统已提供服务类:`app/service/systems/excel.js`,可通过 `ctx.service.systems.excel` 调用。
目录:`native/addons/`
支持能力:
当前已存在的原生模块:
- 生成单 sheet / 多 sheet Excel
- 按 `columns + rows` 输出表格
- 输出 `Buffer`、写入本地文件、直接作为下载响应返回
- 解析 `.xlsx` / `.xls` 文件内容为 JSON
- 自动处理空表头、重复表头
- `subset_selector.node`(已在业务代码接入)
- 接入位置:`app/service/apiMethods/test.js`
- 已使用能力:`selectOrders(orders, n, type)`
- 业务用途:对订单及 SKU 集合进行子集筛选/组合选择(用于加速 JS 侧大批量集合计算)
常用方法:
- `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: '测试货主' },
],
},
],
});
兼容性提示:
const parsed = await ctx.service.systems.excel.parseFile('D:/tmp/demo.xlsx');
```
- Node.js 原生 addon 与运行环境强相关(系统、架构、Node ABI 版本)。
- 当出现 `ERR_DLOPEN_FAILED` / `is not a valid Win32 application` 时,通常表示 addon 与当前 Node 版本或构建目标不匹配,需要使用目标环境重新编译 addon。
## 常见问题
- 启动端口默认 6060,可在配置中调整
- 数据库/Redis 连接失败优先检查 `config/config.local.js`
- 接口路由映射可查阅 `AI_METHOD_ROUTING.md`
- native addon 加载失败(`ERR_DLOPEN_FAILED`)时,优先检查 Node 版本与 addon 构建目标是否一致
- `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`

View File

@ -20,51 +20,24 @@ function isEmptyValue(value) {
return false;
}
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;
function normalizeDate(value) {
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 formatLocalDateTime(value, isEnd);
return value.toISOString().slice(0, 19).replace('T', ' ');
}
if (typeof value === 'number') {
const date = new Date(value);
if (isNaN(date.getTime())) return value;
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 date.toISOString().slice(0, 19).replace('T', ' ');
}
return value;
@ -86,13 +59,11 @@ function processConditionValue(value, type) {
return value;
case 'date':
return normalizeDate(value, { isEnd: false });
case 'daterange':
if (Array.isArray(value)) {
return value.map((v, index) => normalizeDate(v, { isEnd: index === value.length - 1 }));
return value.map(v => normalizeDate(v));
}
return normalizeDate(value, { isEnd: false });
return normalizeDate(value);
case 'number': {
const num = parseFloat(value);

View File

@ -177,7 +177,6 @@ module.exports = app => {
freezeTableName: true,
underscored: true,
timestamps: true,
paranoid: false,
createdAt: 'created_at',
updatedAt: 'updated_at',
comment: 'API应用配置表',

View File

@ -1,27 +0,0 @@
'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;
};

View File

@ -1,204 +0,0 @@
'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;
};

View File

@ -1,48 +0,0 @@
'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;
};

View File

@ -102,12 +102,6 @@ module.exports = app => {
defaultValue: null,
comment: '更新时间',
},
expire_time: {
type: DATE,
allowNull: true,
defaultValue: null,
comment: '过期时间,为空表示永不过期',
},
is_deleted: {
type: BOOLEAN,
allowNull: false,

View File

@ -76,7 +76,6 @@ module.exports = app => {
freezeTableName: true,
underscored: true,
timestamps: true,
paranoid: false,
createdAt: 'created_at',
updatedAt: 'updated_at',
comment: '接口类型配置表',

View File

@ -1,162 +0,0 @@
'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;
};

View File

@ -1,89 +0,0 @@
'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;
};

View File

@ -1,54 +0,0 @@
'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;
};

View File

@ -135,8 +135,8 @@ module.exports = app => {
});
// 关联关系 - 自关联,构建树形结构
Permission.associate = function() {
const { Permission } = app.model;
Permission.associate = function(models) {
const { Role, Permission, RolePermission } = app.model;
// 子权限
Permission.hasMany(Permission, {
foreignKey: 'parent_id',
@ -152,6 +152,13 @@ module.exports = app => {
as: 'parent',
});
// 角色权限关联
Permission.belongsToMany(Role, {
through: RolePermission,
foreignKey: 'permission_id',
otherKey: 'role_id',
as: 'roles',
});
};
// 实例方法:获取类型对应的中文名称

View File

@ -49,11 +49,6 @@ module.exports = app => {
allowNull: true,
comment: '角色描述',
},
permissions: {
type: TEXT,
allowNull: true,
comment: '角色权限集,JSON数组;* 表示所有权限',
},
role_type: {
type: TINYINT(4),
allowNull: false,
@ -162,8 +157,8 @@ module.exports = app => {
});
// 关联关系
Role.associate = function() {
const { Account, Store, EmployeeRole } = app.model;
Role.associate = function(models) {
const { Account, Store, Permission, RolePermission, EmployeeRole } = app.model;
// 创建人
Role.belongsTo(Account, {
foreignKey: 'created_by',
@ -176,6 +171,13 @@ 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',

View File

@ -0,0 +1,78 @@
'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;
};

View File

@ -1,7 +1,7 @@
'use strict';
module.exports = app => {
const { BIGINT, STRING, DATE, TINYINT } = app.Sequelize;
const { BIGINT, STRING, DATE, TINYINT, INTEGER } = app.Sequelize;
const Store = app.model.define('store', {
id: {
@ -179,7 +179,7 @@ module.exports = app => {
// 关联关系 - 使用您推荐的方式
Store.associate = function() {
const { Account, Role, AccountStoreEmployee, ProhibitedType, NotificationWebhook } = app.model;
const { Account, Role, AccountStoreEmployee, ProhibitedType } = app.model;
// 关联创建人
Store.belongsTo(Account, {
@ -209,11 +209,6 @@ module.exports = app => {
foreignKey: 'warehouse_id',
as: 'prohibitedTypes',
});
Store.hasMany(NotificationWebhook, {
foreignKey: 'store_id',
as: 'notificationWebhooks',
});
};
// 实例方法:检查商家是否启用

View File

@ -48,9 +48,20 @@ class PrintApiService extends Service {
return [];
}
const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, {
includeDisabled: false,
const rolePermissionRows = await ctx.model.RolePermission.findAll({
attributes: [ 'permission_id' ],
where: {
role_id: {
[ctx.app.Sequelize.Op.in]: roleIds,
},
},
raw: true,
});
if (!rolePermissionRows || rolePermissionRows.length === 0) {
return [];
}
const permissionIds = [ ...new Set(rolePermissionRows.map(item => item.permission_id).filter(Boolean)) ];
if (permissionIds.length === 0) {
return [];
}

View File

@ -434,7 +434,118 @@ 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.model.RolePermission.findOrCreate({
where: {
role_id: 2,
permission_id: permission.id,
},
defaults: {
role_id: 2,
permission_id: permission.id,
},
});
// 仅在新建权限时清理当前用户缓存,避免继续使用旧权限快照。
if (created && user && user.id) {
await ctx.service.systems.auth.user.clearUserCache(user.id);
}
return {
ensured: true,
permissionId: permission.id,
};
}
async hasRole2(employeeId) {
const { ctx } = this;
if (!employeeId) {
return false;
}
const link = await ctx.model.EmployeeRole.findOne({
where: {
employee_id: employeeId,
role_id: 2,
},
attributes: [ 'id' ],
raw: true,
});
return !!link;
}
/**
* 检查用户是否有 API 访问权限(只检查 type=api)
* @param {Object} user - 用户信息
* @param {string} apiPath - API路径
* @return {Promise<boolean>} 是否有权限
@ -446,7 +557,16 @@ class MainService extends Service {
if (user.permissions && Array.isArray(user.permissions)) {
// 用户权限列表中可能包含所有权限,需要过滤出api权限
console.log('user.permissions', user.permissions);
return user.permissions.includes(apiPath);
if (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) {

View File

@ -23,6 +23,8 @@ class systemService extends Service {
// 检查服务是否存在
if (!systemMethods) {
throw new Error(`服务 ${servicePath} 不存在`);
}else{
console.log(`调用服务: ${servicePath}, 方法: ${actionName}`);
}
let serviceInstance = systemMethods;
@ -43,6 +45,7 @@ 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 {

View File

@ -54,6 +54,58 @@ 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({

View File

@ -6,9 +6,9 @@ class accountService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat';
const _noNeedRight = 'getAccountInfo,updatePassword,list,add,delete,update';
const _noNeedLog = '*';
const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update,getBindWechatCode,unbindWechat';
const _noNeedAuth = 'getAccountInfo,updatePassword,list,add,delete,update';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -85,22 +85,6 @@ 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;

View File

@ -6,15 +6,9 @@ class permissionService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
<<<<<<< HEAD
const _noNeedRight = 'list,add,delete,update';
const _noNeedLog = '*';
const _noNeedAuth = 'list,add,delete,update';
=======
const _noNeedRight = 'list';
const _noNeedLog = '*';
const _noNeedAuth = 'list';
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}

View File

@ -6,15 +6,9 @@ class roleService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
<<<<<<< HEAD
const _noNeedRight = 'list,add,delete,update,permission';
const _noNeedLog = '*';
const _noNeedAuth = 'list,add,delete,update,permission';
=======
const _noNeedRight = 'list,add,delete,update';
const _noNeedLog = '*';
const _noNeedAuth = 'list,add,delete,update';
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -39,17 +33,6 @@ class roleService extends MainService {
}
/**
<<<<<<< HEAD
* 角色权限列表(兼容旧入口)。
* @param {*} data
*/
async permission(data = {}) {
return this.callSystemRole('permission', data, '获取角色权限列表失败');
}
/**
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
* 新增角色。
* @param {*} data
*/

View File

@ -1,60 +0,0 @@
'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;

View File

@ -10,9 +10,9 @@ class configService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
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';
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';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -73,32 +73,6 @@ class configService extends MainService {
return this.success('创建失败', result);
}
/**
* 绑定收货单货主。
* @param {Object} data 请求体
* @param {number} data.id 收货单ID
* @param {number} data.store_id 货主ID
* @return {Promise<Object>} 统一成功包装响应
*/
async bindStore(data) {
const { service } = this;
const result = await service.systems.storage.receiving.bindStore(data);
return this.success('ok', result);
}
/**
* 绑定或改绑收货单明细商品。
* @param {Object} data 请求体
* @param {number} data.detail_id 收货单明细ID
* @param {number} data.system_product_id 商品ID
* @return {Promise<Object>} 统一成功包装响应
*/
async bindDetailProduct(data) {
const { service } = this;
const result = await service.systems.storage.receiving.bindDetailProduct(data);
return this.success('ok', result);
}
/**
* 添加收货商品(当前依赖底层 addItem 实现)。
* @param {Object} data 请求体

View File

@ -1,65 +0,0 @@
'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;

View File

@ -1,3 +0,0 @@
'use strict';
module.exports = require('../storeWarehouse');

View File

@ -6,10 +6,8 @@ class userService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode';
const _noNeedLogin = 'login,loginByCode,register,getLoginWechatCode';
const _noNeedRight = '*';
const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode';
const _noNeedLog = 'info,getBindWechatCode,getLoginWechatCode';
const _noNeedAuth = '*';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -27,16 +25,15 @@ 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('1111登录失败:缺少登录码 code', {
return this.fail('登录失败:缺少登录码 code', {
success: false,
data: null,
code: 0,
message: '缺少登录码 code',
});
}
const result = await service.systems.auth.user.loginByYe4sCode(code);
const result = await service.systems.auth.user.loginByCode(code);
if (result.code) {
return this.success('登录成功', result);
}
@ -58,14 +55,6 @@ 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);

View File

@ -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 ? this.ctx.service.systems.auth.rolePermission.toApiPermissionIds(role.permissions) : [],
role_permissions: role ? role.permissions : [],
store_id: employee.store_id,
store_name: store ? store.name : '',
store_code: store ? store.code : '',

View File

@ -3,352 +3,107 @@
const Service = require('egg').Service;
class RolePermissionService extends Service {
normalizePermissionSet(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 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 roleRows = await ctx.model.Role.findAll({
where: {
id: {
[Op.in]: normalizedRoleIds,
},
...(options.includeRoleDisabled === true ? {} : { status: 1 }),
},
attributes: [ 'id', 'permissions' ],
raw: true,
transaction: options.transaction,
});
if (!roleRows || roleRows.length === 0) {
return [];
}
const directPermissionIds = [];
let allAccess = false;
for (const row of roleRows) {
const state = this.normalizePermissionSet(row.permissions);
if (state.allAccess) {
allAccess = true;
break;
}
if (state.permissionIds.length > 0) {
directPermissionIds.push(...state.permissionIds);
}
}
const permissionWhere = {
status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1,
};
if (options.type) {
permissionWhere.type = options.type;
}
if (allAccess) {
const allPermissions = await ctx.model.Permission.findAll({
where: permissionWhere,
attributes: [ 'id' ],
raw: true,
transaction: options.transaction,
});
return Array.from(new Set(allPermissions
.map(item => Number(item.id))
.filter(item => Number.isFinite(item) && item > 0)));
}
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: {
...permissionWhere,
id: {
[Op.in]: permissionIds,
},
},
attributes: [ 'id' ],
raw: true,
transaction: options.transaction,
});
return Array.from(new Set(permissions
.map(item => Number(item.id))
.filter(item => Number.isFinite(item) && item > 0)));
}
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: {
[Op.in]: permissionIds,
},
status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1,
};
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,
const { ctx } = this;
if (!permissionIds || permissionIds.length === 0) {
return [];
}
const rolePermissions = permissionIds.map(permissionId => ({
role_id: roleId,
permission_id: permissionId,
}));
return await ctx.model.RolePermission.bulkCreate(rolePermissions, {
ignoreDuplicates: 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 },
return await ctx.model.RolePermission.destroy({
where: { role_id: roleId },
transaction: options.transaction,
});
}
async getRolePermissions(roleId, includePermissionDetails = false) {
const { ctx } = this;
const permissionIds = await this.getPermissionIds(roleId);
if (permissionIds.length === 0) {
return [];
const options = {
where: { role_id: roleId },
};
if (includePermissionDetails) {
options.include = [{
model: ctx.model.Permission,
as: 'permission',
where: { status: 1 },
required: false,
}];
}
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,
}));
return await ctx.model.RolePermission.findAll(options);
}
async hasPermission(roleId, permissionId) {
const permissionIds = await this.getPermissionIds(roleId, {
includeDisabled: true,
const { ctx } = this;
const rolePermission = await ctx.model.RolePermission.findOne({
where: {
role_id: roleId,
permission_id: permissionId,
},
});
return permissionIds.includes(Number(permissionId));
return !!rolePermission;
}
async assignPermissions(roleId, permissionIds, options = {}) {
const { ctx } = this;
await this.clearRolePermissions(roleId, options);
await ctx.model.Role.update({
permissions: this.serializePermissionSet(permissionIds),
updated_at: new Date(),
}, {
where: { id: roleId },
transaction: options.transaction,
});
if (permissionIds && permissionIds.length > 0) {
await this.bulkAssign(roleId, permissionIds, options);
}
return true;
}
async getPermissionTree(roleId, permissionType = null) {
const { ctx } = this;
const permissionIds = await this.getPermissionIds(roleId, {
includeDisabled: false,
type: permissionType,
});
const rolePermissions = await this.getRolePermissions(roleId, true);
const permissionIds = rolePermissions
.map(rp => rp.permission && rp.permission.id)
.filter(Boolean);
if (permissionIds.length === 0) {
return [];
}
const where = {
id: permissionIds,
status: 1,
};
if (permissionType) {
where.type = permissionType;
}
const permissions = await ctx.model.Permission.findAll({
where: {
id: permissionIds,
status: 1,
...(permissionType ? { type: permissionType } : {}),
},
where,
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
});
return ctx.model.Permission.buildPermissionTree(permissions);
}
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;
async getPermissionIds(roleId) {
const rolePermissions = await this.getRolePermissions(roleId, false);
return rolePermissions.map(rp => rp.permission_id);
}
}

View File

@ -493,18 +493,6 @@ class UserService extends Service {
}
/**
<<<<<<< HEAD
* 登录码登录:使用Ye4s登录码进行登录
* @param {string} code 登录码(WECHAT_LOGIN_CODE)
* @return {Object} 登录结果
*/
async loginByYe4sCode(code) {
const { ctx, app } = this;
try {
const rawCode = typeof code === 'string' ? code.trim() : '';
if (!rawCode) {
=======
* 登录码登录:使用本系统缓存登录码完成登录
* @param {string} code 登录码(WECHAT_LOGIN_CODE)
* @return {Object} 登录结果
@ -515,7 +503,6 @@ class UserService extends Service {
try {
const normalizedCode = this.parseWechatBindCode(code);
if (!normalizedCode) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
return {
success: false,
data: null,
@ -524,48 +511,6 @@ class UserService extends Service {
};
}
<<<<<<< HEAD
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 rows = await ye4sClient.select('ye4s_user', {
where: {
tmp_code: codeCandidates,
},
columns: [ 'id', 'tmp_code', 'wms_account_id' ],
orders: [[ 'id', 'DESC' ]],
limit: 1,
});
if (!rows || rows.length === 0) {
=======
const codeCacheKey = this.getWechatLoginCodeCacheKey(normalizedCode);
let codeState = null;
try {
@ -575,7 +520,6 @@ class UserService extends Service {
}
if (!codeState) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
return {
success: false,
data: null,
@ -584,19 +528,6 @@ class UserService extends Service {
};
}
<<<<<<< HEAD
const ye4sUserId = Number(rows[0].id);
if (!Number.isFinite(ye4sUserId) || ye4sUserId <= 0) {
return {
success: false,
data: null,
code: 0,
message: '登录码对应用户无效',
};
}
return await this.loginByYe4sUserId(ye4sUserId);
=======
const codeStateWithCode = {
...(codeState || {}),
code: normalizedCode,
@ -633,7 +564,6 @@ class UserService extends Service {
code: 0,
message: '登录码尚未授权,请扫码确认后重试',
};
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
} catch (error) {
app.coreLogger.error(`登录码登录异常: ${error.message}`);
return {
@ -1092,30 +1022,19 @@ class UserService extends Service {
* @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 normalizedAccountId = Number(accountId);
if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) {
const accountId = this.getCurrentAccountId();
if (!accountId) {
return {
success: false,
code: 0,
data: null,
message: options.missingAccountMessage || '未识别到目标账号,无法生成绑定码',
message: '未识别到登录账号,无法生成绑定码',
};
}
<<<<<<< HEAD
const cacheKey = this.getWechatBindCacheKey(normalizedAccountId);
=======
const cacheKey = this.getWechatBindCacheKey(accountId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const useLongPoll = this.shouldUseWechatBindLongPoll(data);
const waitTimeoutMs = this.getWechatLongPollTimeoutMs();
@ -1126,11 +1045,7 @@ class UserService extends Service {
app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`);
}
<<<<<<< HEAD
const refreshed = await this.refreshWechatBindState(normalizedAccountId, cachedState, {
=======
const refreshed = await this.refreshWechatBindState(accountId, cachedState, {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
forceNewCode: false,
});
@ -1143,22 +1058,14 @@ class UserService extends Service {
};
}
<<<<<<< HEAD
const waitResult = await this.waitForWechatBindEvent(normalizedAccountId, waitTimeoutMs);
=======
const waitResult = await this.waitForWechatBindEvent(accountId, waitTimeoutMs);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
try {
cachedState = await this.app.getCacheAsync(cacheKey);
} catch (cacheErr) {
app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`);
}
<<<<<<< HEAD
const nextState = await this.refreshWechatBindState(normalizedAccountId, cachedState, {
=======
const nextState = await this.refreshWechatBindState(accountId, cachedState, {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
forceNewCode: waitResult.timed_out,
});
@ -1367,6 +1274,7 @@ class UserService extends Service {
const updateRet = await ye4sClient.update('ye4s_user', {
id: ye4sUserId,
wms_account_id: accountId,
tmp_code: code,
});
const boundState = {
@ -1426,29 +1334,22 @@ 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 normalizedAccountId = Number(accountId);
if (!Number.isFinite(normalizedAccountId) || normalizedAccountId <= 0) {
const accountId = this.getCurrentAccountId();
if (!accountId) {
return {
success: false,
code: 0,
data: null,
message: options.missingAccountMessage || '未识别到目标账号,无法解绑',
message: '未识别到登录账号,无法解绑',
};
}
const ye4sClient = ctx.app.mysql.get('ye4s');
const bindRows = await ye4sClient.select('ye4s_user', {
where: {
wms_account_id: normalizedAccountId,
wms_account_id: accountId,
},
columns: [ 'id', 'tmp_code', 'wms_account_id' ],
orders: [[ 'id', 'desc' ]],
@ -1464,6 +1365,7 @@ 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,
@ -1472,13 +1374,9 @@ class UserService extends Service {
}
}
<<<<<<< HEAD
const cacheKey = this.getWechatBindCacheKey(normalizedAccountId);
=======
const cacheKey = this.getWechatBindCacheKey(accountId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
await this.setWechatBindCache(cacheKey, null, 1);
await this.publishWechatBindEvent(normalizedAccountId, {
await this.publishWechatBindEvent(accountId, {
status: 'unbound',
source: 'unbind',
});
@ -1487,7 +1385,7 @@ class UserService extends Service {
success: true,
code: 200,
data: {
account_id: normalizedAccountId,
account_id: accountId,
status: 'unbound',
matched_rows: bindRows.length,
affected_rows: affectedRows,
@ -2073,10 +1971,20 @@ class UserService extends Service {
return [];
}
// 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表)
const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, {
includeDisabled: false,
// 2. 获取角色的权限
const rolePermissions = await ctx.model.RolePermission.findAll({
where: {
role_id: {
[Op.in]: roleIds,
},
},
raw: true,
});
if (!rolePermissions || rolePermissions.length === 0) {
return [];
}
const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ];
if (permissionIds.length === 0) {
return [];
}
@ -2149,10 +2057,20 @@ class UserService extends Service {
return [];
}
// 2. 获取角色的权限(来源:wms_role.permissions;兼容空字段回退旧表)
const permissionIds = await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, {
includeDisabled: false,
// 2. 获取角色的权限
const rolePermissions = await ctx.model.RolePermission.findAll({
where: {
role_id: {
[Op.in]: roleIds,
},
},
raw: true,
});
if (!rolePermissions || rolePermissions.length === 0) {
return [];
}
const permissionIds = [ ...new Set(rolePermissions.map(item => item.permission_id).filter(Boolean)) ];
if (permissionIds.length === 0) {
return [];
}

View File

@ -1,744 +0,0 @@
'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;

View File

@ -51,14 +51,6 @@ 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');
}
@ -360,99 +352,6 @@ class SettingAccountService extends Service {
return employeeRoleMap;
}
<<<<<<< HEAD
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);
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
async formatEmployeeRow(employee, options = {}) {
let account = options.account || null;
if (!account) {
@ -565,13 +464,6 @@ class SettingAccountService extends Service {
.map(employee => Number(employee.id))
.filter(employeeId => Number.isFinite(employeeId) && employeeId > 0);
const employeeRoleMap = await this.buildEmployeeRoleGroupMap(employeeIds);
<<<<<<< HEAD
const accountIds = employees
.map(employee => Number(employee.account_id))
.filter(accountId => Number.isFinite(accountId) && accountId > 0);
const wechatBindingMap = await this.buildWechatBindingMap(accountIds);
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const list = [];
for (const employee of employees) {
@ -592,23 +484,10 @@ class SettingAccountService extends Service {
continue;
}
<<<<<<< HEAD
const wechatBinding = wechatBindingMap.get(Number(employee.account_id)) || {
is_wechat_bound: false,
ye4s_user_id: null,
};
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
list.push({
...await this.formatEmployeeRow(employee, {
account: employee.account,
}),
<<<<<<< HEAD
is_wechat_bound: wechatBinding.is_wechat_bound,
ye4s_user_id: wechatBinding.ye4s_user_id,
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
role_ids: roleGroup.role_ids,
roles: roleGroup.roles,
});
@ -879,36 +758,6 @@ class SettingAccountService extends Service {
},
};
}
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;

View File

@ -151,22 +151,12 @@ class SettingPermissionService extends Service {
return new Set(rows.map(item => Number(item.id)).filter(id => Number.isFinite(id) && id > 0));
}
<<<<<<< HEAD
async ensureParentPermissionExists(parentId) {
=======
async ensureParentPermissionInScope(parentId) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
if (!parentId) {
return;
}
await this.getPermission(parentId, false);
<<<<<<< HEAD
}
async ensurePermissionsExist(permissionIds) {
const { ctx } = this;
=======
const availableSet = await this.getAvailablePermissionIdSet({ includeDisabled: false });
if (!availableSet.has(Number(parentId))) {
@ -183,17 +173,12 @@ class SettingPermissionService extends Service {
if (availableSet.size === 0) {
throw this.createError('当前登录工号可用权限集为空,无法操作权限', 400);
}
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const targetRows = await ctx.model.Permission.findAll({
where: {
id: permissionIds,
},
<<<<<<< HEAD
attributes: [ 'id' ],
=======
attributes: [ 'id', 'parent_id' ],
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
raw: true,
});
if (targetRows.length !== permissionIds.length) {
@ -202,9 +187,6 @@ class SettingPermissionService extends Service {
throw this.createError(`权限不存在:${missing.join(',')}`, 404);
}
<<<<<<< HEAD
return targetRows;
=======
const parentMap = new Map(targetRows.map(item => [ Number(item.id), item.parent_id === null ? null : Number(item.parent_id) ]));
let pendingParentIds = Array.from(new Set(targetRows
.map(item => item.parent_id === null ? null : Number(item.parent_id))
@ -263,7 +245,6 @@ class SettingPermissionService extends Service {
if (outOfScopeIds.length > 0) {
throw this.createError(`包含超出当前登录工号可用权限集的权限ID:${outOfScopeIds.join(',')}`, 400);
}
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
normalizePermissionIds(inputPermissionIds) {
@ -359,12 +340,8 @@ class SettingPermissionService extends Service {
}
async getCurrentEmployeePermissionIds() {
<<<<<<< HEAD
const { ctx } = this;
=======
const { ctx, app } = this;
const { Op } = app.Sequelize;
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const currentEmployeeId = this.getCurrentEmployeeId();
if (!currentEmployeeId) {
return [];
@ -396,11 +373,6 @@ class SettingPermissionService extends Service {
return [];
}
<<<<<<< HEAD
return await ctx.service.systems.auth.rolePermission.getPermissionIdsForRoles(roleIds, {
includeDisabled: false,
});
=======
const rolePermissions = await ctx.model.RolePermission.findAll({
where: {
role_id: {
@ -414,7 +386,6 @@ class SettingPermissionService extends Service {
return Array.from(new Set(rolePermissions
.map(item => Number(item.permission_id))
.filter(id => Number.isFinite(id) && id > 0)));
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
async getCurrentRoleId() {
@ -451,25 +422,6 @@ class SettingPermissionService extends Service {
return roleId;
}
<<<<<<< HEAD
async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '', scopeMode = 'available' } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
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,
};
}
=======
async resolveVisiblePermissionRows({ includeDisabled = false, type = null, keyword = '' } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
@ -488,7 +440,6 @@ class SettingPermissionService extends Service {
[Op.notLike]: '%_pages',
},
};
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
if (type) {
where.type = type;
}
@ -510,16 +461,7 @@ class SettingPermissionService extends Service {
'status',
'parent_id',
'sort',
<<<<<<< HEAD
'component',
'redirect',
'meta_title',
'meta_icon',
'hidden',
'always_show',
=======
'meta_title',
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
],
order: [
[ 'sort', 'ASC' ],
@ -548,28 +490,10 @@ class SettingPermissionService extends Service {
role = await this.getRole(roleId);
}
<<<<<<< HEAD
// 权限管理页需要展示全量权限树,不能再按当前登录工号已分配权限做裁剪。
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const permissionRows = await this.resolveVisiblePermissionRows({
includeDisabled,
type,
keyword,
<<<<<<< HEAD
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)));
}
=======
});
let selectedPermissionSet = new Set();
@ -582,7 +506,6 @@ class SettingPermissionService extends Service {
});
selectedPermissionSet = new Set(rolePermissions.map(item => Number(item.permission_id)));
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
const permissions = permissionRows.map(item => ({
@ -593,18 +516,8 @@ class SettingPermissionService extends Service {
status: Number(item.status),
parent_id: item.parent_id === null ? null : Number(item.parent_id),
sort: Number(item.sort || 0),
<<<<<<< HEAD
component: item.component || '',
redirect: item.redirect || '',
meta_title: item.meta_title || '',
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,
=======
meta_title: item.meta_title || '',
selected: role ? selectedPermissionSet.has(Number(item.id)) : false,
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}));
return {
@ -639,11 +552,7 @@ class SettingPermissionService extends Service {
status: this.normalizeStatus(data.status),
};
<<<<<<< HEAD
await this.ensureParentPermissionExists(permissionData.parent_id);
=======
await this.ensureParentPermissionInScope(permissionData.parent_id);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
let created = null;
try {
@ -668,13 +577,9 @@ class SettingPermissionService extends Service {
const { ctx } = this;
const permissionIds = this.normalizeIds(data.ids, 'ids');
<<<<<<< HEAD
await this.ensurePermissionsExist(permissionIds);
=======
await this.ensurePermissionsInAvailableScope(permissionIds, {
includeDisabled: true,
});
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const permissions = await ctx.model.Permission.findAll({
where: {
@ -706,14 +611,10 @@ class SettingPermissionService extends Service {
transaction,
});
<<<<<<< HEAD
await ctx.service.systems.auth.rolePermission.removePermissionsFromAllRoles(deletedIds, {
=======
await ctx.model.RolePermission.destroy({
where: {
permission_id: deletedIds,
},
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
transaction,
});
}
@ -736,17 +637,12 @@ class SettingPermissionService extends Service {
}
async update(data = {}) {
<<<<<<< HEAD
const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id');
await this.ensurePermissionsExist([ permissionId ]);
=======
const { ctx } = this;
const permissionId = this.toPositiveNumber(data.permission_id || data.permissionId, 'permission_id');
await this.ensurePermissionsInAvailableScope([ permissionId ], {
includeDisabled: true,
});
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const permission = await this.getPermission(permissionId, true);
@ -800,11 +696,7 @@ class SettingPermissionService extends Service {
if (parentId && parentId === permissionId) {
throw this.createError('parent_id 不能等于 permission_id', 400);
}
<<<<<<< HEAD
await this.ensureParentPermissionExists(parentId);
=======
await this.ensureParentPermissionInScope(parentId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
updates.parent_id = parentId;
}
if (hasSort) {

View File

@ -145,29 +145,7 @@ class SettingRoleService extends Service {
return visited;
}
<<<<<<< HEAD
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()) {
=======
buildRoleTree(roleRows, rootRoleIds, selectedRoleIdSet) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const nodeMap = new Map();
for (const row of roleRows) {
const roleId = Number(row.id);
@ -183,10 +161,6 @@ class SettingRoleService extends Service {
store_id: row.store_id === null ? null : Number(row.store_id),
pid: Number(row.pid || 0),
selected: selectedRoleIdSet.has(roleId),
<<<<<<< HEAD
permission_ids: rolePermissionMap.get(roleId) || [],
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
children: [],
});
}
@ -249,57 +223,17 @@ class SettingRoleService extends Service {
}
normalizePermissionIds(inputPermissionIds) {
<<<<<<< HEAD
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);
}
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
if (!Array.isArray(inputPermissionIds)) {
throw this.createError('permission_ids 参数不能为空', 400);
}
<<<<<<< HEAD
if (inputPermissionIds.some(item => typeof item === 'string' && item.trim() === '*')) {
return [ '*' ];
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const permissionIds = [];
for (const permissionId of inputPermissionIds) {
const normalized = Number(permissionId);
if (!Number.isFinite(normalized) || normalized <= 0) {
<<<<<<< HEAD
throw this.createError('permission_ids 必须是正整数数组或 ["*"]', 400);
}
permissionIds.push(Math.floor(normalized));
=======
throw this.createError('permission_ids 必须是正整数数组', 400);
}
permissionIds.push(normalized);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
return Array.from(new Set(permissionIds));
@ -339,15 +273,7 @@ class SettingRoleService extends Service {
async validatePermissionSet(permissionIds) {
const { ctx } = this;
<<<<<<< HEAD
if (!Array.isArray(permissionIds) || permissionIds.length === 0) {
return;
}
if (permissionIds.includes('*')) {
=======
if (permissionIds.length === 0) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
return;
}
@ -364,14 +290,6 @@ class SettingRoleService extends Service {
const missing = permissionIds.filter(id => !found.has(id));
throw this.createError(`权限不存在或已禁用:${missing.join(',')}`, 400);
}
<<<<<<< HEAD
}
async replaceRolePermissions(roleId, permissionIds, transaction) {
return await this.ctx.service.systems.auth.rolePermission.assignPermissions(roleId, permissionIds, {
transaction,
});
=======
const visiblePermissions = await this.ctx.service.systems.setting.permission.resolveVisiblePermissionRows({
includeDisabled: false,
@ -403,7 +321,6 @@ class SettingRoleService extends Service {
await ctx.model.RolePermission.bulkCreate(rows, { transaction });
}
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
async clearRoleUsersCache(roleId) {
@ -455,11 +372,7 @@ class SettingRoleService extends Service {
// 先拉取当前主体 + 系统角色域,后续按可见规则二次收敛。
const roleWhere = {
<<<<<<< HEAD
status: includeDisabled ? { [Op.in]: [0, 1] } : 1,
=======
status: includeDisabled ? { [Op.in]: [ 0, 1 ] } : 1,
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
[Op.or]: [ { store_id: storeId }, { store_id: 0 }, { store_id: null } ],
};
@ -476,10 +389,6 @@ class SettingRoleService extends Service {
'status',
'store_id',
'pid',
<<<<<<< HEAD
'permissions',
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
],
order: [
[ 'is_system', 'DESC' ],
@ -513,27 +422,6 @@ class SettingRoleService extends Service {
};
}
<<<<<<< HEAD
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 sameLevelParentIds = new Set(currentRoleRows.map(item => Number(item.pid || 0)));
const currentRoleIdSet = new Set(currentRoleRows.map(item => Number(item.id)));
const hasSystemCurrentRole = currentRoleRows
@ -550,17 +438,12 @@ class SettingRoleService extends Service {
const descendantRoleIds = this.collectDescendantRoleIds(roleRows, currentRoleRows.map(item => Number(item.id)));
const visibleRoleIds = new Set([ ...sameLevelRoleIds, ...descendantRoleIds ]);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const visibleRoleRows = roleRows
.filter(item => visibleRoleIds.has(Number(item.id)))
.filter(item => this.isRoleVisibleInScope(item, currentRoleRows, storeId, includeSystem));
const rootRoleIds = new Set(visibleRoleRows
<<<<<<< HEAD
.filter(item => subordinateRootRoleIds.has(Number(item.id)))
=======
.filter(item => sameLevelRoleIds.has(Number(item.id)))
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
.map(item => Number(item.id)));
let selectedRoleIdSet = new Set();
@ -573,12 +456,7 @@ class SettingRoleService extends Service {
selectedRoleIdSet = new Set(employeeRoles.map(item => Number(item.role_id)));
}
<<<<<<< HEAD
const rolePermissionMap = await this.buildRolePermissionMap(visibleRoleRows);
const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet, rolePermissionMap);
=======
const roles = this.buildRoleTree(visibleRoleRows, rootRoleIds, selectedRoleIdSet);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
return {
code: 200,
@ -589,13 +467,6 @@ class SettingRoleService extends Service {
};
}
<<<<<<< HEAD
async permission(data = {}) {
return this.ctx.service.systems.setting.permission.list(data);
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
async add(data = {}) {
const { ctx } = this;
@ -691,8 +562,6 @@ class SettingRoleService extends Service {
deletedIds.push(roleId);
}
<<<<<<< HEAD
=======
if (deletedIds.length > 0) {
await ctx.model.RolePermission.destroy({
where: {
@ -702,7 +571,6 @@ class SettingRoleService extends Service {
});
}
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
await transaction.commit();
} catch (error) {
await transaction.rollback();

View File

@ -1,711 +0,0 @@
'use strict';
const crypto = require('node:crypto');
const Service = require('egg').Service;
const SIGN_TEMP_EXPIRE_SECONDS = 600;
const AUTH_STATUS_LABELS = Object.freeze({
1: '申请中',
2: '已通过',
3: '已拒绝',
4: '已解除',
5: '已过期',
});
class SettingStoreWarehouseService extends Service {
createError(message, code = 500) {
const error = new Error(message);
error.code = code;
return error;
}
getCurrentStoreId() {
const storeId = Number(this.ctx.user && this.ctx.user.store_id);
if (!Number.isFinite(storeId) || storeId <= 0) {
throw this.createError('未识别到当前主体,无法操作签约关系', 400);
}
return storeId;
}
getCurrentAccountId() {
const accountId = Number(this.ctx.user && this.ctx.user.id);
if (!Number.isFinite(accountId) || accountId <= 0) {
throw this.createError('未识别到当前登录账号', 401);
}
return accountId;
}
toPositiveNumber(value, fieldName, options = {}) {
const { allowEmpty = false } = options;
if (allowEmpty && (value === undefined || value === null || value === '')) {
return null;
}
const num = Number(value);
if (!Number.isFinite(num) || num <= 0) {
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
return num;
}
normalizePage(value, fieldName, defaultValue, maxValue) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const num = Number(value);
if (!Number.isFinite(num) || num <= 0) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return Math.min(Math.floor(num), maxValue);
}
normalizeStatusFlag(value, fieldName, defaultValue = null) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const num = Number(value);
if (num === 0 || num === 1) {
return num;
}
throw this.createError(`${fieldName} 参数不合法`, 400);
}
normalizeAuthStatus(value) {
if (value === undefined || value === null || value === '') {
return null;
}
const num = Number(value);
if ([ 1, 2, 3, 4, 5 ].includes(num)) {
return num;
}
throw this.createError('auth_status 参数不合法', 400);
}
normalizeNonNegativeInteger(value, fieldName, defaultValue = 0) {
if (value === undefined || value === null || value === '') {
return defaultValue;
}
const num = Number(value);
if (!Number.isFinite(num) || num < 0) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return Math.floor(num);
}
normalizeText(value, fieldName, maxLength = 500) {
if (value === undefined || value === null) {
return null;
}
const normalized = String(value).trim();
if (normalized.length > maxLength) {
throw this.createError(`${fieldName} 长度不能超过 ${maxLength}`, 400);
}
return normalized;
}
normalizeDate(value, fieldName, options = {}) {
const { allowNull = true } = options;
if (value === undefined || value === null || value === '') {
if (allowNull) {
return null;
}
throw this.createError(`${fieldName} 参数不能为空`, 400);
}
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime())) {
throw this.createError(`${fieldName} 参数不合法`, 400);
}
return date;
}
normalizeSignAction(value) {
if (value === undefined || value === null || value === '') {
return '';
}
const action = String(value).trim();
if ([ 'preview', 'confirm' ].includes(action)) {
return action;
}
throw this.createError('action 参数不合法', 400);
}
normalizeTempCode(value) {
const code = String(value || '').trim().toUpperCase();
if (!code) {
throw this.createError('temp_code 参数不能为空', 400);
}
return code;
}
getTempCodeCacheKey(tempCode) {
return `store_warehouse:sign:${tempCode}`;
}
createTempCode() {
return crypto.randomBytes(6).toString('hex').toUpperCase();
}
pickRemaskField(currentSubject) {
return currentSubject && currentSubject.isWarehouse ? 'store_remask' : 'warehouse_remask';
}
resolveRemaskValue(data, currentSubject) {
const raw = data.remask !== undefined
? data.remask
: (currentSubject && currentSubject.isWarehouse ? data.store_remask : data.warehouse_remask);
return this.normalizeText(raw, 'remask', 50);
}
buildCurrentRemaskPatch(data, currentSubject) {
const remask = this.resolveRemaskValue(data, currentSubject);
if (remask === null) {
return {};
}
return {
[this.pickRemaskField(currentSubject)]: remask,
};
}
requireCurrentRemaskPatch(data, currentSubject) {
const patch = this.buildCurrentRemaskPatch(data, currentSubject);
if (!Object.keys(patch).length) {
throw this.createError('remask 参数不能为空', 400);
}
return patch;
}
async saveTempSignPayload(payload) {
const now = Date.now();
const expiresAt = new Date(now + SIGN_TEMP_EXPIRE_SECONDS * 1000).toISOString();
const tempCode = this.createTempCode();
await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), {
...payload,
expires_at: expiresAt,
}, SIGN_TEMP_EXPIRE_SECONDS);
return {
tempCode,
expiresAt,
expiresIn: SIGN_TEMP_EXPIRE_SECONDS,
};
}
async getTempSignPayload(tempCode) {
const normalizedCode = this.normalizeTempCode(tempCode);
const payload = await this.app.getCacheAsync(this.getTempCodeCacheKey(normalizedCode));
if (!payload) {
throw this.createError('临时码无效或已过期', 404);
}
return {
tempCode: normalizedCode,
payload,
};
}
async clearTempSignPayload(tempCode) {
const cacheRedis = this.app.redis && this.app.redis.get ? this.app.redis.get('cache') : null;
if (cacheRedis && cacheRedis.del) {
await cacheRedis.del(this.getTempCodeCacheKey(tempCode));
return;
}
await this.app.setCacheAsync(this.getTempCodeCacheKey(tempCode), { consumed: true }, 1);
}
buildTempSignView(tempCode, payload, currentSubject) {
const participantIds = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ];
const currentSubjectId = Number(currentSubject && currentSubject.id);
const expiresAt = payload.expires_at || null;
const expiresMs = expiresAt ? new Date(expiresAt).getTime() : 0;
return {
mode: 'preview',
temp_code: tempCode,
expires_at: expiresAt,
expires_in: expiresMs ? Math.max(0, Math.ceil((expiresMs - Date.now()) / 1000)) : 0,
is_participant: participantIds.includes(currentSubjectId),
can_confirm: currentSubjectId > 0 && currentSubjectId === Number(payload.counterparty_id || 0),
initiator: {
id: Number(payload.initiator_subject_id || 0),
role: payload.initiator_role || '',
name: payload.initiator_name || '',
},
counterparty: {
id: Number(payload.counterparty_id || 0),
role: payload.counterparty_role || '',
name: payload.counterparty_name || '',
},
sign_info: {
store_id: Number(payload.store_id || 0),
warehouse_id: Number(payload.warehouse_id || 0),
auth_start: payload.auth_start || null,
auth_end: payload.auth_end || null,
print_quantity: Number(payload.print_quantity || 0),
apply_reason: payload.apply_reason || '',
remask: payload.remask || '',
},
};
}
async getCurrentSubject() {
const { ctx } = this;
const storeId = this.getCurrentStoreId();
const subject = await ctx.model.Store.findOne({
where: {
id: storeId,
},
attributes: [ 'id', 'company_name', 'project', 'status' ],
});
if (!subject) {
throw this.createError('当前主体不存在', 404);
}
return {
id: Number(subject.id),
company_name: subject.company_name || '',
project: subject.project || '',
isWarehouse: subject.project === 'warehouse',
status: Number(subject.status || 0),
};
}
async getCounterparty(counterpartyId, expectedRole) {
const { ctx } = this;
const counterparty = await ctx.model.Store.findOne({
where: {
id: counterpartyId,
},
attributes: [ 'id', 'company_name', 'project', 'status' ],
});
if (!counterparty) {
throw this.createError('签约对象不存在', 404);
}
const isWarehouse = counterparty.project === 'warehouse';
if (expectedRole === 'warehouse' && !isWarehouse) {
throw this.createError('目标对象不是仓库主体,无法签约', 400);
}
if (expectedRole === 'store' && isWarehouse) {
throw this.createError('目标对象不是货主主体,无法签约', 400);
}
return counterparty;
}
buildListWhere(data, currentSubject) {
const where = {};
if (currentSubject.isWarehouse) {
where.warehouse_id = currentSubject.id;
} else {
where.store_id = currentSubject.id;
}
const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true });
if (relationId) {
where.id = relationId;
}
const rawCounterpartyId = data.counterparty_id !== undefined
? data.counterparty_id
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, 'counterparty_id', { allowEmpty: true });
if (counterpartyId) {
if (currentSubject.isWarehouse) {
where.store_id = counterpartyId;
} else {
where.warehouse_id = counterpartyId;
}
}
const authStatus = this.normalizeAuthStatus(data.auth_status);
if (authStatus !== null) {
where.auth_status = authStatus;
}
const useStatus = this.normalizeStatusFlag(data.use_status, 'use_status', null);
if (useStatus !== null) {
where.use_status = useStatus;
}
return where;
}
getRelationIncludes() {
const { ctx } = this;
return [
{
model: ctx.model.Store,
as: 'store',
attributes: [ 'id', 'company_name', 'project', 'status' ],
required: false,
},
{
model: ctx.model.Store,
as: 'warehouse',
attributes: [ 'id', 'company_name', 'project', 'status' ],
required: false,
},
];
}
resolvePairIds(data, currentSubject) {
const fieldName = currentSubject.isWarehouse ? 'store_id / counterparty_id' : 'warehouse_id / counterparty_id';
const rawCounterpartyId = data.counterparty_id !== undefined
? data.counterparty_id
: (currentSubject.isWarehouse ? data.store_id : data.warehouse_id);
const counterpartyId = this.toPositiveNumber(rawCounterpartyId, fieldName);
if (currentSubject.isWarehouse) {
return {
storeId: counterpartyId,
warehouseId: currentSubject.id,
counterpartyId,
};
}
return {
storeId: currentSubject.id,
warehouseId: counterpartyId,
counterpartyId,
};
}
serializeRelation(relation, currentSubject) {
const item = relation && typeof relation.get === 'function'
? relation.get({ plain: true })
: (relation || {});
const authStatus = Number(item.auth_status || 0);
const currentIsWarehouse = !!(currentSubject && currentSubject.isWarehouse);
const counterparty = currentIsWarehouse ? item.store : item.warehouse;
const storeName = item.store_remask || (item.store && item.store.company_name ? item.store.company_name : '');
const warehouseName = item.warehouse_remask || (item.warehouse && item.warehouse.company_name ? item.warehouse.company_name : '');
const counterpartyName = currentIsWarehouse ? storeName : warehouseName;
let isAuthValid = false;
let remainingDays = 0;
if (authStatus === 2 && item.auth_start && item.auth_end) {
const now = Date.now();
const start = new Date(item.auth_start).getTime();
const end = new Date(item.auth_end).getTime();
if (!Number.isNaN(start) && !Number.isNaN(end) && now >= start && now <= end) {
isAuthValid = true;
remainingDays = Math.max(0, Math.ceil((end - now) / (1000 * 60 * 60 * 24)));
}
}
return {
id: Number(item.id || 0),
store_id: Number(item.store_id || 0),
store_name: storeName,
warehouse_id: Number(item.warehouse_id || 0),
warehouse_name: warehouseName,
counterparty_id: counterparty && counterparty.id ? Number(counterparty.id) : 0,
counterparty_name: counterpartyName,
current_subject_role: currentIsWarehouse ? 'warehouse' : 'store',
auth_status: authStatus,
auth_status_label: AUTH_STATUS_LABELS[authStatus] || '',
apply_reason: item.apply_reason || '',
review_comment: item.review_comment || '',
apply_time: item.apply_time || null,
review_time: item.review_time || null,
auth_start: item.auth_start || null,
auth_end: item.auth_end || null,
actual_end: item.actual_end || null,
print_quantity: Number(item.print_quantity || 0),
applied_by: item.applied_by ? Number(item.applied_by) : null,
reviewed_by: item.reviewed_by ? Number(item.reviewed_by) : null,
ended_by: item.ended_by ? Number(item.ended_by) : null,
remask: currentIsWarehouse ? (item.store_remask || '') : (item.warehouse_remask || ''),
use_status: Number(item.use_status || 0),
is_auth_valid: isAuthValid,
remaining_days: remainingDays,
};
}
async findScopedRelation(data, currentSubject, transaction) {
const { ctx } = this;
const where = currentSubject.isWarehouse
? { warehouse_id: currentSubject.id }
: { store_id: currentSubject.id };
const relationId = this.toPositiveNumber(data.id, 'id', { allowEmpty: true });
if (relationId) {
where.id = relationId;
} else {
const pair = this.resolvePairIds(data, currentSubject);
where.store_id = pair.storeId;
where.warehouse_id = pair.warehouseId;
}
const relation = await ctx.model.StoreWarehouse.findOne({
where,
include: this.getRelationIncludes(),
transaction,
});
if (!relation) {
throw this.createError('签约关系不存在或无权限操作', 404);
}
return relation;
}
async list(data = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
const currentSubject = await this.getCurrentSubject();
const page = this.normalizePage(data.page, 'page', 1, 1000000);
const pageSize = this.normalizePage(data.page_size || data.pageSize, 'page_size', 20, 200);
const offset = (page - 1) * pageSize;
const where = this.buildListWhere(data, currentSubject);
const keyword = typeof data.keyword === 'string' ? data.keyword.trim() : '';
if (keyword) {
where[Op.or] = [
{ store_remask: { [Op.like]: `%${keyword}%` } },
{ warehouse_remask: { [Op.like]: `%${keyword}%` } },
{ '$store.company_name$': { [Op.like]: `%${keyword}%` } },
{ '$warehouse.company_name$': { [Op.like]: `%${keyword}%` } },
];
}
const { rows, count } = await ctx.model.StoreWarehouse.findAndCountAll({
where,
include: this.getRelationIncludes(),
order: [[ 'updated_at', 'DESC' ], [ 'id', 'DESC' ]],
offset,
limit: pageSize,
distinct: true,
});
return {
code: 200,
data: {
list: rows.map(item => this.serializeRelation(item, currentSubject)),
total: Number(count || 0),
page,
page_size: pageSize,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
},
};
}
async sign(data = {}) {
const action = this.normalizeSignAction(data.action || data.mode);
if (data.temp_code || data.tempCode || action === 'preview') {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const { tempCode, payload } = await this.getTempSignPayload(data.temp_code || data.tempCode);
const isParticipant = [ Number(payload.initiator_subject_id || 0), Number(payload.counterparty_id || 0) ]
.includes(Number(currentSubject.id));
if (!isParticipant) {
throw this.createError('当前主体无权使用该临时码', 403);
}
if (action === 'preview' || data.preview === 1 || data.preview === '1') {
await transaction.rollback();
return {
code: 200,
data: this.buildTempSignView(tempCode, payload, currentSubject),
};
}
if (Number(currentSubject.id) !== Number(payload.counterparty_id || 0)) {
throw this.createError('需由对方主体确认后才可生效', 400);
}
const relationPatch = {
store_id: Number(payload.store_id || 0),
warehouse_id: Number(payload.warehouse_id || 0),
auth_status: 2,
apply_reason: payload.apply_reason || '',
apply_time: payload.created_at ? new Date(payload.created_at) : new Date(),
print_quantity: Number(payload.print_quantity || 0),
review_time: new Date(),
auth_start: payload.auth_start ? new Date(payload.auth_start) : new Date(),
auth_end: payload.auth_end ? new Date(payload.auth_end) : null,
actual_end: null,
applied_by: Number(payload.initiated_by || 0) || accountId,
reviewed_by: accountId,
ended_by: null,
use_status: 1,
};
if (payload.store_remask !== undefined) {
relationPatch.store_remask = payload.store_remask;
}
if (payload.warehouse_remask !== undefined) {
relationPatch.warehouse_remask = payload.warehouse_remask;
}
Object.assign(relationPatch, this.buildCurrentRemaskPatch(data, currentSubject));
let relation = await ctx.model.StoreWarehouse.findOne({
where: {
store_id: relationPatch.store_id,
warehouse_id: relationPatch.warehouse_id,
},
transaction,
});
const isCreate = !relation;
if (relation) {
await relation.update(relationPatch, { transaction });
} else {
relation = await ctx.model.StoreWarehouse.create(relationPatch, { transaction });
}
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
await this.clearTempSignPayload(tempCode);
await transaction.commit();
return {
code: 200,
data: {
mode: 'confirm',
temp_code: tempCode,
contract: this.serializeRelation(result, currentSubject),
action: isCreate ? 'create' : 'update',
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
const currentSubject = await this.getCurrentSubject();
const accountId = this.getCurrentAccountId();
const pair = this.resolvePairIds(data, currentSubject);
const counterparty = await this.getCounterparty(pair.counterpartyId, currentSubject.isWarehouse ? 'store' : 'warehouse');
const authStart = this.normalizeDate(data.auth_start, 'auth_start', { allowNull: true }) || new Date();
const authEnd = this.normalizeDate(data.auth_end, 'auth_end', { allowNull: true });
if (authEnd && authStart.getTime() > authEnd.getTime()) {
throw this.createError('auth_end 不能早于 auth_start', 400);
}
const remask = this.resolveRemaskValue(data, currentSubject);
const payload = {
initiated_by: accountId,
initiator_subject_id: currentSubject.id,
initiator_role: currentSubject.isWarehouse ? 'warehouse' : 'store',
initiator_name: currentSubject.company_name,
counterparty_id: Number(counterparty.id || 0),
counterparty_role: currentSubject.isWarehouse ? 'store' : 'warehouse',
counterparty_name: counterparty.company_name || '',
store_id: pair.storeId,
warehouse_id: pair.warehouseId,
auth_start: authStart.toISOString(),
auth_end: authEnd ? authEnd.toISOString() : null,
print_quantity: this.normalizeNonNegativeInteger(data.print_quantity, 'print_quantity', 0),
apply_reason: this.normalizeText(data.apply_reason, 'apply_reason', 2000),
remask: remask || '',
created_at: new Date().toISOString(),
...this.buildCurrentRemaskPatch(data, currentSubject),
};
const signPayload = await this.saveTempSignPayload(payload);
return {
code: 200,
data: {
mode: 'initiate',
temp_code: signPayload.tempCode,
expires_at: signPayload.expiresAt,
expires_in: signPayload.expiresIn,
can_confirm: false,
current_subject: {
store_id: currentSubject.id,
company_name: currentSubject.company_name,
role: currentSubject.isWarehouse ? 'warehouse' : 'store',
},
counterparty: {
id: Number(counterparty.id || 0),
company_name: counterparty.company_name || '',
role: currentSubject.isWarehouse ? 'store' : 'warehouse',
},
},
};
}
async rename(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
const relationPatch = this.requireCurrentRemaskPatch(data, currentSubject);
await relation.update(relationPatch, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
await transaction.commit();
return {
code: 200,
data: {
contract: this.serializeRelation(result, currentSubject),
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
async unbind(data = {}) {
const { ctx } = this;
const transaction = await ctx.model.transaction();
try {
const currentSubject = await this.getCurrentSubject();
const relation = await this.findScopedRelation(data, currentSubject, transaction);
const nextUseStatus = this.normalizeStatusFlag(data.use_status, 'use_status', 0);
await relation.update({
use_status: nextUseStatus,
}, { transaction });
const result = await ctx.model.StoreWarehouse.findByPk(relation.id, {
include: this.getRelationIncludes(),
transaction,
});
await transaction.commit();
return {
code: 200,
data: {
contract: this.serializeRelation(result, currentSubject),
},
};
} catch (error) {
await transaction.rollback();
throw error;
}
}
}
module.exports = SettingStoreWarehouseService;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -411,21 +411,6 @@ 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或使用默认仓库
@ -433,15 +418,14 @@ class UploadService extends Service {
file_url: fileUrl,
file_name: data.name,
file_size: data.size,
file_type: resolvedFileType,
mime_type: resolvedMimeType,
file_type: data.type,
mime_type: data.type,
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(),
};
@ -456,20 +440,12 @@ 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,
};
}

View File

@ -1,83 +0,0 @@
'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 },
};

View File

@ -1,25 +0,0 @@
'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');
},
};

View File

@ -1,154 +0,0 @@
'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');
}
},
};

View File

@ -1,26 +0,0 @@
'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');
},
};

View File

@ -1,24 +0,0 @@
# 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 层的散落操作。

File diff suppressed because it is too large Load Diff

898
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -20,14 +20,12 @@
"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",
"xlsx": "^0.18.5"
"spark-md5": "^3.0.2"
},
"devDependencies": {
"egg-bin": "6",

View File

@ -1,224 +0,0 @@
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);
});

View File

@ -232,20 +232,17 @@ function pathMatchesRule(filePath, rule) {
}
function listDeployableFiles(config) {
const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]);
const output = runCommand('git', [ 'ls-files', '--cached' ]);
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 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)))
));
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)));
}
function buildArchive(stamp, config) {

View File

@ -86,68 +86,6 @@ function loadAuthRequiredMethods(methodDocPath) {
return [ ...methodSet ].sort();
}
<<<<<<< HEAD
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);
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
function buildPermissionDefaults(methodPath, templateRow) {
return {
path: methodPath,
@ -181,24 +119,13 @@ async function queryExistingPermissions(conn, methodPaths) {
const placeholders = methodPaths.map(() => '?').join(',');
const [ rows ] = await conn.query(
<<<<<<< HEAD
`SELECT id, path, status FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`,
=======
`SELECT id, path FROM wms_permission WHERE type = 'api' AND path IN (${placeholders})`,
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
methodPaths
);
const result = new Map();
for (const row of rows) {
<<<<<<< HEAD
result.set(row.path, {
id: Number(row.id),
status: Number(row.status),
});
=======
result.set(row.path, row.id);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
return result;
}
@ -227,41 +154,10 @@ async function insertPermission(conn, defaults) {
return result.insertId;
}
<<<<<<< HEAD
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 ]
=======
async function bindRolePermission(conn, roleId, permissionId) {
const [ result ] = await conn.query(
'INSERT IGNORE INTO wms_role_permission (role_id, permission_id, created_at) VALUES (?, ?, NOW())',
[ roleId, permissionId ]
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
);
return result.affectedRows > 0;
}
@ -295,22 +191,10 @@ async function main() {
const existingMap = await queryExistingPermissions(conn, methodPaths);
const missingPaths = methodPaths.filter(item => !existingMap.has(item));
<<<<<<< HEAD
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)) {
=======
const created = [];
const touchedPermissionIds = [];
if (!args.dryRun && missingPaths.length > 0) {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
await conn.beginTransaction();
try {
for (const methodPath of missingPaths) {
@ -319,23 +203,6 @@ async function main() {
created.push({ methodPath, permissionId });
touchedPermissionIds.push(permissionId);
}
<<<<<<< HEAD
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);
}
=======
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
await conn.commit();
} catch (error) {
await conn.rollback();
@ -348,13 +215,8 @@ async function main() {
: await queryExistingPermissions(conn, methodPaths);
for (const methodPath of methodPaths) {
<<<<<<< HEAD
const permissionRow = latestMap.get(methodPath);
if (permissionRow && permissionRow.id) touchedPermissionIds.push(permissionRow.id);
=======
const permissionId = latestMap.get(methodPath);
if (permissionId) touchedPermissionIds.push(permissionId);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}
const uniquePermissionIds = [ ...new Set(touchedPermissionIds) ];
@ -373,18 +235,9 @@ async function main() {
totalAuthMethods: methodPaths.length,
existingPermissionCount: existingMap.size,
missingPermissionCount: missingPaths.length,
<<<<<<< HEAD
disabledPermissionCount: disabledPaths.length,
createdPermissionCount: created.length,
reactivatedPermissionCount: reactivated.length,
roleBindingCreated,
sampleMissing: missingPaths.slice(0, 20),
sampleDisabled: disabledPaths.slice(0, 20),
=======
createdPermissionCount: created.length,
roleBindingCreated,
sampleMissing: missingPaths.slice(0, 20),
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
};
console.log('[sync-system-api-permission] summary');

View File

@ -1,195 +0,0 @@
'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 参数不能为空/);
});
});

View File

@ -39,137 +39,16 @@ describe('test/app/controller/system.setting.permission.test.js', () => {
}
});
<<<<<<< HEAD
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',
=======
it('should reject out-of-scope permission update', async () => {
const updateRes = await invokeSystemMethod('setting.permission.update', {
permission_id: 999999999,
name: 'out_of_scope_update',
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
}, token, EXTRA_HEADERS);
assert.equal(updateRes.status, 200);
assert.equal(updateRes.body.flag, 'failure');
<<<<<<< HEAD
assert.equal(Number(updateRes.body.code), 404);
assert.match(String(updateRes.body.message || ''), /权限不存在/);
=======
assert.ok([ 400, 404 ].includes(Number(updateRes.body.code)), `unexpected code: ${updateRes.body.code}`);
assert.match(String(updateRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
});
it('should create then update then delete permission successfully', async () => {
@ -301,11 +180,7 @@ describe('test/app/controller/system.setting.permission.test.js', () => {
}
});
<<<<<<< HEAD
it('should reject mixed delete when ids contain non-existent permission', async () => {
=======
it('should reject mixed delete when ids contain out-of-scope permission', async () => {
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
const suffix = Date.now();
const path = `autotest.permission.mixed.outscope.${suffix}`;
let permissionId = 0;
@ -331,13 +206,8 @@ describe('test/app/controller/system.setting.permission.test.js', () => {
assert.equal(mixedRes.status, 200);
assert.equal(mixedRes.body.flag, 'failure');
<<<<<<< HEAD
assert.equal(Number(mixedRes.body.code), 404);
assert.match(String(mixedRes.body.message || ''), /权限不存在/);
=======
assert.ok([ 400, 404 ].includes(Number(mixedRes.body.code)), `unexpected code: ${mixedRes.body.code}`);
assert.match(String(mixedRes.body.message || ''), /(超出当前登录工号可用权限集|权限不存在)/);
>>>>>>> 26af1a7039685344b2ea591cc28e63080c1b8893
// 失败后应保持原子性:合法权限仍可被正常删除(说明前一次未误删)
const verifyDeleteRes = await invokeSystemMethod('setting.permission.delete', {

View File

@ -1,198 +0,0 @@
'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), '孙级角色未返回已绑定权限集');
});
});

View File

@ -1,413 +0,0 @@
'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/);
});
});

View File

@ -70,52 +70,6 @@ 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();
@ -181,192 +135,6 @@ 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 () => {
@ -409,104 +177,6 @@ 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);

View File

@ -1,122 +0,0 @@
'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/);
});
});

View File

@ -1,257 +0,0 @@
'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].名称, '示例图片');
});
});

View File

@ -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 00:00:00', '2026-03-31 23:59:59' ],
[Op.between]: [ '2026-03-01', '2026-03-31' ],
},
});
});

View File

@ -1,127 +0,0 @@
'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');
});
});