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>
This commit is contained in:
parent
b946d09a03
commit
a9cca6aa6f
@ -1245,6 +1245,23 @@ module.exports = {
|
||||
combo_product_id: { type: 'integer', description: '组合商品ID,bind_type=2 时必填' },
|
||||
},
|
||||
|
||||
// ---------- 操作日志 operation_logs ----------
|
||||
operationLogItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
principal_id: { type: 'integer', description: '所属主体ID' },
|
||||
target_type: { type: 'string', description: '对象类型:shop_product 店铺商品 / product 系统商品 / combo_product 组合商品' },
|
||||
target_id: { type: 'integer', description: '对象ID' },
|
||||
action: { type: 'string', description: '动作码:create 新增 / update 修改 / bind 绑定 / unbind 解绑 / remove 移出系统 / offline 置为下架 / delete 删除' },
|
||||
title: { type: 'string', description: '操作说明(可直接展示)' },
|
||||
detail: { type: 'string', description: '操作明细 JSON(前后值等)' },
|
||||
source: { type: 'string', description: '来源:ui 界面操作 / sync 自动同步 / system 系统任务' },
|
||||
operator_id: { type: 'integer', description: '操作人用户ID(自动同步为空)' },
|
||||
operator_name: { type: 'string', description: '操作人名称(冗余存档)' },
|
||||
created_at: { type: 'string', description: '操作时间' },
|
||||
},
|
||||
operationLogPage: buildPage('operationLogItem', '操作日志列表'),
|
||||
operationLogListResponse: buildListResponse('operationLogPage'),
|
||||
|
||||
// ---------- 入库单 inbound_orders ----------
|
||||
inboundOrderItem: {
|
||||
id: { type: 'integer', description: '主键' },
|
||||
|
||||
@ -45,6 +45,31 @@ async function replaceComboItems(ctx, comboProductId, principalId, itemList, tra
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 组合商品被修改后,重建引用它的订单明细
|
||||
*
|
||||
* 绑定了该组合的店铺商品,其待审核/异常订单明细是按组合构成展开的(子商品行 + 数量 + 单价),
|
||||
* 组合构成或编码/名称一变,这些订单的明细与列表里的商品摘要就要跟着重算;
|
||||
* 已审核(待推送及之后)的订单不受影响(明细在审核时已锁定)。
|
||||
* @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
|
||||
@ -165,6 +190,15 @@ class ComboProductController extends Controller {
|
||||
{ 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) {
|
||||
@ -201,10 +235,44 @@ class ComboProductController extends Controller {
|
||||
|
||||
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) {
|
||||
@ -231,10 +299,20 @@ class ComboProductController extends Controller {
|
||||
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) {
|
||||
|
||||
@ -791,6 +791,33 @@ class ExternalPrintAccountController extends Controller {
|
||||
});
|
||||
}
|
||||
|
||||
// 操作记录:本次新采集进系统的商品(什么时候、从哪个店铺采集的)
|
||||
const existingIdSet = new Set(existing.map(row => Number(row.id)));
|
||||
const afterRows = await ctx.model.ShopProduct.findAll({
|
||||
where: { shop_id: shop.id },
|
||||
attributes: [ 'id', 'outer_item_id', 'outer_sku_id', 'title' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const createdRows = afterRows.filter(row => !existingIdSet.has(Number(row.id)));
|
||||
if (createdRows.length) {
|
||||
await ctx.service.operationLog.recordMany(
|
||||
createdRows.map(row => ({
|
||||
targetType: 'shop_product',
|
||||
targetId: row.id,
|
||||
action: 'create',
|
||||
title: this.shopProductLogTitle('采集到系统', row),
|
||||
detail: {
|
||||
shop_id: shop.id,
|
||||
shop_name: shop.name,
|
||||
outer_item_id: row.outer_item_id,
|
||||
outer_sku_id: row.outer_sku_id,
|
||||
},
|
||||
})),
|
||||
{ transaction, source: 'sync' }
|
||||
);
|
||||
}
|
||||
|
||||
if (snapshot.verified) {
|
||||
const syncedKeys = new Set(rows.map(row => shopProductKey(row.outer_item_id, row.outer_sku_id)));
|
||||
const staleIds = existing
|
||||
@ -824,9 +851,28 @@ class ExternalPrintAccountController extends Controller {
|
||||
const deleteIds = staleIds.filter(id => !keepIds.has(Number(id)));
|
||||
const offlineIds = staleIds.filter(id => keepIds.has(Number(id)));
|
||||
|
||||
// 取被移除/下架行的标题,写清是哪件商品(删除后查不到,必须先取)
|
||||
const staleRows = await ctx.model.ShopProduct.findAll({
|
||||
where: { id: { [Op.in]: staleIds } },
|
||||
attributes: [ 'id', 'outer_item_id', 'outer_sku_id', 'title' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
const staleMap = new Map(staleRows.map(row => [ Number(row.id), row ]));
|
||||
|
||||
if (deleteIds.length) {
|
||||
await ctx.model.ShopProduct.destroy({ where: { id: deleteIds }, transaction });
|
||||
removed = deleteIds.length;
|
||||
await ctx.service.operationLog.recordMany(
|
||||
deleteIds.map(id => ({
|
||||
targetType: 'shop_product',
|
||||
targetId: id,
|
||||
action: 'remove',
|
||||
title: this.shopProductLogTitle('平台已无此商品,已移出系统', staleMap.get(Number(id))),
|
||||
detail: { shop_id: shop.id, shop_name: shop.name, reason: '平台快照中已不存在' },
|
||||
})),
|
||||
{ transaction, source: 'sync' }
|
||||
);
|
||||
}
|
||||
if (offlineIds.length) {
|
||||
await ctx.model.ShopProduct.update(
|
||||
@ -834,6 +880,16 @@ class ExternalPrintAccountController extends Controller {
|
||||
{ where: { id: offlineIds }, transaction }
|
||||
);
|
||||
offline = offlineIds.length;
|
||||
await ctx.service.operationLog.recordMany(
|
||||
offlineIds.map(id => ({
|
||||
targetType: 'shop_product',
|
||||
targetId: id,
|
||||
action: 'offline',
|
||||
title: this.shopProductLogTitle('平台已无此商品,因已绑定或被订单引用,已保留并置为下架', staleMap.get(Number(id))),
|
||||
detail: { shop_id: shop.id, shop_name: shop.name, reason: '平台快照中已不存在,保留记录' },
|
||||
})),
|
||||
{ transaction, source: 'sync' }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -847,6 +903,19 @@ class ExternalPrintAccountController extends Controller {
|
||||
return { unique: rows.length, created, updated, removed, offline };
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成店铺商品日志标题(商品标题 + 平台商品ID/规格ID)
|
||||
* @param {string} prefix 动作说明
|
||||
* @param {Object} row 店铺商品行(title / outer_item_id / outer_sku_id)
|
||||
* @return {string} 标题
|
||||
*/
|
||||
shopProductLogTitle(prefix, row) {
|
||||
const data = row || {};
|
||||
const name = data.title || data.outer_item_id || '';
|
||||
const spec = data.outer_sku_id ? `,规格 ${data.outer_sku_id}` : '';
|
||||
return `${prefix}:${name}(平台商品ID ${data.outer_item_id || '-'}${spec})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取当前主体下的账号。
|
||||
* 资源不存在时 principalCheck 不会写入主体ID(交由控制器返回 404),此时直接返回 null,
|
||||
|
||||
46
backend/app/controller/operationLog.js
Normal file
46
backend/app/controller/operationLog.js
Normal file
@ -0,0 +1,46 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* @controller OperationLogController 操作日志
|
||||
* 记录店铺商品 / 系统商品 / 组合商品的关键操作,按对象查询历史记录
|
||||
*/
|
||||
class OperationLogController extends Controller {
|
||||
/**
|
||||
* @summary 操作日志列表
|
||||
* @description 按 target_type + target_id 查询某个对象的操作记录,按时间倒序分页返回
|
||||
* @router get /api/operation-logs
|
||||
* @apikey
|
||||
* @request query string *target_type 对象类型:shop_product 店铺商品 / product 系统商品 / combo_product 组合商品
|
||||
* @request query integer *target_id 对象ID
|
||||
* @request query integer page 页码,默认 1
|
||||
* @request query integer pageSize 每页条数,默认 20
|
||||
* @request query integer principal_id 所属主体ID(必填,需当前账号已绑定该主体)
|
||||
* @response 200 operationLogListResponse success
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const targetType = String(ctx.query.target_type || '').trim();
|
||||
const targetId = Number(ctx.query.target_id);
|
||||
|
||||
if (![ 'shop_product', 'product', 'combo_product' ].includes(targetType)) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'target_type 只能为 shop_product / product / combo_product' };
|
||||
return;
|
||||
}
|
||||
if (!targetId) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { code: 400, message: 'target_id 为必填项' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
code: 0,
|
||||
message: 'success',
|
||||
data: await ctx.service.operationLog.page({ targetType, targetId }),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OperationLogController;
|
||||
@ -153,6 +153,19 @@ class ProductController extends Controller {
|
||||
}
|
||||
|
||||
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 } };
|
||||
}
|
||||
|
||||
@ -176,11 +189,50 @@ class ProductController extends Controller {
|
||||
}
|
||||
|
||||
// 主体归属不可通过更新篡改,防止把资源移动到其它主体
|
||||
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 按 商品编码 / 货品编码 / 条码 / 商品名称 聚合模糊匹配,仅返回启用商品,供出入库明细快速选择
|
||||
@ -232,7 +284,17 @@ class ProductController extends Controller {
|
||||
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) } };
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,10 @@
|
||||
|
||||
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 店铺商品管理
|
||||
@ -155,6 +159,9 @@ class ShopProductController extends Controller {
|
||||
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;
|
||||
@ -193,9 +200,50 @@ class ShopProductController extends Controller {
|
||||
|
||||
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」,只同步绑定状态与商品快照;
|
||||
@ -208,6 +256,7 @@ class ShopProductController extends Controller {
|
||||
*/
|
||||
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,
|
||||
@ -219,18 +268,40 @@ class ShopProductController extends Controller {
|
||||
// 历史明细可能没有平台快照(功能上线前拉的单),绑定前先按当前未绑定状态补一份,保证以后解绑还能还原
|
||||
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 }
|
||||
{ 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 }
|
||||
{ where: legacyWhere }
|
||||
);
|
||||
updated = affected;
|
||||
} else {
|
||||
@ -243,7 +314,7 @@ class ShopProductController extends Controller {
|
||||
parse_msg: '店铺商品未绑定系统商品,已保留平台原样数据',
|
||||
};
|
||||
const orderRows = await ctx.model.OrderItem.findAll({
|
||||
where,
|
||||
where: legacyWhere,
|
||||
attributes: [ 'id', 'platform_snapshot' ],
|
||||
raw: true,
|
||||
});
|
||||
@ -256,7 +327,8 @@ class ShopProductController extends Controller {
|
||||
}
|
||||
}
|
||||
|
||||
// 状态明细整体重建:未绑定 / 系统商品 / 组合拆分(行数会变化,不能逐行 update)
|
||||
// 状态明细整体重建:未绑定 / 系统商品 / 组合拆分(行数会变化,不能逐行 update);
|
||||
// 只重建待审核/异常,已审核订单的明细保持审核时的状态
|
||||
updated += await ctx.service.orderItemResolve.rebuildOrderItems(orderIds);
|
||||
return updated;
|
||||
}
|
||||
|
||||
34
backend/app/model/operationLog.js
Normal file
34
backend/app/model/operationLog.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 操作日志模型,对应 operation_logs 表。
|
||||
*
|
||||
* 三类对象(店铺商品 / 系统商品 / 组合商品)共用一张日志表,
|
||||
* 通过 target_type + target_id 定位,页面按对象查历史操作记录。
|
||||
* @param {Egg.Application} app egg application
|
||||
* @return {object} operationLog model
|
||||
*/
|
||||
module.exports = app => {
|
||||
const { BIGINT, STRING, JSON: JsonType, DATE } = app.Sequelize;
|
||||
|
||||
const OperationLog = app.model.define('operation_log', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
target_type: { type: STRING(32), allowNull: false, comment: '对象类型:shop_product / product / combo_product' },
|
||||
target_id: { type: BIGINT.UNSIGNED, allowNull: false, comment: '对象ID' },
|
||||
action: { type: STRING(32), allowNull: false, comment: '动作码:create / update / bind / unbind / remove / offline / delete' },
|
||||
title: { type: STRING(255), allowNull: false, comment: '操作说明' },
|
||||
detail: { type: JsonType, comment: '操作明细(前后值等)' },
|
||||
source: { type: STRING(20), allowNull: false, defaultValue: 'ui', comment: '来源:ui / sync / system' },
|
||||
operator_id: { type: BIGINT.UNSIGNED, comment: '操作人用户ID' },
|
||||
operator_name: { type: STRING(50), comment: '操作人名称' },
|
||||
created_at: { type: DATE, comment: '创建时间' },
|
||||
updated_at: { type: DATE, comment: '更新时间' },
|
||||
});
|
||||
|
||||
OperationLog.associate = () => {
|
||||
app.model.OperationLog.belongsTo(app.model.Principal, { foreignKey: 'principal_id', as: 'principal' });
|
||||
};
|
||||
|
||||
return OperationLog;
|
||||
};
|
||||
@ -126,6 +126,8 @@ module.exports = app => {
|
||||
router.get('/api/shop-products', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.index);
|
||||
router.get('/api/shop-products/:id', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.show);
|
||||
router.post('/api/shop-products/:id/bind', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.bind);
|
||||
// 操作日志:店铺商品 / 系统商品 / 组合商品的历史操作记录(页面底部面板按对象查询)
|
||||
router.get('/api/operation-logs', jwtAuth, principalCheck(), controller.operationLog.index);
|
||||
// 外部打单平台:平台基础资料由开发者维护(只读查询);打单账号归属主体,在「店铺管理」下维护
|
||||
router.get('/api/external-print-platforms', jwtAuth, controller.externalPrintPlatform.index);
|
||||
// 账号登录态检查 / 登录(需在 resources 之前注册,避免被 /:id 误匹配)
|
||||
|
||||
@ -165,6 +165,16 @@ class ExternalPrintOrderService extends Service {
|
||||
created++;
|
||||
}
|
||||
|
||||
// 已审核(离开待审核)的订单明细在审核时已锁定库存、甚至已下发仓库,
|
||||
// 重新拉单只刷新平台侧状态,不重算明细(解绑/改绑也不会波及这些订单)
|
||||
const indexRow = await ctx.model.OrderIndex.findOne({
|
||||
where: { principal_id: shop.principal_id, parent_order_no: externalOrderId },
|
||||
attributes: [ 'id', 'current_status' ],
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
if (indexRow && indexRow.current_status !== ORDER_STATUS.PENDING) continue;
|
||||
|
||||
const existingItems = await ctx.model.OrderItem.findAll({
|
||||
where: { order_id: order.id },
|
||||
attributes: [ 'id', 'external_item_id' ],
|
||||
|
||||
129
backend/app/service/operationLog.js
Normal file
129
backend/app/service/operationLog.js
Normal file
@ -0,0 +1,129 @@
|
||||
'use strict';
|
||||
|
||||
const Service = require('egg').Service;
|
||||
const { resolveAccountName } = require('../lib/accountProfile');
|
||||
const { parsePagination, buildPageResult } = require('../lib/pagination');
|
||||
|
||||
/** 来源:界面操作 / 自动同步 / 系统任务 */
|
||||
const SOURCES = {
|
||||
UI: 'ui',
|
||||
SYNC: 'sync',
|
||||
SYSTEM: 'system',
|
||||
};
|
||||
|
||||
/**
|
||||
* 操作日志服务
|
||||
*
|
||||
* 统一记录三类对象(店铺商品 / 系统商品 / 组合商品)的关键操作,
|
||||
* 并提供按对象分页查询,供页面底部的「操作记录」面板展示。
|
||||
*
|
||||
* 记录失败不影响主流程(日志是旁路能力,不能因为写日志失败让业务操作报错)。
|
||||
*/
|
||||
class OperationLogService extends Service {
|
||||
/**
|
||||
* 写入一条操作日志
|
||||
* @param {Object} p 参数
|
||||
* @param {string} p.targetType 对象类型:shop_product 店铺商品 / product 系统商品 / combo_product 组合商品
|
||||
* @param {number} p.targetId 对象ID
|
||||
* @param {string} p.action 动作码:create / update / bind / unbind / remove / offline / delete
|
||||
* @param {string} p.title 操作说明(直接展示)
|
||||
* @param {Object} [p.detail] 明细(前后值等)
|
||||
* @param {string} [p.source] 来源,默认 ui
|
||||
* @param {number} [p.principalId] 主体ID,默认取上下文
|
||||
* @param {Object} [p.transaction] 事务
|
||||
* @return {Promise<Object|null>} 创建出的日志(失败或参数不全时返回 null)
|
||||
*/
|
||||
async record(p = {}) {
|
||||
const { ctx } = this;
|
||||
const principalId = Number(p.principalId || ctx.state.principalId);
|
||||
const targetId = Number(p.targetId);
|
||||
if (!principalId || !targetId || !p.targetType || !p.action || !p.title) return null;
|
||||
|
||||
try {
|
||||
const operatorId = Number(ctx.userId) || null;
|
||||
const operatorName = operatorId
|
||||
? (await resolveAccountName(ctx, operatorId, principalId)) || null
|
||||
: null;
|
||||
|
||||
return await ctx.model.OperationLog.create({
|
||||
principal_id: principalId,
|
||||
target_type: p.targetType,
|
||||
target_id: targetId,
|
||||
action: p.action,
|
||||
title: String(p.title).slice(0, 255),
|
||||
detail: p.detail && typeof p.detail === 'object' ? p.detail : null,
|
||||
source: p.source || SOURCES.UI,
|
||||
operator_id: operatorId,
|
||||
operator_name: operatorName,
|
||||
}, { transaction: p.transaction });
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[operation-log] 写入失败:%s', err.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量写入(自动同步时会一次新增/移除多行)
|
||||
* @param {Array<Object>} list 日志参数数组(结构同 record)
|
||||
* @param {Object} [options] { transaction, source }
|
||||
* @return {Promise<number>} 写入条数
|
||||
*/
|
||||
async recordMany(list, options = {}) {
|
||||
const { ctx } = this;
|
||||
const rows = (list || []).filter(item => item && item.targetType && Number(item.targetId) && item.title);
|
||||
if (!rows.length) return 0;
|
||||
try {
|
||||
const principalId = Number(ctx.state.principalId);
|
||||
const operatorId = Number(ctx.userId) || null;
|
||||
const operatorName = operatorId && principalId
|
||||
? (await resolveAccountName(ctx, operatorId, principalId)) || null
|
||||
: null;
|
||||
|
||||
const created = await ctx.model.OperationLog.bulkCreate(
|
||||
rows.map(item => ({
|
||||
principal_id: Number(item.principalId || principalId),
|
||||
target_type: item.targetType,
|
||||
target_id: Number(item.targetId),
|
||||
action: item.action,
|
||||
title: String(item.title).slice(0, 255),
|
||||
detail: item.detail && typeof item.detail === 'object' ? item.detail : null,
|
||||
source: item.source || options.source || SOURCES.SYNC,
|
||||
operator_id: operatorId,
|
||||
operator_name: operatorName,
|
||||
})),
|
||||
{ transaction: options.transaction }
|
||||
);
|
||||
return created.length;
|
||||
} catch (err) {
|
||||
ctx.logger.warn('[operation-log] 批量写入失败:%s', err.message);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询某个对象的操作记录
|
||||
* @param {Object} p { targetType, targetId, page, pageSize, principalId }
|
||||
* @return {Promise<Object>} { list, total, page, pageSize }
|
||||
*/
|
||||
async page(p = {}) {
|
||||
const { ctx } = this;
|
||||
const principalId = Number(p.principalId || ctx.state.principalId);
|
||||
const targetId = Number(p.targetId);
|
||||
const { page, pageSize, offset, limit } = parsePagination(p);
|
||||
|
||||
if (!principalId || !targetId || !p.targetType) {
|
||||
return buildPageResult([], 0, { page, pageSize });
|
||||
}
|
||||
|
||||
const { count, rows } = await ctx.model.OperationLog.findAndCountAll({
|
||||
where: { principal_id: principalId, target_type: p.targetType, target_id: targetId },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
offset,
|
||||
limit,
|
||||
});
|
||||
|
||||
return buildPageResult(rows.map(row => row.get({ plain: true })), count, { page, pageSize });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = OperationLogService;
|
||||
@ -19,9 +19,10 @@ class OrderItemResolveService extends Service {
|
||||
/**
|
||||
* 批量载入组合商品的子商品明细
|
||||
* @param {Array<number>} comboIds 组合商品ID
|
||||
* @param {Object} [transaction] 事务(组合商品刚在同事务内改动时必须传,否则读不到未提交的构成)
|
||||
* @return {Promise<Map<number, Array>>} comboId → 子商品数组
|
||||
*/
|
||||
async loadComboItems(comboIds) {
|
||||
async loadComboItems(comboIds, transaction) {
|
||||
const { ctx } = this;
|
||||
const map = new Map();
|
||||
const ids = [ ...new Set((comboIds || []).map(Number).filter(id => id > 0)) ];
|
||||
@ -37,6 +38,7 @@ class OrderItemResolveService extends Service {
|
||||
required: false,
|
||||
}],
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
transaction,
|
||||
});
|
||||
|
||||
for (const row of rows) {
|
||||
@ -60,9 +62,10 @@ class OrderItemResolveService extends Service {
|
||||
/**
|
||||
* 批量载入店铺商品的绑定上下文
|
||||
* @param {Array<number>} shopProductIds 店铺商品ID
|
||||
* @param {Object} [transaction] 事务
|
||||
* @return {Promise<Map<number, Object>>} shopProductId → { shopProduct, product, combo, comboItems }
|
||||
*/
|
||||
async loadBindings(shopProductIds) {
|
||||
async loadBindings(shopProductIds, transaction) {
|
||||
const { ctx } = this;
|
||||
const map = new Map();
|
||||
const ids = [ ...new Set((shopProductIds || []).map(Number).filter(id => id > 0)) ];
|
||||
@ -72,6 +75,7 @@ class OrderItemResolveService extends Service {
|
||||
const shopProducts = await ctx.model.ShopProduct.findAll({
|
||||
where: { id: { [Op.in]: ids } },
|
||||
raw: true,
|
||||
transaction,
|
||||
});
|
||||
if (!shopProducts.length) return map;
|
||||
|
||||
@ -83,12 +87,12 @@ class OrderItemResolveService extends Service {
|
||||
.map(row => Number(row.combo_product_id));
|
||||
|
||||
const products = productIds.length
|
||||
? await ctx.model.Product.findAll({ where: { id: { [Op.in]: productIds } }, raw: true })
|
||||
? await ctx.model.Product.findAll({ where: { id: { [Op.in]: productIds } }, raw: true, transaction })
|
||||
: [];
|
||||
const combos = comboIds.length
|
||||
? await ctx.model.ComboProduct.findAll({ where: { id: { [Op.in]: comboIds } }, raw: true })
|
||||
? await ctx.model.ComboProduct.findAll({ where: { id: { [Op.in]: comboIds } }, raw: true, transaction })
|
||||
: [];
|
||||
const comboItems = await this.loadComboItems(comboIds);
|
||||
const comboItems = await this.loadComboItems(comboIds, transaction);
|
||||
|
||||
const productMap = new Map(products.map(row => [ Number(row.id), row ]));
|
||||
const comboMap = new Map(combos.map(row => [ Number(row.id), row ]));
|
||||
@ -107,6 +111,31 @@ class OrderItemResolveService extends Service {
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按店铺商品批量重建其订单明细(绑定关系或商品资料变化后调用)
|
||||
* @param {Array<number>} shopProductIds 店铺商品ID
|
||||
* @param {Object} [options] { transaction }
|
||||
* @return {Promise<number>} 重建的明细行数
|
||||
*/
|
||||
async rebuildOrdersByShopProducts(shopProductIds, options = {}) {
|
||||
const { ctx } = this;
|
||||
const ids = [ ...new Set((shopProductIds || []).map(Number).filter(id => id > 0)) ];
|
||||
if (!ids.length) return 0;
|
||||
|
||||
const Op = this.app.Sequelize.Op;
|
||||
const items = await ctx.model.OrderStatusItem.findAll({
|
||||
where: { shop_product_id: { [Op.in]: ids } },
|
||||
attributes: [ 'order_id' ],
|
||||
group: [ 'order_id' ],
|
||||
raw: true,
|
||||
transaction: options.transaction,
|
||||
});
|
||||
const orderIds = items.map(row => Number(row.order_id)).filter(id => id > 0);
|
||||
if (!orderIds.length) return 0;
|
||||
|
||||
return this.rebuildOrderItems(orderIds, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前绑定关系重建若干订单的明细(折叠为平台行 → 重新展开为最小单位)
|
||||
*
|
||||
@ -154,7 +183,7 @@ class OrderItemResolveService extends Service {
|
||||
if (!isPlatformOrder) continue;
|
||||
|
||||
const lines = foldPlatformLines(rows);
|
||||
const bindings = await this.loadBindings(lines.map(line => line.shop_product_id));
|
||||
const bindings = await this.loadBindings(lines.map(line => line.shop_product_id), transaction);
|
||||
|
||||
const payload = [];
|
||||
for (const line of lines) {
|
||||
|
||||
@ -0,0 +1,45 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 操作日志表。
|
||||
*
|
||||
* 记录「店铺商品 / 系统商品 / 组合商品」的关键操作,用于在页面下方展示操作记录:
|
||||
* 何时被采集进系统、何时绑定/解绑、谁操作的、来源是界面还是自动同步。
|
||||
*
|
||||
* 设计要点:
|
||||
* - target_type + target_id 指向被操作的对象(三类对象共用一张表,避免三张表结构重复)
|
||||
* - action 为机器可读动作码,title 为给人看的完整描述(列表直接展示,无需前端再拼)
|
||||
* - detail 存前后值等明细(JSON),便于追溯「改了什么」
|
||||
* - operator_name 冗余存档,账号改名后历史记录仍保留当时的操作人名称
|
||||
*/
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable('operation_logs', {
|
||||
id: { type: Sequelize.BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
principal_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, comment: '所属主体ID' },
|
||||
target_type: { type: Sequelize.STRING(32), allowNull: false, comment: '对象类型:shop_product 店铺商品 / product 系统商品 / combo_product 组合商品' },
|
||||
target_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: false, comment: '对象ID' },
|
||||
action: { type: Sequelize.STRING(32), allowNull: false, comment: '动作码:create 新增 / update 修改 / bind 绑定 / unbind 解绑 / remove 移出 / offline 下架 / delete 删除' },
|
||||
title: { type: Sequelize.STRING(255), allowNull: false, comment: '操作说明(直接展示给用户)' },
|
||||
detail: { type: Sequelize.JSON, allowNull: true, comment: '操作明细(前后值等)' },
|
||||
source: { type: Sequelize.STRING(20), allowNull: false, defaultValue: 'ui', comment: '来源:ui 界面操作 / sync 自动同步 / system 系统任务' },
|
||||
operator_id: { type: Sequelize.BIGINT.UNSIGNED, allowNull: true, comment: '操作人用户ID(自动同步为空)' },
|
||||
operator_name: { type: Sequelize.STRING(50), allowNull: true, comment: '操作人名称(冗余存档)' },
|
||||
created_at: { type: Sequelize.DATE, allowNull: true, comment: '创建时间' },
|
||||
updated_at: { type: Sequelize.DATE, allowNull: true, comment: '更新时间' },
|
||||
});
|
||||
|
||||
await queryInterface.addIndex('operation_logs', [ 'principal_id', 'target_type', 'target_id', 'id' ], {
|
||||
name: 'idx_operation_logs_target',
|
||||
});
|
||||
await queryInterface.addIndex('operation_logs', [ 'principal_id', 'created_at' ], {
|
||||
name: 'idx_operation_logs_principal_time',
|
||||
});
|
||||
},
|
||||
|
||||
async down(queryInterface) {
|
||||
await queryInterface.removeIndex('operation_logs', 'idx_operation_logs_principal_time');
|
||||
await queryInterface.removeIndex('operation_logs', 'idx_operation_logs_target');
|
||||
await queryInterface.dropTable('operation_logs');
|
||||
},
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user