feat(order): ?????????? order.deliveryOrder.summary
- ?? order.deliveryOrder.summary??????????????????????? ???????/????/?????????????????????? - ????????? + ??????history/outsourced ?????????? CONVERT_TZ ????????????? UTC ????????? - ???? 7 ????????? 90 ??????????? 0??? store_id ?? - ?? methods/system.json?0.3.302 ? 0.3.303??????? AI_METHOD_ROUTING.md Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
1afe068e73
commit
615e3694b5
@ -308,6 +308,21 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- 表结构:wms_client_error_log(迁移 database/migrations/20260925100000-create-wms-client-error-log.js、模型 app/model/client_error_log.js);索引 uk_report_uuid(唯一)、idx_created_at、idx_client_type_app_version、idx_device_id
|
||||
- 接口文档:methods/system.json 分组「基础模块」(module=index),变更记录见 methods/changes/system.json 版本 `2026.09.25-index-upload-client-error-log`
|
||||
|
||||
## 5.10 order.deliveryOrder.summary(配送订单每日汇总)能力速查
|
||||
|
||||
| method | 实现文件 | 函数 | 登录 | 鉴权/权限 |
|
||||
|---|---|---|---|---|
|
||||
| order.deliveryOrder.summary | app/service/systemMethods/order/deliveryOrder.js → app/service/systems/deliveryOrderSummary.js | summary / queryDailySummary | 需登录 | 免权限、免鉴权(只读接口,systemInit 的 _noNeedRight/_noNeedAuth 与 list/quickSearch 同口径) |
|
||||
|
||||
- 语义:以自然日(yyyy-MM-dd)为维度汇总配送订单,仓库取自登录上下文 `ctx.user.store_id`(禁止传 warehouse_id),可选 `store_id` 按货主过滤;缺省最近 7 个自然日(含今天),单次最多 90 天,区间内无数据日期补 0
|
||||
- 数据源:订单常用表 + 配送表(`OrderDeliveryFactory.getCurrentModel` / `getDispatchModel`);订单出库迁移进配送表时删除源行,两表无重叠直接相加;归档表 history、委托外仓 outsourced 不参与
|
||||
- 日期分组:`DATE(CONVERT_TZ(字段, Sequelize 时区, 服务器本地时区))`,避免数据库 UTC 存储导致自然日偏移 8 小时;区间过滤仍由 Sequelize 按连接时区转义 Date 参数
|
||||
- 指标口径(各指标按自身时间字段落入统计日):`order_count`=create_at(排除 cancel);`dispatch_count`=配送表 dispath_time;`shipped_count`/`shipped_items_total`/`shipped_amount`=delivery_time(排除 cancel);`intercepted_count`=intercept_time 且 intercept_status != none;`intercepted_at_warehouse_count`=配送表 dispath_time 且 intercept_status=intercepted_at_warehouse;`cancelled_count`=updated_at 且 status=cancel(取消操作刷新 updated_at)
|
||||
- 入参:`start_date`/`end_date`(兼容 startDate/start_time、endDate/end_time)、`store_id`(兼容 storeId)
|
||||
- 响应:`warehouse_id` / `store_id` / `start_date` / `end_date` / `day_count` / `list`(逐日指标,按日期升序)/ `summary`(区间合计)
|
||||
- 纯函数:app/lib/delivery_order_summary.js(区间解析、日期展开、聚合合并,无 egg 依赖);测试 test/delivery_order_summary.cjs、test/app/service/systemMethods/order/deliveryOrder.summary.test.js
|
||||
- 接口文档:methods/system.json 分组「订单配送模块」(module=order.deliveryOrder),变更记录见 methods/changes/system.json 版本 `2026.10.21-order-delivery-summary`
|
||||
|
||||
## method结束
|
||||
|
||||
## 6. 全量 Service Method 能力清单(自动扫描)
|
||||
@ -579,6 +594,8 @@ rg "class .*Service|module.exports" app/service/qimenMethods
|
||||
- fetchStockInfoMap, buildSimpleNotation, buildNameNotation, validateItems, getTargetStoreIdFromMap, checkCustomCodeUniqueForCreate, checkCustomCodeUniqueForUpdate, list, buildListWhere, create, update, delete, search, searchByIdOrCode, enrichComboList
|
||||
- app/service/systems/delivery_order.js (55)
|
||||
- getStoreSubjectConfigCacheKey, normalizeStoreSubjectConfig, getStoreSubjectConfig, findCodeOption, getOptionName, appendOrderOperationLog, getOrderLogOperator, getOrderLogWarehouseId, flushOrderOperationLogs, findPlatformOptionByCode, getPlatformSnapshotCode, getPlatformSnapshotName, resolvePlatformSnapshot, resolveExpressCodeFromSetting, resolveExpressSettingSnapshot, resolveEnableExternalExpressCode, resolveExpressSnapshot, normalizeNeedOmsWaybill, addOrder, buildOrderStats, isRetryableLockError, isPrimaryKeyDuplicate, formatOrderCreateError, resolveOrderStep, generateItemsHash, calculateCRC32, normalizeOrderFromKey, resolveOperatorName, prepareOrderData, addOrderLines, buildOrderItemSnapshot, safeParseFloat, withPatchedCtxUser, buildAsyncProcessContext, buildExpressAllocateRequest, enqueueAutoWaybillAllocation, buildStorageAllocateRequest, getStoreWarehousePolicyConfig, normalizePolicyFlag, resolveCutoffOrderConfig, isPastCutoffTime, isAllocationWindowClosed, buildAutoGroupingStructure, findAutoGroupingWaveId, appendOrderToWave, countCandidateGroupOrders, createGroupingWave, markWaveAutoGrouping, finishAutoGroupingIfNeeded, runAutoGrouping, runAsyncProcessStep, findAutoExpressExcludedRemark, appendAutoExpressSkipLog, appendNeedOmsWaybillWaitLog, asyncProcessOrderCreated
|
||||
- app/service/systems/deliveryOrderSummary.js (3)
|
||||
- queryDailySummary, queryDailyCount, queryDailyShipped
|
||||
- app/service/systems/entry_order.js (16)
|
||||
- addOrder, getLineCount, received, success, fail, findByOrderCode, findByStatus, getStatsByWarehouse, updateSyncStatus, updateOrderStatus, calculateReceivedQuantities, batchUpdateReceived, getOrderProgress, tryCreateEntryOrder, addItems, reviewEntry
|
||||
- app/service/systems/excel.js (26)
|
||||
|
||||
330
app/lib/delivery_order_summary.js
Normal file
330
app/lib/delivery_order_summary.js
Normal file
@ -0,0 +1,330 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 配送订单每日汇总纯函数工具(无 egg / DB 依赖,可单测)。
|
||||
*
|
||||
* 口径约定:
|
||||
* 1. 日期维度为本地时区自然日(yyyy-MM-dd),区间左闭右开 [start, end+1day);
|
||||
* 2. 缺省统计区间为「结束日往前 7 个自然日」(含结束日);
|
||||
* 3. 单次最多 {@link MAX_DAY_COUNT} 天,避免跨过订单归档边界(history 分表不参与统计);
|
||||
* 4. 每日指标缺失时补 0,保证前端按日绘图的连续性。
|
||||
*/
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
|
||||
/** 缺省统计天数(含结束日)。 */
|
||||
const DEFAULT_DAY_COUNT = 7;
|
||||
/** 单次查询最大天数。 */
|
||||
const MAX_DAY_COUNT = 90;
|
||||
|
||||
/** 每日指标字段清单(顺序即响应字段顺序)。 */
|
||||
const METRIC_FIELDS = Object.freeze([
|
||||
'order_count',
|
||||
'dispatch_count',
|
||||
'shipped_count',
|
||||
'shipped_items_total',
|
||||
'shipped_amount',
|
||||
'intercepted_count',
|
||||
'intercepted_at_warehouse_count',
|
||||
'cancelled_count',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 两位补零。
|
||||
* @param {number} value 数值。
|
||||
* @return {string} 补零字符串。
|
||||
*/
|
||||
function pad2(value) {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地时区格式化为 yyyy-MM-dd。
|
||||
* @param {Date} date 日期对象。
|
||||
* @return {string} 格式化结果。
|
||||
*/
|
||||
function formatDate(date) {
|
||||
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造日期偏移(按本地年月日加减,规避夏令时步进偏差)。
|
||||
* @param {Date} date 基准日期。
|
||||
* @param {number} days 偏移天数(可为负)。
|
||||
* @return {Date} 偏移后的日期(00:00:00.000)。
|
||||
*/
|
||||
function addDays(date, days) {
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算两个日期相差的自然日数量(按 UTC 年月日归一化,忽略时分秒)。
|
||||
* @param {Date} start 开始日期。
|
||||
* @param {Date} end 结束日期。
|
||||
* @return {number} 相差天数(end - start)。
|
||||
*/
|
||||
function diffDays(start, end) {
|
||||
const startDay = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate()) / DAY_MS;
|
||||
const endDay = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate()) / DAY_MS;
|
||||
return endDay - startDay;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 yyyy-MM-dd(兼容 yyyy-MM-dd HH:mm:ss 等带时间后缀的入参)。
|
||||
* @param {*} value 待解析值(字符串 / Date)。
|
||||
* @return {Date|null} 本地时区 00:00:00.000 的日期;无法解析时返回 null。
|
||||
*/
|
||||
function parseDateOnly(value) {
|
||||
if (value instanceof Date) {
|
||||
return Number.isNaN(value.getTime())
|
||||
? null
|
||||
: new Date(value.getFullYear(), value.getMonth(), value.getDate());
|
||||
}
|
||||
|
||||
const text = String(value === null || value === undefined ? '' : value).trim();
|
||||
if (!text) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const matched = DATE_PATTERN.exec(text.slice(0, 10));
|
||||
if (!matched) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const year = Number(matched[1]);
|
||||
const month = Number(matched[2]);
|
||||
const day = Number(matched[3]);
|
||||
const candidate = new Date(year, month - 1, day);
|
||||
if (
|
||||
candidate.getFullYear() !== year
|
||||
|| candidate.getMonth() !== month - 1
|
||||
|| candidate.getDate() !== day
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造统计区间非法错误。
|
||||
* @param {string} message 错误文案。
|
||||
* @return {Error} 带 INVALID_SUMMARY_RANGE 错误码的异常。
|
||||
*/
|
||||
function buildRangeError(message) {
|
||||
const error = new Error(message);
|
||||
error.code = 'INVALID_SUMMARY_RANGE';
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析并校验统计区间。
|
||||
*
|
||||
* 规则:
|
||||
* - 仅传 endDate:startDate = endDate - (DEFAULT_DAY_COUNT - 1) 天;
|
||||
* - 仅传 startDate:endDate = 今天;
|
||||
* - 都不传:最近 DEFAULT_DAY_COUNT 个自然日(含今天);
|
||||
* - startDate 晚于 endDate、区间超过 MAX_DAY_COUNT 天、格式非法均抛错。
|
||||
*
|
||||
* @param {Object} [options={}] 入参。
|
||||
* @param {*} [options.startDate] 开始日期(yyyy-MM-dd)。
|
||||
* @param {*} [options.endDate] 结束日期(yyyy-MM-dd)。
|
||||
* @param {Date} [options.now=new Date()] 当前时间(便于单测注入)。
|
||||
* @return {{start: Date, end: Date, endExclusive: Date, startDate: string, endDate: string, dayCount: number}} 区间信息。
|
||||
*/
|
||||
function resolveSummaryRange({ startDate = null, endDate = null, now = new Date() } = {}) {
|
||||
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
|
||||
const hasStart = String(startDate === null || startDate === undefined ? '' : startDate).trim() !== '';
|
||||
const hasEnd = String(endDate === null || endDate === undefined ? '' : endDate).trim() !== '';
|
||||
const parsedStart = parseDateOnly(startDate);
|
||||
const parsedEnd = parseDateOnly(endDate);
|
||||
|
||||
if (hasStart && !parsedStart) {
|
||||
throw buildRangeError('开始日期格式不正确,应为 yyyy-MM-dd');
|
||||
}
|
||||
if (hasEnd && !parsedEnd) {
|
||||
throw buildRangeError('结束日期格式不正确,应为 yyyy-MM-dd');
|
||||
}
|
||||
|
||||
const end = parsedEnd || todayStart;
|
||||
const start = parsedStart || addDays(end, -(DEFAULT_DAY_COUNT - 1));
|
||||
|
||||
if (start.getTime() > end.getTime()) {
|
||||
throw buildRangeError('开始日期不能晚于结束日期');
|
||||
}
|
||||
|
||||
const dayCount = diffDays(start, end) + 1;
|
||||
if (dayCount > MAX_DAY_COUNT) {
|
||||
throw buildRangeError(`汇总天数不能超过 ${MAX_DAY_COUNT} 天`);
|
||||
}
|
||||
|
||||
return {
|
||||
start,
|
||||
end,
|
||||
endExclusive: addDays(end, 1),
|
||||
startDate: formatDate(start),
|
||||
endDate: formatDate(end),
|
||||
dayCount,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成区间内逐日日期键(含首尾)。
|
||||
* @param {Date} start 开始日期。
|
||||
* @param {Date} end 结束日期(含)。
|
||||
* @return {Array<string>} yyyy-MM-dd 列表。
|
||||
*/
|
||||
function buildDateKeys(start, end) {
|
||||
const total = diffDays(start, end) + 1;
|
||||
const keys = [];
|
||||
for (let index = 0; index < total; index += 1) {
|
||||
keys.push(formatDate(addDays(start, index)));
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建全零的每日指标对象。
|
||||
* @return {Object} 指标对象。
|
||||
*/
|
||||
function createEmptyMetrics() {
|
||||
const metrics = {};
|
||||
for (const field of METRIC_FIELDS) {
|
||||
metrics[field] = 0;
|
||||
}
|
||||
return metrics;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按日期键初始化每日指标映射。
|
||||
* @param {Array<string>} dateKeys 日期键列表。
|
||||
* @return {Map<string, Object>} 日期键到指标对象的映射。
|
||||
*/
|
||||
function buildDailyMap(dateKeys) {
|
||||
const dailyMap = new Map();
|
||||
for (const key of dateKeys) {
|
||||
dailyMap.set(key, createEmptyMetrics());
|
||||
}
|
||||
return dailyMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化聚合行返回的日期值(MySQL DATE() 可能返回字符串或 Date 实例)。
|
||||
* @param {*} value 原始日期值。
|
||||
* @return {string} yyyy-MM-dd;无法识别时返回空串。
|
||||
*/
|
||||
function normalizeRowDate(value) {
|
||||
if (value instanceof Date) {
|
||||
return Number.isNaN(value.getTime()) ? '' : formatDate(value);
|
||||
}
|
||||
const text = String(value === null || value === undefined ? '' : value).trim();
|
||||
return text.slice(0, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* 数值安全转换。
|
||||
* @param {*} value 原始值。
|
||||
* @return {number} 数值;非法值按 0 处理。
|
||||
*/
|
||||
function toNumber(value) {
|
||||
const num = Number(value);
|
||||
return Number.isFinite(num) ? num : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 金额保留两位小数。
|
||||
* @param {*} value 原始值。
|
||||
* @return {number} 保留两位小数的金额。
|
||||
*/
|
||||
function roundAmount(value) {
|
||||
return Math.round(toNumber(value) * 100) / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并按日计数的聚合行到每日映射(区间外日期忽略)。
|
||||
* @param {Map<string, Object>} dailyMap 每日映射。
|
||||
* @param {Array<Object>} rows 聚合行(date / count)。
|
||||
* @param {string} field 目标指标字段。
|
||||
* @return {Map<string, Object>} 同一映射。
|
||||
*/
|
||||
function addCountRows(dailyMap, rows, field) {
|
||||
const list = Array.isArray(rows) ? rows : [];
|
||||
for (const row of list) {
|
||||
const target = dailyMap.get(normalizeRowDate(row && row.date));
|
||||
if (target) {
|
||||
target[field] += toNumber(row.count);
|
||||
}
|
||||
}
|
||||
return dailyMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并发货聚合行(订单数 / 商品件数 / 金额)到每日映射。
|
||||
* @param {Map<string, Object>} dailyMap 每日映射。
|
||||
* @param {Array<Object>} rows 聚合行(date / count / items_total / amount)。
|
||||
* @return {Map<string, Object>} 同一映射。
|
||||
*/
|
||||
function addShippedRows(dailyMap, rows) {
|
||||
const list = Array.isArray(rows) ? rows : [];
|
||||
for (const row of list) {
|
||||
const target = dailyMap.get(normalizeRowDate(row && row.date));
|
||||
if (!target) {
|
||||
continue;
|
||||
}
|
||||
target.shipped_count += toNumber(row.count);
|
||||
target.shipped_items_total += toNumber(row.items_total);
|
||||
target.shipped_amount += toNumber(row.amount);
|
||||
}
|
||||
return dailyMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按日期顺序输出每日行,金额统一保留两位小数。
|
||||
* @param {Array<string>} dateKeys 日期键列表。
|
||||
* @param {Map<string, Object>} dailyMap 每日映射。
|
||||
* @return {Array<Object>} 每日汇总行。
|
||||
*/
|
||||
function finalizeDailyRows(dateKeys, dailyMap) {
|
||||
return dateKeys.map(date => {
|
||||
const metrics = dailyMap.get(date) || createEmptyMetrics();
|
||||
return {
|
||||
date,
|
||||
...metrics,
|
||||
shipped_amount: roundAmount(metrics.shipped_amount),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 汇总每日行,输出区间合计。
|
||||
* @param {Array<Object>} rows 每日汇总行。
|
||||
* @return {Object} 合计指标。
|
||||
*/
|
||||
function summarizeRows(rows) {
|
||||
const summary = createEmptyMetrics();
|
||||
for (const row of (Array.isArray(rows) ? rows : [])) {
|
||||
for (const field of METRIC_FIELDS) {
|
||||
summary[field] += toNumber(row && row[field]);
|
||||
}
|
||||
}
|
||||
summary.shipped_amount = roundAmount(summary.shipped_amount);
|
||||
return summary;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_DAY_COUNT,
|
||||
MAX_DAY_COUNT,
|
||||
METRIC_FIELDS,
|
||||
formatDate,
|
||||
addDays,
|
||||
parseDateOnly,
|
||||
resolveSummaryRange,
|
||||
buildDateKeys,
|
||||
createEmptyMetrics,
|
||||
buildDailyMap,
|
||||
normalizeRowDate,
|
||||
addCountRows,
|
||||
addShippedRows,
|
||||
finalizeDailyRows,
|
||||
summarizeRows,
|
||||
};
|
||||
@ -44,9 +44,9 @@ class DeliveryOrderService extends OrderBaseService {
|
||||
constructor(ctx) {
|
||||
super(ctx);
|
||||
const _noNeedLogin = '';
|
||||
const _noNeedRight = 'list,deliveryOrder,quickSearch';
|
||||
const _noNeedLog = 'list,quickSearch';
|
||||
const _noNeedAuth = 'list,deliveryOrder,quickSearch';
|
||||
const _noNeedRight = 'list,summary,deliveryOrder,quickSearch';
|
||||
const _noNeedLog = 'list,summary,quickSearch';
|
||||
const _noNeedAuth = 'list,summary,deliveryOrder,quickSearch';
|
||||
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth);
|
||||
}
|
||||
|
||||
@ -59,6 +59,47 @@ class DeliveryOrderService extends OrderBaseService {
|
||||
return await this.listByModule('deliveryOrder', data);
|
||||
}
|
||||
|
||||
/**
|
||||
* 配送订单每日汇总(以日期为维度统计订单量/发货量/拦截量等)。
|
||||
*
|
||||
* 仓库维度取自登录上下文(ctx.user.store_id),禁止前端传 warehouse_id;
|
||||
* 可选 store_id 按货主过滤。缺省统计最近 7 个自然日(含今天),
|
||||
* 单次最多 90 天。
|
||||
*
|
||||
* @param {Object} data 请求体。
|
||||
* @param {string} [data.start_date] 开始日期(yyyy-MM-dd,兼容 startDate/start_time)。
|
||||
* @param {string} [data.end_date] 结束日期(yyyy-MM-dd,兼容 endDate/end_time)。
|
||||
* @param {number} [data.store_id] 货主ID(可选,兼容 storeId)。
|
||||
* @return {Promise<Object>} 每日汇总列表与区间合计。
|
||||
*/
|
||||
async summary(data = {}) {
|
||||
const warehouseId = Number(this.getWarehouseId() || 0);
|
||||
if (warehouseId <= 0) {
|
||||
return this.fail('缺少仓库上下文');
|
||||
}
|
||||
|
||||
const requestData = this.isPlainObject(data) ? data : {};
|
||||
const storeId = Number(requestData.store_id ?? requestData.storeId ?? 0) || 0;
|
||||
|
||||
try {
|
||||
const result = await this.service.systems.deliveryOrderSummary.queryDailySummary({
|
||||
warehouseId,
|
||||
storeId: storeId > 0 ? storeId : null,
|
||||
startDate: requestData.start_date ?? requestData.startDate ?? requestData.start_time,
|
||||
endDate: requestData.end_date ?? requestData.endDate ?? requestData.end_time,
|
||||
});
|
||||
return this.success('ok', result);
|
||||
} catch (error) {
|
||||
if (error && error.code === 'INVALID_SUMMARY_RANGE') {
|
||||
return this.fail(error.message);
|
||||
}
|
||||
this.ctx.logger.error(
|
||||
`[order.deliveryOrder.summary] ${error && error.message ? error.message : error}`
|
||||
);
|
||||
return this.fail('配送订单汇总查询失败');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询配送订单详情。
|
||||
*
|
||||
|
||||
253
app/service/systems/deliveryOrderSummary.js
Normal file
253
app/service/systems/deliveryOrderSummary.js
Normal file
@ -0,0 +1,253 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const {
|
||||
resolveSummaryRange,
|
||||
buildDateKeys,
|
||||
buildDailyMap,
|
||||
addCountRows,
|
||||
addShippedRows,
|
||||
finalizeDailyRows,
|
||||
summarizeRows,
|
||||
} = require('../../lib/delivery_order_summary');
|
||||
|
||||
/** 不参与发货/订单量统计的订单状态。 */
|
||||
const CANCELLED_ORDER_STATUS = 'cancel';
|
||||
/** 库内确定拦截状态(与 report/queries/interceptOrder 口径一致)。 */
|
||||
const INTERCEPTED_AT_WAREHOUSE_STATUS = 'intercepted_at_warehouse';
|
||||
/** 未进入拦截流程的拦截状态。 */
|
||||
const INTERCEPT_STATUS_NONE = 'none';
|
||||
|
||||
/**
|
||||
* 系统层:配送订单每日汇总。
|
||||
*
|
||||
* 数据源为订单常用表与配送表(订单出库后迁移到配送表,迁移时删除源行,两表无重叠,
|
||||
* 直接相加不会重复计数);归档表 history / 委托外仓表 outsourced 不参与统计。
|
||||
*
|
||||
* 每日指标口径(各指标按自身时间字段落入统计日):
|
||||
* - order_count:当日创建订单数(create_at,排除取消单);
|
||||
* - dispatch_count:当日迁入配送表的订单数(配送表 dispath_time);
|
||||
* - shipped_count:当日发货订单数(delivery_time,排除取消单);
|
||||
* - shipped_items_total:当日发货商品件数(发货订单 items_total 合计);
|
||||
* - shipped_amount:当日发货订单金额(发货订单 total_amount 合计,两位小数);
|
||||
* - intercepted_count:当日拦截订单数(intercept_status != 'none' 且 intercept_time 落入当日);
|
||||
* - intercepted_at_warehouse_count:当日库内确定拦截订单数(配送表 dispath_time 落入当日,
|
||||
* intercept_status = 'intercepted_at_warehouse');
|
||||
* - cancelled_count:当日取消订单数(status = 'cancel' 且 updated_at 落入当日,取消操作会刷新 updated_at)。
|
||||
*/
|
||||
class DeliveryOrderSummaryService extends Service {
|
||||
/**
|
||||
* 查询配送订单每日汇总。
|
||||
*
|
||||
* @param {Object} options 查询参数。
|
||||
* @param {number} options.warehouseId 仓库ID(必填)。
|
||||
* @param {number|null} [options.storeId] 货主ID(可选,>0 时按货主过滤)。
|
||||
* @param {*} [options.startDate] 开始日期(yyyy-MM-dd,缺省为结束日往前 6 天)。
|
||||
* @param {*} [options.endDate] 结束日期(yyyy-MM-dd,缺省为今天)。
|
||||
* @return {Promise<Object>} { warehouse_id, store_id, start_date, end_date, day_count, list, summary }
|
||||
*/
|
||||
async queryDailySummary({ warehouseId, storeId = null, startDate = null, endDate = null } = {}) {
|
||||
const normalizedWarehouseId = Number(warehouseId) || 0;
|
||||
if (normalizedWarehouseId <= 0) {
|
||||
const error = new Error('配送订单汇总缺少仓库上下文');
|
||||
error.code = 'INVALID_SUMMARY_REQUEST';
|
||||
throw error;
|
||||
}
|
||||
|
||||
const range = resolveSummaryRange({ startDate, endDate });
|
||||
const dateKeys = buildDateKeys(range.start, range.end);
|
||||
const dailyMap = buildDailyMap(dateKeys);
|
||||
|
||||
const factory = this.ctx.model && this.ctx.model.OrderDeliveryFactory;
|
||||
if (!factory) {
|
||||
throw new Error('订单配送模型工厂不可用');
|
||||
}
|
||||
|
||||
const [ currentModel, dispatchModel ] = await Promise.all([
|
||||
factory.getCurrentModel(normalizedWarehouseId),
|
||||
factory.getDispatchModel(normalizedWarehouseId),
|
||||
]);
|
||||
|
||||
const { Op } = this.app.Sequelize;
|
||||
const normalizedStoreId = Number(storeId) || 0;
|
||||
const storeScope = normalizedStoreId > 0 ? { store_id: normalizedStoreId } : {};
|
||||
const notCancelled = { [Op.ne]: CANCELLED_ORDER_STATUS };
|
||||
const timeWindow = () => ({ [Op.gte]: range.start, [Op.lt]: range.endExclusive });
|
||||
|
||||
const [
|
||||
currentCreatedRows,
|
||||
dispatchCreatedRows,
|
||||
currentShippedRows,
|
||||
dispatchShippedRows,
|
||||
currentInterceptedRows,
|
||||
dispatchInterceptedRows,
|
||||
dispatchConfirmedRows,
|
||||
dispatchMigratedRows,
|
||||
currentCancelledRows,
|
||||
dispatchCancelledRows,
|
||||
] = await Promise.all([
|
||||
this.queryDailyCount(currentModel, 'create_at', {
|
||||
...storeScope,
|
||||
status: notCancelled,
|
||||
create_at: timeWindow(),
|
||||
}),
|
||||
this.queryDailyCount(dispatchModel, 'create_at', {
|
||||
...storeScope,
|
||||
status: notCancelled,
|
||||
create_at: timeWindow(),
|
||||
}),
|
||||
this.queryDailyShipped(currentModel, {
|
||||
...storeScope,
|
||||
status: notCancelled,
|
||||
delivery_time: timeWindow(),
|
||||
}),
|
||||
this.queryDailyShipped(dispatchModel, {
|
||||
...storeScope,
|
||||
status: notCancelled,
|
||||
delivery_time: timeWindow(),
|
||||
}),
|
||||
this.queryDailyCount(currentModel, 'intercept_time', {
|
||||
...storeScope,
|
||||
intercept_status: { [Op.ne]: INTERCEPT_STATUS_NONE },
|
||||
intercept_time: timeWindow(),
|
||||
}),
|
||||
this.queryDailyCount(dispatchModel, 'intercept_time', {
|
||||
...storeScope,
|
||||
intercept_status: { [Op.ne]: INTERCEPT_STATUS_NONE },
|
||||
intercept_time: timeWindow(),
|
||||
}),
|
||||
this.queryDailyCount(dispatchModel, 'dispath_time', {
|
||||
...storeScope,
|
||||
intercept_status: INTERCEPTED_AT_WAREHOUSE_STATUS,
|
||||
dispath_time: timeWindow(),
|
||||
}),
|
||||
this.queryDailyCount(dispatchModel, 'dispath_time', {
|
||||
...storeScope,
|
||||
dispath_time: timeWindow(),
|
||||
}),
|
||||
this.queryDailyCount(currentModel, 'updated_at', {
|
||||
...storeScope,
|
||||
status: CANCELLED_ORDER_STATUS,
|
||||
updated_at: timeWindow(),
|
||||
}),
|
||||
this.queryDailyCount(dispatchModel, 'updated_at', {
|
||||
...storeScope,
|
||||
status: CANCELLED_ORDER_STATUS,
|
||||
updated_at: timeWindow(),
|
||||
}),
|
||||
]);
|
||||
|
||||
addCountRows(dailyMap, currentCreatedRows, 'order_count');
|
||||
addCountRows(dailyMap, dispatchCreatedRows, 'order_count');
|
||||
addCountRows(dailyMap, dispatchMigratedRows, 'dispatch_count');
|
||||
addCountRows(dailyMap, dispatchConfirmedRows, 'intercepted_at_warehouse_count');
|
||||
addShippedRows(dailyMap, currentShippedRows);
|
||||
addShippedRows(dailyMap, dispatchShippedRows);
|
||||
addCountRows(dailyMap, currentInterceptedRows, 'intercepted_count');
|
||||
addCountRows(dailyMap, dispatchInterceptedRows, 'intercepted_count');
|
||||
addCountRows(dailyMap, currentCancelledRows, 'cancelled_count');
|
||||
addCountRows(dailyMap, dispatchCancelledRows, 'cancelled_count');
|
||||
|
||||
const list = finalizeDailyRows(dateKeys, dailyMap);
|
||||
|
||||
return {
|
||||
warehouse_id: normalizedWarehouseId,
|
||||
store_id: normalizedStoreId > 0 ? normalizedStoreId : null,
|
||||
start_date: range.startDate,
|
||||
end_date: range.endDate,
|
||||
day_count: range.dayCount,
|
||||
list,
|
||||
summary: summarizeRows(list),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 按日期分组计数。
|
||||
*
|
||||
* 分组日期按「数据库时区 → 服务器本地时区」换算后再取 DATE,
|
||||
* 与 JS 侧 new Date(y, m, d) 构造的自然日边界保持一致。
|
||||
*
|
||||
* @param {Object} model 订单分表模型。
|
||||
* @param {string} dateField 时间字段。
|
||||
* @param {Object} where 查询条件。
|
||||
* @return {Promise<Array<Object>>} 聚合行(date / count)。
|
||||
*/
|
||||
async queryDailyCount(model, dateField, where) {
|
||||
const { fn, col } = this.app.Sequelize;
|
||||
const dateColumn = this.buildLocalDateColumn(dateField);
|
||||
|
||||
return await model.findAll({
|
||||
attributes: [
|
||||
[ dateColumn, 'date' ],
|
||||
[ fn('COUNT', col('id')), 'count' ],
|
||||
],
|
||||
where,
|
||||
group: [ dateColumn ],
|
||||
raw: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 按发货日期分组统计发货订单数、商品件数与订单金额。
|
||||
*
|
||||
* @param {Object} model 订单分表模型。
|
||||
* @param {Object} where 查询条件。
|
||||
* @return {Promise<Array<Object>>} 聚合行(date / count / items_total / amount)。
|
||||
*/
|
||||
async queryDailyShipped(model, where) {
|
||||
const { fn, col } = this.app.Sequelize;
|
||||
const dateColumn = this.buildLocalDateColumn('delivery_time');
|
||||
|
||||
return await model.findAll({
|
||||
attributes: [
|
||||
[ dateColumn, 'date' ],
|
||||
[ fn('COUNT', col('id')), 'count' ],
|
||||
[ fn('SUM', col('items_total')), 'items_total' ],
|
||||
[ fn('SUM', col('total_amount')), 'amount' ],
|
||||
],
|
||||
where,
|
||||
group: [ dateColumn ],
|
||||
raw: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造按服务器本地自然日归一化的日期表达式。
|
||||
*
|
||||
* @param {string} dateField 时间字段。
|
||||
* @return {Object} Sequelize 表达式 DATE(CONVERT_TZ(field, dbTz, localTz))。
|
||||
*/
|
||||
buildLocalDateColumn(dateField) {
|
||||
const { fn, col } = this.app.Sequelize;
|
||||
return fn(
|
||||
'DATE',
|
||||
fn('CONVERT_TZ', col(dateField), this.resolveDbTimezone(), this.resolveLocalTimezone())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库连接时区(Sequelize options.timezone,缺省 +00:00)。
|
||||
*
|
||||
* @return {string} 形如 +00:00 / +08:00。
|
||||
*/
|
||||
resolveDbTimezone() {
|
||||
const sequelize = this.ctx.model && this.ctx.model.options ? this.ctx.model : null;
|
||||
return (sequelize && sequelize.options && sequelize.options.timezone) || '+00:00';
|
||||
}
|
||||
|
||||
/**
|
||||
* 服务器本地时区偏移(形如 +08:00)。
|
||||
*
|
||||
* @return {string} 时区偏移。
|
||||
*/
|
||||
resolveLocalTimezone() {
|
||||
const offsetMinutes = -new Date().getTimezoneOffset();
|
||||
const sign = offsetMinutes < 0 ? '-' : '+';
|
||||
const absMinutes = Math.abs(offsetMinutes);
|
||||
const hours = String(Math.floor(absMinutes / 60)).padStart(2, '0');
|
||||
const minutes = String(absMinutes % 60).padStart(2, '0');
|
||||
return `${sign}${hours}:${minutes}`;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DeliveryOrderSummaryService;
|
||||
@ -1,4 +1,21 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.10.21-order-delivery-summary",
|
||||
"date": "2026-10-21",
|
||||
"type": "added",
|
||||
"summary": "新增 order.deliveryOrder.summary(配送订单每日汇总):以自然日为维度统计每日订单量、迁入配送表订单量、发货量(订单数/商品件数/金额)、拦截数量、库内确定拦截数量与取消数量,默认最近 7 天、最多 90 天,缺失日期补 0;仓库取自登录上下文,可选 store_id 过滤。",
|
||||
"methods": [
|
||||
"order.deliveryOrder.summary"
|
||||
],
|
||||
"notes": [
|
||||
"方法层:app/service/systemMethods/order/deliveryOrder.js 新增 summary(data),加入 _noNeedRight/_noNeedLog/_noNeedAuth(只读接口,与 list/quickSearch 同口径),统一 this.success('ok', result) 包装;参数兼容 start_date/startDate/start_time、end_date/endDate/end_time、store_id/storeId",
|
||||
"系统层:新增 app/service/systems/deliveryOrderSummary.js(queryDailySummary/queryDailyCount/queryDailyShipped),同时查订单常用表与配送表分表(getCurrentModel + getDispatchModel),归档 history 与委托外仓 outsourced 不参与;日期分组用 CONVERT_TZ(字段, Sequelize 时区, 服务器本地时区) 后取 DATE,保证自然日与本地时区一致",
|
||||
"纯函数:新增 app/lib/delivery_order_summary.js(区间解析/日期展开/聚合合并,无 egg 依赖),单次区间上限 90 天,缺省 7 天",
|
||||
"指标口径:order_count=create_at(排除 cancel);dispatch_count=配送表 dispath_time;shipped_count/shipped_items_total/shipped_amount=delivery_time(排除 cancel);intercepted_count=intercept_time 且 intercept_status != none;intercepted_at_warehouse_count=配送表 dispath_time 且 intercept_status=intercepted_at_warehouse(与 report interceptOrder 口径一致);cancelled_count=updated_at 且 status=cancel(取消操作会刷新 updated_at)",
|
||||
"测试:test/app/service/systemMethods/order/deliveryOrder.summary.test.js(聚合与参数映射 6 例)、test/delivery_order_summary.cjs(区间与合并纯函数 10 例)",
|
||||
"文档变更范围:methods/system.json 的 order.deliveryOrder.summary 一条(新增)+根版本 0.3.302 → 0.3.303、updatedAt 2026-10-21;methods/changes/system.json 新增本条(插入数组首位)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "2026.10.17-returnUnpack.transferByOrders",
|
||||
"date": "2026-10-17",
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
{
|
||||
"module": "system",
|
||||
"description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内",
|
||||
"version": "0.3.302",
|
||||
"updatedAt": "2026-10-17",
|
||||
"version": "0.3.303",
|
||||
"updatedAt": "2026-10-21",
|
||||
"headers": [
|
||||
{
|
||||
"name": "platform",
|
||||
@ -12801,6 +12801,194 @@
|
||||
"message": "搜索失败"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"method": "order.deliveryOrder.summary",
|
||||
"description": "配送订单每日汇总:以自然日(yyyy-MM-dd)为维度统计每日订单量、当日迁入配送表订单量、发货量(订单数/商品件数/发货金额)、拦截数量、库内确定拦截数量与取消数量;仓库取自登录上下文,可选 store_id 按货主过滤;默认最近 7 个自然日(含今天),单次最多 90 天,区间内无数据的日期补 0。数据源为订单常用表与配送表(订单出库迁移进配送表时删除源行,两表无重叠,直接相加不重复计数),不含归档表 history 与委托外仓表 outsourced。各指标按自身时间字段落入统计日:order_count=create_at(排除取消单)、dispatch_count=配送表 dispath_time、shipped_*=delivery_time(排除取消单)、intercepted_count=intercept_time(intercept_status != none)、intercepted_at_warehouse_count=配送表 dispath_time(intercept_status=intercepted_at_warehouse)、cancelled_count=updated_at(status=cancel)。",
|
||||
"isNeedAuth": false,
|
||||
"isNeedLogin": true,
|
||||
"headers": [
|
||||
{
|
||||
"name": "Authorization",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "******"
|
||||
}
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "start_date",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "开始日期(yyyy-MM-dd,兼容 startDate / start_time;缺省为结束日往前 6 天)"
|
||||
},
|
||||
{
|
||||
"name": "end_date",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "结束日期(yyyy-MM-dd,兼容 endDate / end_time;缺省为今天)"
|
||||
},
|
||||
{
|
||||
"name": "store_id",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "货主ID过滤(兼容 storeId;不传或 <=0 表示不按货主过滤)"
|
||||
}
|
||||
],
|
||||
"response": [
|
||||
{
|
||||
"name": "warehouse_id",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "仓库ID(取自登录上下文 ctx.user.store_id)"
|
||||
},
|
||||
{
|
||||
"name": "store_id",
|
||||
"type": "number",
|
||||
"required": false,
|
||||
"description": "货主ID过滤值;未按货主过滤时为 null"
|
||||
},
|
||||
{
|
||||
"name": "start_date",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "实际统计开始日期(yyyy-MM-dd)"
|
||||
},
|
||||
{
|
||||
"name": "end_date",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"description": "实际统计结束日期(yyyy-MM-dd,含当天)"
|
||||
},
|
||||
{
|
||||
"name": "day_count",
|
||||
"type": "number",
|
||||
"required": true,
|
||||
"description": "统计天数(含首尾自然日)"
|
||||
},
|
||||
{
|
||||
"name": "list",
|
||||
"type": "array",
|
||||
"required": true,
|
||||
"description": "逐日汇总数组,按日期升序,区间内无数据的日期补 0;每项字段见 children",
|
||||
"children": [
|
||||
{
|
||||
"name": "date",
|
||||
"type": "string",
|
||||
"description": "统计日期(yyyy-MM-dd)"
|
||||
},
|
||||
{
|
||||
"name": "order_count",
|
||||
"type": "number",
|
||||
"description": "当日创建订单数(create_at 落在当日,排除取消单)"
|
||||
},
|
||||
{
|
||||
"name": "dispatch_count",
|
||||
"type": "number",
|
||||
"description": "当日迁入配送表的订单数(配送表 dispath_time 落在当日)"
|
||||
},
|
||||
{
|
||||
"name": "shipped_count",
|
||||
"type": "number",
|
||||
"description": "当日发货订单数(delivery_time 落在当日,排除取消单)"
|
||||
},
|
||||
{
|
||||
"name": "shipped_items_total",
|
||||
"type": "number",
|
||||
"description": "当日发货商品件数(发货订单 items_total 合计)"
|
||||
},
|
||||
{
|
||||
"name": "shipped_amount",
|
||||
"type": "number",
|
||||
"description": "当日发货订单金额(发货订单 total_amount 合计,两位小数)"
|
||||
},
|
||||
{
|
||||
"name": "intercepted_count",
|
||||
"type": "number",
|
||||
"description": "当日拦截订单数(intercept_status != none 且 intercept_time 落在当日)"
|
||||
},
|
||||
{
|
||||
"name": "intercepted_at_warehouse_count",
|
||||
"type": "number",
|
||||
"description": "当日库内确定拦截订单数(配送表 dispath_time 落在当日,intercept_status=intercepted_at_warehouse)"
|
||||
},
|
||||
{
|
||||
"name": "cancelled_count",
|
||||
"type": "number",
|
||||
"description": "当日取消订单数(status=cancel 且 updated_at 落在当日)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "summary",
|
||||
"type": "object",
|
||||
"required": true,
|
||||
"description": "区间合计(各字段口径同 list 中对应字段之和)",
|
||||
"children": [
|
||||
{
|
||||
"name": "order_count",
|
||||
"type": "number",
|
||||
"description": "区间创建订单数合计"
|
||||
},
|
||||
{
|
||||
"name": "dispatch_count",
|
||||
"type": "number",
|
||||
"description": "区间迁入配送表订单数合计"
|
||||
},
|
||||
{
|
||||
"name": "shipped_count",
|
||||
"type": "number",
|
||||
"description": "区间发货订单数合计"
|
||||
},
|
||||
{
|
||||
"name": "shipped_items_total",
|
||||
"type": "number",
|
||||
"description": "区间发货商品件数合计"
|
||||
},
|
||||
{
|
||||
"name": "shipped_amount",
|
||||
"type": "number",
|
||||
"description": "区间发货金额合计(两位小数)"
|
||||
},
|
||||
{
|
||||
"name": "intercepted_count",
|
||||
"type": "number",
|
||||
"description": "区间拦截订单数合计"
|
||||
},
|
||||
{
|
||||
"name": "intercepted_at_warehouse_count",
|
||||
"type": "number",
|
||||
"description": "区间库内确定拦截订单数合计"
|
||||
},
|
||||
{
|
||||
"name": "cancelled_count",
|
||||
"type": "number",
|
||||
"description": "区间取消订单数合计"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"errors": [
|
||||
{
|
||||
"code": "0",
|
||||
"message": "缺少仓库上下文(当前用户未绑定仓库),返回 flag=failure"
|
||||
},
|
||||
{
|
||||
"code": "0",
|
||||
"message": "日期参数不合法(开始/结束日期格式应为 yyyy-MM-dd、开始日期不能晚于结束日期、汇总天数不能超过 90 天),返回 flag=failure"
|
||||
},
|
||||
{
|
||||
"code": "401",
|
||||
"message": "未登录或 token 无效"
|
||||
},
|
||||
{
|
||||
"code": "500",
|
||||
"message": "配送订单汇总查询失败(数据库异常,详情见服务端日志)"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user