oms/backend/app/service/dashboard.js
liufumingren 489563a4b2 feat(backend): 仪表盘报表接口、配置裁剪、单号 5 位与账号名称/头像
- 仪表盘报表:新增 app/service/dashboard.js + app/controller/dashboard.js +
  app/lib/billStatus.js,注册 GET /api/dashboard/report(jwtAuth + principalCheck),
  一次聚合返回概览指标、发货单/入库单/出库单状态分布与待办、近 N 天单据量与
  出入库数量趋势、库存 Top 商品、最近出入库流水;warehouse_id 只过滤单据与流水
  (product_stocks 无仓库维度);契约 dashboard* 同步到 swagger
- 接口配置裁剪:仓库接口配置只保留 api_version 与 item_name_with_spec;
  历史 warehouse_apis.extra 冗余键、owner_code 配置、递交/回传设置一并清理
  (迁移 20260915002400~02800)
- 入库/出库/发货单报文与字段对齐 WMS 标准:去掉 ownerCode、operatorCode 等多余字段,
  入库明细补 itemId;发货单明细去掉无意义的 owner_code(迁移 20260915002600)
- 单号 5 位起:四张单据表 AUTO_INCREMENT 提到 10000(迁移 20260915002900)
- 账号名称/头像按主体维护:principal_users 增 name/avatar 并回填(迁移 20260915003000/03100),
  新增 app/lib/accountProfile.js(关联表名称/头像 → users 兜底);审核人写入 operator/operator_name;
  register 不再写 nickname、updateProfile 仅接受邮箱/手机号
- 出库单推送/锁库存链路的配套调整(outboundOrderPush、订单与发货单控制器)

Co-Authored-By: GitHub Copilot <noreply@github.com>
2026-09-14 16:09:35 +08:00

