Compare commits

...

10 Commits

Author SHA1 Message Date
liufumingren
30f2177f69 feat(stock): 新增库存盘点主表与盘点明细表 2026-09-29 03:50:36 +08:00
liufumingren
6756ba1474 feat(org): 新增组织架构表与模型 2026-09-29 03:50:34 +08:00
liufumingren
67f57f820d fix(order): 拦截请求按取消处理(未同步/手工单)与拦截确认无拣货行补建拦截锁
- batchIntercept/cancelOrderForInterceptRequest: 未同步订单与手工单拦截请求分流为取消处理,释放两层锁;已同步手工单按明细 inbound 回补 stock quantity(stockId 快速路径),取消后两层可用数守恒
- order_storage_allocation 拦截模式: 无拣货行订单补建拦截锁定(quantity/intercept 同增、available=0),写 INTERCEPT_LOCK 流水
- OperationLog 模型字段修正为下划线命名
2026-09-29 03:30:01 +08:00
liufumingren
e17461fe51 feat(scripts): 新增货主组/仓库组角色授权脚本
- scripts/auth/grant-store-up.js:货主侧全部角色批量授权(内置货主管理员角色
  store_admin_default + 各货主自建角色),permissions='*' 通配角色自动跳过
- scripts/auth/grant-wh-up.js:仓库链路角色批量授权(仓库组员工 27 -> 仓库组主管 26
  -> 经理 8),已拥有通配符权限的仓库管理员/超级管理员自动跳过
- 数据库配置按 env 从 config.default.js / config.local.js 加载,无内嵌凭据
- 用法:node scripts/auth/grant-wh-up.js <权限ID> / node scripts/auth/grant-store-up.js <权限ID>
2026-09-28 16:34:10 +08:00
liufumingren
7838e1cf03 fix(order,workbench): 散单称重拦截提示区分打包中状态
- pack_status=padding(打包中)时提示「订单打包中」,其余未完成状态仍提示「订单未打包」
- order_express.buildWeighPackBlockedMessage(packStatus) 恢复入参按状态区分;
  工作台 _assertSingleWeighPackedForWeigh 复用同一文案口径
- 判定规则不变:配置 single_weigh_require_pack 开启、wave_scope 非 1/3、
  pack_status 非 fin 时拒绝称重;团购波次批量称重不校验
- 测试:test/single_weigh_require_pack.test.cjs(27 用例全部通过)
- 文档:methods/system.json 0.3.195 -> 0.3.196,changes 新增 2026.09.28-weigh-pack-padding-message
2026-09-28 16:34:10 +08:00
liufumingren
f8081b876f feat(order.wave): 新增 order.wave.fetchableOrderCount 团购可抓取订单数统计接口
- 与 order.wave.groupOrderFetchList 同口径:同一候选条件(step in [1,2,3]、status!=cancel、
  outbound_status!=padding、intercept_status='none'、lock_status='none'、wave_id=0,叠加
  store_id/shop_name/stock_query 过滤)+ items_hash 粗分组 + 团购阈值过滤;
  仅取 id/items_hash/items/sys_logistics_code 四列做内存计数,不分页、不查订单明细
- 返回 data:group_count / order_count / same_order_quantity / raw_order_count /
  warehouse_id / distinguish_express;仓库上下文缺失返回 flag=failure/code=400
- 口径提示:order_count 为命中分组的订单数合计(与 groupOrderFetchList 的 pagination.total=分组数语义不同);
  include_sku 为 groupOrderFetchList 页内过滤参数,本方法不参与统计
- 权限与日志:已加入 wave.js systemInit 的 _noNeedRight / _noNeedLog / _noNeedAuth 名单
  (与 groupOrderFetchList 一致),仅需登录;不产生 wms_permission 记录,无需权限同步与迁移
- 文档:methods/system.json 新增 order.wave.fetchableOrderCount(根版本 0.3.194 -> 0.3.195、
  updatedAt 2026-09-28),methods/changes/system.json 新增变更记录;AI_METHOD_ROUTING.md 由脚本重新生成 service method 清单
- 测试:test/app/service/systemMethods/order/wave.fetchableOrderCount.test.js(8 用例);
  该路径命中仓库 .gitignore 的 test/* 规则,按既有约定未纳入版本管理
2026-09-28 01:32:03 +08:00
liufumingren
1fbc24c904 chore(deploy): 运维命令收敛为 install/uninstall,移除失效的 deploy:gateway-probe
- watchdog 部署工具只保留 install / uninstall:uninstall 先备份到
  /tmp/qimen-watchdog-uninstall-<时间戳>/(cp -a 保留权限/时间),再**注销调度**
  —— 删除 /etc/cron.d/qimen-watchdog 并清理 root crontab 中残留的 qimen-watchdog 行
  (历史手工安装可能留过,双跑会并发 kill/start 同一实例),随后删除服务器副本
  <部署根>/script/qimen-watchdog.sh 及其 .prev-* / .legacy-* 与历史根目录副本;
  不碰日志、锁文件与接口服务进程;支持 --dry-run 只打印计划。
  原 precheck 的只读环境快照改为 install 开头自动打印;status / dry-run / run
  三个命令删除(需要时直接 ssh 执行 <部署根>/script/qimen-watchdog.sh --dry-run)。
- 移除失效的 deploy:gateway-probe:npm 脚本未传必需的 method 位置参数,而
  gatewayProbe() 在缺参时直接抛错,命令必然 exit 1(CLI 契约与 npm 接线不匹配,
  该命令从未能成功)。删除 npm 命令与 script/deploy-ops.cjs 中的 gatewayProbe 实现;
  需要网关真实探活时直连活跃端口(current.md:v1→6061 / v2→6062)。
- 两份发布 agent 文档中的 "npm run deploy:gateway-probe -- releaseProbe.ping {}"
  已删除 —— 其中的 releaseProbe.ping 这个 method 在应用内并不存在(双重失效),
  改为「直连活跃端口」的说明;README 同步运维命令清单与 watchdog 卸载说明。
- 顺手修掉 script/deploy-ops.cjs 两处历史 lint 问题(模板字符串改单引号、
  文件末尾补换行),该文件 lint 现已干净。
2026-09-28 01:21:55 +08:00
liufumingren
0918f2d572 feat(deploy): 证书同步改为单片段 include + ver 命名 + 声明式自愈与差集下线
- 站点内容外置为单一片段(upstreamInclude,运维维护):生成的 server 块 = 证书骨架 +
  一行 include <片段>,撤掉此前的 customDir 多片段方案;并强制 include 必须是绝对路径
  且文件已存在(nginx 解析相对 include 的基准是 nginx prefix,不是脚本 cwd,写相对路径
  会让 nginx -t 失败并回滚整轮变更),不满足直接 exit 1(dry-run 下仅告警)
- conf 命名加版本位 <domain>-<ver>.conf:轮转只改配置的 ver,旧命名自动清理并 reload
- 声明式对账自愈:证书 / 私钥 / server 块缺失或被改坏,按库内内容原子重建后统一
  nginx -t + reload(内容一致时零写入、零 reload);失败态(sync_status=2)同样参与
  收敛并在校验通过后回到 1;nginx -t / reload 属全局失败,只落 last_sync_error 下轮
  重试,不再把行写成 2 卡死
- 域名下线改为配置差集驱动:以「已配置 + 已验证 + 证书就绪」的期望集合为准(同一仓库
  只取 id 最小的一条),目录中属于本系统命名规则但配置里已无该域名的 conf / 证书直接
  删除并 reload;不再消费 retired_domain(该列仅作应用侧审计留痕)
- 证书未配置的行不写 conf 也不作为文件保留依据(遗留产物由差集回收,避免 conf 引用
  不存在的证书导致 nginx -t 全局失败),行状态回写 sync_status=0 待同步;证书非空但
  非法、域名形态非法才记行级失败(2)
- cert-sync 部署命令瘦身为 install / uninstall;新增 watchdog 部署命令(precheck /
  install / status / dry-run / run),安装路径统一到 script/;deploy-lib 保护生产运行时
  配置不被发布覆盖;README 补「发布与运维」章节(目录硬约定 / 定时任务 / 命令清单)
2026-09-28 01:02:23 +08:00
liufumingren
cb8a4244e5 feat(setting,order,workbench): 新增仓库配置「散单称重是否需要打包」并在散单称重前校验打包状态
- 新增仓库配置 subject_config.single_weigh_require_pack(flag,默认 false=关闭);
  元信息加入 WAREHOUSE_SETTING_FIELDS,默认值与 flag 校验加入 Store.normalizeSubjectConfig
- 称重前置校验:配置开启且订单 wave_scope 非 1(大团购)/3(小团购)、pack_status 非 fin 时拒绝称重,
  统一返回「订单未打包」;订单未命中/仓库上下文缺失/配置读取异常时降级放行,不阻断称重主流程
- 覆盖 order.updateExpressWeighingWeight(订单模式与运单号模式的散单路径,统一挂 _updateSingleOrderWeight)
  与 workbench.sendWeight(复用已查 orderRow,不二次查表);团购波次批量称重不校验
- 新增回归脚本 test/single_weigh_require_pack.test.cjs(26 用例全部通过)
- 同步接口文档 methods/system.json(version 0.3.194)与变更记录 methods/changes/system.json
2026-09-27 16:23:58 +08:00
liufumingren
360e47415b feat(ops): 新增 qimen 接口服务看门狗脚本(5 分钟探活 + 按 deploy 方式自愈)
生产每 5 分钟探活一次当前版本;连续 4 次探活失败则按 script/deploy-remote.cjs 完全相同的
方式恢复:释放目标端口残留进程(kill → sleep 30 → 仍占用则 kill -9 + fuser -k)→
cd <目标版本目录> && nohup bash -lc 'npm start' > /tmp/wms-<ver>-start.log 2>&1 & →
curl -fsS --connect-timeout 2 --max-time 3 健康检查 10 次 × 2s(与 deploy 的 20s 等待窗口一致)。

保活范围取 current.md 与 nginx-upstream.conf 两个来源的并集(去重):发布过程中二者会短暂
不一致,取并集可避免「nginx 实际转发的那个实例挂了却没人管」;两者不一致时打印 WARN。

两个关键设计:
- 探活失败要重试 3 次(共 6 秒)才动作:deploy 先写 current.md、再启动新实例,中间约 3 秒
  空窗,6 秒重试确认正好覆盖,避免看门狗与 deploy 同时启动同一实例;
- 启动前按目录清理孤儿 node 进程:master 被 kill -9 后 worker 会被 init 收养继续运行
  (端口已释放但进程还在),不清就再次启动会出现两份实例 → egg schedule 重复执行
  (重复推送 / 重复回信)。

其它:flock 串行化防重叠;支持 --dry-run 只检活不启动(用于验证);一次运行输出一行、
约 16 KB/天,无需轮转。

系统级定时任务放在 /etc/cron.d/qimen-watchdog 而不是 root crontab —— 宝塔面板会整体重写
root crontab,放那里会被冲掉:
  */5 * * * * root /www/wwwroot/qimen/qimen-watchdog.sh >> /www/wwwlogs/wms/qimen-watchdog.log 2>&1

服务器上的稳定副本位于 deploy 根目录 /www/wwwroot/qimen/qimen-watchdog.sh(不受版本切换与
发布清理影响,发布只清理 v1/v2 目录),本文件是它的源;更新后需重新安装到该路径。
2026-09-27 03:25:20 +08:00
31 changed files with 4565 additions and 1053 deletions

View File

@ -90,8 +90,9 @@ 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 "{}"
# internal gateway 真实探活(无 npm 命令;需要时直连活跃端口)
# 活跃端口读 current.md:v1 → 6061 / v2 → 6062
# ssh <host> 'curl -sS -X POST "http://127.0.0.1:<port>/internal/v1/gateway?method=<method>&v=1&timestamp=$(date +%s)" -H "Content-Type: text/plain" --data "{}"'
# 手动记录一次本地包版本快照
npm run version:record

View File

@ -127,8 +127,9 @@ 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 "{}"
# internal gateway 真实探活(无 npm 命令;需要时直连活跃端口)
# 活跃端口读 current.md:v1 → 6061 / v2 → 6062
# ssh <host> 'curl -sS -X POST "http://127.0.0.1:<port>/internal/v1/gateway?method=<method>&v=1&timestamp=$(date +%s)" -H "Content-Type: text/plain" --data "{}"'
# 手动记录一次本地包版本快照
npm run version:record

File diff suppressed because one or more lines are too long

View File

@ -123,6 +123,76 @@ npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run
- 数据库、Redis、平台配置在对应配置文件中维护
- 敏感信息不要提交到仓库
## 发布与运维(deploy / 证书同步 / 看门狗)
### 部署根布局(生产 `deployRoot` 默认 `/www/wwwroot/qimen`)
```text
<deployRoot>/
├── current.md # 当前活跃版本(v1 | v2)
├── nginx-upstream.conf # 发布时改写:proxy_pass 指向活跃版本端口(v1:6061 / v2:6062)
├── front.conf # 站点内容片段(root / 伪静态),运维维护、脚本绝不覆盖
├── .ssl/ # 证书目录(cron 写入 {store_id}_{domain}.pem|.key,私钥 0600)
├── nginx_config/ # nginx server 块目录(cron 写入 {domain}-<ver>.conf,如 web.wms.gztbyc.com-1.conf)
├── script/
│ ├── warehouse-cert-sync.sh # 证书同步薄包装(cron 每分钟入口)
│ ├── warehouse-cert-sync.cjs # 证书同步主脚本(读库→写证书/conf→nginx -t+reload→回写状态)
│ ├── warehouse-cert-sync.config.prod.json # 生产运行时配置(服务器自管:仅首次放置,永不覆盖)
│ └── qimen-watchdog.sh # 接口服务看门狗(/etc/cron.d 每 5 分钟)
├── database/config.js # 上述脚本自用的 DB 配置(install 时上传)
├── .deploy/ # 发布状态 / 暂存 / 备份
└── v1/ v2/ # 版本实例目录(发布与回退只清理这里)
```
### 目录约定(**硬约定**:只随 `deployRoot` 变,不随版本切换变)
| 用途 | 路径 | 配置来源 |
|------|------|----------|
| 证书 | `<deployRoot>/.ssl` | `script/warehouse-cert-sync.config.prod.json` → `"certDir": "./.ssl"`(开发 `D:/wms/.ssl`) |
| nginx server 块 | `<deployRoot>/nginx_config` | 同上 → `"confDir": "./nginx_config"`(开发 `D:/wms/nginx_config`) |
| 站点内容片段 | `upstreamInclude` 指向的片段文件(生产 `<deployRoot>/front.conf`) | 同上 → `"upstreamInclude"`(**绝对路径**,**运维维护**) |
- 相对路径按 **cwd=部署根** 解析(薄包装先 `cd <deployRoot>`),目录不存在时脚本自动递归创建。
- 这两个目录都在**部署根一级**(非版本目录):发布/回退只清理 `v1|v2`,不会触碰它们。
- **server 块命名含 `-<ver>`**:文件名为 `<domainSafe><suffix>-<ver>.conf`(suffix 仅当域名清洗后与原名不一致时出现),版本键 `ver` 在运行时配置里(`"ver": "1"`),可用 CLI `--ver` / 环境变量 `CERT_SYNC_VER` 临时覆盖;nginx 主配置 `include <deployRoot>/nginx_config/*.conf;` 与新命名兼容,无需改 nginx。
- **每轮声明式对账 + 自愈**:cron 每分钟把库内「期望集合」(domain 非空且已验证)逐行与磁盘核对,证书 / 私钥 / server 块缺失、被改坏或**命名过期**(旧的无后缀命名、旧 `-<ver>`、手工改名)都会自动重建 / 清理后 reload;内容一致时零写入、零 reload。不再只依赖后台“重新上传证书”触发同步。
- **失败态(`sync_status=2`)同样收敛,不是「终态豁免」**:失败行也参与文件层对账——盘上证书 / 私钥 / server 块缺失或与库不一致就按库内容重建,本轮 `nginx -t`/reload 通过后自动回写 `sync_status=1`(日志 `[RECOVER]` / `[RECOVERED]`)。所以「手工删掉 `.ssl`、`nginx_config`」「早期遗留的失败行」都能自动恢复,**无需人工重传证书**。唯一需要人工的情形:库内 `cert_pem`/`cert_key` 为空或非法(无内容可写,日志 `[BLOCKED]`,需在后台上传证书)。
- **nginx 全局失败不写行失败**:`nginx -t` / reload 失败属环境问题(主配置、片段 include、目录),此时待同步行保持 `sync_status=0`、已同步行保持 `1`、失败行保持 `2`,只落 `last_sync_error` 并下一轮自动重试,避免「运维修好配置后行却卡死在 2、必须人工重传证书」。
- **下线 = 配置差集(不需要两阶段切换的额外机制)**:期望集合 = 库内「已配置 + 已验证 + 证书就绪」的行,且**每个仓库只取一条**(同一 `store_id` 多行时按 id 最小者生效,其余行 WARN 后忽略)。`nginx_config/`、`.ssl/` 中属于本系统命名规则、但域名已不在期望集合内的文件会被删除并 reload(日志 `DELETE … 原因=orphan`)。所以**换域名不需要人工下线**:旧域名在提升后已不是该行的 `domain`,下一轮即被清掉;`retired_domain` / `retired_at` 仅作应用侧审计留痕,脚本不读取、不写回。
- **证书没配置就不写配置**:`cert_pem` / `cert_key` 为空的行**不生成** server 块,也不作为文件保留依据(其遗留 conf / 证书会被差集回收——conf 引用不存在的证书会让 `nginx -t` 全局失败),行状态回写 `sync_status=0` 待同步;证书非空但非法(或域名形态非法)才记行级失败(`sync_status=2`)。
- **ver 轮转步骤**:改服务器 `warehouse-cert-sync.config.prod.json` 的 `"ver"`(或临时 `--ver`)→ 下一轮 cron 自动生成新命名 `<domain>-<新ver>.conf`、删除旧命名并 reload;无需清空库、无需重传证书(证书文件名不含 ver,不受影响)。
- **站点内容单一片段**:生成的 server 块 = 证书骨架 + `include <upstreamInclude>;`;站点内容(root / 伪静态 或 反代)统一由 `upstreamInclude` 指向的片段文件提供(生产 `/www/wwwroot/qimen/front.conf`),**由运维维护、脚本绝不覆盖**;前端个性化在运行时由配置接口按域名完成,nginx 侧无需按域名区分站点内容。
- ⚠️ **`upstreamInclude` 必须写绝对路径,且片段文件必须先存在**:nginx 解析 `include` 相对路径的基准是 **nginx prefix**(宝塔为 `/www/server/nginx/conf`),**不是脚本 cwd(部署根)**;写相对路径会让生成的 server 块 include 到不存在的文件 → `nginx -t` 失败 → 整轮变更回滚(连本轮写入的证书一起被当孤儿回收)。脚本启动即校验,不满足直接 `exit 1`(致命退出、不写盘、不改库)。
- **改名/搬迁必须同步三处**:① nginx 主配置的 `include <deployRoot>/nginx_config/*.conf;`;② 服务器上的 `warehouse-cert-sync.config.prod.json`;③ 库表 `wms_warehouse_front_config.cert_path/key_path`(触发一次重同步即可刷新)。
- 安全:`.ssl/` 与 `nginx_config/` 已在 `.gitignore` 忽略,且列入发布默认排除(`deploy-lib.cjs` 的 `DEFAULT_EXCLUDE_PATHS`),私钥不会进仓库或发布包。
### 定时任务
| 任务 | 载体 | 频率 | 入口与日志 |
|------|------|------|-----------|
| 证书/站点配置同步 | root crontab(**宝塔「计划任务」里看不到**,它是直接写入 crontab 的裸命令) | 每分钟(`flock` 锁 `/var/lock/warehouse-cert-sync.lock`) | `<deployRoot>/script/warehouse-cert-sync.sh` → `/var/log/warehouse-cert-sync.log` |
| 接口服务看门狗 | `/etc/cron.d/qimen-watchdog`(**刻意不放 root crontab**:宝塔面板会整体重写 root crontab) | 每 5 分钟 | `<deployRoot>/script/qimen-watchdog.sh` → `/www/wwwlogs/wms/qimen-watchdog.log` |
### 运维命令
```bash
npm run deploy:precheck / deploy:authcheck / deploy:inspect / deploy:smoke / deploy:verify
npm run deploy:version / deploy:version:history / deploy:cleanup-backups
npm run deploy # 发布(= deploy:prod);npm run rollback # 回退
npm run deploy:cert-sync:install / npm run deploy:cert-sync:uninstall
npm run deploy:watchdog:install / npm run deploy:watchdog:uninstall
```
- **部署配置**:`config/deploy.config.local.cjs`(**本地文件、已被 `.gitignore` 忽略**;模板 `config/deploy.config.example.cjs`)。键:`host / port / username / privateKeyPath / deployRoot / sharedDirs / preserveDirs / keepBackups / preDeployCommands / postDeployCommands / healthCheckUrl / deployIncludePaths / deployExcludePaths / sshOptions`;缺省值在 `script/deploy-lib.cjs`。查看归一化后的生效配置:
```bash
node -e "console.log(JSON.stringify(require('./script/deploy-lib.cjs').loadDeployConfig('production'),null,2))"
```
- **证书同步运行时配置**:`script/warehouse-cert-sync.config.prod.json`(生产)/ `.dev.json`(开发)。生产那份是**服务器自管**(`deploy:cert-sync:install` 仅首次放置,之后永不覆盖)——改生产运行参数请在**服务器上**直接改它,改本地仓库无效。
- **安装位置**:`deploy:cert-sync:install` 与 `deploy:watchdog:install` 都装到 `<deployRoot>/script/`;覆盖前会留 `.prev-<时间戳>` 备份,历史根目录副本会被一次性挪成 `<名>.legacy-<时间戳>`。
- **卸载**(`deploy:cert-sync:uninstall`):先备份再删除——备份到服务器 `/tmp/wms-cert-sync-uninstall-<时间戳>/`(`cp -a` 保留权限/时间),删除包装脚本、主脚本、双环境配置、`database/config.js`、历史位置与 `.prev-*`/`.legacy-*` 备份、crontab 中 `warehouse-cert-sync` 行;支持 `--dry-run` 只打印计划。**不删**证书与生成的 server 块(nginx 仍在 include,删了会立断 443,由运维自行决定)、不删 `/var/log/warehouse-cert-sync.log`(默认保留作排查线索)、不碰任何 watchdog 相关文件/任务。
- **卸载(watchdog)**(`deploy:watchdog:uninstall [--dry-run]`):备份到 `/tmp/qimen-watchdog-uninstall-<时间戳>/` 后**注销调度**——删除 `/etc/cron.d/qimen-watchdog`,并清理 root crontab 中残留的 `qimen-watchdog` 行(历史手工安装可能留过,双跑会并发 kill/start 同一实例);再删除服务器副本 `<deployRoot>/script/qimen-watchdog.sh`(含 `.prev-*` / `.legacy-*` 与历史根目录副本)。**不删** `/www/wwwlogs/wms/qimen-watchdog.log`(留作排查线索)、锁文件与接口服务进程;`deploy:watchdog:install` 会先只读打印一份目标机环境快照。
- **运行期手动排查**:仍可直接执行服务器上的 `<deployRoot>/script/warehouse-cert-sync.sh --dry-run`(主脚本 CLI 不变:`--cleanup-only --dry-run` / `--cleanup-only` / `--env production`)。
## 功能模块
- 多快递平台对接(快手/PolyAPI 等)

170
app/model/org_unit.js Normal file
View File

@ -0,0 +1,170 @@
'use strict';
module.exports = app => {
const { BIGINT, STRING, DATE, TINYINT, INTEGER, JSON: JSON_TYPE } = app.Sequelize;
const OrgUnit = app.model.define('org_unit', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '所属仓库ID,关联 wms_store.id',
},
parent_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '父部门ID,NULL=根部门;必须与 warehouse_id 同仓',
},
name: {
type: STRING(100),
allowNull: false,
comment: '部门名称',
},
code: {
type: STRING(50),
allowNull: true,
comment: '部门编码(仓库内唯一)',
},
leader_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '部门管理员账号ID,关联 wms_account.id',
},
admin_role_ids: {
type: JSON_TYPE,
allowNull: true,
comment: '管理员默认角色集,关联 wms_role.id,如 [3,8];任命管理员时自动分配',
},
default_role_ids: {
type: JSON_TYPE,
allowNull: true,
comment: '部门默认角色集,关联 wms_role.id,如 [3,8];成员入职挂本部门时自动分配',
},
path: {
type: STRING(500),
allowNull: true,
comment: '层级路径,如 /1/5/9/(根部门为 /{id}/),用于一次查询整棵子树',
},
sort: {
type: INTEGER,
allowNull: false,
defaultValue: 0,
comment: '同级排序,越小越靠前',
},
status: {
type: TINYINT,
allowNull: false,
defaultValue: 1,
comment: '状态:0-停用 1-启用',
},
created_at: {
type: DATE,
allowNull: false,
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '软删除时间',
},
}, {
tableName: 'wms_org_unit',
freezeTableName: true,
underscored: true,
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: true,
deletedAt: 'deleted_at',
comment: '组织架构表(部门/子部门层级、部门管理员、管理员与成员默认角色)',
indexes: [
{
name: 'idx_warehouse_parent',
fields: [ 'warehouse_id', 'parent_id' ],
},
{
name: 'idx_parent_id',
fields: [ 'parent_id' ],
},
{
name: 'uk_warehouse_code',
unique: true,
fields: [ 'warehouse_id', 'code' ],
},
{
name: 'idx_path',
fields: [ 'path' ],
},
{
name: 'idx_status',
fields: [ 'status' ],
},
],
});
// 关联关系
OrgUnit.associate = function() {
const { Account, Store } = app.model;
// 所属仓库
OrgUnit.belongsTo(Store, {
foreignKey: 'warehouse_id',
targetKey: 'id',
as: 'warehouse',
});
// 部门管理员
OrgUnit.belongsTo(Account, {
foreignKey: 'leader_id',
targetKey: 'id',
as: 'leader',
});
// 上级部门
OrgUnit.belongsTo(OrgUnit, {
foreignKey: 'parent_id',
targetKey: 'id',
as: 'parent',
});
// 下级部门
OrgUnit.hasMany(OrgUnit, {
foreignKey: 'parent_id',
sourceKey: 'id',
as: 'children',
});
};
// 实例方法:是否根部门
OrgUnit.prototype.isRoot = function() {
return !this.parent_id;
};
// 实例方法:是否启用
OrgUnit.prototype.isEnabled = function() {
return this.status === 1;
};
// 实例方法:管理员默认角色ID列表
OrgUnit.prototype.getAdminRoleIds = function() {
return this.admin_role_ids || [];
};
// 实例方法:部门默认角色ID列表(成员入职自动分配)
OrgUnit.prototype.getDefaultRoleIds = function() {
return this.default_role_ids || [];
};
return OrgUnit;
};

