feat: 商品属性(分类/品牌/单位)关联货主

- product_categories / product_brands / product_units 新增 subsidiary_id(NULL 表示主体级、全集团共用)
- 列表与下拉按货主范围过滤:货主权限仅可见「主体级 + 自己所属公司」,并支持按货主筛选
- 新增/编辑支持选择货主,货主权限只能选主体或自己所属公司;同货主范围内名称唯一
- 详情/更新/删除对越权属性返回 403;导出新增货主列并收窄到可见范围

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-05 02:15:25 +08:00
parent b59ca6a0a8
commit 9c9a81f168
15 changed files with 536 additions and 93 deletions

View File

@ -603,6 +603,9 @@ module.exports = {
productAttributeItem: { productAttributeItem: {
id: { type: 'integer', description: '主键' }, id: { type: 'integer', description: '主键' },
principal_id: { type: 'integer', description: '所属主体ID' }, principal_id: { type: 'integer', description: '所属主体ID' },
subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);null 表示主体级(全集团共用)' },
subsidiary_name: { type: 'string', description: '所属货主名称' },
subsidiary: { type: 'principalSubsidiaryRef', description: '所属货主(下属公司)' },
name: { type: 'string', description: '名称(分类名/品牌名/单位名)' }, name: { type: 'string', description: '名称(分类名/品牌名/单位名)' },
code: { type: 'string', description: '编码' }, code: { type: 'string', description: '编码' },
status: { type: 'integer', description: '状态:1启用 0禁用' }, status: { type: 'integer', description: '状态:1启用 0禁用' },
@ -620,6 +623,7 @@ module.exports = {
productUnitListResponse: buildListResponse('productUnitPage'), productUnitListResponse: buildListResponse('productUnitPage'),
createProductCategoryRequest: { createProductCategoryRequest: {
principal_id: { type: 'integer', description: '所属主体ID(系统按当前主体注入,可不传)' }, principal_id: { type: 'integer', description: '所属主体ID(系统按当前主体注入,可不传)' },
subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);不传/传 null 表示主体级;所在公司权限只能选自己所属公司' },
name: { type: 'string', required: true, description: '分类名称,主体内唯一' }, name: { type: 'string', required: true, description: '分类名称,主体内唯一' },
code: { type: 'string', description: '分类编码' }, code: { type: 'string', description: '分类编码' },
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
@ -627,7 +631,8 @@ module.exports = {
remark: { type: 'string', description: '备注' }, remark: { type: 'string', description: '备注' },
}, },
updateProductCategoryRequest: { updateProductCategoryRequest: {
name: { type: 'string', description: '分类名称,主体内唯一' }, subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);不传表示主体级' },
name: { type: 'string', description: '分类名称,同货主范围内唯一' },
code: { type: 'string', description: '分类编码' }, code: { type: 'string', description: '分类编码' },
status: { type: 'integer', description: '状态:1启用 0禁用' }, status: { type: 'integer', description: '状态:1启用 0禁用' },
sort: { type: 'integer', description: '排序' }, sort: { type: 'integer', description: '排序' },
@ -635,6 +640,7 @@ module.exports = {
}, },
createProductBrandRequest: { createProductBrandRequest: {
principal_id: { type: 'integer', description: '所属主体ID(系统按当前主体注入,可不传)' }, principal_id: { type: 'integer', description: '所属主体ID(系统按当前主体注入,可不传)' },
subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);不传/传 null 表示主体级;所在公司权限只能选自己所属公司' },
name: { type: 'string', required: true, description: '品牌名称,主体内唯一' }, name: { type: 'string', required: true, description: '品牌名称,主体内唯一' },
code: { type: 'string', description: '品牌编码' }, code: { type: 'string', description: '品牌编码' },
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
@ -642,7 +648,8 @@ module.exports = {
remark: { type: 'string', description: '备注' }, remark: { type: 'string', description: '备注' },
}, },
updateProductBrandRequest: { updateProductBrandRequest: {
name: { type: 'string', description: '品牌名称,主体内唯一' }, subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);不传表示主体级' },
name: { type: 'string', description: '品牌名称,同货主范围内唯一' },
code: { type: 'string', description: '品牌编码' }, code: { type: 'string', description: '品牌编码' },
status: { type: 'integer', description: '状态:1启用 0禁用' }, status: { type: 'integer', description: '状态:1启用 0禁用' },
sort: { type: 'integer', description: '排序' }, sort: { type: 'integer', description: '排序' },
@ -650,6 +657,7 @@ module.exports = {
}, },
createProductUnitRequest: { createProductUnitRequest: {
principal_id: { type: 'integer', description: '所属主体ID(系统按当前主体注入,可不传)' }, principal_id: { type: 'integer', description: '所属主体ID(系统按当前主体注入,可不传)' },
subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);不传/传 null 表示主体级;所在公司权限只能选自己所属公司' },
name: { type: 'string', required: true, description: '单位名称,主体内唯一' }, name: { type: 'string', required: true, description: '单位名称,主体内唯一' },
code: { type: 'string', description: '单位编码' }, code: { type: 'string', description: '单位编码' },
status: { type: 'integer', description: '状态:1启用 0禁用,默认1' }, status: { type: 'integer', description: '状态:1启用 0禁用,默认1' },
@ -657,7 +665,8 @@ module.exports = {
remark: { type: 'string', description: '备注' }, remark: { type: 'string', description: '备注' },
}, },
updateProductUnitRequest: { updateProductUnitRequest: {
name: { type: 'string', description: '单位名称,主体内唯一' }, subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);不传表示主体级' },
name: { type: 'string', description: '单位名称,同货主范围内唯一' },
code: { type: 'string', description: '单位编码' }, code: { type: 'string', description: '单位编码' },
status: { type: 'integer', description: '状态:1启用 0禁用' }, status: { type: 'integer', description: '状态:1启用 0禁用' },
sort: { type: 'integer', description: '排序' }, sort: { type: 'integer', description: '排序' },

View File

@ -3,6 +3,12 @@
const { Controller } = require('egg'); const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination'); const { parsePagination, buildPageResult } = require('../lib/pagination');
const { attachUsedCount } = require('../lib/attributeUsage'); const { attachUsedCount } = require('../lib/attributeUsage');
const {
resolveScope,
visibilityWhere,
resolveSubsidiaryValue,
isVisible,
} = require('../lib/productAttributeScope');
/** 商品表引用品牌主键的字段名 */ /** 商品表引用品牌主键的字段名 */
const COLUMN = 'brand_id'; const COLUMN = 'brand_id';
@ -27,32 +33,44 @@ class ProductBrandController extends Controller {
const { ctx } = this; const { ctx } = this;
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { keyword, status } = ctx.query; const { keyword, status, subsidiary_id: subsidiaryId } = ctx.query;
const principalId = ctx.state.principalId; const principalId = ctx.state.principalId;
const where = { // 货主范围:集团权限看全部;所在公司权限仅看「主体级(无货主)+ 自己所属公司」
[Op.or]: [ const scope = await resolveScope(ctx);
{ principal_id: principalId }, const andConditions = [
{ is_system: 1 }, { [Op.or]: [{ principal_id: principalId }, { is_system: 1 }] },
], ];
}; const visible = visibilityWhere(ctx, scope);
if (visible) andConditions.push(visible);
if (keyword) { if (keyword) {
where[Op.or] = [ andConditions.push({
{ name: { [Op.like]: `%${keyword}%` } }, [Op.or]: [
{ code: { [Op.like]: `%${keyword}%` } }, { name: { [Op.like]: `%${keyword}%` } },
]; { code: { [Op.like]: `%${keyword}%` } },
],
});
}
if (status !== undefined && status !== '') andConditions.push({ status: Number(status) });
// 货主筛选:0 表示主体级(无货主)
if (subsidiaryId !== undefined && subsidiaryId !== '') {
andConditions.push({ subsidiary_id: Number(subsidiaryId) === 0 ? null : Number(subsidiaryId) });
} }
if (status !== undefined && status !== '') where.status = Number(status);
const { count, rows } = await ctx.model.ProductBrand.findAndCountAll({ const { count, rows } = await ctx.model.ProductBrand.findAndCountAll({
where, where: { [Op.and]: andConditions },
offset, offset,
limit, limit,
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
],
}); });
const list = await attachUsedCount(ctx, COLUMN, rows); const list = await attachUsedCount(ctx, COLUMN, rows);
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; // 附加扁平的货主名称(主体级为空串)
const data = list.map(row => ({ ...row, subsidiary_name: row.subsidiary ? row.subsidiary.name : '' }));
ctx.body = { code: 0, message: 'success', data: buildPageResult(data, count, { page, pageSize }) };
} }
/** /**
@ -66,15 +84,14 @@ class ProductBrandController extends Controller {
const { ctx } = this; const { ctx } = this;
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
const principalId = ctx.state.principalId; const principalId = ctx.state.principalId;
const scope = await resolveScope(ctx);
const andConditions = [{ [Op.or]: [{ principal_id: principalId }, { is_system: 1 }] }];
const visible = visibilityWhere(ctx, scope);
if (visible) andConditions.push(visible);
const rows = await ctx.model.ProductBrand.findAll({ const rows = await ctx.model.ProductBrand.findAll({
where: { where: { status: 1, [Op.and]: andConditions },
status: 1, attributes: [ 'id', 'name', 'code', 'subsidiary_id' ],
[Op.or]: [
{ principal_id: principalId },
{ is_system: 1 },
],
},
attributes: [ 'id', 'name', 'code' ],
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
}); });
ctx.body = { code: 0, message: 'success', data: rows }; ctx.body = { code: 0, message: 'success', data: rows };
@ -89,13 +106,24 @@ class ProductBrandController extends Controller {
*/ */
async show() { async show() {
const { ctx } = this; const { ctx } = this;
const item = await ctx.model.ProductBrand.findByPk(ctx.params.id); const item = await ctx.model.ProductBrand.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
],
});
if (!item) { if (!item) {
ctx.status = 404; ctx.status = 404;
ctx.body = { code: 404, message: '商品品牌不存在' }; ctx.body = { code: 404, message: '商品品牌不存在' };
return; return;
} }
ctx.body = { code: 0, message: 'success', data: item }; if (!isVisible(item, await resolveScope(ctx))) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可查看自己所属公司或主体级的商品品牌' };
return;
}
const plain = item.toJSON();
plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : '';
ctx.body = { code: 0, message: 'success', data: plain };
} }
/** /**
@ -119,11 +147,21 @@ class ProductBrandController extends Controller {
} }
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
// 自定义不可与系统/本主体已有的重名:若已存在(系统或本主体)则直接复用,不再新增 // 货主为空表示主体级;所在公司权限只能选主体或自己所属公司
const scope = await resolveScope(ctx);
const subsidiary = await resolveSubsidiaryValue(ctx, scope, body.subsidiary_id);
if (!subsidiary.ok) {
ctx.status = subsidiary.forbidden ? 403 : 400;
ctx.body = { code: ctx.status, message: subsidiary.message };
return;
}
// 同一货主范围内不可重名(系统数据可直接复用)
const exist = await ctx.model.ProductBrand.findOne({ const exist = await ctx.model.ProductBrand.findOne({
where: { where: {
name, name,
[Op.or]: [ { principal_id: principalId }, { is_system: 1 } ], subsidiary_id: subsidiary.value,
[Op.or]: [{ principal_id: principalId }, { is_system: 1 }],
}, },
}); });
if (exist) { if (exist) {
@ -131,7 +169,13 @@ class ProductBrandController extends Controller {
return; return;
} }
const item = await ctx.model.ProductBrand.create({ ...body, principal_id: principalId, name, is_system: 0 }); const item = await ctx.model.ProductBrand.create({
...body,
principal_id: principalId,
subsidiary_id: subsidiary.value,
name,
is_system: 0,
});
ctx.body = { code: 0, message: 'success', data: { id: item.id } }; ctx.body = { code: 0, message: 'success', data: { id: item.id } };
} }
@ -159,8 +203,22 @@ class ProductBrandController extends Controller {
return; return;
} }
const scope = await resolveScope(ctx);
if (!isVisible(item, scope)) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可修改自己所属公司或主体级的商品品牌' };
return;
}
const body = { ...(ctx.request.body || {}) }; const body = { ...(ctx.request.body || {}) };
delete body.is_system; delete body.is_system;
const subsidiary = await resolveSubsidiaryValue(ctx, scope, body.subsidiary_id);
if (!subsidiary.ok) {
ctx.status = subsidiary.forbidden ? 403 : 400;
ctx.body = { code: ctx.status, message: subsidiary.message };
return;
}
body.subsidiary_id = subsidiary.value;
if (body.name !== undefined) { if (body.name !== undefined) {
const name = String(body.name).trim(); const name = String(body.name).trim();
if (!name) { if (!name) {
@ -168,7 +226,9 @@ class ProductBrandController extends Controller {
ctx.body = { code: 400, message: '品牌名称不能为空' }; ctx.body = { code: 400, message: '品牌名称不能为空' };
return; return;
} }
const exist = await ctx.model.ProductBrand.findOne({ where: { principal_id: item.principal_id, name } }); const exist = await ctx.model.ProductBrand.findOne({
where: { principal_id: item.principal_id, name, subsidiary_id: subsidiary.value },
});
if (exist && Number(exist.id) !== Number(item.id)) { if (exist && Number(exist.id) !== Number(item.id)) {
ctx.status = 400; ctx.status = 400;
ctx.body = { code: 400, message: `品牌「${name}」已存在` }; ctx.body = { code: 400, message: `品牌「${name}」已存在` };
@ -204,6 +264,12 @@ class ProductBrandController extends Controller {
return; return;
} }
if (!isVisible(item, await resolveScope(ctx))) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可删除自己所属公司或主体级的商品品牌' };
return;
}
const used = await ctx.model.Product.count({ where: { principal_id: item.principal_id, brand_id: item.id } }); const used = await ctx.model.Product.count({ where: { principal_id: item.principal_id, brand_id: item.id } });
if (used > 0) { if (used > 0) {
ctx.status = 400; ctx.status = 400;

View File

@ -3,6 +3,12 @@
const { Controller } = require('egg'); const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination'); const { parsePagination, buildPageResult } = require('../lib/pagination');
const { attachUsedCount } = require('../lib/attributeUsage'); const { attachUsedCount } = require('../lib/attributeUsage');
const {
resolveScope,
visibilityWhere,
resolveSubsidiaryValue,
isVisible,
} = require('../lib/productAttributeScope');
/** 商品表引用分类主键的字段名 */ /** 商品表引用分类主键的字段名 */
const COLUMN = 'category_id'; const COLUMN = 'category_id';
@ -27,32 +33,44 @@ class ProductCategoryController extends Controller {
const { ctx } = this; const { ctx } = this;
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { keyword, status } = ctx.query; const { keyword, status, subsidiary_id: subsidiaryId } = ctx.query;
const principalId = ctx.state.principalId; const principalId = ctx.state.principalId;
const where = { // 货主范围:集团权限看全部;所在公司权限仅看「主体级(无货主)+ 自己所属公司」
[Op.or]: [ const scope = await resolveScope(ctx);
{ principal_id: principalId }, const andConditions = [
{ is_system: 1 }, { [Op.or]: [{ principal_id: principalId }, { is_system: 1 }] },
], ];
}; const visible = visibilityWhere(ctx, scope);
if (visible) andConditions.push(visible);
if (keyword) { if (keyword) {
where[Op.or] = [ andConditions.push({
{ name: { [Op.like]: `%${keyword}%` } }, [Op.or]: [
{ code: { [Op.like]: `%${keyword}%` } }, { name: { [Op.like]: `%${keyword}%` } },
]; { code: { [Op.like]: `%${keyword}%` } },
],
});
}
if (status !== undefined && status !== '') andConditions.push({ status: Number(status) });
// 货主筛选:0 表示主体级(无货主)
if (subsidiaryId !== undefined && subsidiaryId !== '') {
andConditions.push({ subsidiary_id: Number(subsidiaryId) === 0 ? null : Number(subsidiaryId) });
} }
if (status !== undefined && status !== '') where.status = Number(status);
const { count, rows } = await ctx.model.ProductCategory.findAndCountAll({ const { count, rows } = await ctx.model.ProductCategory.findAndCountAll({
where, where: { [Op.and]: andConditions },
offset, offset,
limit, limit,
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
],
}); });
const list = await attachUsedCount(ctx, COLUMN, rows); const list = await attachUsedCount(ctx, COLUMN, rows);
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; // 附加扁平的货主名称(主体级为空串)
const data = list.map(row => ({ ...row, subsidiary_name: row.subsidiary ? row.subsidiary.name : '' }));
ctx.body = { code: 0, message: 'success', data: buildPageResult(data, count, { page, pageSize }) };
} }
/** /**
@ -66,15 +84,14 @@ class ProductCategoryController extends Controller {
const { ctx } = this; const { ctx } = this;
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
const principalId = ctx.state.principalId; const principalId = ctx.state.principalId;
const scope = await resolveScope(ctx);
const andConditions = [{ [Op.or]: [{ principal_id: principalId }, { is_system: 1 }] }];
const visible = visibilityWhere(ctx, scope);
if (visible) andConditions.push(visible);
const rows = await ctx.model.ProductCategory.findAll({ const rows = await ctx.model.ProductCategory.findAll({
where: { where: { status: 1, [Op.and]: andConditions },
status: 1, attributes: [ 'id', 'name', 'code', 'subsidiary_id' ],
[Op.or]: [
{ principal_id: principalId },
{ is_system: 1 },
],
},
attributes: [ 'id', 'name', 'code' ],
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
}); });
ctx.body = { code: 0, message: 'success', data: rows }; ctx.body = { code: 0, message: 'success', data: rows };
@ -89,13 +106,24 @@ class ProductCategoryController extends Controller {
*/ */
async show() { async show() {
const { ctx } = this; const { ctx } = this;
const item = await ctx.model.ProductCategory.findByPk(ctx.params.id); const item = await ctx.model.ProductCategory.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
],
});
if (!item) { if (!item) {
ctx.status = 404; ctx.status = 404;
ctx.body = { code: 404, message: '商品分类不存在' }; ctx.body = { code: 404, message: '商品分类不存在' };
return; return;
} }
ctx.body = { code: 0, message: 'success', data: item }; if (!isVisible(item, await resolveScope(ctx))) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可查看自己所属公司或主体级的商品分类' };
return;
}
const plain = item.toJSON();
plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : '';
ctx.body = { code: 0, message: 'success', data: plain };
} }
/** /**
@ -119,11 +147,21 @@ class ProductCategoryController extends Controller {
} }
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
// 自定义不可与系统/本主体已有的重名:若已存在(系统或本主体)则直接复用,不再新增 // 货主为空表示主体级;所在公司权限只能选主体或自己所属公司
const scope = await resolveScope(ctx);
const subsidiary = await resolveSubsidiaryValue(ctx, scope, body.subsidiary_id);
if (!subsidiary.ok) {
ctx.status = subsidiary.forbidden ? 403 : 400;
ctx.body = { code: ctx.status, message: subsidiary.message };
return;
}
// 同一货主范围内不可重名(系统数据可直接复用)
const exist = await ctx.model.ProductCategory.findOne({ const exist = await ctx.model.ProductCategory.findOne({
where: { where: {
name, name,
[Op.or]: [ { principal_id: principalId }, { is_system: 1 } ], subsidiary_id: subsidiary.value,
[Op.or]: [{ principal_id: principalId }, { is_system: 1 }],
}, },
}); });
if (exist) { if (exist) {
@ -131,7 +169,13 @@ class ProductCategoryController extends Controller {
return; return;
} }
const item = await ctx.model.ProductCategory.create({ ...body, principal_id: principalId, name, is_system: 0 }); const item = await ctx.model.ProductCategory.create({
...body,
principal_id: principalId,
subsidiary_id: subsidiary.value,
name,
is_system: 0,
});
ctx.body = { code: 0, message: 'success', data: { id: item.id } }; ctx.body = { code: 0, message: 'success', data: { id: item.id } };
} }
@ -159,8 +203,22 @@ class ProductCategoryController extends Controller {
return; return;
} }
const scope = await resolveScope(ctx);
if (!isVisible(item, scope)) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可修改自己所属公司或主体级的商品分类' };
return;
}
const body = { ...(ctx.request.body || {}) }; const body = { ...(ctx.request.body || {}) };
delete body.is_system; delete body.is_system;
const subsidiary = await resolveSubsidiaryValue(ctx, scope, body.subsidiary_id);
if (!subsidiary.ok) {
ctx.status = subsidiary.forbidden ? 403 : 400;
ctx.body = { code: ctx.status, message: subsidiary.message };
return;
}
body.subsidiary_id = subsidiary.value;
if (body.name !== undefined) { if (body.name !== undefined) {
const name = String(body.name).trim(); const name = String(body.name).trim();
if (!name) { if (!name) {
@ -168,7 +226,9 @@ class ProductCategoryController extends Controller {
ctx.body = { code: 400, message: '分类名称不能为空' }; ctx.body = { code: 400, message: '分类名称不能为空' };
return; return;
} }
const exist = await ctx.model.ProductCategory.findOne({ where: { principal_id: item.principal_id, name } }); const exist = await ctx.model.ProductCategory.findOne({
where: { principal_id: item.principal_id, name, subsidiary_id: subsidiary.value },
});
if (exist && Number(exist.id) !== Number(item.id)) { if (exist && Number(exist.id) !== Number(item.id)) {
ctx.status = 400; ctx.status = 400;
ctx.body = { code: 400, message: `分类「${name}」已存在` }; ctx.body = { code: 400, message: `分类「${name}」已存在` };
@ -204,6 +264,12 @@ class ProductCategoryController extends Controller {
return; return;
} }
if (!isVisible(item, await resolveScope(ctx))) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可删除自己所属公司或主体级的商品分类' };
return;
}
const used = await ctx.model.Product.count({ where: { principal_id: item.principal_id, category_id: item.id } }); const used = await ctx.model.Product.count({ where: { principal_id: item.principal_id, category_id: item.id } });
if (used > 0) { if (used > 0) {
ctx.status = 400; ctx.status = 400;

View File

@ -3,6 +3,12 @@
const { Controller } = require('egg'); const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination'); const { parsePagination, buildPageResult } = require('../lib/pagination');
const { attachUsedCount } = require('../lib/attributeUsage'); const { attachUsedCount } = require('../lib/attributeUsage');
const {
resolveScope,
visibilityWhere,
resolveSubsidiaryValue,
isVisible,
} = require('../lib/productAttributeScope');
/** 商品表引用单位主键的字段名 */ /** 商品表引用单位主键的字段名 */
const COLUMN = 'unit_id'; const COLUMN = 'unit_id';
@ -27,32 +33,44 @@ class ProductUnitController extends Controller {
const { ctx } = this; const { ctx } = this;
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query); const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { keyword, status } = ctx.query; const { keyword, status, subsidiary_id: subsidiaryId } = ctx.query;
const principalId = ctx.state.principalId; const principalId = ctx.state.principalId;
const where = { // 货主范围:集团权限看全部;所在公司权限仅看「主体级(无货主)+ 自己所属公司」
[Op.or]: [ const scope = await resolveScope(ctx);
{ principal_id: principalId }, const andConditions = [
{ is_system: 1 }, { [Op.or]: [{ principal_id: principalId }, { is_system: 1 }] },
], ];
}; const visible = visibilityWhere(ctx, scope);
if (visible) andConditions.push(visible);
if (keyword) { if (keyword) {
where[Op.or] = [ andConditions.push({
{ name: { [Op.like]: `%${keyword}%` } }, [Op.or]: [
{ code: { [Op.like]: `%${keyword}%` } }, { name: { [Op.like]: `%${keyword}%` } },
]; { code: { [Op.like]: `%${keyword}%` } },
],
});
}
if (status !== undefined && status !== '') andConditions.push({ status: Number(status) });
// 货主筛选:0 表示主体级(无货主)
if (subsidiaryId !== undefined && subsidiaryId !== '') {
andConditions.push({ subsidiary_id: Number(subsidiaryId) === 0 ? null : Number(subsidiaryId) });
} }
if (status !== undefined && status !== '') where.status = Number(status);
const { count, rows } = await ctx.model.ProductUnit.findAndCountAll({ const { count, rows } = await ctx.model.ProductUnit.findAndCountAll({
where, where: { [Op.and]: andConditions },
offset, offset,
limit, limit,
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
],
}); });
const list = await attachUsedCount(ctx, COLUMN, rows); const list = await attachUsedCount(ctx, COLUMN, rows);
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; // 附加扁平的货主名称(主体级为空串)
const data = list.map(row => ({ ...row, subsidiary_name: row.subsidiary ? row.subsidiary.name : '' }));
ctx.body = { code: 0, message: 'success', data: buildPageResult(data, count, { page, pageSize }) };
} }
/** /**
@ -66,15 +84,14 @@ class ProductUnitController extends Controller {
const { ctx } = this; const { ctx } = this;
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
const principalId = ctx.state.principalId; const principalId = ctx.state.principalId;
const scope = await resolveScope(ctx);
const andConditions = [{ [Op.or]: [{ principal_id: principalId }, { is_system: 1 }] }];
const visible = visibilityWhere(ctx, scope);
if (visible) andConditions.push(visible);
const rows = await ctx.model.ProductUnit.findAll({ const rows = await ctx.model.ProductUnit.findAll({
where: { where: { status: 1, [Op.and]: andConditions },
status: 1, attributes: [ 'id', 'name', 'code', 'subsidiary_id' ],
[Op.or]: [
{ principal_id: principalId },
{ is_system: 1 },
],
},
attributes: [ 'id', 'name', 'code' ],
order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]], order: [[ 'sort', 'ASC' ], [ 'id', 'ASC' ]],
}); });
ctx.body = { code: 0, message: 'success', data: rows }; ctx.body = { code: 0, message: 'success', data: rows };
@ -89,13 +106,24 @@ class ProductUnitController extends Controller {
*/ */
async show() { async show() {
const { ctx } = this; const { ctx } = this;
const item = await ctx.model.ProductUnit.findByPk(ctx.params.id); const item = await ctx.model.ProductUnit.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
],
});
if (!item) { if (!item) {
ctx.status = 404; ctx.status = 404;
ctx.body = { code: 404, message: '商品单位不存在' }; ctx.body = { code: 404, message: '商品单位不存在' };
return; return;
} }
ctx.body = { code: 0, message: 'success', data: item }; if (!isVisible(item, await resolveScope(ctx))) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可查看自己所属公司或主体级的商品单位' };
return;
}
const plain = item.toJSON();
plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : '';
ctx.body = { code: 0, message: 'success', data: plain };
} }
/** /**
@ -119,11 +147,21 @@ class ProductUnitController extends Controller {
} }
const Op = this.app.Sequelize.Op; const Op = this.app.Sequelize.Op;
// 自定义不可与系统/本主体已有的重名:若已存在(系统或本主体)则直接复用,不再新增 // 货主为空表示主体级;所在公司权限只能选主体或自己所属公司
const scope = await resolveScope(ctx);
const subsidiary = await resolveSubsidiaryValue(ctx, scope, body.subsidiary_id);
if (!subsidiary.ok) {
ctx.status = subsidiary.forbidden ? 403 : 400;
ctx.body = { code: ctx.status, message: subsidiary.message };
return;
}
// 同一货主范围内不可重名(系统数据可直接复用)
const exist = await ctx.model.ProductUnit.findOne({ const exist = await ctx.model.ProductUnit.findOne({
where: { where: {
name, name,
[Op.or]: [ { principal_id: principalId }, { is_system: 1 } ], subsidiary_id: subsidiary.value,
[Op.or]: [{ principal_id: principalId }, { is_system: 1 }],
}, },
}); });
if (exist) { if (exist) {
@ -131,7 +169,13 @@ class ProductUnitController extends Controller {
return; return;
} }
const item = await ctx.model.ProductUnit.create({ ...body, principal_id: principalId, name, is_system: 0 }); const item = await ctx.model.ProductUnit.create({
...body,
principal_id: principalId,
subsidiary_id: subsidiary.value,
name,
is_system: 0,
});
ctx.body = { code: 0, message: 'success', data: { id: item.id } }; ctx.body = { code: 0, message: 'success', data: { id: item.id } };
} }
@ -159,8 +203,22 @@ class ProductUnitController extends Controller {
return; return;
} }
const scope = await resolveScope(ctx);
if (!isVisible(item, scope)) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可修改自己所属公司或主体级的商品单位' };
return;
}
const body = { ...(ctx.request.body || {}) }; const body = { ...(ctx.request.body || {}) };
delete body.is_system; delete body.is_system;
const subsidiary = await resolveSubsidiaryValue(ctx, scope, body.subsidiary_id);
if (!subsidiary.ok) {
ctx.status = subsidiary.forbidden ? 403 : 400;
ctx.body = { code: ctx.status, message: subsidiary.message };
return;
}
body.subsidiary_id = subsidiary.value;
if (body.name !== undefined) { if (body.name !== undefined) {
const name = String(body.name).trim(); const name = String(body.name).trim();
if (!name) { if (!name) {
@ -168,7 +226,9 @@ class ProductUnitController extends Controller {
ctx.body = { code: 400, message: '单位名称不能为空' }; ctx.body = { code: 400, message: '单位名称不能为空' };
return; return;
} }
const exist = await ctx.model.ProductUnit.findOne({ where: { principal_id: item.principal_id, name } }); const exist = await ctx.model.ProductUnit.findOne({
where: { principal_id: item.principal_id, name, subsidiary_id: subsidiary.value },
});
if (exist && Number(exist.id) !== Number(item.id)) { if (exist && Number(exist.id) !== Number(item.id)) {
ctx.status = 400; ctx.status = 400;
ctx.body = { code: 400, message: `单位「${name}」已存在` }; ctx.body = { code: 400, message: `单位「${name}」已存在` };
@ -204,6 +264,12 @@ class ProductUnitController extends Controller {
return; return;
} }
if (!isVisible(item, await resolveScope(ctx))) {
ctx.status = 403;
ctx.body = { code: 403, message: '仅可删除自己所属公司或主体级的商品单位' };
return;
}
const used = await ctx.model.Product.count({ where: { principal_id: item.principal_id, unit_id: item.id } }); const used = await ctx.model.Product.count({ where: { principal_id: item.principal_id, unit_id: item.id } });
if (used > 0) { if (used > 0) {
ctx.status = 400; ctx.status = 400;

View File

@ -0,0 +1,77 @@
'use strict';
/**
* 商品属性(分类 / 品牌 / 单位)的货主(下属公司)作用域辅助。
*
* 数据规则:
* - subsidiary_id 为 NULL 表示「主体级」属性,全集团可见可用;
* - 填写 subsidiary_id 则为该下属公司(货主)私有;
* - 集团权限可见/可维护全部;所在公司权限仅可见「主体级 + 自己所属公司」,
* 且只能把属性建到「主体级」或自己所属公司。
*/
/**
* 解析当前账号在该主体下的可见范围
* @param {Egg.Context} ctx egg context(需 principalCheck 已写入 ctx.state.principalId)
* @return {Promise<{isGroup: boolean, ownCompanyIds: Array<number>}>} 范围信息
*/
async function resolveScope(ctx) {
const access = await ctx.service.access.resolve(ctx.userId, ctx.state.principalId);
return { isGroup: !!access.isGroup, ownCompanyIds: (access.ownCompanyIds || []).map(Number) };
}
/**
* 组装「主体级 + 自己所属公司」的可见条件(集团权限返回 null,表示不限制)
* @param {Object} ctx egg context
* @param {Object} scope resolveScope 的结果
* @param {string} column 表别名限定列名,默认 subsidiary_id
* @return {Object|null} Sequelize where 片段
*/
function visibilityWhere(ctx, scope, column = 'subsidiary_id') {
if (scope.isGroup) return null;
const Op = ctx.app.Sequelize.Op;
const or = [{ [column]: null }];
if (scope.ownCompanyIds.length) or.push({ [column]: { [Op.in]: scope.ownCompanyIds } });
return { [Op.or]: or };
}
/**
* 校验并归一化前端传入的 subsidiary_id
* @param {Object} ctx egg context
* @param {Object} scope resolveScope 的结果
* @param {number|string|null|undefined} value 前端传入的 subsidiary_id
* @return {Promise<{ok: boolean, value?: number|null, message?: string}>} 校验结果(value 为 null 即主体级)
*/
async function resolveSubsidiaryValue(ctx, scope, value) {
// 空值表示主体级:所在公司权限同样允许
if (value === undefined || value === null || value === '') return { ok: true, value: null };
const id = Number(value);
if (!Number.isInteger(id) || id <= 0) return { ok: false, message: '所属货主不合法' };
const subsidiary = await ctx.model.PrincipalSubsidiary.findOne({
where: { id, principal_id: ctx.state.principalId },
attributes: [ 'id' ],
});
if (!subsidiary) return { ok: false, message: '所属货主不存在或不属于当前集团' };
if (!scope.isGroup && !scope.ownCompanyIds.includes(id)) {
return { ok: false, forbidden: true, message: '只能选择自己所属公司或主体' };
}
return { ok: true, value: id };
}
/**
* 判断属性记录是否在当前账号可见范围内
* @param {Object} item 属性 model 实例
* @param {Object} scope resolveScope 的结果
* @return {boolean} 是否可见
*/
function isVisible(item, scope) {
if (!item) return false;
if (scope.isGroup) return true;
if (item.subsidiary_id === null || item.subsidiary_id === undefined) return true;
return scope.ownCompanyIds.includes(Number(item.subsidiary_id));
}
module.exports = { resolveScope, visibilityWhere, resolveSubsidiaryValue, isVisible };

