feat(shop-product): 移除「按商品ID拉取」,统一走同步商品 + 自动重匹配

按商品ID单品补拉会绕开分区声明与 SelectAgentId 过滤,容易把同一账号下别的商家的
同款商品写进本店铺(线上已确认拉错过别家商品),且与订单明细匹配口径
(店铺 + 平台商品ID + 平台规格ID)不是同一套数据来源。改为只保留全量快照同步。

- 前端店铺商品页:去掉「按商品ID拉取」按钮与弹窗,删除 pullExternalPrintShopProducts
  及 PullShopProducts* 类型
- 后端:删除 controller/externalPrintAccount.pullShopProducts + findSavedShopProducts、
  MAX_PULL_PRODUCT_ITEMS、路由 POST …/shops/:shopId/pull-products
- 平台层:删除 dgj.listProductsByIds 与 base.listProductsByIds 约定
- contract:删除 pullShopProducts* / externalPrintShopProductPull* 定义
- 文档 §4.2.5 补移除原因与替代做法(同步商品后自动重匹配,接口返回 rematched)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-07 21:45:50 +08:00
parent 176e0c0f97
commit b7da68a40c
8 changed files with 7 additions and 403 deletions

View File

@ -1517,48 +1517,6 @@ module.exports = {
message: { type: 'string', description: '提示信息' },
data: { type: 'externalPrintShopProductSyncResult', description: '同步结果' },
},
pullShopProductsItem: {
outer_item_id: { type: 'string', required: true, description: '平台商品ID(订单明细的 outer_item_id)' },
outer_sku_id: { type: 'string', description: '平台规格ID(订单明细的 outer_sku_id)' },
},
pullShopProductsRequest: {
principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' },
items: { type: 'array', itemType: 'pullShopProductsItem', required: true, description: '待补拉的商品列表,单次最多 50 个' },
},
externalPrintShopProductPullMissing: {
outer_item_id: { type: 'string', description: '平台商品ID' },
outer_sku_id: { type: 'string', description: '平台规格ID' },
reason: { type: 'string', description: '未命中的原因' },
},
externalPrintShopProductPullItem: {
id: { type: 'integer', description: '店铺商品ID(可用于绑定)' },
shop_id: { type: 'integer', description: '所属店铺ID' },
outer_item_id: { type: 'string', description: '平台商品ID' },
outer_sku_id: { type: 'string', description: '平台规格ID' },
title: { type: 'string', description: '商品标题' },
spec: { type: 'string', description: '规格' },
platform_type: { type: 'string', description: '外部平台类型(已转换为系统预设平台编码,如 PDD / DYXD / SPH)' },
status: { type: 'integer', description: '状态:1在售 0下架' },
bind_type: { type: 'integer', description: '绑定类型:0未绑定 1系统商品 2组合商品' },
product_id: { type: 'integer', description: '绑定的系统商品ID' },
combo_product_id: { type: 'integer', description: '绑定的组合商品ID' },
},
externalPrintShopProductPullResult: {
requested: { type: 'integer', description: '提交的商品数' },
matched: { type: 'integer', description: '命中的商品行数(商品 + 规格)' },
created: { type: 'integer', description: '新增的店铺商品行数' },
updated: { type: 'integer', description: '更新的店铺商品行数' },
rekeyed: { type: 'integer', description: '按 SkuId 校正平台规格ID 的行数(同商品同规格名就地改键)' },
rematched: { type: 'integer', description: '本次补拉后补匹配上的订单明细行数(原本未采集到店铺商品的待审核明细)' },
hosts: { type: 'array', itemType: 'string', description: '命中的域名与分区' },
missing: { type: 'array', itemType: 'externalPrintShopProductPullMissing', description: '未命中的商品及原因' },
products: { type: 'array', itemType: 'externalPrintShopProductPullItem', description: '拉取后写入的店铺商品' },
},
externalPrintShopProductPullResponse: {
code: { type: 'integer', description: '业务状态码,0 成功' },
message: { type: 'string', description: '提示信息' },
data: { type: 'externalPrintShopProductPullResult', description: '单品补拉结果' },
},
syncShopOrdersRequest: {
principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' },
start_time: { type: 'string', description: '平台下单时间起(yyyy-MM-dd HH:mm:ss),与 days 二选一' },

View File

@ -29,7 +29,6 @@ function toSafeAccount(row) {
const SHOP_TYPE_EXTERNAL = 2;
/** 单品补拉时单次最多提交的商品数(订单明细一般远小于该值) */
const MAX_PULL_PRODUCT_ITEMS = 50;
/**
* 店铺商品唯一键(与店铺商品表的唯一索引对应)
@ -626,132 +625,6 @@ class ExternalPrintAccountController extends Controller {
}
}
/**
* @summary 按平台商品ID单独拉取店铺商品
* @description 订单明细匹配不到店铺商品时按需补拉:按平台商品ID(可选规格ID)在店铺所属分区及其它分区逐个查询,
* 命中后写入店铺商品表并返回该商品;不会改动其它商品的下架状态
* @router post /api/external-print-accounts/{id}/shops/{shopId}/pull-products
* @apikey
* @request path integer *id 账号主键ID
* @request path integer *shopId 店铺主键ID
* @request body pullShopProductsRequest *body
* @response 200 externalPrintShopProductPullResponse success
*/
async pullShopProducts() {
const { ctx } = this;
const account = await this.findAccount(ctx.params.id, { withPlatform: true });
if (!account) {
ctx.status = 404;
ctx.body = { code: 404, message: '打单账号不存在' };
return;
}
const shop = await ctx.model.Shop.findOne({
where: { id: ctx.params.shopId, principal_id: ctx.state.principalId },
});
if (!shop) {
ctx.status = 404;
ctx.body = { code: 404, message: '店铺不存在' };
return;
}
if (Number(shop.type) !== SHOP_TYPE_EXTERNAL) {
ctx.status = 400;
ctx.body = { code: 400, message: '仅外部打单平台商家支持拉取商品' };
return;
}
if (Number(shop.external_print_account_id) !== Number(account.id)) {
ctx.status = 400;
ctx.body = { code: 400, message: '该店铺不属于当前打单账号' };
return;
}
// 所在公司权限:仅可操作自己所属公司(货主)的店铺
const denied = await this.checkShopAccess(shop);
if (denied) {
ctx.status = denied.status;
ctx.body = denied.body;
return;
}
const body = ctx.request.body || {};
const items = (Array.isArray(body.items) ? body.items : [])
.map(item => ({
outer_item_id: String((item && item.outer_item_id) || '').trim(),
outer_sku_id: String((item && item.outer_sku_id) || '').trim(),
}))
.filter(item => item.outer_item_id);
if (!items.length) {
ctx.status = 400;
ctx.body = { code: 400, message: 'items 不能为空(需传 outer_item_id)' };
return;
}
if (items.length > MAX_PULL_PRODUCT_ITEMS) {
ctx.status = 400;
ctx.body = { code: 400, message: `单次最多补拉 ${MAX_PULL_PRODUCT_ITEMS} 个商品` };
return;
}
let result;
try {
const service = this.createPlatformService(account);
result = await service.listProductsByIds(shop.get({ plain: true }), items);
} catch (err) {
ctx.status = 400;
ctx.body = { code: 400, message: err.message };
return;
}
let saved;
try {
// verified=false:单品补拉只做 upsert,不做移除处理,避免把其它商品误删
saved = await this.saveShopProducts(shop, { list: result.list, verified: false });
} catch (err) {
ctx.status = 500;
ctx.body = { code: 500, message: `保存店铺商品失败:${err.message}` };
return;
}
const savedRows = await this.findSavedShopProducts(shop.id, result.list);
ctx.body = {
code: 0,
message: 'success',
data: {
requested: items.length,
matched: result.list.length,
created: saved.created,
updated: saved.updated,
rekeyed: saved.rekeyed || 0,
rematched: saved.rematched || 0,
hosts: result.hosts,
missing: result.missing,
products: savedRows,
},
};
}
/**
* 回查刚写入的店铺商品(供前端直接拿到店铺商品ID去绑定)
* @param {number} shopId 店铺ID
* @param {Array} list 归一化后的商品行
* @return {Promise<Array>} 店铺商品关键字段
*/
async findSavedShopProducts(shopId, list) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const outerIds = Array.from(new Set(list.map(item => item.outer_item_id).filter(Boolean)));
if (!outerIds.length) return [];
const keys = new Set(list.map(item => shopProductKey(item.outer_item_id, item.outer_sku_id)));
const rows = await ctx.model.ShopProduct.findAll({
where: { shop_id: shopId, outer_item_id: { [Op.in]: outerIds } },
attributes: [ 'id', 'shop_id', 'outer_item_id', 'outer_sku_id', 'title', 'spec', 'platform_type', 'status', 'bind_type', 'product_id', 'combo_product_id' ],
raw: true,
});
return rows.filter(row => keys.has(shopProductKey(row.outer_item_id, row.outer_sku_id)));
}
/**
* @summary 拉取外部打单平台商家的订单
* @description 按时间窗拉取平台订单(含明细)并写入 orders / order_items;

View File

@ -196,18 +196,6 @@ class PrintPlatformService {
throw new Error(`外部打单平台 ${this.platformName} 未实现 listOrders()`);
}
/**
* 按平台商品ID(可选规格ID)单独拉取商品,用于订单明细匹配不到店铺商品时按需补拉,由各平台实现。
* 需返回统一结构:
* { list: [与 listProducts().list 同结构], missing: [{ outer_item_id, outer_sku_id, reason }], hosts: [命中来源说明] }
* @param {Object} shop OMS 店铺记录(type=2,external_data 为平台返回的商家原始结构)
* @param {Array<{outer_item_id: string, outer_sku_id?: string}>} items 待补拉的商品
* @return {Promise<{list: Array, missing: Array, hosts: Array}>} 命中与未命中的商品
*/
async listProductsByIds(shop, items) { // eslint-disable-line no-unused-vars
throw new Error(`外部打单平台 ${this.platformName} 未实现 listProductsByIds()`);
}
/**
* 把订单推送到打单平台打印,由各平台实现
* @param {Object} order 订单数据(字段口径由平台协议决定)

View File

@ -1767,81 +1767,6 @@ class DgjService extends PrintPlatformService {
};
}
/**
* 按平台商品ID(可选规格ID)单独拉取商品,用于订单明细匹配不到店铺商品时按需补拉。
* 单品查询不传 SelectAgentId:商品可能属于同一账号下的其它商家,按商品ID更容易命中;
* 域名与分区按「店铺所属分区优先、其余域名兜底」的顺序逐个尝试,命中即停止。
* @param {Object} shop OMS 店铺记录(type=2,external_data 为商家原始结构)
* @param {Array<{outer_item_id: string, outer_sku_id?: string}>} items 待补拉的商品
* @return {Promise<{list: Array, missing: Array, hosts: Array}>} 命中的店铺商品行与未命中的商品
*/
async listProductsByIds(shop, items = []) {
if (!this.token || !this.cookie) {
throw new Error('账号未登录:缺少 token 或 cookie,请先登录');
}
const data = (shop && shop.external_data) || {};
const hosts = [];
for (const host of [ ...this.resolveProductHosts(data), ...FALLBACK_PRODUCT_HOSTS ]) {
if (!hosts.includes(host)) hosts.push(host);
}
let traceId = '';
try {
const info = await this.getUserInfo();
traceId = (info.data && info.data.TraceId) || '';
} catch {
// 忽略:traceId 缺失不阻断单品查询
}
const areaCache = new Map();
const list = [];
const missing = [];
const hitHosts = new Set();
for (const item of items) {
const productId = String((item && item.outer_item_id) || '').trim();
const skuId = String((item && item.outer_sku_id) || '').trim();
if (!productId) {
missing.push({ outer_item_id: productId, outer_sku_id: skuId, reason: '缺少平台商品ID' });
continue;
}
let matched = [];
for (const host of hosts) {
if (!areaCache.has(host)) areaCache.set(host, await this.listProductAreas(host));
for (const area of areaCache.get(host)) {
const page = await this.fetchProductPage(host, {
traceId,
dbname: area.dbname,
productId,
skuId,
pageIndex: 1,
pageSize: 20,
});
if (!page.rows.length) continue;
for (const product of page.rows) {
const rows = this.normalizeProduct(product);
// 带规格ID时只保留该规格(平台可能返回整个商品的全部规格)
const picked = skuId ? rows.filter(row => row.outer_sku_id === skuId) : rows;
matched = matched.concat(picked);
}
if (matched.length) {
hitHosts.add(`${host}(${area.name || area.dbname})`);
break;
}
}
if (matched.length) break;
}
if (matched.length) list.push(...matched);
else missing.push({ outer_item_id: productId, outer_sku_id: skuId, reason: '平台未查询到该商品' });
}
return { list, missing, hosts: Array.from(hitHosts) };
}
/**
* 把店管家商品(含 SKU 列表)转换为店铺商品行的统一结构。
* 平台商品ID取商品级 PlatformId;平台规格ID统一取 SKU 的 `SkuId`
@ -2058,7 +1983,6 @@ class DgjService extends PrintPlatformService {
// 店铺的「所在区」声明(external_data.DbAreas)可能过期:重新授权/换绑后不会自动同步,
// 声明域名一单都没有时再补查账号的其它域名,否则会出现「店管家 UI 有单、OMS 拉不到」
// (单品补拉 listProductsByIds 一直就是这么兜底的,全量拉取此前只查声明域名)
const supplementHosts = [];
if (!orders.size && !finished.size) {
const extraHosts = FALLBACK_PRODUCT_HOSTS.filter(host => !hosts.includes(host));

View File

@ -189,8 +189,6 @@ module.exports = app => {
router.post('/api/external-print-accounts/:id/refresh-shops-area', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.refreshShopAreas);
// 同步商家店铺商品(按商家分区逐域名拉取全量快照后写入店铺商品表)
router.post('/api/external-print-accounts/:id/shops/:shopId/sync-products', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.syncShopProducts);
// 按平台商品ID单独补拉(订单明细匹配不到店铺商品时使用,不做下架处理)
router.post('/api/external-print-accounts/:id/shops/:shopId/pull-products', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.pullShopProducts);
// 拉取商家订单(含明细),明细按店铺商品绑定关系写入系统商品关联
router.post('/api/external-print-accounts/:id/shops/:shopId/sync-orders', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), controller.externalPrintAccount.syncShopOrders);
// 快递接口(面单模板):查看读取已落库数据,手动同步全量拉取;保存绑定的快递编码,明细单独请求平台接口

View File

@ -153,53 +153,6 @@ export function syncExternalPrintShopProducts(accountId: number, shopId: number)
)
}
/** 待补拉的商品(订单明细里的平台商品ID/规格ID) */
export interface PullShopProductItem {
outer_item_id: string
outer_sku_id?: string
}
/** 单品补拉结果里写入的店铺商品 */
export interface PulledShopProductRow {
id: number
shop_id: number
outer_item_id: string
outer_sku_id: string | null
title: string | null
spec: string | null
platform_type: string | null
status: number
bind_type: number
product_id: number | null
combo_product_id: number | null
}
/** 单品补拉结果(未命中的商品带原因返回) */
export interface PullShopProductsResult {
requested: number
matched: number
created: number
updated: number
/** 本次补拉后补匹配上的订单明细行数(原本未采集到店铺商品) */
rematched?: number
hosts: string[]
missing: Array<{ outer_item_id: string; outer_sku_id: string; reason: string }>
products: PulledShopProductRow[]
}
/** 按平台商品ID单独补拉店铺商品(订单明细匹配不到店铺商品时使用) */
export function pullExternalPrintShopProducts(
accountId: number,
shopId: number,
items: PullShopProductItem[],
) {
return post<PullShopProductsResult>(
`/external-print-accounts/${accountId}/shops/${shopId}/pull-products`,
{ items },
{ timeout: 120000 },
)
}
/** 拉取订单结果(手动与定时共用同一后端逻辑) */
export interface SyncShopOrdersResult {
start_time: string

View File

@ -9,7 +9,6 @@ import {
BIND_TYPES,
type ShopProductItem,
} from '@/api/shopProduct'
import { pullExternalPrintShopProducts } from '@/api/externalPrintAccount'
import { getShops, type ShopItem } from '@/api/shop'
import { getProducts, type ProductItem } from '@/api/product'
import { getComboProducts, type ComboProductItem } from '@/api/comboProduct'
@ -443,63 +442,7 @@ const logTargetName = computed(() => {
return `${name}(平台商品ID ${row.outer_item_id}${spec})`
})
/* -------------------- 按平台商品ID补拉 -------------------- */
const pullVisible = ref(false)
const pullSubmitting = ref(false)
const pullForm = reactive({
shop_id: '' as string | number,
outer_item_id: '',
outer_sku_id: '',
})
/** 只允许选择外部打单平台商家店铺(其它类型没有平台商品可拉) */
const externalShops = computed(() => shops.value.filter((shop) => Number(shop.type) === 2))
function openPull() {
// 列表已选单个店铺时带过来,否则默认第一个外部打单平台店铺
pullForm.shop_id = query.shop_ids.length === 1 ? query.shop_ids[0] : (externalShops.value[0]?.id ?? '')
pullForm.outer_item_id = ''
pullForm.outer_sku_id = ''
pullVisible.value = true
}
async function submitPull() {
const shop = shops.value.find((item) => Number(item.id) === Number(pullForm.shop_id))
const outerItemId = pullForm.outer_item_id.trim()
if (!shop) {
ElMessage.warning('请选择外部打单平台店铺')
return
}
if (!shop.external_print_account_id) {
ElMessage.warning('该店铺未关联外部打单账号,无法拉取商品')
return
}
if (!outerItemId) {
ElMessage.warning('请输入平台商品ID')
return
}
pullSubmitting.value = true
try {
const res = await pullExternalPrintShopProducts(shop.external_print_account_id, shop.id, [
{ outer_item_id: outerItemId, outer_sku_id: pullForm.outer_sku_id.trim() },
])
if (!res.matched) {
const reason = res.missing[0]?.reason || '平台未查询到该商品'
ElMessage.warning(`未拉取到商品:${reason}`)
return
}
const rematch = res.rematched ? `,自动匹配订单明细 ${res.rematched} 条` : ''
ElMessage.success(`拉取成功:新增 ${res.created},更新 ${res.updated},来源 ${res.hosts.join('、')}${rematch}`)
pullVisible.value = false
await fetchList()
} catch {
// 拦截器已提示
} finally {
pullSubmitting.value = false
}
}
/* -------------------- 弹窗与初始化 -------------------- */
onMounted(async () => {
updateBindBodyHeight()
window.addEventListener('resize', updateBindBodyHeight)
@ -521,7 +464,6 @@ onBeforeUnmount(() => {
<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>
</div>
@ -714,38 +656,6 @@ onBeforeUnmount(() => {
</div>
</div>
<el-dialog v-model="pullVisible" title="按平台商品ID拉取" width="520px">
<el-alert
type="info"
:closable="false"
show-icon
title="用于订单明细匹配不到店铺商品时补拉:填平台商品ID(可选规格ID),后端按店铺分区及其它域名查询后写入店铺商品"
class="pull-tip"
/>
<el-form :model="pullForm" label-width="100px">
<el-form-item label="店铺" required>
<VirtualSelect
v-model="pullForm.shop_id"
:options="externalShops"
label-key="name"
value-key="id"
placeholder="请选择外部打单平台店铺"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="平台商品ID" required>
<el-input v-model="pullForm.outer_item_id" placeholder="订单明细的 outer_item_id" clearable />
</el-form-item>
<el-form-item label="平台规格ID">
<el-input v-model="pullForm.outer_sku_id" placeholder="留空则拉取该商品的全部规格" clearable />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="pullVisible = false">取消</el-button>
<el-button type="primary" :loading="pullSubmitting" @click="submitPull">拉取</el-button>
</template>
</el-dialog>
<el-dialog
v-model="bindVisible"
:title="bindTitle"
@ -1015,10 +925,6 @@ onBeforeUnmount(() => {
background: var(--el-fill-color-light);
}
.pull-tip {
margin-bottom: 16px;
}
/* 绑定弹窗:左侧页签 + 右侧列表(表格内部滚动,分页固定在底部) */
.bind-layout {
/* 高度由脚本按视口计算(bindBodyHeight),避免小屏溢出 */

View File

@ -422,10 +422,14 @@ WaybillCodeCreateDate='2026-11-04 08:20:37'
- **两种 `parse_status=2` 都会被待审核列表的「仅已绑定」过滤掉**,列表会给出「另有 N 单未显示」提示
(`order_status.list` 的 `hidden_unbound`)。
**商品写入后自动重匹配**(`service/orderItemResolve.rematchUnboundItems`):同步 / 单品补拉商品后,
**商品写入后自动重匹配**(`service/orderItemResolve.rematchUnboundItems`):同步商品后,
在同一事务里把该店铺「`shop_product_id` 为空」的**待审核 / 异常**明细按上述口径再匹配一次并重建明细,
避免「先拉单、后同步商品」导致明细永远停在未采集(已审核之后的订单明细不参与,随审核锁定)。
接口返回 `rematched`(补上的明细行数)。
同步商品接口返回 `rematched`(补上的明细行数)。
> 早期还有一个「按平台商品ID单独补拉」的入口(`POST …/pull-products` + `listProductsByIds`),
> 已移除:它绕开分区声明与 `SelectAgentId` 单查商品,容易把别的商家的同款商品写进本店铺,
> 现在统一走「同步商品(全量快照)+ 自动重匹配」。
沿用旧口径的坑:老数据里 `shop_products.outer_sku_id` 可能是 `SpecId`,与明细的 `SkuId` 对不上;
重新同步商品会按 `SkuId` 就地改键(同商品同规格名唯一命中),之后重匹配即可命中。