liufumingren 025184904a 1
2026-06-14 19:03:58 +08:00

425 lines
12 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 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 warehouseId = ctx.user?.store_id;
if (!warehouseId) {
return this.fail('缺少仓库上下文');
}
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const { Sequelize } = ctx.app;
const { Op } = Sequelize;
// 待处理订单基础条件:step in [1,2,3](排除待审核 step=0,包含待处理异常 step=3)
const pendingBase = {
step: { [Op.in]: [ 1, 2, 3 ] },
outbound_status: { [Op.ne]: 'padding' },
status: { [Op.ne]: 'cancel' },
};
// 今日时间范围
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,
] = 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 } } }),
model.count({ where: { ...pendingBase, intercept_status: { [Op.not]: null, [Op.ne]: 'none' } } }),
model.count({ where: { ...pendingBase, step: 3 } }),
]);
const orderTrend = yesterdayNew > 0
? parseFloat((((todayNew - yesterdayNew) / yesterdayNew) * 100).toFixed(1))
: (todayNew > 0 ? 100 : 0);
const totalForRate = pendingShipments + todayOutbound;
const outboundRate = totalForRate > 0
? parseFloat(((todayOutbound / totalForRate) * 100).toFixed(2))
: 0;
const shipmentProgress = totalPending > 0
? parseFloat((((totalPending - pendingShipments) / totalPending) * 100).toFixed(0))
: 0;
const data = {
code: 200,
message: '成功',
data: {
todayOrders: totalPending + todayOutbound,
orderTrend,
unassignedOrders,
unprintedOrders,
unpickedOrders,
pendingShipments,
shipmentProgress,
todayOutbound,
outboundRate,
interceptedOrders,
exceptionOrders,
},
};
return this.success('ok', data);
}
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);
}
async hot_order_rank() {
const data = {
code: 200,
message: '成功',
data: [{
id: 1,
name: '新***盒1',
sku: 'SKU202510081',
value: 51516,
trend: 18.5,
},
{
id: 2,
name: '天***g',
sku: 'SKU202401002',
value: 43132,
trend: 12.3,
},
{
id: 3,
name: '定****l',
sku: 'SKU202401003',
value: 39098,
trend: -2.5,
},
{
id: 4,
name: '奥*****膜',
sku: 'SKU202401004',
value: 39087,
trend: 8.7,
},
{
id: 5,
name: '美*****液',
sku: 'SKU202401005',
value: 25776,
trend: 15.2,
},
{
id: 6,
name: '荣耀Magic6 Pro 1TB',
sku: 'SKU202401006',
value: 65,
trend: 5.4,
},
{
id: 7,
name: '三星Galaxy S24 Ultra 512GB',
sku: 'SKU202401007',
value: 54,
trend: -3.8,
},
{
id: 8,
name: '一加12 512GB',
sku: 'SKU202401008',
value: 43,
trend: 22.1,
},
{
id: 9,
name: '真我GT5 Pro 1TB',
sku: 'SKU202401009',
value: 38,
trend: 9.6,
},
{
id: 10,
name: '魅族21 Pro 512GB',
sku: 'SKU202401010',
value: 29,
trend: 4.2,
},
],
};
return this.success('ok', data);
}
async express_ratio() {
const { ctx } = this;
const warehouseId = ctx.user?.store_id;
if (!warehouseId) {
return this.fail('缺少仓库上下文');
}
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const { Sequelize } = ctx.app;
// 待处理订单条件:step in [1,2,3](排除待审核 step=0,包含待处理异常 step=3)
// 排除已取消的订单
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 colorPalette = [
'#409EFF', '#67C23A', '#E6A23C', '#909399', '#67023A',
'#97293A', '#F56C6C', '#67913A', '#9370DB', '#67313A',
'#3AA1FF', '#36CFC9', '#FFC53D', '#FF7A45', '#597EF7',
];
const data = {
code: 200,
message: '成功',
data: rows.map((row, index) => ({
name: row.logistics_name || '未指定快递',
value: Number(row.value),
itemStyle: {
color: colorPalette[index % colorPalette.length],
},
})),
};
return this.success('ok', data);
}
async platform_distribution() {
const { ctx } = this;
const warehouseId = ctx.user?.store_id;
if (!warehouseId) {
return this.fail('缺少仓库上下文');
}
const model = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
const { Sequelize } = ctx.app;
// 待处理订单条件:step in [1,2,3](排除待审核 step=0,包含待处理异常 step=3)
// 排除已取消的订单
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 colorPalette = [
'#409EFF', '#67C23A', '#E6A23C', '#909399', '#67023A',
'#97293A', '#F56C6C', '#67913A', '#9370DB', '#67313A',
'#3AA1FF', '#36CFC9', '#FFC53D', '#FF7A45', '#597EF7',
];
const data = {
code: 200,
message: '成功',
data: rows.map((row, index) => ({
name: row.sys_platform_name || '未指定平台',
value: Number(row.value),
itemStyle: {
color: colorPalette[index % colorPalette.length],
},
})),
};
return this.success('ok', data);
}
/**
* 订单趋势统计:按小时统计当日订单数与发货数
* @returns {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,
});
// 查询发货数按发货小时分组
const shipmentRows = 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,
});
// 将查询结果填充到小时映射
for (const row of orderRows) {
orderMap[row.hour] = Number(row.cnt);
}
for (const row of shipmentRows) {
shipmentMap[row.hour] = 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;