oms/backend/app/controller/shopProduct.js
liufumingren a9cca6aa6f feat(log): 新增操作日志(店铺商品/系统商品/组合商品),并修正明细口径
操作日志:
- 新增 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>
2026-11-03 03:43:30 +08:00

412 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Controller } = require('egg');
const { parsePagination, buildPageResult } = require('../lib/pagination');
const { ORDER_STATUS } = require('../lib/orderStatus');
/** 允许维护明细的订单状态:已审核(待推送及之后)的明细锁定,不再随绑定关系变化 */
const EDITABLE_ORDER_STATUSES = [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ];
/**
* @controller ShopProductController 店铺商品管理
* 采集自各平台店铺的商品,可单向绑定系统商品(products)或组合商品(combo_products)
*/
class ShopProductController extends Controller {
/**
* @summary 店铺商品列表
* @description 分页查询店铺商品,支持按店铺、绑定状态、关键词(标题/商家编码/平台商品ID)过滤;
* has_unbound_order=1 时只返回「有订单但未绑定系统商品」的店铺商品
* @router get /api/shop-products
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
* @request query integer shop_id 店铺ID,不传则不过滤
* @request query integer bind_type 绑定类型:0未绑定 1系统商品 2组合商品
* @request query integer status 状态:1在售 0下架
* @request query string keyword 关键词,匹配标题、商家编码或平台商品ID
* @request query integer has_unbound_order 传 1 时只返回有订单且未绑定的商品(待处理订单的商品)
* @response 200 shopProductListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { shop_id: shopId, bind_type: bindType, status, keyword, has_unbound_order: hasUnboundOrder } = ctx.query;
const principalId = Number(ctx.state.principalId);
const where = {};
where.principal_id = principalId;
if (shopId) where.shop_id = Number(shopId);
if (bindType !== undefined && bindType !== '') where.bind_type = Number(bindType);
if (status !== undefined && status !== '') where.status = Number(status);
if (keyword) {
where[Op.or] = [
{ title: { [Op.like]: `%${keyword}%` } },
{ outer_code: { [Op.like]: `%${keyword}%` } },
{ outer_item_id: { [Op.like]: `%${keyword}%` } },
];
}
// 有订单未绑定:店铺商品自身未绑定,且被「未绑定系统商品」的订单明细引用
const onlyUnboundOrder = String(hasUnboundOrder) === '1';
if (onlyUnboundOrder) {
where.bind_type = 0;
where.id = {
[Op.in]: ctx.app.Sequelize.literal(
`(SELECT DISTINCT shop_product_id FROM order_status_items WHERE principal_id = ${principalId} ` +
'AND parse_status = 2 AND shop_product_id IS NOT NULL)'
),
};
}
const { count, rows } = await ctx.model.ShopProduct.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] },
{ 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 }));
await this.attachUnboundOrderCount(list, principalId);
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
}
/**
* 回填每个店铺商品的「待处理订单数」(未绑定系统商品的订单明细按订单去重计数),
* 便于列表上直接看出哪些商品还有订单等绑定
* @param {Array} list 店铺商品列表
* @param {number} principalId 主体ID
* @return {Promise<void>} 无返回值
*/
async attachUnboundOrderCount(list, principalId) {
const { ctx } = this;
const ids = list.map(row => Number(row.id)).filter(id => Number.isInteger(id) && id > 0);
if (!ids.length) return;
const Op = this.app.Sequelize.Op;
const rows = await ctx.model.OrderStatusItem.findAll({
where: { principal_id: principalId, parse_status: 2, shop_product_id: { [Op.in]: ids } },
attributes: [
'shop_product_id',
[ ctx.app.Sequelize.fn('COUNT', ctx.app.Sequelize.fn('DISTINCT', ctx.app.Sequelize.col('order_id'))), 'order_count' ],
],
group: [ 'shop_product_id' ],
raw: true,
});
const countByShopProduct = new Map(rows.map(row => [ Number(row.shop_product_id), Number(row.order_count) || 0 ]));
for (const row of list) row.unbound_order_count = countByShopProduct.get(Number(row.id)) || 0;
}
/**
* @summary 店铺商品详情
* @description 按主键查询,带出店铺、绑定的系统商品与组合商品
* @router get /api/shop-products/{id}
* @apikey
* @request path integer *id 主键ID
* @response 200 baseResponse success
*/
async show() {
const { ctx } = this;
const item = await ctx.model.ShopProduct.findByPk(ctx.params.id, {
include: [
{ model: ctx.model.Shop, as: 'shop', attributes: [ 'id', 'name', 'platform' ] },
{ model: ctx.model.Product, as: 'product', attributes: [ 'id', 'item_code', 'item_name' ] },
{ model: ctx.model.ComboProduct, as: 'comboProduct', attributes: [ 'id', 'code', 'name' ] },
],
});
if (!item) {
ctx.status = 404;
ctx.body = { code: 404, message: '店铺商品不存在' };
return;
}
ctx.body = { code: 0, message: 'success', data: item };
}
/**
* @summary 绑定系统商品或组合商品
* @description 单向绑定:bind_type=1 绑系统商品(传 product_id)、2 绑组合商品(传 combo_product_id)、0 解绑;
* 绑定的商品必须属于当前主体
* @router post /api/shop-products/{id}/bind
* @apikey
* @request path integer *id 店铺商品主键ID
* @request body bindShopProductRequest *body
* @response 200 baseResponse success
*/
async bind() {
const { ctx } = this;
const { bind_type: bindType, product_id: productId, combo_product_id: comboProductId } = ctx.request.body;
const principalId = ctx.state.principalId;
const item = await ctx.model.ShopProduct.findByPk(ctx.params.id);
if (!item) {
ctx.status = 404;
ctx.body = { code: 404, message: '店铺商品不存在' };
return;
}
const type = Number(bindType);
if (![ 0, 1, 2 ].includes(type)) {
ctx.status = 400;
ctx.body = { code: 400, message: 'bind_type 只能为 0未绑定 1系统商品 2组合商品' };
return;
}
// 先记下变更前的绑定,便于日志里写清「从什么改成了什么」
const beforeLabel = await this.describeBinding(item);
const data = { bind_type: type, product_id: null, combo_product_id: null };
let boundProduct = null;
let boundCombo = null;
if (type === 1) {
if (!productId) {
ctx.status = 400;
ctx.body = { code: 400, message: '绑定系统商品时 product_id 为必填项' };
return;
}
const product = await ctx.model.Product.findOne({ where: { id: productId, principal_id: principalId } });
if (!product) {
ctx.status = 404;
ctx.body = { code: 404, message: '系统商品不存在或不属于当前主体' };
return;
}
data.product_id = Number(productId);
boundProduct = product;
}
if (type === 2) {
if (!comboProductId) {
ctx.status = 400;
ctx.body = { code: 400, message: '绑定组合商品时 combo_product_id 为必填项' };
return;
}
const combo = await ctx.model.ComboProduct.findOne({ where: { id: comboProductId, principal_id: principalId } });
if (!combo) {
ctx.status = 404;
ctx.body = { code: 404, message: '组合商品不存在或不属于当前主体' };
return;
}
data.combo_product_id = Number(comboProductId);
boundCombo = combo;
}
await item.update(data);
const syncedItems = await this.syncOrderItems(item, boundProduct, boundCombo);
// 操作记录:绑定 / 解绑都留痕(谁在什么时候把哪个平台商品绑到了哪个商品)
const afterLabel = type === 0
? '未绑定'
: type === 1
? `系统商品 ${boundProduct.item_name || ''}(${boundProduct.item_code || ''})`
: `组合商品 ${boundCombo.name || ''}(${boundCombo.code || ''})`;
await ctx.service.operationLog.record({
targetType: 'shop_product',
targetId: item.id,
action: type === 0 ? 'unbind' : 'bind',
title: type === 0 ? `解除绑定(原绑定:${beforeLabel})` : `绑定${afterLabel}`,
detail: {
target: item.title || item.outer_item_id || `#${item.id}`,
outer_item_id: item.outer_item_id,
outer_sku_id: item.outer_sku_id,
before: beforeLabel,
after: afterLabel,
order_items_updated: syncedItems,
},
});
ctx.body = { code: 0, message: 'success', data: { id: item.id, order_items_updated: syncedItems } };
}
/**
* 描述店铺商品当前的绑定对象(日志里写「原绑定」用)
* @param {Object} item 店铺商品实例
* @return {Promise<string>} 描述文本
*/
async describeBinding(item) {
const { ctx } = this;
const bindType = Number(item.bind_type);
if (bindType === 1 && item.product_id) {
const product = await ctx.model.Product.findByPk(item.product_id, { attributes: [ 'id', 'item_code', 'item_name' ] });
return product ? `系统商品 ${product.item_name || ''}(${product.item_code || ''})` : `系统商品 #${item.product_id}`;
}
if (bindType === 2 && item.combo_product_id) {
const combo = await ctx.model.ComboProduct.findByPk(item.combo_product_id, { attributes: [ 'id', 'code', 'name' ] });
return combo ? `组合商品 ${combo.name || ''}(${combo.code || ''})` : `组合商品 #${item.combo_product_id}`;
}
return '未绑定';
}
/**
* 绑定关系变化后回写订单明细:
* 老明细表(order_items)保持「平台行 1:1」,只同步绑定状态与商品快照;
* 订单页使用的状态明细表(order_status_items)按绑定关系重新展开,
* 绑定组合商品时会拆成组合内子商品行(最小单位)。
* @param {Object} shopProduct 店铺商品实例
* @param {Object|null} product 绑定的系统商品
* @param {Object|null} combo 绑定的组合商品
* @return {Promise<number>} 更新的明细数量(两张表合计)
*/
async syncOrderItems(shopProduct, product, combo) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const where = { shop_product_id: shopProduct.id };
const affectedItems = await ctx.model.OrderStatusItem.findAll({
where,
attributes: [ 'order_id' ],
raw: true,
});
const orderIds = [ ...new Set(affectedItems.map(row => Number(row.order_id)).filter(id => id > 0)) ];
// 历史明细可能没有平台快照(功能上线前拉的单),绑定前先按当前未绑定状态补一份,保证以后解绑还能还原
await this.ensurePlatformSnapshot(where);
// 老表(order_items)只回写「待审核 / 异常」的订单:
// 已审核(待推送/委外中/配送/历史…)的明细在审核时已锁库存、可能已下发仓库,不能随绑定关系变化
const editableIndexRows = orderIds.length
? await ctx.model.OrderIndex.findAll({
where: { id: { [ Op.in ]: orderIds }, current_status: { [ Op.in ]: EDITABLE_ORDER_STATUSES } },
attributes: [ 'order_no' ],
raw: true,
})
: [];
const editableOrderNos = editableIndexRows.map(row => row.order_no).filter(Boolean);
const editableLegacyRows = editableOrderNos.length
? await ctx.model.Order.findAll({
where: { order_no: { [ Op.in ]: editableOrderNos } },
attributes: [ 'id' ],
raw: true,
})
: [];
const legacyWhere = {
...where,
order_id: { [ Op.in ]: editableLegacyRows.map(row => Number(row.id)) },
};
let updated = 0;
if (product) {
// 老表保留平台原样字段,只同步绑定结果(订单页/推送用的状态明细由 rebuildOrderItems 生成)
const [ affected ] = await ctx.model.OrderItem.update(
{ product_id: product.id, combo_product_id: null, item_type: 1, parse_status: 1, parse_msg: null },
{ where: legacyWhere }
);
updated = affected;
} else if (combo) {
const [ affected ] = await ctx.model.OrderItem.update(
{ product_id: null, combo_product_id: combo.id, item_type: 2, parse_status: 1, parse_msg: null },
{ where: legacyWhere }
);
updated = affected;
} else {
// 解绑:清空系统商品关联,并把明细字段还原为绑定前的平台快照(platform_snapshot)
const reset = {
product_id: null,
combo_product_id: null,
item_type: 0,
parse_status: 2,
parse_msg: '店铺商品未绑定系统商品,已保留平台原样数据',
};
const orderRows = await ctx.model.OrderItem.findAll({
where: legacyWhere,
attributes: [ 'id', 'platform_snapshot' ],
raw: true,
});
for (const row of orderRows) {
const [ affected ] = await ctx.model.OrderItem.update(
{ ...reset, ...this._legacyFieldsFromSnapshot(row.platform_snapshot) },
{ where: { id: row.id } }
);
updated += affected;
}
}
// 状态明细整体重建:未绑定 / 系统商品 / 组合拆分(行数会变化,不能逐行 update);
// 只重建待审核/异常,已审核订单的明细保持审核时的状态
updated += await ctx.service.orderItemResolve.rebuildOrderItems(orderIds);
return updated;
}
/**
* 平台快照转老明细表(order_items)字段
* @param {Object|null} snapshot 平台快照
* @return {Object} 需要还原的字段
*/
_legacyFieldsFromSnapshot(snapshot) {
const data = snapshot && typeof snapshot === 'object' ? snapshot : {};
return {
name: data.item_name || null,
sku_code: data.sku_code || null,
spec: data.spec || null,
image: data.image || null,
};
}
/**
* 为缺少平台快照的历史明细补写快照(仅未绑定的明细,此时字段仍是平台原样)
* @param {Object} where 明细筛选条件
* @return {Promise<void>} 无返回值
*/
async ensurePlatformSnapshot(where) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const scope = {
...where,
platform_snapshot: { [Op.is]: null },
parse_status: { [Op.ne]: 1 },
};
const orderRows = await ctx.model.OrderItem.findAll({
where: scope,
attributes: [ 'id', 'name', 'sku_code', 'spec', 'image' ],
raw: true,
});
for (const row of orderRows) {
await ctx.model.OrderItem.update(
{
platform_snapshot: {
item_code: row.sku_code || null,
item_name: row.name || null,
sku_code: row.sku_code || null,
spec: row.spec || null,
image: row.image || null,
},
},
{ where: { id: row.id } }
);
}
const statusRows = await ctx.model.OrderStatusItem.findAll({
where: scope,
attributes: [ 'id', 'order_line_no', 'item_code', 'item_name', 'sku_code', 'spec', 'image', 'plan_qty', 'actual_price' ],
raw: true,
});
for (const row of statusRows) {
await ctx.model.OrderStatusItem.update(
{
platform_snapshot: {
item_code: row.item_code || null,
item_name: row.item_name || null,
sku_code: row.sku_code || null,
spec: row.spec || null,
image: row.image || null,
// 折叠回平台行需要原行号 / 原数量 / 原单价
line_no: row.order_line_no == null ? '' : String(row.order_line_no),
plan_qty: Number(row.plan_qty) || 0,
actual_price: row.actual_price == null ? null : Number(row.actual_price),
},
},
{ where: { id: row.id } }
);
}
}
}
module.exports = ShopProductController;