141
app/model/stock_check.js Normal file
View File

@ -0,0 +1,141 @@
'use strict';
/**
* 库存盘点主表模型。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = app.Sequelize;
const StockCheck = app.model.define('wms_stock_check', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(数据隔离维度)',
},
check_no: {
type: STRING(50),
allowNull: false,
comment: '盘点单号,唯一,生成规则:PD+YYYYMMDD+6位序号',
},
title: {
type: STRING(200),
allowNull: true,
comment: '盘点名称/主题,非必填',
},
type: {
type: STRING(20),
allowNull: false,
defaultValue: 'all',
comment: '盘点范围类型:all=全盘,store=按货主,goods=按商品,location=按库位',
},
mode: {
type: STRING(20),
allowNull: false,
defaultValue: 'open',
comment: '盘点方式:open=明盘(可见账面数量),blind=盲盘(不可见账面数量)',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID,按货主盘点时必填(type=store)',
},
scope_snapshot: {
type: JSON_TYPE,
allowNull: true,
comment: '盘点范围条件快照(JSON),如商品ID列表/库位ID列表,供盘点对比与追溯',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'pending',
comment: '盘点状态:pending=待盘点,in_progress=盘点中,checked=已盘待确认,confirmed=已确认,completed=已完成,cancelled=已取消',
},
detail_status: {
type: STRING(30),
allowNull: false,
defaultValue: 'none_checked',
comment: '明细盘点进度:none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘',
},
check_date: {
type: DATE,
allowNull: false,
comment: '盘点日期',
},
start_time: {
type: DATE,
allowNull: true,
comment: '实际开始时间',
},
end_time: {
type: DATE,
allowNull: true,
comment: '实际结束时间',
},
creator_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '创建人账户ID',
},
creator_name: {
type: STRING(50),
allowNull: true,
comment: '创建人名称快照',
},
total_items: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '明细行数(盘点任务总行数)',
},
checked_items: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '已盘行数',
},
diff_items: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '差异行数(账面与实盘不一致的行数)',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
}, {
tableName: 'wms_stock_check',
comment: '库存盘点主表',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: false,
indexes: [
{ name: 'uk_check_no', unique: true, fields: [ 'check_no' ] },
{ name: 'idx_warehouse_check_date', fields: [ 'warehouse_id', 'check_date' ] },
{ name: 'idx_warehouse_status', fields: [ 'warehouse_id', 'status' ] },
{ name: 'idx_store_id', fields: [ 'store_id' ] },
{ name: 'idx_creator_id', fields: [ 'creator_id' ] },
],
});
StockCheck.associate = function() {
const { StockCheckDetail } = app.model;
// 一个盘点单对应多条盘点明细
StockCheck.hasMany(StockCheckDetail, {
foreignKey: 'check_id',
as: 'details',
});
};
return StockCheck;
};

View File

@ -0,0 +1,142 @@
'use strict';
/**
* 库存盘点明细表模型。
* @param {import('egg').Application} app Egg 应用实例。
* @return {import('sequelize').ModelCtor<import('sequelize').Model>} Sequelize 模型。
*/
module.exports = app => {
const { BIGINT, STRING, INTEGER, DATE, TINYINT } = app.Sequelize;
const StockCheckDetail = app.model.define('wms_stock_check_detail', {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
comment: '主键',
},
check_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联盘点主表 wms_stock_check.id',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(冗余,隔离查询)',
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '库存商品ID,关联 wms_stock_warehouse.id',
},
location_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库位ID,关联 wms_location_space.id;无库位商品为空',
},
location_code: {
type: STRING(50),
allowNull: true,
comment: '库位编码快照(space_code)',
},
item_code: {
type: STRING(50),
allowNull: false,
comment: '商品编码快照',
},
item_name: {
type: STRING(255),
allowNull: true,
comment: '商品名称快照',
},
spec: {
type: STRING(100),
allowNull: true,
comment: '规格快照(sku_property)',
},
batch_no: {
type: STRING(100),
allowNull: true,
comment: '批次号,批次管理商品时记录',
},
system_quantity: {
type: INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '账面数量(生成盘点任务时的系统库存快照)',
},
check_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '实盘数量;未盘点时为空',
},
diff_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '差异数量 = 实盘数量 - 账面数量;正数盘盈,负数盘亏;未盘点时为空',
},
is_diff: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否有差异:1=有差异,0=无差异',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'unchecked',
comment: '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认',
},
checker_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '盘点人账户ID',
},
checker_name: {
type: STRING(50),
allowNull: true,
comment: '盘点人名称快照',
},
checked_at: {
type: DATE,
allowNull: true,
comment: '盘点时间',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注(如差异原因说明)',
},
}, {
tableName: 'wms_stock_check_detail',
comment: '库存盘点明细表',
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: false,
indexes: [
{ name: 'idx_check_id', fields: [ 'check_id' ] },
{ name: 'idx_warehouse_stock', fields: [ 'warehouse_id', 'stock_id' ] },
{ name: 'idx_stock_id', fields: [ 'stock_id' ] },
{ name: 'idx_location_id', fields: [ 'location_id' ] },
{ name: 'idx_is_diff', fields: [ 'is_diff' ] },
],
});
StockCheckDetail.associate = function() {
const { StockCheck, StockWarehouse } = app.model;
// 关联盘点主表
StockCheckDetail.belongsTo(StockCheck, {
foreignKey: 'check_id',
as: 'check',
});
// 关联库存商品
StockCheckDetail.belongsTo(StockWarehouse, {
foreignKey: 'stock_id',
as: 'stockWarehouse',
});
};
return StockCheckDetail;
};

View File

