- 列表接口支持 shop_ids / platform_types / outer_codes(逗号分隔或数组,去重、上限 200),店铺与平台类型为 IN 条件,商家编码为多值精确匹配;保留单值 shop_id 与关键词模糊查询 - 前端:店铺改为多选虚拟下拉、新增平台类型多选、新增商家编码多值控件(收起英文逗号拼接、展开一行一个) - 导出同步支持多值筛选(多选控件按 CSV 提交)并补上「平台类型」列 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
687 lines
27 KiB
JavaScript
687 lines
27 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;
|
||
|
||
/** 多值筛选参数的单次上限(防止超长 IN 拖垮查询) */
|
||
const MAX_FILTER_VALUES = 200;
|
||
|
||
/**
|
||
* 解析多值筛选参数:支持数组(a=1&a=2)与逗号分隔字符串(a=1,2),去空去重
|
||
* @param {*} value 原始参数
|
||
* @param {number} [max] 最多保留的值个数
|
||
* @return {Array<string>} 值列表
|
||
*/
|
||
function parseListParam(value, max = MAX_FILTER_VALUES) {
|
||
const raw = Array.isArray(value) ? value : String(value == null ? '' : value).split(',');
|
||
const list = [];
|
||
for (const item of raw) {
|
||
const text = String(item == null ? '' : item).trim();
|
||
if (text && !list.includes(text)) list.push(text);
|
||
if (list.length >= max) break;
|
||
}
|
||
return list;
|
||
}
|
||
|
||
/**
|
||
* @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 string shop_ids 店铺ID,多个用英文逗号分隔(如 12,18)
|
||
* @request query integer shop_id 店铺ID(单值,兼容旧调用)
|
||
* @request query string platform_types 平台类型编码(PDD/DYXD/SPH…),多个用英文逗号分隔
|
||
* @request query string outer_codes 商家编码,多个用英文逗号分隔(精确匹配)
|
||
* @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,
|
||
shop_ids: shopIds,
|
||
platform_types: platformTypes,
|
||
outer_codes: outerCodes,
|
||
bind_type: bindType,
|
||
status,
|
||
keyword,
|
||
has_unbound_order: hasUnboundOrder,
|
||
} = ctx.query;
|
||
const principalId = Number(ctx.state.principalId);
|
||
|
||
const where = {};
|
||
where.principal_id = principalId;
|
||
const shopIdList = parseListParam(shopIds)
|
||
.map(Number)
|
||
.filter(id => Number.isInteger(id) && id > 0);
|
||
if (shopIdList.length) where.shop_id = { [Op.in]: shopIdList };
|
||
else if (shopId) where.shop_id = Number(shopId);
|
||
// 平台类型按系统预设编码筛选(PDD / DYXD / SPH…)
|
||
const platformTypeList = parseListParam(platformTypes);
|
||
if (platformTypeList.length) where.platform_type = { [Op.in]: platformTypeList };
|
||
// 商家编码支持多个精确匹配(与关键词的模糊匹配区分开)
|
||
const outerCodeList = parseListParam(outerCodes).map(code => code.slice(0, 100));
|
||
if (outerCodeList.length) where.outer_code = { [Op.in]: outerCodeList };
|
||
if (bindType !== undefined && bindType !== '') where.bind_type = Number(bindType);
|
||
if (status !== undefined && status !== '') where.status = Number(status);
|
||
|
||
// 所在公司权限:仅可见自己所属公司(货主)的店铺商品
|
||
const access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
if (!access.isGroup) {
|
||
where.subsidiary_id = { [Op.in]: access.ownCompanyIds.map(Number) };
|
||
}
|
||
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.PrincipalSubsidiary, as: 'subsidiary', attributes: [ 'id', 'name' ], required: false },
|
||
{ 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 => {
|
||
const plain = row.get({ plain: true });
|
||
plain.subsidiary_name = plain.subsidiary ? plain.subsidiary.name : '';
|
||
return plain;
|
||
});
|
||
await this.attachUnboundOrderCount(list, principalId);
|
||
ctx.body = { code: 0, message: 'success', data: buildPageResult(list, count, { page, pageSize }) };
|
||
}
|
||
|
||
/**
|
||
* 判断当前账号是否有权访问该店铺商品(集团权限均可;所在公司权限限自己所属公司)
|
||
* @param {Object} ctx egg context
|
||
* @param {Object} item 店铺商品 model 实例
|
||
* @return {Promise<boolean>} 是否有权限
|
||
*/
|
||
async canAccess(ctx, item) {
|
||
const access = await ctx.service.access.resolve(ctx.userId, item.principal_id);
|
||
if (access.isGroup) return true;
|
||
if (item.subsidiary_id === null || item.subsidiary_id === undefined) return false;
|
||
return access.ownCompanyIds.map(Number).includes(Number(item.subsidiary_id));
|
||
}
|
||
|
||
/**
|
||
* 回填每个店铺商品的「待处理订单数」(未绑定系统商品的订单明细按订单去重计数),
|
||
* 便于列表上直接看出哪些商品还有订单等绑定
|
||
* @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;
|
||
}
|
||
|
||
// 所在公司权限:仅可查看自己所属公司(货主)的店铺商品
|
||
const access = await ctx.service.access.resolve(ctx.userId, item.principal_id);
|
||
if (!access.isGroup
|
||
&& (item.subsidiary_id == null
|
||
|| !access.ownCompanyIds.map(Number).includes(Number(item.subsidiary_id)))) {
|
||
ctx.status = 403;
|
||
ctx.body = { code: 403, 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;
|
||
}
|
||
|
||
// 所在公司权限:仅可维护自己所属公司(货主)的店铺商品
|
||
if (!(await this.canAccess(ctx, item))) {
|
||
ctx.status = 403;
|
||
ctx.body = { code: 403, 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 access = await ctx.service.access.resolve(ctx.userId, principalId);
|
||
if (!access.isGroup) {
|
||
const ownIds = access.ownCompanyIds.map(Number);
|
||
const allowed = items.filter(item => item.subsidiary_id != null && ownIds.includes(Number(item.subsidiary_id)));
|
||
if (!allowed.length) {
|
||
ctx.status = 403;
|
||
ctx.body = { code: 403, message: '仅可维护自己所属公司(货主)的店铺商品' };
|
||
return;
|
||
}
|
||
if (allowed.length !== items.length) {
|
||
const allowedIds = new Set(allowed.map(item => Number(item.id)));
|
||
const denied = ids.filter(id => !allowedIds.has(id));
|
||
ctx.status = 403;
|
||
ctx.body = {
|
||
code: 403,
|
||
message: `以下店铺商品不属于自己所属公司(货主),无权维护:${denied.join('、')}`,
|
||
};
|
||
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;
|