- 新增 POST /api/shop-products/batch-bind(body: ids + bind_type + product_id/combo_product_id) - 目标商品只校验一次(必须属于当前主体),单次最多 500 条 - 已是目标绑定的行计入 skipped,不重复改库、不重复写日志 - 不存在/跨主体的 id 计入 failed,其余正常处理 - bind_type=0 支持统一解绑 - 明细同步抽出 syncOrderItemsOf(items, ...):批量时合并为一次重建 (老表 order_items 一次 IN 更新 + order_status_items 一次 rebuildOrderItems), 单条绑定仍走 syncOrderItems(item, ...),行为不变 - 批量绑定逐条写操作日志(标题带「批量」,detail 记录 before/after 与 order_items_updated) - 前端店铺商品表加勾选列与「批量绑定(N)」按钮,绑定弹窗支持批量模式: 批量提示条、确认后统一绑定、统一解绑,结果提示更新/跳过/失败/明细同步数量 - 点击勾选框不再误触发行点击的操作记录面板 - 接口契约补 batchBindShopProductRequest/Result/Response 实测(主体5/店铺18):3 条统一绑定 → updated 3;重复执行 → updated 0 / skipped 3; 组合商品绑定 → 明细按组合展开(qty 15);统一解绑 → 明细还原平台原样快照; 无效 id → failed 1,其余成功;测试后店铺商品已全部还原为未绑定。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
581 lines
23 KiB
JavaScript
581 lines
23 KiB
JavaScript
'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 ];
|
||
|
||
/** 批量绑定的单次上限(避免一次请求里重建过多订单明细) */
|
||
const BATCH_BIND_LIMIT = 500;
|
||
|
||
/**
|
||
* @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 = this.describeBindingTarget(type, boundProduct, boundCombo);
|
||
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 } };
|
||
}
|
||
|
||
/**
|
||
* @summary 批量绑定(勾选多条店铺商品统一绑定到同一个系统商品 / 组合商品)
|
||
* @description bind_type=1 统一绑系统商品(传 product_id)、2 统一绑组合商品(传 combo_product_id)、0 统一解绑;
|
||
* 已经是目标绑定的行会跳过(skipped),不在当前主体或不存在的 id 计入 failed
|
||
* @router post /api/shop-products/batch-bind
|
||
* @apikey
|
||
* @request body batchBindShopProductRequest *body
|
||
* @response 200 batchBindShopProductResponse success
|
||
*/
|
||
async batchBind() {
|
||
const { ctx } = this;
|
||
const Op = this.app.Sequelize.Op;
|
||
const principalId = ctx.state.principalId;
|
||
const body = ctx.request.body || {};
|
||
|
||
const rawIds = Array.isArray(body.ids) ? body.ids : [];
|
||
const ids = [ ...new Set(rawIds.map(Number).filter(id => Number.isInteger(id) && id > 0)) ];
|
||
if (!ids.length) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '请选择要绑定的店铺商品(ids)' };
|
||
return;
|
||
}
|
||
if (ids.length > BATCH_BIND_LIMIT) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: `单次最多批量绑定 ${BATCH_BIND_LIMIT} 条店铺商品` };
|
||
return;
|
||
}
|
||
|
||
const type = Number(body.bind_type);
|
||
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) {
|
||
const productId = Number(body.product_id);
|
||
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 = productId;
|
||
boundProduct = product;
|
||
}
|
||
if (type === 2) {
|
||
const comboProductId = Number(body.combo_product_id);
|
||
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 = comboProductId;
|
||
boundCombo = combo;
|
||
}
|
||
|
||
const items = await ctx.model.ShopProduct.findAll({
|
||
where: { principal_id: principalId, id: { [ Op.in ]: ids } },
|
||
});
|
||
if (!items.length) {
|
||
ctx.status = 404;
|
||
ctx.body = { code: 404, message: '所选店铺商品不存在或不属于当前主体' };
|
||
return;
|
||
}
|
||
const foundIds = new Set(items.map(item => Number(item.id)));
|
||
const failed = ids
|
||
.filter(id => !foundIds.has(id))
|
||
.map(id => ({ id, message: '店铺商品不存在或不属于当前主体' }));
|
||
|
||
// 已是目标绑定的行直接跳过,避免无意义的明细重建与日志
|
||
const changed = [];
|
||
let skipped = 0;
|
||
for (const item of items) {
|
||
const same = Number(item.bind_type) === type
|
||
&& (type !== 1 || Number(item.product_id) === data.product_id)
|
||
&& (type !== 2 || Number(item.combo_product_id) === data.combo_product_id);
|
||
if (same) skipped++;
|
||
else changed.push(item);
|
||
}
|
||
|
||
let orderItemsUpdated = 0;
|
||
if (changed.length) {
|
||
// 先记下变更前的绑定,日志里写清「从什么改成了什么」
|
||
const beforeLabels = new Map();
|
||
for (const item of changed) beforeLabels.set(Number(item.id), await this.describeBinding(item));
|
||
|
||
await ctx.model.ShopProduct.update(data, {
|
||
where: { principal_id: principalId, id: { [ Op.in ]: changed.map(item => Number(item.id)) } },
|
||
});
|
||
orderItemsUpdated = await this.syncOrderItemsOf(changed, boundProduct, boundCombo);
|
||
|
||
const afterLabel = this.describeBindingTarget(type, boundProduct, boundCombo);
|
||
await ctx.service.operationLog.recordMany(
|
||
changed.map(item => ({
|
||
principalId,
|
||
targetType: 'shop_product',
|
||
targetId: Number(item.id),
|
||
action: type === 0 ? 'unbind' : 'bind',
|
||
title: type === 0
|
||
? `批量解除绑定(原绑定:${beforeLabels.get(Number(item.id))})`
|
||
: `批量绑定${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: beforeLabels.get(Number(item.id)),
|
||
after: afterLabel,
|
||
batch: true,
|
||
order_items_updated: orderItemsUpdated,
|
||
},
|
||
})),
|
||
{ source: 'ui' }
|
||
);
|
||
}
|
||
|
||
ctx.body = {
|
||
code: 0,
|
||
message: changed.length ? 'success' : '所选店铺商品已是该绑定,无需重复绑定',
|
||
data: {
|
||
total: ids.length,
|
||
updated: changed.length,
|
||
skipped,
|
||
failed,
|
||
order_items_updated: orderItemsUpdated,
|
||
},
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 绑定目标的展示文本(绑定 / 批量绑定共用)
|
||
* @param {number} type 绑定类型
|
||
* @param {Object|null} product 系统商品
|
||
* @param {Object|null} combo 组合商品
|
||
* @return {string} 展示文本
|
||
*/
|
||
describeBindingTarget(type, product, combo) {
|
||
if (Number(type) === 0) return '未绑定';
|
||
if (Number(type) === 1) return `系统商品 ${product.item_name || ''}(${product.item_code || ''})`;
|
||
return `组合商品 ${combo.name || ''}(${combo.code || ''})`;
|
||
}
|
||
|
||
/**
|
||
* 描述店铺商品当前的绑定对象(日志里写「原绑定」用)
|
||
* @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) {
|
||
return this.syncOrderItemsOf([ shopProduct ], product, combo);
|
||
}
|
||
|
||
/**
|
||
* 批量版本:一次处理多个店铺商品(批量绑定时只重建一次订单明细,避免逐条重复重建)
|
||
* @param {Array} shopProducts 店铺商品实例数组
|
||
* @param {Object|null} product 绑定的系统商品
|
||
* @param {Object|null} combo 绑定的组合商品
|
||
* @return {Promise<number>} 更新的明细数量(两张表合计)
|
||
*/
|
||
async syncOrderItemsOf(shopProducts, product, combo) {
|
||
const { ctx } = this;
|
||
const Op = this.app.Sequelize.Op;
|
||
const shopProductIds = (shopProducts || []).map(item => Number(item.id)).filter(id => id > 0);
|
||
if (!shopProductIds.length) return 0;
|
||
const where = { shop_product_id: { [ Op.in ]: shopProductIds } };
|
||
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;
|