502 lines
18 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 { Service } = require('egg');
const { BILL_STATUS_LABELS, BILL_STATUS_ORDER } = require('../lib/billStatus');
const { BIZ_TYPES, DIRECTION_LABELS } = require('../utils/stockRecord');
/** 允许的趋势区间长度(天) */
const ALLOWED_DAYS = [ 7, 14, 30, 90 ];
const DEFAULT_DAYS = 7;
/** 库存 Top 商品条数 */
const TOP_PRODUCT_LIMIT = 8;
/** 最近流水条数 */
const RECENT_RECORD_LIMIT = 10;
const pad2 = n => String(n).padStart(2, '0');
/**
* Date → 'YYYY-MM-DD'(按服务器本地时区,与 Sequelize timezone=+08:00 的落库口径一致)
* @param {Date} date 日期对象
* @return {String} 日期串
*/
function toDayString(date) {
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
}
/**
* 按天+方向汇总 → Map<day, {in: Number, out: Number}>
* @param {Array} rows 聚合查询结果
* @return {Map} 汇总表
*/
function groupMovement(rows) {
const map = new Map();
for (const row of rows) {
const day = toDayString(new Date(row.day));
const current = map.get(day) || { in: 0, out: 0 };
const quantity = Number(row.quantity || 0);
if (Number(row.direction) === 1) current.in += quantity;
else current.out += quantity;
map.set(day, current);
}
return map;
}
/**
* 按天汇总单据数 → Map<day, Number>
* @param {Array} rows 聚合查询结果
* @return {Map} 汇总表
*/
function groupBillCount(rows) {
const map = new Map();
for (const row of rows) {
const day = toDayString(new Date(row.day));
map.set(day, (map.get(day) || 0) + Number(row.count || 0));
}
return map;
}
/**
* @service DashboardService 仪表盘报表
*
* 基于现有单据(发货单 / 入库单 / 出库单)、库存(product_stocks)与库存流水(stock_records)
* 做只读聚合:概览指标、单据状态分布与待办、近 N 天趋势、库存 Top 商品、最近流水。
* 全部按主体隔离(principal_id),可选按仓库过滤(库存无仓库维度,见 report 注释)。
*/
class DashboardService extends Service {
/**
* 仪表盘报表数据
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @param {Number} [params.days] 趋势区间天数(7/14/30/90,默认 7)
* @param {Number} [params.warehouseId] 仓库ID(过滤单据与流水;product_stocks 无仓库维度,库存概览不受此过滤)
* @return {Promise<Object>} 报表数据
*/
async report({ principalId, days, warehouseId }) {
const Op = this.app.Sequelize.Op;
const rangeDays = ALLOWED_DAYS.includes(Number(days)) ? Number(days) : DEFAULT_DAYS;
// 趋势区间:起始日 00:00:00(含) → 当前时间
const startDate = new Date();
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - (rangeDays - 1));
const endDate = new Date();
const baseWhere = { principal_id: principalId };
if (warehouseId) baseWhere.warehouse_id = warehouseId;
const rangeWhere = {
...baseWhere,
created_at: { [Op.gte]: startDate, [Op.lte]: endDate },
};
const bills = [
{ key: 'delivery', label: '发货单', model: 'OrderDelivery', path: '/order' },
{ key: 'inbound', label: '入库单', model: 'InboundOrder', path: '/inbound-order' },
{ key: 'outbound', label: '出库单', model: 'OutboundOrder', path: '/outbound-order' },
];
const [ overview, billStats, trend, stockMovement, topProducts, recentRecords ] = await Promise.all([
this._overview({ principalId, warehouseId }),
Promise.all(bills.map(item => this._billStats(item, { baseWhere, rangeWhere }))),
this._billTrend(bills, { baseWhere, startDate, endDate }),
this._stockMovement({ principalId, warehouseId, startDate, endDate }),
this._topProducts({ principalId }),
this._recentRecords({ principalId, warehouseId }),
]);
return {
range: {
days: rangeDays,
start_date: toDayString(startDate),
end_date: toDayString(endDate),
},
overview,
bills: billStats,
todo: this._buildTodo(billStats),
trend: this._mergeTrend({ days: rangeDays, startDate, billTrend: trend, stockMovement }),
movement: {
inbound_qty: stockMovement.reduce((sum, item) => sum + item.inbound_qty, 0),
outbound_qty: stockMovement.reduce((sum, item) => sum + item.outbound_qty, 0),
},
top_products: topProducts,
recent_records: recentRecords,
};
}
/**
* 概览指标:商品/店铺/仓库数量 + 库存汇总 + 区间内单据数与金额
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @param {Number} [params.warehouseId] 仓库ID
* @return {Promise<Object>} 概览数据
*/
async _overview({ principalId, warehouseId }) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const fn = this.app.Sequelize.fn;
const col = this.app.Sequelize.col;
const { ProductStock, Product, Shop, Warehouse, OrderDelivery, InboundOrder, OutboundOrder } = ctx.model;
const startDate = new Date();
startDate.setHours(0, 0, 0, 0);
startDate.setDate(startDate.getDate() - 29);
const endDate = new Date();
const billModels = [ OrderDelivery, InboundOrder, OutboundOrder ];
const billBase = { principal_id: principalId };
if (warehouseId) billBase.warehouse_id = warehouseId;
const billRange = { ...billBase, created_at: { [Op.gte]: startDate, [Op.lte]: endDate } };
const [
productCount,
shopCount,
warehouseCount,
stockRows,
stockProductKind,
billTotal,
deliveryCount30,
deliveryAmount,
] = await Promise.all([
Product.count({ where: { principal_id: principalId } }),
Shop.count({ where: { principal_id: principalId } }),
Warehouse.count({ where: { principal_id: principalId } }),
// ⚠️ product_stocks 只有 (principal_id, product_id, item_type) 维度,没有 warehouse_id → 库存概览不按仓库过滤
ProductStock.findAll({
attributes: [
'item_type',
[ fn('SUM', col('quantity')), 'quantity' ],
[ fn('SUM', col('lock_quantity')), 'lock_quantity' ],
[ fn('SUM', col('available')), 'available' ],
],
where: { principal_id: principalId },
group: [ 'item_type' ],
raw: true,
}),
ProductStock.count({ where: { principal_id: principalId }, distinct: true, col: 'product_id' }),
Promise.all(billModels.map(model => model.count({ where: billBase }))).then(list => list.reduce((a, b) => a + b, 0)),
OrderDelivery.count({ where: billRange }),
OrderDelivery.sum('total_amount', { where: billRange }),
]);
const stock = { quantity: 0, available: 0, locked: 0, zc: 0, cc: 0 };
for (const row of stockRows) {
const quantity = Number(row.quantity || 0);
const available = Number(row.available || 0);
const locked = Number(row.lock_quantity || 0);
stock.quantity += quantity;
stock.available += available;
stock.locked += locked;
if (String(row.item_type).toUpperCase() === 'CC') stock.cc += quantity;
else stock.zc += quantity;
}
return {
product_count: productCount,
shop_count: shopCount,
warehouse_count: warehouseCount,
stock_product_kind: stockProductKind,
stock_quantity: this._round(stock.quantity),
stock_available: this._round(stock.available),
stock_locked: this._round(stock.locked),
stock_zc: this._round(stock.zc),
stock_cc: this._round(stock.cc),
bill_total: billTotal,
delivery_count_30d: deliveryCount30,
delivery_amount_30d: this._round(Number(deliveryAmount || 0), 2),
};
}
/**
* 单类单据的状态分布、区间新增、待办与推送失败数
* @param {Object} bill 单据定义(key/label/model/...)
* @param {Object} params 入参
* @param {Object} params.baseWhere 基础过滤(主体 + 可选仓库)
* @param {Object} params.rangeWhere 基础过滤 + 时间区间
* @return {Promise<Object>} 单据统计
*/
async _billStats(bill, { baseWhere, rangeWhere }) {
const { ctx } = this;
const fn = this.app.Sequelize.fn;
const col = this.app.Sequelize.col;
const Model = ctx.model[bill.model];
const [ statusRows, rangeCount, pushFail, amount ] = await Promise.all([
Model.findAll({
attributes: [ 'status', [ fn('COUNT', col('id')), 'count' ]],
where: baseWhere,
group: [ 'status' ],
raw: true,
}),
Model.count({ where: rangeWhere }),
this._countPushFail(Model, baseWhere),
Model.sum('total_amount', { where: rangeWhere }),
]);
const countByStatus = new Map();
for (const row of statusRows) countByStatus.set(Number(row.status), Number(row.count || 0));
const byStatus = BILL_STATUS_ORDER.map(status => ({
status,
label: BILL_STATUS_LABELS[status],
count: countByStatus.get(status) || 0,
}));
const total = byStatus.reduce((sum, item) => sum + item.count, 0);
const pick = (...statuses) => statuses.reduce((sum, status) => sum + (countByStatus.get(status) || 0), 0);
return {
key: bill.key,
label: bill.label,
path: bill.path,
total,
by_status: byStatus,
range_count: rangeCount,
amount: this._round(Number(amount || 0), 2),
wait_handle: pick(1),
wait_push: pick(2),
wait_finish: pick(3),
finished: pick(4),
canceled: pick(9),
voided: pick(5),
push_fail: pushFail,
};
}
/**
* 推送失败单据数:wms_push_result.success = false(JSON 列取值,注意 JSON 里的 false 需显式比较)
* @param {Object} Model 单据模型
* @param {Object} baseWhere 基础过滤
* @return {Promise<Number>} 失败条数
*/
async _countPushFail(Model, baseWhere) {
const literal = this.app.Sequelize.literal;
return Model.count({
where: {
...baseWhere,
[this.app.Sequelize.Op.and]: [
literal("JSON_EXTRACT(`wms_push_result`, '$.success') = false"),
],
},
});
}
/**
* 近 N 天每类单据的创建量
* @param {Array} bills 单据定义列表
* @param {Object} params 入参
* @param {Object} params.baseWhere 基础过滤
* @param {Date} params.startDate 起始日
* @param {Date} params.endDate 结束时间
* @return {Promise<Array>} [{ key, label, values: Map<day, count> }]
*/
async _billTrend(bills, { baseWhere, startDate, endDate }) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const fn = this.app.Sequelize.fn;
const col = this.app.Sequelize.col;
return Promise.all(bills.map(async bill => {
const rows = await ctx.model[bill.model].findAll({
attributes: [[ fn('DATE', col('created_at')), 'day' ], [ fn('COUNT', col('id')), 'count' ]],
where: { ...baseWhere, created_at: { [Op.gte]: startDate, [Op.lte]: endDate } },
group: [ this.app.Sequelize.literal('DATE(`created_at`)') ],
raw: true,
});
return { key: bill.key, label: bill.label, counts: groupBillCount(rows) };
}));
}
/**
* 近 N 天每日出入库数量(来源 stock_records 流水,direction 1=入库方向 2=出库方向)
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @param {Number} [params.warehouseId] 仓库ID
* @param {Date} params.startDate 起始日
* @param {Date} params.endDate 结束时间
* @return {Promise<Array>} [{ day, inbound_qty, outbound_qty }]
*/
async _stockMovement({ principalId, warehouseId, startDate, endDate }) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const fn = this.app.Sequelize.fn;
const col = this.app.Sequelize.col;
const where = { principal_id: principalId, created_at: { [Op.gte]: startDate, [Op.lte]: endDate } };
if (warehouseId) where.warehouse_id = warehouseId;
const rows = await ctx.model.StockRecord.findAll({
attributes: [
[ fn('DATE', col('created_at')), 'day' ],
'direction',
[ fn('SUM', col('quantity')), 'quantity' ],
],
where,
group: [ this.app.Sequelize.literal('DATE(`created_at`)'), 'direction' ],
raw: true,
});
const map = groupMovement(rows);
return this._dayList(startDate, endDate).map(day => {
const item = map.get(day) || { in: 0, out: 0 };
return {
day,
inbound_qty: this._round(item.in),
outbound_qty: this._round(item.out),
};
});
}
/**
* 合并单据趋势与出入库趋势为前端可直接渲染的序列(按天对齐、补 0)
* @param {Object} params 入参
* @param {Number} params.days 区间天数
* @param {Date} params.startDate 起始日
* @param {Array} params.billTrend 单据趋势
* @param {Array} params.stockMovement 出入库趋势
* @return {Object} { days, dates, series, max_bill, max_qty }
*/
_mergeTrend({ days, startDate, billTrend, stockMovement }) {
const dates = this._dayList(startDate, new Date());
const movementMap = new Map(stockMovement.map(item => [ item.day, item ]));
const series = [
...billTrend.map(item => ({
key: item.key,
label: item.label,
unit: '单',
values: dates.map(day => item.counts.get(day) || 0),
})),
{
key: 'inbound_qty',
label: '入库数量',
unit: '件',
values: dates.map(day => (movementMap.get(day) || {}).inbound_qty || 0),
},
{
key: 'outbound_qty',
label: '出库数量',
unit: '件',
values: dates.map(day => (movementMap.get(day) || {}).outbound_qty || 0),
},
];
const billSeries = series.slice(0, billTrend.length);
const maxBill = Math.max(1, ...billSeries.flatMap(item => item.values));
const maxQty = Math.max(1, ...series.slice(billTrend.length).flatMap(item => item.values));
return { days, dates, series, max_bill: maxBill, max_qty: maxQty };
}
/**
* 库存 Top 商品(按可用数量倒序)
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @return {Promise<Array>} 商品库存列表
*/
async _topProducts({ principalId }) {
const { ctx } = this;
const rows = await ctx.model.ProductStock.findAll({
where: { principal_id: principalId },
include: [{
model: ctx.model.Product,
as: 'product',
attributes: [ 'item_code', 'item_name', 'sku_property', 'stock_unit' ],
required: false,
}],
order: [[ 'available', 'DESC' ]],
limit: TOP_PRODUCT_LIMIT,
});
return rows.map(row => {
const item = row.get({ plain: true });
const product = item.product || {};
return {
product_id: item.product_id,
item_code: product.item_code || '-',
item_name: product.item_name || '(商品已删除)',
sku_property: product.sku_property || '',
stock_unit: product.stock_unit || '',
item_type: item.item_type,
quantity: this._round(Number(item.quantity || 0)),
lock_quantity: this._round(Number(item.lock_quantity || 0)),
available: this._round(Number(item.available || 0)),
};
});
}
/**
* 最近出入库记录(附业务动作/方向中文标签)
* @param {Object} params 入参
* @param {Number} params.principalId 主体ID
* @param {Number} [params.warehouseId] 仓库ID
* @return {Promise<Array>} 流水列表
*/
async _recentRecords({ principalId, warehouseId }) {
const { ctx } = this;
const where = { principal_id: principalId };
if (warehouseId) where.warehouse_id = warehouseId;
const rows = await ctx.model.StockRecord.findAll({
where,
order: [[ 'id', 'DESC' ]],
limit: RECENT_RECORD_LIMIT,
raw: true,
});
return rows.map(row => ({
...row,
biz_type_label: (BIZ_TYPES[row.biz_type] || {}).label || row.biz_type,
direction_label: DIRECTION_LABELS[row.direction] || '',
}));
}
/**
* 待办列表(计数大于 0 才返回,附前端跳转路径与筛选条件)
* @param {Array} billStats 单据统计
* @return {Array} 待办项
*/
_buildTodo(billStats) {
const todo = [];
const push = (key, label, count, path, query) => {
if (count > 0) todo.push({ key, label, count, path, query });
};
for (const bill of billStats) {
push(`${bill.key}_wait_handle`, `${bill.label}待处理`, bill.wait_handle, bill.path, { status: 1 });
push(`${bill.key}_wait_push`, `${bill.label}待推送`, bill.wait_push, bill.path, { status: 2 });
push(`${bill.key}_wait_finish`, `${bill.label}待完成`, bill.wait_finish, bill.path, { status: 3 });
push(`${bill.key}_push_fail`, `${bill.label}推送失败`, bill.push_fail, bill.path, null);
}
return todo;
}
/**
* 生成日期列表(含首尾)
* @param {Date} startDate 起始日(当天 00:00:00)
* @param {Date} endDate 结束日
* @return {Array<String>} ['YYYY-MM-DD', ...]
*/
_dayList(startDate, endDate) {
const days = [];
const cursor = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate());
const last = new Date(endDate.getFullYear(), endDate.getMonth(), endDate.getDate());
while (cursor <= last) {
days.push(toDayString(cursor));
cursor.setDate(cursor.getDate() + 1);
}
return days;
}
/**
* 数值取整(库存/数量按 3 位小数,金额按 2 位)
* @param {Number} value 数值
* @param {Number} [digits] 小数位,默认 3
* @return {Number} 处理后的数值
*/
_round(value, digits = 3) {
const factor = 10 ** digits;
return Math.round((Number(value) || 0) * factor) / factor;
}
}
module.exports = DashboardService;