- combo_products 新增 subsidiary_id(由组合明细的商品货主推导),列表展示货主 - 组合明细只允许来自同一货主的系统商品,混货主直接拒绝(接口 + 页面提示) - 组合商品按货主范围隔离:货主权限仅可见/可维护自己所属公司的组合,创建也不能越界 - 组合编码可留空,由系统生成 ZH + 时间戳 + 随机数(主体内唯一);更新不可清空 - 组合导出新增货主列并按范围收窄;商品选择列表带出货主,选定货主后候选商品自动收窄 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
521 lines
19 KiB
JavaScript
521 lines
19 KiB
JavaScript
'use strict';
|
||
|
||
const { Controller } = require('egg');
|
||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||
|
||
/** 明细里冗余返回的系统商品可选字段,便于前端直接展示 */
|
||
const PRODUCT_ATTRS = [ 'id', 'item_code', 'item_name', 'sku_property', 'stock_unit', 'retail_price', 'subsidiary_id' ];
|
||
|
||
/**
|
||
* 归一化组合明细:过滤非法行、同一商品去重合并为一条(数量取整且大于 0)。
|
||
* @param {Array} items 原始明细 [{ product_id, quantity }]
|
||
* @return {Array} 归一化后的明细
|
||
*/
|
||
function normalizeItems(items) {
|
||
if (!Array.isArray(items)) return [];
|
||
const map = new Map();
|
||
for (const it of items) {
|
||
const productId = Number(it && it.product_id);
|
||
const quantity = Number(it && it.quantity);
|
||
if (!productId || !quantity || quantity <= 0) continue;
|
||
map.set(productId, Math.floor(quantity));
|
||
}
|
||
return Array.from(map, ([ product_id, quantity ]) => ({ product_id, quantity }));
|
||
}
|
||
|
||
/**
|
||
* 用给定明细覆盖组合商品的全部明细关系(先清空再写入)。
|
||
* @param {Object} ctx egg context
|
||
* @param {number} comboProductId 组合商品ID
|
||
* @param {number} principalId 所属主体ID
|
||
* @param {Array} itemList 归一化后的明细
|
||
* @param {Object} transaction 事务
|
||
*/
|
||
async function replaceComboItems(ctx, comboProductId, principalId, itemList, transaction) {
|
||
await ctx.model.ComboProductItem.destroy({ where: { combo_product_id: comboProductId }, transaction });
|
||
if (!itemList.length) return;
|
||
await ctx.model.ComboProductItem.bulkCreate(
|
||
itemList.map(it => ({
|
||
principal_id: principalId,
|
||
combo_product_id: comboProductId,
|
||
product_id: it.product_id,
|
||
quantity: it.quantity,
|
||
})),
|
||
{ transaction }
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 组合商品被修改后,重建引用它的订单明细
|
||
*
|
||
* 绑定了该组合的店铺商品,其待审核/异常订单明细是按组合构成展开的(子商品行 + 数量 + 单价),
|
||
* 组合构成或编码/名称一变,这些订单的明细与列表里的商品摘要就要跟着重算;
|
||
* 已审核(待推送及之后)的订单不受影响(明细在审核时已锁定)。
|
||
* @param {Object} ctx egg context
|
||
* @param {number} comboProductId 组合商品ID
|
||
* @param {number} principalId 所属主体ID
|
||
* @param {Object} [transaction] 事务
|
||
* @return {Promise<number>} 重建的明细行数
|
||
*/
|
||
async function rebuildOrdersOfCombo(ctx, comboProductId, principalId, transaction) {
|
||
const shopProducts = await ctx.model.ShopProduct.findAll({
|
||
where: { principal_id: principalId, combo_product_id: comboProductId, bind_type: 2 },
|
||
attributes: [ 'id' ],
|
||
raw: true,
|
||
transaction,
|
||
});
|
||
return ctx.service.orderItemResolve.rebuildOrdersByShopProducts(
|
||
shopProducts.map(row => Number(row.id)),
|
||
{ transaction }
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 组合商品明细关联(含系统商品信息,带出商品货主)
|
||
* @param {Object} ctx egg context
|
||
* @return {Object} sequelize include 配置
|
||
*/
|
||
function itemsInclude(ctx) {
|
||
return {
|
||
model: ctx.model.ComboProductItem,
|
||
as: 'items',
|
||
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 组合商品管理
|
||
*/
|
||
class ComboProductController extends Controller {
|
||
/**
|
||
* @summary 组合商品列表
|
||
* @description 分页查询组合商品,支持按主体、关键词与状态过滤;items 为组合明细关系
|
||
* @router get /api/combo-products
|
||
* @apikey
|
||
* @request query integer page 页码,默认 1
|
||
* @request query integer pageSize 每页条数,默认 20
|
||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||
* @request query string keyword 关键词,匹配组合商品编码或名称
|
||
* @request query integer status 状态:1上架 0下架,不传则不过滤
|
||
* @response 200 comboProductListResponse success
|
||
*/
|
||
async index() {
|
||
const { ctx } = this;
|
||
const Op = this.app.Sequelize.Op;
|
||
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
|
||
const { keyword, status } = ctx.query;
|
||
const principalId = ctx.state.principalId;
|
||
|
||
const where = { principal_id: principalId };
|
||
if (keyword) {
|
||
where[Op.or] = [
|
||
{ code: { [Op.like]: `%${keyword}%` } },
|
||
{ name: { [Op.like]: `%${keyword}%` } },
|
||
];
|
||
}
|
||
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),
|
||
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
|
||
],
|
||
});
|
||
|
||
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 }) };
|
||
}
|
||
|
||
/**
|
||
* @summary 组合商品详情
|
||
* @description 按主键查询组合商品,items 为组合明细关系(系统商品ID + 数量)
|
||
* @router get /api/combo-products/{id}
|
||
* @apikey
|
||
* @request path integer *id 组合商品主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async show() {
|
||
const { ctx } = this;
|
||
const combo = await ctx.model.ComboProduct.findByPk(ctx.params.id, {
|
||
include: [
|
||
itemsInclude(ctx),
|
||
{ model: ctx.model.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
|
||
],
|
||
});
|
||
|
||
if (!combo) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '组合商品不存在' };
|
||
return;
|
||
}
|
||
|
||
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 };
|
||
}
|
||
|
||
/**
|
||
* @summary 新增组合商品
|
||
* @description 同一主体下组合商品编码 code 唯一;items 为组合明细 [{ product_id, quantity }],写入关系表
|
||
* @router post /api/combo-products
|
||
* @apikey
|
||
* @request body createComboProductRequest *body
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async create() {
|
||
const { ctx } = this;
|
||
const { principal_id: principalId, name, price, items } = ctx.request.body;
|
||
|
||
if (!principalId || !name || price === undefined) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: 'principal_id、name、price 为必填项' };
|
||
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,
|
||
status: ctx.request.body.status,
|
||
remark: ctx.request.body.remark,
|
||
},
|
||
{ transaction }
|
||
);
|
||
await replaceComboItems(ctx, combo.id, principalId, itemList, transaction);
|
||
await ctx.service.operationLog.record({
|
||
targetType: 'combo_product',
|
||
targetId: combo.id,
|
||
principalId,
|
||
transaction,
|
||
action: 'create',
|
||
title: `新增组合商品:${name}(${code}),包含 ${itemList.length} 个子商品`,
|
||
detail: { code, name, price, items: itemList },
|
||
});
|
||
await transaction.commit();
|
||
ctx.body = { code: 0, message: 'success', data: { id: combo.id } };
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @summary 更新组合商品
|
||
* @description 未传入的字段保持原值;传入 items 时以之覆盖关系表中的组合明细
|
||
* @router put /api/combo-products/{id}
|
||
* @apikey
|
||
* @request path integer *id 组合商品主键ID
|
||
* @request body updateComboProductRequest *body
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async update() {
|
||
const { ctx } = this;
|
||
const combo = await ctx.model.ComboProduct.findByPk(ctx.params.id);
|
||
|
||
if (!combo) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '组合商品不存在' };
|
||
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;
|
||
const hasItems = Object.prototype.hasOwnProperty.call(body, 'items');
|
||
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 };
|
||
const beforeItems = hasItems
|
||
? (await ctx.model.ComboProductItem.findAll({
|
||
where: { combo_product_id: combo.id },
|
||
attributes: [ 'product_id', 'quantity' ],
|
||
raw: true,
|
||
transaction,
|
||
}))
|
||
: null;
|
||
|
||
await combo.update(body, { transaction });
|
||
if (hasItems) {
|
||
await replaceComboItems(ctx, combo.id, combo.principal_id, itemList, transaction);
|
||
}
|
||
// 组合构成/编码/名称变更后,重算已绑定该组合的待审核订单明细与商品摘要
|
||
await rebuildOrdersOfCombo(ctx, combo.id, combo.principal_id, transaction);
|
||
|
||
// 操作记录:写清改了哪些字段与构成变化
|
||
const changed = Object.keys(before).filter(key => String(before[key] ?? '') !== String(combo[key] ?? ''));
|
||
const itemsChanged = hasItems && JSON.stringify(beforeItems || []) !== JSON.stringify(
|
||
itemList.map(it => ({ product_id: it.product_id, quantity: it.quantity })).sort((a, b) => a.product_id - b.product_id)
|
||
);
|
||
if (changed.length || itemsChanged) {
|
||
const parts = [ ...changed, ...(itemsChanged ? [ '子商品构成' ] : []) ];
|
||
await ctx.service.operationLog.record({
|
||
targetType: 'combo_product',
|
||
targetId: combo.id,
|
||
principalId: combo.principal_id,
|
||
transaction,
|
||
action: 'update',
|
||
title: `修改组合商品:${combo.name}(${combo.code})— 变更 ${parts.join('、')}`,
|
||
detail: {
|
||
fields: changed.reduce((acc, key) => ({ ...acc, [key]: { before: before[key], after: combo[key] } }), {}),
|
||
items: itemsChanged ? { before: beforeItems, after: itemList } : null,
|
||
},
|
||
});
|
||
}
|
||
|
||
await transaction.commit();
|
||
ctx.body = { code: 0, message: 'success', data: { id: combo.id } };
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
throw err;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 判断货主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<boolean>} 是否有权限
|
||
*/
|
||
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<string|null>} 唯一编码,失败返回 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 物理删除组合商品及其组合明细
|
||
* @router delete /api/combo-products/{id}
|
||
* @apikey
|
||
* @request path integer *id 组合商品主键ID
|
||
* @response 200 baseResponse success
|
||
*/
|
||
async destroy() {
|
||
const { ctx } = this;
|
||
const combo = await ctx.model.ComboProduct.findByPk(ctx.params.id);
|
||
|
||
if (!combo) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '组合商品不存在' };
|
||
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 {
|
||
await ctx.model.ComboProductItem.destroy({ where: { combo_product_id: combo.id }, transaction });
|
||
await combo.destroy({ transaction });
|
||
await ctx.service.operationLog.record({
|
||
targetType: 'combo_product',
|
||
targetId: combo.id,
|
||
principalId: combo.principal_id,
|
||
transaction,
|
||
action: 'delete',
|
||
title: `删除组合商品:${snapshot.name}(${snapshot.code})`,
|
||
detail: snapshot,
|
||
});
|
||
await transaction.commit();
|
||
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
|
||
} catch (err) {
|
||
await transaction.rollback();
|
||
throw err;
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = ComboProductController;
|