liufumingren a4cadeb83b feat: 库内确定拦截订单明细报表与拦截时间口径调整
- 新增通用报表注册类型 interceptOrder(库内确定拦截订单明细):以配送表 dispath_time 为时间基准,统计昨日自然日(不含当天,可用 params.bizDate 指定更早日期补数)intercept_status=intercepted_at_warehouse 的订单,按商品明细展开;列 = 订单导出 item 模式去掉商品图片(46 列)+ 平台交易单号 / 通知拦截时间 / 库内确定拦截时间,共 49 列
- intercept_time 口径统一为「最近一次发起拦截的通知时刻」:发起拦截首次写入不覆盖(新增 app/lib/intercept_time.js 与 qimen/openapi/inbox/pendingOrder 四处改造)、库内拦截确认与退回入库不再覆盖、取消/解除拦截与订单克隆重置置空;库内确定拦截时刻改用配送表 dispath_time
- 报表导出文件名模板新增 {time}(生成时刻 HHmmss)/ {datetime} / {timestamp} 占位符({date} 语义不变),避免同一天多次投递/导出同一报表时 COS 同名覆盖与 CDN 旧内容回源
- 文档同步:methods/system.json 0.3.104 -> 0.3.109(report.generate / report.definition.* 契约与拦截时间口径说明)、methods/changes/system.json 新增 4 条变更记录、docs/report-config-guide.md 新增 2.2 节、字段清单与文件名占位符说明
- 回归与实测:test/report_*.cjs 13 个文件 + test/intercept_time_lifecycle.cjs 全部通过,ESLint 0 error;开发库投递计划实测(19:40 / 20:25 两条计划投递成功或仅文本通知环境依赖失败,文件名均带时分秒、导出列与定义勾选一致)
2026-09-10 20:59:39 +08:00

