oms/backend/app/controller/product.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

303 lines
11 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');
/** 库存类型:与 product_stocks.item_type 对齐(ZC=正品 / CC=残次品) */
const STOCK_TYPE_CC = 'CC';
/** 无库存记录时的库存字段默认值 */
function emptyStockFields() {
return { zc_available: 0, zc_locked: 0, cc_available: 0, cc_locked: 0 };
}
/**
* 为商品附加库存字段(数据源为 product_stocks,按 item_type 聚合):
* - zc_available 正品可用 / zc_locked 正品锁定
* - cc_available 次品可用 / cc_locked 次品锁定
* @param {Object} ctx egg context
* @param {Number} principalId 所属主体ID
* @param {Array} products 商品 model 实例或 plain 对象数组
* @return {Promise<Array>} 附带库存字段的商品 plain 对象数组
*/
async function attachStockFields(ctx, principalId, products) {
const list = products.map(p => (p && p.toJSON ? p.toJSON() : p));
const productIds = list.map(p => Number(p.id)).filter(Boolean);
const stockMap = new Map();
if (productIds.length) {
const stocks = await ctx.model.ProductStock.findAll({
where: { principal_id: principalId, product_id: { [ctx.app.Sequelize.Op.in]: productIds } },
attributes: [ 'product_id', 'item_type', 'available', 'lock_quantity' ],
});
for (const s of stocks) {
const pid = Number(s.product_id);
const cur = stockMap.get(pid) || emptyStockFields();
if (s.item_type === STOCK_TYPE_CC) {
cur.cc_available = Number(s.available) || 0;
cur.cc_locked = Number(s.lock_quantity) || 0;
} else {
cur.zc_available = Number(s.available) || 0;
cur.zc_locked = Number(s.lock_quantity) || 0;
}
stockMap.set(pid, cur);
}
}
return list.map(p => ({ ...p, ...(stockMap.get(Number(p.id)) || emptyStockFields()) }));
}
/**
* @controller ProductController 商品管理
*/
class ProductController extends Controller {
/**
* @summary 商品列表
* @description 分页查询商品,支持按主体、关键词与状态过滤
* @router get /api/products
* @apikey
* @request query integer page 页码,默认 1
* @request query integer pageSize 每页条数,默认 20
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
* @request query string keyword 关键词,匹配商品编码或名称
* @request query string category_name 分类名称,精确匹配
* @request query string brand_name 品牌名称,精确匹配
* @request query string stock_unit 库存单位,精确匹配
* @request query integer status 状态:1上架 0下架,不传则不过滤
* @response 200 productListResponse success
*/
async index() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const { page, pageSize, offset, limit } = parsePagination(ctx.query);
const { keyword, category_name: categoryName, brand_name: brandName, stock_unit: stockUnit, status } = ctx.query;
const principalId = ctx.state.principalId;
const where = {};
where.principal_id = principalId;
if (keyword) {
where[Op.or] = [
{ item_code: { [Op.like]: `%${keyword}%` } },
{ goods_code: { [Op.like]: `%${keyword}%` } },
{ barcode: { [Op.like]: `%${keyword}%` } },
{ item_name: { [Op.like]: `%${keyword}%` } },
];
}
if (categoryName) where.category_name = categoryName;
if (brandName) where.brand_name = brandName;
if (stockUnit) where.stock_unit = stockUnit;
if (status !== undefined && status !== '') where.status = Number(status);
const { count, rows } = await ctx.model.Product.findAndCountAll({
where,
offset,
limit,
order: [[ 'id', 'DESC' ]],
});
// 附带库存字段(正品/次品的可用与锁定数量),取自 product_stocks
const list = await attachStockFields(ctx, principalId, rows);
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
}
/**
* @summary 商品详情
* @description 按主键查询商品
* @router get /api/products/{id}
* @apikey
* @request path integer *id 商品主键ID
* @response 200 baseResponse success
*/
async show() {
const { ctx } = this;
const product = await ctx.model.Product.findByPk(ctx.params.id);
if (!product) {
ctx.status = 404;
ctx.body = { code: 404, message: '商品不存在' };
return;
}
const [ data ] = await attachStockFields(ctx, product.principal_id, [ product ]);
ctx.body = { code: 0, message: 'success', data };
}
/**
* @summary 新增商品
* @description 同一主体下商品编码 item_code 唯一
* @router post /api/products
* @apikey
* @request body createProductRequest *body
* @response 200 baseResponse success
*/
async create() {
const { ctx } = this;
const {
principal_id: principalId,
item_code: itemCode,
item_name: itemName,
retail_price: retailPrice,
} = ctx.request.body;
if (!principalId || !itemCode || !itemName || retailPrice === undefined) {
ctx.status = 400;
ctx.body = { code: 400, message: 'principal_id、item_code、item_name、retail_price 为必填项' };
return;
}
const exist = await ctx.model.Product.findOne({ where: { principal_id: principalId, item_code: itemCode } });
if (exist) {
ctx.status = 400;
ctx.body = { code: 400, message: '该主体下商品编码已存在' };
return;
}
const product = await ctx.model.Product.create(ctx.request.body);
await ctx.service.operationLog.record({
targetType: 'product',
targetId: product.id,
principalId,
action: 'create',
title: `新增商品:${product.item_name || ''}(${product.item_code || ''})`,
detail: {
item_code: product.item_code,
item_name: product.item_name,
sku_property: product.sku_property,
retail_price: product.retail_price,
},
});
ctx.body = { code: 0, message: 'success', data: { id: product.id } };
}
/**
* @summary 更新商品
* @description 未传入的字段保持原值
* @router put /api/products/{id}
* @apikey
* @request path integer *id 商品主键ID
* @request body updateProductRequest *body
* @response 200 baseResponse success
*/
async update() {
const { ctx } = this;
const product = await ctx.model.Product.findByPk(ctx.params.id);
if (!product) {
ctx.status = 404;
ctx.body = { code: 404, message: '商品不存在' };
return;
}
// 主体归属不可通过更新篡改,防止把资源移动到其它主体
const before = {
item_code: product.item_code,
item_name: product.item_name,
sku_property: product.sku_property,
retail_price: product.retail_price,
status: product.status,
};
delete ctx.request.body.principal_id;
await product.update(ctx.request.body);
// 操作记录:写清改了哪些字段(前后值)
const changed = Object.keys(before).filter(key => String(before[key] ?? '') !== String(product[key] ?? ''));
if (changed.length) {
await ctx.service.operationLog.record({
targetType: 'product',
targetId: product.id,
principalId: product.principal_id,
action: 'update',
title: `修改商品:${product.item_name || ''}(${product.item_code || ''})— 变更字段 ${changed.join('、')}`,
detail: changed.reduce((acc, key) => ({ ...acc, [key]: { before: before[key], after: product[key] } }), {}),
});
}
// 商品编码/名称/规格变化后,重算绑定该商品的待审核订单明细与商品摘要(已审核订单不受影响)
await this.rebuildBoundOrders(product.id, product.principal_id);
ctx.body = { code: 0, message: 'success', data: { id: product.id } };
}
/**
* 重建绑定到该商品的店铺商品所属订单的明细(仅待审核/异常)
* @param {number} productId 系统商品ID
* @param {number} principalId 所属主体ID
* @return {Promise<number>} 重建的明细行数
*/
async rebuildBoundOrders(productId, principalId) {
const { ctx } = this;
const shopProducts = await ctx.model.ShopProduct.findAll({
where: { principal_id: principalId, product_id: productId, bind_type: 1 },
attributes: [ 'id' ],
raw: true,
});
return ctx.service.orderItemResolve.rebuildOrdersByShopProducts(shopProducts.map(row => Number(row.id)));
}
/**
* @summary 商品快速搜索(聚合)
* @description 按 商品编码 / 货品编码 / 条码 / 商品名称 聚合模糊匹配,仅返回启用商品,供出入库明细快速选择
* @router get /api/products/search
* @apikey
* @request query string keyword 关键词,匹配商品编码/货品编码/条码/商品名称
* @response 200 productSearchResponse success
*/
async search() {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const keyword = (ctx.query.keyword || '').trim();
const principalId = ctx.state.principalId;
const where = { principal_id: principalId, status: 1 };
if (keyword) {
where[Op.or] = [
{ item_code: { [Op.like]: `%${keyword}%` } },
{ goods_code: { [Op.like]: `%${keyword}%` } },
{ barcode: { [Op.like]: `%${keyword}%` } },
{ item_name: { [Op.like]: `%${keyword}%` } },
];
}
const rows = await ctx.model.Product.findAll({
where,
attributes: [ 'id', 'item_code', 'goods_code', 'barcode', 'item_name', 'sku_property', 'stock_unit', 'status' ],
limit: 50,
order: [[ 'id', 'DESC' ]],
});
ctx.body = { code: 0, message: 'success', data: rows };
}
/**
* @summary 删除商品
* @description 软删除商品(设置 deleted_at);同一主体下商品编码唯一校验忽略已删除记录,故已删除商品编码可再次使用
* @router delete /api/products/{id}
* @apikey
* @request path integer *id 商品主键ID
* @response 200 baseResponse success
*/
async destroy() {
const { ctx } = this;
const product = await ctx.model.Product.findByPk(ctx.params.id);
if (!product) {
ctx.status = 404;
ctx.body = { code: 404, message: '商品不存在' };
return;
}
const snapshot = { item_code: product.item_code, item_name: product.item_name };
await product.destroy();
// 删除后记录也随之无法按对象查询,仍需留痕(按删除前的ID写入)
await ctx.service.operationLog.record({
targetType: 'product',
targetId: product.id,
principalId: product.principal_id,
action: 'delete',
title: `删除商品:${snapshot.item_name || ''}(${snapshot.item_code || ''})`,
detail: snapshot,
});
ctx.body = { code: 0, message: 'success', data: { id: Number(ctx.params.id) } };
}
}
module.exports = ProductController;