feat(dashboard): 首页看板按货主收窄 + 店铺货主创建后不可变更

- dashboard 服务新增货主范围(_ownerScope/_scopeBillWhere),概览、趋势、库存流水、
  Top 商品、最近流水均按当前账号所属货主收窄;首页加货主范围标签
- 店铺编辑禁止修改所属货主(历史无货主可补齐一次并联动店铺商品),详情返回 subsidiary_name
- 更新店铺契约描述
This commit is contained in:
liufumingren 2026-11-05 03:09:23 +08:00
parent 2d2f781f09
commit baa89a7509
5 changed files with 176 additions and 30 deletions

View File

@ -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: '联系电话' },

View File

@ -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;

View File

@ -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<Object|null>} 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<Object>} 概览数据
*/
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<Array>} [{ key, label, values: Map<day, count> }]
*/
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<Array>} [{ 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<Array>} 商品库存列表
*/
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<Array>} 流水列表
*/
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,

View File

@ -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<string, string> = {
const loading = ref(false)
const days = ref(7)
const report = ref<DashboardReport | null>(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()
})
</script>
<template>
@ -112,6 +127,9 @@ onMounted(fetchReport)
<div class="dash-sub">
{{ accountName }}
<template v-if="report"> · 统计区间 {{ report.range.start_date }} ~ {{ report.range.end_date }}</template>
<el-tag v-if="isCompanyScope" size="small" type="warning" effect="plain" class="scope-tag">
仅统计自己所属公司(货主)的数据
</el-tag>
</div>
</div>
<div class="dash-actions">
@ -373,6 +391,9 @@ onMounted(fetchReport)
font-size: 12px;
color: var(--el-text-color-secondary);
}
.scope-tag {
margin-left: 8px;
}
.dash-actions {
display: flex;
align-items: center;

View File

@ -578,11 +578,12 @@ onMounted(() => {
v-model="form.subsidiary_id"
placeholder="请选择所属货主(下属公司)"
filterable
:disabled="editId != null && isCompanyScope"
:disabled="editId != null"
style="width: 100%"
>
<el-option v-for="s in subsidiaryOptions" :key="s.id" :label="s.name" :value="s.id" />
</el-select>
<div v-if="editId != null" class="owner-tip">店铺创建后不可更改所属货主</div>
</el-form-item>
<el-form-item label="店铺名称" prop="name">
<el-input v-model="form.name" placeholder="请输入店铺名称" />
@ -703,6 +704,11 @@ onMounted(() => {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.owner-tip {
font-size: 12px;
line-height: 1.4;
color: var(--el-text-color-secondary);
}
.detail-tabs {
flex: 1;
min-height: 0;