diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 223ea16..4f4696a 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -46,6 +46,8 @@ const buildListResponse = pageContract => ({ const shopItem = { id: { type: 'integer', description: '主键' }, principal_id: { type: 'integer', description: '所属主体ID' }, + subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID)' }, + subsidiary_name: { type: 'string', description: '所属货主名称' }, code: { type: 'string', description: '店铺编码(平台店铺ID / 自定义编码 / OMS 前缀自动生成)' }, name: { type: 'string', description: '店铺名称' }, platform: { type: 'string', description: '所属平台:taobao/pdd/douyin/jd/other' }, @@ -1156,6 +1158,7 @@ module.exports = { }, createShopRequest: { principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + subsidiary_id: { type: 'integer', required: true, description: '所属货主(下属公司ID),必填;所在公司权限只能选自己所属公司' }, code: { type: 'string', description: '店铺编码,留空则自动生成 OMS 前缀编码;传入时同一主体下唯一' }, name: { type: 'string', required: true, description: '店铺名称' }, platform: { type: 'string', description: '平台标识:taobao/pdd/douyin/jd/other' }, @@ -1170,6 +1173,7 @@ module.exports = { updateShopRequest: { code: { type: 'string', description: '店铺编码' }, name: { type: 'string', description: '店铺名称' }, + subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID);所在公司权限不可变更,集团变更后店铺商品货主跟随' }, platform: { type: 'string', description: '平台标识' }, contact_name: { type: 'string', description: '联系人' }, contact_phone: { type: 'string', description: '联系电话' }, @@ -1263,6 +1267,7 @@ module.exports = { externalPrintMerchantListResponse: buildListResponse('externalPrintMerchantPage'), createShopsFromMerchantsRequest: { principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, + subsidiary_id: { type: 'integer', required: true, description: '所属货主(下属公司ID),必填:添加店铺时指定归属货主' }, merchants: { type: 'array', itemType: 'externalPrintMerchantItem', required: true, description: '要创建到店铺的商家列表(取自商家列表接口)' }, }, externalPrintExpressInterfaceSaveItem: { diff --git a/backend/app/controller/externalPrintAccount.js b/backend/app/controller/externalPrintAccount.js index 6fbb130..5ddc677 100644 --- a/backend/app/controller/externalPrintAccount.js +++ b/backend/app/controller/externalPrintAccount.js @@ -43,6 +43,7 @@ function shopProductKey(outerItemId, outerSkuId) { /** 商品同步时允许更新的字段(新增行仍由 bulkCreate 写入) */ const SHOP_PRODUCT_UPSERT_FIELDS = [ + 'subsidiary_id', 'title', 'outer_code', 'spec', @@ -406,6 +407,24 @@ class ExternalPrintAccountController extends Controller { const platformCode = account.platform.code; const principalId = ctx.state.principalId; + + // 添加店铺时必须选择货主(下属公司),货主权限据此判定店铺归属 + const subsidiaryId = Number(ctx.request.body.subsidiary_id); + if (!Number.isInteger(subsidiaryId) || subsidiaryId <= 0) { + ctx.status = 400; + ctx.body = { code: 400, message: '请选择所属货主(下属公司)' }; + return; + } + const subsidiary = await ctx.model.PrincipalSubsidiary.findOne({ + where: { id: subsidiaryId, principal_id: principalId }, + attributes: [ 'id' ], + }); + if (!subsidiary) { + ctx.status = 400; + ctx.body = { code: 400, message: '所属货主不存在或不属于当前集团' }; + return; + } + const created = []; const transaction = await ctx.model.transaction(); @@ -420,6 +439,7 @@ class ExternalPrintAccountController extends Controller { const shop = await ctx.model.Shop.create({ principal_id: principalId, + subsidiary_id: subsidiaryId, code, name: String(item.name || '').trim() || code, platform: platformCode, @@ -491,6 +511,14 @@ class ExternalPrintAccountController extends Controller { return; } + // 所在公司权限:仅可操作自己所属公司(货主)的店铺 + const denied = await this.checkShopAccess(shop); + if (denied) { + ctx.status = denied.status; + ctx.body = denied.body; + return; + } + let snapshot; try { const service = this.createPlatformService(account); @@ -563,6 +591,14 @@ class ExternalPrintAccountController extends Controller { return; } + // 所在公司权限:仅可操作自己所属公司(货主)的店铺 + const denied = await this.checkShopAccess(shop); + if (denied) { + ctx.status = denied.status; + ctx.body = denied.body; + return; + } + const body = ctx.request.body || {}; const items = (Array.isArray(body.items) ? body.items : []) .map(item => ({ @@ -679,6 +715,14 @@ class ExternalPrintAccountController extends Controller { return; } + // 所在公司权限:仅可操作自己所属公司(货主)的店铺 + const denied = await this.checkShopAccess(shop); + if (denied) { + ctx.status = denied.status; + ctx.body = denied.body; + return; + } + const body = ctx.request.body || {}; const days = Number(body.days); // days = 0(或 all=true)表示「全部待处理」:不限下单时间,由服务端按平台发货状态过滤, @@ -760,6 +804,7 @@ class ExternalPrintAccountController extends Controller { .filter(item => item.outer_item_id) .map(item => ({ principal_id: shop.principal_id, + subsidiary_id: shop.subsidiary_id, shop_id: shop.id, outer_item_id: item.outer_item_id, outer_sku_id: item.outer_sku_id || '', @@ -929,6 +974,21 @@ class ExternalPrintAccountController extends Controller { * @param {Object} [options] withPlatform 为 true 时一并带出平台配置 * @return {Promise} 账号实例 */ + /** + * 所在公司权限:校验店铺是否属于自己所属公司(货主) + * @param {Object} shop 店铺 model 实例 + * @return {Promise<{status: number, body: Object}|null>} 无权限时返回错误响应 + */ + async checkShopAccess(shop) { + const { ctx } = this; + const access = await ctx.service.access.resolve(ctx.userId, shop.principal_id); + if (access.isGroup) return null; + const ownIds = access.ownCompanyIds.map(Number); + if (shop.subsidiary_id == null || !ownIds.includes(Number(shop.subsidiary_id))) { + return { status: 403, body: { code: 403, message: '仅可操作自己所属公司(货主)的店铺' } }; + } + return null; + } async findAccount(id, options = {}) { const { ctx } = this; const principalId = ctx.state.principalId; diff --git a/backend/app/controller/menu.js b/backend/app/controller/menu.js index 7a8a71c..1ffccd8 100644 --- a/backend/app/controller/menu.js +++ b/backend/app/controller/menu.js @@ -6,6 +6,9 @@ const { parsePagination, buildPageResult } = require('../lib/pagination'); /** 所在公司权限可访问的系统管理菜单(员工档案) */ const EMPLOYEE_MENU_PATH = '/system/employee'; +/** 仅集团权限可访问的菜单:外部打单平台(账号/商家导入/快递接口均为集团维护) */ +const GROUP_ONLY_MENU_PATHS = [ '/external-print-platform' ]; + /** * @controller MenuController 菜单管理 */ @@ -91,20 +94,24 @@ class MenuController extends Controller { } /** - * 所在公司权限的菜单收束:系统管理目录下仅保留「员工档案」 + * 所在公司权限的菜单收束:系统管理目录下仅保留「员工档案」,外部打单平台相关菜单隐藏 * @param {Array} rows 菜单行 * @return {Array} 过滤后的菜单行 */ filterCompanyScopeMenus(rows) { + const removedIds = new Set(); const employee = rows.find(row => row.path === EMPLOYEE_MENU_PATH && Number(row.type) === 2); - if (!employee) return rows; - - const systemId = Number(employee.parent_id); - const removedIds = new Set( + if (employee) { + const systemId = Number(employee.parent_id); rows .filter(row => Number(row.parent_id) === systemId && Number(row.id) !== Number(employee.id)) - .map(row => Number(row.id)) - ); + .forEach(row => removedIds.add(Number(row.id))); + } + // 外部打单平台相关菜单仅集团权限可见 + rows + .filter(row => GROUP_ONLY_MENU_PATHS.includes(row.path)) + .forEach(row => removedIds.add(Number(row.id))); + // 父级被移除的子级一并移除,避免孤儿节点被挂到根节点 let changed = true; while (changed) { diff --git a/backend/app/controller/shop.js b/backend/app/controller/shop.js index 014669b..f43bfc6 100644 --- a/backend/app/controller/shop.js +++ b/backend/app/controller/shop.js @@ -9,6 +9,9 @@ const CODE_PREFIX = 'OMS'; /** 店铺类型:1 平台店铺(手工/平台)2 外部打单平台商家 */ const SHOP_TYPE_PLATFORM = 1; +/** 店铺类型:外部打单平台导入的商家店铺(货主权限只读) */ +const SHOP_TYPE_EXTERNAL = 2; + /** 自动拉取订单的最小间隔(分钟) */ const MIN_AUTO_FETCH_INTERVAL = 3; @@ -70,10 +73,11 @@ class ShopController extends Controller { const { ctx } = this; const Op = this.app.Sequelize.Op; const { page, pageSize, offset, limit } = parsePagination(ctx.query); - const { keyword, platform, status, type } = ctx.query; + const { keyword, platform, status, type, subsidiary_id: subsidiaryId } = ctx.query; + const principalId = ctx.state.principalId; const where = {}; - where.principal_id = ctx.state.principalId; + where.principal_id = principalId; if (keyword) { where[Op.or] = [ { name: { [Op.like]: `%${keyword}%` } }, @@ -83,18 +87,37 @@ class ShopController extends Controller { if (platform) where.platform = platform; if (status !== undefined && status !== '') where.status = Number(status); if (type !== undefined && type !== '') where.type = Number(type); + if (subsidiaryId !== undefined && subsidiaryId !== '') where.subsidiary_id = Number(subsidiaryId); + + // 所在公司权限:店铺列表仅展示自己所属公司(货主)的店铺 + const access = await ctx.service.access.resolve(ctx.userId, principalId); + if (!access.isGroup) { + const ownIds = access.ownCompanyIds.map(Number); + if (where.subsidiary_id !== undefined) { + if (!ownIds.includes(Number(where.subsidiary_id))) { + ctx.body = { code: 0, message: 'success', data: buildPageResult([], 0, { page, pageSize }) }; + return; + } + } else { + where.subsidiary_id = { [Op.in]: ownIds }; + } + } const { count, rows } = await ctx.model.Shop.findAndCountAll({ where, offset, limit, order: [[ 'id', 'DESC' ]], + include: [ + { model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }, + ], }); - // 数据库模式(预留)的密码不回显 + // 数据库模式(预留)的密码不回显;附带扁平货主名称 const list = rows.map(row => { const plain = row.get({ plain: true }); plain.has_db_password = !!plain.db_password; + plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : ''; delete plain.db_password; return plain; }); @@ -121,6 +144,13 @@ class ShopController extends Controller { return; } + // 所在公司权限:仅可查看自己所属公司(货主)的店铺 + if (!(await this.canAccess(ctx, shop))) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可查看自己所属公司(货主)的店铺' }; + return; + } + const shopId = shop.id; const [ shopProductCount, boundCount, orderCount, orderAmount, latestOrder ] = await Promise.all([ ctx.model.ShopProduct.count({ where: { shop_id: shopId } }), @@ -181,6 +211,20 @@ class ShopController extends Controller { return; } + // 所属货主必填;所在公司权限只能选自己所属公司 + const subsidiary = await this.resolveSubsidiaryId(ctx.request.body.subsidiary_id, principalId); + if (!subsidiary.ok) { + ctx.status = 400; + ctx.body = { code: 400, message: subsidiary.message }; + return; + } + const access = await ctx.service.access.resolve(ctx.userId, principalId); + if (!access.isGroup && !access.ownCompanyIds.map(Number).includes(Number(subsidiary.value))) { + ctx.status = 403; + ctx.body = { code: 403, message: '只能选择自己所属公司(货主)' }; + return; + } + // 已有编码(如平台店铺ID)直接用;未填则生成 OMS 前缀编码 const code = String(ctx.request.body.code || '').trim(); let shopCode = code; @@ -216,6 +260,7 @@ class ShopController extends Controller { ...body, type: SHOP_TYPE_PLATFORM, code: shopCode, + subsidiary_id: subsidiary.value, auto_fetch_order: autoFetch.auto_fetch_order == null ? 0 : autoFetch.auto_fetch_order, auto_fetch_interval: autoFetch.auto_fetch_interval == null ? MIN_AUTO_FETCH_INTERVAL @@ -224,6 +269,59 @@ class ShopController extends Controller { ctx.body = { code: 0, message: 'success', data: { id: shop.id, code: shop.code } }; } + /** + * 校验「所属货主」:必须是当前主体下的下属公司(必填) + * @param {number|string|null|undefined} value 前端传入的 subsidiary_id + * @param {number|string} principalId 当前主体ID + * @return {Promise<{ok: boolean, value?: number, message?: string}>} 校验结果 + */ + async resolveSubsidiaryId(value, principalId) { + if (value === undefined || value === null || value === '') { + return { ok: false, message: '请选择所属货主(下属公司)' }; + } + const id = Number(value); + if (!Number.isInteger(id) || id <= 0) return { ok: false, message: '所属货主不合法' }; + + const subsidiary = await this.ctx.model.PrincipalSubsidiary.findOne({ + where: { id, principal_id: principalId }, + attributes: [ 'id' ], + }); + if (!subsidiary) return { ok: false, message: '所属货主不存在或不属于当前集团' }; + return { ok: true, value: Number(subsidiary.id) }; + } + + /** + * 判断货主ID是否属于当前账号自己的公司 + * @param {Object} access 权限上下文 + * @param {number|null} subsidiaryId 货主ID + * @return {boolean} 是否属于自己公司 + */ + isOwnSubsidiary(access, subsidiaryId) { + if (subsidiaryId === null || subsidiaryId === undefined) return false; + return (access.ownCompanyIds || []).map(Number).includes(Number(subsidiaryId)); + } + + /** + * 判断店铺是否为外部打单平台导入的店铺 + * @param {Object} shop 店铺 model 实例 + * @return {boolean} 是否外部打单平台店铺 + */ + isExternalShop(shop) { + return Number(shop.type) === SHOP_TYPE_EXTERNAL || !!shop.external_print_account_id; + } + + /** + * 判断当前账号是否有权访问该店铺(集团权限均可;所在公司权限限自己所属公司) + * @param {Object} ctx egg context + * @param {Object} shop 店铺 model 实例 + * @return {Promise} 是否有权限 + */ + async canAccess(ctx, shop) { + const access = await ctx.service.access.resolve(ctx.userId, shop.principal_id); + if (access.isGroup) return true; + return this.isOwnSubsidiary(access, shop.subsidiary_id); + } + /** * 生成同主体下唯一的店铺编码 * @param {number} principalId 主体ID @@ -260,6 +358,38 @@ class ShopController extends Controller { } delete ctx.request.body.principal_id; + + // 所在公司权限:仅可维护自己所属公司(货主)的店铺 + if (!(await this.canAccess(ctx, shop))) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可修改自己所属公司(货主)的店铺' }; + return; + } + // 外部打单平台导入的店铺:货主权限只读(仅可拉取订单/同步商品) + const access = await ctx.service.access.resolve(ctx.userId, shop.principal_id); + if (!access.isGroup && this.isExternalShop(shop)) { + ctx.status = 403; + ctx.body = { code: 403, message: '外部打单平台店铺不可编辑,仅可拉取订单和同步商品' }; + return; + } + + // 货主:所在公司权限不可变更;集团可改(店铺商品同步跟随) + let subsidiaryChanged = false; + if (ctx.request.body.subsidiary_id !== undefined) { + const subsidiary = await this.resolveSubsidiaryId(ctx.request.body.subsidiary_id, 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)) { + ctx.status = 403; + ctx.body = { code: 403, message: '只能维护自己所属公司(货主)的店铺' }; + return; + } + subsidiaryChanged = Number(subsidiary.value) !== Number(shop.subsidiary_id); + ctx.request.body.subsidiary_id = subsidiary.value; + } // 外部平台导入 / 数据库模式相关字段由对应接入逻辑维护,普通编辑不允许修改 delete ctx.request.body.type; delete ctx.request.body.external_print_account_id; @@ -298,6 +428,13 @@ class ShopController extends Controller { } await shop.update(ctx.request.body); + // 货主变更时,店铺商品的货主跟随店铺一起调整 + if (subsidiaryChanged) { + await ctx.model.ShopProduct.update( + { subsidiary_id: shop.subsidiary_id }, + { where: { principal_id: shop.principal_id, shop_id: shop.id } } + ); + } // 店铺资料变更:清掉推送/取号用的店铺基础缓存 await ctx.service.cache.invalidateShop(shop.id); ctx.body = { code: 0, message: 'success', data: { id: shop.id, code: shop.code } }; @@ -321,6 +458,21 @@ class ShopController extends Controller { return; } + // 所在公司权限:仅可删除自己所属公司的店铺;外部打单平台店铺不可删除 + const access = await ctx.service.access.resolve(ctx.userId, shop.principal_id); + if (!access.isGroup) { + if (!this.isOwnSubsidiary(access, shop.subsidiary_id)) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可删除自己所属公司(货主)的店铺' }; + return; + } + if (this.isExternalShop(shop)) { + ctx.status = 403; + ctx.body = { code: 403, message: '外部打单平台店铺不可删除,仅可拉取订单和同步商品' }; + return; + } + } + const orderCount = await ctx.model.Order.count({ where: { shop_id: shop.id } }); if (orderCount) { ctx.status = 400; diff --git a/backend/app/controller/shopProduct.js b/backend/app/controller/shopProduct.js index 29aebd3..ca98d73 100644 --- a/backend/app/controller/shopProduct.js +++ b/backend/app/controller/shopProduct.js @@ -43,6 +43,12 @@ class ShopProductController extends Controller { if (shopId) where.shop_id = Number(shopId); if (bindType !== undefined && bindType !== '') where.bind_type = Number(bindType); if (status !== undefined && status !== '') where.status = Number(status); + + // 所在公司权限:仅可见自己所属公司(货主)的店铺商品 + const access = await ctx.service.access.resolve(ctx.userId, principalId); + if (!access.isGroup) { + where.subsidiary_id = { [Op.in]: access.ownCompanyIds.map(Number) }; + } if (keyword) { where[Op.or] = [ { title: { [Op.like]: `%${keyword}%` } }, @@ -70,16 +76,34 @@ class ShopProductController extends Controller { order: [[ 'id', 'DESC' ]], include: [ { model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] }, + { model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }, { model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name' ] }, { model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] }, ], }); - const list = rows.map(row => row.get({ plain: true })); + const list = rows.map(row => { + const plain = row.get({ plain: true }); + plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : ''; + return plain; + }); await this.attachUnboundOrderCount(list, principalId); ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; } + /** + * 判断当前账号是否有权访问该店铺商品(集团权限均可;所在公司权限限自己所属公司) + * @param {Object} ctx egg context + * @param {Object} item 店铺商品 model 实例 + * @return {Promise} 是否有权限 + */ + async canAccess(ctx, item) { + const access = await ctx.service.access.resolve(ctx.userId, item.principal_id); + if (access.isGroup) return true; + if (item.subsidiary_id === null || item.subsidiary_id === undefined) return false; + return access.ownCompanyIds.map(Number).includes(Number(item.subsidiary_id)); + } + /** * 回填每个店铺商品的「待处理订单数」(未绑定系统商品的订单明细按订单去重计数), * 便于列表上直接看出哪些商品还有订单等绑定 @@ -130,6 +154,16 @@ class ShopProductController extends Controller { return; } + // 所在公司权限:仅可查看自己所属公司(货主)的店铺商品 + const access = await ctx.service.access.resolve(ctx.userId, item.principal_id); + if (!access.isGroup + && (item.subsidiary_id == null + || !access.ownCompanyIds.map(Number).includes(Number(item.subsidiary_id)))) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可查看自己所属公司(货主)的店铺商品' }; + return; + } + ctx.body = { code: 0, message: 'success', data: item }; } @@ -155,6 +189,13 @@ class ShopProductController extends Controller { return; } + // 所在公司权限:仅可维护自己所属公司(货主)的店铺商品 + if (!(await this.canAccess(ctx, item))) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可维护自己所属公司(货主)的店铺商品' }; + return; + } + const type = Number(bindType); if (![ 0, 1, 2 ].includes(type)) { ctx.status = 400; @@ -304,6 +345,28 @@ class ShopProductController extends Controller { ctx.body = { code: 404, message: '所选店铺商品不存在或不属于当前主体' }; return; } + + // 所在公司权限:只能批量维护自己所属公司(货主)的店铺商品 + const access = await ctx.service.access.resolve(ctx.userId, principalId); + if (!access.isGroup) { + const ownIds = access.ownCompanyIds.map(Number); + const allowed = items.filter(item => item.subsidiary_id != null && ownIds.includes(Number(item.subsidiary_id))); + if (!allowed.length) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可维护自己所属公司(货主)的店铺商品' }; + return; + } + if (allowed.length !== items.length) { + const allowedIds = new Set(allowed.map(item => Number(item.id))); + const denied = ids.filter(id => !allowedIds.has(id)); + ctx.status = 403; + ctx.body = { + code: 403, + message: `以下店铺商品不属于自己所属公司(货主),无权维护:${denied.join('、')}`, + }; + return; + } + } const foundIds = new Set(items.map(item => Number(item.id))); const failed = ids .filter(id => !foundIds.has(id)) diff --git a/backend/app/model/shop.js b/backend/app/model/shop.js index 7cfcd19..9e0bd56 100644 --- a/backend/app/model/shop.js +++ b/backend/app/model/shop.js @@ -11,6 +11,7 @@ module.exports = app => { const Shop = app.model.define('shop', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + subsidiary_id: { type: BIGINT.UNSIGNED, comment: '所属货主(下属公司ID)' }, code: { type: STRING(50), allowNull: false, comment: '店铺编码(平台店铺ID或自定义编码,OMS 内新建时按 OMS 前缀自动生成)' }, name: { type: STRING(100), allowNull: false, comment: '店铺名称' }, platform: { type: STRING(50), comment: '所属平台:taobao/pdd/douyin/jd/other' }, @@ -37,6 +38,7 @@ module.exports = app => { Shop.associate = () => { app.model.Shop.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + app.model.Shop.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' }); app.model.Shop.belongsTo(app.model.ExternalPrintAccount, { foreignKey: 'external_print_account_id', as: 'externalPrintAccount' }); app.model.Shop.hasMany(app.model.ShopProduct, { foreignKey: 'shop_id', as: 'shopProducts' }); app.model.Shop.hasMany(app.model.Order, { foreignKey: 'shop_id', as: 'orders' }); diff --git a/backend/app/model/shopProduct.js b/backend/app/model/shopProduct.js index 55c776f..71730e1 100644 --- a/backend/app/model/shopProduct.js +++ b/backend/app/model/shopProduct.js @@ -13,6 +13,7 @@ module.exports = app => { const ShopProduct = app.model.define('shop_product', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + subsidiary_id: { type: BIGINT.UNSIGNED, comment: '所属货主(下属公司ID),跟随店铺' }, shop_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属店铺ID' }, outer_item_id: { type: STRING(100), allowNull: false, comment: '平台商品ID' }, outer_sku_id: { type: STRING(100), comment: '平台规格ID(SKU),无规格时为空' }, @@ -36,6 +37,7 @@ module.exports = app => { ShopProduct.associate = () => { app.model.ShopProduct.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + app.model.ShopProduct.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' }); app.model.ShopProduct.belongsTo(app.model.Shop, { foreignKey: 'shop_id', as: 'shop' }); app.model.ShopProduct.belongsTo(app.model.Product, { foreignKey: 'product_id', as: 'product' }); app.model.ShopProduct.belongsTo(app.model.ComboProduct, { foreignKey: 'combo_product_id', as: 'comboProduct' }); diff --git a/backend/app/router.js b/backend/app/router.js index 6285701..1000718 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -4,6 +4,8 @@ * @param {Egg.Application} app - egg application */ module.exports = app => { + // 集团权限门禁:所在公司权限访问这些接口会被拒绝 + const groupScope = app.middleware.groupScope; const { router, controller } = app; const jwtAuth = app.middleware.jwtAuth(); const principalCheck = app.middleware.principalCheck; @@ -104,8 +106,8 @@ module.exports = app => { router.post('/api/order-status/:id/push-wms', jwtAuth, principalCheck(), controller.orderStatus.pushWms); // 外部打单平台同步发货(配送后把发货结果同步回店管家):数量统计 / 批量重试 - router.get('/api/external-send/counts', jwtAuth, principalCheck(), controller.externalSendSync.counts); - router.post('/api/external-send/retry', jwtAuth, principalCheck(), controller.externalSendSync.retry); + router.get('/api/external-send/counts', jwtAuth, principalCheck(), groupScope(), controller.externalSendSync.counts); + router.post('/api/external-send/retry', jwtAuth, principalCheck(), groupScope(), controller.externalSendSync.retry); // 以下资源均归属某个主体,需做主体校验与数据隔离,防止跨主体操作 // 商品批量导入:模板下载与导入接口需在 resources 之前注册,避免被 /:id 误匹配 @@ -116,7 +118,6 @@ module.exports = app => { router.resources('menus', '/api/menus', jwtAuth, controller.menu); router.resources('principalExternalApis', '/api/principal-external-apis', jwtAuth, principalCheck({ model: 'PrincipalExternalApi' }), controller.principalExternalApi); // 仓库(仅基础信息)与仓库接口配置(一个仓库可有多条接口配置) - const groupScope = app.middleware.groupScope; router.get('/api/warehouses/select', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouse.select); // 仓库下的商品(是否已推送到该仓库):需在 resources('warehouses') 之前注册,避免 /products 被当作 :id router.get('/api/warehouses/:id/products', jwtAuth, principalCheck({ model: 'Warehouse' }), controller.warehouseProduct.index); @@ -156,25 +157,26 @@ module.exports = app => { // 操作日志:店铺商品 / 系统商品 / 组合商品的历史操作记录(页面底部面板按对象查询) router.get('/api/operation-logs', jwtAuth, principalCheck(), controller.operationLog.index); // 外部打单平台:平台基础资料由开发者维护(只读查询);打单账号归属主体,在「店铺管理」下维护 - router.get('/api/external-print-platforms', jwtAuth, controller.externalPrintPlatform.index); + // 打单平台相关接口(平台资料、账号、商家导入、快递接口)均属于集团权限范围 + router.get('/api/external-print-platforms', jwtAuth, groupScope(), controller.externalPrintPlatform.index); // 账号登录态检查 / 登录(需在 resources 之前注册,避免被 /:id 误匹配) - router.post('/api/external-print-accounts/:id/check', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.check); - router.post('/api/external-print-accounts/:id/login', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.login); + router.post('/api/external-print-accounts/:id/check', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.check); + router.post('/api/external-print-accounts/:id/login', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.login); // 平台侧店铺(商家)列表与创建到 OMS 店铺(前端按账号ID调用,后端按平台服务分发) - router.get('/api/external-print-accounts/:id/merchants', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.merchants); - router.post('/api/external-print-accounts/:id/shops', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.createShops); + router.get('/api/external-print-accounts/:id/merchants', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.merchants); + router.post('/api/external-print-accounts/:id/shops', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.createShops); // 同步商家店铺商品(按商家分区逐域名拉取全量快照后写入店铺商品表) router.post('/api/external-print-accounts/:id/shops/:shopId/sync-products', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.syncShopProducts); // 按平台商品ID单独补拉(订单明细匹配不到店铺商品时使用,不做下架处理) - router.post('/api/external-print-accounts/:id/shops/:shopId/pull-products', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.pullShopProducts); + router.post('/api/external-print-accounts/:id/shops/:shopId/pull-products', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.pullShopProducts); // 拉取商家订单(含明细),明细按店铺商品绑定关系写入系统商品关联 router.post('/api/external-print-accounts/:id/shops/:shopId/sync-orders', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.syncShopOrders); // 快递接口(面单模板):查看读取已落库数据,手动同步全量拉取;保存绑定的快递编码,明细单独请求平台接口 - router.get('/api/external-print-accounts/:id/express-interfaces', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintExpressInterface.index); - router.post('/api/external-print-accounts/:id/sync-express-interfaces', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintExpressInterface.sync); - router.put('/api/external-print-accounts/:id/express-interfaces', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintExpressInterface.saveSettings); - router.get('/api/external-print-accounts/:id/express-interfaces/:interfaceId/detail', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintExpressInterface.detail); - router.resources('externalPrintAccounts', '/api/external-print-accounts', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount); + router.get('/api/external-print-accounts/:id/express-interfaces', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintExpressInterface.index); + router.post('/api/external-print-accounts/:id/sync-express-interfaces', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintExpressInterface.sync); + router.put('/api/external-print-accounts/:id/express-interfaces', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintExpressInterface.saveSettings); + router.get('/api/external-print-accounts/:id/express-interfaces/:interfaceId/detail', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintExpressInterface.detail); + router.resources('externalPrintAccounts', '/api/external-print-accounts', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount); // 出入库单与明细(明细共用 stock_items 表,以 bill_type 区分:1入库 2出库) // 单据状态由业务事务推动(审核/推送/完成/驳回/作废/取消/恢复),不提供直接修改状态的接口 // 状态流转(按序校验):审核 / 推送 / 完成 / 取消 / 恢复 / 作废,需在 resources 之前注册避免被 :id 误匹配 diff --git a/backend/app/utils/exportDefs.js b/backend/app/utils/exportDefs.js index 57b1915..bafd964 100644 --- a/backend/app/utils/exportDefs.js +++ b/backend/app/utils/exportDefs.js @@ -443,6 +443,11 @@ const SHOP_PRODUCT_COLUMNS = [ { key: 'id', header: 'ID' }, { key: 'shop_id', header: '店铺ID' }, { key: 'shop_name', header: '店铺名称', expr: '(SELECT s.name FROM shops s WHERE s.id = t.shop_id)' }, + { + key: 'subsidiary_name', + header: '货主', + expr: '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id)', + }, { key: 'bind_type', header: '绑定类型', format: labels(BIND_TYPE_MAP) }, { key: 'product_id', header: '系统商品ID' }, { key: 'product_name', header: '系统商品名称', expr: '(SELECT p.item_name FROM products p WHERE p.id = t.product_id)' }, @@ -464,6 +469,11 @@ const SHOP_COLUMNS = [ { key: 'id', header: 'ID' }, { key: 'code', header: '店铺编码' }, { key: 'name', header: '店铺名称' }, + { + key: 'subsidiary_name', + header: '货主', + expr: '(SELECT s.name FROM principal_subsidiaries s WHERE s.id = t.subsidiary_id)', + }, { key: 'platform', header: '平台', format: labels(PLATFORM_MAP) }, { key: 'contact_name', header: '联系人' }, { key: 'contact_phone', header: '联系电话' }, @@ -893,6 +903,12 @@ const EXPORT_TYPES = { 'AND parse_status = 2 AND shop_product_id IS NOT NULL)' ); } + // 所在公司权限:只能导出自己所属公司(货主)的店铺商品 + if (ctx.access && !ctx.access.isGroup) { + const ids = (ctx.access.ownCompanyIds || []).map(Number); + if (ids.length) wh.raw(`t.subsidiary_id IN (${ids.map(() => '?').join(',')})`, ...ids); + else wh.raw('1 = 0'); + } return buildResult({ columns: SHOP_PRODUCT_COLUMNS, from: 'shop_products t', wh }); }, }, @@ -910,6 +926,12 @@ const EXPORT_TYPES = { .kw([ 't.code', 't.name' ], f.keyword) .eq('t.platform', f.platform) .eq('t.status', f.status); + // 所在公司权限:只能导出自己所属公司(货主)的店铺 + if (ctx.access && !ctx.access.isGroup) { + const ids = (ctx.access.ownCompanyIds || []).map(Number); + if (ids.length) wh.raw(`t.subsidiary_id IN (${ids.map(() => '?').join(',')})`, ...ids); + else wh.raw('1 = 0'); + } return buildResult({ columns: SHOP_COLUMNS, from: 'shops t', wh }); }, }, diff --git a/backend/database/migrations/20261104071200-add-subsidiary-to-shops.js b/backend/database/migrations/20261104071200-add-subsidiary-to-shops.js new file mode 100644 index 0000000..dd9aacf --- /dev/null +++ b/backend/database/migrations/20261104071200-add-subsidiary-to-shops.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 店铺绑定下属公司(货主):shops 增加 subsidiary_id。 + * + * 货主权限仅可见自己所属公司的店铺;外部打单平台添加店铺时必须选择货主。 + * 历史店铺可为空(未绑定货主时仅集团权限可见)。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('shops', 'subsidiary_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '所属货主(下属公司ID)', + references: { model: 'principal_subsidiaries', key: 'id' }, + after: 'principal_id', + }); + await queryInterface.addIndex('shops', [ 'principal_id', 'subsidiary_id' ], { + name: 'idx_shops_principal_subsidiary', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('shops', 'idx_shops_principal_subsidiary'); + await queryInterface.removeColumn('shops', 'subsidiary_id'); + }, +}; diff --git a/backend/database/migrations/20261104071300-add-subsidiary-to-shop-products.js b/backend/database/migrations/20261104071300-add-subsidiary-to-shop-products.js new file mode 100644 index 0000000..2f67e97 --- /dev/null +++ b/backend/database/migrations/20261104071300-add-subsidiary-to-shop-products.js @@ -0,0 +1,34 @@ +'use strict'; + +/** + * 店铺商品绑定下属公司(货主):shop_products 增加 subsidiary_id。 + * + * 取值跟随所属店铺的 subsidiary_id(店铺 = 货主),历史数据按店铺回填; + * 货主权限仅可见自己所属公司的店铺商品。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('shop_products', 'subsidiary_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '所属货主(下属公司ID),跟随店铺', + references: { model: 'principal_subsidiaries', key: 'id' }, + after: 'principal_id', + }); + await queryInterface.addIndex('shop_products', [ 'principal_id', 'subsidiary_id' ], { + name: 'idx_shop_products_principal_subsidiary', + }); + // 按所属店铺的货主回填历史数据 + await queryInterface.sequelize.query( + 'UPDATE shop_products sp' + + ' JOIN shops s ON s.id = sp.shop_id' + + ' SET sp.subsidiary_id = s.subsidiary_id' + + ' WHERE sp.subsidiary_id IS NULL AND s.subsidiary_id IS NOT NULL' + ); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('shop_products', 'idx_shop_products_principal_subsidiary'); + await queryInterface.removeColumn('shop_products', 'subsidiary_id'); + }, +}; diff --git a/frontend/src/api/externalPrintAccount.ts b/frontend/src/api/externalPrintAccount.ts index d503e8f..625e7e3 100644 --- a/frontend/src/api/externalPrintAccount.ts +++ b/frontend/src/api/externalPrintAccount.ts @@ -216,10 +216,11 @@ export function syncExternalPrintShopOrders( ) } -/** 把选中的平台店铺(商家)创建到 OMS 店铺 */export function createShopsFromMerchants(id: number, merchants: ExternalPrintMerchantItem[]) { +/** 把选中的平台店铺(商家)创建到 OMS 店铺:需指定所属货主(下属公司) */ +export function createShopsFromMerchants(id: number, merchants: ExternalPrintMerchantItem[], subsidiaryId: number) { return post<{ created: number; skipped: number; shops: Array<{ id: number; code: string; name: string }> }>( `/external-print-accounts/${id}/shops`, - { merchants }, + { merchants, subsidiary_id: subsidiaryId }, { timeout: 60000 }, ) } diff --git a/frontend/src/api/shop.ts b/frontend/src/api/shop.ts index 20ccc8b..2e7cb84 100644 --- a/frontend/src/api/shop.ts +++ b/frontend/src/api/shop.ts @@ -3,6 +3,10 @@ import { get, post, put, del } from '@/utils/request' export interface ShopItem { id: number principal_id: number + /** 所属货主(下属公司ID) */ + subsidiary_id?: number | null + /** 所属货主名称(列表返回) */ + subsidiary_name?: string code: string name: string platform: string | null @@ -42,6 +46,8 @@ export interface ShopItem { export interface ShopPayload { /** 店铺编码:留空由后端自动生成 OMS 前缀编码 */ code?: string + /** 所属货主(下属公司ID),新增必填 */ + subsidiary_id?: number | null name: string platform?: string contact_name?: string diff --git a/frontend/src/views/ExternalPrintPlatform/Index.vue b/frontend/src/views/ExternalPrintPlatform/Index.vue index 9dc74ed..1c940f9 100644 --- a/frontend/src/views/ExternalPrintPlatform/Index.vue +++ b/frontend/src/views/ExternalPrintPlatform/Index.vue @@ -22,6 +22,7 @@ import DataTable from '@/components/DataTable.vue' import ListPager from '@/components/ListPager.vue' import ExpressInterfaceDialog from './ExpressInterfaceDialog.vue' import { DEFAULT_PAGE_SIZE, useListPage } from '@/composables/useListPage' +import { getPrincipalSubsidiaryOptions } from '@/api/principalSubsidiary' import { formatDateTime } from '@/utils/datetime' /* -------------------- 平台字典(开发者维护,仅用于账号下拉) -------------------- */ @@ -223,6 +224,17 @@ const shopsDialogVisible = ref(false) const shopsAccount = ref(null) const merchantLoading = ref(false) const merchantList = ref([]) +/** 添加店铺时选择的货主(下属公司),必选 */ +const merchantSubsidiaryId = ref(null) +const subsidiaryOptions = ref<{ id: number; name: string }[]>([]) + +async function fetchSubsidiaryOptions() { + try { + subsidiaryOptions.value = await getPrincipalSubsidiaryOptions({ mine: 1 }) + } catch { + subsidiaryOptions.value = [] + } +} const merchantTotal = ref(0) const merchantQuery = reactive({ page: 1, pageSize: 20, keyword: '' }) const selectedMerchants = ref([]) @@ -292,9 +304,17 @@ function canSelectMerchant(row: ExternalPrintMerchantItem) { async function handleAddShops() { if (!shopsAccount.value || !selectedMerchants.value.length) return + if (!merchantSubsidiaryId.value) { + ElMessage.warning('请先选择所属货主(下属公司)') + return + } addingShops.value = true try { - const res = await createShopsFromMerchants(shopsAccount.value.id, selectedMerchants.value) + const res = await createShopsFromMerchants( + shopsAccount.value.id, + selectedMerchants.value, + Number(merchantSubsidiaryId.value), + ) const extra = res.skipped ? `,跳过 ${res.skipped} 个(已添加或无效)` : '' ElMessage.success(`已添加 ${res.created} 个店铺${extra}`) await fetchMerchants() @@ -319,6 +339,7 @@ onMounted(async () => { syncMerchantTableHeight() window.addEventListener('resize', syncMerchantTableHeight) await fetchPlatforms() + await fetchSubsidiaryOptions() await fetchList() }) @@ -494,9 +515,25 @@ onBeforeUnmount(() => { /> @@ -549,6 +586,11 @@ onBeforeUnmount(() => { .merchant-table { width: 100%; } +.merchant-owner { + margin-right: 12px; + font-size: 12px; + color: var(--el-text-color-secondary); +} .merchant-selected { margin-right: 12px; font-size: 12px; diff --git a/frontend/src/views/Shop/Index.vue b/frontend/src/views/Shop/Index.vue index 9ddf80b..3c8fc8e 100644 --- a/frontend/src/views/Shop/Index.vue +++ b/frontend/src/views/Shop/Index.vue @@ -11,6 +11,8 @@ import { type ShopDetail, } from '@/api/shop' import { syncExternalPrintShopProducts, syncExternalPrintShopOrders } from '@/api/externalPrintAccount' +import { getPrincipalSubsidiaryOptions, type PrincipalSubsidiaryOption } from '@/api/principalSubsidiary' +import { getAccessContext } from '@/api/access' import SplitLayout from '@/components/SplitLayout.vue' import ExportButton from '@/components/ExportButton.vue' import DataTable from '@/components/DataTable.vue' @@ -40,15 +42,36 @@ const query = reactive({ pageSize: DEFAULT_PAGE_SIZE, keyword: '', platform: '', + subsidiary_id: '' as string | number, status: '' as string | number, }) +/** 权限范围:所在公司权限只能管理自己所属公司的店铺,且打单平台店铺只读 */ +const isCompanyScope = ref(false) +/** 货主下拉(所在公司权限仅自己所属公司) */ +const subsidiaryOptions = ref([]) + +async function loadAccessInfo() { + 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({ query, fetcher: () => { const params: Record = { ...query } if (!params.keyword) delete params.keyword if (!params.platform) delete params.platform + if (params.subsidiary_id === '') delete params.subsidiary_id if (params.status === '') delete params.status return getShops(params) }, @@ -57,6 +80,7 @@ const { loading, list, total, elapsed, fetchList, search, handlePageChange, hand function reset() { query.keyword = '' query.platform = '' + query.subsidiary_id = '' query.status = '' search() } @@ -65,6 +89,7 @@ function reset() { const exportFilters = computed(() => ({ keyword: query.keyword.trim(), platform: query.platform, + subsidiary_id: query.subsidiary_id, status: query.status, })) @@ -96,6 +121,7 @@ const formRef = ref() const editId = ref(null) const form = reactive({ code: '', + subsidiary_id: null as number | null, name: '', platform: '', contact_name: '', @@ -107,6 +133,7 @@ const form = reactive({ }) // 新增时无需填编码(由后端生成 OMS 前缀编码),故 code 不做必填校验 const rules: FormRules = { + subsidiary_id: [{ required: true, message: '请选择所属货主', trigger: 'change' }], name: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }], status: [{ required: true, message: '请选择状态', trigger: 'change' }], auto_fetch_interval: [ @@ -127,6 +154,9 @@ const rules: FormRules = { function openCreate() { editId.value = null form.code = '' + form.subsidiary_id = isCompanyScope.value && subsidiaryOptions.value.length === 1 + ? subsidiaryOptions.value[0].id + : null form.name = '' form.platform = '' form.contact_name = '' @@ -141,6 +171,7 @@ function openCreate() { function openEdit(row: ShopItem) { editId.value = row.id form.code = row.code + form.subsidiary_id = row.subsidiary_id ?? null form.name = row.name form.platform = row.platform || '' form.contact_name = row.contact_name || '' @@ -158,7 +189,10 @@ async function submitForm() { if (!valid) return submitting.value = true try { - const payload = { ...form } + const payload = { + ...form, + subsidiary_id: form.subsidiary_id == null ? null : Number(form.subsidiary_id), + } if (editId.value == null) { const { code } = await createShop(payload) ElMessage.success(`新增成功,店铺编码:${code}`) @@ -285,7 +319,10 @@ async function handleDelete(row: ShopItem) { } } -onMounted(fetchList) +onMounted(() => { + fetchList() + loadAccessInfo() +})