feat(shop-product): 店铺商品支持勾选批量绑定到同一个系统商品/组合商品

- 新增 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>
This commit is contained in:
liufumingren 2026-11-03 17:08:54 +08:00
parent e6d3f1ba8d
commit 95c268836e
5 changed files with 352 additions and 12 deletions

View File

@ -1263,6 +1263,25 @@ module.exports = {
product_id: { type: 'integer', description: '系统商品ID,bind_type=1 时必填' },
combo_product_id: { type: 'integer', description: '组合商品ID,bind_type=2 时必填' },
},
batchBindShopProductRequest: {
principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' },
ids: { type: 'array', itemType: 'integer', required: true, description: '要统一绑定的店铺商品ID列表(单次最多 500 条)' },
bind_type: { type: 'integer', required: true, description: '绑定类型:0统一解绑 1统一绑系统商品 2统一绑组合商品' },
product_id: { type: 'integer', description: '系统商品ID,bind_type=1 时必填' },
combo_product_id: { type: 'integer', description: '组合商品ID,bind_type=2 时必填' },
},
batchBindShopProductResult: {
total: { type: 'integer', description: '提交的店铺商品数' },
updated: { type: 'integer', description: '实际变更绑定的数量' },
skipped: { type: 'integer', description: '已绑定同一对象、本次跳过的数量' },
failed: { type: 'array', itemType: 'string', description: '失败明细:{ id, message }' },
order_items_updated: { type: 'integer', description: '被重建的订单明细数量' },
},
batchBindShopProductResponse: {
code: { type: 'integer', description: '业务状态码,0 成功' },
message: { type: 'string', description: '提示信息' },
data: { type: 'batchBindShopProductResult', description: '批量绑定结果' },
},
// ---------- 操作日志 operation_logs ----------
operationLogItem: {

View File

@ -7,6 +7,9 @@ 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)
@ -202,11 +205,7 @@ class ShopProductController extends Controller {
const syncedItems = await this.syncOrderItems(item, boundProduct, boundCombo);
// 操作记录:绑定 / 解绑都留痕(谁在什么时候把哪个平台商品绑到了哪个商品)
const afterLabel = type === 0
? '未绑定'
: type === 1
? `系统商品 ${boundProduct.item_name || ''}(${boundProduct.item_code || ''})`
: `组合商品 ${boundCombo.name || ''}(${boundCombo.code || ''})`;
const afterLabel = this.describeBindingTarget(type, boundProduct, boundCombo);
await ctx.service.operationLog.record({
targetType: 'shop_product',
targetId: item.id,
@ -225,6 +224,163 @@ class ShopProductController extends Controller {
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 店铺商品实例
@ -255,9 +411,22 @@ class ShopProductController extends Controller {
* @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 where = { shop_product_id: shopProduct.id };
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' ],

View File

@ -127,6 +127,8 @@ module.exports = app => {
// 店铺商品完全来自平台采集:不提供手工新增 / 编辑 / 删除,只保留查询与绑定;
// 同步商品时平台已不存在的商品会自动移除
router.get('/api/shop-products', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.index);
// 批量绑定需在 /:id 路由之前注册,避免 batch-bind 被当成 :id
router.post('/api/shop-products/batch-bind', jwtAuth, principalCheck({ model: 'ShopProduct' }), controller.shopProduct.batchBind);
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);
// 操作日志:店铺商品 / 系统商品 / 组合商品的历史操作记录(页面底部面板按对象查询)

View File

@ -51,3 +51,22 @@ export function getShopProducts(params?: object) {
export function bindShopProduct(id: number, data: BindPayload) {
return post<{ id: number }>(`/shop-products/${id}/bind`, data)
}
/** 批量绑定入参:勾选多条店铺商品,统一绑定到同一个系统商品 / 组合商品 */
export interface BatchBindPayload extends BindPayload {
ids: number[]
}
/** 批量绑定结果 */
export interface BatchBindResult {
total: number
updated: number
skipped: number
failed: { id: number; message: string }[]
order_items_updated: number
}
/** 批量绑定(勾选多条统一绑定到同一个对象,bind_type=0 为统一解绑) */
export function batchBindShopProducts(data: BatchBindPayload) {
return post<BatchBindResult>('/shop-products/batch-bind', data)
}

View File

@ -5,6 +5,7 @@ import { QuestionFilled } from '@element-plus/icons-vue'
import {
getShopProducts,
bindShopProduct,
batchBindShopProducts,
BIND_TYPES,
type ShopProductItem,
} from '@/api/shopProduct'
@ -97,6 +98,10 @@ const bindSubmitting = ref(false)
const bindId = ref<number | null>(null)
const bindRow = ref<ShopProductItem | null>(null)
const bindTab = ref<'product' | 'combo'>('product')
/** 批量绑定:勾选的店铺商品(空数组表示单条绑定模式) */
const selectedRows = ref<ShopProductItem[]>([])
const batchMode = computed(() => selectedRows.value.length > 0)
const bindTitle = computed(() => (batchMode.value ? `批量绑定(已选 ${selectedRows.value.length} 条)` : '绑定商品'))
/** 弹窗内容区高度:按视口计算,保证表格内部滚动、底部按钮始终可见 */
const bindBodyHeight = ref(420)
@ -214,6 +219,7 @@ function onComboSizeChange(size: number) {
}
function openBind(row: ShopProductItem) {
selectedRows.value = []
bindId.value = row.id
bindRow.value = row
bindTab.value = row.bind_type === BIND_TYPES.combo ? 'combo' : 'product'
@ -228,6 +234,31 @@ function openBind(row: ShopProductItem) {
loadCombos()
}
/** 批量绑定:把勾选的多条店铺商品统一绑定到同一个系统商品 / 组合商品 */
function openBatchBind() {
if (!selectedRows.value.length) {
ElMessage.warning('请先勾选要绑定的店铺商品')
return
}
bindId.value = null
bindRow.value = null
bindTab.value = 'product'
productQuery.keyword = ''
productQuery.status = ''
productQuery.page = 1
comboQuery.keyword = ''
comboQuery.status = ''
comboQuery.page = 1
bindVisible.value = true
loadProducts()
loadCombos()
}
/** 表格勾选变化 */
function onSelectionChange(rows: ShopProductItem[]) {
selectedRows.value = rows
}
/** 当前行是否已绑定该商品/组合商品 */
function isBoundProduct(row: ProductItem) {
return bindRow.value?.bind_type === BIND_TYPES.product && Number(bindRow.value.product_id) === Number(row.id)
@ -237,9 +268,14 @@ function isBoundCombo(row: ComboProductItem) {
return bindRow.value?.bind_type === BIND_TYPES.combo && Number(bindRow.value.combo_product_id) === Number(row.id)
}
/** 直接把店铺商品绑定到选中的系统商品 / 组合商品 */
/** 直接把店铺商品(或勾选的一批)绑定到选中的系统商品 / 组合商品 */
async function bindTo(targetType: number, targetId: number) {
if (bindId.value == null || bindingKey.value) return
if (bindingKey.value) return
if (batchMode.value) {
await batchBind(targetType, targetId)
return
}
if (bindId.value == null) return
bindingKey.value = `${targetType === BIND_TYPES.combo ? 'c' : 'p'}${targetId}`
bindSubmitting.value = true
try {
@ -259,6 +295,79 @@ async function bindTo(targetType: number, targetId: number) {
}
}
/** 批量绑定:统一绑定到同一对象,逐条结果由后端返回 */
async function batchBind(targetType: number, targetId: number) {
const count = selectedRows.value.length
try {
await ElMessageBox.confirm(
`把已勾选的 ${count} 条店铺商品统一绑定到该${targetType === BIND_TYPES.combo ? '组合商品' : '系统商品'}?已有其它绑定的会被覆盖。`,
'批量绑定确认',
{ type: 'warning', confirmButtonText: '确定绑定', cancelButtonText: '取消' },
)
} catch {
return
}
bindingKey.value = `${targetType === BIND_TYPES.combo ? 'c' : 'p'}${targetId}`
bindSubmitting.value = true
try {
const res = await batchBindShopProducts({
ids: selectedRows.value.map(item => item.id),
bind_type: targetType,
product_id: targetType === BIND_TYPES.product ? targetId : null,
combo_product_id: targetType === BIND_TYPES.combo ? targetId : null,
})
const parts = [`已更新 ${res.updated} 条`]
if (res.skipped) parts.push(`跳过 ${res.skipped} 条(原本就是该绑定)`)
if (res.failed.length) parts.push(`失败 ${res.failed.length} 条`)
if (res.order_items_updated) parts.push(`同步订单明细 ${res.order_items_updated} 条`)
if (res.updated) ElMessage.success(parts.join(';'))
else ElMessage.warning(parts.join(';'))
bindVisible.value = false
selectedRows.value = []
await fetchList()
} catch {
// 拦截器已提示
} finally {
bindingKey.value = ''
bindSubmitting.value = false
}
}
/** 批量解绑:把勾选的店铺商品统一解除绑定 */
async function batchUnbind() {
const count = selectedRows.value.length
if (!count) return
try {
await ElMessageBox.confirm(
`确认解除已勾选 ${count} 条店铺商品的绑定?解除后订单明细会还原为平台原样数据。`,
'批量解绑确认',
{ type: 'warning', confirmButtonText: '解绑', cancelButtonText: '取消' },
)
} catch {
return
}
bindSubmitting.value = true
try {
const res = await batchBindShopProducts({
ids: selectedRows.value.map(item => item.id),
bind_type: BIND_TYPES.none,
product_id: null,
combo_product_id: null,
})
const parts = [`已解绑 ${res.updated} 条`]
if (res.skipped) parts.push(`跳过 ${res.skipped} 条(原本就未绑定)`)
if (res.failed.length) parts.push(`失败 ${res.failed.length} 条`)
ElMessage.success(parts.join(';'))
bindVisible.value = false
selectedRows.value = []
await fetchList()
} catch {
// 拦截器已提示
} finally {
bindSubmitting.value = false
}
}
/** 解除当前店铺商品的绑定 */
async function unbind() {
if (bindId.value == null) return
@ -295,7 +404,10 @@ function boundName(row: ShopProductItem) {
const logRow = ref<ShopProductItem | null>(null)
const logPanelHeight = ref(240)
function onRowClick(row: ShopProductItem) {
function onRowClick(row: ShopProductItem, _column?: unknown, event?: Event) {
// 勾选复选框时不打开操作记录面板(避免点选行时误触)
const target = event && (event.target as HTMLElement | null)
if (target && target.closest && target.closest('.el-checkbox, .el-table-column--selection')) return
// 再次点击同一行则收起
if (logRow.value && logRow.value.id === row.id) {
closeLog()
@ -390,6 +502,9 @@ onBeforeUnmount(() => {
<div class="page-header">
<span>店铺商品</span>
<div class="header-actions">
<el-button type="warning" plain :disabled="!selectedRows.length" @click="openBatchBind">
批量绑定{{ selectedRows.length ? `(${selectedRows.length})` : '' }}
</el-button>
<el-button @click="openPull">按商品ID拉取</el-button>
<ExportButton type="shop_product" :filters="exportFilters" />
</div>
@ -463,7 +578,9 @@ onBeforeUnmount(() => {
height="100%"
highlight-current-row
@row-click="onRowClick"
@selection-change="onSelectionChange"
>
<el-table-column type="selection" width="44" fixed="left" />
<el-table-column label="店铺" width="140">
<template #default="{ row }">{{ row.shop?.name || '-' }}</template>
</el-table-column>
@ -572,12 +689,20 @@ onBeforeUnmount(() => {
<el-dialog
v-model="bindVisible"
title="绑定商品"
:title="bindTitle"
width="min(1100px, 94vw)"
top="5vh"
class="bind-dialog"
destroy-on-close
>
<el-alert
v-if="batchMode"
type="warning"
:closable="false"
show-icon
class="bind-batch-tip"
:title="`已勾选 ${selectedRows.length} 条店铺商品:选择下面的系统商品或组合商品后,会把这 ${selectedRows.length} 条统一绑定到同一个对象(已有其它绑定的会被覆盖)`"
/>
<div class="bind-layout" :style="{ height: `${bindBodyHeight}px` }">
<el-tabs v-model="bindTab" tab-position="left" class="bind-tabs">
<el-tab-pane label="系统商品" name="product">
@ -703,10 +828,13 @@ onBeforeUnmount(() => {
</div>
<template #footer>
<div class="bind-footer">
<span class="bind-current">当前绑定:{{ currentBindLabel }}</span>
<span class="bind-current">
{{ batchMode ? `已勾选 ${selectedRows.length} 条:统一绑定到同一对象` : `当前绑定:${currentBindLabel}` }}
</span>
<div>
<el-button v-if="batchMode" :loading="bindSubmitting" @click="batchUnbind">统一解绑</el-button>
<el-button
v-if="bindRow && bindRow.bind_type !== BIND_TYPES.none"
v-else-if="bindRow && bindRow.bind_type !== BIND_TYPES.none"
:loading="bindSubmitting"
@click="unbind"
>
@ -845,4 +973,7 @@ onBeforeUnmount(() => {
font-size: 12px;
color: var(--el-text-color-secondary);
}
.bind-batch-tip {
margin-bottom: 8px;
}
</style>