diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index a4e25ab..25dea96 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -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: { diff --git a/backend/app/controller/shopProduct.js b/backend/app/controller/shopProduct.js index 9d33999..29aebd3 100644 --- a/backend/app/controller/shopProduct.js +++ b/backend/app/controller/shopProduct.js @@ -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} 更新的明细数量(两张表合计) */ async syncOrderItems(shopProduct, product, combo) { + return this.syncOrderItemsOf([ shopProduct ], product, combo); + } + + /** + * 批量版本:一次处理多个店铺商品(批量绑定时只重建一次订单明细,避免逐条重复重建) + * @param {Array} shopProducts 店铺商品实例数组 + * @param {Object|null} product 绑定的系统商品 + * @param {Object|null} combo 绑定的组合商品 + * @return {Promise} 更新的明细数量(两张表合计) + */ + 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' ], diff --git a/backend/app/router.js b/backend/app/router.js index a504b92..a88104b 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -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); // 操作日志:店铺商品 / 系统商品 / 组合商品的历史操作记录(页面底部面板按对象查询) diff --git a/frontend/src/api/shopProduct.ts b/frontend/src/api/shopProduct.ts index 0875101..ca296a3 100644 --- a/frontend/src/api/shopProduct.ts +++ b/frontend/src/api/shopProduct.ts @@ -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('/shop-products/batch-bind', data) +} diff --git a/frontend/src/views/ShopProduct/Index.vue b/frontend/src/views/ShopProduct/Index.vue index 2224b83..bbdabb9 100644 --- a/frontend/src/views/ShopProduct/Index.vue +++ b/frontend/src/views/ShopProduct/Index.vue @@ -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(null) const bindRow = ref(null) const bindTab = ref<'product' | 'combo'>('product') +/** 批量绑定:勾选的店铺商品(空数组表示单条绑定模式) */ +const selectedRows = ref([]) +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(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(() => {