478 lines
22 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';
const { scheduleDateOf } = require('../../../../lib/report/day_window');
/**
* 库内确定拦截订单明细查询器(静态字段清单)。
*
* 前 46 列与 order.export(export_mode=item,按商品明细展开)的列对齐,
* 仅去掉「商品图片」列(报表渲染不支持内嵌图片,订单导出该列本身也不落地 URL);
* 另附加 3 列(订单导出无):
* `source_order_codes`(平台交易单号,取订单表源单号字段,位置紧跟「外部单号」)、
* `intercept_notice_time`(通知拦截时间,取配送表 intercept_time,为空时回落 ORDER_INTERCEPT_REQUEST 日志最早时间)、
* `intercept_confirm_time`(库内确定拦截时间,取配送表 dispath_time)。
* key 与查询器返回的行字段一一对应,type 统一为 string:
* 渲染层对 string 字段原样输出,不做 zeroToDash/yesNo 转换,
* 从而保证单元格取值与订单导出逐格一致(见 render.js renderCell 口径);
* 两个时间列由查询器格式化为 'YYYY-MM-DD HH:mm:ss' 字符串(与订单导出的时间列同格式)。
* @type {Array<Object>}
*/
const FIELDS = Object.freeze([
{ key: 'id', label: '订单ID', type: 'string' },
{ key: 'delivery_order_code', label: '订单号', type: 'string' },
{ key: 'external_order_code', label: '外部单号', type: 'string' },
{ key: 'source_order_codes', label: '平台交易单号', type: 'string' },
{ key: 'status', label: '订单状态', type: 'string' },
{ key: 'wave_no', label: '波次号', type: 'string' },
{ key: 'wave_index', label: '波次序号', type: 'string' },
{ key: 'store_id', label: '货主', type: 'string' },
{ key: 'sys_platform_name', label: '平台', type: 'string' },
{ key: 'create_channel', label: '来源', type: 'string' },
{ key: 'shop_nick', label: '店铺昵称', type: 'string' },
{ key: 'receiver_name', label: '收件人', type: 'string' },
{ key: 'receiver_mobile', label: '收件人电话', type: 'string' },
{ key: 'receiver_province', label: '省', type: 'string' },
{ key: 'receiver_city', label: '市', type: 'string' },
{ key: 'receiver_district', label: '区', type: 'string' },
{ key: 'receiver_town', label: '镇', type: 'string' },
{ key: 'receiver_detail', label: '详细地址', type: 'string' },
{ key: 'item_name', label: '仓库商品名称', type: 'string' },
{ key: 'item_barcode', label: '商品条码', type: 'string' },
{ key: 'item_quantity', label: '数量', type: 'string' },
{ key: 'logistics_name', label: '物流公司', type: 'string' },
{ key: 'waybill_code', label: '运单号', type: 'string' },
{ key: 'business_type', label: '业务类型', type: 'string' },
{ key: 'logistics_interface_name', label: '运单接口', type: 'string' },
{ key: 'package_material_id', label: '包材ID', type: 'string' },
{ key: 'package_material_code', label: '包材编码', type: 'string' },
{ key: 'package_material_name', label: '包材名称', type: 'string' },
{ key: 'waybill_allocated_at', label: '分配时间', type: 'string' },
{ key: 'items_count', label: '商品种数', type: 'string' },
{ key: 'items_total', label: '商品件数', type: 'string' },
{ key: 'items_weight', label: '商品重量', type: 'string' },
{ key: 'weighing_weight', label: '称重重量(g)', type: 'string' },
{ key: 'total_amount', label: '订单金额', type: 'string' },
{ key: 'got_amount', label: '实收金额', type: 'string' },
{ key: 'create_at', label: '创建时间', type: 'string' },
{ key: 'pay_time', label: '支付时间', type: 'string' },
{ key: 'delivery_time', label: '发货时间', type: 'string' },
{ key: 'outbound_status', label: '出库状态', type: 'string' },
{ key: 'inspection_status', label: '复核状态', type: 'string' },
{ key: 'recheck_status', label: '复核完成状态', type: 'string' },
{ key: 'post_status', label: '配货状态', type: 'string' },
{ key: 'pack_status', label: '打包状态', type: 'string' },
{ key: 'remark', label: '备注', type: 'string' },
{ key: 'buyer_message', label: '买家留言', type: 'string' },
{ key: 'seller_message', label: '卖家留言', type: 'string' },
{ key: 'archive_time', label: '归档时间', type: 'string' },
{ key: 'intercept_notice_time', label: '通知拦截时间', type: 'string' },
{ key: 'intercept_confirm_time', label: '库内确定拦截时间', type: 'string' },
]);
/**
* 查询器缺省窗口元数据(供 report.definition.typeList 展示)。
* 本查询器为「单个自然日」粒度:dayCount=1、cutoverHour=0(00:00 切日,非 stockFlow 的 07:00)。
* @type {{dayCount: number, cutoverHour: number}}
*/
const DEFAULT_WINDOW = Object.freeze({ dayCount: 1, cutoverHour: 0 });
/** 查询表位:配送表(订单出库迁移后的表位,dispath_time 为该表独有字段) */
const DISPATCH_TABLE_TYPE = 'dispatch';
/** 库内确定拦截状态(order.recheckOrder.confirmIntercept / intercept_auto_confirm 写入值) */
const INTERCEPTED_AT_WAREHOUSE_STATUS = 'intercepted_at_warehouse';
/** 明细展开模式(与 order.export export_mode=item 一致:一个商品一行) */
const EXPORT_MODE_ITEM = 'item';
/** 单页拉取订单数(复用订单导出分页大小) */
const DEFAULT_PAGE_SIZE = 1000;
/** 单次报表生成的最大明细行数保护(防御性上限,正常日拦截单量远低于该值) */
const MAX_EXPORT_ROWS = 200000;
/** 通知拦截(发起拦截请求)操作日志编码:wms_operation_log.operation_code */
const ORDER_INTERCEPT_REQUEST_CODE = 'ORDER_INTERCEPT_REQUEST';
/** 拦截时间富化(回查配送表 + 操作日志)单批订单ID数 */
const ENRICH_CHUNK_SIZE = 500;
/**
* 两位补零。
* @param {number} value 数值
* @return {string} 补零字符串
*/
function pad2(value) {
return String(value).padStart(2, '0');
}
/**
* 本地时区格式化为 'YYYY-MM-DD HH:mm:ss'。
* @param {Date} date 时间对象
* @return {string} 格式化结果
*/
function formatDateTime(date) {
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
+ ` ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`;
}
/**
* 解析统计日与查询区间。
*
* 规则:
* 1. `params.bizDate`(或 `biz_date`)为合法 `YYYY-MM-DD` 时,按该日自然日整天统计;
* 2. 未传/非法时回落「昨日自然日」,即 [昨日 00:00:00.000, 今日 00:00:00.000);
* 3. **硬约束:统计日不得晚于昨天**——传入今天/未来日期一律回落昨日,
* 保证「今天生成/投递的报表不含今天的数据」(当天新迁入的拦截单只会在次日报表里出现);
* 4. 区间为本地时区半开区间(start 含、end 不含),通过 `new Date(y, m, d)` 构造,
* 规避夏令时导致的步进偏差。
*
* @param {Object} [params={}] 查询器业务参数
* @return {{bizDate: string, start: Date, end: Date}} 统计日与区间
*/
function resolveBizDayWindow(params = {}) {
const safeParams = params && typeof params === 'object' ? params : {};
const rawBizDate = String(safeParams.bizDate || safeParams.biz_date || '').trim();
const now = new Date();
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
const yesterdayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1, 0, 0, 0, 0);
let baseDate = null;
const matched = /^(\d{4})-(\d{2})-(\d{2})$/.exec(rawBizDate);
if (matched) {
const year = Number(matched[1]);
const month = Number(matched[2]);
const day = Number(matched[3]);
const candidate = new Date(year, month - 1, day, 0, 0, 0, 0);
if (
candidate.getFullYear() === year
&& candidate.getMonth() === month - 1
&& candidate.getDate() === day
) {
baseDate = candidate;
}
}
if (!baseDate) {
baseDate = yesterdayStart;
}
// 今天及以后一律回落昨日:今天生成/投递的报表只含昨天(及更早显式指定日)的数据
if (baseDate.getTime() >= todayStart.getTime()) {
baseDate = yesterdayStart;
}
const start = new Date(baseDate.getFullYear(), baseDate.getMonth(), baseDate.getDate(), 0, 0, 0, 0);
const end = new Date(baseDate.getFullYear(), baseDate.getMonth(), baseDate.getDate() + 1, 0, 0, 0, 0);
return { bizDate: scheduleDateOf(start), start, end };
}
/**
* 按字段清单裁剪订单导出行,保证报表列与订单导出 item 模式对齐并丢弃多余键(如 item_image)。
* @param {Object} row 订单导出行
* @return {Object} 仅含注册字段的报表行
*/
function pickReportRow(row = {}) {
const safeRow = row && typeof row === 'object' ? row : {};
const result = {};
for (const field of FIELDS) {
const value = safeRow[field.key];
result[field.key] = value === undefined ? '' : value;
}
return result;
}
/**
* 安全格式化时间列(与订单导出 formatDateSafe 口径一致:空值/无效值返回空字符串)。
* @param {*} value 时间原始值
* @param {Object} app Egg app 实例(取 app.formatDate)
* @return {string} 'YYYY-MM-DD HH:mm:ss' 或空字符串
*/
function formatTimeValue(value, app) {
if (value === null || value === undefined || value === '' || value === 0) {
return '';
}
const date = value instanceof Date ? value : new Date(value);
if (Number.isNaN(date.getTime()) || date.getTime() <= 0) {
return '';
}
return app && typeof app.formatDate === 'function' ? app.formatDate(date) : formatDateTime(date);
}
/**
* 富化报表附加列(按订单ID回查,分片避免大 IN 列表)。
*
* - `source_order_codes`(平台交易单号):直接取配送表同名字段(`mapOrderExportRow(item)` 不输出该列);
* - `intercept_notice_time`(通知拦截时间):主取配送表 `intercept_time`
* (自 2026-09-10 起该字段为「最近一次发起拦截的通知时刻」,确认拦截不再覆盖,
* 见 `app/lib/intercept_time.js`);该列为空时回落 `wms_operation_log` 中
* `operation_code = 'ORDER_INTERCEPT_REQUEST'` 的**最早**记录时间(历史数据兼容)。
* 回查日志按 `business_type='order' + business_id=订单ID + warehouse_id=当前仓库` 三重过滤:
* 订单 ID 按仓库发号,必须同仓隔离,禁止仅凭订单ID跨仓串读。
* - `intercept_confirm_time`(库内确定拦截时间):取配送表 `dispath_time`
* (订单迁移进配送表的时间;库内确定拦截后订单会走 outbound_status=fin 的自动迁移,故等价于库内确定拦截时刻)。
*
* 时间列均格式化为 'YYYY-MM-DD HH:mm:ss';查不到值时留空字符串。
*
* @param {Object} args 入参
* @param {Object} args.ctx Egg 上下文
* @param {Object} args.app Egg app 实例(时间格式化)
* @param {Object} args.orderModel 配送表模型(读取 source_order_codes/intercept_time/dispath_time)
* @param {number} args.warehouseId 仓库ID
* @param {Array<Object>} args.rows 报表行(原地写入附加列,行内需含订单ID `id`)
* @return {Promise<Array<Object>>} 富化后的行数组(同一引用)
*/
async function enrichInterceptFields({ ctx, app, orderModel, warehouseId, rows = [] }) {
const list = Array.isArray(rows) ? rows : [];
if (list.length === 0) {
return list;
}
const orderIds = [ ...new Set(
list
.map(row => Number(row && row.id) || 0)
.filter(orderId => orderId > 0)
) ];
if (orderIds.length === 0) {
return list;
}
const { Op, fn, col } = app.Sequelize;
const noticeTimeMap = new Map();
const confirmTimeMap = new Map();
const sourceOrderCodeMap = new Map();
const logModel = ctx.model && ctx.model.OperationLog;
for (let offset = 0; offset < orderIds.length; offset += ENRICH_CHUNK_SIZE) {
const chunk = orderIds.slice(offset, offset + ENRICH_CHUNK_SIZE);
// 平台交易单号(source_order_codes)+ 通知拦截时间(intercept_time)+ 库内确定拦截时间(dispath_time)
try {
const orderRows = await orderModel.findAll({
where: { id: { [Op.in]: chunk } },
attributes: [ 'id', 'source_order_codes', 'intercept_time', 'dispath_time' ],
raw: true,
});
for (const orderRow of (Array.isArray(orderRows) ? orderRows : [])) {
const orderId = Number(orderRow && orderRow.id) || 0;
if (orderId > 0) {
sourceOrderCodeMap.set(orderId, orderRow.source_order_codes);
noticeTimeMap.set(orderId, orderRow.intercept_time);
confirmTimeMap.set(orderId, orderRow.dispath_time);
}
}
} catch (error) {
ctx.logger.warn(
'[report.interceptOrder] 回查配送表附加列失败,平台交易单号/拦截时间列留空: %s',
error && error.message ? error.message : `${error}`
);
}
// 通知拦截时间(兜底,仅补齐主取为空的订单):操作日志最早一条 ORDER_INTERCEPT_REQUEST
if (logModel && typeof logModel.findAll === 'function') {
const pendingIds = chunk.filter(
orderId => orderId > 0 && (noticeTimeMap.get(orderId) === null || noticeTimeMap.get(orderId) === undefined)
);
if (pendingIds.length === 0) {
continue;
}
try {
const logRows = await logModel.findAll({
attributes: [ 'business_id', [ fn('MIN', col('created_at')), 'notice_time' ]],
where: {
business_type: 'order',
operation_code: ORDER_INTERCEPT_REQUEST_CODE,
warehouse_id: warehouseId,
business_id: { [Op.in]: pendingIds.map(orderId => String(orderId)) },
},
group: [ 'business_id' ],
raw: true,
});
for (const logRow of (Array.isArray(logRows) ? logRows : [])) {
const orderId = Number(logRow && logRow.business_id) || 0;
if (orderId > 0) {
noticeTimeMap.set(orderId, logRow.notice_time);
}
}
} catch (error) {
ctx.logger.warn(
'[report.interceptOrder] 回查通知拦截操作日志失败,通知拦截时间列留空: %s',
error && error.message ? error.message : `${error}`
);
}
}
}
for (const row of list) {
const orderId = Number(row && row.id) || 0;
const sourceOrderCodes = sourceOrderCodeMap.get(orderId);
row.source_order_codes = sourceOrderCodes === null || sourceOrderCodes === undefined
? ''
: String(sourceOrderCodes);
row.intercept_notice_time = formatTimeValue(noticeTimeMap.get(orderId), app);
row.intercept_confirm_time = formatTimeValue(confirmTimeMap.get(orderId), app);
}
return list;
}
/**
* 内置查询器:库内确定拦截订单明细(昨日迁入配送表的库内拦截订单,按商品明细展开)。
*
* 口径与假设(供测试复核):
* 1. 数据源:配送表 `wms_order_delivery_{warehouseId}_dispatch`,仅取
* `intercept_status = 'intercepted_at_warehouse'`(库内确定拦截;由
* `order.recheckOrder.confirmIntercept` 与 `intercept_auto_confirm` 写入,同时 step=4、outbound_status=fin);
* 2. 时间基准:`dispath_time`(订单迁移进配送表的时刻,配送表独有字段,由
* `orderDeliveryMigration.buildDispatchRow` 写入 `new Date()`);
* 3. 时间范围:默认「昨日自然日」[昨日 00:00:00.000, 今日 00:00:00.000) 本地时区半开区间,
* 可通过 `params.bizDate`(YYYY-MM-DD)指定更早的统计日;非法值回落昨日,
* **今天及以后的日期一律回落昨日**(今天生成/投递的报表永不含今天数据,
* 当天新迁入配送表的拦截单只会在次日报表中出现);
* 4. 明细粒度与列:复用 `orderExport.buildOrderExportPage` → `mapOrderExportRow(row, ctx, 'item')`,
* 因此状态中文翻译、货主备注、条码/商品名回落、运单汇总、包材等取值与订单导出 item 模式逐格一致;
* 列清单 = 订单导出 item 模式 47 列去掉「商品图片」列(46 列)+ 3 列附加列
* (平台交易单号 source_order_codes、通知拦截时间、库内确定拦截时间,共 49 列);
* 5. 无商品明细的订单输出一行订单级数据(运单字段汇总),与订单导出 item 模式一致;
* 6. 主维度:warehouseId 必填(配送表按仓库分表);storeId > 0 时追加 `store_id` 过滤
* (货主维度报表与投递),否则为仓库维度全量;
* 7. 排序:按订单 ID 升序分页拉取(单页 1000 单,循环至不足一页);
* 8. 附加列(订单导出 item 模式无此 3 列):
* - `source_order_codes`(平台交易单号)= 配送表 `source_order_codes` 原值
* (`mapOrderExportRow(item)` 不输出该列,由本查询器回查补充,位置紧跟「外部单号」);
* - `intercept_notice_time`(通知拦截时间)= 配送表 `intercept_time`
* (自 2026-09-10 起为「最近一次发起拦截的通知时刻」,确认拦截不再覆盖;
* 为空时回落 `wms_operation_log` 的 ORDER_INTERCEPT_REQUEST 最早记录,按同仓隔离查询);
* - `intercept_confirm_time`(库内确定拦截时间)= 配送表 `dispath_time`
* (订单迁移进配送表的时间,库内确定拦截后基本都会走出库迁移);
* 两个时间列格式化为 'YYYY-MM-DD HH:mm:ss';
* 8. 波次序号(wave_index):复用订单导出同款 `attachOrderWaveIndex`,该实现按登录上下文仓库
* 取值,定时投递(无 ctx.user)场景降级为 0,手工导出(仓库主体)为真实序号。
*
* @param {Object} args 查询器入参
* @param {Object} args.ctx Egg 上下文
* @param {number|null} args.storeId 货主ID(可选,<=0 时不按货主过滤)
* @param {number|null} args.warehouseId 仓库ID(必填)
* @param {Object} [args.params={}] 业务参数(bizDate 统计日覆盖)
* @return {Promise<{windows: Array<Object>, rows: Array<Object>, meta: Object}>} 查询结果
*/
async function interceptOrder({ ctx, storeId = null, warehouseId = null, params = {} }) {
const { app } = ctx;
const { Op } = app.Sequelize;
const normalizedWarehouseId = Number(warehouseId) || 0;
if (normalizedWarehouseId <= 0) {
throw new Error('interceptOrder 查询器缺少仓库维度 warehouseId');
}
const { bizDate, start, end } = resolveBizDayWindow(params);
const normalizedStoreId = Number(storeId) || 0;
const orderExport = ctx.service && ctx.service.systems ? ctx.service.systems.orderExport : null;
if (!orderExport || typeof orderExport.buildOrderExportPage !== 'function') {
throw new Error('订单导出服务不可用,无法复用订单明细口径(orderExport.buildOrderExportPage)');
}
const target = orderExport.resolveExportTarget({ tableType: DISPATCH_TABLE_TYPE });
const orderModel = await orderExport.getOrderModelByTableType(DISPATCH_TABLE_TYPE, normalizedWarehouseId);
const queryWhere = {
intercept_status: INTERCEPTED_AT_WAREHOUSE_STATUS,
dispath_time: {
[Op.gte]: start,
[Op.lt]: end,
},
};
if (normalizedStoreId > 0) {
queryWhere.store_id = normalizedStoreId;
}
const pageSize = Number(typeof orderExport.getExportPageSize === 'function'
? orderExport.getExportPageSize()
: 0) || DEFAULT_PAGE_SIZE;
const rows = [];
let orderCount = 0;
let page = 1;
let truncated = false;
for (;;) {
const pageResult = await orderExport.buildOrderExportPage({
page,
pageSize,
queryWhere,
order: [[ 'id', 'ASC' ]],
orderModel,
target,
warehouseId: normalizedWarehouseId,
mode: EXPORT_MODE_ITEM,
});
const pageOrderCount = Number(pageResult && pageResult.orderCount) || 0;
if (pageOrderCount <= 0) {
break;
}
const pageRows = Array.isArray(pageResult && pageResult.exportRows) ? pageResult.exportRows : [];
for (const pageRow of pageRows) {
rows.push(pickReportRow(pageRow));
if (rows.length >= MAX_EXPORT_ROWS) {
truncated = true;
break;
}
}
orderCount += pageOrderCount;
if (truncated || pageOrderCount < pageSize) {
break;
}
page += 1;
}
if (truncated) {
ctx.logger.warn(
'[report.interceptOrder] 明细行数达到上限 %s,已截断(bizDate=%s warehouseId=%s)',
MAX_EXPORT_ROWS,
bizDate,
normalizedWarehouseId
);
}
// 附加列:平台交易单号(source_order_codes)+ 通知拦截时间(配送表 intercept_time,日志兜底)
// + 库内确定拦截时间(配送表 dispath_time)
await enrichInterceptFields({
ctx,
app,
orderModel,
warehouseId: normalizedWarehouseId,
rows,
});
const noticeTimeFilledCount = rows.filter(row => String(row.intercept_notice_time || '').trim()).length;
const confirmTimeFilledCount = rows.filter(row => String(row.intercept_confirm_time || '').trim()).length;
return {
windows: [],
rows,
meta: {
bizDate,
startTime: formatDateTime(start),
endTime: formatDateTime(end),
warehouseId: normalizedWarehouseId,
storeId: normalizedStoreId,
interceptStatus: INTERCEPTED_AT_WAREHOUSE_STATUS,
timeField: 'dispath_time',
orderCount,
rowCount: rows.length,
noticeTimeFilledCount,
confirmTimeFilledCount,
truncated,
},
};
}
module.exports = interceptOrder;
module.exports.fields = FIELDS;
module.exports.defaultWindow = DEFAULT_WINDOW;
// 纯函数导出(供单测/校验脚本复核口径,不作为查询器调用入口)
module.exports.resolveBizDayWindow = resolveBizDayWindow;
module.exports.pickReportRow = pickReportRow;
module.exports.enrichInterceptFields = enrichInterceptFields;