@ -97,6 +97,7 @@ module.exports = app => {
single_order_pack_max_minutes: 3,
group_order_pack_max_minutes: 40,
big_group_pack_coefficient: 3,
single_weigh_require_pack: false,
return_unpack_max_record_minutes: 5,
inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES,
auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES,
@ -531,6 +532,14 @@ module.exports = app => {
normalized.big_group_pack_coefficient = bigGroupPackCoefficient;
}
// 散单称重是否需要打包:默认关闭(未配置的仓库不校验打包状态)
if (Object.prototype.hasOwnProperty.call(parsed, 'single_weigh_require_pack')) {
normalized.single_weigh_require_pack = normalizeBooleanFlag(
parsed.single_weigh_require_pack,
'subject_config.single_weigh_require_pack'
);
}
const rawReturnUnpackMaxRecordMinutes = parsed.return_unpack_max_record_minutes;
if (rawReturnUnpackMaxRecordMinutes === undefined || rawReturnUnpackMaxRecordMinutes === null || rawReturnUnpackMaxRecordMinutes === '') {
normalized.return_unpack_max_record_minutes = DEFAULT_SUBJECT_CONFIG.return_unpack_max_record_minutes;

View File

@ -30,6 +30,119 @@ function shouldSkipWorkOrder(ctx) {
return !!(ctx && ctx.inboxContext && ctx.inboxContext.skip_work_order === true);
}
/**
* 拦截请求按取消订单处理(未同步订单/手工单规则):
* 订单状态置 cancel,释放 stock 建单锁与 storage 储位锁,不写拦截状态。
* 已同步订单(sync=fin)取消时按订单明细回补 stock quantity(同步出库冲回),
* 保证取消后两层可用数守恒。
* 整体在一个事务内执行,失败回滚并告警,不阻断主流程。
*
* @param {Object} ctx Egg 上下文。
* @param {Object} orderModel 当前仓库订单模型。
* @param {number|string} warehouseId 仓库ID。
* @param {Array<number>} orderIds 订单ID数组。
* @param {Array<number>} syncedOrderIds 其中已同步的订单ID(取消时需回补 stock quantity)。
* @param {Object} operator 操作人信息({ id, name })。
* @return {Promise<void>}
*/
async function cancelOrderForInterceptRequest(ctx, orderModel, warehouseId, orderIds, syncedOrderIds, operator) {
if (!Array.isArray(orderIds) || orderIds.length === 0) {
return;
}
const syncedIds = Array.isArray(syncedOrderIds) ? syncedOrderIds.map(id => Number(id)).filter(id => Number.isInteger(id) && id > 0) : [];
const now = new Date();
const transaction = await ctx.model.transaction();
try {
await orderModel.update(
{ status: 'cancel', step: 9, outbound_status: 'padding', updated_at: now },
{ where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, warehouse_id: warehouseId }, transaction }
);
// 释放储位分配(普通模式:解除锁定/返还实物)
await ctx.service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: orderIds,
transaction,
});
// 释放 stock 建单锁(仅未同步订单:已同步订单的建单锁已在同步出库时释放)
const unsyncedIds = orderIds
.map(id => Number(id))
.filter(id => Number.isInteger(id) && id > 0 && !syncedIds.includes(id));
if (unsyncedIds.length > 0) {
await ctx.service.systemMethods.order.pendingOrder.releaseCreationLockForCancel({
orderIds: unsyncedIds,
warehouseId,
transaction,
});
}
// 已同步订单:回补 stock quantity(同步出库冲回,货物回可用)
if (syncedIds.length > 0) {
const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const cancelOrderItems = await orderItemsModel.findAll({
where: { order_id: { [ctx.app.Sequelize.Op.in]: syncedIds } },
attributes: [ 'order_id', 'stock_id', 'plan_qty' ],
raw: true,
transaction,
});
for (const item of Array.isArray(cancelOrderItems) ? cancelOrderItems : []) {
const stockId = Number(item && item.stock_id) || 0;
const qty = Number(item && item.plan_qty) || 0;
if (stockId <= 0 || qty <= 0) {
continue;
}
const inboundResult = await ctx.service.systems.stockStore.inbound(
stockId,
qty,
transaction,
{ stockId }
);
if (!inboundResult || inboundResult.success !== true) {
throw new Error(
`未同步/手工单取消回补库存失败: stockId=${stockId}, qty=${qty}, ${(inboundResult && inboundResult.error) || '未知错误'}`
);
}
}
}
await transaction.commit();
} catch (error) {
await transaction.rollback().catch(() => {});
ctx.logger.warn(`[inbox functions] 未同步/手工单按取消处理失败: ${error.message}`);
return;
}
// 写入操作日志(失败不影响主流程)
try {
const logSvc = ctx.service?.systems?.operationLog;
if (logSvc && typeof logSvc.createOperationLogs === 'function') {
await logSvc.createOperationLogs(
orderIds.map(orderId => ({
businessType: 'order',
businessId: String(orderId),
operationCode: 'ORDER_INTERCEPT_REQUEST_CANCELED',
operator: operator || { id: '0', name: 'AI系统' },
extras: {
warehouseId,
orderId,
message: syncedIds.includes(Number(orderId))
? '已同步手工单拦截请求按取消订单处理(库存已回补)'
: '未同步订单拦截请求按取消订单处理',
externalLogType: 'NONE',
},
}))
);
}
} catch (logErr) {
ctx.logger.warn(`[inbox functions] 未同步/手工单按取消处理-操作日志失败: ${logErr.message}`);
}
ctx.logger.info(`[inbox functions] 未同步/手工单按取消处理: ${orderIds.length} 个订单`);
}
/**
* 站内信函数注册表。
* 负责注册 AI 可调用的函数(含 handler),支持按分组声明可见性。
@ -1102,7 +1215,7 @@ class InboxFunctionsService extends Service {
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
if (orderModel) {
const orders = await orderModel.findAll({
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time' ],
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time', 'sync_status', 'create_channel' ],
where: {
id: { [ctx.app.Sequelize.Op.in]: orderIds },
step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] },
@ -1124,6 +1237,9 @@ class InboxFunctionsService extends Service {
}
const interceptOrderIds = [];
// 未同步订单/手工单:拦截请求按取消订单处理(释放两层锁,不走拦截)
const cancelHandledOrderIds = [];
const syncedCancelOrderIds = [];
const kickOutOrderIds = [];
// 批量查询散单的称重状态(wms_order_express.weighing_weight)
@ -1164,7 +1280,16 @@ class InboxFunctionsService extends Service {
}
if (needIntercept) {
interceptOrderIds.push(orderId);
const isManualOrder = String(order.create_channel || '').trim().toUpperCase() === 'MANUAL';
const isUnsyncedOrder = String(order.sync_status || '').trim() !== 'fin';
if (isManualOrder || isUnsyncedOrder) {
cancelHandledOrderIds.push(orderId);
if (!isUnsyncedOrder) {
syncedCancelOrderIds.push(orderId);
}
} else {
interceptOrderIds.push(orderId);
}
}
// 规则2:有波次且未打印
@ -1222,6 +1347,18 @@ class InboxFunctionsService extends Service {
);
}
// 未同步/手工单:拦截请求按取消订单处理(释放两层锁)
if (cancelHandledOrderIds.length > 0) {
await cancelOrderForInterceptRequest(
ctx,
orderModel,
warehouseId,
cancelHandledOrderIds,
syncedCancelOrderIds,
{ id: '0', name: groupName || 'AI系统' }
);
}
// 执行踢出波次
if (kickOutOrderIds.length > 0) {
await ctx.service.systemMethods.order.wave.batchRemoveOrders({
@ -1986,7 +2123,7 @@ class InboxFunctionsService extends Service {
const orderModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
if (orderModel) {
const orders = await orderModel.findAll({
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time' ],
attributes: [ 'id', 'step', 'wave_id', 'inspection_status', 'intercept_time', 'sync_status', 'create_channel' ],
where: { id: { [ctx.app.Sequelize.Op.in]: orderIds }, step: { [ctx.app.Sequelize.Op.in]: [ 1, 2, 3 ] } },
raw: true,
});
@ -2001,6 +2138,9 @@ class InboxFunctionsService extends Service {
waveMap = Object.fromEntries(waves.map(w => [ w.wave_id, w ]));
}
const interceptOrderIds = [];
// 未同步订单/手工单:拦截请求按取消订单处理(释放两层锁,不走拦截)
const cancelHandledOrderIds = [];
const syncedCancelOrderIds = [];
// 批量查询散单的称重状态
const scatterIds = orders
.filter(o => o.wave_id > 0 && waveMap[o.wave_id] && waveMap[o.wave_id].wave_type === 2)
@ -2028,7 +2168,18 @@ class InboxFunctionsService extends Service {
} else {
needIntercept = true;
}
if (needIntercept) interceptOrderIds.push(order.id);
if (needIntercept) {
const isManualOrder = String(order.create_channel || '').trim().toUpperCase() === 'MANUAL';
const isUnsyncedOrder = String(order.sync_status || '').trim() !== 'fin';
if (isManualOrder || isUnsyncedOrder) {
cancelHandledOrderIds.push(order.id);
if (!isUnsyncedOrder) {
syncedCancelOrderIds.push(order.id);
}
} else {
interceptOrderIds.push(order.id);
}
}
}
if (interceptOrderIds.length > 0) {
const noticeNow = new Date();
@ -2069,6 +2220,18 @@ class InboxFunctionsService extends Service {
}
ctx.logger.info(`[inbox functions] 取消拦截-设置拦截状态: ${interceptOrderIds.length} 个订单`);
}
// 未同步/手工单:拦截请求按取消订单处理(释放两层锁)
if (cancelHandledOrderIds.length > 0) {
await cancelOrderForInterceptRequest(
ctx,
orderModel,
warehouseId,
cancelHandledOrderIds,
syncedCancelOrderIds,
{ id: '0', name: groupName || 'AI系统' }
);
}
}
}
} catch (e) {

View File

@ -4670,7 +4670,7 @@ class PendingOrderService extends OrderBaseService {
}
const orderRows = await orderModel.findAll({
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'wave_id', 'inspection_status', 'intercept_time' ],
attributes: [ 'id', 'delivery_order_code', 'pre_delivery_order_code', 'wave_id', 'inspection_status', 'intercept_time', 'sync_status', 'create_channel' ],
where: {
warehouse_id: warehouseId,
id: {
@ -4714,8 +4714,22 @@ class PendingOrderService extends OrderBaseService {
}
}
// 未同步订单与手工单不发起拦截,默认按取消订单处理:
// 释放 stock 建单锁与 storage 储位锁,不走常规拦截(不迁移拦截锁)
const cancelHandledOrderRows = [];
const interceptTargetRows = [];
for (const row of eligibleOrderRows) {
const isManualOrder = String(row.create_channel || '').trim().toUpperCase() === 'MANUAL';
const isUnsyncedOrder = String(row.sync_status || '').trim() !== 'fin';
if (isManualOrder || isUnsyncedOrder) {
cancelHandledOrderRows.push(row);
} else {
interceptTargetRows.push(row);
}
}
const normalizedOrderRows = Array.isArray(validOrderRows) ? validOrderRows : [];
const eligibleOrderCount = eligibleOrderRows.length;
const eligibleOrderCount = interceptTargetRows.length;
const totalOrderCount = orderIds.length;
const validOrderCount = normalizedOrderRows.length;
@ -4746,10 +4760,141 @@ class PendingOrderService extends OrderBaseService {
return;
}
// 分批更新拦截状态,每批最多500条(仅处理未命中「已复核/已称重」前置校验的订单)
const cancelledOrderIds = [];
const UPDATE_CHUNK_SIZE = 500;
for (let i = 0; i < eligibleOrderRows.length; i += UPDATE_CHUNK_SIZE) {
const chunkRows = eligibleOrderRows.slice(i, i + UPDATE_CHUNK_SIZE);
// ── 未同步/手工单:按取消订单处理(状态置 cancel + 释放两层锁,不走拦截) ──
// 已同步订单(stock 层已同步出库)取消时按订单明细回补 stock quantity,
// 保证取消后两层可用数守恒(storage 锁释放、stock 数量冲回)
if (cancelHandledOrderRows.length > 0) {
const cancelIds = cancelHandledOrderRows.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
const now = new Date();
for (let i = 0; i < cancelIds.length; i += UPDATE_CHUNK_SIZE) {
const chunkCancelIds = cancelIds.slice(i, i + UPDATE_CHUNK_SIZE);
if (chunkCancelIds.length === 0) {
continue;
}
const chunkRows = cancelHandledOrderRows.filter(row => chunkCancelIds.includes(Number(row.id)));
const syncedCancelIds = chunkRows
.filter(row => String(row.sync_status || '').trim() === 'fin')
.map(row => Number(row.id));
const unsyncedCancelIds = chunkCancelIds.filter(id => !syncedCancelIds.includes(id));
const cancelTransaction = await this.ctx.model.transaction();
try {
await orderModel.update(
{ status: 'cancel', step: 9, outbound_status: 'padding', updated_at: now },
{ where: { id: { [Op.in]: chunkCancelIds }, warehouse_id: warehouseId }, transaction: cancelTransaction }
);
// 释放储位分配(普通模式:解除锁定/返还实物)
const originalUser = ctx.user;
ctx.user = originalUser
? { ...originalUser, store_id: warehouseId }
: { store_id: warehouseId };
try {
await this.service.systems.orderStorageAllocation.cancelAllocateStorage({
order_ids: chunkCancelIds,
transaction: cancelTransaction,
});
} finally {
ctx.user = originalUser;
}
// 释放 stock 建单锁(仅未同步订单:已同步订单的建单锁已在同步出库时释放)
if (unsyncedCancelIds.length > 0) {
await this.releaseCreationLockForCancel({
orderIds: unsyncedCancelIds,
warehouseId,
transaction: cancelTransaction,
});
}
// 已同步订单:回补 stock quantity(同步出库冲回,货物回可用)
if (syncedCancelIds.length > 0) {
const orderItemsModel = await this.ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const cancelOrderItems = await orderItemsModel.findAll({
where: { order_id: { [Op.in]: syncedCancelIds } },
attributes: [ 'stock_id', 'plan_qty' ],
raw: true,
transaction: cancelTransaction,
});
// 回补依赖 ctx.user.store_id 写流水,任务执行时上下文可能已失效,临时注入
const inboundOriginalUser = ctx.user;
ctx.user = inboundOriginalUser
? { ...inboundOriginalUser, store_id: warehouseId }
: { store_id: warehouseId };
for (const item of Array.isArray(cancelOrderItems) ? cancelOrderItems : []) {
const stockId = Number(item && item.stock_id) || 0;
const qty = Number(item && item.plan_qty) || 0;
if (stockId <= 0 || qty <= 0) {
continue;
}
const inboundResult = await this.ctx.service.systems.stockStore.inbound(
stockId,
qty,
cancelTransaction,
{ stockId }
);
if (!inboundResult || inboundResult.success !== true) {
throw new Error(
`未同步/手工单取消回补库存失败: stockId=${stockId}, qty=${qty}, ${(inboundResult && inboundResult.error) || '未知错误'}`
);
}
}
ctx.user = inboundOriginalUser;
}
await cancelTransaction.commit();
} catch (cancelErr) {
await cancelTransaction.rollback().catch(() => {});
ctx.logger.warn(
`[order.pendingOrder.batchIntercept] 未同步/手工单取消失败, ids=${chunkCancelIds.join(',')}, error=${cancelErr.message}`
);
continue;
}
cancelledOrderIds.push(...chunkCancelIds);
// 写入操作日志(失败不影响主流程)
try {
const cancelLogRows = chunkRows
.map(row => {
const orderId = Number(row.id || 0);
const isSynced = String(row.sync_status || '').trim() === 'fin';
return {
business_type: 'order',
business_id: String(orderId),
operation_code: 'ORDER_INTERCEPT_REQUEST_CANCELED',
operator_id: operator && operator.id != null ? String(operator.id) : null,
operator_name: operator && operator.name ? String(operator.name) : 'system',
external_log_type: 'NONE',
warehouse_id: logWarehouseId || null,
platform_code: 'SYSTEM',
message: isSynced
? '已同步手工单拦截请求按取消订单处理(库存已回补)'
: '未同步订单拦截请求按取消订单处理',
created_at: new Date(),
};
})
.filter(row => Number(row.businessId) > 0);
if (cancelLogRows.length > 0 && this.ctx.model && this.ctx.model.OperationLog) {
await this.ctx.model.OperationLog.bulkCreate(cancelLogRows);
}
} catch (logErr) {
ctx.logger.warn(`[order.pendingOrder.batchIntercept] 未同步/手工单取消日志写入失败, count=${chunkCancelIds.length}, error=${logErr.message}`);
}
}
}
// 分批更新拦截状态,每批最多500条(仅处理未命中「已复核/已称重」前置校验的订单)
for (let i = 0; i < interceptTargetRows.length; i += UPDATE_CHUNK_SIZE) {
const chunkRows = interceptTargetRows.slice(i, i + UPDATE_CHUNK_SIZE);
if (chunkRows.length === 0) {
continue;
}
@ -4876,13 +5021,14 @@ class PendingOrderService extends OrderBaseService {
order_ids: orderIds,
intercepted_order_ids: interceptedOrderIds,
intercepted_order_count: interceptedOrderIds.length,
cancelled_order_ids: cancelledOrderIds,
cancelled_order_count: cancelledOrderIds.length,
skipped_order_ids: skippedInterceptOrderIds,
skipped_order_count: skippedInterceptOrderIds.length,
total_order_count: totalOrderCount,
duration_ms: durationMs,
message: skippedInterceptOrderIds.length > 0
? `已拦截 ${interceptedOrderIds.length} 条订单,跳过 ${skippedInterceptOrderIds.length} 条(已复核/已称重)`
: `已拦截 ${interceptedOrderIds.length} 条订单`,
message: `已拦截 ${interceptedOrderIds.length} 条订单,未同步/手工单按取消处理 ${cancelledOrderIds.length} 条`
+ (skippedInterceptOrderIds.length > 0 ? `,跳过 ${skippedInterceptOrderIds.length} 条(已复核/已称重)` : ''),
},
});
} catch (error) {

View File

@ -134,9 +134,9 @@ class WaveService extends OrderBaseService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount';
const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintScan,confirmPrintUnclaimedWaveCount';
const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount';
const _noNeedRight = 'wavePickTaskCancelSelf,groupOrderFetchList,singleOrderFetchList,fetchableOrderCount,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount';
const _noNeedLog = 'groupOrderFetchList,singleOrderFetchList,fetchableOrderCount,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintScan,confirmPrintUnclaimedWaveCount';
const _noNeedAuth = 'groupOrderFetchList,singleOrderFetchList,fetchableOrderCount,waveStrategyList,waveStrategyFallbackOrderList,waveStrategyFetchPda,waveStrategyFetchAdmin,groupFetch,singleFetch,fetch,fetchTaskProgress,batchList,wavePickTaskList,batchCancel,batchCancelTaskProgress,batchRemoveExceptionOrders,batchRemoveExceptionOrdersTaskProgress,batchAllocateExpress,batchAllocateExpressTaskProgress,batchAllocateStorage,batchAllocateStorageTaskProgress,batchAutoGrouping,batchFinishAutoGrouping,batchRemoveOrders,singleFetchByIds,waveStrategyQuickScan,waveStrategyQuickScanTaskProgress,confirmPrintUnclaimedWaveCount';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
}
@ -3379,6 +3379,141 @@ class WaveService extends OrderBaseService {
});
}
/**
* 团购可抓取订单数统计。
*
* 口径与 groupOrderFetchList 完全一致(同一候选 where、同一 items_hash 粗分组、
* 同一团购阈值 same_order_quantity 过滤),但**不分页、不查订单明细**,
* 仅返回达到团购阈值分组的数量与组内订单数合计,供前端展示「可抓取订单数」等轻量统计。
*
* 差异说明:groupOrderFetchList 的 pagination.total 是**分组数**(每组订单数在 group_count 内),
* 本方法 order_count 是**订单数合计**,两者口径不同;include_sku 为页内过滤,本方法不参与统计。
*
* @param {Object} [data={}] 请求参数。
* @param {boolean} [data.distinguish_express=false] 是否区分快递(影响分组粒度)。
* @param {number|string} [data.store_id] 货主ID(作为筛选条件)。
* @param {number|string} [data.same_order_quantity] 最小同组订单数量阈值(>=);未传时取仓库配置 min_group_order_fetch_quantity(默认 13)。
* @param {string} [data.shop_name] 店铺名称(模糊匹配)。
* @param {string} [data.stock_query] 商品模糊筛选(stock_warehouse / stock_barcodes → order_items)。
* @return {Promise<Object>} 统一返回结构,data 含 group_count / order_count / same_order_quantity / raw_order_count / warehouse_id / distinguish_express。
*/
async fetchableOrderCount(data = {}) {
const t0 = Date.now();
const requestData = this.isPlainObject(data) ? data : {};
const warehouseId = Number(this.getWarehouseId() || 0);
if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
return this.fail('未识别到当前仓库上下文', {}, 400);
}
const model = await this.getOrderModel('pendingOrder', warehouseId);
const t1 = Date.now();
const distinguishExpress = this.normalizeBoolean(requestData.distinguish_express, false);
const storeId = this.normalizePositiveInteger(requestData.store_id, 'store_id', 0);
const sameOrderQuantityInput = requestData.same_order_quantity;
const hasSameOrderQuantityInput = !(sameOrderQuantityInput === undefined || sameOrderQuantityInput === null || sameOrderQuantityInput === '');
const explicitSameOrderQuantity = hasSameOrderQuantityInput
? this.normalizePositiveInteger(sameOrderQuantityInput, 'same_order_quantity', 0)
: 0;
const minGroupOrderFetchQuantity = await this.getMinGroupOrderFetchQuantity(warehouseId);
const sameOrderQuantity = explicitSameOrderQuantity > 0
? explicitSameOrderQuantity
: minGroupOrderFetchQuantity;
const shopName = this.normalizeShopName(requestData.shop_name);
const stockQuery = String(requestData.stock_query || '').trim();
const where = {
step: { [Op.in]: [ 1, 2, 3 ] },
status: { [Op.ne]: 'cancel' },
outbound_status: { [Op.ne]: 'padding' },
intercept_status: 'none',
lock_status: 'none',
wave_id: 0,
};
if (storeId > 0) {
where.store_id = storeId;
}
if (shopName) {
where.shop_nick = { [Op.like]: `%${shopName}%` };
}
if (stockQuery) {
const stockOrderIds = await this.findOrderIdsByStockQuery(stockQuery, 'order', warehouseId);
if (stockOrderIds.length <= 0) {
return this.success('ok', {
group_count: 0,
order_count: 0,
same_order_quantity: sameOrderQuantity,
raw_order_count: 0,
warehouse_id: warehouseId,
distinguish_express: distinguishExpress,
});
}
where.id = { [Op.in]: stockOrderIds };
}
// 仅取分组基准字段,不取明细(与 groupOrderFetchList Phase 1 同表同 where)
const rawOrders = await model.findAll({
where,
attributes: [ 'id', 'items_hash', 'items', 'sys_logistics_code' ],
raw: true,
});
const t2 = Date.now();
// 纯内存粗分组:items_hash(缺省回落 items)相同即为同组,distinguish_express 时再叠加快递编码
const coarseGroupSizeMap = new Map();
for (const order of rawOrders) {
const coarseKey = this.buildCoarseGroupKey(order, distinguishExpress);
if (!coarseKey) {
continue;
}
coarseGroupSizeMap.set(coarseKey, Number(coarseGroupSizeMap.get(coarseKey) || 0) + 1);
}
// 团购阈值过滤:仅统计同组订单数 >= sameOrderQuantity 的分组
let groupCount = 0;
let orderCount = 0;
for (const groupSize of coarseGroupSizeMap.values()) {
if (groupSize < sameOrderQuantity) {
continue;
}
groupCount += 1;
orderCount += groupSize;
}
const t3 = Date.now();
this.ctx.logger.info('[wave.fetchableOrderCount] 链路耗时', {
warehouseId,
params: { distinguishExpress, storeId, sameOrderQuantity, shopName: shopName || null, stockQuery: stockQuery || null },
counts: {
rawOrders: rawOrders.length,
coarseGroups: coarseGroupSizeMap.size,
fetchableGroups: groupCount,
fetchableOrders: orderCount,
},
timing_ms: {
getModel: t1 - t0,
queryOrders: t2 - t1,
counting: t3 - t2,
total: t3 - t0,
},
});
return this.success('ok', {
group_count: groupCount,
order_count: orderCount,
same_order_quantity: sameOrderQuantity,
raw_order_count: rawOrders.length,
warehouse_id: warehouseId,
distinguish_express: distinguishExpress,
});
}
/**
* 查询当前仓库波次策略列表。
*

View File

@ -247,6 +247,134 @@ class OrderExpressService extends Service {
}
}
/**
* 读取订单的波次范围与打包状态(依次查询 current → history → dispatch 分表)。
*
* 序列表定位优先:命中时先查对应分表,未命中(存量订单)按原遍历顺序回退。
*
* @param {number} orderId 订单ID。
* @param {number} warehouseId 仓库ID。
* @return {Promise<Object|null>} { id, wave_scope, pack_status },未命中时返回 null。
*/
async findOrderWaveAndPackStatus(orderId, warehouseId) {
const orderDeliveryFactory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
if (!orderDeliveryFactory || typeof orderDeliveryFactory.getCurrentModel !== 'function') {
return null;
}
const tableOrders = [
{ label: 'current', getModel: () => orderDeliveryFactory.getCurrentModel(warehouseId) },
{ label: 'history', getModel: () => orderDeliveryFactory.getHistoryModel(warehouseId) },
{ label: 'dispatch', getModel: () => orderDeliveryFactory.getDispatchModel(warehouseId) },
];
try {
if (typeof orderDeliveryFactory.getOrderLocation === 'function') {
const preferredLocation = await orderDeliveryFactory.getOrderLocation(orderId, warehouseId);
if (preferredLocation) {
tableOrders.sort((a, b) => (a.label === preferredLocation ? -1 : b.label === preferredLocation ? 1 : 0));
}
}
} catch (_err) { /* 定位失败,保持原遍历顺序 */ }
for (const entry of tableOrders) {
try {
const model = await entry.getModel();
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'wave_scope', 'pack_status' ],
raw: true,
});
if (row) return row;
} catch (_err) { continue; }
}
return null;
}
/**
* 读取仓库「散单称重是否需要打包」配置。
*
* 配置来源:wms_store.subject_config.single_weigh_require_pack(默认关闭)。
* 走 deliveryOrder.getStoreSubjectConfig 公共读取链路(带缓存);配置缺失、
* 读取失败或值非法时按「关闭」处理,保证称重主流程可用。
*
* @param {number|null} warehouseId 仓库ID。
* @return {Promise<boolean>} 是否要求散单称重前已完成打包。
*/
async isSingleWeighRequirePack(warehouseId) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return false;
}
try {
const deliveryOrderService = this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.deliveryOrder;
if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') {
return false;
}
const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(normalizedWarehouseId);
return !!(subjectConfig && subjectConfig.single_weigh_require_pack === true);
} catch (error) {
this.ctx.logger.warn(
'[OrderExpressService.isSingleWeighRequirePack] 读取仓库配置失败,按关闭处理: %s',
error.message
);
return false;
}
}
/**
* 散单称重前置校验:开启「散单称重是否需要打包」时,未打包订单禁止称重。
*
* 适用范围:订单波次范围 wave_scope 不属于 1(大团购)/ 3(小团购)时生效,
* 即未分配波次、散单、单品单件等按散单处理的订单;团购订单不校验。
* 订单未命中(分表无记录)时跳过校验,由后续称重逻辑自行报错。
*
* @param {number} orderId 订单ID。
* @param {number|null} warehouseId 仓库ID,缺失时跳过校验。
* @return {Promise<void>} 无返回值;未打包时抛出业务异常。
*/
async assertSingleOrderPackedForWeigh(orderId, warehouseId) {
const normalizedWarehouseId = Number(warehouseId || 0);
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return;
}
const requirePack = await this.isSingleWeighRequirePack(normalizedWarehouseId);
if (!requirePack) {
return;
}
const orderRow = await this.findOrderWaveAndPackStatus(orderId, normalizedWarehouseId);
if (!orderRow) {
return;
}
const waveScope = Number(orderRow.wave_scope || 0);
if (waveScope === 1 || waveScope === 3) {
return;
}
const packStatus = String(orderRow.pack_status || '').trim();
if (packStatus !== 'fin') {
throw this.createBusinessError(this.buildWeighPackBlockedMessage(packStatus), 400);
}
}
/**
* 构造「散单称重需先打包」拦截文案,供各称重入口复用(保证提示语一致)。
* @param {string} packStatus 打包状态原值。
* @return {string} 拦截提示文案:打包中(padding)返回「订单打包中」,其余未完成状态返回「订单未打包」。
*/
buildWeighPackBlockedMessage(packStatus) {
return packStatus === 'padding' ? '订单打包中' : '订单未打包';
}
/**
* 规范化并校验称重重量。
*
@ -464,7 +592,7 @@ class OrderExpressService extends Service {
*
* @param {Object} payload 入参对象。
* @param {string} payload.waybillCode 运单号(必填)。
* @param {number|string} payload.weighingWeight 称重重量(kg)。
* @param {number|string} payload.weighingWeight 称重重量(g)。
* @return {Promise<Object>} 单运单返回 {order_id, waybill_code, weighing_weight, items_weight};
* 团购批量返回 {wave_id, wave_no, order_id, weighing_weight, total_weight, split_count, splits, store_name, sys_logistics_name, items_weight}。
*/
@ -861,6 +989,9 @@ class OrderExpressService extends Service {
* @return {Promise<{order_id:number, waybill_code:string, weighing_weight:number, items_weight:number}>} 更新结果。
*/
async _updateSingleOrderWeight(orderId, waybillCode, weight, warehouseId) {
// 散单称重前置校验:开启「散单称重是否需要打包」后,未打包订单禁止称重
await this.assertSingleOrderPackedForWeigh(orderId, warehouseId);
const rows = await this.findValidOrderExpressRows(orderId, warehouseId);
if (rows.length === 0) {

View File

@ -2229,6 +2229,9 @@ class OrderStorageAllocationService extends MainService {
const skippedOrders = [];
const eligibleOrderIds = [];
// 拦截模式:无拣货行(含已软删)或储位已释放但已同步出库的订单,
// 按订单明细补建拦截锁承接总量差,避免可用数漂移
const interceptNoPickingOrderIds = [];
for (const orderId of orderIds) {
const orderRow = orderMap.get(orderId);
@ -2249,6 +2252,11 @@ class OrderStorageAllocationService extends MainService {
}
if (String(orderRow.storage_status || 'none') !== STORAGE_STATUS_FIN) {
// 拦截确认模式:储位已释放但已同步出库的订单(stock 层已扣、storage 层无锁可迁)
// 不直接跳过,登记为拦截锁补建候选,保证可用数守恒
if (interceptMode && String(orderRow.sync_status || '').trim() === 'fin') {
interceptNoPickingOrderIds.push(orderId);
}
skippedOrders.push({
order_id: orderId,
status: 'skipped',
@ -2268,24 +2276,29 @@ class OrderStorageAllocationService extends MainService {
});
if (eligibleOrderIds.length === 0) {
if (!externalTransaction) {
await transaction.commit();
// 拦截模式下存在无拣货行补建候选(储位已释放但已同步出库)时,
// 继续执行拦截分支完成拦截锁补建,保证可用数守恒
const hasNoPickingCompensate = interceptMode && interceptNoPickingOrderIds.length > 0;
if (!hasNoPickingCompensate) {
if (!externalTransaction) {
await transaction.commit();
}
return {
code: 200,
message: '没有需要取消分配的订单',
data: {
warehouse_id: warehouseId,
requested_order_ids: orderIds,
cancellable_order_ids: [],
skipped_orders: skippedOrders,
orders: skippedOrders,
picking_count: 0,
storage_unlock_summary: [],
storage_return_summary: [],
stock_unlock_summary: [],
},
};
}
return {
code: 200,
message: '没有需要取消分配的订单',
data: {
warehouse_id: warehouseId,
requested_order_ids: orderIds,
cancellable_order_ids: [],
skipped_orders: skippedOrders,
orders: skippedOrders,
picking_count: 0,
storage_unlock_summary: [],
storage_return_summary: [],
stock_unlock_summary: [],
},
};
}
const pickingRows = await pickingModel.findAll({
@ -2354,6 +2367,14 @@ class OrderStorageAllocationService extends MainService {
continue;
}
if (interceptMode) {
// 拦截确认:储位状态为 fin 但无拣货行(已软删/已删除)的订单不跳过,
// 按订单明细补建拦截锁,承接同步出库造成的总量差
cancellableOrderIds.push(orderId);
interceptNoPickingOrderIds.push(orderId);
continue;
}
skippedOrders.push({
order_id: orderId,
status: 'skipped',
@ -2363,24 +2384,29 @@ class OrderStorageAllocationService extends MainService {
}
if (cancellableOrderIds.length === 0) {
if (!externalTransaction) {
await transaction.commit();
// 拦截模式下存在无拣货行补建候选(储位已释放但已同步出库)时,
// 继续执行拦截分支完成拦截锁补建,保证可用数守恒
const hasNoPickingCompensate = interceptMode && interceptNoPickingOrderIds.length > 0;
if (!hasNoPickingCompensate) {
if (!externalTransaction) {
await transaction.commit();
}
return {
code: 200,
message: '没有需要取消分配的订单',
data: {
warehouse_id: warehouseId,
requested_order_ids: orderIds,
cancellable_order_ids: [],
skipped_orders: skippedOrders,
orders: skippedOrders,
picking_count: 0,
storage_unlock_summary: [],
storage_return_summary: [],
stock_unlock_summary: [],
},
};
}
return {
code: 200,
message: '没有需要取消分配的订单',
data: {
warehouse_id: warehouseId,
requested_order_ids: orderIds,
cancellable_order_ids: [],
skipped_orders: skippedOrders,
orders: skippedOrders,
picking_count: 0,
storage_unlock_summary: [],
storage_return_summary: [],
stock_unlock_summary: [],
},
};
}
const storageRows = await storageModel.findAll({
@ -2407,6 +2433,8 @@ class OrderStorageAllocationService extends MainService {
const storageUnlockSummary = [];
const storageReturnSummary = [];
// 拦截模式无拣货行补建汇总(storage_id -> 补建拦截锁数量),随响应返回供对账追溯
const interceptCompensateSummaryMap = new Map();
if (interceptMode) {
// ── 拦截模式:库存不归还可用,移入拦截锁定字段(intercept_locked_quantity) ──
@ -2678,6 +2706,178 @@ class OrderStorageAllocationService extends MainService {
for (const [ storageId, quantity ] of interceptReturnSummaryMap.entries()) {
storageReturnSummary.push({ storage_id: storageId, returned_quantity: quantity });
}
// ── 拦截模式无拣货行补建:拣货行已被删除/软删(取消储位分配等路径)的订单, ──
// ── 同步出库已在 stock 层扣减而 storage 层从未扣,拦截锁无行可迁。 ──
// ── 按订单明细数量补建拦截锁(intercept +q、available -q、quantity 不变), ──
// ── 确保可用数守恒:storage 可用 === stock 可用。 ──
if (interceptNoPickingOrderIds.length > 0) {
const orderItemsModel = ctx.model && ctx.model.OrderItemsFactory
&& typeof ctx.model.OrderItemsFactory.getCurrentModel === 'function'
? await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId)
: null;
if (!orderItemsModel) {
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式无拣货行补建跳过:订单明细模型不可用', {
interceptNoPickingOrderIds,
});
} else {
const noPickingOrderItems = await orderItemsModel.findAll({
where: {
order_id: { [Op.in]: interceptNoPickingOrderIds },
},
attributes: [ 'order_id', 'stock_id', 'plan_qty' ],
raw: true,
transaction,
});
// 按 (order_id, stock_id) 汇总补建量
const compensatePlanMap = new Map(); // orderId -> [{ stockId, qty }]
for (const item of Array.isArray(noPickingOrderItems) ? noPickingOrderItems : []) {
const itemOrderId = toNumber(item && item.order_id, 0);
const stockId = toNumber(item && item.stock_id, 0);
const qty = toNumber(item && item.plan_qty, 0);
if (itemOrderId <= 0 || stockId <= 0 || qty <= 0) {
continue;
}
const plans = compensatePlanMap.get(itemOrderId) || [];
const existing = plans.find(p => p.stockId === stockId);
if (existing) {
existing.qty += qty;
} else {
plans.push({ stockId, qty });
}
compensatePlanMap.set(itemOrderId, plans);
}
// 逐商品查询可用库存行(有行挂锁,无行补建行),并写拦截锁定流水
for (const orderId of interceptNoPickingOrderIds) {
const plans = compensatePlanMap.get(orderId) || [];
if (plans.length === 0) {
continue;
}
const orderRow = orderMap.get(orderId) || {};
const orderNo = String(orderRow.delivery_order_code || orderRow.pre_delivery_order_code || '').trim()
|| 'INTERCEPT_CONFIRM';
const orderStoreId = toNumber(orderRow.store_id, 0) || null;
for (const plan of plans) {
const { stockId, qty } = plan;
// 优先找该商品数量最多的未删除行挂锁,保证拦截锁落在真实库存行上
const candidateRows = await storageModel.findAll({
where: {
stock_id: stockId,
warehouse_id: warehouseId,
is_enabled: 1,
delete_at: null,
},
order: [[ 'quantity', 'DESC' ]],
lock: transaction ? transaction.LOCK.UPDATE : undefined,
raw: true,
transaction,
});
if (candidateRows.length > 0) {
const targetRow = candidateRows[0];
const beforeInterceptLockedQuantity = toNumber(targetRow.intercept_locked_quantity, 0);
await ctx.service.systems.storage.index.updateQuantity(
Number(targetRow.id),
0,
0,
{ transaction, interceptLockedChange: qty }
);
await ctx.model.StorageTransaction.create({
transaction_type: 'LOCK',
warehouse_id: warehouseId,
store_id: Number(targetRow.store_id) || orderStoreId,
stock_id: stockId,
storage_id: Number(targetRow.id),
space_id: Number(targetRow.space_id) || null,
quantity: qty,
before_quantity: Number(targetRow.quantity) || 0,
after_quantity: Number(targetRow.quantity) || 0,
before_locked_quantity: Number(targetRow.locked_quantity) || 0,
after_locked_quantity: Number(targetRow.locked_quantity) || 0,
before_intercept_locked_quantity: beforeInterceptLockedQuantity,
after_intercept_locked_quantity: beforeInterceptLockedQuantity + qty,
batch_no: targetRow.batch_no || null,
inventory_type: targetRow.inventory_type || 'ZP',
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(无拣货行补建拦截锁定)',
}, { transaction });
interceptCompensateSummaryMap.set(
Number(targetRow.id),
(interceptCompensateSummaryMap.get(Number(targetRow.id)) || 0) + qty
);
} else {
// 该商品没有任何库存行:按缺行补建(quantity=q、intercept=q、available=0)
const created = await storageModel.create({
warehouse_id: warehouseId,
store_id: orderStoreId,
space_id: fallbackDefaultSpaceId,
stock_id: stockId,
batch_no: String(orderNo).slice(0, 100),
inventory_type: 'ZP',
quantity: qty,
locked_quantity: 0,
intercept_locked_quantity: qty,
available_quantity: 0,
inbound_time: now,
inbound_order_no: String(orderNo).slice(0, 100),
is_enabled: 1,
created_at: now,
updated_at: now,
}, { transaction });
const plainCreated = created && typeof created.get === 'function'
? created.get({ plain: true })
: created;
await ctx.model.StorageTransaction.create({
transaction_type: 'LOCK',
warehouse_id: warehouseId,
store_id: plainCreated.store_id,
stock_id: stockId,
storage_id: plainCreated.id,
space_id: plainCreated.space_id,
quantity: qty,
before_quantity: qty,
after_quantity: qty,
before_locked_quantity: 0,
after_locked_quantity: 0,
before_intercept_locked_quantity: 0,
after_intercept_locked_quantity: qty,
batch_no: plainCreated.batch_no,
inventory_type: 'ZP',
order_type: 'INTERCEPT_LOCK',
order_no: orderNo,
order_id: orderId,
operator_id: String(ctx.user?.employees_id ?? ctx.user?.id ?? ''),
operator_name: ctx.user?.employees_name ?? ctx.user?.real_name ?? ctx.user?.name ?? '',
remark: '拦截确认(无拣货行补建库存行并拦截锁定)',
}, { transaction });
interceptCompensateSummaryMap.set(
Number(plainCreated.id),
(interceptCompensateSummaryMap.get(Number(plainCreated.id)) || 0) + qty
);
}
}
}
writeAllocationTextLog('[OrderStorageAllocationService.cancelAllocateStorage] 拦截模式无拣货行补建完成', {
interceptNoPickingOrderIds,
interceptCompensateSummary: Array.from(interceptCompensateSummaryMap.entries()),
});
}
}
} else {
// ── 普通取消模式:解除锁定/返还实物,回到可用数量(既有行为不变) ──
// pending 记录:解除锁定,实物库存不动
@ -2848,6 +3048,8 @@ class OrderStorageAllocationService extends MainService {
picking_count: cancelPickingIds.length,
storage_unlock_summary: storageUnlockSummary,
storage_return_summary: storageReturnSummary,
intercept_compensate_summary: Array.from(interceptCompensateSummaryMap.entries())
.map(([ storageId, quantity ]) => ({ storage_id: storageId, intercept_locked_quantity: quantity })),
stock_unlock_summary: [],
};

View File

@ -346,6 +346,14 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([
description: '大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0',
min: 0.1,
}),
Object.freeze({
key: 'single_weigh_require_pack',
name: '散单称重是否需要打包',
type: 'flag',
default: false,
required: false,
description: '开启后散单称重(订单波次范围 wave_scope 非 1 大团购 / 3 小团购)前必须已打包完成(pack_status=fin),未打包时拒绝称重并返回错误,默认 false(关闭)',
}),
Object.freeze({
key: 'return_unpack_max_record_minutes',
name: '拆包最大录制时长(分钟)',

View File

@ -1608,7 +1608,7 @@ class WorkbenchService extends Service {
if (!model || typeof model.findOne !== 'function') continue;
const row = await model.findOne({
where: { id: orderId, warehouse_id: warehouseId },
attributes: [ 'id', 'wave_id', 'wave_no', 'items_weight', 'intercept_status' ],
attributes: [ 'id', 'wave_id', 'wave_no', 'wave_scope', 'pack_status', 'items_weight', 'intercept_status' ],
raw: true,
});
if (row) {
@ -1631,6 +1631,9 @@ class WorkbenchService extends Service {
throw new Error(`订单已被拦截,无法称重 [${normalizedBarcode}]`);
}
// 散单称重前置校验:开启「散单称重是否需要打包」后,波次范围非大团购(1)/小团购(3)的未打包订单禁止称重
await this._assertSingleWeighPackedForWeigh(orderRow, warehouseId);
const waveId = Number(orderRow.wave_id || 0);
// 步骤3:散单(wave_id=0)→ 仅更新该运单的称重重量
@ -1762,6 +1765,48 @@ class WorkbenchService extends Service {
};
}
/**
* 散单称重前置校验(工作台):开启仓库配置「散单称重是否需要打包」后,
* 波次范围(wave_scope)非 1(大团购)/ 3(小团购)的订单未打包完成
* (pack_status != fin)时禁止称重。
*
* 配置读取与提示文案复用 systems/order_express,避免多处判定逻辑漂移;
* 当前订单行已含 wave_scope/pack_status,故无需重复查询订单表。
* 配置服务不可用时静默跳过,不阻断称重主流程。
*
* @param {Object} orderRow 订单行(需包含 wave_scope/pack_status)
* @param {number} warehouseId 仓库ID
* @return {Promise<void>} 无返回值;未打包时抛出错误
*/
async _assertSingleWeighPackedForWeigh(orderRow, warehouseId) {
const waveScope = Number((orderRow && orderRow.wave_scope) || 0);
if (waveScope === 1 || waveScope === 3) {
return;
}
const orderExpressService = this.ctx.service
&& this.ctx.service.systems
&& this.ctx.service.systems.orderExpress;
if (!orderExpressService || typeof orderExpressService.isSingleWeighRequirePack !== 'function') {
return;
}
const requirePack = await orderExpressService.isSingleWeighRequirePack(warehouseId);
if (!requirePack) {
return;
}
const packStatus = String((orderRow && orderRow.pack_status) || '').trim();
if (packStatus === 'fin') {
return;
}
const message = typeof orderExpressService.buildWeighPackBlockedMessage === 'function'
? orderExpressService.buildWeighPackBlockedMessage(packStatus)
: (packStatus === 'padding' ? '订单打包中' : '订单未打包');
throw new Error(message);
}
/**
* 写入称重操作日志(内部方法,失败不影响主流程)
* @param {Object} opts

View File

@ -0,0 +1,153 @@
'use strict';
const TABLE_NAME = 'wms_org_unit';
/**
* Migration: create wms_org_unit(组织架构表)
*
* 背景:系统多仓库多主体,各仓库自行维护自己的组织架构(部门/子部门层级),
* 用于工单派发、组级消息推送、入职默认权限等场景。本表与角色表(wms_role)
* 分离:角色管"能做什么",组织架构管"归属哪个组"。
*
* 字段说明:
* - warehouse_id:所属仓库,多主体数据隔离维度,部门树不允许跨仓挂接。
* - parent_id:父部门ID,NULL 表示根部门;挂接时必须与 warehouse_id 同仓(服务层校验)。
* - path:冗余层级路径(如 /1/5/9/),用前缀 LIKE 一次查询整棵子树,避免递归。
* - leader_id:部门/子部门管理员(关联 wms_account.id),可空。
* - admin_role_ids:管理员默认角色集(关联 wms_role.id),任命管理员时自动分配。
* - default_role_ids:部门默认角色集(关联 wms_role.id),成员入职挂本部门时自动分配。
* - code:部门编码,仓库内唯一(NULL 不参与唯一约束,允许多个未编码部门)。
*
* 索引:idx_warehouse_parent、idx_parent_id、uk_warehouse_code(唯一)、
* idx_path、idx_status。
*
* Idempotent: 表已存在时跳过创建。
*/
module.exports = {
/**
* 执行正向迁移:创建组织架构表与索引。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @param {import('sequelize')} Sequelize Sequelize 实例。
* @return {Promise<void>} 无返回值。
*/
up: async (queryInterface, Sequelize) => {
const tables = await queryInterface.showAllTables();
const exists = tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === TABLE_NAME);
if (exists) return;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: Sequelize.BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
warehouse_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: false,
comment: '所属仓库ID,关联 wms_store.id',
},
parent_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '父部门ID,NULL=根部门;必须与 warehouse_id 同仓',
},
name: {
type: Sequelize.STRING(100),
allowNull: false,
comment: '部门名称',
},
code: {
type: Sequelize.STRING(50),
allowNull: true,
comment: '部门编码(仓库内唯一)',
},
leader_id: {
type: Sequelize.BIGINT(20).UNSIGNED,
allowNull: true,
comment: '部门管理员账号ID,关联 wms_account.id',
},
admin_role_ids: {
type: Sequelize.JSON,
allowNull: true,
comment: '管理员默认角色集,关联 wms_role.id,如 [3,8];任命管理员时自动分配',
},
default_role_ids: {
type: Sequelize.JSON,
allowNull: true,
comment: '部门默认角色集,关联 wms_role.id,如 [3,8];成员入职挂本部门时自动分配',
},
path: {
type: Sequelize.STRING(500),
allowNull: true,
comment: '层级路径,如 /1/5/9/(根部门为 /{id}/),用于一次查询整棵子树',
},
sort: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0,
comment: '同级排序,越小越靠前',
},
status: {
type: Sequelize.TINYINT,
allowNull: false,
defaultValue: 1,
comment: '状态:0-停用 1-启用',
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: Sequelize.DATE,
allowNull: true,
comment: '软删除时间',
},
});
// 按仓库查部门树(取根 + 挂接校验)
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'parent_id' ], {
name: 'idx_warehouse_parent',
});
// 按父部门查子部门
await queryInterface.addIndex(TABLE_NAME, [ 'parent_id' ], {
name: 'idx_parent_id',
});
// 仓库内部门编码唯一
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'code' ], {
name: 'uk_warehouse_code',
unique: true,
});
// 路径前缀查询子树
await queryInterface.addIndex(TABLE_NAME, [ 'path' ], {
name: 'idx_path',
});
// 启用状态过滤
await queryInterface.addIndex(TABLE_NAME, [ 'status' ], {
name: 'idx_status',
});
},
/**
* 执行回滚迁移:删除组织架构表。
* @param {import('sequelize').QueryInterface} queryInterface 查询接口。
* @return {Promise<void>} 无返回值。
*/
down: async queryInterface => {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,147 @@
'use strict';
/**
* 创建库存盘点主表 wms_stock_check。
*
* 字段:仓库隔离 warehouse_id、盘点单号 check_no(PD+YYYYMMDD+6位序号,唯一)、
* 盘点名称 title、盘点范围类型 type(all全盘/store按货主/goods按商品/location按库位)、
* 盘点方式 mode(open明盘/blind盲盘)、货主 store_id、范围条件快照 scope_snapshot(JSON)、
* 状态 status(pending/in_progress/checked/confirmed/completed/cancelled)、
* 明细盘点状态 detail_status(none_checked/partial_checked/all_checked)、
* 盘点日期 check_date、起止时间 start_time/end_time、创建人 creator_id/creator_name、
* 汇总 total_items/checked_items/diff_items、备注 remark。
*
* 索引:
* uk_check_no(单号唯一)
* idx_warehouse_check_date(仓库+盘点日期隔离查询)
* idx_warehouse_status(仓库+状态)
* idx_store_id / idx_creator_id
*/
const TABLE_NAME = 'wms_stock_check';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, INTEGER, DATE, JSON: JSON_TYPE } = Sequelize;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(数据隔离维度)',
},
check_no: {
type: STRING(50),
allowNull: false,
comment: '盘点单号,唯一,生成规则:PD+YYYYMMDD+6位序号',
},
title: {
type: STRING(200),
allowNull: true,
comment: '盘点名称/主题,非必填',
},
type: {
type: STRING(20),
allowNull: false,
defaultValue: 'all',
comment: '盘点范围类型:all=全盘,store=按货主,goods=按商品,location=按库位',
},
mode: {
type: STRING(20),
allowNull: false,
defaultValue: 'open',
comment: '盘点方式:open=明盘(可见账面数量),blind=盲盘(不可见账面数量)',
},
store_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '货主ID,按货主盘点时必填(type=store)',
},
scope_snapshot: {
type: JSON_TYPE,
allowNull: true,
comment: '盘点范围条件快照(JSON),如商品ID列表/库位ID列表,供盘点对比与追溯',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'pending',
comment: '盘点状态:pending=待盘点,in_progress=盘点中,checked=已盘待确认,confirmed=已确认,completed=已完成,cancelled=已取消',
},
detail_status: {
type: STRING(30),
allowNull: false,
defaultValue: 'none_checked',
comment: '明细盘点进度:none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘',
},
check_date: {
type: DATE,
allowNull: false,
comment: '盘点日期',
},
start_time: {
type: DATE,
allowNull: true,
comment: '实际开始时间',
},
end_time: {
type: DATE,
allowNull: true,
comment: '实际结束时间',
},
creator_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '创建人账户ID',
},
creator_name: {
type: STRING(50),
allowNull: true,
comment: '创建人名称快照',
},
total_items: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '明细行数(盘点任务总行数)',
},
checked_items: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '已盘行数',
},
diff_items: {
type: INTEGER(11),
allowNull: false,
defaultValue: 0,
comment: '差异行数(账面与实盘不一致的行数)',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注',
},
created_at: { type: DATE, allowNull: false },
updated_at: { type: DATE, allowNull: false },
});
await queryInterface.addIndex(TABLE_NAME, [ 'check_no' ], { unique: true, name: 'uk_check_no' });
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'check_date' ], { name: 'idx_warehouse_check_date' });
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'status' ], { name: 'idx_warehouse_status' });
await queryInterface.addIndex(TABLE_NAME, [ 'store_id' ], { name: 'idx_store_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'creator_id' ], { name: 'idx_creator_id' });
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -0,0 +1,143 @@
'use strict';
/**
* 创建库存盘点明细表 wms_stock_check_detail。
*
* 字段:关联主表 check_id、仓库冗余 warehouse_id、库存商品 stock_id(关联 wms_stock_warehouse.id)、
* 库位 location_id/location_code(关联 wms_location_space.id + 编码快照)、
* 商品快照 item_code/item_name/spec、批次号 batch_no、账面数量 system_quantity、
* 实盘数量 check_quantity(可空=未盘)、差异数量 diff_quantity(=实盘-账面,正盘盈负盘亏)、
* 差异标记 is_diff、明细状态 status(unchecked/checked/confirmed)、
* 盘点人 checker_id/checker_name、盘点时间 checked_at、备注 remark。
*
* 索引:
* idx_check_id(按盘点单查明细,最高频)
* idx_warehouse_stock(仓库+商品)
* idx_stock_id(按商品反查)
* idx_location_id(按库位反查)
* idx_is_diff(差异行筛选)
*/
const TABLE_NAME = 'wms_stock_check_detail';
module.exports = {
// eslint-disable-next-line no-unused-vars
async up(queryInterface, Sequelize) {
const { BIGINT, STRING, INTEGER, DATE, TINYINT } = Sequelize;
await queryInterface.createTable(TABLE_NAME, {
id: {
type: BIGINT(20).UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键',
},
check_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '关联盘点主表 wms_stock_check.id',
},
warehouse_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '仓库ID(冗余,隔离查询)',
},
stock_id: {
type: BIGINT(20).UNSIGNED,
allowNull: false,
comment: '库存商品ID,关联 wms_stock_warehouse.id',
},
location_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '库位ID,关联 wms_location_space.id;无库位商品为空',
},
location_code: {
type: STRING(50),
allowNull: true,
comment: '库位编码快照(space_code)',
},
item_code: {
type: STRING(50),
allowNull: false,
comment: '商品编码快照',
},
item_name: {
type: STRING(255),
allowNull: true,
comment: '商品名称快照',
},
spec: {
type: STRING(100),
allowNull: true,
comment: '规格快照(sku_property)',
},
batch_no: {
type: STRING(100),
allowNull: true,
comment: '批次号,批次管理商品时记录',
},
system_quantity: {
type: INTEGER(12),
allowNull: false,
defaultValue: 0,
comment: '账面数量(生成盘点任务时的系统库存快照)',
},
check_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '实盘数量;未盘点时为空',
},
diff_quantity: {
type: INTEGER(12),
allowNull: true,
comment: '差异数量 = 实盘数量 - 账面数量;正数盘盈,负数盘亏;未盘点时为空',
},
is_diff: {
type: TINYINT(1),
allowNull: false,
defaultValue: 0,
comment: '是否有差异:1=有差异,0=无差异',
},
status: {
type: STRING(20),
allowNull: false,
defaultValue: 'unchecked',
comment: '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认',
},
checker_id: {
type: BIGINT(20).UNSIGNED,
allowNull: true,
comment: '盘点人账户ID',
},
checker_name: {
type: STRING(50),
allowNull: true,
comment: '盘点人名称快照',
},
checked_at: {
type: DATE,
allowNull: true,
comment: '盘点时间',
},
remark: {
type: STRING(500),
allowNull: true,
comment: '备注(如差异原因说明)',
},
created_at: { type: DATE, allowNull: false },
updated_at: { type: DATE, allowNull: false },
});
await queryInterface.addIndex(TABLE_NAME, [ 'check_id' ], { name: 'idx_check_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'stock_id' ], { name: 'idx_warehouse_stock' });
await queryInterface.addIndex(TABLE_NAME, [ 'stock_id' ], { name: 'idx_stock_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'location_id' ], { name: 'idx_location_id' });
await queryInterface.addIndex(TABLE_NAME, [ 'is_diff' ], { name: 'idx_is_diff' });
},
// eslint-disable-next-line no-unused-vars
async down(queryInterface, Sequelize) {
await queryInterface.dropTable(TABLE_NAME);
},
};

View File

@ -1,4 +1,92 @@
[
{
"version": "2026.09.28-weigh-pack-padding-message",
"date": "2026-09-28",
"type": "updated",
"summary": "散单称重拦截提示区分打包中状态:pack_status=padding 返回「订单打包中」,其余未完成状态返回「订单未打包」",
"methods": [
"order.updateExpressWeighingWeight",
"workbench.sendWeight"
],
"notes": [
"代码依据:app/service/systems/order_express.js 的 buildWeighPackBlockedMessage(packStatus) 恢复入参,padding 返回「订单打包中」、其余非 fin 状态返回「订单未打包」;assertSingleOrderPackedForWeigh 沿用该文案抛 400。",
"代码依据:app/service/systems/workbench.js 的 _assertSingleWeighPackedForWeigh 复用同一文案,不再固定「订单未打包」。",
"判定规则未变:开启仓库配置 single_weigh_require_pack 后,wave_scope 非 1 大团购/3 小团购的订单 pack_status 非 fin 时拒绝称重;团购波次批量称重不校验。",
"测试:test/single_weigh_require_pack.test.cjs(27 用例,新增打包中文案断言,全部通过)。",
"本次仅提示文案区分,无接口结构变化。"
]
},
{
"version": "2026.09.28-order-wave-fetchable-order-count",
"date": "2026-09-28",
"type": "added",
"summary": "新增 order.wave.fetchableOrderCount:统计当前仓库团购可抓取订单数(与 order.wave.groupOrderFetchList 同口径:同一候选条件 + items_hash 粗分组 + 团购阈值过滤),但不分页、不查订单明细,仅返回命中分组数与组内订单数合计。",
"methods": [
"order.wave.fetchableOrderCount"
],
"notes": [
"代码依据:app/service/systemMethods/order/wave.js 新增 async fetchableOrderCount(data)。候选 where 与 groupOrderFetchList 完全一致(step in [1,2,3]、status != cancel、outbound_status != padding、intercept_status='none'、lock_status='none'、wave_id=0,叠加 store_id / shop_name / stock_query 过滤);分组键复用 buildCoarseGroupKey(items_hash 缺省回落 items,distinguish_express=true 时再叠加 sys_logistics_code);阈值同源 getMinGroupOrderFetchQuantity(仓库配置,默认 13);仅取 id/items_hash/items/sys_logistics_code 四列,纯内存计数,不查订单明细。",
"口径差异(重要):groupOrderFetchList 的 pagination.total 是分组数(每组订单数在 item.group_count 内),本方法 order_count 是命中分组的订单数合计、group_count 是命中分组数;include_sku 为 groupOrderFetchList 的页内过滤参数,本方法不参与统计,因此带 include_sku 时两者不保证一致。",
"权限与日志:方法已加入 wave.js systemInit 的 _noNeedRight / _noNeedLog / _noNeedAuth 名单(与 groupOrderFetchList 一致),仅需登录;isNeedAuth=false,不产生 wms_permission 权限记录,无需执行 permission:sync:system-api,也不需要新增迁移。",
"返回结构:成功返回 flag=success/code=1,data 含 group_count / order_count / same_order_quantity / raw_order_count / warehouse_id / distinguish_express;仓库上下文缺失时返回 flag=failure/code=400「未识别到当前仓库上下文」。",
"测试:test/app/service/systemMethods/order/wave.fetchableOrderCount.test.js(8 用例:阈值命中统计、阈值变化、区分快递粒度、store_id+shop_name 进入候选 where、stock_query 空命中短路、仓库上下文缺失 400、默认阈值回落、与 groupOrderFetchList 命中分组订单数合计一致性)。",
"文档变更范围:methods/system.json 在 module=order.wave(订单波次模块)分组 list 末尾新增 1 条 method;根版本 0.3.194 → 0.3.195、updatedAt 2026-09-27 → 2026-09-28;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。",
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。"
]
},
{
"version": "2026.09.27-weigh-pack-message-simplify",
"date": "2026-09-27",
"type": "updated",
"summary": "散单称重未打包拦截文案简化为固定「订单未打包」(移除打包状态明细与工作台条码后缀)",
"methods": [
"order.updateExpressWeighingWeight",
"workbench.sendWeight"
],
"notes": [
"代码依据:app/service/systems/order_express.js 的 buildWeighPackBlockedMessage() 现返回固定文案「订单未打包」,assertSingleOrderPackedForWeigh 沿用该文案抛 400;原 formatPackStatusText 状态文案方法已移除。",
"代码依据:app/service/systems/workbench.js 的 _assertSingleWeighPackedForWeigh(orderRow, warehouseId) 复用同一文案,不再追加 ` [条码]` 后缀。",
"判定规则未变:开启仓库配置 single_weigh_require_pack 后,wave_scope 非 1 大团购/3 小团购的订单 pack_status 非 fin 时拒绝称重;团购波次批量称重不校验。",
"测试:test/single_weigh_require_pack.test.cjs(26 用例,已按新文案断言)。",
"本次仅文档文案对齐,无接口结构变化。"
]
},
{
"version": "2026.09.27-setting-save-big-group-coefficient-doc-fix",
"date": "2026-09-27",
"type": "updated",
"summary": "补 setting.warehouse.saveSettings 入参遗漏的 subject_config.big_group_pack_coefficient(对齐 getSettings/getFieldMeta 与代码实现):大团购波次(wave_scope=1)打包中扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,默认 3,必须大于 0;非法值报 400。",
"methods": [
"setting.warehouse.saveSettings"
],
"notes": [
"代码依据:app/service/systems/setting/warehouse.js#WAREHOUSE_SETTING_FIELDS 已有 key=big_group_pack_coefficient(name=大团购打包系数,type=number,default=3,required=false,min=0.1,description=大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0);app/model/store.js#DEFAULT_SUBJECT_CONFIG.big_group_pack_coefficient=3,normalizeSubjectConfig 对非空值 Number() 后校验有限且 >0,非法抛错 subject_config.big_group_pack_coefficient 必须是大于 0 的数字,空值/null/'' 回落默认 3。",
"历史新增来源:该字段为上一期仓库配置新增(changes 已有记录「仓库设置新增大团购打包系数」,当时同步了 setting.warehouse.getSettings 响应与 getFieldMeta 字段元信息,但遗漏 saveSettings 入参文档);本次为文档补漏修正,仅补齐该遗漏,不涉及任何代码变更。",
"文档变更范围:methods/system.json 仅 setting.warehouse.saveSettings 一条(params 在 subject_config.group_order_pack_max_minutes 之后、subject_config.single_weigh_require_pack 之前新增 subject_config.big_group_pack_coefficient;errors 新增对应 400;description 追加补漏说明);根版本 0.3.192 → 0.3.193、updatedAt 保持 2026-09-27;methods/changes/system.json 新增本条(插入数组首位);其余 method 逐字节未变。",
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库。"
]
},
{
"version": "2026.09.27-single-weigh-require-pack",
"date": "2026-09-27",
"type": "updated",
"summary": "新增仓库配置「散单称重是否需要打包」single_weigh_require_pack(默认关闭)+ 散单称重前置打包校验:开启后,订单波次范围 wave_scope 非 1(大团购)/3(小团购)且 pack_status 非 fin 的散单称重被拒绝(业务错误 code=400)。",
"methods": [
"setting.warehouse.getSettings",
"setting.warehouse.getFieldMeta",
"setting.warehouse.saveSettings",
"order.updateExpressWeighingWeight",
"workbench.sendWeight"
],
"notes": [
"代码依据:app/service/systems/setting/warehouse.js#WAREHOUSE_SETTING_FIELDS 新增 key=single_weigh_require_pack(name=散单称重是否需要打包,type=flag,default=false,required=false,位于 big_group_pack_coefficient 与 return_unpack_max_record_minutes 之间);app/model/store.js#DEFAULT_SUBJECT_CONFIG 新增默认 false,normalizeSubjectConfig 仅布尔/like-flag(true/1/'1'/'true' → true;false/0/'0'/'false → false),非法值抛错 subject_config.single_weigh_require_pack 必须是布尔值,未配置时不写该键。",
"校验逻辑(app/service/systems/order_express.js):新增 findOrderWaveAndPackStatus(current→history→dispatch 分表 + 序列表定位优先)/formatPackStatusText(none=未打包、padding=打包中、fin=已打包、error=打包异常,未知值按未打包)/isSingleWeighRequirePack(走 deliveryOrder.getStoreSubjectConfig 带缓存,缺失/读取异常按关闭)/assertSingleOrderPackedForWeigh/buildWeighPackBlockedMessage;_updateSingleOrderWeight 开头调用 assertSingleOrderPackedForWeigh,因此订单模式(order_id>0)与运单号模式(order_id=0)的散单/非团购波次路径均生效;规则:配置开启且 wave_scope ∉ {1,3} 且 pack_status != fin → 业务错误 code=400「散单称重需先完成打包:订单尚未打包(当前打包状态:未打包)」;warehouseId 缺失跳过校验;团购波次 _updateWaveOrderWeight/_updateWaveAllOrdersWeight 不校验。",
"工作台路径(app/service/systems/workbench.js):_sendWeight 订单行查询补充 wave_scope/pack_status,拦截校验后调用 _assertSingleWeighPackedForWeigh,复用 order_express.buildWeighPackBlockedMessage 文案并在末尾追加「 [条码]」,经 workbench.sendWeight 出口以业务失败(code=400)返回。",
"测试证据:test/single_weigh_require_pack.test.cjs(26 用例全部通过,覆盖配置规范化、wave_scope 1/3 跳过、未打包拦截且不落库、已打包放行、配置读取异常降级)。",
"文档变更范围:methods/system.json 更新 5 条 method(setting.warehouse.getSettings 响应新增 subject_config.single_weigh_require_pack;getFieldMeta 描述补新字段元信息;saveSettings 入参补该字段与非法值 400;order.updateExpressWeighingWeight 与 workbench.sendWeight 的 errors 补未打包拦截 400 场景);根版本 0.3.191 → 0.3.192、updatedAt 2026-09-26 → 2026-09-27;methods/changes/system.json 新增本条(插入数组首位)。分组结构、其它 method、响应结构(除 getSettings 新增 1 字段)不变。",
"维护源口径(遗留事项):methods/system.json 的维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 直接写 JSON,未连接数据库、未写库,后续由维护者决定是否同步入库(method-doc-update 或全量 method-doc-import 后重新导出)。"
]
},
{
"version": "2026.09.26-order-packing-returnUnpack-where-person-filter",
"date": "2026-09-26",

View File

@ -1,8 +1,8 @@
{
"module": "system",
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
"version": "0.3.191",
"updatedAt": "2026-09-26",
"version": "0.3.196",
"updatedAt": "2026-09-28",
"headers": [
{
"name": "platform",
@ -3003,7 +3003,7 @@
},
{
"method": "order.updateExpressWeighingWeight",
"description": "更新订单运单称重重量。支持两种模式:1) 订单模式(order_id>0):规则:订单仅一个运单时,直接写入该运单重量;多运单时,必须传 waybill_code 并按运单写入;团购波次批量设置同一重量到波次下所有订单运单,并返回拆单汇总信息(total_weight/split_count/splits/store_name/sys_logistics_name)。2) 运单号模式(order_id=0):从运单号反查订单与波次,散单/非团购波次仅更新单个运单重量,团购波次按 wave_no+business_key 批量设置并返回拆单汇总信息。",
"description": "更新订单运单称重重量。支持两种模式:1) 订单模式(order_id>0):规则:订单仅一个运单时,直接写入该运单重量;多运单时,必须传 waybill_code 并按运单写入;团购波次批量设置同一重量到波次下所有订单运单,并返回拆单汇总信息(total_weight/split_count/splits/store_name/sys_logistics_name)。2) 运单号模式(order_id=0):从运单号反查订单与波次,散单/非团购波次仅更新单个运单重量,团购波次按 wave_no+business_key 批量设置并返回拆单汇总信息。;散单称重前置打包校验:开启仓库配置 single_weigh_require_pack 后,散单路径(订单模式与运单号模式的散单/非团购波次)写入重量前校验订单波次范围与打包状态,wave_scope 非 1(大团购)/3(小团购)且 pack_status 非 fin 时拒绝称重(400);团购波次批量称重不校验;配置缺失/读取异常按关闭处理",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -3126,6 +3126,10 @@
"code": 400,
"message": "多运单订单必须传入 waybill_code"
},
{
"code": 400,
"message": "订单未打包(pack_status=padding 打包中时返回「订单打包中」)——开启仓库配置 single_weigh_require_pack 后,散单/非团购波次(wave_scope 非 1 大团购/3 小团购)订单 pack_status 未达 fin 时拒绝称重"
},
{
"code": 404,
"message": "未找到有效的订单运单记录"
@ -11668,6 +11672,109 @@
"message": "内部错误"
}
]
},
{
"method": "order.wave.fetchableOrderCount",
"description": "统计当前仓库团购可抓取订单数。口径与 order.wave.groupOrderFetchList 完全一致(同一候选条件 + items_hash 粗分组 + 团购阈值过滤),但不分页、不查订单明细,仅返回达到团购阈值分组的数量与组内订单数合计。注意与 groupOrderFetchList 的口径差异:其 pagination.total 是分组数,本方法 order_count 是命中分组的订单数合计。",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
{
"name": "Authorization",
"type": "string",
"required": true,
"description": "Bearer token"
}
],
"params": [
{
"name": "distinguish_express",
"type": "boolean",
"required": false,
"source": "body",
"description": "是否区分快递(影响分组粒度):开启后按「结构(items_hash) + 快递编码」分组,关闭(默认)仅按结构分组。"
},
{
"name": "store_id",
"type": "number",
"required": false,
"source": "body",
"description": "货主ID(仅作为筛选条件,需为非负整数)。"
},
{
"name": "same_order_quantity",
"type": "number",
"required": false,
"source": "body",
"description": "最小同组订单数量阈值(>=)。显式传入有效非负整数且大于 0 时按传入值使用;未传入或为 0 时使用仓库配置 min_group_order_fetch_quantity(默认 13)。"
},
{
"name": "shop_name",
"type": "string",
"required": false,
"source": "body",
"description": "店铺名称(shop_nick 模糊匹配)。"
},
{
"name": "stock_query",
"type": "string",
"required": false,
"source": "body",
"description": "商品模糊筛选:经 stock_warehouse / stock_barcodes → order_items 限定候选订单范围;未匹配到任何商品时直接返回 group_count=0 / order_count=0。"
}
],
"response": [
{
"name": "group_count",
"type": "number",
"required": true,
"description": "达到团购阈值的分组数(同组订单数 >= same_order_quantity)。"
},
{
"name": "order_count",
"type": "number",
"required": true,
"description": "可抓取订单数合计(命中分组内订单数之和;不含未达阈值分组的订单,也不含 items_hash/items 均为空无法分组的订单)。"
},
{
"name": "same_order_quantity",
"type": "number",
"required": true,
"description": "本次统计实际使用的团购阈值(入参值或仓库配置值)。"
},
{
"name": "raw_order_count",
"type": "number",
"required": true,
"description": "参与分组统计的候选订单总数(过滤团购阈值之前,便于核对口径)。"
},
{
"name": "warehouse_id",
"type": "number",
"required": true,
"description": "当前仓库ID(取自登录上下文 ctx.user.store_id)。"
},
{
"name": "distinguish_express",
"type": "boolean",
"required": true,
"description": "是否区分快递(回显本次分组粒度)。"
}
],
"errors": [
{
"code": "400",
"message": "未识别到当前仓库上下文"
},
{
"code": "400",
"message": "参数格式错误(如 store_id / same_order_quantity 非非负整数)"
},
{
"code": "500",
"message": "查询失败"
}
]
}
]
},
@ -15159,7 +15266,7 @@
"list": [
{
"method": "setting.warehouse.getSettings",
"description": "获取当前登录仓库的 subject_config;subject_config 新增大团购打包系数 big_group_pack_coefficient(数字,默认 3,单位秒/单,必须大于 0,用于 workbench 大团购波次打包时长闸门与倒计时)",
"description": "获取当前登录仓库的 subject_config;subject_config 新增大团购打包系数 big_group_pack_coefficient(数字,默认 3,单位秒/单,必须大于 0,用于 workbench 大团购波次打包时长闸门与倒计时);新增散单称重是否需要打包 single_weigh_require_pack(flag 布尔,默认 false 关闭;开启后散单称重(订单波次范围 wave_scope 非 1 大团购/3 小团购)前必须已打包完成 pack_status=fin,未打包时拒绝称重并返回错误)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -15304,6 +15411,12 @@
"required": false,
"description": "大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0"
},
{
"name": "subject_config.single_weigh_require_pack",
"type": "boolean",
"required": false,
"description": "散单称重是否需要打包(flag,默认 false 关闭):开启后散单称重(订单波次范围 wave_scope 非 1 大团购/3 小团购)前必须已打包完成(pack_status=fin),未打包时拒绝称重并返回错误"
},
{
"name": "subject_config.return_unpack_max_record_minutes",
"type": "number",
@ -15412,7 +15525,7 @@
},
{
"method": "setting.warehouse.getFieldMeta",
"description": "获取仓库设置字段元信息;本次 list 新增「大团购打包系数」(key=big_group_pack_coefficient,type=number,default=3,min=0.1,单位秒/单,用于大团购波次打包时长闸门与倒计时)",
"description": "获取仓库设置字段元信息;本次 list 新增「大团购打包系数」(key=big_group_pack_coefficient,type=number,default=3,min=0.1,单位秒/单,用于大团购波次打包时长闸门与倒计时);本次新增「散单称重是否需要打包」(key=single_weigh_require_pack,type=flag,default=false,required=false,开启后散单称重(wave_scope 非 1 大团购/3 小团购)前必须已打包完成 pack_status=fin)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -15497,7 +15610,7 @@
},
{
"method": "setting.warehouse.saveSettings",
"description": "修改仓库设置并清理指定仓库缓存",
"description": "修改仓库设置并清理指定仓库缓存(subject_config 支持部分字段更新,本次新增 subject_config.single_weigh_require_pack);本次文档补漏 subject_config.big_group_pack_coefficient 入参说明(对齐 getSettings/getFieldMeta 与代码实现)",
"isNeedAuth": false,
"isNeedLogin": true,
"headers": [
@ -15663,6 +15776,20 @@
"source": "body.subject_config",
"description": "团购打包最大时长,单位:分钟,默认 40,须为大于 0 的整数"
},
{
"name": "subject_config.big_group_pack_coefficient",
"type": "number",
"required": false,
"source": "body.subject_config",
"description": "大团购波次(wave_scope=1)打包中,扫描其他波次订单至少需等待「当前波次打包数 × 系数」秒,单位:秒/单,默认 3,必须大于 0;非法值报 400:subject_config.big_group_pack_coefficient 必须是大于 0 的数字"
},
{
"name": "subject_config.single_weigh_require_pack",
"type": "boolean",
"required": false,
"source": "body.subject_config",
"description": "散单称重是否需要打包(flag,默认 false 关闭):开启后散单称重(wave_scope 非 1 大团购/3 小团购)前必须已打包完成(pack_status=fin)。仅接受布尔/like-flag(true/1/'1'/'true' → true;false/0/'0'/'false' → false),非法值报 400:subject_config.single_weigh_require_pack 必须是布尔值"
},
{
"name": "subject_config.return_unpack_max_record_minutes",
"type": "number",
@ -15800,6 +15927,14 @@
"code": "400",
"message": "未识别到当前仓库/参数不合法"
},
{
"code": "400",
"message": "subject_config.single_weigh_require_pack 必须是布尔值(仅接受 true/false/1/0 及其字符串)"
},
{
"code": "400",
"message": "subject_config.big_group_pack_coefficient 必须是大于 0 的数字(非有限数字或小于等于 0 视为非法)"
},
{
"code": "404",
"message": "仓库不存在"
@ -35771,7 +35906,7 @@
},
{
"method": "workbench.sendWeight",
"description": "工作台称重上报(免登录、免权限、免鉴权,以工作台 token 鉴权):仓库由服务端从 token 解析注入(body 传入 warehouse_id/workbench_id 一律忽略,禁止前端传值),入参条码(运单号)+ 重量(单位克,必须为正整数);条码→运单记录(wms_order_express,按 waybill_code+warehouse_id 精确匹配)→ 定位订单分表(current→history→dispatch,序列表定位优先,命中先查对应分表)→ 更新运单称重重量 weighing_weight(DB 统一单位 g):散单(wave_id=0)仅更新该运单;团购波次(wave_type=1)批量更新波次下所有未拦截订单的运单称重重量并返回 total_weight(单件重量×订单数)与 order_count;非团购波次降级为散单逻辑;拦截流程中的订单不允许称重;写称重操作日志(ORDER_WEIGH,团购逐订单批量写);保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200",
"description": "工作台称重上报(免登录、免权限、免鉴权,以工作台 token 鉴权):仓库由服务端从 token 解析注入(body 传入 warehouse_id/workbench_id 一律忽略,禁止前端传值),入参条码(运单号)+ 重量(单位克,必须为正整数);条码→运单记录(wms_order_express,按 waybill_code+warehouse_id 精确匹配)→ 定位订单分表(current→history→dispatch,序列表定位优先,命中先查对应分表)→ 更新运单称重重量 weighing_weight(DB 统一单位 g):散单(wave_id=0)仅更新该运单;团购波次(wave_type=1)批量更新波次下所有未拦截订单的运单称重重量并返回 total_weight(单件重量×订单数)与 order_count;非团购波次降级为散单逻辑;拦截流程中的订单不允许称重;写称重操作日志(ORDER_WEIGH,团购逐订单批量写);保留系统日志(systemInit 未声明免日志);成功返回 flag=success、code=200;散单称重前置打包校验:开启仓库配置 single_weigh_require_pack 后,散单路径(订单 wave_scope 非 1 大团购/3 小团购)在拦截校验后校验打包状态,pack_status 非 fin 时拒绝称重(业务失败 code=400,提示末尾附 [条码]);团购波次批量称重不校验",
"isNeedAuth": false,
"isNeedLogin": false,
"isNeedRight": false,
@ -35893,6 +36028,10 @@
{
"code": "400",
"message": "订单已被拦截,无法称重 [xxx]"
},
{
"code": 400,
"message": "订单未打包(pack_status=padding 打包中时返回「订单打包中」)——开启仓库配置 single_weigh_require_pack 后,wave_scope 非 1 大团购/3 小团购 且 pack_status 非 fin 时拦截;团购波次不校验"
}
]
},

View File

@ -59,16 +59,11 @@
"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:cert-sync:precheck": "node ./script/deploy-cert-sync.cjs production precheck",
"deploy:cert-sync:install": "node ./script/deploy-cert-sync.cjs production install",
"deploy:cert-sync:dry-run": "node ./script/deploy-cert-sync.cjs production dry-run",
"deploy:cert-sync:run": "node ./script/deploy-cert-sync.cjs production run",
"deploy:cert-sync:status": "node ./script/deploy-cert-sync.cjs production status",
"deploy:cert-sync:config-check": "node ./script/deploy-cert-sync.cjs production config-check",
"deploy:cert-sync:cleanup-dry-run": "node ./script/deploy-cert-sync.cjs production cleanup-dry-run",
"deploy:cert-sync:cleanup": "node ./script/deploy-cert-sync.cjs production cleanup",
"deploy:cert-sync:uninstall": "node ./script/deploy-cert-sync.cjs production uninstall",
"deploy:watchdog:install": "node ./script/deploy-watchdog.cjs production install",
"deploy:watchdog:uninstall": "node ./script/deploy-watchdog.cjs production uninstall",
"deploy:gateway-probe": "node ./script/deploy-ops.cjs production gateway-probe",
"ops:check-root-logs": "node ./script/check-root-logs.cjs",
"ops:clean-root-logs": "node ./script/check-root-logs.cjs production --clean",
"ops:clean-root-logs:apply": "node ./script/check-root-logs.cjs production --clean --apply",

View File

@ -1,3 +1,18 @@
/**
* cert-sync 部署工具(npm 命令仅 install / uninstall 两条)。
*
* - install:校验并上传主脚本 / DB 配置;prod 配置按「首次放置一次、永不覆盖」约定处理;
* 生成薄包装 <deployRoot>/script/warehouse-cert-sync.sh 并注册 root crontab(每分钟 flock)。
* - uninstall:先备份再删除工具自身(包装脚本 / 主脚本 / 双环境配置 / database/config.js /
* 历史位置与 .prev-* / .legacy-* 备份 / crontab 行);支持 --dry-run 只打印计划。
* 证书、nginx server 块、日志、watchdog 相关一律不删(原因见输出)。
*
* 运行期手动操作仍可直接调用服务器上的包装脚本(这是主脚本 CLI 的能力,不属于本工具 npm 命令):
* <deployRoot>/script/warehouse-cert-sync.sh --dry-run
* <deployRoot>/script/warehouse-cert-sync.sh --cleanup-only --dry-run
* <deployRoot>/script/warehouse-cert-sync.sh --cleanup-only
* <deployRoot>/script/warehouse-cert-sync.sh --env production
*/
'use strict';
const fs = require('node:fs');
@ -11,26 +26,52 @@ const {
runSsh,
} = require('./deploy-lib.cjs');
const COMMANDS = new Set([ 'precheck', 'install', 'dry-run', 'run', 'status', 'config-check', 'cleanup-dry-run', 'cleanup' ]);
const COMMANDS = new Set([ 'install', 'uninstall' ]);
const LOCAL_SYNC_SCRIPT = path.join(ROOT, 'script', 'warehouse-cert-sync.cjs');
const LOCAL_DB_CONFIG = path.join(ROOT, 'database', 'config.js');
const LOCAL_PROD_CONFIG = path.join(ROOT, 'script', 'warehouse-cert-sync.config.prod.json');
/**
* 打印本工具用法(仅 install / uninstall 两条 npm 命令)。
*/
function printUsage() {
console.error([
'usage: node script/deploy-cert-sync.cjs [env] <command> [--dry-run]',
' env: production | development(默认 production)',
' command: install 上传脚本/配置、生成薄包装、注册 crontab',
' uninstall 备份并删除工具自身(脚本/配置/crontab),支持 --dry-run',
'运行期手动操作请直接调用服务器上的包装脚本(主脚本 CLI 能力,非本工具命令):',
' <deployRoot>/script/warehouse-cert-sync.sh --dry-run',
' <deployRoot>/script/warehouse-cert-sync.sh --cleanup-only --dry-run',
' <deployRoot>/script/warehouse-cert-sync.sh --cleanup-only',
' <deployRoot>/script/warehouse-cert-sync.sh --env production',
].join('\n'));
}
/**
* 解析命令行参数。
* @param {string[]} argv 原始参数数组(不含 node / 脚本名)。
* @return {{ envName: string, command: string, dryRun: boolean }} 解析结果。
*/
function parseArgs(argv) {
const options = { envName: 'production', command: '' };
const options = { envName: 'production', command: '', dryRun: false };
const tokens = [ ...argv ];
if (tokens.length === 0) {
throw new Error('missing command: precheck | install | dry-run | run | status | config-check | cleanup-dry-run | cleanup');
options.dryRun = tokens.includes('--dry-run');
const positional = tokens.filter(token => token !== '--dry-run');
if (positional.length === 0) {
printUsage();
throw new Error('missing command: install | uninstall');
}
if (!COMMANDS.has(tokens[0])) {
options.envName = tokens[0];
tokens.shift();
if (!COMMANDS.has(positional[0])) {
options.envName = positional[0];
positional.shift();
}
if (tokens.length === 0 || !COMMANDS.has(tokens[0])) {
throw new Error('missing command: precheck | install | dry-run | run | status | config-check | cleanup-dry-run | cleanup');
if (positional.length === 0 || !COMMANDS.has(positional[0])) {
printUsage();
throw new Error('missing command: install | uninstall');
}
options.command = tokens[0];
options.command = positional[0];
return options;
}
@ -142,132 +183,6 @@ exit $STATUS
`;
}
/** Read-only DB probe JS (never prints credentials). */
const DB_PROBE_JS = `
const path = require("node:path");
const Sequelize = require("sequelize");
const appDir = process.argv[1];
function load(p) {
try {
const f = require(p);
const c = typeof f === "function" ? f({ name: "cert-sync-precheck", baseDir: appDir }) : f;
return c && typeof c === "object" ? c : {};
} catch (e) { return {}; }
}
let src = "none"; let client = null;
const def = load(path.join(appDir, "config", "config.default.js"));
if (def.sequelize && def.sequelize.host) { src = "config.default.js#sequelize"; client = def.sequelize; }
else if (def.mysql && def.mysql.clients && def.mysql.clients.wms && def.mysql.clients.wms.host) { src = "config.default.js#mysql.clients.wms"; client = def.mysql.clients.wms; }
else if (def.mysql && def.mysql.host) { src = "config.default.js#mysql"; client = def.mysql; }
if (!client) {
const loc = load(path.join(appDir, "config", "config.local.js"));
if (loc.sequelize && loc.sequelize.host) { src = "config.local.js#sequelize"; client = loc.sequelize; }
else if (loc.mysql && loc.mysql.host) { src = "config.local.js#mysql"; client = loc.mysql; }
}
if (!client) { console.log("[DB_PROBE] cannot resolve db config from active instance"); process.exit(0); }
console.log("[DB_PROBE] config source: " + src + " database=" + String(client.database || ""));
const seq = new Sequelize(client.database, client.username || client.user, client.password, {
host: client.host, port: client.port || 3306, dialect: "mysql", logging: false,
});
(async () => {
try {
await seq.authenticate();
console.log("[DB_PROBE] prod db connect OK");
const [t] = await seq.query("SELECT COUNT(*) AS c FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'wms_warehouse_front_config'");
const exists = Number(t[0].c) > 0;
console.log("[DB_PROBE] wms_warehouse_front_config exists: " + (exists ? "YES" : "NO"));
if (exists) {
const [cols] = await seq.query("SELECT column_name AS cn FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = 'wms_warehouse_front_config'");
console.log("[DB_PROBE] columns: " + cols.map(r => r.cn).join(","));
const hasDomainStatus = cols.some(r => r.cn === "domain_status");
console.log("[DB_PROBE] domain_status column: " + (hasDomainStatus ? "YES" : "NO"));
const [total] = await seq.query("SELECT COUNT(*) AS c FROM wms_warehouse_front_config");
console.log("[DB_PROBE] total rows: " + total[0].c);
const [dist] = await seq.query("SELECT sync_status AS s, COUNT(*) AS c FROM wms_warehouse_front_config GROUP BY sync_status ORDER BY sync_status");
console.log("[DB_PROBE] sync_status distribution: " + (dist.length ? dist.map(r => r.s + "=" + r.c).join(" ") : "(empty)"));
if (hasDomainStatus) {
const [ddist] = await seq.query("SELECT domain_status AS s, COUNT(*) AS c FROM wms_warehouse_front_config GROUP BY domain_status ORDER BY domain_status");
console.log("[DB_PROBE] domain_status distribution: " + (ddist.length ? ddist.map(r => (r.s === null ? "null" : r.s) + "=" + r.c).join(" ") : "(empty)"));
const sumStatus = want => ddist.filter(r => Number(r.s) === want).reduce((n, r) => n + Number(r.c), 0);
console.log("[DB_PROBE] domain_status counts: 0_unverified=" + sumStatus(0) + " 1_verified=" + sumStatus(1) + " 2_failed=" + sumStatus(2));
console.log("[DB_PROBE] gated-out rows (domain_status 0/2, no nginx server block after gate): " + (sumStatus(0) + sumStatus(2)));
} else {
console.log("[DB_PROBE] domain_status distribution: (column missing, migration not applied; cert-sync falls back to no filter)");
}
const hasRetiredDomain = cols.some(r => r.cn === "retired_domain");
console.log("[DB_PROBE] retired_domain column: " + (hasRetiredDomain ? "YES" : "NO"));
if (hasRetiredDomain) {
const [rCount] = await seq.query("SELECT COUNT(*) AS c FROM wms_warehouse_front_config WHERE retired_domain IS NOT NULL AND retired_domain <> ''");
const [rPreview] = await seq.query("SELECT retired_domain AS d FROM wms_warehouse_front_config WHERE retired_domain IS NOT NULL AND retired_domain <> '' ORDER BY id ASC LIMIT 20");
const names = rPreview.map(r => String(r.d)).join(",");
console.log("[DB_PROBE] retired_domain pending: retired=" + rCount[0].c + (names ? ": " + names : ""));
} else {
console.log("[DB_PROBE] retired_domain pending: (column missing, migration not applied; cleanup flow skipped)");
}
}
} catch (e) {
console.log("[DB_PROBE] failed: " + e.message);
}
await seq.close();
})();
`;
/**
* Read-only remote precheck.
* @param {Object} config deploy 配置对象。
*/
function runPrecheck(config) {
const deployRoot = config.deployRoot;
const remoteScript = [
'set -uo pipefail',
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
'echo "[WHOAMI] $(id -un)"',
'echo "[UNAME] $(uname -a)"',
`echo "[CURRENT_MD] $(cat ${quoteForBash(`${deployRoot}/current.md`)} 2>/dev/null || echo MISSING)"`,
`echo "[DEPLOY_ROOT_LS]"; ls -la ${quoteForBash(deployRoot)} | awk '{print $1, $3, $4, $9}'`,
'echo "[NGINX_BIN]"; command -v nginx || echo "nginx not in PATH"',
'echo "[NGINX_V]"; nginx -v 2>&1 || true',
'echo "[NGINX_V_PREFIX]"; nginx -V 2>&1 | grep -E "configure arguments|--prefix" | head -2 || true',
'echo "[NGINX_T_NOW]"; nginx -t 2>&1 || true',
'echo "[NGINX_PROCESS]"; ps -eo pid=,args= | grep "[n]ginx" | head -6 || true',
'echo "[SYSTEMD_NGINX]"; systemctl is-active nginx 2>&1 || true; systemctl is-enabled nginx 2>&1 || true',
'echo "[FLOCK]"; command -v flock || echo "flock missing"',
'echo "[MAIN_CONF_INCLUDES]"; for f in /etc/nginx/nginx.conf /www/server/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf; do if [ -f "$f" ]; then echo "-- $f"; grep -n "include" "$f" | grep -v "^[[:space:]]*#" | head -20; fi; done',
'echo "[CONF_DIR_PROBE]"; for d in /etc/nginx/conf.d /www/server/nginx/conf/conf.d; do if [ -d "$d" ]; then echo "-- $d EXISTS"; ls -1 "$d" | head -20; fi; done',
'echo "[SSL_DIR] /www/wwwroot/.ssl"; if [ -d /www/wwwroot/.ssl ]; then echo EXISTS; ls -la /www/wwwroot/.ssl | head -20; else echo MISSING; fi',
'echo "[CERT_CONF_DIR] /www/wwwroot/nginx_config"; if [ -d /www/wwwroot/nginx_config ]; then echo EXISTS; ls -la /www/wwwroot/nginx_config | head -30; else echo MISSING; fi',
'echo "[PARENT_WRITABLE]"; if [ -w /www/wwwroot ]; then echo YES; else echo NO; fi',
'echo "[DEPLOY_ROOT_META]"; for p in script database config node_modules; do if [ -e "$DEPLOY_ROOT/$p" ]; then echo "$p EXISTS"; else echo "$p MISSING"; fi; done',
'echo "[V1_CONFIG_LS]"; ls -la "$DEPLOY_ROOT/v1/config" 2>/dev/null | head -20 || echo "v1/config missing"',
'echo "[V2_CONFIG_LS]"; ls -la "$DEPLOY_ROOT/v2/config" 2>/dev/null | head -20 || echo "v2/config missing"',
'echo "[V1_SEQUELIZE]"; if [ -d "$DEPLOY_ROOT/v1/node_modules/sequelize" ]; then echo YES; else echo NO; fi',
'echo "[V2_SEQUELIZE]"; if [ -d "$DEPLOY_ROOT/v2/node_modules/sequelize" ]; then echo YES; else echo NO; fi',
'echo "[EXISTING_CRON_CERT]"; crontab -l 2>/dev/null | grep -i "cert" || echo NONE',
'echo "[CRON_LINE_COUNT]"; crontab -l 2>/dev/null | grep -cv "^#" || echo 0',
'echo "[CERT_LOG_TAIL]"; tail -20 /var/log/warehouse-cert-sync.log 2>/dev/null || echo "log not exists"',
].join('\n');
console.log('[PRECHECK] remote env check (read-only)');
console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim());
const dbProbeScript = [
'set -uo pipefail',
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
'ACTIVE=$(cat "$DEPLOY_ROOT/current.md" 2>/dev/null | tr -d "[:space:]" || true)',
'APP_DIR=""',
'if [ -n "$ACTIVE" ] && [ -d "$DEPLOY_ROOT/$ACTIVE/config" ]; then APP_DIR="$DEPLOY_ROOT/$ACTIVE"; fi',
'if [ -z "$APP_DIR" ]; then for CAND in v1 v2; do if [ -d "$DEPLOY_ROOT/$CAND/config" ]; then APP_DIR="$DEPLOY_ROOT/$CAND"; break; fi; done; fi',
'if [ -z "$APP_DIR" ]; then echo "[DB_PROBE] no active instance dir found"; exit 0; fi',
'export NODE_PATH="$APP_DIR/node_modules"',
`node -e ${quoteForBash(DB_PROBE_JS)} "$APP_DIR"`,
].join('\n');
console.log('');
console.log('[PRECHECK] prod db probe (read-only, no credentials printed)');
console.log(runSsh(config, dbProbeScript, { stdio: 'pipe' }).trim());
}
/**
* Install: upload files, create thin shell wrapper, register root crontab.
* @param {Object} config deploy 配置对象。
@ -288,11 +203,14 @@ function runInstall(config) {
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
`STAMP=${quoteForBash(getNowStamp())}`,
'mkdir -p "$DEPLOY_ROOT/script" "$DEPLOY_ROOT/database"',
'for p in "$DEPLOY_ROOT/warehouse-cert-sync.sh" "$DEPLOY_ROOT/script/warehouse-cert-sync.cjs" "$DEPLOY_ROOT/database/config.js"; do',
'for p in "$DEPLOY_ROOT/script/warehouse-cert-sync.sh" "$DEPLOY_ROOT/script/warehouse-cert-sync.cjs" "$DEPLOY_ROOT/database/config.js"; do',
' if [ -f "$p" ]; then cp -a "$p" "$p.prev-$STAMP" && echo "BACKED_UP $p -> $p.prev-$STAMP"; fi',
'done',
'# 历史位置(部署根)一次性迁移:旧 wrapper 挪进 script/ 留作回滚备份,避免根目录残留孤儿',
'LEGACY="$DEPLOY_ROOT/warehouse-cert-sync.sh"',
'if [ -f "$LEGACY" ]; then mv "$LEGACY" "$DEPLOY_ROOT/script/warehouse-cert-sync.sh.legacy-$STAMP" && echo "LEGACY_MOVED $LEGACY -> $DEPLOY_ROOT/script/warehouse-cert-sync.sh.legacy-$STAMP"; fi',
].join('\n');
console.log('[INSTALL] remote dir prep + backup of existing files');
console.log('[INSTALL] remote dir prep + backup of existing files (wrapper installs under script/)');
console.log(runSsh(config, remoteDirScript, { stdio: 'pipe' }).trim());
const remoteScriptPath = `${deployRoot}/script/warehouse-cert-sync.cjs`;
@ -340,7 +258,7 @@ function runInstall(config) {
}
console.log('[INSTALL] dev config NOT uploaded (development-only)');
const wrapperPath = `${deployRoot}/warehouse-cert-sync.sh`;
const wrapperPath = `${deployRoot}/script/warehouse-cert-sync.sh`;
const installScript = [
'set -euo pipefail',
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
@ -366,119 +284,281 @@ function runInstall(config) {
}
/**
* Run the remote wrapper with optional extra args; returns output + exit code.
* useFlock=true 时用与 crontab 相同的锁文件串行化(手工清理与每分钟定时任务互斥),
* flock 不可用时只告警并降级为不加锁执行(不阻断运维操作)。
* @param {Object} config deploy 配置对象(含 deployRoot)。
* @param {string[]} extraArgs 透传给远端包装脚本的额外参数。
* @param {boolean} useFlock 是否用 flock 串行化执行,默认 false。
* @return {string} 远端输出(已 trim)。
* 把远端配置里的目录值(如 ./.ssl)按部署根解析成绝对路径。
* @param {string} deployRoot 部署根目录。
* @param {string} value 配置值(相对或绝对)。
* @param {string} fallback 解析失败时的默认值。
* @return {string} 远端绝对路径。
*/
function runRemoteWrapper(config, extraArgs = [], useFlock = false) {
const wrapperPath = `${config.deployRoot}/warehouse-cert-sync.sh`;
const runLine = useFlock
? 'FLOCK_BIN=$(command -v flock || true); if [ -n "$FLOCK_BIN" ]; then "$FLOCK_BIN" -w 30 /var/lock/warehouse-cert-sync.lock bash "$WRAPPER" $ARGS; else echo "WARN: flock not found, run without lock"; bash "$WRAPPER" $ARGS; fi'
: 'bash "$WRAPPER" $ARGS';
const remoteScript = [
'set -uo pipefail',
`WRAPPER=${quoteForBash(wrapperPath)}`,
`ARGS=${quoteForBash(extraArgs.join(' '))}`,
'if [ ! -f "$WRAPPER" ]; then echo "FATAL: wrapper missing: $WRAPPER"; exit 1; fi',
runLine,
'echo "CERT_SYNC_EXIT=$?"',
].join('\n');
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
function resolveRemotePath(deployRoot, value, fallback) {
const v = String(value || '').trim();
if (!v) return fallback;
if (v.startsWith('/')) return v;
return `${String(deployRoot).replace(/\/+$/, '')}/${v.replace(/^\.\//, '')}`;
}
/**
* Status: crontab line, remote file list, log tail.
* 只读解析服务器 prod 配置中的 certDir / confDir(用于「未触碰」清单展示)。
* 配置缺失或解析失败时回退默认值(<deployRoot>/.ssl、<deployRoot>/nginx_config),不阻断卸载流程。
* @param {Object} config deploy 配置对象。
* @return {{ certDir: string, confDir: string }} 解析出的远端绝对目录。
*/
function runStatus(config) {
function resolveServerDirs(config) {
const deployRoot = config.deployRoot;
const remoteScript = [
const defaultCertDir = `${deployRoot}/.ssl`;
const defaultConfDir = `${deployRoot}/nginx_config`;
const result = { certDir: defaultCertDir, confDir: defaultConfDir };
const cfgPath = `${deployRoot}/script/warehouse-cert-sync.config.prod.json`;
const probeScript = [
'set -uo pipefail',
'echo "[CRONTAB_CERT_LINES]"',
'crontab -l 2>/dev/null | grep -n "warehouse-cert-sync" || echo NONE',
'echo "[REMOTE_FILES]"',
`ls -la ${quoteForBash(`${deployRoot}/warehouse-cert-sync.sh`)} ${quoteForBash(`${deployRoot}/script/warehouse-cert-sync.cjs`)} ${quoteForBash(`${deployRoot}/script/warehouse-cert-sync.config.prod.json`)} ${quoteForBash(`${deployRoot}/script/warehouse-cert-sync.config.dev.json`)} ${quoteForBash(`${deployRoot}/database/config.js`)} 2>&1`,
'echo "[WRAPPER_HEAD]"',
`head -12 ${quoteForBash(`${deployRoot}/warehouse-cert-sync.sh`)} 2>/dev/null`,
'echo "[CERT_LOG_TAIL]"',
'tail -30 /var/log/warehouse-cert-sync.log 2>/dev/null || echo "log not exists"',
`CFG=${quoteForBash(cfgPath)}`,
'if [ -f "$CFG" ]; then',
` node -e ${quoteForBash('const c=JSON.parse(require("node:fs").readFileSync(process.argv[1],"utf8")); console.log("CERT_DIR="+(c.certDir||"./.ssl")); console.log("CONF_DIR="+(c.confDir||"./nginx_config"));')} "$CFG"`,
'else',
' echo "CERT_DIR=./.ssl"',
' echo "CONF_DIR=./nginx_config"',
'fi',
].join('\n');
console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim());
try {
const output = String(runSsh(config, probeScript, { stdio: 'pipe' }) || '');
for (const line of output.split('\n')) {
if (line.startsWith('CERT_DIR=')) {
result.certDir = resolveRemotePath(deployRoot, line.slice(9), defaultCertDir);
}
if (line.startsWith('CONF_DIR=')) {
result.confDir = resolveRemotePath(deployRoot, line.slice(9), defaultConfDir);
}
}
} catch (err) {
console.warn(`[UNINSTALL] 服务器目录探测失败,回退默认值:${err.message}`);
}
return result;
}
/**
* 只读核对服务器 prod 配置文件:存在性 + JSON 合法性 + 内容展示(无凭据,可安全输出)。
* @param {Object} config deploy 配置对象。
* 生成卸载目标清单:精确路径 + 历史备份 glob(.prev-* / .legacy-*)。
* @param {string} deployRoot 部署根目录。
* @return {{ exactPaths: string[], globPatterns: string[] }} 目标清单。
*/
function runConfigCheck(config) {
const deployRoot = config.deployRoot;
const remoteScript = [
function buildUninstallTargets(deployRoot) {
const exactPaths = [
`${deployRoot}/script/warehouse-cert-sync.sh`,
`${deployRoot}/warehouse-cert-sync.sh`,
`${deployRoot}/script/warehouse-cert-sync.cjs`,
`${deployRoot}/script/warehouse-cert-sync.config.prod.json`,
`${deployRoot}/script/warehouse-cert-sync.config.dev.json`,
`${deployRoot}/database/config.js`,
];
const globPatterns = [];
for (const base of [
`${deployRoot}/script/warehouse-cert-sync.sh`,
`${deployRoot}/warehouse-cert-sync.sh`,
`${deployRoot}/script/warehouse-cert-sync.cjs`,
`${deployRoot}/script/warehouse-cert-sync.config.prod.json`,
`${deployRoot}/script/warehouse-cert-sync.config.dev.json`,
`${deployRoot}/database/config.js`,
]) {
globPatterns.push(`${base}.prev-*`, `${base}.legacy-*`);
}
return { exactPaths, globPatterns };
}
/**
* 生成 dry-run 计划脚本(只读:只打印将备份/将删除的目标与将清理的 crontab 行)。
* @param {Object} config deploy 配置对象。
* @param {string} backupDir 计划使用的备份目录(dry-run 不创建)。
* @return {string} 远端 bash 脚本。
*/
function buildUninstallDryRunScript(config, backupDir) {
const { exactPaths, globPatterns } = buildUninstallTargets(config.deployRoot);
return [
'set -uo pipefail',
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
'PROD="$DEPLOY_ROOT/script/warehouse-cert-sync.config.prod.json"',
'DEV="$DEPLOY_ROOT/script/warehouse-cert-sync.config.dev.json"',
'for f in "$PROD" "$DEV"; do',
' if [ -f "$f" ]; then',
' echo "[CONFIG_EXISTS] $f"',
' if node -e \'JSON.parse(require("node:fs").readFileSync(process.argv[1], "utf8"))\' "$f" >/dev/null 2>&1; then',
' echo "[CONFIG_JSON] $f VALID"',
`B_DIR=${quoteForBash(backupDir)}`,
'echo "PLAN_BACKUP_DIR=$B_DIR"',
`for T in ${exactPaths.map(quoteForBash).join(' ')}; do`,
' if [ -f "$T" ]; then echo "WOULD_BACKUP_AND_DELETE $T"; else echo "MISSING_SKIP $T"; fi',
'done',
`for G in ${globPatterns.map(quoteForBash).join(' ')}; do`,
' for F in $G; do',
' [ -f "$F" ] || continue',
' echo "WOULD_BACKUP_AND_DELETE $F"',
' done',
'done',
'CRON_BEFORE=$(crontab -l 2>/dev/null | wc -l)',
'CRON_CERT=$(crontab -l 2>/dev/null | grep -c "warehouse-cert-sync" || true)',
'if [ "$CRON_CERT" -gt 0 ]; then',
' crontab -l 2>/dev/null | grep "warehouse-cert-sync" | sed "s|^|WOULD_REMOVE_CRON_LINE |" || true',
' echo "CRONTAB_WOULD_GO before=$CRON_BEFORE after=$((CRON_BEFORE - CRON_CERT))"',
'else',
' echo "CRONTAB_UNTOUCHED_NO_MATCH"',
'fi',
].join('\n');
}
/**
* 生成真实卸载脚本:先备份(cp -a 保留权限/时间)再删除,清理 crontab 行。
* 单项失败不中断(HAD_ERRORS 标记),证书/server 块/日志/watchdog 一律不触碰。
* @param {Object} config deploy 配置对象。
* @param {string} backupDir 备份目录(/tmp/wms-cert-sync-uninstall-<时间戳>/)。
* @return {string} 远端 bash 脚本。
*/
function buildUninstallScript(config, backupDir) {
const { exactPaths, globPatterns } = buildUninstallTargets(config.deployRoot);
return [
'set -u',
`BACKUP_DIR=${quoteForBash(backupDir)}`,
'HAD_ERRORS=0',
'mkdir -p "$BACKUP_DIR" && echo "BACKUP_DIR=$BACKUP_DIR" || { echo "BACKUP_DIR_CREATE_FAILED $BACKUP_DIR"; HAD_ERRORS=1; }',
`for T in ${exactPaths.map(quoteForBash).join(' ')}; do`,
' if [ -f "$T" ]; then',
' BASE=$(basename "$T")',
' if cp -a "$T" "$BACKUP_DIR/$BASE"; then',
' echo "BACKED_UP $T -> $BACKUP_DIR/$BASE"',
' else',
' echo "[CONFIG_JSON] $f INVALID"',
' echo "BACKUP_FAILED $T (保留未删)"',
' HAD_ERRORS=1',
' continue',
' fi',
' else',
' echo "[CONFIG_MISSING] $f"',
' if rm -f "$T"; then echo "DELETED $T"; else echo "DELETE_FAILED $T"; HAD_ERRORS=1; fi',
' fi',
'done',
'echo "[PROD_CONFIG_CONTENT]"',
'cat "$PROD" 2>/dev/null || echo "(missing)"',
'echo "[DEV_CONFIG_ON_SERVER]"',
'if [ -f "$DEV" ]; then echo YES; else echo NO; fi',
`for G in ${globPatterns.map(quoteForBash).join(' ')}; do`,
' for F in $G; do',
' [ -f "$F" ] || continue',
' BASE=$(basename "$F")',
' if cp -a "$F" "$BACKUP_DIR/$BASE"; then',
' echo "BACKED_UP $F -> $BACKUP_DIR/$BASE"',
' else',
' echo "BACKUP_FAILED $F (保留未删)"',
' HAD_ERRORS=1',
' continue',
' fi',
' if rm -f "$F"; then echo "DELETED $F"; else echo "DELETE_FAILED $F"; HAD_ERRORS=1; fi',
' done',
'done',
'CRON_BEFORE=$(crontab -l 2>/dev/null | wc -l)',
'CRON_CERT=$(crontab -l 2>/dev/null | grep -c "warehouse-cert-sync" || true)',
'if [ "$CRON_CERT" -gt 0 ]; then',
' crontab -l 2>/dev/null | grep "warehouse-cert-sync" | sed "s|^|CRON_REMOVED_LINE |" || true',
' if ( crontab -l 2>/dev/null | grep -v "warehouse-cert-sync" || true ) | crontab -; then',
' echo "CRONTAB_REWRITTEN before=$CRON_BEFORE after=$(crontab -l 2>/dev/null | wc -l)"',
' else',
' echo "CRONTAB_REWRITE_FAILED"',
' HAD_ERRORS=1',
' fi',
'else',
' echo "CRONTAB_UNTOUCHED_NO_MATCH"',
'fi',
'echo "HAD_ERRORS=$HAD_ERRORS"',
].join('\n');
console.log(runSsh(config, remoteScript, { stdio: 'pipe' }).trim());
}
/**
* 按三段结构打印卸载输出:[UNINSTALL] 备份 / [UNINSTALL] 已删除 / [UNINSTALL] 未触碰(原因)。
* @param {string} output 远端脚本输出。
* @param {boolean} dryRun 是否 dry-run(只打印计划)。
* @param {string} backupDir 备份目录路径。
* @param {{ certDir: string, confDir: string }} dirs 证书/server 块目录解析结果。
* @param {string} deployRoot 部署根目录。
*/
function printUninstallReport(output, dryRun, backupDir, dirs, deployRoot) {
const lines = String(output || '').split(/\r?\n/);
const planNote = dryRun ? '(计划,未执行)' : '';
const backupLines = [];
const deletedLines = [];
for (const line of lines) {
if (line.startsWith('PLAN_BACKUP_DIR=')) {
backupLines.push(`BACKUP_DIR=${line.slice('PLAN_BACKUP_DIR='.length)}${dryRun ? '(计划,不创建)' : ''}`);
} else if (line.startsWith('WOULD_BACKUP_AND_DELETE ')) {
const src = line.slice('WOULD_BACKUP_AND_DELETE '.length);
backupLines.push(`BACKED_UP ${src} -> ${backupDir}${src.split('/').pop()}${planNote}`);
deletedLines.push(`DELETED ${src}${planNote}`);
} else if (line.startsWith('MISSING_SKIP ')) {
backupLines.push(`SKIP ${line.slice('MISSING_SKIP '.length)}(不存在)`);
} else if (line.startsWith('BACKUP_DIR=')) {
backupLines.push(line);
} else if (line.startsWith('BACKUP_DIR_CREATE_FAILED ')) {
backupLines.push(line);
} else if (line.startsWith('BACKED_UP ')) {
backupLines.push(line);
} else if (line.startsWith('BACKUP_FAILED ')) {
backupLines.push(line);
} else if (line.startsWith('DELETED ')) {
deletedLines.push(line);
} else if (line.startsWith('DELETE_FAILED ')) {
deletedLines.push(line);
} else if (line.startsWith('WOULD_REMOVE_CRON_LINE ')) {
deletedLines.push(`CRON_REMOVED_LINE ${line.slice('WOULD_REMOVE_CRON_LINE '.length)}${planNote}`);
} else if (line.startsWith('CRON_REMOVED_LINE ')) {
deletedLines.push(line);
} else if (line.startsWith('CRONTAB_REWRITTEN ')) {
deletedLines.push(line);
} else if (line.startsWith('CRONTAB_WOULD_GO ')) {
deletedLines.push(`${line}${dryRun ? '(计划,未执行)' : ''}`);
} else if (line.startsWith('CRONTAB_UNTOUCHED_NO_MATCH')) {
deletedLines.push('crontab 无 warehouse-cert-sync 行,未改写');
}
}
console.log(`[UNINSTALL] 备份${dryRun ? '(计划)' : ''}`);
for (const line of backupLines) console.log(` ${line}`);
console.log(`[UNINSTALL] 已删除${dryRun ? '(计划)' : ''}`);
for (const line of deletedLines) console.log(` ${line}`);
console.log('[UNINSTALL] 未触碰(原因)');
console.log(` CERT_DIR_KEPT ${dirs.certDir}(运行产物:证书/私钥,nginx 仍在 include,删除会立断 443;由运维自行决定,如先切走 include 再手工删)`);
console.log(` CONF_DIR_KEPT ${dirs.confDir}(运行产物:<domain>-<ver>.conf server 块,nginx 仍在 include,同上)`);
console.log(' LOG_KEPT /var/log/warehouse-cert-sync.log(默认保留作排查线索)');
console.log(` UPSTREAM_KEPT ${deployRoot}/nginx-upstream.conf(非本工具文件,不删)`);
console.log(` WATCHDOG_KEPT ${deployRoot}/script/qimen-watchdog.*、/etc/cron.d/qimen-watchdog(看门狗相关,不属于 cert-sync 工具)`);
if (dryRun) {
console.log(`[UNINSTALL] dry-run 结束(未做任何变更)。实际执行时备份目录:${backupDir}`);
console.log('如需回滚(实际执行后):把备份目录里的文件 cp -a 回原路径并重跑 install');
return;
}
console.log(`备份目录:${backupDir}`);
console.log('如需回滚:把备份目录里的文件 cp -a 回原路径并重跑 install');
if (lines.some(line => line === 'HAD_ERRORS=1')) {
console.error('[UNINSTALL] 存在失败项(见上),可从备份目录恢复');
process.exitCode = 1;
}
}
/**
* 卸载 cert-sync 工具自身:先备份再删除(包装脚本 / 主脚本 / 双环境配置 /
* database/config.js / 历史位置与 .prev-* / .legacy-* 备份 / crontab 行)。
* 证书、nginx server 块、日志、watchdog 相关一律不删(原因见输出)。
* --dry-run 时只打印计划,不备份、不删除、不改 crontab。
* @param {Object} config deploy 配置对象。
* @param {Object} options 命令选项(dryRun)。
*/
function runUninstall(config, options) {
const backupDir = `/tmp/wms-cert-sync-uninstall-${getNowStamp()}/`;
const dirs = resolveServerDirs(config);
const remoteScript = options.dryRun
? buildUninstallDryRunScript(config, backupDir)
: buildUninstallScript(config, backupDir);
if (options.dryRun) {
console.log('[UNINSTALL] dry-run(只读:只打印计划,不备份、不删除、不改 crontab)');
} else {
console.log('[UNINSTALL] 开始卸载(先备份再删除)');
}
const output = String(runSsh(config, remoteScript, { stdio: 'pipe' }) || '');
printUninstallReport(output, options.dryRun, backupDir, dirs, config.deployRoot);
}
/**
* 入口:解析命令行参数并执行 install / uninstall。
*/
function main() {
const options = parseArgs(process.argv.slice(2));
const config = loadDeployConfig(options.envName);
if (options.command === 'precheck') {
runPrecheck(config);
return;
}
if (options.command === 'install') {
runInstall(config);
return;
}
if (options.command === 'dry-run') {
console.log('[DRY-RUN] remote dry-run (read-only, no file writes, no db updates)');
console.log(runRemoteWrapper(config, [ '--dry-run' ]));
return;
}
if (options.command === 'run') {
console.log('[RUN] remote real execution');
console.log(runRemoteWrapper(config, []));
return;
}
if (options.command === 'cleanup-dry-run') {
console.log('[CLEANUP-DRY-RUN] remote retired-domain cleanup dry-run (read-only: no file deletes, no db updates, no reload)');
console.log(runRemoteWrapper(config, [ '--cleanup-only', '--dry-run' ], true));
return;
}
if (options.command === 'cleanup') {
console.log('[CLEANUP] remote retired-domain cleanup (real execution: deletes retired conf/cert files, then nginx -t + reload)');
console.log(runRemoteWrapper(config, [ '--cleanup-only' ], true));
return;
}
if (options.command === 'status') {
runStatus(config);
return;
}
if (options.command === 'config-check') {
runConfigCheck(config);
if (options.command === 'uninstall') {
runUninstall(config, options);
return;
}
throw new Error(`unsupported command: ${options.command}`);

View File

@ -22,6 +22,12 @@ const DEFAULT_POST_DEPLOY_COMMANDS = [
'npm run stop || true',
'npm start',
];
/**
* 默认发布排除路径:应用配置 + 工程内的证书/nginx 产物目录。
* `.ssl/` 与 `nginx_config/` 同在部署根一级(工程目录内),虽已被 .gitignore 忽略,
* 这里再排一次做防御,避免将来 include 规则放宽时把私钥打进发布包。
*/
const DEFAULT_EXCLUDE_PATHS = [ 'config/**', '.ssl/**', 'nginx_config/**' ];
/**
* 发布包固定排除文件(与 config.deployExcludePaths 叠加,防御性兜底)。
@ -183,7 +189,7 @@ function normalizeDeployConfig(config, envName) {
deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length > 0
? config.deployIncludePaths
: DEFAULT_EGG_MINIMAL_INCLUDE_PATHS,
deployExcludePaths: Array.isArray(config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ],
deployExcludePaths: Array.isArray(config.deployExcludePaths) ? config.deployExcludePaths : [ ...DEFAULT_EXCLUDE_PATHS ],
sshOptions,
};
}
@ -275,7 +281,7 @@ function pathMatchesRule(filePath, rule) {
function listDeployableFiles(config) {
const output = runCommand('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]);
const includeRules = Array.isArray(config && config.deployIncludePaths) ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS;
const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ];
const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : DEFAULT_EXCLUDE_PATHS;
const allExcludeRules = [ ...excludeRules, ...RELEASE_PINNED_EXCLUDE_PATHS ];
return Array.from(new Set(

View File

@ -2,7 +2,7 @@
const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs');
const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]);
const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups' ]);
/**
* 解析命令行参数,返回环境名、命令及额外参数
@ -19,7 +19,7 @@ function parseArgs(argv) {
const tokens = [ ...argv ];
if (tokens.length === 0) {
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe');
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups');
}
const first = tokens[0];
@ -29,7 +29,7 @@ function parseArgs(argv) {
}
if (tokens.length === 0) {
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe');
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups');
}
options.command = tokens[0];
@ -148,33 +148,6 @@ function cleanupBackups(config, names) {
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
}
/**
* 对当前活跃端口的内部网关接口执行探活调用
*
* @param {object} config - 部署配置对象
* @param {string} methodName - method 名称
* @param {string} payloadText - 请求体 JSON 字符串
* @return {string} 网关接口响应内容
*/
function gatewayProbe(config, methodName, payloadText) {
if (!methodName) {
throw new Error('gateway-probe 需要 method 名称');
}
const { port } = getActivePortInfo(config);
const payload = payloadText && payloadText.trim() ? payloadText : '{}';
const remoteScript = [
'set -euo pipefail',
`METHOD_NAME=${quoteForBash(methodName)}`,
`PAYLOAD=${quoteForBash(payload)}`,
`PORT=${port}`,
'timestamp=$(date +%s)',
'curl -sS -X POST "http://127.0.0.1:$PORT/internal/v1/gateway?method=$METHOD_NAME&v=1&timestamp=$timestamp" -H "Content-Type: text/plain" --data "$PAYLOAD"',
].join('\n');
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
}
/**
* 显示远端 current.md 内容及当前活跃端口信息
*
@ -207,7 +180,7 @@ function main() {
if (options.command === 'smoke') {
showActiveInfo(config);
console.log(`[SMOKE]`);
console.log('[SMOKE]');
console.log(smokeRoutes(config));
return;
}
@ -226,16 +199,7 @@ function main() {
return;
}
if (options.command === 'gateway-probe') {
const methodName = options.args[0];
const payloadText = options.args[1] || '{}';
showActiveInfo(config);
console.log(`[GATEWAY_PROBE] method=${methodName}`);
console.log(gatewayProbe(config, methodName, payloadText));
return;
}
throw new Error(`不支持的命令: ${options.command}`);
}
main();
main();

475
script/deploy-watchdog.cjs Normal file
View File

@ -0,0 +1,475 @@
'use strict';
/**
* qimen 接口服务看门狗(keep-alive)的安装与运维工具。
*
* 与 script/deploy-cert-sync.cjs 同源思路,但对象完全不同:
* - 安装对象:script/qimen-watchdog.sh(仓库源)→ <部署根>/script/qimen-watchdog.sh(服务器稳定副本)
* - 调度载体:/etc/cron.d/qimen-watchdog(系统级 cron.d)
* **刻意不放 root crontab**:宝塔面板会整体重写 root crontab,放那儿会被冲掉。
* - 日志:/www/wwwlogs/wms/qimen-watchdog.log
*
* 为什么副本放部署根下的 script/ 目录而不是 v1/v2:
* 与证书同步脚本同理——不受版本切换与发布清理影响,版本目录里没有它的位置;
* 同时与 warehouse-cert-sync.sh / warehouse-cert-sync.cjs 收口在同一目录,运维只需看一处。
* install 会把历史位置(部署根)的同名副本一次性挪成 script/<name>.legacy-<时间戳> 备份。
*
* 设计要点:
* 1. 幂等:可重复 install;cron.d 文件用「临时文件 + mv」原子覆盖,不会出现半截配置;
* 2. 备份:覆盖前把既有副本 cp -a 成 <path>.prev-<时间戳>,保留回滚余地;
* 3. 去重:若 root crontab 里存在历史 watchdog 行(早期手工装的),install 会删掉,
* 避免与 cron.d 条目双跑——看门狗双跑会并发 kill/start 同一实例,风险很高;
* 4. 校验三连:bash -n 语法校验 + sha256 与本地源比对(不一致直接失败)+
* 远端 --dry-run 冒烟(只探活、绝不启动/杀进程);
* 5. 不碰服务:install 不重启 qimen、不 reload nginx、不动任何数据库。
*
* 用法(npm 命令仅 install / uninstall 两条):
* node script/deploy-watchdog.cjs production install
* node script/deploy-watchdog.cjs production uninstall [--dry-run]
*
* uninstall 做什么(先备份再删除):
* 1. 备份到 /tmp/qimen-watchdog-uninstall-<时间戳>/(cp -a 保留权限/时间);
* 2. **注销调度**:删除 /etc/cron.d/qimen-watchdog,并清理 root crontab 中残留的
* qimen-watchdog 行(历史手工安装可能留过,双跑会并发 kill/start 同一实例);
* 3. 删除服务器副本 <部署根>/script/qimen-watchdog.sh 及其 .prev-* / .legacy-* 备份,
* 以及历史位置 <部署根>/qimen-watchdog.sh;
* 4. **不碰**:日志 /www/wwwlogs/wms/qimen-watchdog.log、锁 /var/lock/qimen-watchdog.lock、
* 接口服务进程、nginx 与数据库(日志保留作排查线索)。
* 支持 --dry-run:只打印计划,不备份、不删除、不改 crontab。
*
* 退出码:0 成功;非 0 失败(参数非法 / 本地文件缺失 / sha 不一致 / 远端命令失败)。
*/
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const {
ROOT,
getNowStamp,
loadDeployConfig,
quoteForBash,
runScp,
runSsh,
} = require('./deploy-lib.cjs');
const COMMANDS = new Set([ 'install', 'uninstall' ]);
/** 仓库源文件(脚本本体)。 */
const LOCAL_WATCHDOG = path.join(ROOT, 'script', 'qimen-watchdog.sh');
/** 服务器副本文件名(落在部署根的 script/ 目录下,与 cert-sync 脚本同目录)。 */
const REMOTE_FILENAME = 'qimen-watchdog.sh';
/** 服务器副本相对部署根的路径。 */
const REMOTE_RELATIVE = `script/${REMOTE_FILENAME}`;
/** cron.d 文件名 / 路径(名称不含点,避免被 cron 忽略)。 */
const CRON_D_NAME = 'qimen-watchdog';
const CRON_D_PATH = `/etc/cron.d/${CRON_D_NAME}`;
const LOG_PATH = '/www/wwwlogs/wms/qimen-watchdog.log';
const LOCK_PATH = '/var/lock/qimen-watchdog.lock';
const CRON_SCHEDULE = '*/5 * * * *';
const CRON_USER = 'root';
/**
* 打印本工具用法(仅 install / uninstall 两条 npm 命令)。
*/
function printUsage() {
console.error([
'usage: node script/deploy-watchdog.cjs [env] <command> [--dry-run]',
' env: production | development(默认 production)',
' command: install 上传看门狗脚本 + 写 /etc/cron.d/qimen-watchdog(含语法/哈希/冒烟校验)',
' uninstall 注销 cron.d 与 root crontab 行,备份后删除服务器副本(支持 --dry-run)',
'运行期手动排查:直接执行服务器上的 <deployRoot>/script/qimen-watchdog.sh --dry-run',
].join('\n'));
}
/**
* 解析命令行参数。
* @param {string[]} argv process.argv.slice(2)。
* @return {{envName: string, command: string, dryRun: boolean}} 解析结果。
* @throws {Error} 缺少/非法命令时抛出。
*/
function parseArgs(argv) {
const options = { envName: 'production', command: '', dryRun: false };
const tokens = [ ...argv ];
options.dryRun = tokens.includes('--dry-run');
const positional = tokens.filter(token => token !== '--dry-run');
if (positional.length === 0) {
printUsage();
throw new Error('missing command: install | uninstall');
}
if (!COMMANDS.has(positional[0])) {
options.envName = positional[0];
positional.shift();
}
if (positional.length === 0 || !COMMANDS.has(positional[0])) {
printUsage();
throw new Error('missing command: install | uninstall');
}
options.command = positional[0];
return options;
}
/**
* 计算本地文件 sha256(十六进制,小写)。
* @param {string} filePath 文件绝对路径。
* @return {string} sha256 摘要。
*/
function localSha256(filePath) {
return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
}
/**
* 目标服务器上的看门狗脚本绝对路径。
* @param {Object} config deploy 配置对象。
* @return {string} 绝对路径。
*/
function remoteWatchdogPath(config) {
return `${config.deployRoot}/${REMOTE_RELATIVE}`;
}
/**
* 生成 /etc/cron.d/qimen-watchdog 的完整内容。
* @param {string} watchdogPath 服务器上的看门狗脚本绝对路径。
* @return {string} cron.d 文件内容(含首部注释与 env 声明)。
*/
function buildCronFileContent(watchdogPath) {
return [
'# qimen 接口服务看门狗(保活)',
'# 由 npm run deploy:watchdog:install 维护,请勿手工编辑(会被下次安装覆盖)。',
'# 仓库源:script/qimen-watchdog.sh;服务器稳定副本:<部署根>/script/qimen-watchdog.sh',
'# 放在 /etc/cron.d 而非 root crontab:宝塔面板会整体重写 root crontab,会把它冲掉。',
'# 手动验证:bash <部署根>/script/qimen-watchdog.sh --dry-run',
'SHELL=/bin/bash',
'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
`${CRON_SCHEDULE} ${CRON_USER} ${watchdogPath} >> ${LOG_PATH} 2>&1`,
'',
].join('\n');
}
/**
* 安装前只读打印目标机环境快照(部署根、current.md、cron.d、实例与端口等),
* 让安装日志保留一份「安装前」现场;只读,不启动 / 不杀任何进程。
* @param {Object} config deploy 配置对象。
* @return {void}
*/
function printTargetEnvInfo(config) {
const deployRoot = config.deployRoot;
const remoteScript = [
'set -uo pipefail',
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
`TARGET="$DEPLOY_ROOT/${REMOTE_FILENAME}"`,
'echo "[WHOAMI] $(id -un)"',
'echo "[UNAME] $(uname -a)"',
'echo "[DEPLOY_ROOT_LS]"; ls -la "$DEPLOY_ROOT" | awk \'{print $1, $3, $4, $9}\'',
'echo "[CURRENT_MD] $(cat "$DEPLOY_ROOT/current.md" 2>/dev/null | tr -d "[:space:]" || echo MISSING)"',
'echo "[UPSTREAM_CONF]"; cat "$DEPLOY_ROOT/nginx-upstream.conf" 2>/dev/null || echo "(missing)"',
'echo "[WATCHDOG_FILE]"; if [ -f "$TARGET" ]; then ls -l --time-style=full-iso "$TARGET"; sha256sum "$TARGET"; else echo "MISSING"; fi',
'echo "[CRON_D]"; if [ -f ' + quoteForBash(CRON_D_PATH) + ' ]; then cat ' + quoteForBash(CRON_D_PATH) + '; else echo "MISSING"; fi',
'echo "[CRON_SERVICE]"; systemctl is-active cron 2>/dev/null || (service cron status 2>/dev/null | head -1) || echo unknown',
'echo "[ROOT_CRONTAB_MATCH]"; crontab -l 2>/dev/null | grep -n "qimen-watchdog" || echo NONE',
'echo "[LOG]"; ls -l ' + quoteForBash(LOG_PATH) + ' 2>/dev/null || echo "log missing"; tail -5 ' + quoteForBash(LOG_PATH) + ' 2>/dev/null',
'echo "[LOCK]"; ls -l ' + quoteForBash(LOCK_PATH) + ' 2>/dev/null || echo "lock not created yet"',
'echo "[INSTANCES]"; ps -eo pid=,etime=,args= | grep "[e]gg-scripts start" | head -6 || true',
'echo "[PORTS]"; ss -lntp 2>/dev/null | grep -E ":6061|:6062" || echo "no 6061/6062 listener"',
].join('\n');
console.log('[INSTALL] 目标机环境快照(只读,不启动/不杀进程)');
console.log(String(runSsh(config, remoteScript, { stdio: 'pipe' }) || '').trim());
}
/**
* 安装:备份旧副本 → 上传脚本 → 写 cron.d → 清理历史 root crontab 行 → 语法/哈希/冒烟校验。
* @param {Object} config deploy 配置对象。
* @return {void}
*/
function runInstall(config) {
const deployRoot = config.deployRoot;
printTargetEnvInfo(config);
if (!fs.existsSync(LOCAL_WATCHDOG)) {
throw new Error(`local file missing: ${LOCAL_WATCHDOG} (script/qimen-watchdog.sh)`);
}
const localSha = localSha256(LOCAL_WATCHDOG);
const target = remoteWatchdogPath(config);
console.log(`[INSTALL] local source: ${LOCAL_WATCHDOG} sha256=${localSha}`);
const remoteDirScript = [
'set -euo pipefail',
`DEPLOY_ROOT=${quoteForBash(deployRoot)}`,
`TARGET="$DEPLOY_ROOT/${REMOTE_RELATIVE}"`,
`STAMP=${quoteForBash(getNowStamp())}`,
'mkdir -p "$DEPLOY_ROOT/script" /www/wwwlogs/wms',
'# 历史位置(部署根)一次性迁移:旧副本挪进 script/ 留作回滚备份,避免根目录残留孤儿',
'LEGACY="$DEPLOY_ROOT/qimen-watchdog.sh"',
'if [ -f "$LEGACY" ]; then mv "$LEGACY" "$DEPLOY_ROOT/script/qimen-watchdog.sh.legacy-$STAMP" && echo "LEGACY_MOVED $LEGACY -> $DEPLOY_ROOT/script/qimen-watchdog.sh.legacy-$STAMP"; fi',
'if [ -f "$TARGET" ]; then cp -a "$TARGET" "$TARGET.prev-$STAMP" && echo "BACKED_UP $TARGET -> $TARGET.prev-$STAMP"; else echo "NO_EXISTING_COPY"; fi',
`touch ${quoteForBash(LOG_PATH)} && chmod 644 ${quoteForBash(LOG_PATH)} && echo "LOG_FILE_OK"`,
].join('\n');
console.log('[INSTALL] remote dir prep + backup of existing copy');
console.log(String(runSsh(config, remoteDirScript, { stdio: 'pipe' }) || '').trim());
runScp(config, LOCAL_WATCHDOG, target);
console.log(`[INSTALL] uploaded -> ${target}`);
const finalizeScript = [
'set -euo pipefail',
`TARGET=${quoteForBash(target)}`,
`CRON_D=${quoteForBash(CRON_D_PATH)}`,
'chmod 755 "$TARGET" && echo "CHMOD_OK"',
'bash -n "$TARGET" && echo "WATCHDOG_SYNTAX_OK"',
`LOCAL_SHA=${quoteForBash(localSha)}`,
'REMOTE_SHA_LINE=$(sha256sum "$TARGET")',
'REMOTE_SHA=${REMOTE_SHA_LINE%% *}',
'if [ "$REMOTE_SHA" = "$LOCAL_SHA" ]; then echo "SHA_MATCH $REMOTE_SHA"; else echo "SHA_MISMATCH local=$LOCAL_SHA remote=$REMOTE_SHA"; exit 1; fi',
'TMP=$(mktemp /tmp/qimen-watchdog.cron.XXXXXX)',
'cat > "$TMP" <<\'QIMEN_WATCHDOG_CRON_EOF\'',
buildCronFileContent(target).replace(/\n+$/, ''),
'QIMEN_WATCHDOG_CRON_EOF',
'chown root:root "$TMP" && chmod 644 "$TMP"',
'mv "$TMP" "$CRON_D" && echo "CRON_D_WRITTEN $CRON_D"',
'echo "[CRON_D_CONTENT]"',
'cat "$CRON_D"',
'if crontab -l 2>/dev/null | grep -q "qimen-watchdog"; then',
' crontab -l 2>/dev/null | grep -v "qimen-watchdog" | crontab -',
' echo "ROOT_CRONTAB_DEDUPED (legacy watchdog line removed)"',
'else',
' echo "ROOT_CRONTAB_CLEAN"',
'fi',
'echo "[CRON_SERVICE] $(systemctl is-active cron 2>/dev/null || echo unknown)"',
'echo "[SMOKE] bash $TARGET --dry-run (probe only, never starts/kills)"',
'bash "$TARGET" --dry-run 2>&1 | tail -15 || true',
].join('\n');
console.log('[INSTALL] write cron.d + verify (syntax / sha256 / dry-run smoke)');
console.log(String(runSsh(config, finalizeScript, { stdio: 'pipe' }) || '').trim());
}
/**
* 生成卸载目标清单:服务器副本 + 历史位置 + 备份 glob(.prev-* / .legacy-*)。
* @param {string} deployRoot 部署根目录。
* @return {{ exactPaths: string[], globPatterns: string[] }} 目标清单。
*/
function buildUninstallTargets(deployRoot) {
const exactPaths = [
`${deployRoot}/${REMOTE_RELATIVE}`,
`${deployRoot}/${REMOTE_FILENAME}`,
];
const globPatterns = [];
for (const base of exactPaths) {
globPatterns.push(`${base}.prev-*`, `${base}.legacy-*`);
}
return { exactPaths, globPatterns };
}
/**
* 生成 dry-run 计划脚本(只读:只打印将备份/将删除的目标与将注销的 cron 项)。
* @param {Object} config deploy 配置对象。
* @param {string} backupDir 计划使用的备份目录(dry-run 不创建)。
* @return {string} 远端 bash 脚本。
*/
function buildUninstallDryRunScript(config, backupDir) {
const { exactPaths, globPatterns } = buildUninstallTargets(config.deployRoot);
return [
'set -uo pipefail',
`B_DIR=${quoteForBash(backupDir)}`,
'echo "PLAN_BACKUP_DIR=$B_DIR"',
`for T in ${exactPaths.map(quoteForBash).join(' ')}; do`,
' if [ -f "$T" ]; then echo "WOULD_BACKUP_AND_DELETE $T"; else echo "MISSING_SKIP $T"; fi',
'done',
`for G in ${globPatterns.map(quoteForBash).join(' ')}; do`,
' for F in $G; do',
' [ -f "$F" ] || continue',
' echo "WOULD_BACKUP_AND_DELETE $F"',
' done',
'done',
`CRON_D=${quoteForBash(CRON_D_PATH)}`,
'if [ -f "$CRON_D" ]; then echo "WOULD_BACKUP_AND_DELETE $CRON_D"; else echo "MISSING_SKIP $CRON_D"; fi',
'CRON_BEFORE=$(crontab -l 2>/dev/null | wc -l)',
'CRON_HIT=$(crontab -l 2>/dev/null | grep -c "qimen-watchdog" || true)',
'if [ "$CRON_HIT" -gt 0 ]; then',
' crontab -l 2>/dev/null | grep "qimen-watchdog" | sed "s|^|WOULD_REMOVE_CRON_LINE |" || true',
' echo "CRONTAB_WOULD_GO before=$CRON_BEFORE after=$((CRON_BEFORE - CRON_HIT))"',
'else',
' echo "CRONTAB_UNTOUCHED_NO_MATCH"',
'fi',
].join('\n');
}
/**
* 生成真实卸载脚本:先备份(cp -a 保留权限/时间)再删除,并注销调度:
* - 删除 /etc/cron.d/qimen-watchdog(先备份);
* - 清理 root crontab 中残留的 qimen-watchdog 行(历史手工安装可能留过)。
* 单项失败不中断(HAD_ERRORS 标记);日志 / 锁 / 服务 / nginx / 数据库一律不触碰。
* @param {Object} config deploy 配置对象。
* @param {string} backupDir 备份目录(/tmp/qimen-watchdog-uninstall-<时间戳>/)。
* @return {string} 远端 bash 脚本。
*/
function buildUninstallScript(config, backupDir) {
const { exactPaths, globPatterns } = buildUninstallTargets(config.deployRoot);
return [
'set -u',
`BACKUP_DIR=${quoteForBash(backupDir)}`,
'HAD_ERRORS=0',
'mkdir -p "$BACKUP_DIR" && echo "BACKUP_DIR=$BACKUP_DIR" || { echo "BACKUP_DIR_CREATE_FAILED $BACKUP_DIR"; HAD_ERRORS=1; }',
`for T in ${exactPaths.map(quoteForBash).join(' ')}; do`,
' if [ -f "$T" ]; then',
' BASE=$(basename "$T")',
' if cp -a "$T" "$BACKUP_DIR/$BASE"; then echo "BACKED_UP $T -> $BACKUP_DIR/$BASE"; else echo "BACKUP_FAILED $T (保留未删)"; HAD_ERRORS=1; continue; fi',
' if rm -f "$T"; then echo "DELETED $T"; else echo "DELETE_FAILED $T"; HAD_ERRORS=1; fi',
' else',
' echo "MISSING_SKIP $T"',
' fi',
'done',
`for G in ${globPatterns.map(quoteForBash).join(' ')}; do`,
' for F in $G; do',
' [ -f "$F" ] || continue',
' BASE=$(basename "$F")',
' if cp -a "$F" "$BACKUP_DIR/$BASE"; then echo "BACKED_UP $F -> $BACKUP_DIR/$BASE"; else echo "BACKUP_FAILED $F (保留未删)"; HAD_ERRORS=1; continue; fi',
' if rm -f "$F"; then echo "DELETED $F"; else echo "DELETE_FAILED $F"; HAD_ERRORS=1; fi',
' done',
'done',
`CRON_D=${quoteForBash(CRON_D_PATH)}`,
'if [ -f "$CRON_D" ]; then',
' if cp -a "$CRON_D" "$BACKUP_DIR/qimen-watchdog.cron.d"; then echo "BACKED_UP $CRON_D -> $BACKUP_DIR/qimen-watchdog.cron.d"; else echo "BACKUP_FAILED $CRON_D (保留未删)"; HAD_ERRORS=1; fi',
' if rm -f "$CRON_D"; then echo "CRON_D_REMOVED $CRON_D"; else echo "CRON_D_REMOVE_FAILED $CRON_D"; HAD_ERRORS=1; fi',
'else',
' echo "MISSING_SKIP $CRON_D"',
'fi',
'CRON_BEFORE=$(crontab -l 2>/dev/null | wc -l)',
'CRON_HIT=$(crontab -l 2>/dev/null | grep -c "qimen-watchdog" || true)',
'if [ "$CRON_HIT" -gt 0 ]; then',
' crontab -l 2>/dev/null | grep "qimen-watchdog" | sed "s|^|CRON_REMOVED_LINE |" || true',
' if ( crontab -l 2>/dev/null | grep -v "qimen-watchdog" || true ) | crontab -; then',
' echo "CRONTAB_REWRITTEN before=$CRON_BEFORE after=$(crontab -l 2>/dev/null | wc -l)"',
' else',
' echo "CRONTAB_REWRITE_FAILED"',
' HAD_ERRORS=1',
' fi',
'else',
' echo "CRONTAB_UNTOUCHED_NO_MATCH"',
'fi',
'echo "HAD_ERRORS=$HAD_ERRORS"',
].join('\n');
}
/**
* 打印卸载结果(三段:备份 / 已删除(含调度注销)/ 未触碰)。
* @param {string} output 远端脚本输出。
* @param {boolean} dryRun 是否 dry-run(只打印计划)。
* @param {string} backupDir 备份目录路径。
* @return {void}
*/
function printUninstallReport(output, dryRun, backupDir) {
const lines = String(output || '')
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean);
const planned = [];
const backedUp = [];
const deleted = [];
const untouched = [];
const failures = [];
for (const line of lines) {
if (line === 'HAD_ERRORS=0' || line === 'HAD_ERRORS=1') {
continue;
}
if (/^(WOULD_BACKUP_AND_DELETE|WOULD_REMOVE_CRON_LINE|CRONTAB_WOULD_GO|PLAN_BACKUP_DIR)/.test(line)) {
planned.push(line);
continue;
}
if (/^(BACKED_UP|BACKUP_DIR=)/.test(line)) {
backedUp.push(line);
continue;
}
if (/^(DELETED|CRON_D_REMOVED|CRON_REMOVED_LINE|CRONTAB_REWRITTEN)/.test(line)) {
deleted.push(line);
continue;
}
if (/^(MISSING_SKIP|CRONTAB_UNTOUCHED_NO_MATCH)/.test(line)) {
untouched.push(line);
continue;
}
if (/FAIL|ERROR/.test(line)) {
failures.push(line);
continue;
}
failures.push(`UNCLASSIFIED ${line}`);
}
const suffix = dryRun ? '(计划)' : '';
const backupLines = dryRun ? planned : backedUp;
const deleteLines = dryRun
? planned.filter(line => !line.startsWith('PLAN_BACKUP_DIR'))
: deleted;
console.log(`[UNINSTALL] 备份${suffix}`);
for (const line of (backupLines.length > 0 ? backupLines : [ '(无)' ])) {
console.log(` ${line}`);
}
console.log(`[UNINSTALL] 已删除 / 已注销调度${suffix}`);
for (const line of (deleteLines.length > 0 ? deleteLines : [ '(无)' ])) {
console.log(` ${line}`);
}
console.log('[UNINSTALL] 未触碰(原因)');
for (const line of untouched) {
console.log(` ${line}`);
}
console.log(` 日志(保留作排查线索):${LOG_PATH}`);
console.log(` 锁文件(空闲时本就不存在):${LOCK_PATH}`);
console.log(' 接口服务进程 / nginx / 数据库:本工具从不触碰');
if (failures.length > 0) {
console.error('[UNINSTALL] 失败项');
for (const line of failures) {
console.error(` ${line}`);
}
}
console.log(`[UNINSTALL] 备份目录:${backupDir}`);
}
/**
* 卸载:备份 → 注销调度(/etc/cron.d 与 root crontab 残留行)→ 删除服务器副本。
* @param {Object} config deploy 配置对象。
* @param {{dryRun: boolean}} options 解析后的参数。
* @return {void}
*/
function runUninstall(config, options) {
const backupDir = `/tmp/qimen-watchdog-uninstall-${getNowStamp()}/`;
const script = options.dryRun
? buildUninstallDryRunScript(config, backupDir)
: buildUninstallScript(config, backupDir);
if (options.dryRun) {
console.log('[UNINSTALL] dry-run(只读:只打印计划,不备份、不删除、不改 crontab)');
} else {
console.log('[UNINSTALL] 开始卸载(先备份再删除,并注销 /etc/cron.d 与 root crontab 行)');
}
const output = String(runSsh(config, script, { stdio: 'pipe' }) || '');
printUninstallReport(output, options.dryRun, backupDir);
if (options.dryRun) {
console.log('[UNINSTALL] dry-run 结束(未做任何变更)');
return;
}
if (/(^|\n)HAD_ERRORS=1/.test(output)) {
console.error('[UNINSTALL] 存在失败项(见上),可从备份目录恢复');
process.exitCode = 1;
}
}
function main() {
const options = parseArgs(process.argv.slice(2));
const config = loadDeployConfig(options.envName);
if (options.command === 'install') {
runInstall(config);
return;
}
if (options.command === 'uninstall') {
runUninstall(config, options);
return;
}
throw new Error(`unsupported command: ${options.command}`);
}
main();

233
script/qimen-watchdog.sh Normal file
View File

@ -0,0 +1,233 @@
#!/bin/bash
#
# qimen 接口服务看门狗(保活)
#
# 目的:每 5 分钟探活一次当前版本;探活失败且重试仍失败时,**按 deploy 完全相同的方式**把
# current.md 指定的版本拉起来。启动方式与 script/deploy-remote.cjs 严格对齐:
# 1) 释放目标端口残留进程(先 kill 优雅停止 → sleep 30 → 仍占用则 kill -9 + fuser -k);
# 2) cd <目标版本目录> && nohup bash -lc 'npm start' > /tmp/wms-<ver>-start.log 2>&1 &;
# 3) 健康检查 curl -fsS --connect-timeout 2 --max-time 3 http://127.0.0.1:<port>/,
# 10 次 × 2s(与 deploy 的 20s 等待窗口一致)。
#
# 保活范围(两个来源取并集,去重;正常情况下二者相同):
# - current.md → 「当前版本」
# - nginx-upstream.conf → nginx 实际转发到的版本(发布过程中可能出现短暂不一致)
# 两者不一致时打印 WARN 并同时保活,避免「nginx 指向的实例挂了却没人管」。
#
# 为什么探活要重试 3 次再动作:发布过程中 deploy 会先写 current.md、再启动新实例、最后切
# upstream。写 current.md 到新实例就绪之间有约 3 秒空窗,6 秒重试确认正好覆盖这个窗口,
# 避免看门狗与 deploy 同时启动同一实例。
#
# 为什么启动前要按目录清残留进程:若 master 被 kill -9,worker 会被 init 收养继续跑
# (端口已释放但进程还在),此时直接再启动会出现两份实例 → egg schedule 重复执行
# (重复推送/重复回信)。按 deploy 的做法先清干净再启动。
#
# 用法:
# bash qimen-watchdog.sh # 正常保活
# bash qimen-watchdog.sh --dry-run # 只探活并报告,绝不启动/杀进程(用于验证)
# QIMEN_DEPLOY_ROOT=/xxx bash ... # 覆盖部署根目录(默认 /www/wwwroot/qimen)
#
# cron(系统级,不放在 root crontab —— 宝塔面板会整体重写 root crontab,会把它冲掉):
# /etc/cron.d/qimen-watchdog
# */5 * * * * root /www/wwwroot/qimen/script/qimen-watchdog.sh >> /www/wwwlogs/wms/qimen-watchdog.log 2>&1
#
# 仓库源文件:script/qimen-watchdog.sh(本文件是它在服务器上的稳定副本,更新后需重新安装;
# 放 deploy 根下的 script/ 目录而非 v1/v2 内,是为了不受版本切换与发布清理影响,
# 并与 warehouse-cert-sync.sh / warehouse-cert-sync.cjs 收口在同一目录)。
#
# 安装/更新:npm run deploy:watchdog:install(script/deploy-watchdog.cjs;
# 会把历史位置 <部署根>/qimen-watchdog.sh 挪成 script/<名>.legacy-<时间戳> 备份)。
#
set -u
DEPLOY_ROOT=${QIMEN_DEPLOY_ROOT:-/www/wwwroot/qimen}
PROBE_PATH=${QIMEN_PROBE_PATH:-/}
CURRENT_MD="$DEPLOY_ROOT/current.md"
UPSTREAM_CONF="$DEPLOY_ROOT/nginx-upstream.conf"
LOCK_FILE=${QIMEN_WATCHDOG_LOCK:-/var/lock/qimen-watchdog.lock}
TAG='[qimen-watchdog]'
DRY_RUN=0
for arg in "$@"; do
case "$arg" in
--dry-run) DRY_RUN=1 ;;
-h|--help)
sed -n '2,40p' "$0"
exit 0
;;
esac
done
now() { date '+%F %T'; }
say() { echo "$(now) $TAG $*"; }
# 版本 ↔ 端口(与 script/deploy-remote.cjs 的 getTargetPort 一致)
port_of() {
case "$1" in
v1) echo 6061 ;;
v2) echo 6062 ;;
*) echo '' ;;
esac
}
# 探活:与 deploy 的健康检查同一条命令
probe() {
curl -fsS --connect-timeout 2 --max-time 3 "http://127.0.0.1:$1$PROBE_PATH" >/dev/null 2>&1
}
# 取端口占用进程(与 deploy 的 killPortScript 同一套 ss/awk/grep 写法)
port_pid() {
ss -tlnp 2>/dev/null \
| awk -v p=":$1 " 'index($0, p) { print $0 }' \
| grep -oP 'pid=\K[0-9]+' | head -1 || true
}
# 取某版本目录下的 node 进程(与 deploy 的 stopOldScript / killNewScript 同一套写法)
dir_pids() {
ps -eo pid=,args= 2>/dev/null \
| awk -v root="$1" 'index($0, root) && $2 ~ /node$/ { print $1 }' || true
}
# ---------------------------------------------------------------------------
# 0. 串行化:上一轮没跑完就跳过,避免并发重复启动
# ---------------------------------------------------------------------------
if ! ( exec 9>"$LOCK_FILE" ) 2>/dev/null; then
say "ERROR 无法打开锁文件 $LOCK_FILE,本轮跳过"
exit 1
fi
exec 9>"$LOCK_FILE"
if ! flock -n 9; then
say "上一轮尚未结束,本轮跳过"
exit 0
fi
# ---------------------------------------------------------------------------
# 1. 确定要保活的版本集合
# ---------------------------------------------------------------------------
CURRENT_VER=$(tr -d '\r\n' < "$CURRENT_MD" 2>/dev/null || true)
UPSTREAM_PORT=$(grep -oE '127\.0\.0\.1:[0-9]+' "$UPSTREAM_CONF" 2>/dev/null | head -1 | grep -oE '[0-9]+$' || true)
case "$UPSTREAM_PORT" in
6061) UPSTREAM_VER=v1 ;;
6062) UPSTREAM_VER=v2 ;;
*) UPSTREAM_VER='' ;;
esac
TARGETS=''
for v in "$CURRENT_VER" "$UPSTREAM_VER"; do
case "$v" in
v1|v2) ;;
*) continue ;;
esac
case " $TARGETS " in
*" $v "*) ;;
*) TARGETS="$TARGETS $v" ;;
esac
done
if [ -z "$TARGETS" ]; then
say "ERROR 无法确定目标版本(current.md='$CURRENT_VER' upstream_port='$UPSTREAM_PORT'),本轮跳过"
exit 1
fi
if [ "$CURRENT_VER" != "$UPSTREAM_VER" ]; then
say "WARN current.md=$CURRENT_VER 与 upstream=$UPSTREAM_VER 不一致(可能正在发布),本轮同时保活:$TARGETS"
fi
RC=0
# ---------------------------------------------------------------------------
# 2. 逐版本探活 → 不活则按 deploy 方式启动
# ---------------------------------------------------------------------------
for ver in $TARGETS; do
port=$(port_of "$ver")
dir="$DEPLOY_ROOT/$ver"
pid=$(port_pid "$port")
if probe "$port"; then
say "OK $ver:$port 存活 (pid=${pid:-?})"
continue
fi
# 二次确认:6 秒内再探 3 次,覆盖「发布中 current.md 已写、实例还没起来」的空窗
confirmed_down=0
for _ in 1 2 3; do
sleep 2
if probe "$port"; then
confirmed_down=0
break
fi
confirmed_down=1
done
if [ "$confirmed_down" = 0 ]; then
say "OK $ver:$port 存活(首次探活失败,重试后恢复,判定为瞬时抖动)"
continue
fi
say "DOWN $ver:$port 连续 4 次探活失败(pid=${pid:-无}),开始按 deploy 相同方式恢复"
if [ "$DRY_RUN" = 1 ]; then
say "DRY-RUN 跳过启动:cd $dir && nohup bash -lc 'npm start' > /tmp/wms-$ver-start.log 2>&1 &"
RC=1
continue
fi
# 2.1 释放端口残留进程(与 deploy 的 killPortScript 一致)
if [ -n "$pid" ]; then
say "端口 $port 被进程 $pid 占用,发送优雅停止信号"
kill "$pid" 2>/dev/null || true
sleep 30
pid_check=$(port_pid "$port")
if [ -n "$pid_check" ]; then
say "端口 $port 仍有残留进程 $pid_check,强制停止"
kill -9 "$pid_check" 2>/dev/null || true
fuser -k "$port/tcp" 2>/dev/null || true
fi
else
say "端口 $port 空闲"
fi
# 2.2 端口已空闲时,清理该目录下可能被 init 收养的孤儿 node 进程
# (master 被 kill -9 后 worker 存活、端口已释放,不清会导致两份实例重复跑定时任务)
orphans=$(dir_pids "$dir")
if [ -n "$orphans" ]; then
say "清理 $ver 目录下的孤儿进程: $orphans"
# shellcheck disable=SC2086
kill $orphans 2>/dev/null || true
sleep 5
orphans_left=$(dir_pids "$dir")
if [ -n "$orphans_left" ]; then
say "孤儿进程未退出,强制停止: $orphans_left"
# shellcheck disable=SC2086
kill -9 $orphans_left 2>/dev/null || true
fi
fi
# 2.3 启动(与 deploy 完全一致:目标目录 + nohup bash -lc 'npm start' + /tmp/wms-<ver>-start.log)
if [ ! -d "$dir" ]; then
say "ERROR 目标目录不存在: $dir,无法启动"
RC=1
continue
fi
start_log="/tmp/wms-$ver-start.log"
( cd "$dir" && nohup bash -lc 'npm start' > "$start_log" 2>&1 & )
say "已在 $dir 启动 $ver,启动日志: $start_log"
# 2.4 健康检查(与 deploy 一致:10 次 × 2s)
started=0
for _ in $(seq 1 10); do
if probe "$port"; then
started=1
break
fi
sleep 2
done
if [ "$started" = 1 ]; then
say "RECOVERED $ver:$port 启动成功且探活通过 (pid=$(port_pid "$port" || true))"
else
say "ERROR $ver:$port 启动后 20s 内仍未通过探活,请检查 $start_log"
RC=1
fi
done
exit $RC

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,10 @@
{
"description": "开发环境配置(Windows 本机 / 宝塔 Windows 版 nginx,nginx.exe)。nginx.exe 从任意 cwd 启动时会把启动目录当作前缀,导致读不到 conf/nginx.conf,因此 test/reload 命令必须带 -p 前缀指向 D:/BtSoft/nginx/;-p 的值使用正斜杠形式,经 win 版 nginx -t 实测可用。",
"description": "开发环境配置(Windows 本机 / 宝塔 Windows 版 nginx,nginx.exe)。证书与 nginx 配置目录同样在【工程目录内】(仓库根 D:/wms/.ssl 与 D:/wms/nginx_config),与生产 <部署根>/.ssl、<部署根>/nginx_config 同构。nginx.exe 从任意 cwd 启动时会把启动目录当作前缀,导致读不到 conf/nginx.conf,因此 test/reload 命令必须带 -p 前缀指向 D:/BtSoft/nginx/;-p 的值使用正斜杠形式,经 win 版 nginx -t 实测可用。ver 为 conf 命名版本:生成的 server 块文件名为 <domainSafe><suffix>-<ver>.conf(如 web.wms.gztbyc.com-1.conf);证书/私钥文件名不变。站点内容片段路径 = upstreamInclude(开发为 D:/wms/nginx-upstream-local.conf,运维维护):生成的 server 块 = 证书骨架 + 一行 include <upstreamInclude>,站点 root / 伪静态 或 反代统一由该片段提供,脚本绝不覆盖,前端个性化在运行时由配置接口按域名完成。",
"nginxBin": "D:/BtSoft/nginx/nginx.exe",
"nginxPrefix": "D:/BtSoft/nginx/",
"certDir": "D:/wms/.ssl",
"confDir": "D:/wms/nginx_config",
"ver": "1",
"upstreamInclude": "D:/wms/nginx-upstream-local.conf",
"testCmd": "{nginxBin} -p {nginxPrefix} -t",
"reloadCmd": "{nginxBin} -p {nginxPrefix} -s reload"

View File

@ -1,10 +1,11 @@
{
"description": "生产环境配置(Linux 服务器 / 宝塔构建 nginx,systemd 管理)。脚本以部署根 /www/wwwroot/qimen 为 cwd 运行,certDir/confDir 相对 cwd 解析到上一级;reload 走 systemctl reload nginx,test 直接调 /usr/bin/nginx -t。",
"description": "生产环境配置(Linux 服务器 / 宝塔构建 nginx,systemd 管理)。脚本以部署根 /www/wwwroot/qimen 为 cwd 运行;证书与生成的 server 块固定放在【工程目录内】:certDir=<部署根>/.ssl、confDir=<部署根>/nginx_config(相对 cwd 解析,目录不存在时自动递归创建),与开发环境仓库根的 .ssl / nginx_config 同构。目录名是【硬约定】,改名必须同步改:① nginx 主配置的 include;② 本文件;③ 库表 wms_warehouse_front_config.cert_path/key_path(触发重同步刷新),详见 README「发布与运维」。ver 为 conf 命名版本:生成的 server 块文件名为 <domainSafe><suffix>-<ver>.conf(如 web.wms.gztbyc.com-1.conf);证书/私钥文件名不变。轮转时改本键(或传 --ver / CERT_SYNC_VER),下一轮脚本自动删除旧命名并生成新命名后 reload。站点内容片段路径 = upstreamInclude(生产为 /www/wwwroot/qimen/front.conf,运维维护):生成的 server 块 = 证书骨架 + 一行 include <upstreamInclude>,站点 root / 伪静态 或 反代统一由该片段提供,脚本绝不覆盖,前端个性化在运行时由配置接口按域名完成。【红线】upstreamInclude 必须写绝对路径且片段文件必须先存在(nginx 解析相对 include 的基准是 nginx prefix,如 /www/server/nginx/conf,不是脚本 cwd;写相对路径会让 nginx -t 失败并回滚整轮变更);脚本启动即校验,不满足直接 exit 1。reload 走 systemctl reload nginx,test 直接调 /usr/bin/nginx -t。",
"nginxBin": "/usr/bin/nginx",
"nginxPrefix": "",
"certDir": "../.ssl",
"confDir": "../nginx_config",
"upstreamInclude": "/www/wwwroot/qimen/nginx-upstream.conf",
"certDir": "./.ssl",
"confDir": "./nginx_config",
"ver": "1",
"upstreamInclude": "/www/wwwroot/qimen/front.conf",
"testCmd": "{nginxBin} -t",
"reloadCmd": "systemctl reload nginx"
}

View File

@ -0,0 +1,203 @@
/**
* 货主角色组授权脚本
*
* 用法: node scripts/auth/grant-store-up.js <权限ID>
* 示例: node scripts/auth/grant-store-up.js 630
*
* 授权目标(货主侧全部角色):
* - 内置货主管理员角色(role_code='store_admin_default' 且 store_id IS NULL)
* - 各货主自建角色(store_id IS NOT NULL 的全部角色)
* permissions='*' 的通配符角色自动拥有所有权限,跳过
*/
const path = require('path');
const { createRequire } = require('module');
const PROJECT_ROOT = path.join(__dirname, '..', '..');
const projectRequire = createRequire(path.join(PROJECT_ROOT, 'package.json'));
const mysql = projectRequire('mysql2/promise');
// ── 数据库连接 ──
function loadDbConfig(env) {
const configFile = env === 'production'
? path.join(PROJECT_ROOT, 'config', 'config.default.js')
: path.join(PROJECT_ROOT, 'config', 'config.local.js');
const factory = require(configFile);
const cfg = typeof factory === 'function'
? factory({ name: 'wms', baseDir: PROJECT_ROOT })
: factory;
if (env === 'production') {
return cfg.sequelize;
}
return cfg.mysql && cfg.mysql.clients && cfg.mysql.clients.wms;
}
async function createConnection(env) {
const cfg = loadDbConfig(env);
if (!cfg) throw new Error(`无法加载 ${env} 数据库配置`);
return mysql.createConnection({
host: cfg.host,
port: cfg.port || 3306,
user: cfg.username || cfg.user,
password: cfg.password,
database: cfg.database,
});
}
// ── 权限校验 ──
async function getPermission(conn, permId) {
const [ rows ] = await conn.query(
'SELECT id, name, meta_title, type, path FROM wms_permission WHERE id = ?',
[ permId ]
);
return rows[0] || null;
}
// ── 货主角色查询 ──
async function loadStoreRoles(conn) {
const [ rows ] = await conn.query(
'SELECT id, store_id, role_code, role_name, permissions FROM wms_role '
+ 'WHERE deleted_at IS NULL AND (store_id IS NOT NULL OR (store_id IS NULL AND role_code = ?)) '
+ 'ORDER BY id',
[ 'store_admin_default' ]
);
return rows;
}
// ── 授权逻辑 ──
async function grantPermission(conn, permId, envLabel) {
const results = [];
const storeRoles = await loadStoreRoles(conn);
if (storeRoles.length === 0) {
console.log(' 未找到任何货主角色');
return results;
}
for (const record of storeRoles) {
const role = {
id: Number(record.id),
name: `${record.role_name || '(无名称)'}${record.store_id ? `(store:${record.store_id})` : ''}`,
};
// 通配符角色跳过
if (record.permissions === '*') {
results.push({ role, status: 'wildcard', msg: '已有通配符 *,跳过' });
continue;
}
// 解析权限数组
let perms;
try {
perms = JSON.parse(record.permissions);
} catch {
results.push({ role, status: 'error', msg: 'permissions JSON 解析失败' });
continue;
}
if (!Array.isArray(perms)) {
results.push({ role, status: 'error', msg: 'permissions 不是数组' });
continue;
}
if (perms.includes(Number(permId))) {
results.push({ role, status: 'skip', msg: `已包含权限 ${permId}` });
continue;
}
// 添加权限并排序
perms.push(Number(permId));
perms.sort((a, b) => a - b);
await conn.query('UPDATE wms_role SET permissions = ? WHERE id = ?', [
JSON.stringify(perms),
record.id,
]);
results.push({ role, status: 'ok', msg: '已添加', count: perms.length });
}
return results;
}
// ── 主流程 ──
async function main() {
const permId = process.argv[2];
if (!permId || isNaN(Number(permId))) {
console.error('用法: node scripts/auth/grant-store-up.js <权限ID>');
console.error('示例: node scripts/auth/grant-store-up.js 630');
process.exit(1);
}
const permIdNum = Number(permId);
console.log('═══════════════════════════════════════');
console.log(' 货主角色组授权脚本');
console.log('═══════════════════════════════════════');
console.log(` 权限 ID: ${permIdNum}`);
console.log(' 目标角色: 内置货主管理员(store_admin_default) + 各货主自建角色(store_id 非空)');
console.log(' 通配符角色(permissions=*): 跳过');
console.log('═══════════════════════════════════════\n');
// ── 开发环境:查询权限信息 ──
let devConn;
try {
devConn = await createConnection('dev');
} catch (e) {
console.error(`[DEV] 开发环境连接失败: ${e.message}`);
process.exit(1);
}
const perm = await getPermission(devConn, permIdNum);
if (!perm) {
console.error(`[DEV] 权限 ${permIdNum} 在数据库中不存在!`);
await devConn.end();
process.exit(1);
}
console.log(`权限信息: ${perm.meta_title || '(无名称)'} [${perm.type}] ${perm.path || ''}\n`);
// ── 开发环境授权 ──
console.log('[DEV] 开发环境 ======');
const devResults = await grantPermission(devConn, permIdNum, '[DEV]');
for (const r of devResults) {
const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌';
const extra = r.status === 'ok' ? ` (共${r.count}个权限)` : '';
console.log(` ${icon} ${r.role.name}(id=${r.role.id}): ${r.msg}${extra}`);
}
await devConn.end();
// ── 生产环境授权 ──
console.log('\n[PROD] 生产环境 ======');
let prodConn;
try {
prodConn = await createConnection('production');
} catch (e) {
console.error(` 生产环境连接失败: ${e.message}`);
process.exit(1);
}
const prodResults = await grantPermission(prodConn, permIdNum, '[PROD]');
for (const r of prodResults) {
const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌';
const extra = r.status === 'ok' ? ` (共${r.count}个权限)` : '';
console.log(` ${icon} ${r.role.name}(id=${r.role.id}): ${r.msg}${extra}`);
}
await prodConn.end();
console.log('\n═══════════════════════════════════════');
console.log(' 授权完成');
console.log('═══════════════════════════════════════');
}
main().catch(e => {
console.error('执行失败:', e.message);
process.exit(1);
});

200
scripts/auth/grant-wh-up.js Normal file
View File

@ -0,0 +1,200 @@
/**
* 仓库组及以上角色授权脚本
*
* 用法: node scripts/auth/grant-wh-up.js <权限ID>
* 示例: node scripts/auth/grant-wh-up.js 634
*
* 授权链路: 仓库组-员工(27) → 仓库组-主管(26) → 经理(8)
* 仓库管理员(2)和超级管理员(7)已有通配符 *,自动拥有所有权限,无需处理
*/
const path = require('path');
const { createRequire } = require('module');
const PROJECT_ROOT = path.join(__dirname, '..', '..');
const projectRequire = createRequire(path.join(PROJECT_ROOT, 'package.json'));
const mysql = projectRequire('mysql2/promise');
// ── 仓库链路角色(从低到高) ──
const WH_CHAIN_ROLES = [
{ id: 27, code: 'warehouse_role', name: '仓库组-员工' },
{ id: 26, code: 'warehouse', name: '仓库组-主管' },
{ id: 8, code: '2', name: '经理' },
];
// 已有通配符 * 的角色,自动拥有所有权限,跳过
const WILDCARD_ROLES = [ 7, 2 ];
// ── 数据库连接 ──
function loadDbConfig(env) {
const configFile = env === 'production'
? path.join(PROJECT_ROOT, 'config', 'config.default.js')
: path.join(PROJECT_ROOT, 'config', 'config.local.js');
const factory = require(configFile);
const cfg = typeof factory === 'function'
? factory({ name: 'wms', baseDir: PROJECT_ROOT })
: factory;
if (env === 'production') {
return cfg.sequelize;
}
return cfg.mysql && cfg.mysql.clients && cfg.mysql.clients.wms;
}
async function createConnection(env) {
const cfg = loadDbConfig(env);
if (!cfg) throw new Error(`无法加载 ${env} 数据库配置`);
return mysql.createConnection({
host: cfg.host,
port: cfg.port || 3306,
user: cfg.username || cfg.user,
password: cfg.password,
database: cfg.database,
});
}
// ── 权限校验 ──
async function getPermission(conn, permId) {
const [ rows ] = await conn.query(
'SELECT id, name, meta_title, type, path FROM wms_permission WHERE id = ?',
[ permId ]
);
return rows[0] || null;
}
// ── 授权逻辑 ──
async function grantPermission(conn, permId, envLabel) {
const results = [];
for (const role of WH_CHAIN_ROLES) {
const [ rows ] = await conn.query(
'SELECT id, role_code, role_name, permissions FROM wms_role WHERE id = ? AND deleted_at IS NULL',
[ role.id ]
);
if (rows.length === 0) {
results.push({ role, status: 'not_found', msg: '角色不存在或已删除' });
continue;
}
const record = rows[0];
// 通配符角色跳过
if (record.permissions === '*') {
results.push({ role, status: 'wildcard', msg: '已有通配符 *,跳过' });
continue;
}
// 解析权限数组
let perms;
try {
perms = JSON.parse(record.permissions);
} catch {
results.push({ role, status: 'error', msg: 'permissions JSON 解析失败' });
continue;
}
if (!Array.isArray(perms)) {
results.push({ role, status: 'error', msg: 'permissions 不是数组' });
continue;
}
if (perms.includes(Number(permId))) {
results.push({ role, status: 'skip', msg: `已包含权限 ${permId}` });
continue;
}
// 添加权限并排序
perms.push(Number(permId));
perms.sort((a, b) => a - b);
await conn.query('UPDATE wms_role SET permissions = ? WHERE id = ?', [
JSON.stringify(perms),
role.id,
]);
results.push({ role, status: 'ok', msg: '已添加', count: perms.length });
}
return results;
}
// ── 主流程 ──
async function main() {
const permId = process.argv[2];
if (!permId || isNaN(Number(permId))) {
console.error('用法: node scripts/auth/grant-wh-up.js <权限ID>');
console.error('示例: node scripts/auth/grant-wh-up.js 634');
process.exit(1);
}
const permIdNum = Number(permId);
console.log('═══════════════════════════════════════');
console.log(' 仓库组及以上角色授权脚本');
console.log('═══════════════════════════════════════');
console.log(` 权限 ID: ${permIdNum}`);
console.log(` 目标角色: ${WH_CHAIN_ROLES.map(r => `${r.name}(${r.id})`).join(' → ')}`);
console.log(` 通配符角色(跳过): id=${WILDCARD_ROLES.join(',')} (已有 *)`);
console.log('═══════════════════════════════════════\n');
// ── 开发环境:查询权限信息 ──
let devConn;
try {
devConn = await createConnection('dev');
} catch (e) {
console.error(`[DEV] 开发环境连接失败: ${e.message}`);
process.exit(1);
}
const perm = await getPermission(devConn, permIdNum);
if (!perm) {
console.error(`[DEV] 权限 ${permIdNum} 在数据库中不存在!`);
await devConn.end();
process.exit(1);
}
console.log(`权限信息: ${perm.meta_title || '(无名称)'} [${perm.type}] ${perm.path || ''}\n`);
// ── 开发环境授权 ──
console.log('[DEV] 开发环境 ======');
const devResults = await grantPermission(devConn, permIdNum, '[DEV]');
for (const r of devResults) {
const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌';
const extra = r.status === 'ok' ? ` (共${r.count}个权限)` : '';
console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`);
}
await devConn.end();
// ── 生产环境授权 ──
console.log('\n[PROD] 生产环境 ======');
let prodConn;
try {
prodConn = await createConnection('production');
} catch (e) {
console.error(` 生产环境连接失败: ${e.message}`);
process.exit(1);
}
const prodResults = await grantPermission(prodConn, permIdNum, '[PROD]');
for (const r of prodResults) {
const icon = r.status === 'ok' ? '✅' : r.status === 'skip' ? '⏭️' : r.status === 'wildcard' ? '🔹' : '❌';
const extra = r.status === 'ok' ? ` (共${r.count}个权限)` : '';
console.log(` ${icon} ${r.role.name}(${r.role.id}): ${r.msg}${extra}`);
}
await prodConn.end();
console.log('\n═══════════════════════════════════════');
console.log(' 授权完成');
console.log('═══════════════════════════════════════');
}
main().catch(e => {
console.error('执行失败:', e.message);
process.exit(1);
});