931 lines
33 KiB
JavaScript
Raw Permalink 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 MainService = require('../main');
class dashboardService extends MainService {
constructor(ctx) {
super(ctx);
const _noNeedLogin = '';
const _noNeedRight = '*';
const _noNeedLog = '*';
this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog);
}
async storeStats() {
const { ctx } = this;
const storeType = String(ctx.user?.store_type || '').trim();
if (storeType === 'store') {
return await this.storeSideStoreStats();
}
// 仓库端:单仓查询
const warehouseId = Number(ctx.user?.store_id);
if (!warehouseId) {
return this.fail('缺少仓库上下文');
}
const stats = await this.queryWarehouseStats(warehouseId);
return this.success('ok', this.mergeStoreStats([ stats ]));
}
async storeSideStoreStats() {
const { ctx } = this;
const storeId = Number(ctx.user?.store_id);
if (!storeId) {
return this.fail('缺少货主上下文');
}
// 获取签约仓库
const contracts = await ctx.model.StoreWarehouse.findAll({
where: { store_id: storeId, auth_status: 2 },
attributes: [ 'warehouse_id' ],
raw: true,
});
const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0);
if (!warehouseIds.length) {
return this.success('ok', this.emptyStoreStats());
}
// 跨仓并行查询并汇总
const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseStats(wid, storeId).catch(() => null)));
return this.success('ok', this.mergeStoreStats(results.filter(Boolean)));
}
async queryWarehouseStats(warehouseId, storeId = null) {
const { ctx } = this;
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const { Sequelize } = ctx.app;
const { Op } = Sequelize;
const pendingBase = {
step: { [Op.in]: [ 1, 2, 3 ] },
outbound_status: { [Op.ne]: 'padding' },
status: { [Op.ne]: 'cancel' },
};
if (storeId) {
pendingBase.store_id = storeId;
}
const now = new Date();
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const todayEnd = new Date(todayStart.getTime() + 86400000);
const yesterdayStart = new Date(todayStart.getTime() - 86400000);
const [
totalPending,
todayNew,
yesterdayNew,
unassignedOrders,
unprintedOrders,
unpickedOrders,
pendingShipments,
todayOutbound,
interceptedOrders,
exceptionOrders,
recheckedOrders,
packedOrders,
] = await Promise.all([
model.count({ where: pendingBase }),
model.count({ where: { ...pendingBase, create_at: { [Op.gte]: todayStart, [Op.lt]: todayEnd } } }),
model.count({ where: { ...pendingBase, create_at: { [Op.gte]: yesterdayStart, [Op.lt]: todayStart } } }),
model.count({ where: { ...pendingBase, post_status: 'none' } }),
model.count({ where: { ...pendingBase, print_status: 'none' } }),
model.count({ where: { ...pendingBase, pick_status: 'none' } }),
model.count({ where: { ...pendingBase, outbound_status: { [Op.ne]: 'fin' } } }),
model.count({ where: { step: 4, outbound_status: 'fin', status: { [Op.ne]: 'cancel' }, delivery_time: { [Op.gte]: todayStart, [Op.lt]: todayEnd }, ...(storeId ? { store_id: storeId } : {}) } }),
model.count({ where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } } }),
model.count({ where: { ...pendingBase, step: 3 } }),
model.count({ where: { ...pendingBase, recheck_status: 'fin' } }),
model.count({ where: { ...pendingBase, pack_status: 'fin' } }),
]);
return {
warehouseId,
totalPending,
todayNew,
yesterdayNew,
unassignedOrders,
unprintedOrders,
unpickedOrders,
pendingShipments,
todayOutbound,
interceptedOrders,
exceptionOrders,
recheckedOrders,
packedOrders,
};
}
mergeStoreStats(results) {
const merged = {
totalPending: 0, todayNew: 0, yesterdayNew: 0,
unassignedOrders: 0, unprintedOrders: 0, unpickedOrders: 0,
pendingShipments: 0, todayOutbound: 0, interceptedOrders: 0, exceptionOrders: 0,
recheckedOrders: 0, packedOrders: 0,
};
for (const r of results) {
merged.totalPending += r.totalPending || 0;
merged.todayNew += r.todayNew || 0;
merged.yesterdayNew += r.yesterdayNew || 0;
merged.unassignedOrders += r.unassignedOrders || 0;
merged.unprintedOrders += r.unprintedOrders || 0;
merged.unpickedOrders += r.unpickedOrders || 0;
merged.pendingShipments += r.pendingShipments || 0;
merged.todayOutbound += r.todayOutbound || 0;
merged.interceptedOrders += r.interceptedOrders || 0;
merged.exceptionOrders += r.exceptionOrders || 0;
merged.recheckedOrders += r.recheckedOrders || 0;
merged.packedOrders += r.packedOrders || 0;
}
const orderTrend = merged.yesterdayNew > 0
? parseFloat((((merged.todayNew - merged.yesterdayNew) / merged.yesterdayNew) * 100).toFixed(1))
: (merged.todayNew > 0 ? 100 : 0);
const totalForRate = merged.pendingShipments + merged.todayOutbound;
const outboundRate = totalForRate > 0
? parseFloat(((merged.todayOutbound / totalForRate) * 100).toFixed(2))
: 0;
const shipmentProgress = merged.totalPending > 0
? parseFloat((((merged.totalPending - merged.pendingShipments) / merged.totalPending) * 100).toFixed(0))
: 0;
return {
code: 200,
message: '成功',
data: {
todayOrders: merged.totalPending + merged.todayOutbound,
orderTrend,
unassignedOrders: merged.unassignedOrders,
unprintedOrders: merged.unprintedOrders,
unpickedOrders: merged.unpickedOrders,
pendingShipments: merged.pendingShipments,
shipmentProgress,
todayOutbound: merged.todayOutbound,
outboundRate,
interceptedOrders: merged.interceptedOrders,
exceptionOrders: merged.exceptionOrders,
recheckedOrders: merged.recheckedOrders,
packedOrders: merged.packedOrders,
},
};
}
emptyStoreStats() {
return {
code: 200,
message: '成功',
data: {
todayOrders: 0, orderTrend: 0,
unassignedOrders: 0, unprintedOrders: 0, unpickedOrders: 0,
pendingShipments: 0, shipmentProgress: 0,
todayOutbound: 0, outboundRate: 0,
interceptedOrders: 0, exceptionOrders: 0,
recheckedOrders: 0, packedOrders: 0,
},
};
}
async warehouseStats() {
const data = {
code: 200,
message: '成功',
data: {
todayOrders: 153023, // 今日订单数(基准)
orderTrend: 3, // 较昨日增长3%
// 处理状态(按百分比计算)
unassignedOrders: 3060, // 未分配快递号(占2%)
unprintedOrders: 4591, // 未打印(占3%)
unpickedOrders: 7651, // 未拣货(占5%)
// 发货相关
pendingShipments: 45907, // 待发货(占30%)
shipmentProgress: 70, // 发货进度70%
// 出库相关
todayOutbound: 107116, // 今日出库(占70%)
outboundRate: 70, // 出库完成率70%
// 异常订单(按比例)
interceptedOrders: 306, // 拦截订单(占0.2%)
exceptionOrders: 1530, // 异常订单(占1%)
},
};
return this.success('ok', data);
}
/**
* 热销商品排行:统计仓库端/货主端范围内今日热销商品 Top 10。
*
* 口径说明:
* - 今日窗口为 [今日 00:00, 当前时刻),昨日窗口为 [昨日 00:00, 今日 00:00);
* - value 为窗口内非取消、非异常、未删除订单的商品计划数量(plan_qty)合计;
* - trend 为今日销量相对昨日销量的环比百分比(保留一位小数),昨日为 0 且今日大于 0 时按 100 处理;
* - 已出库订单会从常用表迁移到配送表,因此常用表与配送表均参与统计。
*
* 仓库端使用 ctx.user.store_id 作为仓库ID,单仓统计;
* 货主端(store_type 为 store)跨所有签约仓库并行统计并按商品聚合。
*
* @return {Promise<Object>} 热销商品排行响应,data 为最多 10 条的排行数组。
*/
async hot_order_rank() {
const { ctx } = this;
const storeType = String(ctx.user?.store_type || '').trim();
if (storeType === 'store') {
return await this.storeSideHotOrderRank();
}
const warehouseId = Number(ctx.user?.store_id);
if (!warehouseId) {
return this.fail('缺少仓库上下文');
}
const rankMap = await this.queryWarehouseHotOrderRank(warehouseId);
return this.success('ok', await this.formatHotOrderRank(rankMap));
}
/**
* 货主端热销商品排行:跨所有已签约仓库并行统计并按商品聚合。
*
* @return {Promise<Object>} 热销商品排行响应。
*/
async storeSideHotOrderRank() {
const { ctx } = this;
const storeId = Number(ctx.user?.store_id);
if (!storeId) {
return this.fail('缺少货主上下文');
}
// 获取签约仓库
const contracts = await ctx.model.StoreWarehouse.findAll({
where: { store_id: storeId, auth_status: 2 },
attributes: [ 'warehouse_id' ],
raw: true,
});
const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0);
if (!warehouseIds.length) {
return this.success('ok', this.emptyHotOrderRank());
}
// 跨仓并行查询并汇总
const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseHotOrderRank(wid, storeId).catch(() => null)));
return this.success('ok', await this.formatHotOrderRank(this.mergeHotOrderRank(results.filter(Boolean))));
}
/**
* 查询单个仓库的热销商品聚合结果。
*
* 今日窗口同时覆盖订单常用表与配送表(已出库订单会迁移到配送表);
* 昨日窗口仅统计今日候选商品的销量作为环比基线,避免全量扫描。
*
* @param {number} warehouseId 仓库ID。
* @param {number|null} [storeId=null] 货主ID,货主端传值以限定统计范围。
* @return {Promise<Map<string, Object>>} 商品键到 { name, currentValue, previousValue } 的映射,
* 商品键规则:有编码时为 code:商品编码,无编码时为 stock:库存商品ID。
*/
async queryWarehouseHotOrderRank(warehouseId, storeId = null) {
const now = new Date();
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const yesterdayStart = new Date(todayStart.getTime() - 86400000);
// 今日窗口:常用表与配送表并行聚合
const [ currentRows, dispatchRows ] = await Promise.all([
this.queryHotOrderRankWindowRows(warehouseId, 'current', todayStart, now, storeId),
this.queryHotOrderRankWindowRows(warehouseId, 'dispatch', todayStart, now, storeId),
]);
const currentMap = this.buildHotOrderRankMap(currentRows.concat(dispatchRows));
if (currentMap.size === 0) {
return currentMap;
}
// 昨日窗口:仅统计今日候选商品的销量作为环比基线
const keyFilter = this.buildHotOrderRankKeyFilter(currentMap);
const [ prevCurrentRows, prevDispatchRows ] = await Promise.all([
this.queryHotOrderRankWindowRows(warehouseId, 'current', yesterdayStart, todayStart, storeId, keyFilter),
this.queryHotOrderRankWindowRows(warehouseId, 'dispatch', yesterdayStart, todayStart, storeId, keyFilter),
]);
const rankMap = new Map();
for (const [ key, entry ] of currentMap.entries()) {
rankMap.set(key, { ...entry, previousValue: 0 });
}
const previousMap = this.buildHotOrderRankMap(prevCurrentRows.concat(prevDispatchRows));
for (const [ key, prevEntry ] of previousMap.entries()) {
const target = rankMap.get(key);
if (target) {
target.previousValue = prevEntry.currentValue;
}
}
return rankMap;
}
/**
* 查询单个订单分表在指定时间窗口内的商品销量分组。
*
* @param {number} warehouseId 仓库ID。
* @param {string} tableType 表类型:current(常用表)或 dispatch(配送表)。
* @param {Date} startTime 窗口开始时间(含)。
* @param {Date} endTime 窗口结束时间(不含)。
* @param {number|null} [storeId=null] 货主ID,货主端传值以限定统计范围。
* @param {Object|null} [keyFilter=null] 候选商品键过滤:{ itemCodes, stockIds },为空则统计全部商品。
* @return {Promise<Array<Object>>} 分组行数组 [{ item_code, stock_id, item_name, total_qty }]。
*/
async queryHotOrderRankWindowRows(warehouseId, tableType, startTime, endTime, storeId = null, keyFilter = null) {
const { ctx } = this;
const isDispatch = tableType === 'dispatch';
const orderModel = isDispatch
? await ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId)
: await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const itemsModel = isDispatch
? await ctx.model.OrderItemsFactory.getDispatchModel(warehouseId)
: await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
const orderTableName = orderModel.getTableName();
const itemsTableName = itemsModel.getTableName();
const whereClauses = [
'o.status NOT IN (\'cancel\', \'error\')',
'o.delete_at IS NULL',
'o.create_at >= :startTime',
'o.create_at < :endTime',
];
const replacements = { startTime, endTime };
if (storeId) {
whereClauses.push('o.store_id = :storeId');
replacements.storeId = storeId;
}
if (keyFilter) {
const keyParts = [];
if (Array.isArray(keyFilter.itemCodes) && keyFilter.itemCodes.length > 0) {
keyParts.push('i.item_code IN (:itemCodes)');
replacements.itemCodes = keyFilter.itemCodes;
}
if (Array.isArray(keyFilter.stockIds) && keyFilter.stockIds.length > 0) {
keyParts.push('i.stock_id IN (:stockIds)');
replacements.stockIds = keyFilter.stockIds;
}
if (keyParts.length > 0) {
whereClauses.push(`(${keyParts.join(' OR ')})`);
}
}
const rows = await ctx.model.query(`
SELECT
i.item_code,
i.stock_id,
MAX(i.item_name) AS item_name,
SUM(i.plan_qty) AS total_qty
FROM \`${itemsTableName}\` AS i
INNER JOIN \`${orderTableName}\` AS o ON o.id = i.order_id
WHERE ${whereClauses.join('\n AND ')}
GROUP BY i.item_code, i.stock_id
`, {
replacements,
type: ctx.app.Sequelize.QueryTypes.SELECT,
});
return Array.isArray(rows) ? rows : [];
}
/**
* 将分组行转换为商品键到销量聚合的映射。
*
* 商品键规则:优先使用商品编码(code:商品编码);无编码时使用库存商品ID(stock:库存商品ID);
* 编码与库存ID均缺失或销量不大于 0 的行会被跳过。
*
* @param {Array<Object>} rows 分组行数组 [{ item_code, stock_id, item_name, total_qty }]。
* @return {Map<string, Object>} 商品键到 { name, stockId, currentValue } 的映射,
* stockId 为库存商品ID(stock_warehouse.id)。
*/
buildHotOrderRankMap(rows) {
const rankMap = new Map();
for (const row of Array.isArray(rows) ? rows : []) {
const itemCode = String(row.item_code || '').trim();
const stockId = Number(row.stock_id) || 0;
const totalQty = Number(row.total_qty) || 0;
if (totalQty <= 0) {
continue;
}
const key = itemCode ? `code:${itemCode}` : `stock:${stockId}`;
if (key === 'stock:0') {
continue;
}
const itemName = String(row.item_name || '').trim();
const existing = rankMap.get(key);
if (existing) {
existing.currentValue += totalQty;
if (!existing.name && itemName) {
existing.name = itemName;
}
if (!existing.stockId && stockId > 0) {
existing.stockId = stockId;
}
} else {
rankMap.set(key, { name: itemName, stockId, currentValue: totalQty });
}
}
return rankMap;
}
/**
* 根据商品键映射构造昨日窗口的候选键过滤条件。
*
* @param {Map<string, Object>} rankMap 商品键映射。
* @return {Object} { itemCodes, stockIds } 候选商品编码与库存商品ID数组。
*/
buildHotOrderRankKeyFilter(rankMap) {
const itemCodes = [];
const stockIds = [];
for (const key of rankMap.keys()) {
if (key.startsWith('code:')) {
itemCodes.push(key.slice(5));
} else if (key.startsWith('stock:')) {
const stockId = Number(key.slice(6));
if (stockId > 0) {
stockIds.push(stockId);
}
}
}
return { itemCodes, stockIds };
}
/**
* 合并多个仓库的热销商品聚合映射(货主端跨仓汇总)。
*
* @param {Array<Map<string, Object>>} results 各仓库的聚合映射数组。
* @return {Map<string, Object>} 合并后的商品键到聚合数据(含 stockId)的映射。
*/
mergeHotOrderRank(results) {
const merged = new Map();
for (const rankMap of Array.isArray(results) ? results : []) {
if (!(rankMap instanceof Map)) {
continue;
}
for (const [ key, entry ] of rankMap.entries()) {
const existing = merged.get(key);
if (existing) {
existing.currentValue += entry.currentValue || 0;
existing.previousValue += entry.previousValue || 0;
if (!existing.name && entry.name) {
existing.name = entry.name;
}
if (!existing.stockId && entry.stockId) {
existing.stockId = entry.stockId;
}
} else {
merged.set(key, {
name: entry.name || '',
stockId: entry.stockId || 0,
currentValue: entry.currentValue || 0,
previousValue: entry.previousValue || 0,
});
}
}
}
return merged;
}
/**
* 批量查询库存商品信息,用于补充无编码商品的名称与编码。
*
* @param {Array<number>} stockIds 库存商品ID数组。
* @return {Promise<Map<number, Object>>} 库存商品ID到 { item_code, item_name } 的映射。
*/
async loadHotOrderRankStockInfo(stockIds) {
const { ctx } = this;
const uniqueStockIds = [ ...new Set((Array.isArray(stockIds) ? stockIds : []).filter(id => Number(id) > 0)) ];
if (uniqueStockIds.length === 0) {
return new Map();
}
const { Op } = ctx.app.Sequelize;
const rows = await ctx.model.StockWarehouse.findAll({
where: { id: { [Op.in]: uniqueStockIds }, deleted_at: null },
attributes: [ 'id', 'item_code', 'item_name' ],
raw: true,
});
const stockInfoMap = new Map();
for (const row of Array.isArray(rows) ? rows : []) {
stockInfoMap.set(Number(row.id), {
item_code: String(row.item_code || '').trim(),
item_name: String(row.item_name || '').trim(),
});
}
return stockInfoMap;
}
/**
* 解析商品键对应的商品名称与库存商品ID。
*
* sku 统一取库存商品ID(stock_warehouse.id):库存键(stock:库存商品ID)直接取键内ID,
* 编码键(code:商品编码)取聚合条目携带的 stockId;均缺失时回退商品编码字符串。
* 名称为聚合行携带的商品名,库存键无名称时回退库存主表信息或 商品+库存ID 兜底。
*
* @param {string} key 商品键。
* @param {Object} entry 聚合数据 { name, stockId, currentValue, previousValue }。
* @param {Map<number, Object>} stockInfoMap 库存商品信息映射。
* @return {Object} { name, sku } 商品展示信息(sku 为库存商品ID,缺失时回退商品编码字符串)。
*/
resolveHotOrderRankProduct(key, entry, stockInfoMap) {
const stockId = key.startsWith('stock:')
? Number(key.slice(6))
: (Number(entry && entry.stockId) || 0);
if (stockId > 0) {
const stockInfo = stockInfoMap.get(stockId) || {};
return {
name: entry.name || stockInfo.item_name || `商品${stockId}`,
sku: stockId,
};
}
const itemCode = key.startsWith('code:') ? key.slice(5) : '';
return { name: entry.name || itemCode, sku: itemCode };
}
/**
* 对商品名称做脱敏处理:保留前两个字符与后两个字符,中间以三个星号替代。
* 名称长度不足 4 个字符时无法按规则脱敏,统一返回 ***。
*
* @param {string} name 原始商品名称。
* @return {string} 脱敏后的商品名称。
*/
maskHotOrderRankName(name) {
const value = String(name || '').trim();
if (value.length >= 4) {
return `${value.slice(0, 2)}***${value.slice(-2)}`;
}
return '***';
}
/**
* 将聚合映射格式化为热销商品排行响应数据。
*
* 按今日销量降序取前 10 条;trend 为今日销量相对昨日的环比百分比(保留一位小数),
* 昨日为 0 且今日大于 0 时按 100 处理;name 做脱敏处理(前2字符+***+后2字符,
* 长度不足 4 字符时返回 ***),sku 为库存商品ID(stock_warehouse.id)。
*
* @param {Map<string, Object>} rankMap 商品键到聚合数据的映射。
* @return {Promise<Object>} { code: 200, message: '成功', data: [{ id, name, sku, value, trend }] }。
*/
async formatHotOrderRank(rankMap) {
if (!rankMap || rankMap.size === 0) {
return this.emptyHotOrderRank();
}
const stockIds = [];
for (const key of rankMap.keys()) {
if (key.startsWith('stock:')) {
const stockId = Number(key.slice(6));
if (stockId > 0) {
stockIds.push(stockId);
}
}
}
const stockInfoMap = await this.loadHotOrderRankStockInfo(stockIds);
const sorted = [ ...rankMap.entries() ].sort((left, right) => right[1].currentValue - left[1].currentValue);
return {
code: 200,
message: '成功',
data: sorted.slice(0, 10).map(([ key, entry ], index) => {
const { name, sku } = this.resolveHotOrderRankProduct(key, entry, stockInfoMap);
const previousValue = entry.previousValue || 0;
const trend = previousValue > 0
? parseFloat((((entry.currentValue - previousValue) / previousValue) * 100).toFixed(1))
: (entry.currentValue > 0 ? 100 : 0);
return { id: index + 1, name: this.maskHotOrderRankName(name), sku, value: entry.currentValue, trend };
}),
};
}
/**
* 构造热销商品排行的空响应数据。
*
* @return {Object} { code: 200, message: '成功', data: [] }。
*/
emptyHotOrderRank() {
return { code: 200, message: '成功', data: [] };
}
async express_ratio() {
const { ctx } = this;
const storeType = String(ctx.user?.store_type || '').trim();
if (storeType === 'store') {
return await this.storeSideExpressRatio();
}
const warehouseId = Number(ctx.user?.store_id);
if (!warehouseId) {
return this.fail('缺少仓库上下文');
}
const nameValueMap = await this.queryWarehouseExpressRatio(warehouseId);
return this.success('ok', this.formatChartData(nameValueMap));
}
async storeSideExpressRatio() {
const { ctx } = this;
const storeId = Number(ctx.user?.store_id);
if (!storeId) {
return this.fail('缺少货主上下文');
}
const contracts = await ctx.model.StoreWarehouse.findAll({
where: { store_id: storeId, auth_status: 2 },
attributes: [ 'warehouse_id' ],
raw: true,
});
const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0);
if (!warehouseIds.length) {
return this.success('ok', this.emptyChartData());
}
const results = await Promise.all(warehouseIds.map(wid => this.queryWarehouseExpressRatio(wid).catch(() => null)));
return this.success('ok', this.mergeChartData(results.filter(Boolean)));
}
async queryWarehouseExpressRatio(warehouseId) {
const { ctx } = this;
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const { Sequelize } = ctx.app;
const rows = await model.findAll({
attributes: [
'logistics_name',
[ Sequelize.fn('COUNT', Sequelize.col('id')), 'value' ],
],
where: {
step: { [Sequelize.Op.in]: [ 1, 2, 3 ] },
outbound_status: { [Sequelize.Op.ne]: 'padding' },
status: { [Sequelize.Op.ne]: 'cancel' },
},
group: [ 'logistics_name' ],
order: [[ Sequelize.fn('COUNT', Sequelize.col('id')), 'DESC' ]],
raw: true,
});
const nameValueMap = new Map();
for (const row of rows) {
nameValueMap.set(row.logistics_name || '未指定快递', Number(row.value) || 0);
}
return nameValueMap;
}
mergeChartData(results) {
const merged = new Map();
for (const map of results) {
for (const [ name, value ] of map.entries()) {
merged.set(name, (merged.get(name) || 0) + value);
}
}
return this.formatChartData(merged);
}
formatChartData(nameValueMap) {
if (!nameValueMap || nameValueMap.size === 0) {
return { code: 200, message: '成功', data: [] };
}
const colorPalette = [
'#409EFF', '#67C23A', '#E6A23C', '#909399', '#67023A',
'#97293A', '#F56C6C', '#67913A', '#9370DB', '#67313A',
'#3AA1FF', '#36CFC9', '#FFC53D', '#FF7A45', '#597EF7',
];
const sorted = [ ...nameValueMap.entries() ].sort((a, b) => b[1] - a[1]);
return {
code: 200,
message: '成功',
data: sorted.map(([ name, value ], index) => ({
name,
value,
itemStyle: { color: colorPalette[index % colorPalette.length] },
})),
};
}
emptyChartData() {
return {
code: 200,
message: '成功',
data: [],
};
}
async platform_distribution() {
const { ctx } = this;
const storeType = String(ctx.user?.store_type || '').trim();
if (storeType === 'store') {
return await this.storeSidePlatformDistribution();
}
const warehouseId = Number(ctx.user?.store_id);
if (!warehouseId) {
return this.fail('缺少仓库上下文');
}
const nameValueMap = await this.queryWarehousePlatformDistribution(warehouseId);
return this.success('ok', this.formatChartData(nameValueMap));
}
async storeSidePlatformDistribution() {
const { ctx } = this;
const storeId = Number(ctx.user?.store_id);
if (!storeId) {
return this.fail('缺少货主上下文');
}
const contracts = await ctx.model.StoreWarehouse.findAll({
where: { store_id: storeId, auth_status: 2 },
attributes: [ 'warehouse_id' ],
raw: true,
});
const warehouseIds = (contracts || []).map(c => Number(c.warehouse_id)).filter(id => id > 0);
if (!warehouseIds.length) {
return this.success('ok', this.emptyChartData());
}
const results = await Promise.all(warehouseIds.map(wid => this.queryWarehousePlatformDistribution(wid).catch(() => null)));
return this.success('ok', this.mergeChartData(results.filter(Boolean)));
}
async queryWarehousePlatformDistribution(warehouseId) {
const { ctx } = this;
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const { Sequelize } = ctx.app;
const rows = await model.findAll({
attributes: [
'sys_platform_name',
[ Sequelize.fn('COUNT', Sequelize.col('id')), 'value' ],
],
where: {
step: { [Sequelize.Op.in]: [ 1, 2, 3 ] },
outbound_status: { [Sequelize.Op.ne]: 'padding' },
status: { [Sequelize.Op.ne]: 'cancel' },
},
group: [ 'sys_platform_name' ],
order: [[ Sequelize.fn('COUNT', Sequelize.col('id')), 'DESC' ]],
raw: true,
});
const nameValueMap = new Map();
for (const row of rows) {
nameValueMap.set(row.sys_platform_name || '未指定平台', Number(row.value) || 0);
}
return nameValueMap;
}
/**
* 订单趋势统计:按小时统计当日订单数与发货数
*
* 口径说明:
* - orders:待处理表订单按创建时间(create_at)小时分组统计;
* - shipments:配送表与待处理表两表汇总——
* - 配送表记录按发货时间(delivery_time)小时分组统计;
* - 待处理表已复核记录(recheck_status 为 fin)视为已发货,优先按复核时间(recheck_time)小时分组统计,
* recheck_time 为空时回退使用 create_at;
* - 配送表记录由待处理表迁移并同步删除源记录,两表数据无重叠,直接汇总不会重复计数。
*
* @return {Object} 包含 categories(时段)、orders(订单数)、shipments(发货数)和 summary(汇总)的响应数据
*/
async order_trend() {
const { ctx } = this;
const warehouseId = ctx.user?.store_id;
if (!warehouseId) {
return this.fail('缺少仓库上下文');
}
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const dispatchModel = await ctx.model.OrderDeliveryFactory.getDispatchModel(warehouseId);
const { Sequelize } = ctx.app;
const { Op } = Sequelize;
// 今日时间范围
const now = new Date();
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const currentHour = now.getHours();
// 时间段:08:00 到当前小时(最晚 23:00),若当前小时早于 08:00 则从 08:00 开始
const startHour = 8;
const endHour = currentHour < startHour ? startHour : Math.min(currentHour, 23);
// 生成 categories 和初始化小时映射
const categories = [];
const orderMap = {};
const shipmentMap = {};
for (let h = startHour; h <= endHour; h++) {
const key = `${String(h).padStart(2, '0')}:00`;
categories.push(key);
orderMap[h] = 0;
shipmentMap[h] = 0;
}
// 查询订单数按创建小时分组
const orderRows = await model.findAll({
attributes: [
[ Sequelize.fn('HOUR', Sequelize.col('create_at')), 'hour' ],
[ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ],
],
where: {
step: { [Op.in]: [ 1, 2, 3 ] },
outbound_status: { [Op.ne]: 'padding' },
status: { [Op.ne]: 'cancel' },
create_at: { [Op.gte]: todayStart, [Op.lte]: now },
},
group: [ Sequelize.fn('HOUR', Sequelize.col('create_at')) ],
raw: true,
});
// 查询配送表发货数按发货小时分组(已进入配送流程的记录按 delivery_time 统计)
const dispatchShipmentRows = await dispatchModel.findAll({
attributes: [
[ Sequelize.fn('HOUR', Sequelize.col('delivery_time')), 'hour' ],
[ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ],
],
where: {
dispatch_lane: 'm4',
delivery_time: { [Op.gte]: todayStart, [Op.lte]: now },
},
group: [ Sequelize.fn('HOUR', Sequelize.col('delivery_time')) ],
raw: true,
});
// 查询待处理表已复核发货数按复核小时分组(已复核视为已发货,优先按 recheck_time 统计,为空时回退 create_at)
const recheckTimeAttr = Sequelize.fn('COALESCE', Sequelize.col('recheck_time'), Sequelize.col('create_at'));
const recheckShipmentRows = await model.findAll({
attributes: [
[ Sequelize.fn('HOUR', recheckTimeAttr), 'hour' ],
[ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ],
],
where: {
step: { [Op.in]: [ 1, 2, 3 ] },
outbound_status: { [Op.ne]: 'padding' },
status: { [Op.ne]: 'cancel' },
recheck_status: 'fin',
[Op.or]: [
{ recheck_time: { [Op.gte]: todayStart, [Op.lte]: now } },
{ recheck_time: null, create_at: { [Op.gte]: todayStart, [Op.lte]: now } },
],
},
group: [ Sequelize.fn('HOUR', recheckTimeAttr) ],
raw: true,
});
// 将查询结果填充到小时映射(发货数为配送表与待处理表两表汇总)
for (const row of orderRows) {
orderMap[row.hour] = Number(row.cnt);
}
for (const row of dispatchShipmentRows) {
shipmentMap[row.hour] = (shipmentMap[row.hour] || 0) + Number(row.cnt);
}
for (const row of recheckShipmentRows) {
shipmentMap[row.hour] = (shipmentMap[row.hour] || 0) + Number(row.cnt);
}
// 按 categories 顺序构建 orders / shipments 数组
const orders = categories.map(cat => orderMap[parseInt(cat, 10)] || 0);
const shipments = categories.map(cat => shipmentMap[parseInt(cat, 10)] || 0);
// 汇总计算
const totalOrders = orders.reduce((sum, v) => sum + v, 0);
const totalShipments = shipments.reduce((sum, v) => sum + v, 0);
const shipmentRate = totalOrders > 0
? parseFloat(((totalShipments / totalOrders) * 100).toFixed(1))
: 0;
// 找订单峰值小时
let peakHour = categories[0] || '08:00';
let peakOrders = 0;
for (let i = 0; i < categories.length; i++) {
if (orders[i] > peakOrders) {
peakOrders = orders[i];
peakHour = categories[i];
}
}
// 当天日期 YYYY-MM-DD
const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
const data = {
code: 200,
message: '成功',
data: {
range: 'day',
date: dateStr,
summary: {
total_orders: totalOrders,
total_shipments: totalShipments,
shipment_rate: shipmentRate,
peak_hour: peakHour,
peak_orders: peakOrders,
},
categories,
orders,
shipments,
},
};
return this.success('ok', data);
}
}
module.exports = dashboardService;