oms/backend/app/schedule/fetchExternalShopOrders.js
liufumingren a4213bfd0d fix(external-print): 拉单只取平台未发货订单,已发货/已终结不再进待审核
问题:店管家 /NewOrder/List 只支持按时间窗查询,不提供发货状态过滤,
原实现仅按 UpFxUserId 归属就整批入库,导致 sended/success/close 的订单
全部堆进「待审核」(实测店铺 19 近 7 天平台返回 385 单,真正待发货只有 11 单)。

- dgj 新增 isOrderFinished():ErpState∈sended/success/close(及各平台等价状态)、
  有 OnlineSendTime、面单 IsSended=true、LogisticStatus>0 任一命中即视为已处理;
  PrintState/ExpressPrintTime 仅表示已打印面单,不作为判定依据
- listOrders 过滤未发货订单,返回 skipped 与 finished 列表
- externalPrintOrder.syncOrders 新增 voidFinishedOrders():本地仍处于待审核、
  平台侧已发货的副本自动作废(写 void_at/void_reason + 操作日志),已审核订单不动
- orderStatus.voidOrder 支持 principalId(定时任务无登录态)
- 手动/自动拉单消息、接口返回、接口契约、前端提示补充「跳过已发货 / 自动作废」统计
- 新增 scripts/cleanup-shipped-pending-orders.js(npm run orders:cleanup-shipped):
  按同一口径清理历史脏单,默认 dry-run,--apply 才删除
- 新增 isOrderFinished 单测(7 项)

已清理历史脏单 103 条(备份见会话 files/backup-shipped-pending-orders.json),
清理后待审核仅剩 2 单真实的平台待发货订单。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-03 04:14:02 +08:00

111 lines
3.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/**
* 定时拉取外部打单平台订单。
*
* 每分钟扫描开启「自动拉取订单」的外部打单平台店铺(type=2),
* 按各店铺配置的间隔(auto_fetch_interval,最小 3 分钟)判断是否到期:
* - 上次拉取时间 + 间隔 > 现在 → 跳过
* - 否则以「上次拉取时间向前重叠 10 分钟」为起点拉取,避免边界订单漏单;
* 从未拉取过时按最近一个间隔拉取
*
* 拉取逻辑与手动拉取共用 service(externalPrintOrder),保证入库口径一致;
* 每次执行后记录 last_order_sync_at / last_order_sync_msg,失败不影响其它店铺。
*/
const OVERLAP_MS = 10 * 60 * 1000;
const MIN_INTERVAL_MINUTES = 3;
const DEFAULT_INTERVAL_MINUTES = 3;
/** 防止上一轮未结束时重复触发(单进程内串行) */
let running = false;
module.exports = {
schedule: {
cron: '0 * * * * *',
type: 'worker',
disable: false,
},
async task(ctx) {
if (running) {
ctx.logger.info('[external-order-fetch] 上一轮仍在执行,跳过本次');
return { skipped: true };
}
running = true;
try {
const Op = ctx.app.Sequelize.Op;
const shops = await ctx.model.Shop.findAll({
where: {
type: 2,
status: 1,
auto_fetch_order: 1,
external_print_account_id: { [Op.ne]: null },
},
order: [[ 'id', 'ASC' ]],
});
if (!shops.length) return { shops: 0 };
const accountIds = Array.from(new Set(shops.map(shop => Number(shop.external_print_account_id))));
const accounts = await ctx.model.ExternalPrintAccount.findAll({
where: { id: { [Op.in]: accountIds } },
include: [
{
model: ctx.model.ExternalPrintPlatform,
as: 'platform',
attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ],
},
],
});
const accountMap = new Map(accounts.map(account => [ Number(account.id), account ]));
const now = new Date();
let fetched = 0;
let failed = 0;
for (const shop of shops) {
const interval = Math.max(
MIN_INTERVAL_MINUTES,
Number(shop.auto_fetch_interval) || DEFAULT_INTERVAL_MINUTES
) * 60 * 1000;
const last = shop.last_order_sync_at ? new Date(shop.last_order_sync_at) : null;
if (last && now.getTime() - last.getTime() < interval) continue;
const account = accountMap.get(Number(shop.external_print_account_id));
if (!account) {
await ctx.service.externalPrintOrder.markShopSynced(shop, now, '拉单失败:店铺关联的打单账号不存在');
failed++;
continue;
}
const startTime = last ? new Date(last.getTime() - OVERLAP_MS) : new Date(now.getTime() - interval);
try {
const result = await ctx.service.externalPrintOrder.syncOrders(shop, account, {
startTime,
endTime: now,
});
await ctx.service.externalPrintOrder.markShopSynced(
shop,
now,
`自动拉取成功:${result.orders} 单(新增 ${result.created},更新 ${result.updated}),明细 ${result.items} 条` +
`,跳过平台已发货 ${result.skipped || 0} 单,自动作废 ${result.voided || 0} 单`
);
fetched++;
ctx.logger.info(
`[external-order-fetch] 店铺 ${shop.id} 拉单成功:订单 ${result.orders},明细 ${result.items},跳过已发货 ${result.skipped || 0},作废 ${result.voided || 0}`
);
} catch (err) {
await ctx.service.externalPrintOrder.markShopSynced(shop, now, `自动拉取失败:${err.message}`);
failed++;
ctx.logger.warn(`[external-order-fetch] 店铺 ${shop.id} 拉单失败:${err.message}`);
}
}
return { shops: shops.length, fetched, failed };
} finally {
running = false;
}
},
};