Compare commits

...

9 Commits

Author SHA1 Message Date
9924c8d1c9 Merge pull request 'fix(wle): 超时参数真正生效 —— 售后拦截 20s 不重试、表级探测走 querySlow' (#98) 2026-11-14 09:51:28 +08:00
936d391142 Merge pull request 'fix(wle): 正文写明物流快照是否覆盖核验时刻 / 是否过旧' (#97) 2026-11-14 09:51:25 +08:00
2f44cdce82 Merge pull request 'fix(wle): 钉钉推送失败后自动重试,不再「一天只有一次机会」' (#96) 2026-11-14 09:51:21 +08:00
3062182417 fix(wle): 超时参数真正生效 —— 售后拦截 20s 不重试、表级探测走 querySlow
11-13 09:10 那轮钉钉推送 300s 超时没发出去。除了业务库本身变慢,代码里还有两笔白等:

1. `{ timeoutMs: 240000 }` 是无效参数
   cloudDatabase 只读 connectRequestTimeoutMs / requestTimeout。mssql 12.x 上请求级
   request.timeout 不生效,超时只能靠池配置级 requestTimeout,而共享池(query())的
   池级超时在 pool 创建时就定死 —— 所以「给足 4 分钟」从来没生效过,实际一路按
   60s(普通 query)/ 300s(querySlow)掐断。
   → cloudDatabase 两个查询入口加 warnLegacyTimeoutOption():再传 timeoutMs 就告警,
     不再静默当没看见。

2. 售后拦截子查询:名义 240s → 真 20s,且不重试
   两张售后表在 rpt 副本里是堆表,实测 4.5s / 8.5s。原来超时后 query() 还把它当
   可重试错误 resetPool + 重查一次,白等 60s(11-13 日志里约 2 分钟)。
   改成 querySlow + connectRequestTimeoutMs=20000 + maxAttempts=1:超了就按既有
   catch 降级「不剔除」,不为一个补充判据把整批核验拖进超时窗口。

3. 空窗口的表级 MAX(query_time) 探测改走 querySlow(180s,maxAttempts=1)
   全表 MAX 实测已跑不进 60s,用共享池等于永远探测不到 → sourceLastUpdate 恒空,
   「0 单是没发货还是没同步」又分不清了。探测失败只需退回「不知道」,不值得重试。

顺带修一个时间炸弹测试:用例「窗口 0 行但数据源是新的」硬编码 sourceMaxQueryTime
为 2026-11-02 09:58,而服务层算 ageMinutes 用的是真实时钟(registry.beijingNow)——
隔一天就变成「停更 24h」,该用例在 origin/main 上从 11-03 起一直是红的。
改成相对当前时间。

测试:warehouseLogisticsException 36/36 通过(新增 2 条「超时参数必须真生效」断言)。
2026-11-14 09:28:27 +08:00
9a7215a46c fix(wle): 正文写明物流快照是否覆盖核验时刻 / 是否过旧
11-11 09:10 那批:物流镜像表停在 11-10 11:53,算出 990 单**全部异常**,
钉钉正文却只有「已发货 990 单,异常 990 个包裹(100%)」。群里没法分辨
这是真异常还是数据没更新 —— 而这恰恰决定当天要不要去催快递。

PR #94 只修了「0 单」这一种(emptyWindow),有异常但快照降级的情形仍然是哑的。

- 新增 `buildFreshnessWarning`:`coversDeadline === false` 或 `stale === true`
  时,在数字行下面插一条 ⚠️ 告警,写明快照最新时刻、本轮核验时刻、未刷新时长,
  并明确「请以聚水潭实时物流为准,别按这个数去催快递」。
- 新增 `formatSnapshotMoment`:快照时刻**跨天必须带 MM-DD**。
  11-11 那批的 snapshotAt 是前一天的,只写「11:53」会被读成当天上午的新鲜数据
  (与 WST「历史单审核时间必须带 MM-DD」是同一个坑)。
- 只在「算出异常」时告警;0 单走原有 emptyWindow 分支,不叠加两条。
- 字段缺失(老缓存 / 接口未返回)静默跳过,不能把推送搞崩,也不能瞎报警。

测试:新增 5 条(未覆盖核验时刻含跨天日期 / 同日不写日期 / stale 带时长 /
正常批次无告警 / 字段缺失不崩),26/26 通过。
2026-11-11 11:14:31 +08:00
6c4f36f9fd fix(wle): 钉钉推送失败后自动重试,不再「一天只有一次机会」
11-11 09:10 那次推送撞上业务库连不上(状态里 `Failed to connect to
218.93.9.21:1433`)。老逻辑用 `chinaHourMinute(now) === config.sendTime`
严格相等判定,只给这一分钟一次机会:失败后当天彻底不推,群里一整天
没有任何消息,也没人知道任务其实跑过。

改成「推送时刻 + 重试窗口」模型:

- 新增纯函数 `resolveScheduledPushDecision`,每分钟 tick 只需问它一次;
  窗口 = sendTime ~ sendTime+30min,窗口内每 5 分钟重试一次,成功即停
  (`lastSentDate` 落库后后续 tick 走 already_sent_today)。
- 状态新增 `attemptDate` / `attemptCount` / `lastAttemptAt`:既做节流
  (避免每分钟重跑 240s 的全量核验),也做跨天归零。
- 窗口不跨日(sendTime+window 超过 23:59 截到当天最后一分钟),
  否则 pushDate 换天会把去重键带歪、同一天可能推两遍。
- 窗口关闭且当天始终未成功时打一条 error 日志,明确「今天不会再自己来了」。
- 窗口 / 间隔支持 `WLE_NOTIFY_RETRY_WINDOW_MINUTES`、
  `WLE_NOTIFY_RETRY_INTERVAL_MINUTES` 环境变量覆盖,现网调整不用发版。

测试:`test/warehouseLogisticsExceptionNotify.test.js` 新增 10 条边界用例
(到点首轮 / 未到点 / 已推过 / 间隔内节流 / 间隔到点 / 窗口边界含端点 /
窗口关闭 / 跨天归零 / 窗口不跨日 / 状态残缺不卡死 / sendTime 非法),
30/30 通过。
2026-11-11 11:12:26 +08:00
f8b99151b5 Merge pull request 'fix(mkh): 在途加工单换用聚水潭原生三表(po_id 关联),修「页面 9 单 vs 聚水潭 18 单」' (#94) from yanhui-mkh-workorder-1111 into main 2026-11-11 10:17:59 +08:00
c5a8b592a1 fix(mkh): 在途加工单换用聚水潭原生三表(po_id 关联),修「页面 9 单 vs 聚水潭 18 单」
## 问题
页面「在途加工单 / 已排产」只显示 9 个,且全是 2026-11-03 的僵尸单;
业务在聚水潭看到的是 18 个,且那 9 个早已加工入库完成。

## 根因
旧数据源是链接服务器快照表
`LS_JS_DMP(192.168.1.209).JSDataMiddlePlatform.dbo.bi_processing_work_orders`:
- 表内**无任何时间列**,实测按加工日期自 2026-11-03 10:49 起 **8 天 0 行**
  (1,370 行 / MAX(Id)=1370 不再增长,而此前每天都有 5~34 行);
- 且**数据陈旧不会报错** —— `workOrderDegraded` 只反映「查询失败」,
  停更期间恒为 false,页面完全无告警。
结果:9 行残留「已确认/未入库」把对应成品永久锁成「已排产」压住补货预警,
而 11-04 之后新开的加工单一条都没进库(在途量按 0 算,缺货会被误报)。

## 改动
数据源改为聚水潭原生加工单三表(业务库本实例,随主库小时级刷新),主键 `po_id` 关联:
- `rpt.jst_manufactureInfo`  单头:status / wms_co_id(加工仓) / receipt_wms_co_id(收货仓)
- `rpt.jst_manufactureItem`  成品明细:sku_id / qty / io_qty(已入库) / delivery_date
- `rpt.jst_manufactureRaw`   原料明细(本次不参与在途核算,配件占用仍走 BOM 单台用量)

口径保持业务确认的语义,只换算字段:
- 加工仓:中文名 `加工仓储方` → `wms_co_id = 15718196`(ID 比名称稳定)
- 作废:`'作废'` → `'Cancelled'`
- 完成:`'全部入库'` → `'Finished'`
- 剩余量:`数量 − 已入库数量` → `qty − io_qty`
- ETA:`预计加工完成时间` → `delivery_date`(实测 18 单全能解析)
- 查询从 `getPool()` 四段名改为 `cloudDatabase.query()`(表名已带 rpt. 前缀,不受 dbo→rpt 重写影响)

## 验证
- 真实库实跑(生产 13333 隧道)SQL 与服务层 `loadPendingWorkOrderIndex()`:
  命中 **18 个 SKU / 18 单 / 在途 175 件**,`degraded=false`,ETA 2026-11-24 ~ 11-25;
  热态耗时 **0.7~1.5s**(冷启动 5s,结果进 10 分钟缓存)。
- 状态一致性:`Finished` 1,149 单的 1,173 行明细**零剩余**;`Cancelled` 178 单 io_qty 全 0;
  `Confirmed` 18 单 io_qty 全 0 → 剩余量判据自身即可区分完成,状态只用来剔作废。
- `node --test test/mkhBomService.test.js` **56/56 通过**;全量 505 项 502 通过,
  3 项失败均为既有环境问题(secretStore Windows 权限、cloudDatabase 负缓存 TTL、
  WST 用例在并发下的时序抖动,单独跑均通过)。
- `check-syntax` 196 文件通过。

## 风险与回退
- 只换数据源、不动预警优先级与结余口径,接口字段名全部保持不变(`pendingWorkOrderQty/Count/Eta/No`),
  前端零改动。
- 回退:单文件还原 `mkhBomService.js` 即可,无数据迁移、无 DDL。
2026-11-11 10:05:43 +08:00
54ad6aad89 Merge pull request 'fix(wle): 0 单不再冒充「全部正常」——窗口空时查数据源是否停更' (#94) from yanhui-wle-emptydata-1102 into main 2026-11-02 13:32:49 +08:00
7 changed files with 539 additions and 78 deletions

View File

@ -76,6 +76,24 @@ function isTransientError(error) {
); );
} }
/**
* ⚠️ `options.timeoutMs` 是个「看着能用、其实没人读」的参数 —— 历史踩坑,留个告警别再犯。
*
* 根因:mssql 12.x 上请求级 `request.timeout` 不生效,超时只能靠**池配置级** requestTimeout,
* 而共享池(query())的池级超时在 pool 创建时就定死了,调用方改不了。想放宽只有两条路:
* · querySlow(sql, params, { connectRequestTimeoutMs }) —— 临时独立连接,可任意放宽;
* · query(sql, params, { requestTimeout }) —— 只对独立连接路径(queryWithFreshConnection)有意义。
* 2026-11-14 实况:WLE 服务层两处 `{ timeoutMs: 240000 }` 想着「给足 4 分钟」,
* 实际一路按 60s/300s 跑,11-13 那轮钉钉推送就因此超时没推出去。
*/
function warnLegacyTimeoutOption(options, caller) {
if (!options || options.timeoutMs === undefined) return;
console.warn(
`[CloudDB] ${caller} 收到无效参数 timeoutMs=${options.timeoutMs}(已被忽略,不会放宽超时);`
+ '需要更长超时请改用 querySlow + connectRequestTimeoutMs'
);
}
function isTruthy(value) { function isTruthy(value) {
return value === true || value === 1 || String(value || '').toLowerCase() === 'true' || String(value || '') === '1'; return value === true || value === 1 || String(value || '').toLowerCase() === 'true' || String(value || '') === '1';
} }
@ -1036,6 +1054,7 @@ const resetPool = async () => {
* @param {object} params - 命名参数对象 * @param {object} params - 命名参数对象
*/ */
const query = async (sqlText, params = {}, options = {}) => { const query = async (sqlText, params = {}, options = {}) => {
warnLegacyTimeoutOption(options, 'query()');
const maxAttempts = parsePositiveInt(options.maxAttempts, 2); const maxAttempts = parsePositiveInt(options.maxAttempts, 2);
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
@ -1072,6 +1091,7 @@ const query = async (sqlText, params = {}, options = {}) => {
}; };
const queryWithFreshConnection = async (sqlText, params = {}, options = {}) => { const queryWithFreshConnection = async (sqlText, params = {}, options = {}) => {
warnLegacyTimeoutOption(options, 'queryWithFreshConnection()');
const maxAttempts = parsePositiveInt(options.maxAttempts, 2); const maxAttempts = parsePositiveInt(options.maxAttempts, 2);
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {

View File

@ -6,6 +6,8 @@
* 业务口径(2026-10-22 定稿): * 业务口径(2026-10-22 定稿):
* ① 每天 09:10(核验 09:00 之后)把**当天核验批次**的异常情况发到指定钉钉群; * ① 每天 09:10(核验 09:00 之后)把**当天核验批次**的异常情况发到指定钉钉群;
* **0 条也推**(群里看到「本批 0 异常」= 任务没挂)。 * **0 条也推**(群里看到「本批 0 异常」= 任务没挂)。
* ⚠️ 失败必须重试(2026-11-11 加):09:10 起 30 分钟内每 5 分钟再试一次,成功即停;
* 窗口过了不再补推(上午的数据下午才发会误导业务)。见 `resolveScheduledPushDecision`。
* ② 不发 .xlsx 附件 —— 群机器人 webhook 发不了文件,业务也确认群里看文本就够。 * ② 不发 .xlsx 附件 —— 群机器人 webhook 发不了文件,业务也确认群里看文本就够。
* 内容 = 汇总(发货/异常/异常率/分类型/分仓)+ 前 N 条明细 + 页面链接。 * 内容 = 汇总(发货/异常/异常率/分类型/分仓)+ 前 N 条明细 + 页面链接。
* N 由页面配置(默认 30,上限 50);要全部明细就点链接去页面导出 Excel。 * N 由页面配置(默认 30,上限 50);要全部明细就点链接去页面导出 Excel。
@ -20,6 +22,9 @@
* 关键词一般是「异常」,缺了会被拒(errcode 310000)。 * 关键词一般是「异常」,缺了会被拒(errcode 310000)。
* ④ 一天只推一次:状态存 system_config,按「推送日(北京时间)」去重, * ④ 一天只推一次:状态存 system_config,按「推送日(北京时间)」去重,
* 服务重启不会重复轰炸;手动「立即推送」才强制重发。 * 服务重启不会重复轰炸;手动「立即推送」才强制重发。
* ⑤ 数据新鲜度必须进正文(2026-11-11 加):只要算出异常,就要说明物流快照
* 是否覆盖本轮核验时刻、是否过旧 —— 否则「990 单 100% 异常」到底是真异常
* 还是镜像表停在昨天,群里看不出来。见 `buildFreshnessWarning`。
* *
* 时区:生产容器是 UTC,核验批次和「到点没有」全部用 Asia/Shanghai 判断。 * 时区:生产容器是 UTC,核验批次和「到点没有」全部用 Asia/Shanghai 判断。
*/ */
@ -42,6 +47,32 @@ const DEFAULT_TICK_CRON = '* * * * *';
// 钉钉 text 上限 20000 字节;留 300 字节给「已精简」尾巴,避免临界失败 // 钉钉 text 上限 20000 字节;留 300 字节给「已精简」尾巴,避免临界失败
const SAFE_CONTENT_BYTES = MAX_CONTENT_BYTES - 300; const SAFE_CONTENT_BYTES = MAX_CONTENT_BYTES - 300;
// 🔥 2026-11-11 加:推送失败要重试,不能「一天只有一次机会」。
// 实况:11-11 09:10 那次撞上业务库连不上(状态里 `Failed to connect to 218.93.9.21:1433`),
// 老逻辑只在 `HH:mm === sendTime` 这一分钟内跑一次,失败后当天彻底不推 —— 群里一整天没消息。
// 现在改成:从推送时刻起 `RETRY_WINDOW_MINUTES` 分钟内,每隔 `RETRY_INTERVAL_MINUTES` 分钟再试,
// 成功即停(`lastSentDate` 落库后后续 tick 自动 skip),窗口过了就不再补(避免上午的数据下午才发)。
// 两个值都可用环境变量覆盖,现网想调不用改前端配置、也不用发版。
const DEFAULT_RETRY_WINDOW_MINUTES = 30;
const DEFAULT_RETRY_INTERVAL_MINUTES = 5;
function readPositiveMinutes(value, fallback, max) {
const num = Number(value);
if (!Number.isFinite(num) || num <= 0) return fallback;
return Math.min(Math.round(num), max);
}
const RETRY_WINDOW_MINUTES = readPositiveMinutes(
process.env.WLE_NOTIFY_RETRY_WINDOW_MINUTES,
DEFAULT_RETRY_WINDOW_MINUTES,
12 * 60
);
const RETRY_INTERVAL_MINUTES = readPositiveMinutes(
process.env.WLE_NOTIFY_RETRY_INTERVAL_MINUTES,
DEFAULT_RETRY_INTERVAL_MINUTES,
RETRY_WINDOW_MINUTES
);
let tickRunning = false; let tickRunning = false;
function pad2(value) { function pad2(value) {
@ -72,6 +103,66 @@ function chinaHourMinute(date = new Date()) {
}).format(base); }).format(base);
} }
/** 'HH:mm' → 当天第几分钟(09:10 → 550)。非法输入返回 null,调用方按「不跑」处理 */
function minuteOfDay(hhmm) {
const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(String(hhmm || '').trim());
if (!match) return null;
return Number(match[1]) * 60 + Number(match[2]);
}
/**
* 定时器每一分钟问一次「现在该不该推」。纯函数,便于把时间窗口/节流的边界钉死在单测里。
*
* 返回 `{ run, reason, pushDate, attempt }`:
* · `already_sent_today` 今天已推成功 → 不再动(重试自然也停)
* · `before_time` 还没到配置的推送时刻
* · `window_closed` 已过「推送时刻 + 重试窗口」,不再补推(避免 10 点失败、下午才发出去)
* · `wait_interval` 上一轮失败距现在不到重试间隔,等着
* · `first_round` 到点第一次跑
* · `retry` 上一轮失败后的第 N 次重试
*
* ⚠️ 窗口**不跨日**:`sendTime + window` 超过 23:59 就截到当天最后一分钟。
* 跨日会让 `pushDate` 换天,去重键(`lastSentDate`)跟着变,容易出现同一天推两遍。
*/
function resolveScheduledPushDecision(options = {}) {
const now = options.now instanceof Date ? options.now : new Date(options.now ?? Date.now());
const pushDate = chinaDateKey(now);
const state = options.state && typeof options.state === 'object' ? options.state : {};
const windowMinutes = readPositiveMinutes(options.retryWindowMinutes, RETRY_WINDOW_MINUTES, 12 * 60);
const intervalMinutes = readPositiveMinutes(options.retryIntervalMinutes, RETRY_INTERVAL_MINUTES, windowMinutes);
if (state.lastSentDate === pushDate) {
return { run: false, reason: 'already_sent_today', pushDate, attempt: 0 };
}
const nowMinute = minuteOfDay(chinaHourMinute(now));
const startMinute = minuteOfDay(options.sendTime);
if (nowMinute === null || startMinute === null) {
return { run: false, reason: 'bad_send_time', pushDate, attempt: 0 };
}
if (nowMinute < startMinute) {
return { run: false, reason: 'before_time', pushDate, attempt: 0 };
}
const endMinute = Math.min(startMinute + windowMinutes, 23 * 60 + 59);
if (nowMinute > endMinute) {
return { run: false, reason: 'window_closed', pushDate, attempt: 0 };
}
// 当天的尝试次数:跨天或没有记录都归零,避免沿用昨天的计数把节流算歪
const attempt = state.attemptDate === pushDate ? Number(state.attemptCount) || 0 : 0;
if (attempt > 0) {
const lastAttemptMs = Date.parse(String(state.lastAttemptAt || ''));
if (Number.isFinite(lastAttemptMs)) {
const gapMinutes = (now.getTime() - lastAttemptMs) / 60000;
if (gapMinutes < intervalMinutes) {
return { run: false, reason: 'wait_interval', pushDate, attempt };
}
}
}
return { run: true, reason: attempt > 0 ? 'retry' : 'first_round', pushDate, attempt: attempt + 1 };
}
/** /**
* 字段清洗:换行/连续空白压成单空格。 * 字段清洗:换行/连续空白压成单空格。
* ⚠️ 物流描述里常有 `\n`,直接拼进 text 消息会把一条明细劈成两行,看着像两条异常。 * ⚠️ 物流描述里常有 `\n`,直接拼进 text 消息会把一条明细劈成两行,看着像两条异常。
@ -208,6 +299,51 @@ function buildTypeLine(data = {}) {
.join(' · '); .join(' · ');
} }
/**
* 快照时刻的展示形式:`2026-11-11 09:05:00` → `09:05`;**跨天则带 `MM-DD`**。
* ⚠️ 只显示 HH:mm 会把「昨天 11:53」读成「今天 11:53」。11-11 那批的 `snapshotAt`
* 其实是前一天的(镜像表停在 11-10 11:53),群里看到「快照最新只到 11:53」会误以为
* 当天上午的数据很新鲜 —— 与 WST「历史单审核时间必须带 MM-DD」是同一个坑。
*/
function formatSnapshotMoment(value, referenceDate = '') {
const text = String(value || '').trim();
if (text.length < 16) return text;
const datePart = text.slice(0, 10);
const timePart = text.slice(11, 16);
const refDate = String(referenceDate || '').trim().slice(0, 10);
if (refDate && datePart === refDate) return timePart;
return `${datePart.slice(5)} ${timePart}`;
}
/**
* 快照新鲜度告警 —— **有异常数据时才用**(0 单的情形由 `buildNotifyText` 里的 emptyWindow 分支处理)。
*
* 🔥 2026-11-11 实况:物流镜像表停在 11-10 11:53,09:10 那批算出 990 单**全部异常**,
* 正文却只有一句「异常 990 个(100%)」。群里没法分辨这是真异常还是数据没更新,
* 而这恰恰决定当天要不要去催快递。所以「没覆盖核验时刻」「快照过旧」必须写进正文,
* 不能只留在页面 hint 里 —— 群里干活的人看不到页面。
*/
function buildFreshnessWarning(freshness = {}, batch = {}) {
const info = freshness && typeof freshness === 'object' ? freshness : {};
const snapshotAt = formatSnapshotMoment(info.snapshotAt, batch.verifyDate);
if (info.coversDeadline === false) {
const deadline = formatSnapshotMoment(batch.deadline, batch.verifyDate);
return `⚠️ 数据未覆盖核验时刻:物流快照最新只到 ${snapshotAt || '未知'}`
+ `${deadline ? `,本轮核验 ${deadline}` : ''} —— 之后的揽收/中转轨迹没进库,异常量会偏大。`
+ '请以聚水潭实时物流为准,别按这个数去催快递。';
}
if (info.stale === true) {
const ageMinutes = Number(info.ageMinutes);
const hours = Number.isFinite(ageMinutes) && ageMinutes > 0
? `(已 ${Math.round((ageMinutes / 60) * 10) / 10} 小时未刷新)`
: '';
return `⚠️ 物流快照偏旧:最新只到 ${snapshotAt || '未知'}${hours} —— 状态可能滞后,`
+ '异常量仅供参考,请以聚水潭实时物流为准。';
}
return '';
}
function buildPageLink(pageUrl, verifyDate) { function buildPageLink(pageUrl, verifyDate) {
const base = String(pageUrl || DEFAULT_PAGE_URL); const base = String(pageUrl || DEFAULT_PAGE_URL);
if (!verifyDate) return base; if (!verifyDate) return base;
@ -245,10 +381,15 @@ function buildNotifyText(data = {}, options = {}) {
const typeLine = buildTypeLine(data); const typeLine = buildTypeLine(data);
if (typeLine) head.push(`类型:${typeLine}`); if (typeLine) head.push(`类型:${typeLine}`);
// 快照新鲜度告警:只对「算出了异常」的批次有意义 —— 11-11 那批 990 单全部异常,
// 正文却完全看不出数据停在昨天,业务只能凭印象判断要不要催快递。
const freshness = data.freshness || {};
const freshnessWarning = totalPackages > 0 ? buildFreshnessWarning(freshness, batch) : '';
if (freshnessWarning) head.push(freshnessWarning);
// 🔥 2026-11-02 修:0 单有两种完全不同的含义,不能都写「全部正常」—— // 🔥 2026-11-02 修:0 单有两种完全不同的含义,不能都写「全部正常」——
// ① 数据源没同步(镜像表窗口 0 行)→ 0 单是假的,写「全部正常」等于给群里发假绿; // ① 数据源没同步(镜像表窗口 0 行)→ 0 单是假的,写「全部正常」等于给群里发假绿;
// ② 当天确实没发货 → 0 单是真的,那也不叫「正常」,叫「无发货可核」。 // ② 当天确实没发货 → 0 单是真的,那也不叫「正常」,叫「无发货可核」。
const freshness = data.freshness || {};
if (totalPackages === 0) { if (totalPackages === 0) {
if (freshness.emptyWindow && freshness.sourceStale) { if (freshness.emptyWindow && freshness.sourceStale) {
const hours = Number(freshness.sourceAgeMinutes) > 0 const hours = Number(freshness.sourceAgeMinutes) > 0
@ -479,8 +620,9 @@ async function runWarehouseLogisticsExceptionNotifyJob(source = 'scheduled', opt
} }
/** /**
* 调度:每分钟比对「北京时间 HH:mm == 配置的 sendTime」。 * 调度:每分钟问一次 `resolveScheduledPushDecision`。
* 之所以不用固定 cron 表达式:业务在页面上改时间后要立即生效,不能等后端重启。 * 之所以不用固定 cron 表达式:业务在页面上改时间后要立即生效,不能等后端重启。
* 之所以不是「HH:mm 严格相等」:那样只给一次机会,09:10 撞上业务库连不上就整天不推(11-11 实况)。
*/ */
function startWarehouseLogisticsExceptionNotifyScheduler() { function startWarehouseLogisticsExceptionNotifyScheduler() {
const disabled = String(process.env.DISABLE_WLE_NOTIFY || '').trim().toLowerCase() === 'true'; const disabled = String(process.env.DISABLE_WLE_NOTIFY || '').trim().toLowerCase() === 'true';
@ -489,6 +631,7 @@ function startWarehouseLogisticsExceptionNotifyScheduler() {
return; return;
} }
const expression = String(process.env.WLE_NOTIFY_TICK_CRON || DEFAULT_TICK_CRON).trim(); const expression = String(process.env.WLE_NOTIFY_TICK_CRON || DEFAULT_TICK_CRON).trim();
let windowClosedLoggedDate = '';
cron.schedule(expression, () => { cron.schedule(expression, () => {
if (tickRunning) return; if (tickRunning) return;
tickRunning = true; tickRunning = true;
@ -497,8 +640,32 @@ function startWarehouseLogisticsExceptionNotifyScheduler() {
const now = new Date(); const now = new Date();
const config = await getWarehouseLogisticsExceptionNotifyRuntimeConfig(); const config = await getWarehouseLogisticsExceptionNotifyRuntimeConfig();
if (!config.enabled) return; if (!config.enabled) return;
if (chinaHourMinute(now) !== config.sendTime) return; const state = await loadWarehouseLogisticsExceptionNotifyState();
await runWarehouseLogisticsExceptionNotifyJob('daily_schedule', { now }); const decision = resolveScheduledPushDecision({ now, sendTime: config.sendTime, state });
if (!decision.run) {
// 窗口刚过、当天又一直没推成功 → 打一条,明确「今天不会自己来了」,别让人一直等
if (decision.reason === 'window_closed' && windowClosedLoggedDate !== decision.pushDate) {
windowClosedLoggedDate = decision.pushDate;
console.error(
`[WleNotify] 今日推送窗口已关闭(${config.sendTime} 起 ${RETRY_WINDOW_MINUTES} 分钟内重试,`
+ '始终未成功),今天不再自动重试,请人工处理'
);
}
return;
}
// 先落「本轮尝试」:失败后下一分钟的 tick 才能按间隔节流。
// 成功时 push 内部会覆盖 lastSentDate(去重键),此后本函数直接走 already_sent_today。
await saveWarehouseLogisticsExceptionNotifyState({
...state,
attemptDate: decision.pushDate,
attemptCount: decision.attempt,
lastAttemptAt: now.toISOString(),
});
await runWarehouseLogisticsExceptionNotifyJob(
decision.reason === 'retry' ? 'daily_retry' : 'daily_schedule',
{ now }
);
} catch (error) { } catch (error) {
console.error('[WleNotify] 定时检查失败:', error.message || error); console.error('[WleNotify] 定时检查失败:', error.message || error);
} finally { } finally {
@ -507,23 +674,31 @@ function startWarehouseLogisticsExceptionNotifyScheduler() {
})(); })();
}, { timezone: TIMEZONE }); }, { timezone: TIMEZONE });
console.log(`[Scheduler] 物流转运异常钉钉推送已注册: 每分钟检查,到点(默认 09:10)推送 (${TIMEZONE})`); console.log(
`[Scheduler] 物流转运异常钉钉推送已注册: 每分钟检查,到点(默认 09:10)推送,`
+ `失败后每 ${RETRY_INTERVAL_MINUTES} 分钟重试、最多 ${RETRY_WINDOW_MINUTES} 分钟内 (${TIMEZONE})`
);
} }
module.exports = { module.exports = {
DEFAULT_RETRY_INTERVAL_MINUTES,
DEFAULT_RETRY_WINDOW_MINUTES,
DEFAULT_TICK_CRON, DEFAULT_TICK_CRON,
SAFE_CONTENT_BYTES, SAFE_CONTENT_BYTES,
TIMEZONE, TIMEZONE,
buildCenterLines, buildCenterLines,
buildDetailLine, buildDetailLine,
buildFreshnessWarning,
buildNotifyText, buildNotifyText,
buildTypeLine, buildTypeLine,
chinaDateKey, chinaDateKey,
chinaHourMinute, chinaHourMinute,
groupRowsByWarehouse, groupRowsByWarehouse,
minuteOfDay,
pickDetailRows, pickDetailRows,
cleanCell, cleanCell,
pushWarehouseLogisticsExceptionNotify, pushWarehouseLogisticsExceptionNotify,
resolveScheduledPushDecision,
runWarehouseLogisticsExceptionNotifyJob, runWarehouseLogisticsExceptionNotifyJob,
startWarehouseLogisticsExceptionNotifyScheduler, startWarehouseLogisticsExceptionNotifyScheduler,
}; };

View File

@ -240,24 +240,27 @@
// ⚠️ 配件库存**不适用本口径**(配件仍只算 15718196)——新仓一个配件都没有, // ⚠️ 配件库存**不适用本口径**(配件仍只算 15718196)——新仓一个配件都没有,
// 横林三仓/沭阳仓虽有 MKH 配件但归属别的项目,并入会让「配件不足」漏报。 // 横林三仓/沭阳仓虽有 MKH 配件但归属别的项目,并入会让「配件不足」漏报。
// //
// ── ⑧ 在途加工单(2026-09-17 业务确认口径)──────────────────────── // ── ⑧ 在途加工单(2026-09-17 业务确认口径;2026-11-11 换数据源)──────────
// 规则:**只要该 MKH 商品存在未完成的加工单,就不再列入补货预警** // 规则:**只要该 MKH 商品存在未完成的加工单,就不再列入补货预警**
// (工厂已经在做了,不重复提示补货),改标为「已排产」。 // (工厂已经在做了,不重复提示补货),改标为「已排产」。
// · 数据源:业务库同实例的链接服务器 // · 数据源(2026-11-11 起):聚水潭原生加工单三表,主键 `po_id` 关联
// LS_JS_DMP → JSDataMiddlePlatform.dbo.bi_processing_work_orders // rpt.jst_manufactureInfo 加工单单头:status / wms_co_id(加工仓) / receipt_wms_co_id(收货仓) / po_date
// (聚水潭「组装加工」加工单,一张扁平的 加工单 × 商品 明细表) // rpt.jst_manufactureItem 加工单**成品**明细:sku_id / qty(计划数) / io_qty(已入库) / delivery_date
// · 过滤:加工仓储方 = '简尚-崔桥工厂半成品包装项目仓' // rpt.jst_manufactureRaw 加工单**原料**明细:qty(暂未参与在途核算,配件占用走 BOM 单台用量)
// AND 状态 <> '作废' ← 作废单据一律不核算 // · 过滤:i.wms_co_id = 15718196(简尚-崔桥工厂半成品包装项目仓,产出入品牌仓 15870495)
// AND max(数量 − 已入库数量, 0) > 0 ← 只认真实剩余量 // AND i.status <> 'Cancelled' ← 作废单不核算(实测 178 单 7,515 件,不过滤会虚增几十倍)
// · 在途加工量 = Σ max(数量 − 已入库数量, 0),按 商品编码 归集。 // AND it.qty > ISNULL(it.io_qty,0) ← 只认真实剩余量
// 不再依赖「收货状态」文本:上游状态字段延迟时,已入库数量已追平的单据必须立即退出在途。 // · 在途加工量 = Σ(qty − io_qty),按成品编码 sku_id 归集;ETA 取 delivery_date 最小值。
// ⚠️ 为什么走 getPool 而不是 cloudDatabase.query: // 状态值域实测(2026-11-11):Finished 1,149 单 / Cancelled 178 / **Confirmed 18**;
// query() 会经 rewriteReportReplicaSql() 把 `dbo.xxx` 重写成 `rpt.xxx`, // Finished 的 1,173 行明细**零剩余**(io_qty 已追平),Confirmed 的 18 行 io_qty 全 0。
// 跨库四段名 `LS_JS_DMP.JSDataMiddlePlatform.dbo.t` 会被改坏成 // → 无需依赖状态文本判「完成」,剩余量判据自身就够;状态只用来剔作废。
// `LS_JS_DMP.JSDataMiddlePlatform.rpt.t`。getPool() 不经过该重写。 // ⚠️ **换源原因**:旧源是链接服务器 `LS_JS_DMP`(192.168.1.209) 的快照表
// 实测(2026-09-16):全表 679 行,其中 完成 498(全部入库)/ 作废 176 / // `JSDataMiddlePlatform.dbo.bi_processing_work_orders`,自 2026-11-03 10:49 起**停更 8 天**
// 已确认 3 / 待审核 2;属半成品包装仓且未完成且非作废的只有 5 单 40 件。 // (1,370 行 / MAX(Id)=1370 不再增长,而此前每天都有 5~34 行),且**不会报错** ——
// ⚠️ 作废单在半成品包装仓有 79 单 740 件,若不过滤会虚增约 18 倍在途量。 // `workOrderDegraded` 只反映「查询失败」,数据陈旧永远是 false,
// 于是页面长期显示 9 个 11-03 的僵尸单(业务在聚水潭看到的是 18 个新单)。
// 换成本实例内的原生三表后随主库小时级刷新,不再依赖那台内网机器的同步任务。
// 实测(2026-11-11):18 单 / 18 个成品 / 在途 175 件,ETA 全可解析(11-24 ~ 11-25)。
// //
// ── ⑨ 导出(2026-09-17)────────────────────────────────────────── // ── ⑨ 导出(2026-09-17)──────────────────────────────────────────
// 导出与列表**共用同一套筛选/排序口径**(filterRows + sortRows),区别只有两点: // 导出与列表**共用同一套筛选/排序口径**(filterRows + sortRows),区别只有两点:
@ -465,15 +468,25 @@ const WARNING_LEVEL = Object.freeze({
}); });
// ── 在途加工单参数(见文件头 ⑧)────────────────────────────────── // ── 在途加工单参数(见文件头 ⑧)──────────────────────────────────
// 加工仓储方:加工单的加工地,即半成品包装项目仓(产出入品牌仓) // 加工仓储方:加工单的加工地,即半成品包装项目仓(产出入品牌仓)。仅用于文案展示。
const WORK_ORDER_WAREHOUSE = '简尚-崔桥工厂半成品包装项目仓'; const WORK_ORDER_WAREHOUSE = '简尚-崔桥工厂半成品包装项目仓';
// 作废状态:作废单据不参与在途量核算 // 加工仓 wms_co_id(半成品包装项目仓):SQL 侧按它过滤。
const WORK_ORDER_VOID_STATUS = '作废'; // ⚠️ 用 ID 而不是中文名 —— 名称可能被上游改写,ID 稳定;实测该仓加工单收货仓恒为品牌仓 15870495。
// 收货状态:该值表示已全部入库,等价于「已完成」 const WORK_ORDER_WMS_CO_ID = 15718196;
const WORK_ORDER_RECEIVED_STATUS = '全部入库'; // 作废状态:作废单据不参与在途量核算(聚水潭加工单 status 值域 Confirmed / Finished / Cancelled)
// 加工单表位于同一实例的链接服务器上,四段名必须走 getPool 查询(原因见文件头 ⑧) const WORK_ORDER_VOID_STATUS = 'Cancelled';
const WORK_ORDER_TABLE = 'LS_JS_DMP.JSDataMiddlePlatform.dbo.bi_processing_work_orders'; // 完成状态:已全部入库
// 链接服务器不可用时的降级缓存时长:短一点,避免长时间带着错误在途量 const WORK_ORDER_RECEIVED_STATUS = 'Finished';
// 聚水潭原生加工单三表(rpt schema 视图,主键 po_id):
// Info = 单头(status / wms_co_id / po_date)
// Item = 成品明细(sku_id / qty / io_qty 已入库 / delivery_date 预计到货)
// Raw = 原料明细(暂未参与在途核算,配件占用走 BOM 单台用量)
// ⚠️ 2026-11-11 换源:旧的链接服务器 LS_JS_DMP 快照表自 11-03 起停更 8 天且**不会报错**
// (`workOrderDegraded` 只反映查询失败),导致页面 9 个僵尸单 + 新单全丢。
// 这三张表在业务库本实例内,可走 cloudDatabase.query()(表名已带 rpt.,不会被重写坏)。
const WORK_ORDER_INFO_TABLE = 'rpt.jst_manufactureInfo';
const WORK_ORDER_ITEM_TABLE = 'rpt.jst_manufactureItem';
// 加工单不可用时的降级缓存时长:短一点,避免长时间带着错误在途量
const WORK_ORDER_DEGRADED_TTL_MS = 60 * 1000; const WORK_ORDER_DEGRADED_TTL_MS = 60 * 1000;
// ── 订单参数(见文件头 ⑩ 待发货 / ⑦-a 近15天已发货)────────────── // ── 订单参数(见文件头 ⑩ 待发货 / ⑦-a 近15天已发货)──────────────
@ -1392,8 +1405,10 @@ async function loadMkhProductIndex() {
/** /**
* 未完成加工单(在途量)索引 —— 进程内缓存 { bySku: Map<归一化编码, 在途指标>, degraded }。 * 未完成加工单(在途量)索引 —— 进程内缓存 { bySku: Map<归一化编码, 在途指标>, degraded }。
* 只保留「半成品包装项目仓加工、未完成、非作废」的加工单,口径见文件头 ⑧。 * 只保留「半成品包装项目仓加工、未完成、非作废」的加工单,口径见文件头 ⑧。
* ⚠️ 该数据源是链接服务器,取不到时**降级为空索引**(补货预警照常跑), * 数据源:聚水潭原生加工单三表 —— jst_manufactureInfo(单头)+ jst_manufactureItem(成品明细),
* 并缩短缓存避免长时间带着错误在途量。degraded=true 会被透出到接口。 * PO 关联键 po_id;剩余量 = qty − io_qty(已入库数量)。
* ⚠️ 取不到时**降级为空索引**(补货预警照常跑),并缩短缓存避免长时间带着错误在途量。
* degraded=true 会被透出到接口。
*/ */
async function loadPendingWorkOrderIndex() { async function loadPendingWorkOrderIndex() {
const now = Date.now(); const now = Date.now();
@ -1403,43 +1418,26 @@ async function loadPendingWorkOrderIndex() {
if (workOrderIndexCache?.pending) return workOrderIndexCache.pending; if (workOrderIndexCache?.pending) return workOrderIndexCache.pending;
const pending = (async () => { const pending = (async () => {
// ⚠️ 必须走 getPool:cloudDatabase.query() 会把 `dbo.xxx` 重写成 `rpt.xxx`, // 表名已带 rpt. 前缀,`query()` 的 dbo→rpt 重写不会碰它,无需 getPool。
// 跨库四段名会被改坏(见文件头 ⑧)。 // Finished 单的 io_qty 已追平(实测 1,173 行零剩余),靠 `qty > io_qty` 自然退出,不依赖状态文本。
const pool = await cloudDatabase.getPool(); const rows = await cloudDatabase.query(
const request = pool.request(); `SELECT it.sku_id AS skuId,
request.input('workOrderWarehouse', WORK_ORDER_WAREHOUSE); SUM(it.qty - ISNULL(it.io_qty, 0)) AS pendingQty,
request.input('voidStatus', WORK_ORDER_VOID_STATUS); COUNT(DISTINCT i.po_id) AS orderCount,
const result = await request.query(` MIN(TRY_CONVERT(DATETIME, it.delivery_date, 111)) AS eta,
SELECT [商品编码] AS skuId, MIN(CAST(i.po_id AS NVARCHAR(40))) AS firstOrderNo
SUM(CASE FROM ${WORK_ORDER_ITEM_TABLE} it WITH (NOLOCK)
WHEN CAST([数量] AS DECIMAL(18, 4)) > CAST([已入库数量] AS DECIMAL(18, 4)) JOIN ${WORK_ORDER_INFO_TABLE} i WITH (NOLOCK) ON i.po_id = it.po_id
THEN CAST([数量] AS DECIMAL(18, 4)) - CAST([已入库数量] AS DECIMAL(18, 4)) WHERE i.wms_co_id = @workOrderWmsCoId
ELSE 0 AND i.status <> @voidStatus
END) AS pendingQty, AND it.qty > ISNULL(it.io_qty, 0)
COUNT(DISTINCT CASE GROUP BY it.sku_id`,
WHEN CAST([数量] AS DECIMAL(18, 4)) > CAST([已入库数量] AS DECIMAL(18, 4)) { workOrderWmsCoId: WORK_ORDER_WMS_CO_ID, voidStatus: WORK_ORDER_VOID_STATUS },
THEN [加工单号] { requestTimeout: 180000 }
END) AS orderCount, );
MIN(CASE
WHEN CAST([数量] AS DECIMAL(18, 4)) > CAST([已入库数量] AS DECIMAL(18, 4))
THEN TRY_CONVERT(DATETIME, [预计加工完成时间], 111)
END) AS eta,
MIN(CASE
WHEN CAST([数量] AS DECIMAL(18, 4)) > CAST([已入库数量] AS DECIMAL(18, 4))
THEN CAST([加工单号] AS NVARCHAR(40))
END) AS firstOrderNo
FROM ${WORK_ORDER_TABLE} WITH (NOLOCK)
WHERE [加工仓储方] = @workOrderWarehouse
AND [状态] <> @voidStatus
GROUP BY [商品编码]
HAVING SUM(CASE
WHEN CAST([数量] AS DECIMAL(18, 4)) > CAST([已入库数量] AS DECIMAL(18, 4))
THEN CAST([数量] AS DECIMAL(18, 4)) - CAST([已入库数量] AS DECIMAL(18, 4))
ELSE 0
END) > 0`);
const bySku = new Map(); const bySku = new Map();
(result.recordset || []).forEach((row) => { (rows || []).forEach((row) => {
const key = normalizeCode(row.skuId); const key = normalizeCode(row.skuId);
if (!key) return; if (!key) return;
const pendingQty = Math.max(0, toNumber(row.pendingQty) ?? 0); const pendingQty = Math.max(0, toNumber(row.pendingQty) ?? 0);
@ -2349,7 +2347,7 @@ async function getMkhBomList(query = {}) {
operationalRefreshedAt: operationalRefreshedAt operationalRefreshedAt: operationalRefreshedAt
? new Date(operationalRefreshedAt).toISOString() ? new Date(operationalRefreshedAt).toISOString()
: null, : null,
// 加工单数据源(链接服务器)不可用时为 true,此时在途量按 0 处理 // 加工单数据源不可用(查询失败)时为 true,此时在途量按 0 处理
workOrderDegraded: replenishIndex.workOrderDegraded === true, workOrderDegraded: replenishIndex.workOrderDegraded === true,
workOrderWarehouse: WORK_ORDER_WAREHOUSE, workOrderWarehouse: WORK_ORDER_WAREHOUSE,
// 待发货订单数据源不可用时为 true,此时待发货量按 0 处理(退化为旧口径) // 待发货订单数据源不可用时为 true,此时待发货量按 0 处理(退化为旧口径)
@ -2733,8 +2731,11 @@ module.exports = {
SCOPES, SCOPES,
WARNING_LEVEL, WARNING_LEVEL,
WORK_ORDER_WAREHOUSE, WORK_ORDER_WAREHOUSE,
WORK_ORDER_WMS_CO_ID,
WORK_ORDER_VOID_STATUS, WORK_ORDER_VOID_STATUS,
WORK_ORDER_RECEIVED_STATUS, WORK_ORDER_RECEIVED_STATUS,
WORK_ORDER_INFO_TABLE,
WORK_ORDER_ITEM_TABLE,
EXPORT_MODES, EXPORT_MODES,
buildProductExportRows, buildProductExportRows,
buildComponentExportRows, buildComponentExportRows,

View File

@ -152,6 +152,14 @@ async function loadShippedPackages(batch) {
return rows || []; return rows || [];
} }
// 🔥 2026-11-14 修:原来调这里写的是 `{ timeoutMs: 240000 }` —— **这个参数没人读**。
// mssql 12.x 上请求级 request.timeout 不生效,超时只能靠池配置级 requestTimeout,
// 而共享池(query())的池级超时在 pool 创建时就定死了,改不了。结果是「想给 4 分钟」
// 实际一路按默认 60s 掐断(11-14 实测全表 MAX 已经跑不进 60s → 探测永远返回空)。
// 真正生效的写法只有 querySlow(临时独立连接)+ connectRequestTimeoutMs。
const SOURCE_LAST_UPDATE_TIMEOUT_MS = Number(process.env.CANGKU_WLE_SOURCE_LAST_UPDATE_TIMEOUT_MS)
|| 180000;
/** /**
* 整张镜像表最后被灌库的时刻(表级新鲜度)。 * 整张镜像表最后被灌库的时刻(表级新鲜度)。
* *
@ -163,16 +171,18 @@ async function loadShippedPackages(batch) {
* *
* 成本:全表 `MAX(query_time)` 在一个 402 万行的视图上实测 **13.5s**(谓词下推差), * 成本:全表 `MAX(query_time)` 在一个 402 万行的视图上实测 **13.5s**(谓词下推差),
* 所以**只在窗口 0 行时才调**(正常批次一行都不用付这笔钱),结果随主结果进 5 分钟缓存。 * 所以**只在窗口 0 行时才调**(正常批次一行都不用付这笔钱),结果随主结果进 5 分钟缓存。
* ⚠️ 11-14 实测已退化到 60s 以上,所以超时上限 180s + maxAttempts=1
* (超时就退回「不知道」,重试只会把等待翻倍 —— 原来 query() 默认 2 次 × 60s 白等)。
* *
* @returns {Promise<string>} 'YYYY-MM-DD HH:mm:ss',取不到返回空串 * @returns {Promise<string>} 'YYYY-MM-DD HH:mm:ss',取不到返回空串
*/ */
async function loadSourceLastUpdate() { async function loadSourceLastUpdate() {
try { try {
const rows = await cloudDatabase.query( const rows = await cloudDatabase.querySlow(
`SELECT MAX(e.query_time) AS max_q `SELECT MAX(e.query_time) AS max_q
FROM dbo.jst_order_express_details e WITH (NOLOCK)`, FROM dbo.jst_order_express_details e WITH (NOLOCK)`,
{}, {},
{ timeoutMs: 240000 } { connectRequestTimeoutMs: SOURCE_LAST_UPDATE_TIMEOUT_MS, maxAttempts: 1 }
); );
return formatDateTime(rows?.[0]?.max_q); return formatDateTime(rows?.[0]?.max_q);
} catch (err) { } catch (err) {
@ -188,8 +198,15 @@ async function loadSourceLastUpdate() {
// · 只查「本来就会报异常」的 oId(正常单不查,量级从 9800 降到几十); // · 只查「本来就会报异常」的 oId(正常单不查,量级从 9800 降到几十);
// · 两套店铺表**并发**查,总耗时取较慢的那条(~8.5s),而不是相加的 13s; // · 两套店铺表**并发**查,总耗时取较慢的那条(~8.5s),而不是相加的 13s;
// · 结果进 5 分钟结果缓存,页面自动刷新时基本命中缓存。 // · 结果进 5 分钟结果缓存,页面自动刷新时基本命中缓存。
//
// 🔥 2026-11-14 修:超时从「名义 240s」改成「真 20s,且不重试」。
// 原来写 `{ timeoutMs: 240000 }`(无效参数),实际按共享池 60s 掐;
// 超时后 query() 还把它当可重试错误 —— resetPool + 再查一次,**再多等 60s**。
// 11-13 09:10 那轮推送就是这么被拖掉 2 分钟的(日志:售后拦截 60s 超时 → 重连重试)。
// 售后表跟不上时业务影响只是「少剔几单」,不值得为它把整批核验拖进超时窗口:
// 2 倍实测余量(8.5s → 20s)够用,超了就降级不剔(catch 里已有兜底)。
const INTERCEPT_QUERY_BATCH = 500; const INTERCEPT_QUERY_BATCH = 500;
const INTERCEPT_QUERY_TIMEOUT_MS = 240000; const INTERCEPT_QUERY_TIMEOUT_MS = 20000;
/** /**
* 找出「现场拦截、货已被售后仓签收」的订单(业务 2026-10-23 口径)。 * 找出「现场拦截、货已被售后仓签收」的订单(业务 2026-10-23 口径)。
@ -219,7 +236,7 @@ async function loadInterceptedOrders(rows) {
const oIds = ids.slice(i, i + INTERCEPT_QUERY_BATCH).join(','); const oIds = ids.slice(i, i + INTERCEPT_QUERY_BATCH).join(',');
for (const source of registry.INTERCEPT_AFTERSALE_SOURCES) { for (const source of registry.INTERCEPT_AFTERSALE_SOURCES) {
tasks.push((async () => { tasks.push((async () => {
const hits = await cloudDatabase.query( const hits = await cloudDatabase.querySlow(
`SELECT h.o_id `SELECT h.o_id
FROM ${source.header} h WITH (NOLOCK) FROM ${source.header} h WITH (NOLOCK)
JOIN ${source.item} it WITH (NOLOCK) ON it.as_id = ${source.headerAsId} JOIN ${source.item} it WITH (NOLOCK) ON it.as_id = ${source.headerAsId}
@ -228,7 +245,8 @@ async function loadInterceptedOrders(rows) {
GROUP BY h.o_id GROUP BY h.o_id
HAVING SUM(ISNULL(it.r_qty, 0)) > 0`, HAVING SUM(ISNULL(it.r_qty, 0)) > 0`,
{}, {},
{ timeoutMs: INTERCEPT_QUERY_TIMEOUT_MS } // maxAttempts: 1 —— 超时就在 catch 里降级「不剔除」,别让重连重试再白等一轮
{ connectRequestTimeoutMs: INTERCEPT_QUERY_TIMEOUT_MS, maxAttempts: 1 }
); );
return hits || []; return hits || [];
})().catch((err) => { })().catch((err) => {

View File

@ -395,8 +395,12 @@ test('replenish: products without sales stay "no sale" even with a pending work
test('pending work order filters keep the business-confirmed source and exclusions', () => { test('pending work order filters keep the business-confirmed source and exclusions', () => {
assert.equal(_private.WORK_ORDER_WAREHOUSE, '简尚-崔桥工厂半成品包装项目仓'); assert.equal(_private.WORK_ORDER_WAREHOUSE, '简尚-崔桥工厂半成品包装项目仓');
assert.equal(_private.WORK_ORDER_VOID_STATUS, '作废'); // 2026-11-11 换源:聚水潭原生加工单三表(po_id 关联),状态值域为英文
assert.equal(_private.WORK_ORDER_RECEIVED_STATUS, '全部入库'); assert.equal(_private.WORK_ORDER_WMS_CO_ID, 15718196);
assert.equal(_private.WORK_ORDER_VOID_STATUS, 'Cancelled');
assert.equal(_private.WORK_ORDER_RECEIVED_STATUS, 'Finished');
assert.equal(_private.WORK_ORDER_INFO_TABLE, 'rpt.jst_manufactureInfo');
assert.equal(_private.WORK_ORDER_ITEM_TABLE, 'rpt.jst_manufactureItem');
assert.equal(_private.WARNING_LEVEL.SCHEDULED, '已排产'); assert.equal(_private.WARNING_LEVEL.SCHEDULED, '已排产');
}); });

View File

@ -145,11 +145,13 @@ test('状态为空时按运单号区分:有号=未揽收,无号=无物流单
const dbPath = require.resolve('../src/config/cloudDatabase'); const dbPath = require.resolve('../src/config/cloudDatabase');
function stubDb(rows, options = {}) { function stubDb(rows, options = {}) {
const calls = { times: 0, sql: [], params: [] }; const calls = { times: 0, sql: [], params: [], options: [], api: [] };
const handler = async (sql, params) => { const makeHandler = (api) => async (sql, params, opts) => {
calls.times += 1; calls.times += 1;
calls.sql.push(String(sql)); calls.sql.push(String(sql));
calls.params.push(params || {}); calls.params.push(params || {});
calls.options.push(opts || {});
calls.api.push(api);
// 售后拦截判定会额外查两张售后表 —— 按表名分流,别把物流行当成售后行 // 售后拦截判定会额外查两张售后表 —— 按表名分流,别把物流行当成售后行
if (/jst_returnAndRefundInfo|jst_qmcust_refundlist/u.test(String(sql))) { if (/jst_returnAndRefundInfo|jst_qmcust_refundlist/u.test(String(sql))) {
return options.interceptRows || []; return options.interceptRows || [];
@ -164,7 +166,7 @@ function stubDb(rows, options = {}) {
id: dbPath, id: dbPath,
filename: dbPath, filename: dbPath,
loaded: true, loaded: true,
exports: { query: handler, querySlow: handler }, exports: { query: makeHandler('query'), querySlow: makeHandler('querySlow') },
}; };
return calls; return calls;
} }
@ -698,13 +700,21 @@ test('窗口 0 行 + 数据源停更 → emptyWindow/sourceStale,hint 明说
test('窗口 0 行但数据源是新的 → 仍然提示「0 条记录」,不能静默全绿', async () => { test('窗口 0 行但数据源是新的 → 仍然提示「0 条记录」,不能静默全绿', async () => {
const nov2 = new Date(2026, 10, 2, 10, 0, 0); const nov2 = new Date(2026, 10, 2, 10, 0, 0);
// ⚠️ sourceLastUpdate 必须是「相对真实现在」的时间,不能像原来那样硬编码 2026-11-02 09:58。
// 服务层算 ageMinutes 用的是 registry.beijingNow()(真实时钟),不是测试传进来的 now ——
// 硬编码的日期过一天就变成「停更 24h」,这个用例第二天起就必挂(2026-11-14 实测挂在 main 上)。
const freshText = new Intl.DateTimeFormat('sv-SE', {
timeZone: 'Asia/Shanghai',
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false,
}).format(new Date(Date.now() - 3 * 60 * 1000));
await withStub(async (svc) => { await withStub(async (svc) => {
const data = await svc.getLogisticsExceptions({ date: '2026-11-02', now: nov2, limit: 100 }); const data = await svc.getLogisticsExceptions({ date: '2026-11-02', now: nov2, limit: 100 });
assert.equal(data.freshness.emptyWindow, true); assert.equal(data.freshness.emptyWindow, true);
assert.equal(data.freshness.sourceStale, false, '表是新的,不该报停更'); assert.equal(data.freshness.sourceStale, false, '表是新的,不该报停更');
assert.match(data.freshness.hint, /0 条发货记录/, '真 0 单也要说清是「库里没有记录」'); assert.match(data.freshness.hint, /0 条发货记录/, '真 0 单也要说清是「库里没有记录」');
assert.match(data.freshness.hint, /数据源本身正常/); assert.match(data.freshness.hint, /数据源本身正常/);
}, [], { sourceMaxQueryTime: '2026-11-02 09:58:00' }); }, [], { sourceMaxQueryTime: freshText });
}); });
test('窗口有行时不做全表探测(省掉 13.5s 的表级 MAX)', async () => { test('窗口有行时不做全表探测(省掉 13.5s 的表级 MAX)', async () => {
@ -715,3 +725,37 @@ test('窗口有行时不做全表探测(省掉 13.5s 的表级 MAX)', async
assert.equal(calls.sql.filter((s) => /MAX\(\s*e\.query_time\s*\)/iu.test(s)).length, 0); assert.equal(calls.sql.filter((s) => /MAX\(\s*e\.query_time\s*\)/iu.test(s)).length, 0);
}); });
}); });
// ── ⑨ 超时参数必须「真生效」(2026-11-14)──────────────────────────────────
// 起因:11-13 09:10 那轮钉钉推送 300s 超时没推出去。查代码发现两处写了
// `{ timeoutMs: 240000 }` 想「给足 4 分钟」,而 cloudDatabase **根本不读 timeoutMs**
// (mssql 12.x 请求级 request.timeout 不生效,只能靠池配置级 requestTimeout,
// 共享池的池级超时创建时就定死了)—— 实际一路按 60s 掐断,
// 超时后 query() 还当可重试错误重连再查一次,日志里白等了约 2 分钟。
test('售后拦截查询走 querySlow + 20s 短超时 + 不重试', async () => {
await withStub(async (svc, calls) => {
await svc.getLogisticsExceptions({ date: '2026-10-21', now: at(21, 10, 0), limit: 100 });
const idx = calls.sql.findIndex((s) => /jst_returnAndRefundInfo|jst_qmcust_refundlist/u.test(s));
assert.ok(idx >= 0, '这批有异常单,应该去查售后表');
assert.equal(calls.api[idx], 'querySlow', '必须走 querySlow:query() 的池级超时调用方改不了');
assert.equal(calls.options[idx].connectRequestTimeoutMs, 20000, '2 倍实测余量(8.5s → 20s)就够');
assert.equal(calls.options[idx].maxAttempts, 1, '超时就降级「不剔除」,别重连重试白等一轮');
assert.equal(calls.options[idx].timeoutMs, undefined, 'timeoutMs 是无效参数,不许再写');
}, rows, { interceptRows: [{ o_id: 1 }] });
});
test('空窗口的表级 MAX 探测也走 querySlow(共享池 60s 跑不动全表)', async () => {
const nov2 = new Date(2026, 10, 2, 10, 0, 0);
await withStub(async (svc, calls) => {
await svc.getLogisticsExceptions({ date: '2026-11-02', now: nov2, limit: 100 });
const idx = calls.sql.findIndex((s) => /MAX\(\s*e\.query_time\s*\)/iu.test(s));
assert.ok(idx >= 0, '空窗口要探测表级最后灌库时刻');
assert.equal(calls.api[idx], 'querySlow');
assert.ok(
Number(calls.options[idx].connectRequestTimeoutMs) >= 120000,
`全表 MAX 实测已超 60s,必须放宽,实际 ${calls.options[idx].connectRequestTimeoutMs}`
);
assert.equal(calls.options[idx].maxAttempts, 1, '探测失败退回「不知道」即可,不值得重试');
assert.equal(calls.options[idx].timeoutMs, undefined);
}, [], { sourceMaxQueryTime: '2026-11-01 07:55:04' });
});

View File

@ -541,4 +541,203 @@ test('数据源正常但当天 0 条记录 → 说明是「库里没有记录」
assert.match(built.text, /请到聚水潭核对/); assert.match(built.text, /请到聚水潭核对/);
assert.ok(!built.text.includes('物流数据未同步'), '表是新的,不能谎报停更'); assert.ok(!built.text.includes('物流数据未同步'), '表是新的,不能谎报停更');
assert.ok(!built.text.includes('全部正常'), '0 条不能糊成「全部正常」'); assert.ok(!built.text.includes('全部正常'), '0 条不能糊成「全部正常」');
assert.ok(!built.text.includes('数据未覆盖核验时刻'), '0 单已有专门告警,别再叠一条快照告警');
});
// ── ⑥ 有异常时的快照新鲜度也必须进正文(2026-11-11)──────────────────
// 实况:镜像表停在 11-10 11:53,09:10 那批算出 990 单全部异常,正文只有一句
// 「异常 990 个(100%)」。群里没法分辨「真异常」和「数据停在昨天」,
// 而这恰恰决定当天要不要催快递。下面把两种降级(未覆盖核验时刻 / 快照过旧)钉死。
test('快照没覆盖核验时刻 → 正文点名「未覆盖」,并把前一天的日期带上(不能只写 11:53)', () => {
const data = sampleData({
freshness: {
snapshotAt: '2026-10-21 11:53:00',
ageMinutes: 1270,
stale: true,
coversDeadline: false,
emptyWindow: false,
},
});
const built = job.buildNotifyText(data, { maxDetailRows: 30 });
assert.match(built.text, /数据未覆盖核验时刻/);
assert.match(built.text, /最新只到 10-21 11:53/, '跨天必须带 MM-DD,否则会被读成当天 11:53');
assert.match(built.text, /本轮核验 09:00/, '同一天的时刻不带日期');
assert.match(built.text, /别按这个数去催快递/);
// 抬头仍要带「异常」关键词,否则钉钉自定义关键词会拒收
assert.match(built.text, /【仓储物流转运异常】/);
});
test('快照同日但没过核验时刻 → 只写时分,不啰嗦日期', () => {
const data = sampleData({
freshness: { snapshotAt: '2026-10-22 08:30:00', ageMinutes: 30, stale: false, coversDeadline: false },
});
const built = job.buildNotifyText(data, { maxDetailRows: 30 });
assert.match(built.text, /最新只到 08:30/);
assert.ok(!built.text.includes('10-22 08:30'), '同一天不重复写日期');
});
test('快照过旧(stale)→ 正文写「偏旧」+ 未刷新时长,异常量标注仅供参考', () => {
const data = sampleData({
freshness: { snapshotAt: '2026-10-22 09:05:00', ageMinutes: 200, stale: true, coversDeadline: true },
});
const built = job.buildNotifyText(data, { maxDetailRows: 30 });
assert.match(built.text, /物流快照偏旧/);
assert.match(built.text, /09:05/);
assert.match(built.text, /已 3\.3 小时未刷新/);
assert.match(built.text, /仅供参考/);
});
test('快照正常 → 正文不出现任何新鲜度告警(别把正常批次也刷成黄色)', () => {
const data = sampleData({
freshness: { snapshotAt: '2026-10-22 09:05:00', ageMinutes: 3, stale: false, coversDeadline: true },
});
const built = job.buildNotifyText(data, { maxDetailRows: 30 });
assert.ok(!built.text.includes('数据未覆盖核验时刻'));
assert.ok(!built.text.includes('物流快照偏旧'));
assert.match(built.text, /异常 144 个包裹/);
});
test('快照字段缺失(老缓存 / 接口未返回)→ 不能崩,也不能瞎报警', () => {
const data = sampleData({ freshness: undefined });
const built = job.buildNotifyText(data, { maxDetailRows: 30 });
assert.match(built.text, /异常 144 个包裹/);
assert.ok(!built.text.includes('⚠️ 数据未覆盖'));
assert.equal(job.buildFreshnessWarning(undefined, {}), '');
assert.equal(job.buildFreshnessWarning({ coversDeadline: null }, {}), '');
});
// ── ⑥ 推送失败要重试,不能「一天只有一次机会」(2026-11-11)──────────────
// 实况:11-11 09:10 那次撞上业务库连不上(状态里 `Failed to connect to 218.93.9.21:1433`),
// 老逻辑用 `HH:mm === sendTime` 严格相等,只给一分钟机会,失败后当天彻底不推、群里一整天没消息。
// 下面把窗口与节流的边界钉死,避免改成「每分钟都重跑」把 240s 的全量核验打成 DDoS。
function beijing(isoText) {
return new Date(isoText); // 测试用 UTC 写法,避免本机时区把断言带偏
}
test('重试调度:到点第一次跑,推成功之后当天不再跑', () => {
const sendTime = '09:10';
const first = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T01:10:00Z'), // 北京 09:10
sendTime,
state: {},
});
assert.equal(first.run, true);
assert.equal(first.reason, 'first_round');
assert.equal(first.attempt, 1);
assert.equal(first.pushDate, '2026-11-11');
const sent = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T01:11:00Z'), // 北京 09:11,09:10 那轮已成功
sendTime,
state: { lastSentDate: '2026-11-11', lastSentAt: '2026-11-11T01:10:03Z' },
});
assert.equal(sent.run, false);
assert.equal(sent.reason, 'already_sent_today');
});
test('重试调度:没到点的分钟一律不跑(不会被「窗口」提前触发)', () => {
const decision = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T01:09:00Z'), // 北京 09:09
sendTime: '09:10',
state: {},
});
assert.equal(decision.run, false);
assert.equal(decision.reason, 'before_time');
});
test('重试调度:失败后按 5 分钟间隔重试,间隔内不重复拉全量核验', () => {
const sendTime = '09:10';
const failedState = { lastAttemptAt: '2026-11-11T01:10:00Z', attemptDate: '2026-11-11', attemptCount: 1 };
const tooSoon = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T01:13:00Z'), // 距上次尝试 3 分钟
sendTime,
state: failedState,
});
assert.equal(tooSoon.run, false);
assert.equal(tooSoon.reason, 'wait_interval');
const retry = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T01:15:00Z'), // 距上次尝试 5 分钟,正好到间隔
sendTime,
state: failedState,
});
assert.equal(retry.run, true);
assert.equal(retry.reason, 'retry');
assert.equal(retry.attempt, 2);
});
test('重试调度:过了「推送时刻 + 30 分钟」窗口就不再补推', () => {
const sendTime = '09:10';
const failedState = { lastAttemptAt: '2026-11-11T01:35:00Z', attemptDate: '2026-11-11', attemptCount: 6 };
const inside = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T01:40:00Z'), // 北京 09:40,窗口最后一分钟
sendTime,
state: failedState,
});
assert.equal(inside.run, true, '窗口边界(含)仍要重试');
const closed = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T01:41:00Z'), // 北京 09:41
sendTime,
state: failedState,
});
assert.equal(closed.run, false);
assert.equal(closed.reason, 'window_closed');
});
test('重试调度:跨天后尝试次数归零,昨天的失败不节流今天的首轮', () => {
const decision = job.resolveScheduledPushDecision({
now: beijing('2026-11-12T01:10:00Z'), // 北京 11-12 09:10
sendTime: '09:10',
state: { lastAttemptAt: '2026-11-11T01:35:00Z', attemptDate: '2026-11-11', attemptCount: 6 },
});
assert.equal(decision.run, true);
assert.equal(decision.reason, 'first_round');
assert.equal(decision.attempt, 1);
});
test('重试调度:重试窗口不跨日(23:50 推送不会被次日 00:10 当成「窗口内」)', () => {
const decision = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T16:10:00Z'), // 北京 11-12 00:10
sendTime: '23:50',
state: {},
});
assert.equal(decision.run, false);
assert.equal(decision.reason, 'before_time');
});
test('重试调度:尝试记录残缺(有次数没时间)时不能卡死,该重试就重试', () => {
const decision = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T01:11:00Z'),
sendTime: '09:10',
state: { attemptDate: '2026-11-11', attemptCount: 2, lastAttemptAt: '' },
});
assert.equal(decision.run, true);
assert.equal(decision.reason, 'retry');
assert.equal(decision.attempt, 3);
});
test('重试调度:sendTime 非法时安静不跑(配置坏了不能把定时任务打崩)', () => {
const decision = job.resolveScheduledPushDecision({
now: beijing('2026-11-11T01:10:00Z'),
sendTime: 'not-a-time',
state: {},
});
assert.equal(decision.run, false);
assert.equal(decision.reason, 'bad_send_time');
});
test('重试参数:默认 30 分钟窗口 / 5 分钟间隔,环境变量可覆盖', () => {
assert.equal(job.DEFAULT_RETRY_WINDOW_MINUTES, 30);
assert.equal(job.DEFAULT_RETRY_INTERVAL_MINUTES, 5);
assert.equal(job.minuteOfDay('09:10'), 550);
assert.equal(job.minuteOfDay('00:00'), 0);
assert.equal(job.minuteOfDay('23:59'), 1439);
assert.equal(job.minuteOfDay('9:10'), null, '必须是零填充的 HH:mm');
assert.equal(job.minuteOfDay(''), null);
}); });