From baa89a7509e198d15119a821711d059a2f59c8a0 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Thu, 5 Nov 2026 03:09:23 +0800 Subject: [PATCH] =?UTF-8?q?feat(dashboard):=20=E9=A6=96=E9=A1=B5=E7=9C=8B?= =?UTF-8?q?=E6=9D=BF=E6=8C=89=E8=B4=A7=E4=B8=BB=E6=94=B6=E7=AA=84=20+=20?= =?UTF-8?q?=E5=BA=97=E9=93=BA=E8=B4=A7=E4=B8=BB=E5=88=9B=E5=BB=BA=E5=90=8E?= =?UTF-8?q?=E4=B8=8D=E5=8F=AF=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - dashboard 服务新增货主范围(_ownerScope/_scopeBillWhere),概览、趋势、库存流水、 Top 商品、最近流水均按当前账号所属货主收窄;首页加货主范围标签 - 店铺编辑禁止修改所属货主(历史无货主可补齐一次并联动店铺商品),详情返回 subsidiary_name - 更新店铺契约描述 --- backend/app/contract/index.js | 2 +- backend/app/controller/shop.js | 26 ++++-- backend/app/service/dashboard.js | 147 +++++++++++++++++++++++++----- frontend/src/views/Home.vue | 23 ++++- frontend/src/views/Shop/Index.vue | 8 +- 5 files changed, 176 insertions(+), 30 deletions(-) diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 4f4696a..d2232be 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -1173,7 +1173,7 @@ module.exports = { updateShopRequest: { code: { type: 'string', description: '店铺编码' }, name: { type: 'string', description: '店铺名称' }, - subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);所在公司权限不可变更,集团变更后店铺商品货主跟随' }, + subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);店铺创建后不可变更(历史无货主店铺可补齐一次)' }, platform: { type: 'string', description: '平台标识' }, contact_name: { type: 'string', description: '联系人' }, contact_phone: { type: 'string', description: '联系电话' }, diff --git a/backend/app/controller/shop.js b/backend/app/controller/shop.js index f43bfc6..bd82cb5 100644 --- a/backend/app/controller/shop.js +++ b/backend/app/controller/shop.js @@ -136,7 +136,11 @@ class ShopController extends Controller { async show() { const { ctx } = this; const Op = ctx.app.Sequelize.Op; - const shop = await ctx.model.Shop.findByPk(ctx.params.id); + const shop = await ctx.model.Shop.findByPk(ctx.params.id, { + include: [ + { model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }, + ], + }); if (!shop) { ctx.status = 404; @@ -167,6 +171,7 @@ class ShopController extends Controller { const data = shop.get({ plain: true }); data.has_db_password = !!data.db_password; + data.subsidiary_name = data.subsidiary ? data.subsidiary.name : ''; delete data.db_password; ctx.body = { @@ -373,22 +378,31 @@ class ShopController extends Controller { return; } - // 货主:所在公司权限不可变更;集团可改(店铺商品同步跟随) + // 店铺创建后不可更改所属货主(历史无货主店铺允许补齐一次) let subsidiaryChanged = false; - if (ctx.request.body.subsidiary_id !== undefined) { - const subsidiary = await this.resolveSubsidiaryId(ctx.request.body.subsidiary_id, shop.principal_id); + const incomingSubsidiary = ctx.request.body.subsidiary_id; + if (incomingSubsidiary !== undefined && incomingSubsidiary !== null && incomingSubsidiary !== '') { + const subsidiary = await this.resolveSubsidiaryId(incomingSubsidiary, shop.principal_id); if (!subsidiary.ok) { ctx.status = 400; ctx.body = { code: 400, message: subsidiary.message }; return; } - if (!access.isGroup && Number(subsidiary.value) !== Number(shop.subsidiary_id)) { + if (shop.subsidiary_id != null && Number(subsidiary.value) !== Number(shop.subsidiary_id)) { + ctx.status = 400; + ctx.body = { code: 400, message: '店铺创建后不可更改所属货主' }; + return; + } + if (!access.isGroup && !this.isOwnSubsidiary(access, subsidiary.value)) { ctx.status = 403; ctx.body = { code: 403, message: '只能维护自己所属公司(货主)的店铺' }; return; } - subsidiaryChanged = Number(subsidiary.value) !== Number(shop.subsidiary_id); + subsidiaryChanged = shop.subsidiary_id == null; ctx.request.body.subsidiary_id = subsidiary.value; + } else { + // 未传或传空:保持原货主,不允许清空 + delete ctx.request.body.subsidiary_id; } // 外部平台导入 / 数据库模式相关字段由对应接入逻辑维护,普通编辑不允许修改 delete ctx.request.body.type; diff --git a/backend/app/service/dashboard.js b/backend/app/service/dashboard.js index 9d5d940..8d5abe2 100644 --- a/backend/app/service/dashboard.js +++ b/backend/app/service/dashboard.js @@ -88,6 +88,9 @@ class DashboardService extends Service { 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' }, @@ -95,12 +98,15 @@ class DashboardService extends Service { ]; 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 }), + 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 { @@ -122,14 +128,75 @@ class DashboardService extends Service { }; } + /** + * 所在公司权限的统计范围(货主) + * @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 }) { + async _overview({ principalId, warehouseId, scope }) { const { ctx } = this; const Op = this.app.Sequelize.Op; const fn = this.app.Sequelize.fn; @@ -146,6 +213,20 @@ class DashboardService extends Service { 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, @@ -156,9 +237,9 @@ class DashboardService extends Service { deliveryCount30, deliveryAmount, ] = await Promise.all([ - Product.count({ where: { principal_id: principalId } }), - Shop.count({ where: { principal_id: principalId } }), - Warehouse.count({ where: { principal_id: principalId } }), + 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: [ @@ -167,14 +248,16 @@ class DashboardService extends Service { [ fn('SUM', col('lock_quantity')), 'lock_quantity' ], [ fn('SUM', col('available')), 'available' ], ], - where: { principal_id: principalId }, + where: stockWhere, 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 }), + 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 }; @@ -286,18 +369,20 @@ class DashboardService extends Service { * @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 }) { + 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: { ...baseWhere, created_at: { [Op.gte]: startDate, [Op.lte]: endDate } }, + where: { ...where, created_at: { [Op.gte]: startDate, [Op.lte]: endDate } }, group: [ this.app.Sequelize.literal('DATE(`created_at`)') ], raw: true, }); @@ -309,12 +394,13 @@ class DashboardService extends Service { * 近 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 }) { + async _stockMovement({ principalId, warehouseId, startDate, endDate, scope }) { const { ctx } = this; const Op = this.app.Sequelize.Op; const fn = this.app.Sequelize.fn; @@ -322,6 +408,13 @@ class DashboardService extends Service { 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: [ @@ -390,12 +483,15 @@ class DashboardService extends Service { * 库存 Top 商品(按可用数量倒序) * @param {Object} params 入参 * @param {Number} params.principalId 主体ID + * @param {Object} [params.scope] 货主范围(所在公司权限) * @return {Promise} 商品库存列表 */ - async _topProducts({ principalId }) { + 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: { principal_id: principalId }, + where, include: [{ model: ctx.model.Product, as: 'product', @@ -427,13 +523,22 @@ class DashboardService extends Service { * 最近出入库记录(附业务动作/方向中文标签) * @param {Object} params 入参 * @param {Number} params.principalId 主体ID + * @param {Object} [params.scope] 货主范围(所在公司权限) * @param {Number} [params.warehouseId] 仓库ID * @return {Promise} 流水列表 */ - async _recentRecords({ principalId, warehouseId }) { + 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, diff --git a/frontend/src/views/Home.vue b/frontend/src/views/Home.vue index edfc487..6318bed 100644 --- a/frontend/src/views/Home.vue +++ b/frontend/src/views/Home.vue @@ -4,6 +4,7 @@ import { useRouter } from 'vue-router' import { getDashboardReport, type DashboardBill, type DashboardReport } from '@/api/dashboard' import { useAuthStore } from '@/store/auth' import { usePrincipalStore } from '@/store/principal' +import { getAccessContext } from '@/api/access' import { formatDateTime } from '@/utils/datetime' /** @@ -35,6 +36,17 @@ const BAR_CLASSES: Record = { const loading = ref(false) const days = ref(7) const report = ref(null) +/** 是否所在公司权限(看板只统计自己所属公司的数据) */ +const isCompanyScope = ref(false) + +async function loadAccessContext() { + try { + const access = await getAccessContext() + isCompanyScope.value = !access.is_group + } catch { + isCompanyScope.value = false + } +} const overview = computed(() => report.value?.overview || null) /** 当前账号在当前主体下的名称(与右上角头像旁名称同口径) */ @@ -100,7 +112,10 @@ function statusJump(bill: DashboardBill, status: number) { router.push({ path: bill.path, query: { status: String(status) } }) } -onMounted(fetchReport) +onMounted(() => { + fetchReport() + loadAccessContext() +})