操作日志: - 新增 operation_logs 表与 model/service/controller,接口 GET /api/operation-logs (按 target_type + target_id 分页查询,主体隔离,按时间倒序) - 店铺商品:采集进系统、平台已无此商品被移出/下架、绑定/解绑均留痕(含原绑定与受影响订单数) - 系统商品:新增 / 修改(记录变更字段与前后值)/ 删除 - 组合商品:新增 / 修改(含子商品构成前后值)/ 删除 - 日志为旁路能力:写入失败只告警,不影响业务操作 明细口径修正: - 已审核订单(待推送及之后)的明细在审核时已锁定,重算时按状态过滤, 重新拉单与改绑定都不再波及(原先会覆盖老表 order_items 的解析结果) - 组合商品构成/系统商品资料变更后,重建绑定方的待审核订单明细与商品摘要; 并修正重建时读不到同事务内未提交构成的问题(loadBindings/loadComboItems 传事务) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
326 lines
11 KiB
JavaScript
326 lines
11 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' ];
|
||
|
||
/**
|
||
* 归一化组合明细:过滤非法行、同一商品去重合并为一条(数量取整且大于 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 }],
|
||
};
|
||
}
|
||
|
||
/**
|
||
* @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 { count, rows } = await ctx.model.ComboProduct.findAndCountAll({
|
||
where,
|
||
offset,
|
||
limit,
|
||
order: [[ 'id', 'DESC' ]],
|
||
distinct: true,
|
||
include: [ itemsInclude(ctx) ],
|
||
});
|
||
|
||
ctx.body = { code: 0, message: 'success', data: buildPageResult(rows, 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) ],
|
||
});
|
||
|
||
if (!combo) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '组合商品不存在' };
|
||
return;
|
||
}
|
||
|
||
ctx.body = { code: 0, message: 'success', data: combo };
|
||
}
|
||
|
||
/**
|
||
* @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, code, name, price, items } = ctx.request.body;
|
||
|
||
if (!principalId || !code || !name || price === undefined) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: 'principal_id、code、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;
|
||
}
|
||
|
||
const itemList = normalizeItems(items);
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
const combo = await ctx.model.ComboProduct.create(
|
||
{
|
||
principal_id: principalId,
|
||
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;
|
||
}
|
||
|
||
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;
|
||
|
||
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;
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @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;
|
||
}
|
||
|
||
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;
|