liufumingren 81350c0d6b fix: 定时任务同步日志 + 基础设施修复 + 权限迁移(收尾)
【定时任务】sync_outbound_orders_to_delivery: 执行日志写缓存 + 错误详情提取(parent/validation)

【基础设施】system.js: snake_case→camelCase 服务路由转换(兼容 express_interface 等)

【看板】dashboard: queryWarehouseStats 支持 storeId 货主维度过滤

【订单基类】order/base: getOrderModel 兼容无上下文时传入 warehouseId(货主侧场景)

【库存】inventory: 全量移库软删除→硬删除(force destroy)释放唯一键 + 唯一约束/校验错误友好提示

【快递平台】express_platform: KS(快手)平台 receiver.phone 不传(平台要求)

【迁移】delivery 自增起点 + supervisor CS 权限修复
2026-07-27 03:49:27 +08:00

574 lines
17 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 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,
] = 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 } }),
]);
return {
warehouseId,
totalPending,
todayNew,
yesterdayNew,
unassignedOrders,
unprintedOrders,
unpickedOrders,
pendingShipments,
todayOutbound,
interceptedOrders,
exceptionOrders,
};
}
mergeStoreStats(results) {
const merged = {
totalPending: 0, todayNew: 0, yesterdayNew: 0,
unassignedOrders: 0, unprintedOrders: 0, unpickedOrders: 0,
pendingShipments: 0, todayOutbound: 0, interceptedOrders: 0, exceptionOrders: 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;
}
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,
},
};
}
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,
},
};
}
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 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;
}
/**
* 订单趋势统计:按小时统计当日订单数与发货数
* @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,
});
// 查询发货数按发货小时分组
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;