diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index acfb391..223ea16 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -675,12 +675,15 @@ module.exports = { // ---------- 组合商品 combo_products ---------- comboProductSubItem: { - product_id: { type: 'integer', description: '系统商品ID' }, + product_id: { type: 'integer', description: '系统商品ID(同一组合的明细必须来自同一货主)' }, quantity: { type: 'integer', description: '该商品在组合中的数量' }, }, comboProductItem: { id: { type: 'integer', description: '主键' }, principal_id: { type: 'integer', description: '所属主体ID' }, + subsidiary_id: { type: 'integer', description: '所属货主(下属公司ID),由组合明细的商品货主推导' }, + subsidiary_name: { type: 'string', description: '所属货主名称' }, + subsidiary: { type: 'principalSubsidiaryRef', description: '所属货主(下属公司)' }, code: { type: 'string', description: '组合商品编码' }, name: { type: 'string', description: '组合商品名称' }, price: { type: 'number', description: '组合售价' }, @@ -694,7 +697,7 @@ module.exports = { comboProductListResponse: buildListResponse('comboProductPage'), createComboProductRequest: { principal_id: { type: 'integer', required: true, description: '所属主体ID' }, - code: { type: 'string', required: true, description: '组合商品编码,主体内唯一' }, + code: { type: 'string', description: '组合商品编码;留空由系统生成(ZH + 时间戳 + 随机数,主体内唯一)' }, name: { type: 'string', required: true, description: '组合商品名称' }, price: { type: 'number', required: true, description: '组合售价' }, items: { type: 'array', itemType: 'comboProductSubItem', description: '组合明细:[{ product_id: 1, quantity: 2 }]' }, @@ -703,7 +706,7 @@ module.exports = { }, updateComboProductRequest: { principal_id: { type: 'integer', description: '所属主体ID' }, - code: { type: 'string', description: '组合商品编码' }, + code: { type: 'string', description: '组合商品编码(不可清空;不为空时需主体内唯一)' }, name: { type: 'string', description: '组合商品名称' }, price: { type: 'number', description: '组合售价' }, items: { type: 'array', itemType: 'comboProductSubItem', description: '组合明细:[{ product_id: 1, quantity: 2 }],传入则覆盖原明细' }, diff --git a/backend/app/controller/comboProduct.js b/backend/app/controller/comboProduct.js index 369a186..886c85b 100644 --- a/backend/app/controller/comboProduct.js +++ b/backend/app/controller/comboProduct.js @@ -4,7 +4,7 @@ const { Controller } = require('egg'); const { parsePagination, buildPageResult } = require('../lib/pagination'); /** 明细里冗余返回的系统商品可选字段,便于前端直接展示 */ -const PRODUCT_ATTRS = [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'retail_price' ]; +const PRODUCT_ATTRS = [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'retail_price', 'subsidiary_id' ]; /** * 归一化组合明细:过滤非法行、同一商品去重合并为一条(数量取整且大于 0)。 @@ -71,7 +71,7 @@ async function rebuildOrdersOfCombo(ctx, comboProductId, principalId, transactio } /** - * 组合商品详情/列表统一的明细关联(含系统商品信息) + * 组合商品明细关联(含系统商品信息,带出商品货主) * @param {Object} ctx egg context * @return {Object} sequelize include 配置 */ @@ -79,10 +79,46 @@ function itemsInclude(ctx) { return { model: ctx.model.ComboProductItem, as: 'items', - include: [{ model: ctx.model.Product, as: 'product', attributes: PRODUCT_ATTRS }], + include: [ + { + model: ctx.model.Product, + as: 'product', + attributes: PRODUCT_ATTRS, + include: [ + { model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }, + ], + }, + ], }; } +/** + * 组合商品自身所属货主(由明细商品推导) + * @param {Object} ctx egg context + * @param {Array} itemList 归一化后的明细 + * @param {number} principalId 所属主体ID + * @return {Promise<{ok: boolean, subsidiaryId?: number|null, message?: string}>} 校验结果 + */ +async function resolveItemsSubsidiary(ctx, itemList, principalId) { + if (!itemList.length) return { ok: true, subsidiaryId: null }; + const Op = ctx.app.Sequelize.Op; + const ids = itemList.map(it => it.product_id); + const products = await ctx.model.Product.findAll({ + where: { id: { [Op.in]: ids }, principal_id: principalId }, + attributes: [ 'id', 'subsidiary_id' ], + raw: true, + }); + if (products.length !== ids.length) { + return { ok: false, message: '组合明细中存在无效商品(不存在或不属于当前主体)' }; + } + const ownerIds = new Set(products.map(p => (p.subsidiary_id == null ? 0 : Number(p.subsidiary_id)))); + if (ownerIds.size > 1) { + return { ok: false, message: '组合明细只能包含同一货主的商品,请先移除其它货主的商品' }; + } + const ownerId = [ ...ownerIds ][0]; + return { ok: true, subsidiaryId: ownerId === 0 ? null : ownerId }; +} + /** * @controller ComboProductController 组合商品管理 */ @@ -115,16 +151,36 @@ class ComboProductController extends Controller { } 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) }; + } + const { count, rows } = await ctx.model.ComboProduct.findAndCountAll({ where, offset, limit, order: [[ 'id', 'DESC' ]], distinct: true, - include: [ itemsInclude(ctx) ], + include: [ + itemsInclude(ctx), + { model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }, + ], }); - ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, count, { page, pageSize }) }; + const list = rows.map(row => { + const plain = row.toJSON(); + plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : ''; + plain.items = (plain.items || []).map(it => ({ + ...it, + product: it.product + ? { ...it.product, subsidiary_name: it.product.subsidiary ? it.product.subsidiary.name : '' } + : it.product, + })); + return plain; + }); + ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) }; } /** @@ -138,7 +194,10 @@ class ComboProductController extends Controller { async show() { const { ctx } = this; const combo = await ctx.model.ComboProduct.findByPk(ctx.params.id, { - include: [ itemsInclude(ctx) ], + include: [ + itemsInclude(ctx), + { model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false }, + ], }); if (!combo) { @@ -147,7 +206,21 @@ class ComboProductController extends Controller { return; } - ctx.body = { code: 0, message: 'success', data: combo }; + if (!(await this.canAccess(ctx, combo))) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可查看自己所属公司(货主)的组合商品' }; + return; + } + + const plain = combo.toJSON(); + plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : ''; + plain.items = (plain.items || []).map(it => ({ + ...it, + product: it.product + ? { ...it.product, subsidiary_name: it.product.subsidiary ? it.product.subsidiary.name : '' } + : it.product, + })); + ctx.body = { code: 0, message: 'success', data: plain }; } /** @@ -160,27 +233,55 @@ class ComboProductController extends Controller { */ async create() { const { ctx } = this; - const { principal_id: principalId, code, name, price, items } = ctx.request.body; + const { principal_id: principalId, name, price, items } = ctx.request.body; - if (!principalId || !code || !name || price === undefined) { + if (!principalId || !name || price === undefined) { ctx.status = 400; - ctx.body = { code: 400, message: 'principal_id、code、name、price 为必填项' }; + ctx.body = { code: 400, message: 'principal_id、name、price 为必填项' }; return; } - const exist = await ctx.model.ComboProduct.findOne({ where: { principal_id: principalId, code } }); - if (exist) { - ctx.status = 400; - ctx.body = { code: 400, message: '该主体下组合商品编码已存在' }; - return; + // 组合编码留空时由系统生成(主体内不重复) + let code = String(ctx.request.body.code || '').trim(); + if (!code) { + code = await this.genComboCode(principalId); + if (!code) { + ctx.status = 500; + ctx.body = { code: 500, message: '组合商品编码生成失败,请重试' }; + return; + } + } else { + const exist = await ctx.model.ComboProduct.findOne({ where: { principal_id: principalId, code } }); + if (exist) { + ctx.status = 400; + ctx.body = { code: 400, message: '该主体下组合商品编码已存在' }; + return; + } } const itemList = normalizeItems(items); + // 组合明细必须来自同一货主,组合的 subsidiary_id 由明细推导 + const owner = await resolveItemsSubsidiary(ctx, itemList, principalId); + if (!owner.ok) { + ctx.status = 400; + ctx.body = { code: 400, message: owner.message }; + return; + } + + // 所在公司权限:只能创建自己所属公司(货主)的组合商品 + const access = await ctx.service.access.resolve(ctx.userId, principalId); + if (!access.isGroup && !this.isOwnSubsidiary(access, owner.subsidiaryId)) { + ctx.status = 403; + ctx.body = { code: 403, message: '只能创建自己所属公司(货主)的组合商品' }; + return; + } + const transaction = await ctx.model.transaction(); try { const combo = await ctx.model.ComboProduct.create( { principal_id: principalId, + subsidiary_id: owner.subsidiaryId, code, name, price, @@ -226,6 +327,13 @@ class ComboProductController extends Controller { return; } + // 所在公司权限:仅可维护自己所属公司(货主)的组合商品 + if (!(await this.canAccess(ctx, combo))) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可修改自己所属公司(货主)的组合商品' }; + return; + } + const body = { ...ctx.request.body }; // 主体归属不可通过更新篡改,防止把资源移动到其它主体 delete body.principal_id; @@ -233,6 +341,42 @@ class ComboProductController extends Controller { const itemList = normalizeItems(body.items); delete body.items; + // 组合编码不可清空;传入新编码时需在主体内唯一 + if (Object.prototype.hasOwnProperty.call(body, 'code')) { + const nextCode = String(body.code || '').trim(); + if (!nextCode) { + delete body.code; + } else { + const dup = await ctx.model.ComboProduct.findOne({ + where: { principal_id: combo.principal_id, code: nextCode }, + }); + if (dup && Number(dup.id) !== Number(combo.id)) { + ctx.status = 400; + ctx.body = { code: 400, message: '该主体下组合商品编码已存在' }; + return; + } + body.code = nextCode; + } + } + + // 传入明细时:明细必须来自同一货主,组合货主随之更新 + if (hasItems) { + const owner = await resolveItemsSubsidiary(ctx, itemList, combo.principal_id); + if (!owner.ok) { + ctx.status = 400; + ctx.body = { code: 400, message: owner.message }; + return; + } + // 所在公司权限:不能把组合改到其它货主 + const access = await ctx.service.access.resolve(ctx.userId, combo.principal_id); + if (!access.isGroup && !this.isOwnSubsidiary(access, owner.subsidiaryId)) { + ctx.status = 403; + ctx.body = { code: 403, message: '只能维护自己所属公司(货主)的组合商品' }; + return; + } + body.subsidiary_id = owner.subsidiaryId; + } + const transaction = await ctx.model.transaction(); try { const before = { code: combo.code, name: combo.name, price: combo.price, status: combo.status }; @@ -281,6 +425,50 @@ class ComboProductController extends Controller { } } + /** + * 判断货主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} ctx egg context + * @param {Object} combo 组合商品 model 实例 + * @return {Promise} 是否有权限 + */ + async canAccess(ctx, combo) { + const access = await ctx.service.access.resolve(ctx.userId, combo.principal_id); + if (access.isGroup) return true; + return this.isOwnSubsidiary(access, combo.subsidiary_id); + } + + /** + * 生成组合商品编码:ZH + yyMMddHHmmss + 4 位随机数,重试保证主体内唯一 + * @param {number} principalId 所属主体ID + * @return {Promise} 唯一编码,失败返回 null + */ + async genComboCode(principalId) { + const { ctx } = this; + const pad = num => String(num).padStart(2, '0'); + for (let i = 0; i < 5; i++) { + const d = new Date(); + const ts = + `${pad(d.getFullYear() % 100)}${pad(d.getMonth() + 1)}${pad(d.getDate())}` + + `${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`; + const rand = Math.floor(1000 + Math.random() * 9000); + const code = `ZH${ts}${rand}`; + const exist = await ctx.model.ComboProduct.findOne({ where: { principal_id: principalId, code } }); + if (!exist) return code; + } + return null; + } + /** * @summary 删除组合商品 * @description 物理删除组合商品及其组合明细 @@ -299,6 +487,13 @@ class ComboProductController extends Controller { return; } + // 所在公司权限:仅可删除自己所属公司(货主)的组合商品 + if (!(await this.canAccess(ctx, combo))) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可删除自己所属公司(货主)的组合商品' }; + return; + } + const snapshot = { code: combo.code, name: combo.name }; const transaction = await ctx.model.transaction(); try { diff --git a/backend/app/model/comboProduct.js b/backend/app/model/comboProduct.js index 727cbd9..72fbc4f 100644 --- a/backend/app/model/comboProduct.js +++ b/backend/app/model/comboProduct.js @@ -11,6 +11,7 @@ module.exports = app => { const ComboProduct = app.model.define('combo_product', { id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' }, principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' }, + subsidiary_id: { type: BIGINT.UNSIGNED, allowNull: true, comment: '所属货主(下属公司ID);由组合明细的商品货主推导' }, code: { type: STRING(50), allowNull: false, comment: '组合商品编码' }, name: { type: STRING(100), allowNull: false, comment: '组合商品名称' }, price: { type: DECIMAL(12, 2), allowNull: false, defaultValue: 0, comment: '组合商品售价' }, @@ -22,6 +23,7 @@ module.exports = app => { ComboProduct.associate = () => { app.model.ComboProduct.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' }); + app.model.ComboProduct.belongsTo(app.model.PrincipalSubsidiary, { foreignKey: 'subsidiary_id', as: 'subsidiary' }); // 组合明细:一个组合商品包含多条「系统商品 + 数量」关系 app.model.ComboProduct.hasMany(app.model.ComboProductItem, { foreignKey: 'combo_product_id', as: 'items' }); // 反向关联:店铺商品单向绑定到该组合商品、订单明细解析到该组合商品 diff --git a/backend/app/utils/exportDefs.js b/backend/app/utils/exportDefs.js index e150115..57b1915 100644 --- a/backend/app/utils/exportDefs.js +++ b/backend/app/utils/exportDefs.js @@ -422,6 +422,11 @@ const COMBO_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: 'price', header: '组合售价' }, { key: 'status', header: '状态', format: labels(ENABLE_MAP) }, { @@ -854,6 +859,12 @@ const EXPORT_TYPES = { wh.eq('t.principal_id', ctx.principalId) .kw([ 't.code', 't.name' ], f.keyword) .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: COMBO_COLUMNS, from: 'combo_products t', wh }); }, }, diff --git a/backend/database/migrations/20261104071100-add-subsidiary-to-combo-products.js b/backend/database/migrations/20261104071100-add-subsidiary-to-combo-products.js new file mode 100644 index 0000000..833cf53 --- /dev/null +++ b/backend/database/migrations/20261104071100-add-subsidiary-to-combo-products.js @@ -0,0 +1,27 @@ +'use strict'; + +/** + * 组合商品关联下属公司(货主):combo_products 增加 subsidiary_id。 + * + * 组合明细必须来自同一货主的系统商品,保存时由明细的商品货主推导写入; + * 历史组合可为空(明细商品无货主的旧数据)。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('combo_products', 'subsidiary_id', { + type: Sequelize.BIGINT.UNSIGNED, + allowNull: true, + comment: '所属货主(下属公司ID);由组合明细的商品货主推导', + references: { model: 'principal_subsidiaries', key: 'id' }, + after: 'principal_id', + }); + await queryInterface.addIndex('combo_products', [ 'principal_id', 'subsidiary_id' ], { + name: 'idx_combo_products_principal_subsidiary', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('combo_products', 'idx_combo_products_principal_subsidiary'); + await queryInterface.removeColumn('combo_products', 'subsidiary_id'); + }, +}; diff --git a/frontend/src/api/comboProduct.ts b/frontend/src/api/comboProduct.ts index 146b8b9..886d182 100644 --- a/frontend/src/api/comboProduct.ts +++ b/frontend/src/api/comboProduct.ts @@ -3,6 +3,10 @@ import { get, post, put, del } from '@/utils/request' /** 明细中冗余返回的系统商品信息(后端 include 提供,便于展示) */ export interface ComboItemProduct { id: number + /** 所属货主(下属公司ID) */ + subsidiary_id?: number | null + /** 所属货主名称 */ + subsidiary_name?: string item_code: string item_name: string sku_property: string | null @@ -19,6 +23,10 @@ export interface ComboItem { export interface ComboProductItem { id: number principal_id: number + /** 所属货主(下属公司ID),由组合明细的商品货主推导 */ + subsidiary_id?: number | null + /** 所属货主名称 */ + subsidiary_name?: string code: string name: string price: number | string diff --git a/frontend/src/views/ComboProduct/Index.vue b/frontend/src/views/ComboProduct/Index.vue index 25b6a05..a9a6710 100644 --- a/frontend/src/views/ComboProduct/Index.vue +++ b/frontend/src/views/ComboProduct/Index.vue @@ -60,6 +60,9 @@ interface ComboRow { item_code: string sku_property: string | null stock_unit: string | null + /** 商品所属货主(组合明细必须来自同一货主) */ + subsidiary_id: number | null + subsidiary_name: string } const drawerVisible = ref(false) @@ -76,7 +79,6 @@ const form = reactive({ // 已添加的组合明细(含展示所需快照) const itemRows = ref([]) const rules: FormRules = { - code: [{ required: true, message: '请输入组合商品编码', trigger: 'blur' }], name: [{ required: true, message: '请输入组合商品名称', trigger: 'blur' }], price: [{ required: true, message: '请输入组合售价', trigger: 'blur' }], status: [{ required: true, message: '请选择状态', trigger: 'change' }], @@ -87,11 +89,16 @@ const productKeyword = ref('') const productList = ref([]) const productLoading = ref(false) +/** 已添加明细的货主:同一组合只允许一个货主的商品 */ +const comboOwnerId = computed(() => itemRows.value[0]?.subsidiary_id ?? null) + async function fetchSearchProducts() { productLoading.value = true try { const keyword = productKeyword.value.trim() - productList.value = await searchProducts(keyword || undefined) + // 已确定货主时只搜索该货主的商品,避免误加其它货主 + const params = comboOwnerId.value ? { subsidiary_id: comboOwnerId.value } : undefined + productList.value = await searchProducts(keyword || undefined, params) } catch { // 拦截器已提示 } finally { @@ -103,11 +110,18 @@ function isAdded(productId: number) { return itemRows.value.some((r) => r.product_id === productId) } -/** 添加系统商品:已存在则数量 +1,否则追加一行 */ +/** 添加系统商品:已存在则数量 +1,否则追加一行;不同货主的商品不允许混入同一组合 */ function addProduct(p: ProductSearchItem) { const exist = itemRows.value.find((r) => r.product_id === p.id) if (exist) { exist.quantity += 1 + fetchSearchProducts() + return + } + const ownerId = p.subsidiary_id ?? null + if (itemRows.value.length && comboOwnerId.value !== ownerId) { + const current = itemRows.value[0]?.subsidiary_name || '未指定货主' + ElMessage.warning(`组合明细只能包含同一货主的商品,当前已添加「${current}」的商品`) return } itemRows.value.push({ @@ -117,11 +131,17 @@ function addProduct(p: ProductSearchItem) { item_code: p.item_code, sku_property: p.sku_property, stock_unit: p.stock_unit, + subsidiary_id: ownerId, + subsidiary_name: p.subsidiary_name || '', }) + // 已确定货主:立刻按该货主刷新候选商品,避免继续列出其它货主的商品 + fetchSearchProducts() } function removeRow(index: number) { itemRows.value.splice(index, 1) + // 明细清空后恢复展示全部可选商品 + if (!itemRows.value.length) fetchSearchProducts() } function openCreate() { @@ -151,6 +171,8 @@ function openEdit(row: ComboProductItem) { item_code: it.product?.item_code || '', sku_property: it.product?.sku_property ?? null, stock_unit: it.product?.stock_unit ?? null, + subsidiary_id: it.product?.subsidiary_id ?? null, + subsidiary_name: it.product?.subsidiary_name || '', })) productKeyword.value = '' drawerVisible.value = true @@ -168,6 +190,12 @@ function validateRows(): boolean { ElMessage.warning('每条明细都需选择商品且数量大于 0') return false } + // 同一组合只允许一个货主的商品 + const owners = new Set(itemRows.value.map((r) => r.subsidiary_id ?? 0)) + if (owners.size > 1) { + ElMessage.warning('组合明细只能包含同一货主的商品') + return false + } return true } @@ -287,6 +315,9 @@ onMounted(fetchList) + + + @@ -347,7 +378,7 @@ onMounted(fetchList)
组合商品信息
- + @@ -391,6 +422,9 @@ onMounted(fetchList) > + + +