oms/backend/app/controller/shopProduct.js
liufumingren ab630e7c01 feat(external-print): 订单拉取与定时同步,组合商品拆分为最小单位
后端能力:
- 接入店管家订单接口(/NewOrder/List),明细归一化后按店铺商品匹配系统商品/组合商品
- 新增 service/externalPrintOrder:手动与定时拉单共用入库逻辑,同时写入待审核状态分表
- 新增 schedule/fetchExternalShopOrders:按店铺配置的间隔自动拉单(最小 3 分钟,起点重叠 10 分钟)
- 新增 lib/orderItemExpand + service/orderItemResolve:平台行与最小单位行互转;
  绑定组合商品时按「数量 = 平台数量 x 组合内数量、单价取子商品零售价」拆成子商品行,解绑可还原
- 明细新增 platform_snapshot,保留平台原样(编码/名称/规格/图片/原行号/原数量/原单价)
- 店铺商品列表支持 has_unbound_order 筛选,订单列表支持 exclude_unbound(均已同步导出定义)
- 店铺商品只读化:移除新增/编辑/删除动作,仅保留查询与绑定;
  同步商品时平台已不存在的商品自动清理(未绑定且未被订单引用直接删除,已绑定或被引用仅下架)
- 新增 scripts/rebuild-order-items 存量明细重建脚本,新增 orderItemExpand 单测(8 项)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-03 03:29:09 +08:00

340 lines
13 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');
/**
* @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 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);
ctx.body = { code: 0, message: 'success', data: { id: item.id, order_items_updated: syncedItems } };
}
/**
* 绑定关系变化后回写订单明细:
* 老明细表(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 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);
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 }
);
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 }
);
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,
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;