'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 * @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 * @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} 报表数据 */ 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 scope = await this._ownerScope(principalId); 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, scope }), Promise.all(bills.map(item => this._billStats(item, { baseWhere: this._scopeBillWhere(item.model, baseWhere, scope), rangeWhere: this._scopeBillWhere(item.model, rangeWhere, scope), }))), this._billTrend(bills, { baseWhere, startDate, endDate, scope }), this._stockMovement({ principalId, warehouseId, startDate, endDate, scope }), this._topProducts({ principalId, scope }), this._recentRecords({ principalId, warehouseId, scope }), ]); 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 {Number} principalId 主体ID * @return {Promise} null 表示集团权限(不做限制) */ async _ownerScope(principalId) { const { ctx } = this; // 无登录态(内部调用)按集团口径 if (!ctx.userId) return null; const access = await ctx.service.access.resolve(ctx.userId, principalId); if (access.isGroup) return null; const Op = this.app.Sequelize.Op; const ownIds = (access.ownCompanyIds || []).map(Number); if (!ownIds.length) return { ownIds, shopIds: [], warehouseIds: [], productSubSql: '1 = 0' }; const [ shops, warehouses ] = await Promise.all([ ctx.model.Shop.findAll({ where: { principal_id: principalId, subsidiary_id: { [Op.in]: ownIds } }, attributes: [ 'id' ], raw: true, }), ctx.model.Warehouse.findAll({ where: { principal_id: principalId, subsidiary_id: { [Op.in]: ownIds } }, attributes: [ 'id' ], raw: true, }), ]); return { ownIds, shopIds: shops.map(row => Number(row.id)), warehouseIds: warehouses.map(row => Number(row.id)), // 商品用子查询,避免商品多时拼接超长 IN 列表 productSubSql: `product_id IN (SELECT id FROM products WHERE principal_id = ${Number(principalId)}` + ` AND subsidiary_id IN (${ownIds.join(',')}))`, }; } /** * 单据查询条件按货主范围收窄(发货单按店铺/仓库,入库出库单按仓库) * @param {String} modelName 模型名 * @param {Object} base 基础条件 * @param {Object|null} scope 货主范围 * @return {Object} 收窄后的条件 */ _scopeBillWhere(modelName, base, scope) { if (!scope) return base; const Op = this.app.Sequelize.Op; if (modelName === 'OrderDelivery' || modelName === 'order_delivery') { const ors = []; if (scope.shopIds.length) ors.push({ shop_id: { [Op.in]: scope.shopIds } }); if (scope.warehouseIds.length) ors.push({ warehouse_id: { [Op.in]: scope.warehouseIds } }); return { ...base, [Op.and]: [ ors.length ? { [Op.or]: ors } : this.app.Sequelize.literal('1 = 0') ] }; } if (!scope.warehouseIds.length) { return { ...base, [Op.and]: [ this.app.Sequelize.literal('1 = 0') ] }; } return { ...base, [Op.and]: [{ warehouse_id: { [Op.in]: scope.warehouseIds } }] }; } /** * 概览指标:商品/店铺/仓库数量 + 库存汇总 + 区间内单据数与金额 * @param {Object} params 入参 * @param {Number} params.principalId 主体ID * @param {Number} [params.warehouseId] 仓库ID * @param {Object} [params.scope] 货主范围(所在公司权限) * @return {Promise} 概览数据 */ async _overview({ principalId, warehouseId, scope }) { 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 } }; // 货主范围:商品/店铺/仓库按 subsidiary_id 限定,库存按商品子查询限定 const productWhere = { principal_id: principalId }; const shopWhere = { principal_id: principalId }; const warehouseWhere = { principal_id: principalId }; if (scope) { productWhere.subsidiary_id = { [Op.in]: scope.ownIds }; shopWhere.subsidiary_id = { [Op.in]: scope.ownIds }; warehouseWhere.subsidiary_id = { [Op.in]: scope.ownIds }; } const stockWhere = scope ? { principal_id: principalId, [Op.and]: [ this.app.Sequelize.literal(scope.productSubSql) ] } : { principal_id: principalId }; const deliveryRange = this._scopeBillWhere('order_delivery', billRange, scope); const [ productCount, shopCount, warehouseCount, stockRows, stockProductKind, billTotal, deliveryCount30, deliveryAmount, ] = await Promise.all([ Product.count({ where: productWhere }), Shop.count({ where: shopWhere }), Warehouse.count({ where: warehouseWhere }), // ⚠️ 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: stockWhere, group: [ 'item_type' ], raw: true, }), ProductStock.count({ where: stockWhere, distinct: true, col: 'product_id' }), Promise.all(billModels.map(model => model.count({ where: this._scopeBillWhere(model.name, billBase, scope), }))).then(list => list.reduce((a, b) => a + b, 0)), OrderDelivery.count({ where: deliveryRange }), OrderDelivery.sum('total_amount', { where: deliveryRange }), ]); 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} 单据统计 */ 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} 失败条数 */ 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 结束时间 * @param {Object} [params.scope] 货主范围(所在公司权限) * @return {Promise} [{ key, label, values: Map }] */ async _billTrend(bills, { baseWhere, startDate, endDate, scope }) { 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 where = this._scopeBillWhere(bill.model, baseWhere, scope); const rows = await ctx.model[bill.model].findAll({ attributes: [[ fn('DATE', col('created_at')), 'day' ], [ fn('COUNT', col('id')), 'count' ]], where: { ...where, 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 {Object} [params.scope] 货主范围(所在公司权限) * @param {Number} [params.warehouseId] 仓库ID * @param {Date} params.startDate 起始日 * @param {Date} params.endDate 结束时间 * @return {Promise} [{ day, inbound_qty, outbound_qty }] */ async _stockMovement({ principalId, warehouseId, startDate, endDate, scope }) { 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; // 货主范围:仓库属于自己公司,或商品属于自己公司 if (scope) { const ors = []; if (scope.warehouseIds.length) ors.push({ warehouse_id: { [Op.in]: scope.warehouseIds } }); ors.push(this.app.Sequelize.literal(scope.productSubSql)); where[Op.and] = [ ors.length > 1 ? { [Op.or]: ors } : ors[0] ]; } 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 * @param {Object} [params.scope] 货主范围(所在公司权限) * @return {Promise} 商品库存列表 */ async _topProducts({ principalId, scope }) { const { ctx } = this; const where = { principal_id: principalId }; if (scope) where[this.app.Sequelize.Op.and] = [ this.app.Sequelize.literal(scope.productSubSql) ]; const rows = await ctx.model.ProductStock.findAll({ where, 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 {Object} [params.scope] 货主范围(所在公司权限) * @param {Number} [params.warehouseId] 仓库ID * @return {Promise} 流水列表 */ async _recentRecords({ principalId, warehouseId, scope }) { const { ctx } = this; const where = { principal_id: principalId }; if (warehouseId) where.warehouse_id = warehouseId; // 货主范围:仓库属于自己公司,或商品属于自己公司 if (scope) { const Op = this.app.Sequelize.Op; const ors = []; if (scope.warehouseIds.length) ors.push({ warehouse_id: { [Op.in]: scope.warehouseIds } }); ors.push(this.app.Sequelize.literal(scope.productSubSql)); where[Op.and] = [ ors.length > 1 ? { [Op.or]: ors } : ors[0] ]; } 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} ['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;