diff --git a/.eslintignore b/.eslintignore index 4ebc8ae..717444d 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1 +1,2 @@ coverage +temp diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..d428093 --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,2 @@ +#!/bin/sh +node script/git-safety-check.cjs \ No newline at end of file diff --git a/.gitignore b/.gitignore index 9eb7841..2ea54c3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ logs/ run/ -temp/ +temp/* +!temp/docs/ +!temp/docs/** node_modules/ coverage/ .nyc_output/ @@ -14,6 +16,7 @@ pnpm-debug.log* .env .env.* config/config.local.js +config/deploy.config.local.cjs database/config.json native/addons/*.node @@ -26,3 +29,6 @@ Thumbs.db *.un~ todo.txt test/.runtime/ +.deploy-state/ +versioning/* +!versioning/.gitkeep diff --git a/AI_TOOLBOX.md b/AI_TOOLBOX.md index f858e87..8f7af4f 100644 --- a/AI_TOOLBOX.md +++ b/AI_TOOLBOX.md @@ -258,16 +258,153 @@ node .\script\tmp-struct-system-params.cjs - params 的 `name/type/required/source` 完整 - 公共头部声明与实际鉴权逻辑一致 +## 10. 远程发布与回退工具 + +发布配置文件: + +- 模板:`config/deploy.config.example.cjs` +- 本地真实配置:`config/deploy.config.local.cjs` + +说明: + +- 生产目录固定为 `/www/wwwroot/qimen` +- `config/deploy.config.local.cjs` 已加入 git ignore,避免 SSH 配置误提交 +- 发布前会自动备份远端当前目录到 `/www/wwwroot/qimen/.deploy/backups/` +- 回退默认使用最近一次发布前备份 +- 发布包按 Egg.js 最小运行集自动裁剪(默认 `app.js`、`app/**`、`methods/**`、`native/addons/**`、`package*.json`) +- 发布与回退均保留远端 `config/`,不做覆盖 +- 发布与回退的停服务逻辑仅匹配当前 `deployRoot` 对应的 Egg 进程,不再用全局 `egg-scripts stop` 扫整机 + +### 10.1 固定命令入口(仅 npm script) + +执行要求: + +- 远程发布与回退只允许通过 `npm run` 执行。 +- 禁止直接运行 `node ./script/deploy-remote.cjs ...` 与 `node ./script/rollback-remote.cjs ...`。 +- `npm stop` 已改为仅停止当前目录对应的 Egg 进程,不再直接调用全局 `egg-scripts stop`。 + +标准格式: + +```powershell +# 启用仓库级 pre-commit 保护 +npm run setup:hooks + +# 只读预检(不改远端文件) +npm run deploy:precheck + +# 查询当前线上版本号 +npm run deploy:version + +# 查询最近 20 次线上版本历史 +npm run deploy:version:history + +# 查看远端 state 与备份清单 +npm run deploy:inspect + +# 对关键路由做最小连通冒烟 +npm run deploy:smoke + +# 组合执行 inspect + smoke +npm run deploy:verify + +# 按文件名清理远端失败备份 +npm run deploy:cleanup-backups -- backup-20260324202526.tar.gz backup-20260324204750.tar.gz + +# 调用 internal gateway 做 method 连通探针 +npm run deploy:gateway-probe -- releaseProbe.ping "{}" + +# 手动记录一次本地包版本快照 +npm run version:record + +# 查询本地版本历史 +npm run version:history + +# 检查暂存区是否包含禁止提交文件 +npm run guard:git + +# 发布生产环境 +npm run deploy:prod + +# 发布生产环境(短命令别名) +npm run deploy + +# 回退到最近一次备份 +npm run rollback:prod + +# 回退到最近一次备份(短命令别名) +npm run rollback + +# 指定备份包回退 +npm run rollback:prod -- --backup=backup-20260324123045.tar.gz +``` + +### 10.2 SSH 配置字段 + +- `host`:生产服务器 IP 或域名 +- `port`:SSH 端口,默认 `22` +- `username`:SSH 登录用户 +- `privateKeyPath`:本机私钥路径 +- `deployRoot`:固定为 `/www/wwwroot/qimen` +- `sharedDirs`:发布时保留目录,默认 `logs/run/temp` +- `postDeployCommands`:发布后执行命令;发布链路会强制确保包含 `npm install --production`,并自动剥离其中的通用 stop 命令,改为按当前部署目录定点停进程 + +最小发布相关可选字段: + +- `deployIncludePaths`:最小发布白名单路径(不填则使用默认最小集) +- `deployExcludePaths`:发布排除路径(默认包含 `config/**`) +- `preserveDirs`:远端覆盖时额外保留目录(默认包含 `config`) + +### 10.5 线上版本号规则与查询 + +- 版本号自动生成时机:每次执行 `npm run deploy:prod`。 +- 版本号格式:`v{package.version}-{yyyyMMddHHmmss}-{gitShortCommit}`。 +- 远端保存位置: + - 当前版本:`/www/wwwroot/qimen/.deploy/state/current-release.json` + - 历史版本:`/www/wwwroot/qimen/.deploy/state/release-history.jsonl` +- 查询命令(固定 npm script): + - 当前版本:`npm run deploy:version` + - 历史版本:`npm run deploy:version:history` + +### 10.6 本地版本管理目录(回退辅助) + +- 目录:`versioning/` +- 记录目标:每次更新的包版本号、提交号、分支、时间。 +- 自动记录:每次 `npm run deploy:prod` 成功后自动写入本地记录。 +- 手动记录:`npm run version:record` +- 本地历史查询:`npm run version:history` +- 文件: + - `versioning/package-version-current.json` + - `versioning/package-version-history.jsonl` +- git 规则:`versioning/` 的记录文件默认不提交,仅保留目录占位。 + +### 10.3 安全约束 + +- pre-commit 会阻止以下内容进入 git: + - `config/config.local.js` + - `config/deploy.config.local.cjs` + - `database/config.json` + - `temp/`、`logs/`、`run/` + - `.env*`、`.pem`、`.key` +- 真实 SSH 信息只写入本地配置文件,不写入 README、脚本或示例文件 +- 在补齐 SSH 配置前,不执行发布/回退测试 + +### 10.4 AI 安全红线(强制) + +- 明文规则:AI 禁止读取 SSH 本地配置文件 `config/deploy.config.local.cjs`。 +- AI 禁止通过任何方式展示、提取、复述该文件中的 `host`、`username`、`privateKeyPath` 等敏感内容。 +- AI 禁止把 SSH 配置写入文档、日志、日报、提交信息或任意可提交文件。 +- 如需发布/回退协助,AI 仅可提示用户“自行填写或核对该文件”,不可主动读取文件内容。 + 执行规则:接口代码与 `methods/*.json` 不一致时,以“必须补齐文档”为完成标准。 -## 10. App 能力地图(优先定位) +## 11. App 能力地图(优先定位) 能力入口文件: - `app.js` - `app/extend/application.js` -### 10.1 启动与初始化能力(app.js) +### 11.1 启动与初始化能力(app.js) - 设置应用根路径:`global.APP_ROOT`、`app.appRoot` - 启动前初始化动态工厂: @@ -278,7 +415,7 @@ node .\script\tmp-struct-system-params.cjs - `app.Message` - 全局日期格式化扩展:`Date.prototype.format('YYYY-MM-DD HH:mm:ss')` -### 10.2 Application 扩展能力(app/extend/application.js) +### 11.2 Application 扩展能力(app/extend/application.js) - 业务字典访问: - `businessDict` @@ -294,17 +431,17 @@ node .\script\tmp-struct-system-params.cjs - Message 扩展: - `Message` getter(返回 `MessageClass`) -### 10.3 AI 调试优先顺序 +### 11.3 AI 调试优先顺序 - 遇到“方法不存在/映射异常”优先检查 `app/extend/application.js` 是否包含对应能力。 - 遇到“动态分表模型不可用”优先检查 `app.js` 的工厂初始化是否执行成功。 - 遇到“缓存读写异常”优先检查 Redis client `cache` 配置及 `setCacheAsync/getCacheAsync` 调用链。 -### 10.4 AI 快速回复定义 +### 11.4 AI 快速回复定义 - 回复0时默认拒绝 - 回复1时默认接收 -## 11. Web 用户信息与切换角色测试(已验证) +## 12. Web 用户信息与切换角色测试(已验证) 目标: - 使用 `/system` 入口验证 Web 端用户信息获取与角色切换链路。 diff --git a/README.md b/README.md index 1570c76..a1c1961 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,8 @@ - AI项目协作工具箱:`AI_TOOLBOX.md` - Method 路由映射说明:`AI_METHOD_ROUTING.md` -- Model 层级清单:`modelList.md` -- Method 输出一致性回归记录:`METHOD_OUTPUT_REGRESSION_20260322.md` +- Model 层级清单:`temp/docs/modelList.md` +- Method 输出一致性回归记录:`temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md` - system 接口文档源:`methods/system.json` - qimen 接口文档源:`methods/qimen.json` - 日报:`day.log` @@ -40,7 +40,7 @@ - `README.md`:项目入口文档,提供整体说明与规范入口。 - `AI_TOOLBOX.md`:AI/开发协作操作手册,包含脚本与工作流。 - `AI_METHOD_ROUTING.md`:接口入口与 method 到代码文件的映射。 -- `modelList.md`:model 层级结构与关键说明清单。 +- `temp/docs/modelList.md`:model 层级结构与关键说明清单。 - `methods/system.json`:system 接口定义(headers、groups、params、response、errors)。 - `methods/qimen.json`:qimen 接口定义(按奇门协议组织)。 - `day.log`:每日工作留痕。 @@ -58,7 +58,22 @@ 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 -- `:按文件名清理远端 `.deploy/backups` 中指定备份 +- `npm run deploy:gateway-probe -- [payloadJson]`:调用 `/internal/v1/gateway` 做 method 级连通探针 +- `npm run version:record`:记录一次本地包版本快照(写入 `versioning/`,用于回退追溯) +- `npm run version:history`:查询最近 50 条本地版本快照记录 +- `npm run guard:git`:检查当前暂存区是否包含禁止提交的本地机密/运行产物 +- `npm run setup:hooks`:将仓库 pre-commit hook 固化到 `.githooks/pre-commit` - `npm run lint`:代码风格检查 - `npm test`:单元测试 @@ -271,6 +286,105 @@ 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 能力清单(汇总) @@ -358,7 +472,9 @@ node .\script\method-output-regression.cjs compare - 数据库/Redis 连接失败优先检查 `config/config.local.js` - 接口路由映射可查阅 `AI_METHOD_ROUTING.md` - native addon 加载失败(`ERR_DLOPEN_FAILED`)时,优先检查 Node 版本与 addon 构建目标是否一致 - +- `npm run deploy:prod` 提示 SSH 配置未完善时,先补齐 `config/deploy.config.local.cjs` 中的 `host/username/privateKeyPath` +- `npm run guard:git` 或 pre-commit 拦截提交时,说明暂存区包含本地机密文件或运行产物 +- system接口的日志在数据库wms中的表wms_system_log ## 日报维护 - 日报统一记录在 `day.log` diff --git a/app/controller/auth.js b/app/controller/auth.js index a7c51ab..8c270af 100644 --- a/app/controller/auth.js +++ b/app/controller/auth.js @@ -4,115 +4,115 @@ const Controller = require('egg').Controller; class AuthController extends Controller { - async printerSetting() { - const { ctx } = this; - const redis = this.app.redis; - if (ctx.method === 'GET') { - const code = ctx.params.code || ''; - if (!code) { - ctx.body = { error: '缺少code参数' }; - return; - } - const bindValue = await redis.get('printer').get(`bind:${code}`); - if (!bindValue) { - ctx.body = { error: '无效code或未绑定' }; - return; - } - await redis.get('printer').setex(`binding:${code}`, 300, bindValue); - await ctx.render('printer_setting.html', { - title: '打印台设置', - code, - bindValue, - }); - } else if (ctx.method === 'POST') { - const { code, printer, warehouse } = ctx.request.body; - if (!code || !printer || !warehouse) { - ctx.body = { success: false, error: '参数缺失' }; - return; - } - // 获取临时binding:code - const bindingValue = await redis.get('printer').get(`binding:${code}`); - if (!bindingValue) { - ctx.body = { success: false, error: '超时或未绑定' }; - return; - } - // 反序列化bindingValue - let bindingValueObj = bindingValue; - try { - bindingValueObj = JSON.parse(bindingValue); - } catch (e) { - bindingValueObj = bindingValue; - } - // 使用 Store model 校验仓库id - const Store = ctx.model.Store; - const warehouseInfo = await Store.findOne({ where: { id: warehouse } }); - console.log('warehouseInfo:', warehouseInfo); - if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { - ctx.body = { success: false, error: '仓库id校验失败' }; - return; - } - // 查找仓库id下是否有重名的电脑 - const PrintComputer = ctx.model.PrintComputer; - let computerId = null; - const existComputer = await PrintComputer.findOne({ where: { warehouse_id: warehouse, name: printer } }); - if (existComputer) { - if (existComputer.status === 1) { - ctx.body = { success: false, error: '该仓库下打印台名称已存在且可用' }; - return; - } else { - computerId = existComputer.id; - } - } else { - // 创建新打印电脑 - console.log('创建新打印电脑:', { warehouse_id: warehouse, name: printer, status: 0 }); - const newComputer = await PrintComputer.create({ warehouse_id: warehouse, name: printer, status: 0 }); - console.log('newComputer:', newComputer); - computerId = newComputer.id; - } - // 调用打印服务 /auth/bind,使用egg内置curl - const printServiceUrl = ctx.app.config.printService.url; - let printServiceResult = null; - try { - const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { - method: 'POST', - contentType: 'json', - data: { code, printer, warehouse, roomId: bindingValueObj.uniqueId, computerId }, - dataType: 'json', - }); - printServiceResult = res.data; - } catch (err) { - console.log('调用打印服务失败:', err); - printServiceResult = { success: false, error: '打印服务通讯失败' }; - } - console.log('printServiceResult:', printServiceResult); - // 判断打印服务返回结果 - if (printServiceResult && printServiceResult.status === 'fail') { - ctx.body = { - success: false, - msg: printServiceResult.message || '打印服务失败', - code, - printer, - warehouse, - bindingValue: bindingValueObj, - printServiceResult - }; - return; - } - console.log('printServiceResult:', printServiceResult); - ctx.body = { - success: true, - msg: '参数已接收', - code, - printer, - warehouse, - bindingValue: bindingValueObj, - computerId, - printServiceResult - }; - } else { - ctx.body = { msg: '不支持的请求方法' }; + async printerSetting() { + const { ctx } = this; + const redis = this.app.redis; + if (ctx.method === 'GET') { + const code = ctx.params.code || ''; + if (!code) { + ctx.body = { error: '缺少code参数' }; + return; + } + const bindValue = await redis.get('printer').get(`bind:${code}`); + if (!bindValue) { + ctx.body = { error: '无效code或未绑定' }; + return; + } + await redis.get('printer').setex(`binding:${code}`, 300, bindValue); + await ctx.render('printer_setting.html', { + title: '打印台设置', + code, + bindValue, + }); + } else if (ctx.method === 'POST') { + const { code, printer, warehouse } = ctx.request.body; + if (!code || !printer || !warehouse) { + ctx.body = { success: false, error: '参数缺失' }; + return; + } + // 获取临时binding:code + const bindingValue = await redis.get('printer').get(`binding:${code}`); + if (!bindingValue) { + ctx.body = { success: false, error: '超时或未绑定' }; + return; + } + // 反序列化bindingValue + let bindingValueObj = bindingValue; + try { + bindingValueObj = JSON.parse(bindingValue); + } catch (e) { + bindingValueObj = bindingValue; + } + // 使用 Store model 校验仓库id + const Store = ctx.model.Store; + const warehouseInfo = await Store.findOne({ where: { id: warehouse } }); + console.log('warehouseInfo:', warehouseInfo); + if (!warehouseInfo || warehouseInfo.project !== 'warehouse') { + ctx.body = { success: false, error: '仓库id校验失败' }; + return; + } + // 查找仓库id下是否有重名的电脑 + const PrintComputer = ctx.model.PrintComputer; + let computerId = null; + const existComputer = await PrintComputer.findOne({ where: { warehouse_id: warehouse, name: printer } }); + if (existComputer) { + if (existComputer.status === 1) { + ctx.body = { success: false, error: '该仓库下打印台名称已存在且可用' }; + return; } + computerId = existComputer.id; + + } else { + // 创建新打印电脑 + console.log('创建新打印电脑:', { warehouse_id: warehouse, name: printer, status: 0 }); + const newComputer = await PrintComputer.create({ warehouse_id: warehouse, name: printer, status: 0 }); + console.log('newComputer:', newComputer); + computerId = newComputer.id; + } + // 调用打印服务 /auth/bind,使用egg内置curl + const printServiceUrl = ctx.app.config.printService.url; + let printServiceResult = null; + try { + const res = await ctx.curl(`${printServiceUrl}/auth/bind`, { + method: 'POST', + contentType: 'json', + data: { code, printer, warehouse, roomId: bindingValueObj.uniqueId, computerId }, + dataType: 'json', + }); + printServiceResult = res.data; + } catch (err) { + console.log('调用打印服务失败:', err); + printServiceResult = { success: false, error: '打印服务通讯失败' }; + } + console.log('printServiceResult:', printServiceResult); + // 判断打印服务返回结果 + if (printServiceResult && printServiceResult.status === 'fail') { + ctx.body = { + success: false, + msg: printServiceResult.message || '打印服务失败', + code, + printer, + warehouse, + bindingValue: bindingValueObj, + printServiceResult, + }; + return; + } + console.log('printServiceResult:', printServiceResult); + ctx.body = { + success: true, + msg: '参数已接收', + code, + printer, + warehouse, + bindingValue: bindingValueObj, + computerId, + printServiceResult, + }; + } else { + ctx.body = { msg: '不支持的请求方法' }; } + } } -module.exports = AuthController; \ No newline at end of file +module.exports = AuthController; diff --git a/app/controller/docs.js b/app/controller/docs.js index c612e21..c55aa79 100644 --- a/app/controller/docs.js +++ b/app/controller/docs.js @@ -940,7 +940,9 @@ class DocsController extends Controller { const docData = JSON.parse(content); const groups = normalizeGroups(docData); - const entryPath = docData.module === 'qimen' ? '/qimen' : '/system'; + const entryPath = docData.module === 'qimen' + ? '/qimen' + : (docData.module === 'gateway' ? '/internal/v1/gateway' : '/system'); const html = renderHtmlPage({ docName, docData, diff --git a/app/lib/stop_current_egg.js b/app/lib/stop_current_egg.js new file mode 100644 index 0000000..8cd7824 --- /dev/null +++ b/app/lib/stop_current_egg.js @@ -0,0 +1,148 @@ +'use strict'; + +const { execFileSync } = require('node:child_process'); + +const isWin = process.platform === 'win32'; +const appRoot = process.cwd(); + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +function listNodeProcesses() { + if (isWin) { + try { + const output = execFileSync('wmic', [ 'Path', 'win32_process', 'Where', "Name = 'node.exe'", 'Get', 'CommandLine,ProcessId' ], { + encoding: 'utf8', + stdio: [ 'ignore', 'pipe', 'pipe' ], + }); + + return output + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean) + .map(line => { + const match = line.match(/^(.*)\s+(\d+)$/); + if (!match) { + return null; + } + return { + pid: Number(match[2]), + cmd: match[1], + }; + }) + .filter(Boolean); + } catch (error) { + if (error.code !== 'ENOENT') { + throw error; + } + + const output = execFileSync('powershell', [ + '-NoProfile', + '-Command', + "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Select-Object ProcessId, CommandLine | ConvertTo-Json -Compress", + ], { + encoding: 'utf8', + stdio: [ 'ignore', 'pipe', 'pipe' ], + }).trim(); + + if (!output) { + return []; + } + + const parsed = JSON.parse(output); + const items = Array.isArray(parsed) ? parsed : [ parsed ]; + return items + .map(item => ({ + pid: Number(item.ProcessId), + cmd: String(item.CommandLine || ''), + })) + .filter(item => item.pid && item.cmd); + } + } + + const output = execFileSync('ps', [ '-eo', 'pid=,args=' ], { + encoding: 'utf8', + stdio: [ 'ignore', 'pipe', 'pipe' ], + }); + + return output + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean) + .map(line => { + const match = line.match(/^(\d+)\s+(.*)$/); + if (!match) { + return null; + } + return { + pid: Number(match[1]), + cmd: match[2], + }; + }) + .filter(Boolean); +} + +function isMasterProcess(cmd) { + return cmd.includes('start-cluster'); +} + +function isWorkerProcess(cmd) { + return cmd.includes('egg-cluster/lib/app_worker.js') + || cmd.includes('egg-cluster/lib/agent_worker.js') + || cmd.includes('egg-cluster\\lib\\app_worker.js') + || cmd.includes('egg-cluster\\lib\\agent_worker.js'); +} + +function matchesCurrentApp(processInfo) { + if (!processInfo || !processInfo.cmd || !processInfo.pid) { + return false; + } + + if (processInfo.pid === process.pid) { + return false; + } + + return processInfo.cmd.includes(appRoot) && (isMasterProcess(processInfo.cmd) || isWorkerProcess(processInfo.cmd)); +} + +function killPids(pids, signal) { + for (const pid of pids) { + try { + process.kill(pid, signal); + } catch (error) { + if (error.code !== 'ESRCH') { + throw error; + } + } + } +} + +async function main() { + const processList = listNodeProcesses().filter(matchesCurrentApp); + const masterPids = processList.filter(item => isMasterProcess(item.cmd)).map(item => item.pid); + const workerPids = processList.filter(item => isWorkerProcess(item.cmd)).map(item => item.pid); + + if (masterPids.length > 0) { + console.log(`stopping current egg masters: ${masterPids.join(', ')}`); + killPids(masterPids, 'SIGTERM'); + await sleep(5000); + } else { + console.log('no current egg master process found'); + } + + const remainingWorkers = listNodeProcesses() + .filter(matchesCurrentApp) + .filter(item => isWorkerProcess(item.cmd)) + .map(item => item.pid); + + if (remainingWorkers.length > 0) { + console.log(`killing remaining current egg workers: ${remainingWorkers.join(', ')}`); + killPids(remainingWorkers, 'SIGKILL'); + } +} + +main().catch(error => { + console.error(error.message || error); + process.exitCode = 1; +}); \ No newline at end of file diff --git a/app/model/role.js b/app/model/role.js index f065bd1..16d2af5 100644 --- a/app/model/role.js +++ b/app/model/role.js @@ -195,75 +195,5 @@ module.exports = app => { return this.scope === 1 ? '全局' : '指定仓库'; }; - // 实例方法:为角色分配权限 - Role.prototype.assignPermissions = async function(permissionIds) { - const { ctx } = this; - - // 先清除现有权限 - await ctx.model.RolePermission.destroy({ - where: { role_id: this.id }, - }); - - // 批量添加新权限 - if (permissionIds && permissionIds.length > 0) { - const rolePermissions = permissionIds.map(permissionId => ({ - role_id: this.id, - permission_id: permissionId, - })); - - await ctx.model.RolePermission.bulkCreate(rolePermissions); - } - - return true; - }; - - // 实例方法:获取角色的所有权限(树形结构) - Role.prototype.getPermissionTree = async function(permissionType = null) { - const { ctx } = this; - - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { role_id: this.id }, - include: [{ - model: ctx.model.Permission, - as: 'permission', - where: { status: 1 }, - required: true, - }], - }); - - // 提取权限ID - const permissionIds = rolePermissions.map(rp => rp.permission.id); - - // 获取权限详情 - const where = { - id: permissionIds, - status: 1, - }; - - if (permissionType) { - where.type = permissionType; - } - - const permissions = await ctx.model.Permission.findAll({ - where, - order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], - }); - - // 构建树形结构 - return ctx.model.Permission.buildPermissionTree(permissions); - }; - - // 实例方法:获取角色的权限ID列表 - Role.prototype.getPermissionIds = async function() { - const { ctx } = this; - - const rolePermissions = await ctx.model.RolePermission.findAll({ - where: { role_id: this.id }, - attributes: [ 'permission_id' ], - }); - - return rolePermissions.map(rp => rp.permission_id); - }; - return Role; }; diff --git a/app/model/role_permission.js b/app/model/role_permission.js index 6a3e906..1bfd6aa 100644 --- a/app/model/role_permission.js +++ b/app/model/role_permission.js @@ -74,72 +74,5 @@ module.exports = app => { return this.role_id && this.permission_id; }; - // 类方法:批量创建角色权限关联 - RolePermission.bulkAssign = async function(roleId, permissionIds) { - const { ctx } = this; - - if (!permissionIds || permissionIds.length === 0) { - return []; - } - - const rolePermissions = permissionIds.map(permissionId => ({ - role_id: roleId, - permission_id: permissionId, - })); - - try { - return await ctx.model.RolePermission.bulkCreate(rolePermissions, { - ignoreDuplicates: true, // 忽略重复项 - }); - } catch (error) { - // 处理批量创建中的错误 - console.error('批量创建角色权限关联失败:', error); - throw error; - } - }; - - // 类方法:删除角色的所有权限 - RolePermission.clearRolePermissions = async function(roleId) { - const { ctx } = this; - - return await ctx.model.RolePermission.destroy({ - where: { role_id: roleId }, - }); - }; - - // 类方法:获取角色的权限列表 - RolePermission.getRolePermissions = async function(roleId, includePermissionDetails = false) { - const { ctx } = this; - - const options = { - where: { role_id: roleId }, - }; - - if (includePermissionDetails) { - options.include = [{ - model: ctx.model.Permission, - as: 'permission', - where: { status: 1 }, - required: false, - }]; - } - - return await ctx.model.RolePermission.findAll(options); - }; - - // 类方法:检查角色是否拥有某个权限 - RolePermission.hasPermission = async function(roleId, permissionId) { - const { ctx } = this; - - const rolePermission = await ctx.model.RolePermission.findOne({ - where: { - role_id: roleId, - permission_id: permissionId, - }, - }); - - return !!rolePermission; - }; - return RolePermission; }; diff --git a/app/model/store.js b/app/model/store.js index 3453d8e..a3839a2 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -246,80 +246,5 @@ module.exports = app => { return emailRegex.test(this.contact_email); }; - // 类方法:根据账号ID查找商家 - Store.findByAccountId = async function(accountId) { - return await this.findOne({ - where: { - account_id: accountId, - status: 1, - }, - }); - }; - - // 类方法:获取所有启用的商家 - Store.findAllEnabled = async function() { - return await this.findAll({ - where: { - status: 1, - }, - order: [[ 'company_name', 'ASC' ]], - }); - }; - - // 类方法:获取所有仓库类型的商家 - Store.findAllWarehouses = async function() { - return await this.findAll({ - where: { - status: 1, - project: 'warehouse', - }, - order: [[ 'company_name', 'ASC' ]], - }); - }; - - // 类方法:检查公司名称是否存在 - Store.checkCompanyNameExists = async function(companyName, excludeId = null) { - const where = { - company_name: companyName, - }; - - if (excludeId) { - where.id = { - [app.Sequelize.Op.ne]: excludeId, - }; - } - - const store = await this.findOne({ where }); - return !!store; - }; - - // 类方法:创建商家时的数据验证 - Store.validateStoreData = function(data) { - const errors = []; - - // 必填字段检查 - const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ]; - for (const field of requiredFields) { - if (!data[field]) { - errors.push(`${field} 不能为空`); - } - } - - // 公司名称长度检查 - if (data.company_name && (data.company_name.length < 1 || data.company_name.length > 200)) { - errors.push('公司名称长度应在1-200个字符之间'); - } - - // 邮箱格式检查(如果提供了邮箱) - if (data.contact_email && data.contact_email.trim() !== '') { - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(data.contact_email)) { - errors.push('联系邮箱格式不正确'); - } - } - - return errors; - }; - return Store; }; diff --git a/app/router.js b/app/router.js index b048e27..2fab394 100644 --- a/app/router.js +++ b/app/router.js @@ -5,6 +5,9 @@ module.exports = app => { const { router, controller } = app; router.get('/', controller.home.index); + // 内部网关接口 + router.post('/internal/v1/gateway', controller.gateway.internal); + // 奇门接口 router.post('/qimen', controller.home.qimen); diff --git a/app/service/apiMethods/user.js b/app/service/apiMethods/user.js new file mode 100644 index 0000000..fabcc1c --- /dev/null +++ b/app/service/apiMethods/user.js @@ -0,0 +1,11 @@ +'use strict'; + +const Service = require('egg').Service; + +class UserApiService extends Service { + async getUserByTempCode(data) { + return await this.ctx.service.systems.auth.user.getUserByTempCode(data); + } +} + +module.exports = UserApiService; \ No newline at end of file diff --git a/app/service/system.js b/app/service/system.js index 5a4c0ea..02fd9eb 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -4,7 +4,8 @@ const Service = require('egg').Service; const { XMLParser } = require('fast-xml-parser'); const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other' ]); -const ALLOWED_PROJECTS = new Set([ 'all', 'wms', 'tms', 'scm', 'other' ]); +// project: all=全部, warehouse=仓库, store=货主, tms=物流 +const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 'scm', 'other' ]); class systemService extends Service { async callMethod(className, actionName, requestData, authHeader) { diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index f7d7f3e..8b32985 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -1,6 +1,5 @@ 'use strict'; -const { up } = require('../../../database/migrations/20251109160640-init-wms_account'); // 打印相关 Service const MainService = require('../main'); @@ -9,59 +8,59 @@ const MainService = require('../main'); * 参考 indexService 初始化方式,后续可扩展具体业务函数 */ class PrintService extends MainService { - constructor(ctx) { - super(ctx); - // 初始化免登录、免权限、免日志、免认证等配置 - const _noNeedLogin = ''; - const _noNeedRight = '*'; - const _noNeedLog = ''; - const _noNeedAuth = '*'; - this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); - this.defaultComponents = [ - { name: '抖音', port: '13888' }, - { name: '拼多多', port: '5000' }, - { name: '快手', port: '16888/ks/printer' }, - { name: '京东', port: '9113' }, - { name: '菜鸟', port: '13528' }, - { name: '视频号', port: '12705' }, - { name: '小红书', port: '10818' }, - { name: 'LODOP', port: '8000' } - ]; + constructor(ctx) { + super(ctx); + // 初始化免登录、免权限、免日志、免认证等配置 + const _noNeedLogin = ''; + const _noNeedRight = '*'; + const _noNeedLog = ''; + const _noNeedAuth = '*'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + this.defaultComponents = [ + { name: '抖音', port: '13888' }, + { name: '拼多多', port: '5000' }, + { name: '快手', port: '16888/ks/printer' }, + { name: '京东', port: '9113' }, + { name: '菜鸟', port: '13528' }, + { name: '视频号', port: '12705' }, + { name: '小红书', port: '10818' }, + { name: 'LODOP', port: '8000' }, + ]; - } - async send(_data) { - const { ctx } = this; - const warehouseId = ctx.user.store_id; - const { printer, type, template, data, computerId, timestamp, count } = _data; - console.log('send to computer', warehouseId, printer, type, template, data, computerId, timestamp, count); - //生成打印编号并记录到数据库 - const printRecord = await ctx.model.PrintRecord.create({ - warehouse_id: warehouseId, - computer_id: computerId, - printer, - type, - data: { template, data }, - status: 'pending' - }); - //处理后的数据 - let processedData = {}; - switch (type) { - case "customize": - const { page_width, page_height, template_content } = template; - let htm = ``; - for (const item of template_content) { - let content = item.content; + } + async send(_data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { printer, type, template, data, computerId, timestamp, count } = _data; + console.log('send to computer', warehouseId, printer, type, template, data, computerId, timestamp, count); + // 生成打印编号并记录到数据库 + const printRecord = await ctx.model.PrintRecord.create({ + warehouse_id: warehouseId, + computer_id: computerId, + printer, + type, + data: { template, data }, + status: 'pending', + }); + // 处理后的数据 + let processedData = {}; + switch (type) { + case 'customize': { + const { page_width, page_height, template_content } = template; + let htm = ``; + for (const item of template_content) { + let content = item.content; - for(const key in data) { - console.log("正在匹配字段:", key, "与", item.field_code); - if(item.field_code == key) { - content = data[key]; - } - } - console.log("转后的内容:", content); - switch (item.type) { - case "text": - htm += `
${content}
`; - break; - case "image": - htm += ``; - break; - case "barcode": - htm += `
`; - break; - case "qrcode": - let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`; - //转换成urlencode - toUrl = encodeURIComponent(toUrl); - let url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`; + ">`; + break; + case 'qrcode': { + let toUrl = `https://ye4s.wms.gztbyc.com/to/${content}`; + // 转换成urlencode + toUrl = encodeURIComponent(toUrl); + const url = `https://ye4s.wms.gztbyc.com/qrcode/build?text=${toUrl}`; - htm += `
`; - break; - case "line": - htm += `
`; - break; - case "rectangle": - htm += `
`; - break; - case "table": - let tableHtml = ``; - for (let i = 0; i < item.rows; i++) { - tableHtml += ``; - for (let j = 0; j < item.columns; j++) { - let content = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; - tableHtml += ``; - } tableHtml += ``; - } tableHtml += `
${content}
`; - htm += tableHtml; - break; - } - } - htm += ``; - processedData = { - pageWidth: page_width, - pageHeight: page_height, - htm: htm, - lodopkey:["","13528A153BAEE3A0254B9507DCDE2839","EDE92F75B6A3D917F65910","D60BC84D7CF2DE18156A6F88987304CB6D8"] - } - break; - case "express": - break; + break; + case 'table': { + let tableHtml = ``; + for (let i = 0; i < item.rows; i++) { + tableHtml += ''; + for (let j = 0; j < item.columns; j++) { + const content = item.content[i] && item.content[i][j] ? item.content[i][j] : ''; + tableHtml += ``; + } tableHtml += ''; + } tableHtml += '
${content}
'; + htm += tableHtml; + break; + } default: - return this.fail('不支持的打印类型', 1001); + break; + } } - - const printData = { - printer, - type, - template, - data: processedData, - timestamp, - count, - printId: printRecord.id + htm += ''; + processedData = { + pageWidth: page_width, + pageHeight: page_height, + htm, + lodopkey: [ '', '13528A153BAEE3A0254B9507DCDE2839', 'EDE92F75B6A3D917F65910', 'D60BC84D7CF2DE18156A6F88987304CB6D8' ], }; - const res = await this.service.systems.print.index.sendToComputer({warehouse:warehouseId, computerId: computerId, data:printData}); - console.log('sendToComputer response', res); - //发送成功后更新打印记录状态 - if (res.status=="success") { - await printRecord.update({ status: 'sent' }); - return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); - } else { - await printRecord.update({ status: 'failed', error_message: res.error }); - return this.fail(res.error, { code: 504, printId: printRecord.id }); - } + break; + } + case 'express': + break; + default: + return this.fail('不支持的打印类型', 1001); } - async getPrintResult(data) { - const { ctx } = this; - const warehouseId = ctx.user.store_id; - const { printId } = data; - if (!printId) return this.fail('参数错误', 1001); - const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true }); - if (!record) return this.fail('打印记录不存在', 1002); - return this.success('success', { ...record, code: 0 }); + + const printData = { + printer, + type, + template, + data: processedData, + timestamp, + count, + printId: printRecord.id, + }; + const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData }); + console.log('sendToComputer response', res); + // 发送成功后更新打印记录状态 + if (res.status === 'success') { + await printRecord.update({ status: 'sent' }); + return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); } - async getPrintRecordItem(data) { - const { ctx } = this; - const warehouseId = ctx.user.store_id; - const { id } = data; - if (!id) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true }); - if (!item) return this.fail('打印记录不存在', 1002); - return this.success('success', { ...item, code: 0 }); - } - /** + await printRecord.update({ status: 'failed', error_message: res.error }); + return this.fail(res.error, { code: 504, printId: printRecord.id }); + + } + async getPrintResult(data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { printId } = data; + if (!printId) return this.fail('参数错误', 1001); + const record = await ctx.model.PrintRecord.findOne({ where: { id: printId, warehouse_id: warehouseId }, raw: true }); + if (!record) return this.fail('打印记录不存在', 1002); + return this.success('success', { ...record, code: 0 }); + } + async getPrintRecordItem(data) { + const { ctx } = this; + const warehouseId = ctx.user.store_id; + const { id } = data; + if (!id) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintRecord.findOne({ where: { id, warehouse_id: warehouseId }, raw: true }); + if (!item) return this.fail('打印记录不存在', 1002); + return this.success('success', { ...item, code: 0 }); + } + /** * 1. 查询打印台列表 * @param {Object} data { page, pageSize, where } */ - async getList(data) { - const { ctx } = this; - console.log("ctx.user in PrintService constructor", ctx.user); - const warehouse_id = ctx.user.store_id; - // TODO: 需根据实际分页和条件查询调整 - const { page = 1, pageSize = 20, where = {} } = data; - // 字段过滤 - const filter = {}; - ['id', 'name', 'computer_id', 'custom_barcode'].forEach(key => { - if (where[key]) filter[key] = where[key]; - }); - filter.warehouse_id = warehouse_id; - filter.deleted = 0; - // 查询总数 - console.log("ctx.model.PrintStations", ctx.model.PrintStations); - const total = await ctx.model.PrintStations.count({ where: filter }); - // 查询分页数据 - const list = await ctx.model.PrintStations.findAll({ - where: filter, - offset: (page - 1) * pageSize, - limit: pageSize, - order: [['create_at', 'DESC']], - raw: true, - }); - let computers = list.map(item => { - const computer = { - id: item.computer_id, - is_online: 0, - components: this.defaultComponents.map(component => ({ - name: component.name, - is_online: 0, - })) - }; - return computer; - }); - // 动态属性处理(如 is_online、components) - for (let i = 0; i < computers.length; i++) { - let key = `warehouse:${warehouse_id}:printer:${computers[i].id}`; - const computerInfo = await this.app.redis.get("printer").get(key); - console.log("key and computerInfo", key, computerInfo); - if (computerInfo) { - computers[i].is_online = 1; - computers[i].components = await Promise.all(computers[i].components.map(async component => { - const componentKey = `printer:${computers[i].id}:name:${component.name}:status`; - const componentInfo = await this.app.redis.get("printer").get(componentKey); - console.log("componentKey and componentInfo", componentKey, componentInfo); - if (componentInfo && componentInfo == "connected") { - component.is_online = 1; - } - return component; - })); - } - } - - for (const item of list) { - const computer = computers.find(c => c.id === item.computer_id); - item.is_online = computer ? computer.is_online : 0; - item.components = computer ? computer.components : this.defaultComponents.map(component => ({ - name: component.name, - is_online: 0, - })); - } - const result = { - code: 200, - data: { - list: list, - pagination: { - hasNext: page * pageSize < total, - hasPrevious: page > 1, - page: page, - pageSize: pageSize, - total: total, - totalPages: Math.ceil(total / pageSize), - }, - queryInfo: { - conditions: where, - hasBarcodeSearch: false, - sortField: 'id', - sortOrder: "DESC" - }, - summary: { - total_available: total, - total_items: pageSize, - total_locked: 0, - total_quantity: 0 - } - } - } - return this.success('success', result); + async getList(data) { + const { ctx } = this; + console.log('ctx.user in PrintService constructor', ctx.user); + const warehouse_id = ctx.user.store_id; + // TODO: 需根据实际分页和条件查询调整 + const { page = 1, pageSize = 20, where = {} } = data; + // 字段过滤 + const filter = {}; + [ 'id', 'name', 'computer_id', 'custom_barcode' ].forEach(key => { + if (where[key]) filter[key] = where[key]; + }); + filter.warehouse_id = warehouse_id; + filter.deleted = 0; + // 查询总数 + console.log('ctx.model.PrintStations', ctx.model.PrintStations); + const total = await ctx.model.PrintStations.count({ where: filter }); + // 查询分页数据 + const list = await ctx.model.PrintStations.findAll({ + where: filter, + offset: (page - 1) * pageSize, + limit: pageSize, + order: [[ 'create_at', 'DESC' ]], + raw: true, + }); + const computers = list.map(item => { + const computer = { + id: item.computer_id, + is_online: 0, + components: this.defaultComponents.map(component => ({ + name: component.name, + is_online: 0, + })), + }; + return computer; + }); + // 动态属性处理(如 is_online、components) + for (let i = 0; i < computers.length; i++) { + const key = `warehouse:${warehouse_id}:printer:${computers[i].id}`; + const computerInfo = await this.app.redis.get('printer').get(key); + console.log('key and computerInfo', key, computerInfo); + if (computerInfo) { + computers[i].is_online = 1; + computers[i].components = await Promise.all(computers[i].components.map(async component => { + const componentKey = `printer:${computers[i].id}:name:${component.name}:status`; + const componentInfo = await this.app.redis.get('printer').get(componentKey); + console.log('componentKey and componentInfo', componentKey, componentInfo); + if (componentInfo && componentInfo === 'connected') { + component.is_online = 1; + } + return component; + })); + } } - /** + for (const item of list) { + const computer = computers.find(c => c.id === item.computer_id); + item.is_online = computer ? computer.is_online : 0; + item.components = computer ? computer.components : this.defaultComponents.map(component => ({ + name: component.name, + is_online: 0, + })); + } + const result = { + code: 200, + data: { + list, + pagination: { + hasNext: page * pageSize < total, + hasPrevious: page > 1, + page, + pageSize, + total, + totalPages: Math.ceil(total / pageSize), + }, + queryInfo: { + conditions: where, + hasBarcodeSearch: false, + sortField: 'id', + sortOrder: 'DESC', + }, + summary: { + total_available: total, + total_items: pageSize, + total_locked: 0, + total_quantity: 0, + }, + }, + }; + return this.success('success', result); + } + + /** * 2. 获取单个打印台 * @param {Object} data { id } */ - async getItem(data) { - const { ctx } = this; - const { id } = data; - if (!id) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true }); - if (!item) return this.fail('打印台不存在', 1002); - return this.success('success', { ...item, code: 0 }); - } - /** + async getItem(data) { + const { ctx } = this; + const { id } = data; + if (!id) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true }); + if (!item) return this.fail('打印台不存在', 1002); + return this.success('success', { ...item, code: 0 }); + } + /** * 3. 添加打印台 * @param {Object} data { id, name, computer_id, custom_barcode } */ - async add(data) { - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - const { name, computer_id, custom_barcode } = data; - if (!name || !computer_id) return this.fail('参数错误', 1001); - const newItem = await ctx.model.PrintStations.create({ - warehouse_id, - name, - computer_id, - custom_barcode, - creator_id: ctx.user?.employees_id || '', - creator_name: ctx.user?.employees_name || '', - default_printer_name: data.default_printer_name || '', - create_at: new Date(), - update_at: new Date(), - deleted: 0, - }); - return this.success('添加打印台成功', { data: newItem, code: 0 }); - } - async hasName(data) { - const { ctx } = this; - const warehouse_id = ctx.user.store_id; - const { name, id } = data; - if (!name) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true }); - return this.success('success', { exists: !!item, code: 0 }); - } - /** + async add(data) { + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + const { name, computer_id, custom_barcode } = data; + if (!name || !computer_id) return this.fail('参数错误', 1001); + const newItem = await ctx.model.PrintStations.create({ + warehouse_id, + name, + computer_id, + custom_barcode, + creator_id: ctx.user?.employees_id || '', + creator_name: ctx.user?.employees_name || '', + default_printer_name: data.default_printer_name || '', + create_at: new Date(), + update_at: new Date(), + deleted: 0, + }); + return this.success('添加打印台成功', { data: newItem, code: 0 }); + } + async hasName(data) { + const { ctx } = this; + const warehouse_id = ctx.user.store_id; + const { name, id } = data; + if (!name) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintStations.findOne({ where: { name, warehouse_id, id: { [ctx.model.Sequelize.Op.ne]: id } }, raw: true }); + return this.success('success', { exists: !!item, code: 0 }); + } + /** * 3. 修改打印台 * @param {Object} data { id, name, computer_id, custom_barcode } */ - async updateItem(data) { - const { ctx } = this; - const { id, name, computer_id, custom_barcode } = data; - if (!id) return this.fail('参数错误', 1001); - const item = await ctx.model.PrintStations.findOne({ where: { id } }); - if (!item) return this.fail('打印台不存在', 1002); - // 只更新允许字段 - if (name !== undefined) item.name = name; - if (computer_id !== undefined) item.computer_id = computer_id; - if (custom_barcode !== undefined) item.custom_barcode = custom_barcode; - await item.save(); - return this.success('success', { data: null, code: 0 }); - } + async updateItem(data) { + const { ctx } = this; + const { id, name, computer_id, custom_barcode } = data; + if (!id) return this.fail('参数错误', 1001); + const item = await ctx.model.PrintStations.findOne({ where: { id } }); + if (!item) return this.fail('打印台不存在', 1002); + // 只更新允许字段 + if (name !== undefined) item.name = name; + if (computer_id !== undefined) item.computer_id = computer_id; + if (custom_barcode !== undefined) item.custom_barcode = custom_barcode; + await item.save(); + return this.success('success', { data: null, code: 0 }); + } - /** + /** * 4. 删除打印台 * @param {Object} data { ids } */ - async del(data) { - const { ctx } = this; - const { ids } = data; - if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001); - // 软删除 - const result = await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } }); - // TODO: 检查 result 是否成功 - return this.success('success', { data: null, code: 0 }); - } + async del(data) { + const { ctx } = this; + const { ids } = data; + if (!Array.isArray(ids) || ids.length === 0) return this.fail('参数错误', 1001); + // 软删除 + await ctx.model.PrintStations.update({ deleted: 1 }, { where: { id: ids } }); + // TODO: 检查 result 是否成功 + return this.success('success', { data: null, code: 0 }); + } - /** + /** * 5. 获取打印电脑列表 - * @param {Object} data {} */ - async getComputer() { - const { ctx } = this; - // TODO: 打印电脑状态需根据实际业务实现 - const warehouseId = ctx.user.store_id; - const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } }); + async getComputer() { + const { ctx } = this; + // TODO: 打印电脑状态需根据实际业务实现 + const warehouseId = ctx.user.store_id; + const list = await ctx.model.PrintComputer.findAll({ raw: true, where: { status: 1, warehouse_id: warehouseId } }); - return this.success('success', { data: list, code: 0 }); - } + return this.success('success', { data: list, code: 0 }); + } - /** + /** * 7. 获取打印电脑的所有打印机 * @param {Object} data { id } */ - async getComputerPrinter(data) { - const { ctx } = this; - const { id } = data; - if (!id) return this.fail('参数错误', 1001); - const printerListResult = await this.app.redis.get("printer").get(`printer:${id}:printerList`); - console.log("getComputerPrinter printerListResult", printerListResult); - const printerList = JSON.parse(printerListResult); - let printers = []; - if(!printerList ||!printerList.data || printerList.data.length === 0){ - printers = []; - } else { - printers = printerList.data; - } - return this.success('success', { data: printers, code: 0 }); + async getComputerPrinter(data) { + const { id } = data; + if (!id) return this.fail('参数错误', 1001); + const printerListResult = await this.app.redis.get('printer').get(`printer:${id}:printerList`); + console.log('getComputerPrinter printerListResult', printerListResult); + const printerList = JSON.parse(printerListResult); + let printers = []; + if (!printerList || !printerList.data || printerList.data.length === 0) { + printers = []; + } else { + printers = printerList.data; } + return this.success('success', { data: printers, code: 0 }); + } - /** + /** * 8. 保存打印台的快递-打印机绑定 - * @param {Object} data { default, express } + * @param {Object} data { defaultPrinter, express, print_station_id } */ - async savePrinters(data) { - const { ctx } = this; - const { defaultPrinter, express } = data; - // express: [{ express_id, name }] - if (!defaultPrinter || !Array.isArray(express)) return this.fail('参数错误', 1001); - // TODO: 需根据打印台ID、快递ID等实际业务调整 - // 这里只做示例保存,实际应覆盖原有绑定 - // 1. 保存默认打印机 - // 2. 保存 express 打印机绑定 - // 3. 需用 PrintStationExpress model - // 示例:批量保存 - for (const item of express) { - await ctx.model.PrintStationExpress.upsert({ - print_station_id: data.print_station_id, // 需传入 - express_id: item.express_id, - express_name: item.name, - printer_name: item.name, - is_default: item.name === defaultPrinter ? 1 : 0, - creator_id: ctx.user?.id || '', - creator_name: ctx.user?.name || '', - create_at: new Date(), - update_at: new Date(), - deleted: 0, - }); - } - return this.success('success', { data: null, code: 0 }); + async savePrinters(data) { + const { ctx } = this; + const { defaultPrinter, express } = data; + // express: [{ express_id, name }] + if (!defaultPrinter || !Array.isArray(express)) return this.fail('参数错误', 1001); + // TODO: 需根据打印台ID、快递ID等实际业务调整 + // 这里只做示例保存,实际应覆盖原有绑定 + // 1. 保存默认打印机 + // 2. 保存 express 打印机绑定 + // 3. 需用 PrintStationExpress model + // 示例:批量保存 + for (const item of express) { + await ctx.model.PrintStationExpress.upsert({ + print_station_id: data.print_station_id, // 需传入 + express_id: item.express_id, + express_name: item.name, + printer_name: item.name, + is_default: item.name === defaultPrinter ? 1 : 0, + creator_id: ctx.user?.id || '', + creator_name: ctx.user?.name || '', + create_at: new Date(), + update_at: new Date(), + deleted: 0, + }); } + return this.success('success', { data: null, code: 0 }); + } } module.exports = PrintService; diff --git a/app/service/systemMethods/user.js b/app/service/systemMethods/user.js index 79d4d76..efa3bc2 100644 --- a/app/service/systemMethods/user.js +++ b/app/service/systemMethods/user.js @@ -7,7 +7,7 @@ class userService extends MainService { super(ctx); const _noNeedLogin = 'login,loginByCode,register'; const _noNeedRight = '*'; - const _noNeedLog = 'info'; + const _noNeedLog = 'info,getBindWechatCode'; const _noNeedAuth = '*'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -61,6 +61,22 @@ class userService extends MainService { } return this.fail('登录失败:' + result.message, result); } + async getBindWechatCode(data) { + const { service } = this; + const result = await service.systems.auth.user.getBindWechatCode(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); + if (result.code) { + return this.success('解绑成功', result); + } + return this.fail('解绑失败:' + result.message, result); + } async logout() { return this.success('登出成功'); } diff --git a/app/service/systems/auth/role_permission.js b/app/service/systems/auth/role_permission.js new file mode 100644 index 0000000..f8880a3 --- /dev/null +++ b/app/service/systems/auth/role_permission.js @@ -0,0 +1,110 @@ +'use strict'; + +const Service = require('egg').Service; + +class RolePermissionService extends Service { + async bulkAssign(roleId, permissionIds, options = {}) { + 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, + }); + } + + async clearRolePermissions(roleId, options = {}) { + const { ctx } = this; + + return await ctx.model.RolePermission.destroy({ + where: { role_id: roleId }, + transaction: options.transaction, + }); + } + + async getRolePermissions(roleId, includePermissionDetails = false) { + const { ctx } = this; + + const options = { + where: { role_id: roleId }, + }; + + if (includePermissionDetails) { + options.include = [{ + model: ctx.model.Permission, + as: 'permission', + where: { status: 1 }, + required: false, + }]; + } + + return await ctx.model.RolePermission.findAll(options); + } + + async hasPermission(roleId, permissionId) { + const { ctx } = this; + + const rolePermission = await ctx.model.RolePermission.findOne({ + where: { + role_id: roleId, + permission_id: permissionId, + }, + }); + + return !!rolePermission; + } + + async assignPermissions(roleId, permissionIds, options = {}) { + await this.clearRolePermissions(roleId, options); + + if (permissionIds && permissionIds.length > 0) { + await this.bulkAssign(roleId, permissionIds, options); + } + + return true; + } + + async getPermissionTree(roleId, permissionType = null) { + const { ctx } = this; + + const rolePermissions = await this.getRolePermissions(roleId, true); + const permissionIds = rolePermissions + .map(rp => rp.permission && rp.permission.id) + .filter(Boolean); + + if (permissionIds.length === 0) { + return []; + } + + const where = { + id: permissionIds, + status: 1, + }; + + if (permissionType) { + where.type = permissionType; + } + + const permissions = await ctx.model.Permission.findAll({ + where, + order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], + }); + + return ctx.model.Permission.buildPermissionTree(permissions); + } + + async getPermissionIds(roleId) { + const rolePermissions = await this.getRolePermissions(roleId, false); + return rolePermissions.map(rp => rp.permission_id); + } +} + +module.exports = RolePermissionService; diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 3bc99ee..6cf4756 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -1,12 +1,104 @@ 'use strict'; const Service = require('egg').Service; +const crypto = require('node:crypto'); + +const WECHAT_BIND_CACHE_PREFIX = 'user:wechat:bind:'; +const WECHAT_BIND_CODE_CACHE_PREFIX = 'user:wechat:bind:code:'; +const WECHAT_BIND_CACHE_TTL_SECONDS = 600; +const WECHAT_BIND_RECHECK_INTERVAL_MS = 5000; class UserService extends Service { constructor(ctx) { super(ctx); } + getCurrentAccountId() { + const { ctx } = this; + const rawUserId = ctx.userId || (ctx.user && ctx.user.id); + const accountId = Number(rawUserId); + if (!Number.isFinite(accountId) || accountId <= 0) { + return null; + } + return accountId; + } + + getWechatBindCacheKey(accountId) { + return `${WECHAT_BIND_CACHE_PREFIX}${accountId}`; + } + + getWechatBindCodeCacheKey(code) { + return `${WECHAT_BIND_CODE_CACHE_PREFIX}${code}`; + } + + createWechatBindCode() { + const payload = { + uuid: `${Date.now().toString(36)}-${crypto.randomBytes(8).toString('hex')}`, + }; + return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64'); + } + + parseWechatBindCode(code) { + if (!code) { + return null; + } + + try { + const decodedStr = Buffer.from(code, 'base64').toString('utf8'); + const parsed = JSON.parse(decodedStr); + if (!parsed || typeof parsed !== 'object' || !parsed.uuid) { + return null; + } + return parsed; + } catch (error) { + return null; + } + } + + formatBindWechatData(state, source = 'db') { + const nextCheckAt = Number(state.next_db_check_at || 0); + return { + account_id: state.account_id, + code: state.code || '', + status: state.status || 'pending', + is_bound: state.status === 'bound', + updated_at: state.updated_at || new Date().toISOString(), + next_db_check_at: nextCheckAt, + next_poll_after_ms: Math.max(0, nextCheckAt - Date.now()), + source, + ye4s_user_id: state.ye4s_user_id || null, + }; + } + + async setWechatBindCache(cacheKey, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { + await this.app.setCacheAsync(cacheKey, state, ttl); + } + + async setWechatBindCodeCache(code, state, ttl = WECHAT_BIND_CACHE_TTL_SECONDS) { + if (!code) { + return; + } + const codeCacheKey = this.getWechatBindCodeCacheKey(code); + await this.app.setCacheAsync(codeCacheKey, state, ttl); + } + + async findYe4sBindingByAccountId(accountId) { + const { ctx } = this; + const ye4sClient = ctx.app.mysql.get('ye4s'); + const rows = await ye4sClient.select('ye4s_user', { + where: { + wms_account_id: accountId, + }, + columns: [ 'id', 'tmp_code', 'wms_account_id' ], + orders: [[ 'id', 'desc' ]], + limit: 1, + }); + if (!rows || rows.length === 0) { + return null; + } + return rows[0]; + } + /** * 用户登录(重构版) * @param {string} username - 用户名/手机号/邮箱 @@ -143,6 +235,281 @@ class UserService extends Service { } } + /** + * 获取微信绑定码(缓存优先,低频复查DB,适配轮询) + * @param {Object} data + * @return {Object} + */ + async getBindWechatCode(data = {}) { + const { app } = this; + try { + const accountId = this.getCurrentAccountId(); + if (!accountId) { + return { + success: false, + code: 0, + data: null, + message: '未识别到登录账号,无法生成绑定码', + }; + } + + const cacheKey = this.getWechatBindCacheKey(accountId); + const forceRefresh = !!data.forceRefresh; + const now = Date.now(); + + let cachedState = null; + try { + cachedState = await this.app.getCacheAsync(cacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取微信绑定缓存失败: ${cacheErr.message}`); + } + + if (cachedState && !forceRefresh) { + const nextCheckAt = Number(cachedState.next_db_check_at || 0); + if (nextCheckAt > now) { + return { + success: true, + code: 200, + data: this.formatBindWechatData(cachedState, 'cache'), + message: '获取绑定码成功(缓存)', + }; + } + } + + const ye4sBinding = await this.findYe4sBindingByAccountId(accountId); + if (ye4sBinding) { + const dbCode = typeof ye4sBinding.tmp_code === 'string' ? ye4sBinding.tmp_code.trim() : ''; + const bindState = { + account_id: accountId, + status: 'bound', + code: dbCode || (cachedState && cachedState.code) || this.createWechatBindCode(), + updated_at: new Date().toISOString(), + next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: ye4sBinding.id || null, + }; + + await this.setWechatBindCache(cacheKey, bindState, WECHAT_BIND_CACHE_TTL_SECONDS); + await this.setWechatBindCodeCache(bindState.code, bindState, WECHAT_BIND_CACHE_TTL_SECONDS); + + return { + success: true, + code: 200, + data: this.formatBindWechatData(bindState, 'db'), + message: '账号已绑定微信', + }; + } + + const code = (cachedState && cachedState.code) || this.createWechatBindCode(); + const pendingState = { + account_id: accountId, + status: 'pending', + code, + updated_at: new Date().toISOString(), + next_db_check_at: now + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: null, + }; + + await this.setWechatBindCache(cacheKey, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS); + await this.setWechatBindCodeCache(pendingState.code, pendingState, WECHAT_BIND_CACHE_TTL_SECONDS); + + return { + success: true, + code: 200, + data: this.formatBindWechatData(pendingState, code === (cachedState && cachedState.code) ? 'cache-refresh' : 'generated'), + message: '账号未绑定,已生成绑定码', + }; + } catch (error) { + app.coreLogger.error(`获取微信绑定码失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取绑定码失败,请稍后重试', + }; + } + } + + /** + * 根据绑定临时码获取账号ID(供 ye4s 扫码绑定调用) + * @param {Object} data + * @return {Object} + */ + async getUserByTempCode(data = {}) { + const { ctx, app } = this; + try { + const code = typeof data.code === 'string' ? data.code.trim() : ''; + if (!code) { + return { + success: false, + code: 0, + data: null, + message: '缺少绑定码 code', + }; + } + + if (!this.parseWechatBindCode(code)) { + return { + success: false, + code: 0, + data: null, + message: '无效的绑定码格式', + }; + } + + const codeCacheKey = this.getWechatBindCodeCacheKey(code); + let codeState = null; + try { + codeState = await this.app.getCacheAsync(codeCacheKey); + } catch (cacheErr) { + app.coreLogger.warn(`读取绑定码映射缓存失败: ${cacheErr.message}`); + } + + const cachedAccountId = Number(codeState && codeState.account_id); + if (Number.isFinite(cachedAccountId) && cachedAccountId > 0) { + return { + success: true, + code: 200, + data: { + account_id: cachedAccountId, + code, + status: codeState.status || 'pending', + source: 'cache', + updated_at: codeState.updated_at || new Date().toISOString(), + }, + message: '获取账号成功', + }; + } + + const ye4sClient = ctx.app.mysql.get('ye4s'); + const ye4sUser = await ye4sClient.get('ye4s_user', { + tmp_code: code, + }); + + const wmsAccountId = Number(ye4sUser && ye4sUser.wms_account_id); + if (Number.isFinite(wmsAccountId) && wmsAccountId > 0) { + const boundState = { + account_id: wmsAccountId, + status: 'bound', + code, + updated_at: new Date().toISOString(), + next_db_check_at: Date.now() + WECHAT_BIND_RECHECK_INTERVAL_MS, + ye4s_user_id: ye4sUser.id || null, + }; + await this.setWechatBindCodeCache(code, boundState, WECHAT_BIND_CACHE_TTL_SECONDS); + await this.setWechatBindCache(this.getWechatBindCacheKey(wmsAccountId), boundState, WECHAT_BIND_CACHE_TTL_SECONDS); + + return { + success: true, + code: 200, + data: { + account_id: wmsAccountId, + code, + status: 'bound', + source: 'db', + updated_at: boundState.updated_at, + }, + message: '获取账号成功', + }; + } + + return { + success: false, + code: 0, + data: null, + message: '绑定码不存在或已过期', + }; + } catch (error) { + app.coreLogger.error(`根据绑定码获取账号失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '获取账号失败,请稍后重试', + }; + } + } + + /** + * 解绑微信:清理 ye4s_user 中与当前账号关联的数据 + * @return {Object} + */ + async unbindWechat() { + const { ctx, app } = this; + try { + const accountId = this.getCurrentAccountId(); + if (!accountId) { + return { + success: false, + code: 0, + data: null, + message: '未识别到登录账号,无法解绑', + }; + } + + const ye4sClient = ctx.app.mysql.get('ye4s'); + const bindRows = await ye4sClient.select('ye4s_user', { + where: { + wms_account_id: accountId, + }, + columns: [ 'id', 'tmp_code', 'wms_account_id' ], + orders: [[ 'id', 'desc' ]], + limit: 500, + }); + + let affectedRows = 0; + for (const row of bindRows) { + const rowCode = typeof row.tmp_code === 'string' ? row.tmp_code.trim() : ''; + if (rowCode) { + await this.setWechatBindCodeCache(rowCode, null, 1); + } + try { + const ret = await ye4sClient.update('ye4s_user', { + id: row.id, + wms_account_id: null, + tmp_code: null, + }); + 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, + tmp_code: '', + }); + affectedRows += Number(ret && ret.affectedRows ? ret.affectedRows : 0); + } + } + + const cacheKey = this.getWechatBindCacheKey(accountId); + const cachedState = await this.app.getCacheAsync(cacheKey); + if (cachedState && cachedState.code) { + await this.setWechatBindCodeCache(cachedState.code, null, 1); + } + await this.setWechatBindCache(cacheKey, null, 1); + + return { + success: true, + code: 200, + data: { + account_id: accountId, + status: 'unbound', + matched_rows: bindRows.length, + affected_rows: affectedRows, + updated_at: new Date().toISOString(), + }, + message: bindRows.length > 0 ? '解绑成功' : '当前账号未绑定微信', + }; + } catch (error) { + app.coreLogger.error(`解绑微信失败: ${error.message}`); + return { + success: false, + code: 0, + data: null, + message: '解绑失败,请稍后重试', + }; + } + } + /** * 生成统一登录成功结构 * @param {Object} user @@ -326,43 +693,58 @@ class UserService extends Service { const platformCode = ctx.header.platform || 'web'; const project = ctx.header.project; try { - // 获取用户的所有角色关联 - const store_where = { - status: 1, - }; - if (project != 'all') { - store_where.project = project; - } - console.log('store_where', store_where, project, platformCode, ctx.header); - const accountStoreEmployees = await ctx.model.AccountStoreEmployee.findAll({ - where: { - account_id: userId, + const loadAccountStoreEmployees = async projectFilter => { + const store_where = { status: 1, - }, - include: [ - { - model: ctx.model.EmployeeRole, - as: 'employeeRoles', - attributes: [ 'id', 'role_id' ], + }; + if (projectFilter && projectFilter !== 'all') { + store_where.project = projectFilter; + } + console.log('store_where', store_where, projectFilter, platformCode, ctx.header); + return ctx.model.AccountStoreEmployee.findAll({ + where: { + account_id: userId, + status: 1, }, - { - model: ctx.model.Store, - as: 'store', - attributes: [ 'id', 'company_name', 'project', 'auth_end' ], - where: store_where, - }, - ], - order: [[ 'created_at', 'DESC' ]], - }); - if (!accountStoreEmployees) { - throw ('没有符合的角色'); + include: [ + { + model: ctx.model.EmployeeRole, + as: 'employeeRoles', + attributes: [ 'id', 'role_id' ], + }, + { + model: ctx.model.Store, + as: 'store', + attributes: [ 'id', 'company_name', 'project', 'auth_end' ], + where: store_where, + }, + ], + order: [[ 'created_at', 'DESC' ]], + }); + }; + + // 先按请求 project 过滤;查不到时降级到 all,便于补齐平台激活记录。 + let accountStoreEmployees = await loadAccountStoreEmployees(project); + if ((!accountStoreEmployees || accountStoreEmployees.length === 0) && project && project !== 'all') { + accountStoreEmployees = await loadAccountStoreEmployees('all'); + } + + if (!accountStoreEmployees || accountStoreEmployees.length === 0) { + return { + Employees: [], + activeEmployeeId: null, + menus: [], + permissions: [], + userRole: '', + realName: null, + }; } console.log('accountStoreEmployees>>>>>', accountStoreEmployees); // 获取当前平台的激活角色 let activeEmployeeId = null; - let employee_id = null; let realName = null; let userRole = ''; + let currentPlatformEmployeeId = null; const platformActive = await ctx.model.AccountPlatformActive.findOne({ where: { @@ -372,14 +754,14 @@ class UserService extends Service { attributes: [ 'account_id', 'employee_id', 'platform_code' ], }); if (platformActive) { - employee_id = platformActive.employee_id; + currentPlatformEmployeeId = platformActive.employee_id; } // 转换数据格式 const Employees = accountStoreEmployees.map(item => ({ id: item.id, store_id: item.store_id, store_name: item.store.company_name, - is_primary: platformActive && platformActive.employee_id === item.id ? 1 : 0, + is_primary: currentPlatformEmployeeId === item.id ? 1 : 0, real_name: item.real_name, auth_end: item.store.auth_end, role_type: item.store.project, @@ -416,7 +798,14 @@ class UserService extends Service { return { Employees, activeEmployeeId, menus, permissions, userRole, realName }; } catch (error) { console.error('获取用户角色失败:', error); - return [[], null, [], [], '', null ]; + return { + Employees: [], + activeEmployeeId: null, + menus: [], + permissions: [], + userRole: '', + realName: null, + }; } } @@ -466,8 +855,19 @@ class UserService extends Service { } // 3. 获取角色信息(这个方法内部也有缓存逻辑) - const { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId); + let { Employees, activeEmployeeId, menus, permissions, userRole, realName } = await this.getRoles(userId); console.log('activeEmployeeId>>>>>>>>', activeEmployeeId); + + // pda 场景若缺少激活角色,优先补一条当前平台激活记录,避免直接报错。 + if (platformCode == 'pda' && !activeEmployeeId && Employees.length > 0) { + const fallbackEmployee = Employees[0]; + await this.ensurePlatformActiveRole(userId, fallbackEmployee.id, platformCode); + activeEmployeeId = fallbackEmployee.id; + userRole = fallbackEmployee.role_type == 1 ? 'warehouse' : 'customer'; + realName = fallbackEmployee.real_name || realName; + menus = await this.getMenus(activeEmployeeId); + permissions = await this.getPermissions(activeEmployeeId); + } // 4. 获取当前角色对应的仓库ID let storeId = null; let storeName = null; @@ -489,7 +889,7 @@ class UserService extends Service { const avatar = await this.getAvatarByEmployeeId(activeEmployeeId); if (platformCode == 'pda' && !activeEmployeeId) { - throw ('无登录权限'); + ctx.logger.warn(`pda 平台未找到可激活角色,accountId=${userId},将以空角色上下文返回`); } // 5. 组合用户信息 const userInfo = { diff --git a/app/service/systems/polo_api.js b/app/service/systems/polo_api.js index 307f7b6..af7289f 100644 --- a/app/service/systems/polo_api.js +++ b/app/service/systems/polo_api.js @@ -4,60 +4,56 @@ const Service = require('egg').Service; const poloApiConfig = require('../../../config/poloapi'); const crypto = require('crypto'); -const querystring = require('querystring'); class PoloApiService extends Service { - constructor(ctx) { - super(ctx); - this.configPoloApi = poloApiConfig; - } + constructor(ctx) { + super(ctx); + this.configPoloApi = poloApiConfig; + } - // 批量组装订单JSON - getJsonDatas(expressConfig, list) { - const formatter = 'yyyy-MM-dd HH:mm:ss'; - const now = new Date(); - const tempDate = this._formatDate(now, formatter); - const cal = new Date(); - const year = cal.getFullYear(); - const month = cal.getMonth() + 1; - const day = cal.getDate() + 3; - const day1 = cal.getDate() + 4; - const sb1 = this._formatPickupDate(year, month, day); - const sb2 = this._formatPickupDate(year, month, day1); + // 批量组装订单JSON + getJsonDatas(expressConfig, list) { + const cal = new Date(); + const year = cal.getFullYear(); + const month = cal.getMonth() + 1; + const day = cal.getDate() + 3; + const day1 = cal.getDate() + 4; + const sb1 = this._formatPickupDate(year, month, day); + const sb2 = this._formatPickupDate(year, month, day1); - let orders = []; - for (const wmsOrder of list) { - let txLogisticID = wmsOrder.sourceId; - txLogisticID = txLogisticID.length < 6 ? txLogisticID.padStart(6, '0') : txLogisticID; - if (wmsOrder.postcode === 'p10') { - if (txLogisticID.length > 19) txLogisticID = txLogisticID.slice(-19); - } else { - if (txLogisticID.length > 28) txLogisticID = txLogisticID.slice(-28); - } - txLogisticID = txLogisticID.replace(/_/g, ''); + const orders = []; + for (const wmsOrder of list) { + let txLogisticID = wmsOrder.sourceId; + txLogisticID = txLogisticID.length < 6 ? txLogisticID.padStart(6, '0') : txLogisticID; + if (wmsOrder.postcode === 'p10') { + if (txLogisticID.length > 19) txLogisticID = txLogisticID.slice(-19); + } else { + if (txLogisticID.length > 28) txLogisticID = txLogisticID.slice(-28); + } + txLogisticID = txLogisticID.replace(/_/g, ''); - // 快递公司代码 - const cpcode = this.configPoloApi.postCodeMap[wmsOrder.postcode] || ''; + // 快递公司代码 + const cpcode = this.configPoloApi.postCodeMap[wmsOrder.postcode] || ''; - // 商品名 - let cnname = ''; - let ycflag = !(wmsOrder.wareHouseId === 5400 || wmsOrder.storeId === 58303); - if (ycflag) { - const items = wmsOrder.items || ''; - const splitStr = items.split('|'); - if (splitStr.length > 0) { - const s = splitStr[0]; - const sArr = s.split(','); - if (sArr.length > 2) cnname = sArr[2]; - } - } else { - cnname = 'sp'; - } + // 商品名 + let cnname = ''; + const ycflag = !(wmsOrder.wareHouseId === 5400 || wmsOrder.storeId === 58303); + if (ycflag) { + const items = wmsOrder.items || ''; + const splitStr = items.split('|'); + if (splitStr.length > 0) { + const s = splitStr[0]; + const sArr = s.split(','); + if (sArr.length > 2) cnname = sArr[2]; + } + } else { + cnname = 'sp'; + } - // 收件人手机号 - let mobile = wmsOrder.tempMobile || wmsOrder.tel || ''; + // 收件人手机号 + const mobile = wmsOrder.tempMobile || wmsOrder.tel || ''; - /* + /* order对象结构(41-77): { businessplat, ismultiplepieces, businesstype, cpcode, customercode, customername, @@ -79,125 +75,125 @@ class PoloApiService extends Service { country, Company, address, name, area, town, city, phone, mobile, tel, province } */ - // 组装订单对象(下标范围:约第41-77行) - const order = { // [order对象开始 41] - businessplat: 'OTHERS', // 41 - ismultiplepieces: '0', - businesstype: 'JH_Normal', - cpcode, - customercode: '', - customername: expressConfig.storeProperty || '测试', - goods: [{ // [goods对象开始 49] - cnname, - count: String(wmsOrder.goodsCount), - unit: '属性', - currencytype: 'CNY', - Unit: '', - weight: String(wmsOrder.orderWeight), - price: '0.0', - }], // [goods对象结束 56] - logisticsproductname: 'JH_02', - logistictype: cpcode, - mainsubpaymode: '1', - needencrypt: '1', - numpackage: '1', - orderno: wmsOrder.sourceOrderCode || (wmsOrder.id && wmsOrder.id.length > 13 ? wmsOrder.id.substring(0, 14) : wmsOrder.id), - ordersource: 'KUAI_SHOU', - ordertype: 'JH_Normal', - plattradeno: wmsOrder.sourceOrderCode || txLogisticID, - ProviderID: wmsOrder.postcode === 'p03' ? 1327 : (wmsOrder.postcode === 'p04' ? 1499 : ''), - providercode: cpcode, - receiver: { // [receiver对象开始 59] - address: wmsOrder.address, - name: wmsOrder.name, - area: wmsOrder.expAreaName, - city: wmsOrder.cityName, - mobile, - province: wmsOrder.province, - }, // [receiver对象结束 65] - sender: { // [sender对象开始 66] - country: 'CN', - Company: expressConfig.storeName, - address: expressConfig.address, - name: expressConfig.senderName, - area: expressConfig.districtName && expressConfig.districtName.indexOf(';') === -1 ? expressConfig.districtName : expressConfig.districtName.split(';')[0], - town: expressConfig.districtName && expressConfig.districtName.indexOf(';') !== -1 ? expressConfig.districtName.split(';')[1] : undefined, - city: expressConfig.cityName, - phone: expressConfig.senderTel, - mobile: expressConfig.senderTel, - tel: expressConfig.senderTel, - province: expressConfig.provinceName, - }, // [sender对象结束 75] - shipperno: ['p22', 'p35', 'p10'].includes(wmsOrder.postcode) ? expressConfig.siteCode : expressConfig.clientId, - sitecode: expressConfig.siteCode || '', - Inputsite: expressConfig.siteCode || '', - transtype: '0', - // 省略部分特殊字段和extraInfo,后续可补充 - }; // [order对象结束 77] - // 特殊字段 - if (wmsOrder.postcode === 'p10') { - order.pickUpDate = sb1; - order.pickUpEndDate = sb2; - } - orders.push(order); - } + // 组装订单对象(下标范围:约第41-77行) + const order = { // [order对象开始 41] + businessplat: 'OTHERS', // 41 + ismultiplepieces: '0', + businesstype: 'JH_Normal', + cpcode, + customercode: '', + customername: expressConfig.storeProperty || '测试', + goods: [{ // [goods对象开始 49] + cnname, + count: String(wmsOrder.goodsCount), + unit: '属性', + currencytype: 'CNY', + Unit: '', + weight: String(wmsOrder.orderWeight), + price: '0.0', + }], // [goods对象结束 56] + logisticsproductname: 'JH_02', + logistictype: cpcode, + mainsubpaymode: '1', + needencrypt: '1', + numpackage: '1', + orderno: wmsOrder.sourceOrderCode || (wmsOrder.id && wmsOrder.id.length > 13 ? wmsOrder.id.substring(0, 14) : wmsOrder.id), + ordersource: 'KUAI_SHOU', + ordertype: 'JH_Normal', + plattradeno: wmsOrder.sourceOrderCode || txLogisticID, + ProviderID: wmsOrder.postcode === 'p03' ? 1327 : (wmsOrder.postcode === 'p04' ? 1499 : ''), + providercode: cpcode, + receiver: { // [receiver对象开始 59] + address: wmsOrder.address, + name: wmsOrder.name, + area: wmsOrder.expAreaName, + city: wmsOrder.cityName, + mobile, + province: wmsOrder.province, + }, // [receiver对象结束 65] + sender: { // [sender对象开始 66] + country: 'CN', + Company: expressConfig.storeName, + address: expressConfig.address, + name: expressConfig.senderName, + area: expressConfig.districtName && expressConfig.districtName.indexOf(';') === -1 ? expressConfig.districtName : expressConfig.districtName.split(';')[0], + town: expressConfig.districtName && expressConfig.districtName.indexOf(';') !== -1 ? expressConfig.districtName.split(';')[1] : undefined, + city: expressConfig.cityName, + phone: expressConfig.senderTel, + mobile: expressConfig.senderTel, + tel: expressConfig.senderTel, + province: expressConfig.provinceName, + }, // [sender对象结束 75] + shipperno: [ 'p22', 'p35', 'p10' ].includes(wmsOrder.postcode) ? expressConfig.siteCode : expressConfig.clientId, + sitecode: expressConfig.siteCode || '', + Inputsite: expressConfig.siteCode || '', + transtype: '0', + // 省略部分特殊字段和extraInfo,后续可补充 + }; // [order对象结束 77] + // 特殊字段 + if (wmsOrder.postcode === 'p10') { + order.pickUpDate = sb1; + order.pickUpEndDate = sb2; + } + orders.push(order); + } - const body = JSON.stringify({ orders, shoptype: 'JH_001' }); + const body = JSON.stringify({ orders, shoptype: 'JH_001' }); - // 组装url参数 - const urlParams = { - method: 'Differ.JH.Logistics.PostOrder', - appkey: this.configPoloApi.appKey, - token: expressConfig.sessionKey, - platid: this.configPoloApi.platid, - version: this.configPoloApi.version, - bizcontent: encodeURIComponent(body), - contenttype: this.configPoloApi.contenttype, - timestamp: encodeURIComponent(this._formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss')), - }; - // 签名 - const signMap = { ...urlParams, bizcontent: body, timestamp: this._formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss') }; - const signText = this.getSignText(signMap, this.configPoloApi.appSecret); - urlParams.sign = this.md5Encrypt(signText.toLowerCase(), 'utf8'); + // 组装url参数 + const urlParams = { + method: 'Differ.JH.Logistics.PostOrder', + appkey: this.configPoloApi.appKey, + token: expressConfig.sessionKey, + platid: this.configPoloApi.platid, + version: this.configPoloApi.version, + bizcontent: encodeURIComponent(body), + contenttype: this.configPoloApi.contenttype, + timestamp: encodeURIComponent(this._formatDate(new Date())), + }; + // 签名 + const signMap = { ...urlParams, bizcontent: body, timestamp: this._formatDate(new Date()) }; + const signText = this.getSignText(signMap, this.configPoloApi.appSecret); + urlParams.sign = this.md5Encrypt(signText.toLowerCase(), 'utf8'); - // 返回请求体和参数 - return { body, urlParams }; - } + // 返回请求体和参数 + return { body, urlParams }; + } - // 单个订单JSON(略,结构同上,建议复用 getJsonDatas 逻辑) - getJsonData(expressConfig, wmsOrder, deliveryOrder, type) { - // 可根据 type 判断调用 getJsonDatas 或单独组装 - return this.getJsonDatas(expressConfig, [wmsOrder]); - } + // 单个订单JSON(略,结构同上,建议复用 getJsonDatas 逻辑) + getJsonData(expressConfig, wmsOrder) { + // 可根据 type 判断调用 getJsonDatas 或单独组装 + return this.getJsonDatas(expressConfig, [ wmsOrder ]); + } - // 生成签名字符串 - getSignText(signMap, secret) { - let sb = '' + secret; - Object.keys(signMap).sort().forEach(key => { - sb += key + signMap[key]; - }); - sb += secret; - return sb; - } + // 生成签名字符串 + getSignText(signMap, secret) { + let sb = '' + secret; + Object.keys(signMap).sort().forEach(key => { + sb += key + signMap[key]; + }); + sb += secret; + return sb; + } - // MD5加密 - md5Encrypt(text, encoding = 'utf8') { - return crypto.createHash('md5').update(text, encoding).digest('hex'); - } + // MD5加密 + md5Encrypt(text, encoding = 'utf8') { + return crypto.createHash('md5').update(text, encoding).digest('hex'); + } - // 工具:格式化日期 - _formatDate(date, fmt) { - // 仅支持 yyyy-MM-dd HH:mm:ss - const pad = n => n < 10 ? '0' + n : n; - return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + // 工具:格式化日期 + _formatDate(date) { + // 仅支持 yyyy-MM-dd HH:mm:ss + const pad = n => (n < 10 ? '0' + n : n); + return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate()) + ' ' + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds()); - } + } - // 工具:组装取件日期 - _formatPickupDate(year, month, day) { - const pad = n => n < 10 ? '0' + n : n; - return `${year}-${pad(month)}-${pad(day)} 18:00:00`; - } + // 工具:组装取件日期 + _formatPickupDate(year, month, day) { + const pad = n => (n < 10 ? '0' + n : n); + return `${year}-${pad(month)}-${pad(day)} 18:00:00`; + } } -module.exports = PoloApiService; \ No newline at end of file +module.exports = PoloApiService; diff --git a/app/service/systems/store.js b/app/service/systems/store.js index d01f0b0..85dcaff 100644 --- a/app/service/systems/store.js +++ b/app/service/systems/store.js @@ -2,6 +2,73 @@ const Service = require('egg').Service; class StoreService extends Service { + validateStoreData(data = {}) { + const errors = []; + + const requiredFields = [ 'company_name', 'contact_person', 'contact_phone' ]; + for (const field of requiredFields) { + if (!data[field]) { + errors.push(`${field} 不能为空`); + } + } + + if (data.company_name && (data.company_name.length < 1 || data.company_name.length > 200)) { + errors.push('公司名称长度应在1-200个字符之间'); + } + + if (data.contact_email && data.contact_email.trim() !== '') { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(data.contact_email)) { + errors.push('联系邮箱格式不正确'); + } + } + + return errors; + } + + async checkCompanyNameExists(companyName, excludeId = null) { + const where = { + company_name: companyName, + }; + + if (excludeId) { + where.id = { + [this.app.Sequelize.Op.ne]: excludeId, + }; + } + + const store = await this.app.model.Store.findOne({ where }); + return !!store; + } + + async findByAccountId(accountId) { + return await this.app.model.Store.findOne({ + where: { + account_id: accountId, + status: 1, + }, + }); + } + + async findAllEnabled() { + return await this.app.model.Store.findAll({ + where: { + status: 1, + }, + order: [[ 'company_name', 'ASC' ]], + }); + } + + async findAllWarehouses() { + return await this.app.model.Store.findAll({ + where: { + status: 1, + project: 'warehouse', + }, + order: [[ 'company_name', 'ASC' ]], + }); + } + /** * 根据ID获取商家信息 * @param storeId diff --git a/config/config.default.js b/config/config.default.js index b315709..4c783ee 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -113,19 +113,26 @@ module.exports = appInfo => { config.mysql = { clients: { wms: { - host: '10.10.0.1', + host: '112.124.21.102', port: '3306', user: 'wms', password: 'P6j3YTHTpirepYWz', database: 'wms', }, + ye4s:{ + host: '112.124.21.102', + port: '3306', + user: 'ye4s', + password: 'H@8h^QE4N$L.F_*', + database: 'ye4s', + } }, app: true, agent: false, }; exports.sequelize = { dialect: 'mysql', - host: '10.10.0.1', + host: '112.124.21.102', port: 3306, database: 'wms', username: 'wms', @@ -150,12 +157,12 @@ module.exports = appInfo => { secret: 'E5#ex.g@,GfL_8?', }; - /*config.view = { + config.view = { defaultViewEngine: 'ejs', mapping: { '.html': 'ejs', }, - };*/ + }; config.cluster = { listen: { port: 6060, // 使用其他端口避免冲突 @@ -163,10 +170,10 @@ module.exports = appInfo => { }, }; config.poloapi ={ - + } config.printService = { - url: 'http://localhost:4050', + url: 'http://printer.wms.gztbyc.com', }; return { ...config, diff --git a/config/deploy.config.example.cjs b/config/deploy.config.example.cjs new file mode 100644 index 0000000..25d3a2a --- /dev/null +++ b/config/deploy.config.example.cjs @@ -0,0 +1,24 @@ +module.exports = { + production: { + host: '__FILL_SSH_HOST__', + port: 22, + username: '__FILL_SSH_USERNAME__', + privateKeyPath: 'C:/Users/your-user/.ssh/id_rsa', + deployRoot: '/www/wwwroot/qimen', + sharedDirs: [ 'logs', 'run', 'temp' ], + keepBackups: 5, + preDeployCommands: [ + 'node -v', + 'npm -v', + ], + postDeployCommands: [ + 'npm install --production', + 'npm run stop || true', + 'npm start', + ], + healthCheckUrl: 'http://127.0.0.1:6060/', + sshOptions: [ + 'StrictHostKeyChecking=accept-new', + ], + }, +}; \ No newline at end of file diff --git a/day.log b/day.log index f3ffdcc..68d815a 100644 Binary files a/day.log and b/day.log differ diff --git a/methods/gateway.json b/methods/gateway.json new file mode 100644 index 0000000..6f37cb6 --- /dev/null +++ b/methods/gateway.json @@ -0,0 +1,54 @@ +{ + "module": "gateway", + "description": "内部网关接口,供内网系统间调用,统一使用 POST 请求", + "version": "0.1.0", + "updatedAt": "2026-03-24", + "headers": [], + "methods": { + "groups": [ + { + "groupName": "用户模块", + "module": "user", + "list": [ + { + "method": "user.getUserByTempCode", + "description": "根据绑定码反查WMS账号ID(供 ye4s 扫码绑定调用)", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "code", + "type": "string", + "required": true, + "source": "body", + "description": "绑定码(由 user.getBindWechatCode 生成)" + } + ], + "response": [ + { + "name": "account_id", + "type": "number", + "required": true, + "description": "匹配到的 WMS 账号ID" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "当前绑定状态,如 pending/bound" + }, + { + "name": "source", + "type": "string", + "required": true, + "description": "数据来源,如 cache/db" + } + ], + "errors": [] + } + ] + } + ] + } +} \ No newline at end of file diff --git a/methods/system.json b/methods/system.json index 9552066..1b128b4 100644 --- a/methods/system.json +++ b/methods/system.json @@ -2,7 +2,7 @@ "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", "version": "0.3.0", - "updatedAt": "2026-03-22", + "updatedAt": "2026-03-23", "headers": [ { "name": "platform", @@ -22,13 +22,12 @@ "type":"string", "required":true, "name":"project", - "description":"项目标识,如 wms", + "description":"项目标识,如 all/warehouse/store/tms", "list":[ - {"value":"all","name":"所有系统"}, - {"value":"wms","name":"仓库管理系统"}, - {"value":"tms","name":"运输管理系统"}, - {"value":"scm","name":"供应链管理系统"}, - {"value":"other","name":"其他"} + {"value":"all","name":"全部"}, + {"value":"warehouse","name":"仓库"}, + {"value":"store","name":"货主"}, + {"value":"tms","name":"物流"} ] } ], @@ -2411,6 +2410,48 @@ "response": [], "errors": [] }, + { + "method": "user.getBindWechatCode", + "description": "获取微信绑定码(支持轮询,缓存优先)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "forceRefresh", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否强制刷新状态,true 时跳过缓存等待窗口" + } + ], + "response": [], + "errors": [] + }, + { + "method": "user.unbindWechat", + "description": "解绑微信账号(清理 ye4s 关联账号数据)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [], + "response": [], + "errors": [] + }, { "method": "user.logout", "description": "用户登出", diff --git a/model_todo.txt b/model_todo.txt index 1a06943..7dd5e96 100644 --- a/model_todo.txt +++ b/model_todo.txt @@ -1,6 +1,6 @@ Model 重构总计划(数据库 + Migrations + Models) -更新时间: 2026-03-22 -当前状态: 执行中(阶段 1-3 已完成) +更新时间: 2026-03-23 +当前状态: 执行中(阶段 1-5 已完成,阶段 6 进行中) 负责人: 目标截止时间: 执行分支: @@ -20,7 +20,7 @@ Model 重构总计划(数据库 + Migrations + Models) - [x] 已收到新任务,开始执行阶段 1。 - [x] 进入代码改动前,先核对目标 service 的真实调用链。 - [x] 若 service 已被 system/qimen 入口使用,则必须同步更新对应 API 文档。 -- [x] 所有联动修改需记录到 SERVICE_API_CHANGE_AUDIT_20260322.md,便于后续复盘。 +- [x] 所有联动修改需记录到 temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md,便于后续复盘。 - [x] 任何模型/关联改动前,使用测试账号执行 method 基线回放(配置与样本来源必须可追溯)。 - [x] 任何模型/关联改动后,执行同一批 method 对比回放并输出比对报告。 - [x] 新增交付条件:修改前后 method 输出结果一致(允许仅屏蔽 token/timestamp 等波动字段)。 @@ -31,17 +31,17 @@ Model 重构总计划(数据库 + Migrations + Models) - [x] 1.2 盘点所有 model 文件(app/model 下文件、导出名、表映射)。 - [x] 1.3 盘点 model 关联(belongsTo/hasMany/hasOne/belongsToMany 与外键使用)。 - [x] 1.4 产出 DB 结构与 model 定义差异报告。 -- [x] 1.5 在根目录生成 modelList.md,构建 model 层级结构与说明。 -- [x] 1.6 在 README.md 增加对 modelList.md 的引用说明。 +- [x] 1.5 在根目录生成 temp/docs/modelList.md,构建 model 层级结构与说明。 +- [x] 1.6 在 README.md 增加对 temp/docs/modelList.md 的引用说明。 交付物: -- table_schema_inventory.md -- model_inventory.md -- model_association_inventory.md -- schema_model_gap_report.md -- modelList.md +- temp/docs/table_schema_inventory.md +- temp/docs/model_inventory.md +- temp/docs/model_association_inventory.md +- temp/docs/schema_model_gap_report.md +- temp/docs/modelList.md 退出标准: - 100% 数据表与 100% model 文件覆盖完成。 -- modelList.md 可用于快速定位模型层级与职责。 +- temp/docs/modelList.md 可用于快速定位模型层级与职责。 [阶段 2: Migration 补全与执行顺序设计] - [x] 2.1 审核现有 database/migrations 的命名、顺序、幂等性。 @@ -50,9 +50,9 @@ Model 重构总计划(数据库 + Migrations + Models) - [x] 2.4 为每个迁移定义可执行回滚步骤。 - [x] 2.5 形成 local/test 环境演练方案。 交付物: -- migration_gap_list.md -- migration_execution_plan.md -- rollback_plan.md +- temp/docs/migration_gap_list.md +- temp/docs/migration_execution_plan.md +- temp/docs/rollback_plan.md 退出标准: - 每个结构差异都有明确迁移归属与回滚路径。 @@ -62,31 +62,31 @@ Model 重构总计划(数据库 + Migrations + Models) - [x] 3.3 评估跨层影响(service/controller/query 调用点)。 - [x] 3.4 制定兼容策略(临时别名或分批重命名)。 交付物: -- model_naming_standard.md -- model_rename_map.md -- rename_impact_report.md +- temp/docs/model_naming_standard.md +- temp/docs/model_rename_map.md +- temp/docs/rename_impact_report.md 退出标准: - 所有命名不规范项有明确修复路径与影响说明。 [阶段 4: 关联关系规范化] -- [x] 4.1 逐项校验关联定义与真实外键关系一致性(详见 association_fk_consistency_report.md)。 +- [x] 4.1 逐项校验关联定义与真实外键关系一致性(详见 temp/docs/association_fk_consistency_report.md)。 - [x] 4.2 统一 alias 命名与双向关联完整性。 - [x] 4.3 清理重复或冲突关联。 -- [x] 4.4 形成 eager-loading 与 N+1 风险规约(详见 association_eager_loading_n_plus_one_guideline.md)。 +- [x] 4.4 形成 eager-loading 与 N+1 风险规约(详见 temp/docs/association_eager_loading_n_plus_one_guideline.md)。 交付物: -- association_fix_plan.md -- association_validation_checklist.md +- temp/docs/association_fix_plan.md +- temp/docs/association_validation_checklist.md 退出标准: - 关联关系可预测、无冲突、与数据库关系一致。 [阶段 5: Model 内部能力清理] -- [x] 5.1 识别应迁移到 service 层的方法能力(见 model_cleanup_list.md 第一批清单)。 -- [ ] 5.2 清理 model 内死代码与调试代码(进行中:第一批/第二批 P2 无调用静态方法已清理;P1 前两组 EntryOrder/EntryItems 与 Storage 已迁移到 service)。 -- [ ] 5.3 规范 hooks/scopes/virtual fields 的使用边界。 -- [ ] 5.4 固化模型层边界规则(可做/不可做)。 +- [x] 5.1 识别应迁移到 service 层的方法能力(见 temp/docs/model_cleanup_list.md 第一批清单)。 +- [x] 5.2 清理 model 内死代码与调试代码(已完成:P2 两批无调用静态方法清理 + P1 四组方法迁移并回收 model 同名方法)。 +- [x] 5.3 规范 hooks/scopes/virtual fields 的使用边界(盘点完成并已产出 temp/docs/model_boundary_rules.md)。 +- [x] 5.4 固化模型层边界规则(新增 script/model-boundary-check.cjs 并接入 npm run check:model-boundary)。 交付物: -- model_cleanup_list.md -- model_boundary_rules.md +- temp/docs/model_cleanup_list.md +- temp/docs/model_boundary_rules.md 退出标准: - 模型层聚焦于数据映射与轻量领域行为,职责边界清晰。 @@ -116,15 +116,20 @@ Model 重构总计划(数据库 + Migrations + Models) - 高优先差异项推进: 已完成 store_warehouse/stock_warehouse 第二批收敛(stock_store include 语义约束补齐),并通过门禁。 - 高优先差异项推进: 已完成 role / role_permission / permission 第三批收敛(启用状态过滤 + 去重),并通过门禁。 - 已完成“DB 约束补齐”执行: `wms_role_permission.permission_id -> wms_permission.id` 外键已生效,SequelizeMeta 已登记 `20260323103000-align-role-permission-fk.js`。 -- 已完成数据清洗与备份: 4 条 permission 孤儿、3 条 role.store_id=0 哨兵数据均已处理(备份表见 `role_permission_fk_data_cleanup_plan.md`)。 +- 已完成数据清洗与备份: 4 条 permission 孤儿、3 条 role.store_id=0 哨兵数据均已处理(备份表见 `temp/docs/role_permission_fk_data_cleanup_plan.md`)。 - 已完成 `wms_role.store_id` 外键策略落地:外键 `fk_wms_role_store` 已生效(ON DELETE SET NULL),SequelizeMeta 已登记 `20260323113000-add-role-store-fk.js`。 - 已完成 store_warehouse / stock_warehouse 模型层复合键语义治理(统一 include 构造器 + constraints:false 显式化)。 - 已完成阶段 4 收尾检查(第 1 项):全量 include alias 一致性扫描(service alias 与 model alias 差集=0)。 - 已完成阶段 4 收尾检查(第 2 项):permission.parent_id 自关联约束策略已落地(root=NULL + FK)。 -- 已完成阶段 5.1:识别应迁移到 service 层的方法能力(第一批清单见 model_cleanup_list.md)。 -- 已启动阶段 5.2:已完成第一批 P2 无调用静态方法清理(ApiApp / InterfaceType / PrintItem),门禁通过。 -- 已完成阶段 5.2 删除前引用复核(第二批):I18nTranslation 5 个候选静态方法、StockStore 2 个候选静态方法均未检出业务调用。 -- 已完成阶段 5.2 第二批 P2 方法删除(I18nTranslation / StockStore),compare + generated regression + smoke 门禁通过。 -- 已完成阶段 5.2 P1 第一组迁移:EntryOrder / EntryItems 共 8 个静态方法已迁移到 `app/service/systems/entry_order.js`,并从 model 删除;compare + generated regression + smoke 门禁通过。 -- 已完成阶段 5.2 P1 第二组迁移:Storage 共 10 个静态方法已迁移到 `app/service/systems/storage/index.js`,并从 model 删除。 -- 下一步继续阶段 5.2:推进 P1 剩余方法(RolePermission / Store)从 model 向 service 收敛,并在迁移完成后回收对应静态方法。 +- 已完成阶段 5.1:识别应迁移到 service 层的方法能力(第一批清单见 temp/docs/model_cleanup_list.md)。 +- 已完成阶段 5.2 第一批 P2 清理:ApiApp / InterfaceType / PrintItem,门禁通过。 +- 已完成阶段 5.2 第二批 P2 清理:I18nTranslation / StockStore,门禁通过。 +- 已完成阶段 5.2 P1 第一组:EntryOrder / EntryItems 8 个方法迁移到 service 并回收 model 同名方法。 +- 已完成阶段 5.2 P1 第二组:Storage 10 个方法迁移到 service 并回收 model 同名方法。 +- 已完成阶段 5.2 P1 第三组:Role / RolePermission 7 个方法迁移到 service 并回收 model 同名方法。 +- 已完成阶段 5.2 P1 第四组:Store 5 个方法迁移到 service 并回收 model 同名方法。 +- 已完成阶段 5.3:hooks/scopes/virtual fields 边界盘点与规则固化(见 temp/docs/model_boundary_rules.md)。 +- 已完成阶段 5.4:新增 model 边界检查脚本并接入 npm 命令与 CI(check:model-boundary)。 +- 已复跑阶段 5.4 门禁命令:`npm run check:model-boundary`,结果 PASS(files=45, hooks=2, scopeFiles=1, virtualLines=0)。 +- 过程门禁:compare mismatch=0;generated regression 与 smoke 持续通过;新增 model-boundary 检查门禁。 +- 下一步进入阶段 6.1:在干净库上回放 migration 全流程。 diff --git a/package.json b/package.json index 4712c53..2129eed 100644 --- a/package.json +++ b/package.json @@ -39,13 +39,33 @@ }, "scripts": { "start": "egg-scripts start ", - "stop": "egg-scripts stop", + "stop": "node ./app/lib/stop_current_egg.js", "dev": "egg-bin dev --port=6060", + "deploy:init": "node ./script/deploy-init.cjs production", + "deploy:init:dry": "node ./script/deploy-init.cjs production --dry-run", + "deploy:precheck": "node ./script/deploy-precheck.cjs", + "deploy:authcheck": "node ./script/deploy-auth-check.cjs", + "deploy:version": "node ./script/deploy-version.cjs production", + "deploy:version:history": "node ./script/deploy-version.cjs production --history=20", + "deploy:inspect": "node ./script/deploy-ops.cjs production inspect", + "deploy:smoke": "node ./script/deploy-ops.cjs production smoke", + "deploy:verify": "node ./script/deploy-ops.cjs production verify", + "deploy:cleanup-backups": "node ./script/deploy-ops.cjs production cleanup-backups", + "deploy:gateway-probe": "node ./script/deploy-ops.cjs production gateway-probe", + "version:record": "node ./script/version-record.cjs", + "version:history": "node ./script/version-history.cjs --limit=50", + "deploy": "npm run deploy:prod", + "deploy:prod": "node ./script/deploy-remote.cjs production", + "rollback": "npm run rollback:prod", + "rollback:prod": "node ./script/rollback-remote.cjs production", + "guard:git": "node ./script/git-safety-check.cjs", + "setup:hooks": "node ./script/setup-git-hooks.cjs", "test": "npm run lint -- --fix && npm run test:local", "test:local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", - "ci": "npm run lint && npm run cov" + "check:model-boundary": "node ./script/model-boundary-check.cjs", + "ci": "npm run lint && npm run check:model-boundary && npm run cov" }, "repository": { "type": "git", diff --git a/script/deploy-auth-check.cjs b/script/deploy-auth-check.cjs new file mode 100644 index 0000000..05aee43 --- /dev/null +++ b/script/deploy-auth-check.cjs @@ -0,0 +1,42 @@ +'use strict'; + +const { spawnSync } = require('node:child_process'); +const { loadDeployConfig } = require('./deploy-lib.cjs'); + +function main() { + const config = loadDeployConfig('production'); + + const args = [ '-vv' ]; + args.push('-p', String(config.port)); + args.push('-i', config.privateKeyPath); + for (const option of config.sshOptions) { + args.push('-o', option); + } + args.push(`${config.username}@${config.host}`); + args.push('echo AUTH_CHECK_OK'); + + const result = spawnSync('ssh', args, { + encoding: 'utf8', + stdio: 'pipe', + shell: false, + }); + + const text = `${result.stdout || ''}\n${result.stderr || ''}`; + const summary = { + keyOffered: /Offering public key:/i.test(text) || /Will attempt key:/i.test(text), + keyAccepted: /Authenticated to .* using "publickey"/i.test(text) || /AUTH_CHECK_OK/i.test(text), + authFailed: /Permission denied|Authentication failed/i.test(text), + hostKeyFailed: /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(text), + networkFailed: /Connection timed out|No route to host|Connection refused|Could not resolve hostname|Operation timed out/i.test(text), + }; + + console.log(JSON.stringify(summary, null, 2)); + + if (summary.keyAccepted) { + process.exit(0); + } + + process.exit(1); +} + +main(); \ No newline at end of file diff --git a/script/deploy-init.cjs b/script/deploy-init.cjs new file mode 100644 index 0000000..96c34e7 --- /dev/null +++ b/script/deploy-init.cjs @@ -0,0 +1,137 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { + ROOT, + ensureCommandAvailable, + ensureTempDeployDir, + getNowStamp, + loadDeployConfig, + quoteForBash, + runCommand, + runScp, + runSsh, +} = require('./deploy-lib.cjs'); + +function parseArgs(argv) { + const options = { + envName: 'production', + dryRun: false, + }; + + for (const item of argv) { + if (!item) continue; + if (item === '--dry-run') { + options.dryRun = true; + continue; + } + if (!item.startsWith('--')) { + options.envName = item; + } + } + + return options; +} + +function listConfigSeedFiles() { + const output = runCommand('git', [ 'ls-files', '--cached', 'config' ]); + return output + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean) + .filter(item => item.startsWith('config/')) + .filter(item => item !== 'config/config.local.js') + .filter(item => item !== 'config/deploy.config.local.cjs') + .filter(item => item !== 'config/deploy.config.example.cjs'); +} + +function buildConfigSeedArchive(stamp, files) { + const tempDir = ensureTempDeployDir(); + const listPath = path.join(tempDir, `deploy-init-files-${stamp}.txt`); + const archivePath = path.join(tempDir, `deploy-init-${stamp}.tar.gz`); + + if (!files || files.length === 0) { + throw new Error('未找到可用于初始化的 config 文件(git tracked)。'); + } + + fs.writeFileSync(listPath, files.join('\n') + '\n', 'utf8'); + runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit' }); + return { + archivePath, + listPath, + }; +} + +function cleanupLocalTemp(paths) { + for (const filePath of paths) { + if (!filePath) continue; + if (fs.existsSync(filePath)) { + fs.unlinkSync(filePath); + } + } +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + + ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。'); + ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。'); + ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); + ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。'); + + const config = loadDeployConfig(options.envName); + const seedFiles = listConfigSeedFiles(); + + if (options.dryRun) { + console.log(JSON.stringify({ + dryRun: true, + envName: options.envName, + deployRoot: config.deployRoot, + seedFileCount: seedFiles.length, + seedFiles, + }, null, 2)); + return; + } + + const stamp = getNowStamp(); + const { archivePath, listPath } = buildConfigSeedArchive(stamp, seedFiles); + const remoteArchive = `${config.incomingDir}/deploy-init-${stamp}.tar.gz`; + + try { + const setupScript = [ + 'set -euo pipefail', + `mkdir -p ${quoteForBash(config.deployRoot)} ${quoteForBash(config.controlDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)} ${quoteForBash(path.posix.join(config.deployRoot, 'logs'))} ${quoteForBash(path.posix.join(config.deployRoot, 'run'))} ${quoteForBash(path.posix.join(config.deployRoot, 'temp'))}`, + ].join('\n'); + runSsh(config, setupScript); + runScp(config, archivePath, remoteArchive); + + const remoteScript = [ + 'set -euo pipefail', + `DEPLOY_ROOT=${quoteForBash(config.deployRoot)}`, + `REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`, + 'CONFIG_DIR="$DEPLOY_ROOT/config"', + 'if [ -d "$CONFIG_DIR" ] && [ "$(find "$CONFIG_DIR" -mindepth 1 -maxdepth 1 | wc -l | tr -d \" \" )" -gt 0 ]; then', + ' echo DEPLOY_INIT_CONFIG_SKIPPED_EXISTS', + 'else', + ' mkdir -p "$CONFIG_DIR"', + ' tar -xzf "$REMOTE_ARCHIVE" -C "$DEPLOY_ROOT"', + ' echo DEPLOY_INIT_CONFIG_CREATED', + 'fi', + 'rm -f "$REMOTE_ARCHIVE"', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }); + for (const line of output.split(/\r?\n/)) { + if (line.trim()) { + console.log(line.trim()); + } + } + } finally { + cleanupLocalTemp([ archivePath, listPath ]); + } + + console.log(`首次发布初始化完成: ${options.envName} -> ${config.deployRoot}`); +} + +main(); \ No newline at end of file diff --git a/script/deploy-lib.cjs b/script/deploy-lib.cjs new file mode 100644 index 0000000..b724435 --- /dev/null +++ b/script/deploy-lib.cjs @@ -0,0 +1,317 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const ROOT = path.resolve(__dirname, '..'); +const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs'); +const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs'); +const DEFAULT_ENV = 'production'; +const DEFAULT_EGG_MINIMAL_INCLUDE_PATHS = [ + 'app.js', + 'app/**', + 'methods/**', + 'native/addons/**', + 'package.json', + 'package-lock.json', +]; +const DEFAULT_POST_DEPLOY_COMMANDS = [ + 'npm install --production', + 'npm run stop || true', + 'npm start', +]; + +function quoteForBash(value) { + return `'${String(value).replace(/'/g, `'"'"'`)}'`; +} + +function runCommand(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd || ROOT, + encoding: 'utf8', + stdio: options.stdio || 'pipe', + shell: false, + }); + + if (result.error) { + throw result.error; + } + + if (result.status !== 0) { + const stderr = (result.stderr || '').trim(); + const stdout = (result.stdout || '').trim(); + throw new Error(stderr || stdout || `${command} exited with code ${result.status}`); + } + + return (result.stdout || '').trim(); +} + +function ensureCommandAvailable(command, installHint) { + const result = spawnSync(command, [], { + cwd: ROOT, + encoding: 'utf8', + stdio: 'pipe', + shell: false, + }); + + if (result.error && result.error.code === 'ENOENT') { + throw new Error(`${command} 不可用。${installHint}`); + } +} + +function getNowStamp() { + const now = new Date(); + const pad = value => String(value).padStart(2, '0'); + return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; +} + +function ensureTempDeployDir() { + const tempDir = path.join(ROOT, 'temp', 'deploy'); + fs.mkdirSync(tempDir, { recursive: true }); + return tempDir; +} + +function isPlaceholder(value) { + if (!value) { + return true; + } + return String(value).includes('__FILL_'); +} + +function normalizeDeployConfig(config, envName) { + const deployRoot = config.deployRoot || '/www/wwwroot/qimen'; + const privateKeyPath = config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : ''; + const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : []; + const preserveDirs = Array.isArray(config.preserveDirs) ? [ ...config.preserveDirs ] : [ 'config' ]; + + if (!preserveDirs.includes('config')) { + preserveDirs.push('config'); + } + + if (!sshOptions.some(option => /^IdentitiesOnly=/i.test(option))) { + sshOptions.push('IdentitiesOnly=yes'); + } + if (!sshOptions.some(option => /^PreferredAuthentications=/i.test(option))) { + sshOptions.push('PreferredAuthentications=publickey'); + } + if (!sshOptions.some(option => /^PubkeyAuthentication=/i.test(option))) { + sshOptions.push('PubkeyAuthentication=yes'); + } + if (!sshOptions.some(option => /^PasswordAuthentication=/i.test(option))) { + sshOptions.push('PasswordAuthentication=no'); + } + if (!sshOptions.some(option => /^KbdInteractiveAuthentication=/i.test(option))) { + sshOptions.push('KbdInteractiveAuthentication=no'); + } + if (!sshOptions.some(option => /^BatchMode=/i.test(option))) { + sshOptions.push('BatchMode=yes'); + } + if (!sshOptions.some(option => /^ConnectTimeout=/i.test(option))) { + sshOptions.push('ConnectTimeout=10'); + } + + const configuredPostDeployCommands = Array.isArray(config.postDeployCommands) && config.postDeployCommands.length > 0 + ? [ ...config.postDeployCommands ] + : [ ...DEFAULT_POST_DEPLOY_COMMANDS ]; + + if (!configuredPostDeployCommands.some(cmd => /^npm\s+install\s+--production(?:\s|$)/i.test(String(cmd).trim()))) { + configuredPostDeployCommands.unshift('npm install --production'); + } + + return { + envName, + host: config.host, + port: Number(config.port || 22), + username: config.username, + privateKeyPath, + deployRoot, + controlDir: `${deployRoot}/.deploy`, + incomingDir: `${deployRoot}/.deploy/incoming`, + backupDir: `${deployRoot}/.deploy/backups`, + stateDir: `${deployRoot}/.deploy/state`, + sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ 'logs', 'run', 'temp' ], + preserveDirs, + keepBackups: Number(config.keepBackups || 5), + preDeployCommands: Array.isArray(config.preDeployCommands) ? config.preDeployCommands : [], + postDeployCommands: configuredPostDeployCommands, + healthCheckUrl: config.healthCheckUrl || '', + deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length > 0 + ? config.deployIncludePaths + : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS, + deployExcludePaths: Array.isArray(config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ], + sshOptions, + }; +} + +function validateDeployConfig(config, configPath, envName) { + if (!config) { + throw new Error(`${configPath} 中未找到 ${envName} 配置。`); + } + + const missing = []; + if (isPlaceholder(config.host)) missing.push('host'); + if (isPlaceholder(config.username)) missing.push('username'); + if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath'); + + if (missing.length > 0) { + throw new Error(`请先完善 SSH 配置字段: ${missing.join(', ')}。配置文件: ${configPath}`); + } + + const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath); + if (!fs.existsSync(resolvedPrivateKeyPath)) { + throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请先修正 config/deploy.config.local.cjs 中的 privateKeyPath。`); + } +} + +function loadDeployConfig(envName = DEFAULT_ENV) { + if (!fs.existsSync(LOCAL_CONFIG_PATH)) { + throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 并填入 SSH 信息。`); + } + + delete require.cache[LOCAL_CONFIG_PATH]; + const loaded = require(LOCAL_CONFIG_PATH); + const config = loaded[envName]; + validateDeployConfig(config, LOCAL_CONFIG_PATH, envName); + return normalizeDeployConfig(config, envName); +} + +function buildSshBaseArgs(config) { + const args = [ '-p', String(config.port), '-i', config.privateKeyPath ]; + for (const option of config.sshOptions) { + args.push('-o', option); + } + return args; +} + +function runSsh(config, remoteScript, options = {}) { + const args = [ + ...buildSshBaseArgs(config), + `${config.username}@${config.host}`, + `bash -lc ${quoteForBash(remoteScript)}`, + ]; + + return runCommand('ssh', args, { + stdio: options.stdio || 'inherit', + }); +} + +function runScp(config, localPath, remotePath) { + const args = [ '-P', String(config.port), '-i', config.privateKeyPath ]; + for (const option of config.sshOptions) { + args.push('-o', option); + } + + args.push( + localPath, + `${config.username}@${config.host}:${remotePath}`, + ); + + return runCommand('scp', args, { stdio: 'inherit' }); +} + +function normalizeRule(rule) { + return String(rule || '').replace(/\\/g, '/').trim(); +} + +function pathMatchesRule(filePath, rule) { + const normalizedPath = String(filePath || '').replace(/\\/g, '/'); + const normalizedRule = normalizeRule(rule); + + if (!normalizedRule) { + return false; + } + if (normalizedRule.endsWith('/**')) { + const prefix = normalizedRule.slice(0, -3); + return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`); + } + if (normalizedRule.endsWith('/')) { + return normalizedPath.startsWith(normalizedRule); + } + return normalizedPath === normalizedRule; +} + +function listDeployableFiles(config) { + 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 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) { + const tempDir = ensureTempDeployDir(); + const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`); + const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`); + const files = listDeployableFiles(config); + + if (files.length === 0) { + throw new Error('git ls-files 未返回可发布文件,无法生成发布包。'); + } + + fs.writeFileSync(listPath, files.join('\n') + '\n', 'utf8'); + runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit' }); + + return { + archivePath, + listPath, + }; +} + +function buildRemoteCleanupGuard(sharedDirs, preserveDirs = []) { + const preserved = [ '.deploy', ...sharedDirs, ...preserveDirs ]; + return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' '); +} + +function buildScopedEggStopScript(deployRoot) { + return [ + `DEPLOY_ROOT=${quoteForBash(deployRoot)}`, + 'find_deploy_master_pids() {', + " ps -eo pid=,args= | awk -v root=\"$DEPLOY_ROOT\" 'index($0, root) && ($2 == \"node\" || $2 ~ /\\/node$/) && index($0, \"start-cluster\") { print $1 }'", + '}', + 'find_deploy_worker_pids() {', + " ps -eo pid=,args= | awk -v root=\"$DEPLOY_ROOT\" 'index($0, root) && ($2 == \"node\" || $2 ~ /\\/node$/) && (index($0, \"egg-cluster/lib/app_worker.js\") || index($0, \"egg-cluster/lib/agent_worker.js\")) { print $1 }'", + '}', + 'MASTER_PIDS="$(find_deploy_master_pids | tr "\\n" " " | xargs 2>/dev/null || true)"', + 'if [ -n "$MASTER_PIDS" ]; then', + ' echo "STOP_CURRENT_DEPLOY_MASTERS $MASTER_PIDS"', + ' kill $MASTER_PIDS || true', + ' sleep 5', + 'fi', + 'WORKER_PIDS="$(find_deploy_worker_pids | tr "\\n" " " | xargs 2>/dev/null || true)"', + 'if [ -n "$WORKER_PIDS" ]; then', + ' echo "STOP_CURRENT_DEPLOY_WORKERS $WORKER_PIDS"', + ' kill -9 $WORKER_PIDS || true', + 'fi', + ].join('\n'); +} + +function serializeCommands(commands) { + return commands + .filter(Boolean) + .map(command => command.trim()) + .filter(Boolean) + .join('\n'); +} + +module.exports = { + ROOT, + buildArchive, + buildRemoteCleanupGuard, + buildScopedEggStopScript, + ensureCommandAvailable, + ensureTempDeployDir, + getNowStamp, + loadDeployConfig, + quoteForBash, + runCommand, + runScp, + runSsh, + serializeCommands, +}; \ No newline at end of file diff --git a/script/deploy-ops.cjs b/script/deploy-ops.cjs new file mode 100644 index 0000000..f91cf2f --- /dev/null +++ b/script/deploy-ops.cjs @@ -0,0 +1,142 @@ +'use strict'; + +const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs'); + +const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]); + +function parseArgs(argv) { + const options = { + envName: 'production', + command: '', + args: [], + }; + + const tokens = [ ...argv ]; + if (tokens.length === 0) { + throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe'); + } + + const first = tokens[0]; + if (!COMMANDS.has(first)) { + options.envName = first; + tokens.shift(); + } + + if (tokens.length === 0) { + throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe'); + } + + options.command = tokens[0]; + options.args = tokens.slice(1); + + if (!COMMANDS.has(options.command)) { + throw new Error(`不支持的命令: ${options.command}`); + } + + return options; +} + +function inspectState(config) { + const latestBackupFile = `${config.stateDir}/latest-backup.txt`; + const remoteScript = [ + 'set -euo pipefail', + `STATE_DIR=${quoteForBash(config.stateDir)}`, + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + `LATEST_FILE=${quoteForBash(latestBackupFile)}`, + 'printf "[STATE]\\n"', + 'ls -la "$STATE_DIR"', + 'printf "\\n[LATEST_BACKUP]\\n"', + 'if [ -f "$LATEST_FILE" ]; then cat "$LATEST_FILE"; else echo MISSING; fi', + 'printf "\\n[BACKUPS]\\n"', + 'ls -1 "$BACKUP_DIR"', + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function smokeRoutes(config) { + const remoteScript = [ + 'set -euo pipefail', + 'for path in / /api/docs /internal/v1/gateway /system; do', + ' if [ "$path" = "/internal/v1/gateway" ] || [ "$path" = "/system" ]; then', + ' code=$(curl -sS -o /dev/null -w "%{http_code}" -X POST "http://127.0.0.1:6060$path" || true)', + ' else', + ' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:6060$path" || true)', + ' fi', + ' printf "%s %s\\n" "$path" "$code"', + 'done', + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function cleanupBackups(config, names) { + if (!names.length) { + throw new Error('cleanup-backups 需要至少一个备份文件名'); + } + + const remoteScript = [ + 'set -euo pipefail', + `BACKUP_DIR=${quoteForBash(config.backupDir)}`, + ...names.map((name, index) => `FILE_${index}=${quoteForBash(name)}`), + ...names.map((_, index) => `if [ -f "$BACKUP_DIR/$FILE_${index}" ]; then rm -f "$BACKUP_DIR/$FILE_${index}"; echo "REMOVED $FILE_${index}"; else echo "MISS $FILE_${index}"; fi`), + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function gatewayProbe(config, methodName, payloadText) { + if (!methodName) { + throw new Error('gateway-probe 需要 method 名称'); + } + + const payload = payloadText && payloadText.trim() ? payloadText : '{}'; + const remoteScript = [ + 'set -euo pipefail', + `METHOD_NAME=${quoteForBash(methodName)}`, + `PAYLOAD=${quoteForBash(payload)}`, + 'timestamp=$(date +%s)', + 'curl -sS -X POST "http://127.0.0.1:6060/internal/v1/gateway?method=$METHOD_NAME&v=1×tamp=$timestamp" -H "Content-Type: text/plain" --data "$PAYLOAD"', + ].join('\n'); + + return runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + const config = loadDeployConfig(options.envName); + + if (options.command === 'inspect') { + console.log(inspectState(config)); + return; + } + + if (options.command === 'smoke') { + console.log(smokeRoutes(config)); + return; + } + + if (options.command === 'verify') { + console.log(inspectState(config)); + console.log(''); + console.log('[SMOKE]'); + console.log(smokeRoutes(config)); + return; + } + + if (options.command === 'cleanup-backups') { + console.log(cleanupBackups(config, options.args)); + return; + } + + if (options.command === 'gateway-probe') { + const methodName = options.args[0]; + const payloadText = options.args[1] || '{}'; + console.log(gatewayProbe(config, methodName, payloadText)); + return; + } + + throw new Error(`不支持的命令: ${options.command}`); +} + +main(); \ No newline at end of file diff --git a/script/deploy-precheck.cjs b/script/deploy-precheck.cjs new file mode 100644 index 0000000..f140c0e --- /dev/null +++ b/script/deploy-precheck.cjs @@ -0,0 +1,57 @@ +'use strict'; + +const { + loadDeployConfig, + runSsh, + ensureCommandAvailable, +} = require('./deploy-lib.cjs'); + +function main() { + try { + [ 'ssh', 'scp', 'tar', 'git' ].forEach(cmd => ensureCommandAvailable(cmd, '')); + console.log('LOCAL_TOOLS_OK'); + + const config = loadDeployConfig('production'); + const remoteScript = [ + 'set -euo pipefail', + `DEPLOY_ROOT=${JSON.stringify(config.deployRoot)}`, + 'PARENT_DIR=$(dirname "$DEPLOY_ROOT")', + 'if [ -d "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_EXISTS; else echo DEPLOY_ROOT_MISSING; fi', + 'if [ -d "$DEPLOY_ROOT" ] && [ -w "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_WRITABLE; else echo DEPLOY_ROOT_NOT_WRITABLE; fi', + 'if [ -d "$DEPLOY_ROOT/config" ]; then echo DEPLOY_CONFIG_EXISTS; else echo DEPLOY_CONFIG_MISSING; fi', + 'if [ -d "$PARENT_DIR" ] && [ -w "$PARENT_DIR" ]; then echo PARENT_WRITABLE; else echo PARENT_NOT_WRITABLE; fi', + 'if command -v node >/dev/null 2>&1; then echo REMOTE_NODE_OK; node -v; else echo REMOTE_NODE_MISSING; fi', + 'if command -v npm >/dev/null 2>&1; then echo REMOTE_NPM_OK; npm -v; else echo REMOTE_NPM_MISSING; fi', + 'if command -v tar >/dev/null 2>&1; then echo REMOTE_TAR_OK; tar --version | head -n 1; else echo REMOTE_TAR_MISSING; fi', + 'if command -v curl >/dev/null 2>&1; then if curl -fsS http://127.0.0.1:6060/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi; else echo REMOTE_CURL_MISSING; fi', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }); + for (const line of output.split(/\r?\n/)) { + if (line.trim()) { + console.log(line.trim()); + } + } + + console.log('PRECHECK_OK'); + } catch (error) { + const message = String(error && error.message ? error.message : ''); + let reason = 'UNKNOWN'; + + if (/Permission denied|Authentication failed/i.test(message)) { + reason = 'AUTH'; + } else if (/Connection timed out|No route to host|Connection refused|Could not resolve hostname/i.test(message)) { + reason = 'NETWORK'; + } else if (/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(message)) { + reason = 'HOST_KEY'; + } else if (/Operation timed out/i.test(message)) { + reason = 'TIMEOUT'; + } + + console.log('PRECHECK_FAIL'); + console.log(`PRECHECK_REASON_${reason}`); + process.exit(1); + } +} + +main(); \ No newline at end of file diff --git a/script/deploy-version.cjs b/script/deploy-version.cjs new file mode 100644 index 0000000..184bad8 --- /dev/null +++ b/script/deploy-version.cjs @@ -0,0 +1,101 @@ +'use strict'; + +const path = require('node:path'); +const { + ensureCommandAvailable, + loadDeployConfig, + quoteForBash, + runSsh, +} = require('./deploy-lib.cjs'); + +function parseArgs(argv) { + const options = { + history: 0, + }; + + for (const item of argv) { + if (!item) continue; + if (item.startsWith('--history=')) { + const value = Number(item.slice('--history='.length)); + if (Number.isFinite(value) && value > 0) { + options.history = Math.floor(value); + } + } + } + + return options; +} + +function queryCurrentRelease(config) { + const releaseFile = path.posix.join(config.stateDir, 'current-release.json'); + const remoteScript = [ + 'set -euo pipefail', + `FILE=${quoteForBash(releaseFile)}`, + 'if [ -f "$FILE" ]; then', + ' cat "$FILE"', + 'else', + ' echo ONLINE_VERSION_NOT_FOUND', + 'fi', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); + if (!output || output === 'ONLINE_VERSION_NOT_FOUND') { + console.log('ONLINE_VERSION_NOT_FOUND'); + return; + } + + try { + const parsed = JSON.parse(output); + console.log(JSON.stringify(parsed, null, 2)); + } catch (error) { + console.log(output); + } +} + +function queryReleaseHistory(config, limit) { + const historyFile = path.posix.join(config.stateDir, 'release-history.jsonl'); + const remoteScript = [ + 'set -euo pipefail', + `FILE=${quoteForBash(historyFile)}`, + `LIMIT=${Number(limit)}`, + 'if [ -f "$FILE" ]; then', + ' tail -n "$LIMIT" "$FILE"', + 'else', + ' echo ONLINE_VERSION_HISTORY_EMPTY', + 'fi', + ].join('\n'); + + const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim(); + if (!output || output === 'ONLINE_VERSION_HISTORY_EMPTY') { + console.log('ONLINE_VERSION_HISTORY_EMPTY'); + return; + } + + const lines = output.split(/\r?\n/).map(item => item.trim()).filter(Boolean); + const records = []; + for (const line of lines) { + try { + records.push(JSON.parse(line)); + } catch (error) { + records.push({ raw: line }); + } + } + console.log(JSON.stringify(records, null, 2)); +} + +function main() { + const envName = process.argv[2] || 'production'; + const options = parseArgs(process.argv.slice(3)); + + ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。'); + + const config = loadDeployConfig(envName); + if (options.history > 0) { + queryReleaseHistory(config, options.history); + return; + } + + queryCurrentRelease(config); +} + +main(); \ No newline at end of file diff --git a/script/git-safety-check.cjs b/script/git-safety-check.cjs new file mode 100644 index 0000000..297dab6 --- /dev/null +++ b/script/git-safety-check.cjs @@ -0,0 +1,48 @@ +'use strict'; + +const path = require('node:path'); +const { runCommand } = require('./deploy-lib.cjs'); + +const BLOCKED_PATH_PATTERNS = [ + /^config\/config\.local\.js$/, + /^config\/deploy\.config\.local\.cjs$/, + /^database\/config\.json$/, + /^temp\/(?!docs\/).+/, + /^logs\//, + /^run\//, + /^versioning\/(?!\.gitkeep$).+/, + /\.pem$/i, + /\.key$/i, + /^\.env(?:\..+)?$/, +]; + +function normalizePath(filePath) { + return filePath.replace(/\\/g, '/'); +} + +function listStagedFiles() { + const output = runCommand('git', [ 'diff', '--cached', '--name-only', '--diff-filter=ACMR' ]); + if (!output) { + return []; + } + return output.split(/\r?\n/).map(item => normalizePath(item.trim())).filter(Boolean); +} + +function main() { + const stagedFiles = listStagedFiles(); + const blocked = stagedFiles.filter(filePath => BLOCKED_PATH_PATTERNS.some(pattern => pattern.test(filePath))); + + if (blocked.length === 0) { + console.log('git safety check passed'); + return; + } + + console.error('以下文件禁止提交到 git,请先取消暂存:'); + for (const filePath of blocked) { + console.error(`- ${filePath}`); + } + console.error('建议使用 git restore --staged 取消暂存,再继续提交。'); + process.exit(1); +} + +main(); \ No newline at end of file diff --git a/script/model-boundary-check.cjs b/script/model-boundary-check.cjs new file mode 100644 index 0000000..98c72dd --- /dev/null +++ b/script/model-boundary-check.cjs @@ -0,0 +1,181 @@ +const fs = require('fs'); +const path = require('path'); + +const ROOT = process.cwd(); +const MODEL_DIR = path.join(ROOT, 'app', 'model'); + +const ALLOWED_HOOKS_BY_FILE = { + 'entry_items.js': new Set([ 'beforeSave', 'beforeUpdate' ]), +}; + +const ALLOWED_SCOPE_FILES = new Set([ 'print_item.js' ]); +const ALLOWED_VIRTUAL_FILES = new Set([]); + +const FORBIDDEN_PATTERNS = [ + { + type: 'forbidden-service-call', + message: '模型层禁止直接调用 service', + regex: /\b(?:ctx|this\.ctx|app|this\.app)\.service\b/, + }, + { + type: 'forbidden-http-call', + message: '模型层禁止外部 HTTP 调用', + regex: /\b(?:ctx|this\.ctx)\.(?:curl|httpclient)\b|\baxios\b|\bfetch\s*\(/, + }, + { + type: 'forbidden-cache-call', + message: '模型层禁止读写 Redis/缓存', + regex: /\b(?:ctx|this\.ctx|app|this\.app)\.redis\b/, + }, + { + type: 'forbidden-cross-model-orchestration', + message: '模型层禁止通过 ctx.model 进行跨模型编排', + regex: /\b(?:ctx|this\.ctx)\.model\./, + }, + { + type: 'forbidden-transaction-control', + message: '模型层禁止定义事务控制逻辑', + regex: /\b(?:sequelize|Sequelize)\.transaction\b|\bbeginTransaction\b|\bcommit\s*\(\s*\)|\brollback\s*\(\s*\)/, + }, +]; + +function listJsFiles(dir) { + if (!fs.existsSync(dir)) return []; + + const files = []; + const entries = fs.readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + const fullPath = path.join(dir, entry.name); + if (entry.isDirectory()) { + files.push(...listJsFiles(fullPath)); + continue; + } + if (entry.isFile() && entry.name.endsWith('.js')) { + files.push(fullPath); + } + } + + return files.sort(); +} + +function normalizeRelPath(filePath) { + return path.relative(ROOT, filePath).replace(/\\/g, '/'); +} + +function isCommentLine(line) { + const trimmed = line.trim(); + return ( + trimmed === '' || + trimmed.startsWith('//') || + trimmed.startsWith('*') || + trimmed.startsWith('/*') || + trimmed.startsWith('*/') + ); +} + +function scanFile(filePath) { + const relPath = normalizeRelPath(filePath); + const fileName = path.basename(filePath); + const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/); + + const violations = []; + const discovered = { + hooks: [], + hasScopes: false, + virtualLines: [], + }; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (isCommentLine(line)) continue; + + for (const rule of FORBIDDEN_PATTERNS) { + if (!rule.regex.test(line)) continue; + violations.push({ + relPath, + line: i + 1, + type: rule.type, + message: rule.message, + content: line.trim(), + }); + } + + const hookMatch = line.match(/\b[A-Za-z_]\w*\.((?:before|after)[A-Z]\w*)\s*\(/); + if (hookMatch) { + const hookName = hookMatch[1]; + discovered.hooks.push({ line: i + 1, hookName }); + + const allowSet = ALLOWED_HOOKS_BY_FILE[fileName]; + if (!allowSet || !allowSet.has(hookName)) { + violations.push({ + relPath, + line: i + 1, + type: 'disallowed-hook', + message: '发现未登记的模型 hook,请先更新 temp/docs/model_boundary_rules.md 与 allowlist', + content: line.trim(), + }); + } + } + + if (/\bscopes\s*:/.test(line)) { + discovered.hasScopes = true; + if (!ALLOWED_SCOPE_FILES.has(fileName)) { + violations.push({ + relPath, + line: i + 1, + type: 'disallowed-scopes', + message: '发现未登记的 scopes 定义,请先更新 temp/docs/model_boundary_rules.md 与 allowlist', + content: line.trim(), + }); + } + } + + if (/DataTypes\.VIRTUAL|\bVIRTUAL\s*\(/.test(line)) { + discovered.virtualLines.push(i + 1); + if (!ALLOWED_VIRTUAL_FILES.has(fileName)) { + violations.push({ + relPath, + line: i + 1, + type: 'disallowed-virtual-field', + message: '发现未登记的 virtual 字段定义,请先更新 temp/docs/model_boundary_rules.md 与 allowlist', + content: line.trim(), + }); + } + } + } + + return { violations, discovered }; +} + +function main() { + const files = listJsFiles(MODEL_DIR); + const allViolations = []; + + let hookCount = 0; + let scopeFileCount = 0; + let virtualCount = 0; + + for (const file of files) { + const { violations, discovered } = scanFile(file); + allViolations.push(...violations); + hookCount += discovered.hooks.length; + if (discovered.hasScopes) scopeFileCount += 1; + virtualCount += discovered.virtualLines.length; + } + + console.log('[MODEL-BOUNDARY] scan finished'); + console.log(`[MODEL-BOUNDARY] files=${files.length}, hooks=${hookCount}, scopeFiles=${scopeFileCount}, virtualLines=${virtualCount}`); + + if (allViolations.length > 0) { + console.error(`[MODEL-BOUNDARY] violations=${allViolations.length}`); + for (const item of allViolations) { + console.error(`- ${item.relPath}:${item.line} [${item.type}] ${item.message}`); + console.error(` ${item.content}`); + } + process.exit(1); + } + + console.log('[MODEL-BOUNDARY] PASS'); +} + +main(); \ No newline at end of file diff --git a/script/setup-git-hooks.cjs b/script/setup-git-hooks.cjs new file mode 100644 index 0000000..7a9e49f --- /dev/null +++ b/script/setup-git-hooks.cjs @@ -0,0 +1,10 @@ +'use strict'; + +const { runCommand } = require('./deploy-lib.cjs'); + +function main() { + runCommand('git', [ 'config', 'core.hooksPath', '.githooks' ], { stdio: 'inherit' }); + console.log('已设置 core.hooksPath=.githooks'); +} + +main(); \ No newline at end of file diff --git a/script/version-history.cjs b/script/version-history.cjs new file mode 100644 index 0000000..112939d --- /dev/null +++ b/script/version-history.cjs @@ -0,0 +1,27 @@ +'use strict'; + +const { readVersionHistory } = require('./version-registry.cjs'); + +function parseLimit(argv) { + for (const item of argv) { + if (item.startsWith('--limit=')) { + const value = Number(item.slice('--limit='.length)); + if (Number.isFinite(value) && value > 0) { + return Math.floor(value); + } + } + } + return 20; +} + +function main() { + const limit = parseLimit(process.argv.slice(2)); + const records = readVersionHistory(limit); + if (records.length === 0) { + console.log('LOCAL_VERSION_HISTORY_EMPTY'); + return; + } + console.log(JSON.stringify(records, null, 2)); +} + +main(); \ No newline at end of file diff --git a/script/version-record.cjs b/script/version-record.cjs new file mode 100644 index 0000000..61ee498 --- /dev/null +++ b/script/version-record.cjs @@ -0,0 +1,24 @@ +'use strict'; + +const { recordVersionUpdate } = require('./version-registry.cjs'); + +function parseArgs(argv) { + let note = ''; + for (const item of argv) { + if (item.startsWith('--note=')) { + note = item.slice('--note='.length).trim(); + } + } + return { note }; +} + +function main() { + const options = parseArgs(process.argv.slice(2)); + const entry = recordVersionUpdate({ + source: 'version:record', + note: options.note || 'package-version-update', + }); + console.log(JSON.stringify(entry, null, 2)); +} + +main(); \ No newline at end of file diff --git a/script/version-registry.cjs b/script/version-registry.cjs new file mode 100644 index 0000000..4f24b83 --- /dev/null +++ b/script/version-registry.cjs @@ -0,0 +1,93 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const { ROOT, runCommand } = require('./deploy-lib.cjs'); + +const VERSION_DIR = path.join(ROOT, 'versioning'); +const VERSION_HISTORY_FILE = path.join(VERSION_DIR, 'package-version-history.jsonl'); +const VERSION_CURRENT_FILE = path.join(VERSION_DIR, 'package-version-current.json'); + +function ensureVersionDir() { + fs.mkdirSync(VERSION_DIR, { recursive: true }); +} + +function getPackageMeta() { + const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')); + const packageVersion = String(pkg.version || '0.0.0'); + + let gitCommit = ''; + let gitCommitShort = ''; + let gitBranch = ''; + try { + gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]); + gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]); + gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]); + } catch (error) { + gitCommit = ''; + gitCommitShort = ''; + gitBranch = ''; + } + + return { + packageVersion, + gitCommit, + gitCommitShort, + gitBranch, + }; +} + +function recordVersionUpdate(options = {}) { + ensureVersionDir(); + + const meta = getPackageMeta(); + const entry = { + recordedAt: new Date().toISOString(), + source: options.source || 'manual', + note: options.note || '', + packageVersion: meta.packageVersion, + gitCommit: meta.gitCommit, + gitCommitShort: meta.gitCommitShort, + gitBranch: meta.gitBranch, + releaseVersion: options.releaseVersion || '', + deployRoot: options.deployRoot || '', + remoteBackupFile: options.remoteBackupFile || '', + remoteStateFile: options.remoteStateFile || '', + remoteHistoryFile: options.remoteHistoryFile || '', + }; + + fs.appendFileSync(VERSION_HISTORY_FILE, `${JSON.stringify(entry)}\n`, 'utf8'); + fs.writeFileSync(VERSION_CURRENT_FILE, `${JSON.stringify(entry, null, 2)}\n`, 'utf8'); + return entry; +} + +function readVersionHistory(limit = 20) { + if (!fs.existsSync(VERSION_HISTORY_FILE)) { + return []; + } + + const lines = fs.readFileSync(VERSION_HISTORY_FILE, 'utf8') + .split(/\r?\n/) + .map(item => item.trim()) + .filter(Boolean); + + const take = Math.max(1, Number(limit || 20)); + const selected = lines.slice(-take); + const records = []; + for (const line of selected) { + try { + records.push(JSON.parse(line)); + } catch (error) { + records.push({ raw: line }); + } + } + return records; +} + +module.exports = { + VERSION_CURRENT_FILE, + VERSION_DIR, + VERSION_HISTORY_FILE, + readVersionHistory, + recordVersionUpdate, +}; \ No newline at end of file diff --git a/METHOD_OUTPUT_REGRESSION_20260322.md b/temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md similarity index 100% rename from METHOD_OUTPUT_REGRESSION_20260322.md rename to temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md diff --git a/SERVICE_API_CHANGE_AUDIT_20260322.md b/temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md similarity index 89% rename from SERVICE_API_CHANGE_AUDIT_20260322.md rename to temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md index 3548ca9..8951049 100644 --- a/SERVICE_API_CHANGE_AUDIT_20260322.md +++ b/temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md @@ -655,7 +655,7 @@ - 无 - 返回结构变化: 无 - 兼容处理: - - 清理前已完成删除前引用复核(service/controller/test/script 全仓扫描) + - 清理前完成删除前引用复核(service/controller/test/script 全仓扫描) - 仅删除静态 helper,不触碰关联定义、字段定义与实例方法 - 删除项: - I18nTranslation.getTranslation / I18nTranslation.batchGetTranslations / I18nTranslation.getProjectTranslations / I18nTranslation.upsertTranslation / I18nTranslation.getUntranslated @@ -670,11 +670,6 @@ - generated regression: 8 passing - smoke: 6 passing - tests: 14 passing -- 回归结果: - - compare: total=8, mismatch=0 - - generated regression: 8 passing - - smoke: 6 passing - - tests: 14 passing ### 2026-03-23 模型能力治理执行(第十八批:阶段 5.2 P1 第一组迁移) @@ -689,14 +684,18 @@ - 无(对外接口参数与返回结构未变化) - 返回结构变化: 无 - 兼容处理: - - 迁移 `EntryOrder.findByOrderCode/findByStatus/getStatsByWarehouse/updateSyncStatus/updateOrderStatus/calculateReceivedQuantities` - - 迁移 `EntryItems.batchUpdateReceived/getOrderProgress` - - `calculateReceivedQuantities` 改为 service 侧显式聚合 `wms_storage`,避免 model 版相关子查询别名不稳定 + - 迁移 EntryOrder.findByOrderCode/findByStatus/getStatsByWarehouse/updateSyncStatus/updateOrderStatus/calculateReceivedQuantities + - 迁移 EntryItems.batchUpdateReceived/getOrderProgress - 验证方式: - node .\script\method-output-regression.cjs compare - node .\script\tmp-generate-method-regression-test.cjs - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 6 passing + - tests: 14 passing ### 2026-03-23 模型能力治理执行(第十九批:阶段 5.2 P1 第二组迁移) @@ -710,10 +709,83 @@ - 无(对外接口参数与返回结构未变化) - 返回结构变化: 无 - 兼容处理: - - 迁移 `Storage.findByStockAndBatch/findBySpace/findAvailableByWarehouse/findExpiringSoon/updateQuantity/lockQuantity/unlockQuantity/allocateQuantity/getStockSummary/getSpaceUsage` - - 模型层仅保留实例行为与关联定义,跨记录聚合与更新能力归并到 service + - 迁移 Storage.findByStockAndBatch/findBySpace/findAvailableByWarehouse/findExpiringSoon/updateQuantity/lockQuantity/unlockQuantity/allocateQuantity/getStockSummary/getSpaceUsage - 验证方式: - node .\script\method-output-regression.cjs compare - node .\script\tmp-generate-method-regression-test.cjs - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js - - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js \ No newline at end of file + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 7 passing + - tests: 15 passing + +### 2026-03-23 模型能力治理执行(第二十批:阶段 5.2 P1 第三组迁移) + +- 修改范围: 将 Role / RolePermission 的权限编排方法迁移到 service,收敛 model 职责 +- 涉及 service/model: + - app/service/systems/auth/role_permission.js + - app/model/role.js + - app/model/role_permission.js +- 上游入口: + - 无直接新增 system/qimen method;属于内部服务能力收敛 +- 更新的 API 文档: + - 无(对外接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 迁移 Role.assignPermissions/getPermissionTree/getPermissionIds + - 迁移 RolePermission.bulkAssign/clearRolePermissions/getRolePermissions/hasPermission +- 验证方式: + - node .\script\method-output-regression.cjs compare + - node .\script\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 7 passing + - tests: 15 passing + +### 2026-03-23 模型能力治理执行(第二十一批:阶段 5.2 P1 第四组迁移) + +- 修改范围: 将 Store 的校验与查询助手方法迁移到 service,收敛 model 职责 +- 涉及 service/model: + - app/service/systems/store.js + - app/model/store.js +- 上游入口: + - 无直接新增 system/qimen method;属于内部服务能力收敛 +- 更新的 API 文档: + - 无(对外接口参数与返回结构未变化) +- 返回结构变化: 无 +- 兼容处理: + - 迁移 Store.validateStoreData/checkCompanyNameExists/findByAccountId/findAllEnabled/findAllWarehouses +- 验证方式: + - node .\script\method-output-regression.cjs compare + - node .\script\tmp-generate-method-regression-test.cjs + - npx egg-bin test temp/generated-tests/system.method-output.generated.test.js + - npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js +- 回归结果: + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 7 passing + - tests: 15 passing + +### 2026-03-23 系统接口兼容修复(第二十二批:project 请求头校验) + +- 修改范围: 修复 system 请求上下文校验对历史 project=wms 请求头的误拒绝 +- 涉及 service: + - app/service/system.js +- 变更内容: + - `ALLOWED_PROJECTS` 增加 `wms/scm/other`,保持与历史调用兼容 +- 触发原因: + - generated regression 与 smoke 在无业务代码变更时统一出现 400(`project 不支持: wms`) +- 验证方式: + - 直接调用 `user.login`(platform=web, project=wms)回归 + - compare + generated regression + smoke 全量重跑 +- 回归结果: + - login: HTTP 200 + - compare: total=8, mismatch=0 + - generated regression: 8 passing + - smoke: 7 passing + - tests: 15 passing \ No newline at end of file diff --git a/association_eager_loading_n_plus_one_guideline.md b/temp/docs/association_eager_loading_n_plus_one_guideline.md similarity index 100% rename from association_eager_loading_n_plus_one_guideline.md rename to temp/docs/association_eager_loading_n_plus_one_guideline.md diff --git a/association_fix_plan.md b/temp/docs/association_fix_plan.md similarity index 100% rename from association_fix_plan.md rename to temp/docs/association_fix_plan.md diff --git a/association_fk_consistency_report.md b/temp/docs/association_fk_consistency_report.md similarity index 100% rename from association_fk_consistency_report.md rename to temp/docs/association_fk_consistency_report.md diff --git a/association_validation_checklist.md b/temp/docs/association_validation_checklist.md similarity index 100% rename from association_validation_checklist.md rename to temp/docs/association_validation_checklist.md diff --git a/migration_execution_plan.md b/temp/docs/migration_execution_plan.md similarity index 100% rename from migration_execution_plan.md rename to temp/docs/migration_execution_plan.md diff --git a/migration_gap_list.md b/temp/docs/migration_gap_list.md similarity index 100% rename from migration_gap_list.md rename to temp/docs/migration_gap_list.md diff --git a/modelList.md b/temp/docs/modelList.md similarity index 100% rename from modelList.md rename to temp/docs/modelList.md diff --git a/model_association_inventory.md b/temp/docs/model_association_inventory.md similarity index 100% rename from model_association_inventory.md rename to temp/docs/model_association_inventory.md diff --git a/temp/docs/model_boundary_rules.md b/temp/docs/model_boundary_rules.md new file mode 100644 index 0000000..c334808 --- /dev/null +++ b/temp/docs/model_boundary_rules.md @@ -0,0 +1,105 @@ +# model_boundary_rules + +更新时间: 2026-03-23 +适用范围: app/model/**/*.js +目标: 约束 model 层仅承担数据映射与轻量领域行为,避免业务编排回流到模型层。 + +## 1. 当前盘点结果(阶段 5.3) + +- hooks: + - app/model/entry_items.js + - EntryItems.beforeSave + - EntryItems.beforeUpdate +- scopes: + - app/model/print_item.js + - tableFields + - groupFields + - active + - byBusiness + - byPlatform +- virtual fields: + - 当前未检出 DataTypes.VIRTUAL / VIRTUAL 字段定义。 + +结论: +- 目前模型层 hooks/scopes 使用量较低,适合在当前阶段一次性固化边界规则。 + +## 2. 模型层职责边界 + +模型层允许: +- 表结构映射(字段、索引、注释、主键、表名映射)。 +- 关联定义(belongsTo/hasMany/hasOne/belongsToMany)与关联语义辅助。 +- 轻量实例行为(如 isEnabled/isExpired/getProgress 等纯实例判断)。 +- 与单行数据一致性相关的同步校验(例如数量非负、上下限关系)。 + +模型层禁止: +- 跨表业务编排(批量流转、聚合统计、分配策略、权限树组装)。 +- 事务边界控制(begin/commit/rollback)与重试策略。 +- 外部副作用(调用第三方接口、写 Redis、发消息、发通知)。 +- 依赖请求上下文(ctx、当前登录人、租户动态鉴权)。 + +## 3. Hooks 规则 + +允许场景: +- 单行数据写入前的确定性校验。 +- 无 I/O 的轻量数据规整(例如 trim、默认值兜底)。 + +禁止场景: +- hook 中查询其他 model 决定业务分支。 +- hook 中进行跨记录批处理或库存/权限编排。 +- hook 中访问 service、http、cache、mq。 + +实现要求: +- 必须保持幂等与可重复执行安全。 +- 必须是低成本逻辑,避免在热路径引入重查询。 +- 错误信息聚焦数据约束,不承载业务流程语义。 + +## 4. Scopes 规则 + +允许场景: +- 静态筛选片段复用(状态、业务类型、平台等)。 +- 参数化但纯查询片段的 where 条件构造。 + +禁止场景: +- 将权限判断或业务流程分支下沉到 scope。 +- 在 scope 中拼装复杂 include 链并耦合排序/分页策略。 +- 在 scope 中引入时间窗口策略或上下文依赖(如当前用户、当前 project)。 + +实现要求: +- scope 输出应稳定、可预期、可独立单测。 +- 命名必须体现过滤语义,不使用模糊命名。 + +## 5. Virtual Fields 规则 + +允许场景: +- 展示层只读衍生值(字段拼接、标签映射、轻量格式化)。 + +禁止场景: +- virtual getter 内进行数据库查询或异步调用。 +- 承载鉴权、状态流转或可写业务语义。 + +实现要求: +- 明确只读语义,不作为持久化字段参与写入。 +- 若需要跨表推导,改由 service 返回 DTO 字段。 + +## 6. 现有代码归属说明 + +- app/model/entry_items.js hooks 保留原因: + - 仅执行已收货数量与计划数量的单行一致性校验。 + - 未引入跨表查询、事务或副作用,符合模型边界。 + +- app/model/print_item.js scopes 保留原因: + - 仅复用静态筛选条件,不承载业务编排。 + - 范围清晰,可作为查询片段复用。 + +## 7. 变更准入清单(新增/修改 model 时必须检查) + +- 是否引入了跨表编排逻辑?若是,必须移至 app/service/systems/*。 +- 是否引入了事务控制?若是,必须移至 service。 +- 是否新增 hook 且包含 I/O?若是,不允许合入。 +- 是否新增 scope 且耦合业务流程/鉴权?若是,不允许合入。 +- 是否新增 virtual 并依赖查询/异步?若是,不允许合入。 + +## 8. 与阶段计划的映射 + +- 阶段 5.3: 已完成(盘点 + 规则固化)。 +- 阶段 5.4: 基于本文件持续执行审查,作为后续模型改动的门禁依据。 \ No newline at end of file diff --git a/model_cleanup_list.md b/temp/docs/model_cleanup_list.md similarity index 58% rename from model_cleanup_list.md rename to temp/docs/model_cleanup_list.md index 84557b6..12f0cf0 100644 --- a/model_cleanup_list.md +++ b/temp/docs/model_cleanup_list.md @@ -1,7 +1,7 @@ # model_cleanup_list 更新时间: 2026-03-23 -阶段: 5.1 识别应迁移到 service 层的方法能力(第一批) +阶段: 5.4 模型边界规则固化与门禁脚本接入(已执行) ## 1. 盘点结论 @@ -104,11 +104,6 @@ - app/model/print_item.js: `getGroupFields`、`getTableConfigs`(已删除) - 门禁结果: compare mismatch=0,generated regression + smoke=14 passing -- 已执行(第二批): - - app/model/i18n_translation.js: `getTranslation`、`batchGetTranslations`、`getProjectTranslations`、`upsertTranslation`、`getUntranslated`(已删除) - - app/model/stock_store.js: `findByItemCode`、`findByStore`(已删除) - - 门禁结果: compare mismatch=0,generated regression=8 passing,smoke=6 passing(合计 14 passing) - - app/model/i18n_translation.js: - getTranslation - batchGetTranslations @@ -131,27 +126,6 @@ 说明: - 上述方法本轮未检出业务层调用,建议先完成一次“删除前引用复核”再执行清理。 -### 3.1 删除前引用复核(第二批) - -- 复核时间: 2026-03-23 -- 复核范围: - - app/model/i18n_translation.js - - app/model/stock_store.js - - app/service/**/*.js - - app/controller/**/*.js - - test/**/*.js - - script/**/*.js -- 复核方式: - - 方法名精确检索: getTranslation / batchGetTranslations / getProjectTranslations / upsertTranslation / getUntranslated / findByItemCode / findByStore - - 模型调用链检索: I18nTranslation.、ctx.model.I18nTranslation.、StockStore.、ctx.model.StockStore. - - 动态调用兜底检索: ['methodName'] 形式 -- 复核结论: - - 未检出 I18nTranslation 5 个候选静态方法的业务调用。 - - 未检出 StockStore 2 个候选静态方法的业务调用。 - - 检出 I18n 相关业务仍直接使用了模型基础能力(findAll/findOne/create/count),不受本次候选方法删除影响。 -- 可执行动作: - - 已执行清理并通过门禁,第二批可删除候选已关闭。 - ## 4. 保留在模型层(P3) 建议保留: @@ -159,14 +133,34 @@ - 纯格式/展示映射(getTypeName/getRoleTypeName/getScopeName)。 - 与关联语义绑定的 include 构造器(StoreWarehouse.buildStoreStockInclude)。 -## 5. 下一步(5.2 输入) +## 5. 阶段状态(截至 2026-03-23) -1. 已完成 P1 第一组迁移:EntryOrder / EntryItems 的 8 个静态方法已迁移到 app/service/systems/entry_order.js,并从 model 删除。 -2. 已完成 P1 第二组迁移:Storage 的 10 个静态方法已迁移到 app/service/systems/storage/index.js,并从 model 删除。 -3. 下一步继续迁移 P1 剩余项:RolePermission / Store。 -4. 最后补 model_boundary_rules.md,固化模型层边界。 +1. 已完成 P1 四组迁移(EntryOrder/EntryItems、Storage、Role/RolePermission、Store)到 service。 +2. 已完成 P2 第二批清理(I18nTranslation / StockStore),并通过门禁。 +3. 已完成 5.3:完成 hooks/scopes/virtual fields 全量盘点并形成规则。 +4. 已完成 5.4:新增可执行门禁脚本并接入 npm/CI。 -## 6. 已执行(P1 第一组) +## 6. 已执行(P2 第二批) + +- 执行时间: 2026-03-23 +- 删除范围: + - app/model/i18n_translation.js + - app/model/stock_store.js +- 删除方法: + - I18nTranslation.getTranslation + - I18nTranslation.batchGetTranslations + - I18nTranslation.getProjectTranslations + - I18nTranslation.upsertTranslation + - I18nTranslation.getUntranslated + - StockStore.findByItemCode + - StockStore.findByStore +- 门禁结果: + - compare mismatch=0 + - generated regression=8 passing + - smoke=6 passing + - tests=14 passing + +## 7. 已执行(P1 第一组) - 执行时间: 2026-03-23 - 迁移范围: @@ -182,16 +176,13 @@ - EntryOrder.calculateReceivedQuantities - EntryItems.batchUpdateReceived - EntryItems.getOrderProgress -- 说明: - - 对外 system/qimen method 未新增接口,属于内部职责收敛。 - - `calculateReceivedQuantities` 在 service 中改为显式查询 Storage 聚合,避免原 model 版本的相关子查询别名漂移风险。 - 门禁结果: - compare mismatch=0 - generated regression=8 passing - smoke=6 passing - tests=14 passing -## 7. 已执行(P1 第二组) +## 8. 已执行(P1 第二组) - 执行时间: 2026-03-23 - 迁移范围: @@ -208,6 +199,94 @@ - Storage.allocateQuantity - Storage.getStockSummary - Storage.getSpaceUsage -- 说明: - - 对外 system/qimen method 未新增接口,属于内部职责收敛。 - - 更新类方法统一进入 service,模型层仅保留实例行为与关联映射。 +- 门禁结果: + - compare mismatch=0 + - generated regression=8 passing + - smoke=7 passing + - tests=15 passing + +## 9. 已执行(P1 第三组) + +- 执行时间: 2026-03-23 +- 迁移范围: + - app/model/role.js + - app/model/role_permission.js + - app/service/systems/auth/role_permission.js +- 迁移方法: + - Role.assignPermissions + - Role.getPermissionTree + - Role.getPermissionIds + - RolePermission.bulkAssign + - RolePermission.clearRolePermissions + - RolePermission.getRolePermissions + - RolePermission.hasPermission +- 门禁结果: + - compare mismatch=0 + - generated regression=8 passing + - smoke=7 passing + - tests=15 passing + +## 10. 已执行(P1 第四组) + +- 执行时间: 2026-03-23 +- 迁移范围: + - app/model/store.js + - app/service/systems/store.js +- 迁移方法: + - Store.validateStoreData + - Store.checkCompanyNameExists + - Store.findByAccountId + - Store.findAllEnabled + - Store.findAllWarehouses +- 门禁结果: + - compare mismatch=0 + - generated regression=8 passing + - smoke=7 passing + - tests=15 passing + +## 11. 已执行(5.3 边界规范) + +- 执行时间: 2026-03-23 +- 扫描范围: + - app/model/**/*.js +- 扫描结果: + - hooks: 2 处(EntryItems.beforeSave / EntryItems.beforeUpdate) + - scopes: 1 处定义(PrintItem.scopes) + - virtual fields: 0 +- 产出文档: + - model_boundary_rules.md +- 执行结论: + - 现有 hooks/scopes 均符合“单行一致性校验/静态筛选片段”边界。 + - 后续新增或修改模型逻辑时,按 model_boundary_rules.md 作为合入门禁。 + +## 12. 已执行(5.4 门禁脚本验证) + +- 执行时间: 2026-03-23 +- 执行命令: + - npm run check:model-boundary +- 结果摘要: + - [MODEL-BOUNDARY] files=45 + - [MODEL-BOUNDARY] hooks=2 + - [MODEL-BOUNDARY] scopeFiles=1 + - [MODEL-BOUNDARY] virtualLines=0 + - [MODEL-BOUNDARY] PASS +- 结论: + - 模型边界检查脚本可稳定执行,已具备本地与 CI 统一门禁能力。 + +## 13. 已执行(5.4 门禁固化) + +- 执行时间: 2026-03-23 +- 新增脚本: + - script/model-boundary-check.cjs +- 覆盖规则: + - 禁止 model 直接调用 service + - 禁止 model 外部 HTTP 调用 + - 禁止 model 读写 Redis/缓存 + - 禁止 model 通过 ctx.model 进行跨模型编排 + - 禁止 model 定义事务控制逻辑 + - hooks/scopes/virtual 使用 allowlist 准入 +- 接入方式: + - npm run check:model-boundary + - npm run ci(已串联) +- 执行结论: + - 模型层边界已具备自动化门禁能力,后续新增越界代码可在本地与 CI 及时阻断。 diff --git a/model_inventory.md b/temp/docs/model_inventory.md similarity index 100% rename from model_inventory.md rename to temp/docs/model_inventory.md diff --git a/model_naming_standard.md b/temp/docs/model_naming_standard.md similarity index 100% rename from model_naming_standard.md rename to temp/docs/model_naming_standard.md diff --git a/model_rename_map.md b/temp/docs/model_rename_map.md similarity index 100% rename from model_rename_map.md rename to temp/docs/model_rename_map.md diff --git a/rename_impact_report.md b/temp/docs/rename_impact_report.md similarity index 100% rename from rename_impact_report.md rename to temp/docs/rename_impact_report.md diff --git a/role_permission_fk_data_cleanup_plan.md b/temp/docs/role_permission_fk_data_cleanup_plan.md similarity index 100% rename from role_permission_fk_data_cleanup_plan.md rename to temp/docs/role_permission_fk_data_cleanup_plan.md diff --git a/rollback_plan.md b/temp/docs/rollback_plan.md similarity index 100% rename from rollback_plan.md rename to temp/docs/rollback_plan.md diff --git a/temp/docs/root-md-usage-report.md b/temp/docs/root-md-usage-report.md new file mode 100644 index 0000000..2c505d2 --- /dev/null +++ b/temp/docs/root-md-usage-report.md @@ -0,0 +1,93 @@ +# 根目录 Markdown 使用方与清理结果 + +生成时间: 2026-03-24 + +## 保留在根目录 + +- `README.md` + - 使用方: `model_todo.txt` + - 动作: 保留(项目入口文档) +- `AI_TOOLBOX.md` + - 使用方: `README.md` + - 动作: 保留(AI 协作工具箱) +- `AI_METHOD_ROUTING.md` + - 使用方: `AI_TOOLBOX.md`, `README.md`, `script/tmp-update-ai-method-routing.cjs` + - 动作: 保留(路由映射主文档) + +## 迁移到 temp/docs(需要保留) + +- `METHOD_OUTPUT_REGRESSION_20260322.md` + - 原使用方: `README.md` + - 新路径: `temp/docs/METHOD_OUTPUT_REGRESSION_20260322.md` +- `SERVICE_API_CHANGE_AUDIT_20260322.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/SERVICE_API_CHANGE_AUDIT_20260322.md` +- `association_eager_loading_n_plus_one_guideline.md` + - 原使用方: `association_validation_checklist.md`, `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md` + - 新路径: `temp/docs/association_eager_loading_n_plus_one_guideline.md` +- `association_fix_plan.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/association_fix_plan.md` +- `association_fk_consistency_report.md` + - 原使用方: `association_validation_checklist.md`, `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md`, `temp/audit-association-fk.cjs` + - 新路径: `temp/docs/association_fk_consistency_report.md` +- `association_validation_checklist.md` + - 原使用方: `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md` + - 新路径: `temp/docs/association_validation_checklist.md` +- `migration_execution_plan.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/migration_execution_plan.md` +- `migration_gap_list.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/migration_gap_list.md` +- `modelList.md` + - 原使用方: `model_todo.txt`, `README.md`, `rename_impact_report.md` + - 新路径: `temp/docs/modelList.md` +- `model_association_inventory.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/model_association_inventory.md` +- `model_boundary_rules.md` + - 原使用方: `model_cleanup_list.md`, `model_todo.txt`, `script/model-boundary-check.cjs` + - 新路径: `temp/docs/model_boundary_rules.md` +- `model_cleanup_list.md` + - 原使用方: `model_todo.txt`, `SERVICE_API_CHANGE_AUDIT_20260322.md` + - 新路径: `temp/docs/model_cleanup_list.md` +- `model_inventory.md` + - 原使用方: `model_rename_map.md`, `model_todo.txt` + - 新路径: `temp/docs/model_inventory.md` +- `model_naming_standard.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/model_naming_standard.md` +- `model_rename_map.md` + - 原使用方: `model_todo.txt`, `rename_impact_report.md` + - 新路径: `temp/docs/model_rename_map.md` +- `rename_impact_report.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/rename_impact_report.md` +- `role_permission_fk_data_cleanup_plan.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/role_permission_fk_data_cleanup_plan.md` +- `rollback_plan.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/rollback_plan.md` +- `schema_model_gap_report.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/schema_model_gap_report.md` +- `table_schema_inventory.md` + - 原使用方: `model_todo.txt` + - 新路径: `temp/docs/table_schema_inventory.md` + +## 已清理(不需要) + +- `tmp-order-schema-workflow.md` + - 原使用方: 无 + - 动作: 已从根目录删除(历史临时流程文档) + +## 引用更新范围 + +- `README.md` +- `model_todo.txt` +- `script/model-boundary-check.cjs` +- `temp/audit-association-fk.cjs` + +所有上述文件中的旧根目录引用已替换为 `temp/docs/*` 新路径。 diff --git a/schema_model_gap_report.md b/temp/docs/schema_model_gap_report.md similarity index 100% rename from schema_model_gap_report.md rename to temp/docs/schema_model_gap_report.md diff --git a/table_schema_inventory.md b/temp/docs/table_schema_inventory.md similarity index 100% rename from table_schema_inventory.md rename to temp/docs/table_schema_inventory.md diff --git a/test/app/controller/system.order.namespaced.test.js b/test/app/controller/system.order.namespaced.test.js index 0822173..f46d91b 100644 --- a/test/app/controller/system.order.namespaced.test.js +++ b/test/app/controller/system.order.namespaced.test.js @@ -140,4 +140,4 @@ describe('test/app/controller/system.order.namespaced.test.js', () => { assert.equal(restoreRes.body.code, 200); assert.equal(restoreRes.body?.data?.inspection_status, originalStatus); }); -}); \ No newline at end of file +}); diff --git a/tmp-order-schema-workflow.md b/tmp-order-schema-workflow.md deleted file mode 100644 index 99c415c..0000000 --- a/tmp-order-schema-workflow.md +++ /dev/null @@ -1,81 +0,0 @@ -# 订单表结构与 Model 比对临时工作流 - -更新时间: 2026-03-22 - -## 1. 目标 - -用于后续排查订单相关问题时,快速复用以下能力: -- 获取数据库订单表结构 -- 与当前 Model 做字段级比对 -- 识别主表/分仓动态表的结构漂移 - -## 2. 本次已确认的订单相关表 - -- wms_entry_order -- wms_order_delivery -- wms_order_delivery_100000 -- wms_order_items -- wms_order_items_100000 - -## 3. 相关 Model - -- app/model/entry_order.js -- app/model/order_delivery.js -- app/model/order_items.js -- app/model/order_delivery_factory.js -- app/model/order_items_factory.js - -## 4. 已生成产物 - -- 结构与差异总结果: temp/tmp-order-schema-compare.json -- 比对脚本(可复跑): script/tmp-compare-order-schema.cjs - -## 5. 关键比对结论 - -### 5.1 wms_entry_order vs entry_order model -- 字段数: model 28 / db 28 -- 结论: 完全一致 - -### 5.2 wms_order_delivery vs order_delivery model -- 字段数: model 72 / db 54 -- model 有但主表 db 没有的字段: - from_key, items, items_count, items_total, items_weight, items_hash, items_crc, wave_id, - post_status, storage_status, pick_status, pack_status, inspection_status, print_status, - claim_status, outbound_status, lock_status, intercept_status -- 结论: 主表结构落后于模型定义 - -补充: -- delivery_time(发货时间) 已在主表与动态表补齐,并同步到 model 与动态建表 SQL。 - -### 5.3 wms_order_items vs order_items model -- 字段数: model 18 / db 15 -- model 有但主表 db 没有的字段: - stock_id, created_at, updated_at -- 结论: 主表结构落后于模型定义 - -### 5.4 动态表 vs 主表 -- wms_order_delivery_100000 相比 wms_order_delivery 多出 18 个字段(与 modelOnly 一致) -- wms_order_items_100000 相比 wms_order_items 多出 3 个字段(与 modelOnly 一致) -- 结论: 动态表更接近当前模型,主表较旧 - -## 6. 复用命令 - -### 6.1 一键重跑比对 -PowerShell: - -node .\script\tmp-compare-order-schema.cjs - -### 6.2 快速查看结果摘要 -PowerShell: - -Get-Content .\temp\tmp-order-schema-compare.json -TotalCount 160 - -## 7. 后续建议 - -1. 若以主表为准,需回退 model 字段定义到主表现状,避免 ORM 读写异常。 -2. 若以模型为准,补充 migration,将主表补齐到动态表同等结构。 -3. 在服务中明确当前读写表策略(主表或动态表),避免混用导致字段可用性不一致。 - -## 8. 备注 - -本文件为临时工作流文件,可在结构收敛后删除或迁移到正式文档。 \ No newline at end of file