View File

@ -12,6 +12,7 @@ module.exports = app => {
const ProductBrand = app.model.define('product_brand', { const ProductBrand = app.model.define('product_brand', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
subsidiary_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '所属货主(下属公司ID);NULL 表示主体级(全集团共用)' },
name: { type: STRING(100), allowNull: false, comment: '品牌名称' }, name: { type: STRING(100), allowNull: false, comment: '品牌名称' },
code: { type: STRING(50), comment: '品牌编码' }, code: { type: STRING(50), comment: '品牌编码' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
@ -27,6 +28,7 @@ module.exports = app => {
ProductBrand.associate = () => { ProductBrand.associate = () => {
app.model.ProductBrand.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); app.model.ProductBrand.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
app.model.ProductBrand.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' });
}; };
return ProductBrand; return ProductBrand;

View File

@ -12,6 +12,7 @@ module.exports = app => {
const ProductCategory = app.model.define('product_category', { const ProductCategory = app.model.define('product_category', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
subsidiary_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '所属货主(下属公司ID);NULL 表示主体级(全集团共用)' },
name: { type: STRING(100), allowNull: false, comment: '分类名称' }, name: { type: STRING(100), allowNull: false, comment: '分类名称' },
code: { type: STRING(50), comment: '分类编码' }, code: { type: STRING(50), comment: '分类编码' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
@ -27,6 +28,7 @@ module.exports = app => {
ProductCategory.associate = () => { ProductCategory.associate = () => {
app.model.ProductCategory.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); app.model.ProductCategory.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
app.model.ProductCategory.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' });
}; };
return ProductCategory; return ProductCategory;

View File

@ -12,6 +12,7 @@ module.exports = app => {
const ProductUnit = app.model.define('product_unit', { const ProductUnit = app.model.define('product_unit', {
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
subsidiary_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '所属货主(下属公司ID);NULL 表示主体级(全集团共用)' },
name: { type: STRING(100), allowNull: false, comment: '单位名称' }, name: { type: STRING(100), allowNull: false, comment: '单位名称' },
code: { type: STRING(50), comment: '单位编码' }, code: { type: STRING(50), comment: '单位编码' },
status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
@ -27,6 +28,7 @@ module.exports = app => {
ProductUnit.associate = () => { ProductUnit.associate = () => {
app.model.ProductUnit.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); app.model.ProductUnit.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
app.model.ProductUnit.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' });
}; };
return ProductUnit; return ProductUnit;

View File

@ -44,7 +44,8 @@ class ExportTaskService extends Service {
* @return {Promise<Object>} 任务实例 * @return {Promise<Object>} 任务实例
*/ */
async submit(type, filters, principalId, userId) { async submit(type, filters, principalId, userId) {
const { sql } = buildExportSql(type, filters, principalId, userId); const access = await this.ctx.service.access.resolve(userId, principalId);
const { sql } = buildExportSql(type, filters, principalId, userId, access);
return this.ctx.model.ExportTask.create({ return this.ctx.model.ExportTask.create({
principal_id: principalId, principal_id: principalId,
type, type,

View File

@ -405,6 +405,11 @@ const ATTR_COLUMNS = [
{ key: 'id', header: 'ID' }, { key: 'id', header: 'ID' },
{ key: 'name', header: '名称' }, { key: 'name', header: '名称' },
{ key: 'code', header: '编码' }, { key: 'code', header: '编码' },
{
key: 'subsidiary_name',
header: '货主',
expr: '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id)',
},
{ key: 'status', header: '状态', format: labels(ENABLE_MAP) }, { key: 'status', header: '状态', format: labels(ENABLE_MAP) },
{ key: 'sort', header: '排序' }, { key: 'sort', header: '排序' },
{ key: 'is_system', header: '数据来源', format: labels(IS_SYSTEM_MAP) }, { key: 'is_system', header: '数据来源', format: labels(IS_SYSTEM_MAP) },
@ -606,6 +611,7 @@ function attrType(label, table) {
label, label,
filters: [ filters: [
{ key: 'keyword', label: '关键词', type: 'text', placeholder: '名称 / 编码' }, { key: 'keyword', label: '关键词', type: 'text', placeholder: '名称 / 编码' },
{ key: 'subsidiary_id', label: '货主', type: 'subsidiary' },
{ key: 'status', label: '状态', type: 'select', options: ENABLE_OPTIONS }, { key: 'status', label: '状态', type: 'select', options: ENABLE_OPTIONS },
{ key: 'is_system', label: '数据来源', type: 'select', options: IS_SYSTEM_OPTIONS }, { key: 'is_system', label: '数据来源', type: 'select', options: IS_SYSTEM_OPTIONS },
], ],
@ -615,6 +621,23 @@ function attrType(label, table) {
.kw([ 't.name', 't.code' ], f.keyword) .kw([ 't.name', 't.code' ], f.keyword)
.eq('t.status', f.status) .eq('t.status', f.status)
.eq('t.is_system', f.is_system); .eq('t.is_system', f.is_system);
// 货主筛选:0 表示主体级(无货主)
if (!blank(f.subsidiary_id)) {
if (Number(f.subsidiary_id) === 0) wh.raw('t.subsidiary_id IS NULL');
else wh.eq('t.subsidiary_id', f.subsidiary_id);
}
// 所在公司权限:仅导出「主体级(无货主)+ 自己所属公司」的属性
if (ctx.access && !ctx.access.isGroup) {
const ids = (ctx.access.ownCompanyIds || []).map(Number);
if (ids.length) {
wh.raw(
`(t.subsidiary_id IS NULL OR t.subsidiary_id IN (${ids.map(() => '?').join(',')}))`,
...ids
);
} else {
wh.raw('t.subsidiary_id IS NULL');
}
}
return buildResult({ columns: ATTR_COLUMNS, from: `${table} t`, wh }); return buildResult({ columns: ATTR_COLUMNS, from: `${table} t`, wh });
}, },
}; };
@ -1043,12 +1066,13 @@ const TYPE_LABELS = Object.keys(EXPORT_TYPES).reduce((acc, key) => { acc[key] =
* @param {Object} filters 筛选条件(来自前端,键已按类型白名单过滤) * @param {Object} filters 筛选条件(来自前端,键已按类型白名单过滤)
* @param {number} principalId 主体ID(强制隔离) * @param {number} principalId 主体ID(强制隔离)
* @param {number} [userId] 提交人ID(「主体」类型按账号可见主体隔离时使用) * @param {number} [userId] 提交人ID(「主体」类型按账号可见主体隔离时使用)
* @param {Object} [access] 权限范围 { isGroup, ownCompanyIds }(带 subsidiary_id 的导出类型据此收窄)
* @return {{sql: string, countSql: string, columns: Array, replacements: Array}} 查询语句与列定义 * @return {{sql: string, countSql: string, columns: Array, replacements: Array}} 查询语句与列定义
*/ */
function buildExportSql(type, filters, principalId, userId) { function buildExportSql(type, filters, principalId, userId, access) {
const def = EXPORT_TYPES[type]; const def = EXPORT_TYPES[type];
if (!def) throw new Error('不支持的导出类型: ' + type); if (!def) throw new Error('不支持的导出类型: ' + type);
return def.build(filters || {}, { principalId, userId }); return def.build(filters || {}, { principalId, userId, access });
} }
/** /**

View File

@ -0,0 +1,33 @@
'use strict';
/**
* 商品属性(分类 / 品牌 / 单位)关联下属公司:三张表各增加 subsidiary_id。
*
* NULL 表示主体级(全集团共用);填写则为某个下属公司(货主)私有。
* 所在公司权限只能新增/维护「主体级」与「自己所属公司」的属性,列表也仅可见这两类。
*/
const TABLES = [ 'product_categories', 'product_brands', 'product_units' ];
module.exports = {
async up(queryInterface, Sequelize) {
for (const table of TABLES) {
await queryInterface.addColumn(table, 'subsidiary_id', {
type: Sequelize.BIGINT.UNSIGNED,
allowNull: true,
comment: '所属货主(下属公司ID);NULL 表示主体级(全集团共用)',
references: { model: 'principal_subsidiaries', key: 'id' },
after: 'principal_id',
});
await queryInterface.addIndex(table, [ 'principal_id', 'subsidiary_id' ], {
name: `idx_${table}_principal_subsidiary`,
});
}
},
async down(queryInterface) {
for (const table of TABLES) {
await queryInterface.removeIndex(table, `idx_${table}_principal_subsidiary`);
await queryInterface.removeColumn(table, 'subsidiary_id');
}
},
};

View File

@ -4,6 +4,12 @@ import { get, post, put, del } from '@/utils/request'
export interface ProductBrand { export interface ProductBrand {
id: number id: number
principal_id: number principal_id: number
/** 所属货主(下属公司ID);null 表示主体级(全集团共用) */
subsidiary_id: number | null
/** 所属货主名称(列表/详情接口返回,主体级为空串) */
subsidiary_name?: string
/** 所属货主明细(列表/详情接口返回) */
subsidiary?: { id: number; name: string } | null
name: string name: string
code: string | null code: string | null
status: number status: number
@ -22,9 +28,13 @@ export interface ProductAttributeOption {
id: number id: number
name: string name: string
code: string | null code: string | null
/** 所属货主(下属公司ID);null 表示主体级 */
subsidiary_id?: number | null
} }
export interface ProductBrandPayload { export interface ProductBrandPayload {
/** 所属货主(下属公司ID);null/不传表示主体级 */
subsidiary_id?: number | null
name: string name: string
code?: string | null code?: string | null
status?: number status?: number

View File

@ -4,6 +4,12 @@ import { get, post, put, del } from '@/utils/request'
export interface ProductCategory { export interface ProductCategory {
id: number id: number
principal_id: number principal_id: number
/** 所属货主(下属公司ID);null 表示主体级(全集团共用) */
subsidiary_id: number | null
/** 所属货主名称(列表/详情接口返回,主体级为空串) */
subsidiary_name?: string
/** 所属货主明细(列表/详情接口返回) */
subsidiary?: { id: number; name: string } | null
name: string name: string
code: string | null code: string | null
status: number status: number
@ -22,9 +28,13 @@ export interface ProductAttributeOption {
id: number id: number
name: string name: string
code: string | null code: string | null
/** 所属货主(下属公司ID);null 表示主体级 */
subsidiary_id?: number | null
} }
export interface ProductCategoryPayload { export interface ProductCategoryPayload {
/** 所属货主(下属公司ID);null/不传表示主体级 */
subsidiary_id?: number | null
name: string name: string
code?: string | null code?: string | null
status?: number status?: number

View File

@ -4,6 +4,12 @@ import { get, post, put, del } from '@/utils/request'
export interface ProductUnit { export interface ProductUnit {
id: number id: number
principal_id: number principal_id: number
/** 所属货主(下属公司ID);null 表示主体级(全集团共用) */
subsidiary_id: number | null
/** 所属货主名称(列表/详情接口返回,主体级为空串) */
subsidiary_name?: string
/** 所属货主明细(列表/详情接口返回) */
subsidiary?: { id: number; name: string } | null
name: string name: string
code: string | null code: string | null
status: number status: number
@ -22,9 +28,13 @@ export interface ProductAttributeOption {
id: number id: number
name: string name: string
code: string | null code: string | null
/** 所属货主(下属公司ID);null 表示主体级 */
subsidiary_id?: number | null
} }
export interface ProductUnitPayload { export interface ProductUnitPayload {
/** 所属货主(下属公司ID);null/不传表示主体级 */
subsidiary_id?: number | null
name: string name: string
code?: string | null code?: string | null
status?: number status?: number

View File

@ -24,6 +24,8 @@ import {
updateProductUnit, updateProductUnit,
deleteProductUnit, deleteProductUnit,
} from '@/api/productUnit' } from '@/api/productUnit'
import { getPrincipalSubsidiaryOptions, type PrincipalSubsidiaryOption } from '@/api/principalSubsidiary'
import { getAccessContext } from '@/api/access'
export type AttrType = 'category' | 'brand' | 'unit' export type AttrType = 'category' | 'brand' | 'unit'
@ -33,6 +35,10 @@ const props = defineProps<{ type: AttrType }>()
interface AttrRow { interface AttrRow {
id: number id: number
principal_id: number principal_id: number
/** 所属货主(下属公司ID);null 表示主体级 */
subsidiary_id: number | null
/** 所属货主名称(主体级为空串) */
subsidiary_name?: string
name: string name: string
code: string | null code: string | null
status: number status: number
@ -89,6 +95,7 @@ const EXPORT_TYPE: Record<AttrType, string> = {
/** 导出筛选条件(与列表筛选同源) */ /** 导出筛选条件(与列表筛选同源) */
const exportFilters = computed(() => ({ const exportFilters = computed(() => ({
keyword: query.keyword.trim(), keyword: query.keyword.trim(),
subsidiary_id: query.subsidiary_id,
status: query.status, status: query.status,
})) }))
const exportType = computed(() => EXPORT_TYPE[props.type]) const exportType = computed(() => EXPORT_TYPE[props.type])
@ -110,14 +117,35 @@ const query = reactive({
page: 1, page: 1,
pageSize: DEFAULT_PAGE_SIZE, pageSize: DEFAULT_PAGE_SIZE,
keyword: '', keyword: '',
subsidiary_id: '' as string | number,
status: '' as string | number, status: '' as string | number,
}) })
/** 权限范围:所在公司权限只能把属性建到「主体级」或自己所属公司 */
const isCompanyScope = ref(false)
/** 货主下拉(主体级 + 可选下属公司) */
const subsidiaryOptions = ref<PrincipalSubsidiaryOption[]>([])
async function loadSubsidiaryOptions() {
try {
const [access, options] = await Promise.all([
getAccessContext(),
getPrincipalSubsidiaryOptions({ mine: 1 }),
])
isCompanyScope.value = !access.is_group
subsidiaryOptions.value = options
} catch {
isCompanyScope.value = false
subsidiaryOptions.value = []
}
}
const { loading, list, total, elapsed, fetchList, search, handlePageChange, handleSizeChange } = useListPage({ const { loading, list, total, elapsed, fetchList, search, handlePageChange, handleSizeChange } = useListPage({
query, query,
fetcher: () => { fetcher: () => {
const params: Record<string, unknown> = { ...query } const params: Record<string, unknown> = { ...query }
if (!params.keyword) delete params.keyword if (!params.keyword) delete params.keyword
if (params.subsidiary_id === '') delete params.subsidiary_id
if (params.status === '') delete params.status if (params.status === '') delete params.status
return api.list(params) return api.list(params)
}, },
@ -125,6 +153,7 @@ const { loading, list, total, elapsed, fetchList, search, handlePageChange, hand
function reset() { function reset() {
query.keyword = '' query.keyword = ''
query.subsidiary_id = ''
query.status = '' query.status = ''
search() search()
} }
@ -135,13 +164,14 @@ const submitting = ref(false)
const formRef = ref<FormInstance>() const formRef = ref<FormInstance>()
const editId = ref<number | null>(null) const editId = ref<number | null>(null)
const form = reactive({ const form = reactive({
subsidiary_id: '' as number | '' | null,
name: '', name: '',
code: '', code: '',
status: 1, status: 1,
sort: 0, sort: 0,
remark: '', remark: '',
}) })
const EMPTY_FORM = { name: '', code: '', status: 1, sort: 0, remark: '' } const EMPTY_FORM = { subsidiary_id: '' as number | '' | null, name: '', code: '', status: 1, sort: 0, remark: '' }
const rules: FormRules = { const rules: FormRules = {
name: [{ required: true, message: `请输入${cur.nameLabel}`, trigger: 'blur' }], name: [{ required: true, message: `请输入${cur.nameLabel}`, trigger: 'blur' }],
status: [{ required: true, message: '请选择状态', trigger: 'change' }], status: [{ required: true, message: '请选择状态', trigger: 'change' }],
@ -156,6 +186,7 @@ function openCreate() {
function openEdit(row: AttrRow) { function openEdit(row: AttrRow) {
editId.value = row.id editId.value = row.id
Object.assign(form, { Object.assign(form, {
subsidiary_id: row.subsidiary_id ?? '',
name: row.name, name: row.name,
code: row.code || '', code: row.code || '',
status: row.status, status: row.status,
@ -171,7 +202,10 @@ async function submitForm() {
if (!valid) return if (!valid) return
submitting.value = true submitting.value = true
try { try {
const payload = { ...form } const payload = {
...form,
subsidiary_id: form.subsidiary_id === '' || form.subsidiary_id === null ? null : Number(form.subsidiary_id),
}
if (editId.value == null) { if (editId.value == null) {
await api.create(payload) await api.create(payload)
ElMessage.success('新增成功') ElMessage.success('新增成功')
@ -216,7 +250,10 @@ async function handleDelete(row: AttrRow) {
} }
} }
onMounted(fetchList) onMounted(() => {
fetchList()
loadSubsidiaryOptions()
})
</script> </script>
<template> <template>
@ -225,6 +262,19 @@ onMounted(fetchList)
<el-form-item :label="`${cur.nameLabel}关键词`"> <el-form-item :label="`${cur.nameLabel}关键词`">
<el-input v-model="query.keyword" :placeholder="`匹配名称或编码`" clearable @keyup.enter="search" /> <el-input v-model="query.keyword" :placeholder="`匹配名称或编码`" clearable @keyup.enter="search" />
</el-form-item> </el-form-item>
<el-form-item label="货主">
<el-select
v-model="query.subsidiary_id"
placeholder="全部"
clearable
filterable
style="width: 160px"
@change="search"
>
<el-option label="主体(全集团)" :value="0" />
<el-option v-for="s in subsidiaryOptions" :key="s.id" :label="s.name" :value="s.id" />
</el-select>
</el-form-item>
<el-form-item label="状态"> <el-form-item label="状态">
<el-select v-model="query.status" placeholder="全部" clearable style="width: 120px"> <el-select v-model="query.status" placeholder="全部" clearable style="width: 120px">
<el-option label="启用" :value="1" /> <el-option label="启用" :value="1" />
@ -245,6 +295,9 @@ onMounted(fetchList)
<DataTable :loading="loading" :data="list" height="100%"> <DataTable :loading="loading" :data="list" height="100%">
<el-table-column prop="code" :label="cur.codeLabel" width="130" /> <el-table-column prop="code" :label="cur.codeLabel" width="130" />
<el-table-column prop="name" :label="cur.nameLabel" min-width="140" /> <el-table-column prop="name" :label="cur.nameLabel" min-width="140" />
<el-table-column label="货主" width="150" show-overflow-tooltip>
<template #default="{ row }">{{ row.subsidiary_name || '主体(全集团)' }}</template>
</el-table-column>
<el-table-column label="使用商品数" width="100" align="center"> <el-table-column label="使用商品数" width="100" align="center">
<template #default="{ row }"> <template #default="{ row }">
<el-button <el-button
@ -301,6 +354,13 @@ onMounted(fetchList)
size="460px" size="460px"
> >
<el-form ref="formRef" :model="form" :rules="rules" label-width="100px"> <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
<el-form-item label="货主">
<el-select v-model="form.subsidiary_id" placeholder="主体(全集团)" clearable filterable style="width: 100%">
<el-option label="主体(全集团)" value="" />
<el-option v-for="s in subsidiaryOptions" :key="s.id" :label="s.name" :value="s.id" />
</el-select>
<div v-if="isCompanyScope" class="form-tip">所在公司权限只能选择主体或自己所属公司</div>
</el-form-item>
<el-form-item :label="cur.nameLabel" prop="name"> <el-form-item :label="cur.nameLabel" prop="name">
<el-input v-model="form.name" :placeholder="cur.placeholder" /> <el-input v-model="form.name" :placeholder="cur.placeholder" />
</el-form-item> </el-form-item>
@ -350,4 +410,9 @@ onMounted(fetchList)
:deep(.el-input-number) { :deep(.el-input-number) {
width: 100%; width: 100%;
} }
.form-tip {
font-size: 12px;
color: var(--el-text-color-secondary);
line-height: 1.4;
}
</style> </style>