From c27ea5a7893a0935b4ca66dd85e0ae890e162d8f Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 9 Nov 2026 02:42:19 +0800 Subject: [PATCH] =?UTF-8?q?feat(shop):=20=E5=BA=97=E7=AE=A1=E5=AE=B6?= =?UTF-8?q?=E6=8E=A5=E5=85=A5=E3=80=8C=E6=88=91=E7=9A=84=E5=BA=97=E9=93=BA?= =?UTF-8?q?=E3=80=8D=E7=AC=AC=E4=BA=8C=E6=9D=A5=E6=BA=90=EF=BC=8C=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E6=8B=89=E5=8F=96=E5=BA=97=E9=93=BA=E5=B9=B6=E7=BB=91?= =?UTF-8?q?=E5=AE=9A=E8=B4=A7=E4=B8=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 平台层新增 listShopSources() / resolveShopScope() 契约,来源由平台实现声明,控制器与前端不写死 - 店管家实现 my_shop 来源:POST /partner/LoadMyShopList 店铺列表(授权状态、平台、名称过滤)并归一化 - 新增 GET /api/external-print-accounts/:id/shop-sources;店铺列表接口支持 ?source= - 店铺创建支持 source,写入 shops.external_source;编码 dgj-{账号ID}-{来源}-{ShopId},默认来源不加来源段 - 新增迁移 shops.external_source(默认 agent);刷新所在区只处理默认来源,避免自营店被误判解绑而自动禁用 - my_shop 的拉单/拉商品暂时明确拒绝,防止按账号 FxUserId 拉到上游其它数据(下一步接入) - 前端「店铺列表」弹窗支持来源切换,展示平台、授权状态与服务到期时间 - 补充单元测试与文档(店管家取号-旧系统提取 §4.2.1.1) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 8 + backend/app/contract/index.js | 41 ++- .../app/controller/externalPrintAccount.js | 103 +++++-- backend/app/lib/printPlatform/base.js | 39 ++- backend/app/lib/printPlatform/dgj.js | 272 ++++++++++++++++-- backend/app/model/shop.js | 3 +- backend/app/router.js | 4 +- backend/app/service/shopAreaSync.js | 7 +- ...1109110000-add-external-source-to-shops.js | 32 +++ backend/test/app/lib/dgjMyShopList.test.js | 139 +++++++++ frontend/src/api/externalPrintAccount.ts | 55 +++- .../src/views/ExternalPrintPlatform/Index.vue | 67 ++++- 店管家取号-旧系统提取.md | 31 ++ 13 files changed, 737 insertions(+), 64 deletions(-) create mode 100644 backend/database/migrations/20261109110000-add-external-source-to-shops.js create mode 100644 backend/test/app/lib/dgjMyShopList.test.js diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index c9ad555..d7ae54c 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -34,6 +34,14 @@ 5. 同步更新 `店管家取号-旧系统提取.md` §4.2 换算表 / §4.2.6 6. `npx egg-bin test test/app/lib/dgjOrderPlatformRule.test.js` 后提交 +## 店管家店铺的两个来源 + +`shops.external_source` 区分 `agent`(平台商家,`LoadMyAgentList`,订单按商家 `FxUserId` 归属) +与 `my_shop`(我的店铺,`LoadMyShopList`,订单按 `ShopId` 归属)。来源清单由 +`PrintPlatformService.listShopSources()` 声明,控制器/前端不写死。 +`my_shop` 目前只支持店铺导入,`listOrders` / `listProducts` 会明确报「暂未支持」, +避免按账号 `FxUserId` 拉到别人的数据。细节见 `店管家取号-旧系统提取.md` §4.2.1.1。 + ## 常见排查入口 - 取号失败:平台原始返回在 `waybill_fetch_records.raw_response`,可读原因由 `DgjService.describeWaybillError` diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 21350c1..b823c0c 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -58,7 +58,8 @@ const shopItem = { status: { type: 'integer', description: '状态:1启用 0禁用' }, type: { type: 'integer', description: '店铺类型:1平台店铺 2外部打单平台商家 3数据库模式(预留)' }, external_print_account_id: { type: 'integer', description: '来源外部打单账号ID(type=2 时有值)' }, - external_data: { type: 'string', description: '外部打单平台返回的商家原始结构 JSON' }, + external_source: { type: 'string', description: '外部打单平台店铺来源(平台自定义,如 agent/my_shop)' }, + external_data: { type: 'string', description: '外部打单平台返回的店铺原始结构 JSON' }, db_host: { type: 'string', description: '数据库地址(type=3 数据库模式店铺使用,预留)' }, db_port: { type: 'integer', description: '数据库端口(type=3 数据库模式店铺使用,预留)' }, db_name: { type: 'string', description: '数据库名(type=3 数据库模式店铺使用,预留)' }, @@ -1446,22 +1447,46 @@ module.exports = { message: { type: 'string', description: '提示信息' }, data: { type: 'externalPrintAccountLoginResult', description: '登录结果' }, }, + externalPrintShopSource: { + code: { type: 'string', description: '来源标识(平台自定义,如 agent / my_shop)' }, + name: { type: 'string', description: '来源名称(如「平台商家」「我的店铺」)' }, + }, + externalPrintShopSourceResult: { + list: { type: 'array', itemType: 'externalPrintShopSource', description: '平台支持的店铺来源(第一个为默认来源)' }, + }, + externalPrintShopSourceListResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'externalPrintShopSourceResult', description: '店铺来源清单' }, + }, externalPrintMerchantItem: { - external_id: { type: 'string', description: '平台侧商家ID' }, - name: { type: 'string', description: '商家名称' }, + source: { type: 'string', description: '店铺来源(agent / my_shop,见 /shop-sources)' }, + external_id: { type: 'string', description: '平台侧店铺ID(商家来源为商家ID,我的店铺为平台店铺ID)' }, + name: { type: 'string', description: '店铺/商家名称' }, contact_name: { type: 'string', description: '联系人' }, contact_phone: { type: 'string', description: '联系电话' }, - status: { type: 'integer', description: '状态:1正常 0停用' }, + status: { type: 'integer', description: '状态:1正常 0停用或授权过期' }, + status_label: { type: 'string', description: '状态文案(正常 / 停用 / 授权过期 / 服务到期)' }, + platform_code: { type: 'string', description: '电商平台编码(系统预设,如 DYXD / PDD / TB)' }, + platform_name: { type: 'string', description: '电商平台名称(如「抖店」)' }, + platform_type: { type: 'string', description: '平台原始标识(如 TouTiao,仅留痕)' }, + auth_expired: { type: 'boolean', description: '平台授权是否过期(我的店铺来源)' }, + service_expired: { type: 'boolean', description: '服务是否到期(我的店铺来源)' }, + auth_time: { type: 'string', description: '服务到期时间(我的店铺来源)' }, remark: { type: 'string', description: '备注(如商家分组)' }, added: { type: 'boolean', description: '是否已创建到 OMS 店铺' }, - raw: { type: 'string', description: '平台返回的商家原始结构 JSON' }, + raw: { type: 'string', description: '平台返回的店铺原始结构 JSON' }, + }, + externalPrintMerchantPage: { + ...buildPage('externalPrintMerchantItem', '外部打单平台店铺列表'), + source: { type: 'string', description: '本次返回的店铺来源(缺省取平台第一项来源)' }, }, - externalPrintMerchantPage: buildPage('externalPrintMerchantItem', '外部打单平台商家列表'), externalPrintMerchantListResponse: buildListResponse('externalPrintMerchantPage'), createShopsFromMerchantsRequest: { principal_id: { type: 'integer', required: true, description: '所属主体ID,由请求拦截器注入' }, subsidiary_id: { type: 'integer', required: true, description: '所属货主(下属公司ID),必填:添加店铺时指定归属货主' }, - merchants: { type: 'array', itemType: 'externalPrintMerchantItem', required: true, description: '要创建到店铺的商家列表(取自商家列表接口)' }, + source: { type: 'string', description: '店铺来源(缺省取平台第一项来源,店管家为 agent)' }, + merchants: { type: 'array', itemType: 'externalPrintMerchantItem', required: true, description: '要创建到 OMS 店铺的店铺列表(取自店铺列表接口)' }, }, externalPrintExpressInterfaceSaveItem: { id: { type: 'integer', required: true, description: '快递接口记录ID' }, @@ -1474,7 +1499,7 @@ module.exports = { }, externalPrintShopCreatedItem: { id: { type: 'integer', description: '店铺主键' }, - code: { type: 'string', description: '店铺编码(平台标识-账号ID-商家ID)' }, + code: { type: 'string', description: '店铺编码(平台标识-账号ID-来源-店铺ID,默认来源省略来源段)' }, name: { type: 'string', description: '店铺名称' }, }, externalPrintShopCreateResult: { diff --git a/backend/app/controller/externalPrintAccount.js b/backend/app/controller/externalPrintAccount.js index 91e1b1e..b70919d 100644 --- a/backend/app/controller/externalPrintAccount.js +++ b/backend/app/controller/externalPrintAccount.js @@ -102,14 +102,20 @@ const SHOP_PRODUCT_UPSERT_FIELDS = [ ]; /** - * 外部平台商家在 OMS 店铺表中的编码:平台标识-账号ID-商家ID(最多 50 字符) + * 外部平台店铺在 OMS 店铺表中的编码:平台标识-账号ID-来源-店铺ID(最多 50 字符) + * + * 默认来源(店管家为 agent)不加来源段,保持历史编码不变; + * 其它来源加来源段,避免同一账号下不同来源的 external_id 撞车。 * @param {string} platformCode 平台标识 * @param {number} accountId 账号ID - * @param {string} externalId 商家ID + * @param {string} externalId 平台侧店铺/商家ID + * @param {string} [source] 店铺来源 + * @param {string} [defaultSource] 平台的默认来源 * @return {string} 店铺编码 */ -function buildExternalShopCode(platformCode, accountId, externalId) { - return `${platformCode}-${accountId}-${externalId}`.slice(0, 50); +function buildExternalShopCode(platformCode, accountId, externalId, source = '', defaultSource = 'agent') { + const prefix = source && source !== defaultSource ? `${source}-` : ''; + return `${platformCode}-${accountId}-${prefix}${externalId}`.slice(0, 50); } class ExternalPrintAccountController extends Controller { @@ -363,14 +369,45 @@ class ExternalPrintAccountController extends Controller { } /** - * @summary 拉取账号在外部打单平台的店铺(商家)列表 - * @description 实时向平台拉取并标记是否已创建到 OMS 店铺;不落库。前端按账号ID调用,不直连平台 + * @summary 账号所属打单平台支持的店铺来源 + * @description 前端据此渲染来源切换(如店管家的「平台商家 / 我的店铺」),不写死平台来源 + * @router get /api/external-print-accounts/{id}/shop-sources + * @apikey + * @request path integer *id 账号主键ID + * @response 200 externalPrintShopSourceListResponse success + */ + async shopSources() { + const { ctx } = this; + const account = await this.findAccount(ctx.params.id, { withPlatform: true }); + + if (!account) { + ctx.status = 404; + ctx.body = { code: 404, message: '打单账号不存在' }; + return; + } + + try { + const service = this.createPlatformService(account); + ctx.body = { code: 0, message: 'success', data: { list: service.listShopSources() } }; + } catch (err) { + ctx.status = 400; + ctx.body = { code: 400, message: err.message }; + } + } + + /** + * @summary 拉取账号在外部打单平台的店铺列表(按来源) + * @description 实时向平台拉取并标记是否已创建到 OMS 店铺;不落库。前端按账号ID调用,不直连平台。 + * source 缺省取平台来源清单的第一项(店管家为 agent 平台商家) * @router get /api/external-print-accounts/{id}/merchants * @apikey * @request path integer *id 账号主键ID + * @request query string source 店铺来源(见 /shop-sources),默认平台第一项 * @request query integer page 页码,默认 1 * @request query integer pageSize 每页条数,默认 20 - * @request query string keyword 关键词(商家名称/手机号) + * @request query string keyword 关键词(名称/手机号) + * @request query string status 授权状态(店管家我的店铺:1 授权成功 / 3 授权过期,空为全部) + * @request query string platformTypes 平台过滤(店管家我的店铺,逗号分隔,如 TouTiao,KuaiShou) * @response 200 externalPrintMerchantListResponse success */ async merchants() { @@ -388,14 +425,28 @@ class ExternalPrintAccountController extends Controller { try { const service = this.createPlatformService(account); + const sources = service.listShopSources(); + const defaultSource = (sources[0] && sources[0].code) || 'default'; + const source = String(ctx.query.source || '').trim() || defaultSource; + const result = await service.listShops({ + source, pageIndex: page, pageSize, keyword: ctx.query.keyword || '', + status: ctx.query.status || '', + platformTypes: ctx.query.platformTypes || ctx.query.platform_types || '', }); const platformCode = account.platform.code; - const codes = result.list.map(item => buildExternalShopCode(platformCode, account.id, item.external_id)); + const codeOf = item => buildExternalShopCode( + platformCode, + account.id, + item.external_id, + item.source || source, + defaultSource + ); + const codes = result.list.map(codeOf); const existing = codes.length ? await ctx.model.Shop.findAll({ where: { principal_id: ctx.state.principalId, code: { [Op.in]: codes } }, @@ -405,12 +456,13 @@ class ExternalPrintAccountController extends Controller { : []; const added = new Set(existing.map(row => row.code)); - const list = result.list.map(item => ({ - ...item, - added: added.has(buildExternalShopCode(platformCode, account.id, item.external_id)), - })); + const list = result.list.map(item => ({ ...item, added: added.has(codeOf(item)) })); - ctx.body = { code: 0, message: 'success', data: buildPageResult(list, result.total, { page, pageSize }) }; + ctx.body = { + code: 0, + message: 'success', + data: { ...buildPageResult(list, result.total, { page, pageSize }), source }, + }; } catch (err) { ctx.status = 400; ctx.body = { code: 400, message: err.message }; @@ -448,8 +500,9 @@ class ExternalPrintAccountController extends Controller { } /** - * @summary 把外部打单平台的店铺(商家)创建到 OMS 店铺 - * @description merchants 为商家列表接口返回的项(含 raw),按 external_id 去重;已存在的跳过 + * @summary 把外部打单平台的店铺创建到 OMS 店铺 + * @description merchants 为店铺列表接口返回的项(含 raw),按 external_id 去重;已存在的跳过。 + * source 缺省取平台来源清单的第一项;店铺会记录来源(shops.external_source) * @router post /api/external-print-accounts/{id}/shops * @apikey * @request path integer *id 账号主键ID @@ -481,6 +534,21 @@ class ExternalPrintAccountController extends Controller { const platformCode = account.platform.code; const principalId = ctx.state.principalId; + // 店铺来源:缺省用平台的第一项来源(店管家为 agent 平台商家) + let sources = []; + try { + sources = this.createPlatformService(account).listShopSources(); + } catch { + sources = []; + } + const defaultSource = (sources[0] && sources[0].code) || 'agent'; + const source = String(ctx.request.body.source || '').trim() || defaultSource; + if (sources.length && !sources.some(item => item.code === source)) { + ctx.status = 400; + ctx.body = { code: 400, message: `不支持的店铺来源:${source}` }; + return; + } + // 添加店铺时必须选择货主(下属公司),货主权限据此判定店铺归属 const subsidiaryId = Number(ctx.request.body.subsidiary_id); if (!Number.isInteger(subsidiaryId) || subsidiaryId <= 0) { @@ -506,7 +574,7 @@ class ExternalPrintAccountController extends Controller { const externalId = String((item && item.external_id) || '').trim(); if (!externalId) continue; - const code = buildExternalShopCode(platformCode, account.id, externalId); + const code = buildExternalShopCode(platformCode, account.id, externalId, source, defaultSource); const exist = await ctx.model.Shop.findOne({ where: { principal_id: principalId, code }, transaction }); if (exist) continue; @@ -521,7 +589,8 @@ class ExternalPrintAccountController extends Controller { status: Number(item.status) === 0 ? 0 : 1, type: SHOP_TYPE_EXTERNAL, external_print_account_id: account.id, - // 原样保存平台返回的商家完整结构(未带 raw 时退化为保存整条入参),后续按需取字段 + external_source: source, + // 原样保存平台返回的店铺完整结构(未带 raw 时退化为保存整条入参),后续按需取字段 external_data: item.raw || item, remark: item.remark ? String(item.remark).slice(0, 255) : null, }, { transaction }); diff --git a/backend/app/lib/printPlatform/base.js b/backend/app/lib/printPlatform/base.js index ab35e0b..c9726c4 100644 --- a/backend/app/lib/printPlatform/base.js +++ b/backend/app/lib/printPlatform/base.js @@ -142,11 +142,46 @@ class PrintPlatformService { throw new Error(`外部打单平台 ${this.platformName} 未实现 checkSession()`); } + /** + * 该平台支持的店铺来源清单(同一账号下可能有多种来源的店铺)。 + * + * 通用层与前端只认这个清单:新增来源/新平台时只改平台实现,接口和页面都不用动。 + * 默认实现为单一来源,老平台保持原行为。 + * @return {Array<{code: string, name: string}>} 来源清单(第一个为默认来源) + */ + listShopSources() { + return [{ code: 'default', name: '店铺' }]; + } + + /** + * 解析店铺在平台侧的作用域(订单/商品/分区同步都按它取数)。 + * + * 各平台把「用哪个字段定位店铺、去哪些域名查」这类平台知识收在自己实现里, + * 上层(控制器、定时任务、订单/商品同步)不再直接读 external_data 的平台字段。 + * @param {Object} shop OMS 店铺记录(type=2) + * @return {{source: string, externalId: string, shopId: string, platformType: string, hosts: string[]}} 店铺作用域 + */ + resolveShopScope(shop) { // eslint-disable-line no-unused-vars + const data = (shop && shop.external_data) || {}; + const code = String((shop && shop.code) || ''); + const tail = code.includes('-') ? code.slice(code.lastIndexOf('-') + 1) : code; + return { + source: String((shop && shop.external_source) || 'default'), + externalId: String(data.Id == null ? tail : data.Id), + shopId: data.ShopId == null ? '' : String(data.ShopId), + platformType: String(data.PlatformType || ''), + hosts: [], + }; + } + /** * 拉取平台侧的店铺/商家列表,由各平台实现。 * 需返回统一结构,避免上层直接依赖各平台字段: - * { total, list: [{ external_id, name, contact_name, contact_phone, status, remark, raw }] } - * @param {Object} [options] 查询参数:pageIndex / pageSize / keyword + * { total, list: [{ + * source, external_id, name, contact_name, contact_phone, status, status_label, + * platform, platform_code, platform_name, remark, raw, + * }] } + * @param {Object} [options] 查询参数:source(默认取 listShopSources() 的第一项)/ pageIndex / pageSize / keyword / status / platformTypes * @return {Promise<{total: number, list: Array}>} 平台店铺列表 */ async listShops(options) { // eslint-disable-line no-unused-vars diff --git a/backend/app/lib/printPlatform/dgj.js b/backend/app/lib/printPlatform/dgj.js index 7357311..b5833ce 100644 --- a/backend/app/lib/printPlatform/dgj.js +++ b/backend/app/lib/printPlatform/dgj.js @@ -23,6 +23,10 @@ const USER_INFO_URL = `https://${WORKBENCH_HOST}/api/user/GetUserInfo`; const AREAS_INFO_PATH = '/api/user/GetAreasInfo'; /** 商家(即店管家侧的店铺)列表接口 */ const AGENT_LIST_URL = `https://${WORKBENCH_HOST}/Partner/LoadMyAgentList`; +/** 账号自己绑定的平台店铺(我的店铺 → 国内电商)列表接口 */ +const MY_SHOP_LIST_URL = `https://${WORKBENCH_HOST}/partner/LoadMyShopList`; +/** 「我的店铺」接口不支持关键词搜索,带关键词时最多翻的页数(200/页,防异常总数死循环) */ +const MY_SHOP_MAX_PAGES = 20; /** 商品列表接口(按分区域名请求,路径固定) */ const PRODUCT_LIST_PATH = '/Product/LoadList'; @@ -501,6 +505,7 @@ const PLATFORM_TYPE_PRESETS = { xiaohongshu: 'XHS', dewu: 'DW', meituan: 'MTYYJK', + virtual: 'OFFLINE', offline: 'OFFLINE', }; @@ -1171,6 +1176,24 @@ class DgjService extends PrintPlatformService { return 'dgj'; } + /** + * 店管家的两种店铺来源: + * - agent:合作商家(「绑定商家」LoadMyAgentList),订单按 PathFlowNode.UpFxUserId 归属 + * - my_shop:账号自己绑定的平台店铺(「我的店铺」LoadMyShopList),订单按 LogicOrder.ShopId 归属 + */ + static shopSources = [ + { code: 'agent', name: '平台商家' }, + { code: 'my_shop', name: '我的店铺' }, + ]; + + /** + * 店铺来源清单(第一个为默认来源) + * @return {Array<{code: string, name: string}>} 来源清单 + */ + listShopSources() { + return this.constructor.shopSources.map(item => ({ ...item })); + } + /** * 店管家站点根地址(平台配置的链接未带协议时补 https://) * @return {string} 站点根地址 @@ -1276,24 +1299,10 @@ class DgjService extends PrintPlatformService { } /** - * 拉取当前账号的商家列表(店管家的「商家」即 OMS 的店铺)。 - * 返回统一结构,上层(控制器/前端)不直接依赖店管家字段。 - * @param {Object} [options] 查询参数 - * @param {number} [options.pageIndex] 页码,从 1 开始 - * @param {number} [options.pageSize] 每页条数(最大 200) - * @param {string} [options.keyword] 关键词(商家名称/手机号) - * @return {Promise<{total: number, list: Array}>} 统一的店铺列表 + * 店铺列表接口需要的登录上下文(traceId 与默认分区库名) + * @return {Promise<{traceId: string, dbName: string}>} 上下文参数,取不到时为空串 */ - async listShops(options = {}) { - if (!this.token || !this.cookie) { - throw new Error('账号未登录:缺少 token 或 cookie,请先登录'); - } - - const pageIndex = Math.max(1, Number.parseInt(options.pageIndex, 10) || 1); - const pageSize = Math.min(200, Math.max(1, Number.parseInt(options.pageSize, 10) || 20)); - const keyword = String(options.keyword || ''); - - // 商家列表接口需要 traceId 与 dbname,取不到时按空值请求 + async shopListContext() { let traceId = ''; let dbName = ''; try { @@ -1304,6 +1313,45 @@ class DgjService extends PrintPlatformService { } catch { // 忽略:上下文参数缺失不阻断列表查询 } + return { traceId, dbName }; + } + + /** + * 拉取当前账号的店铺列表,按 source 分派到对应来源。 + * 返回统一结构,上层(控制器/前端)不直接依赖店管家字段。 + * @param {Object} [options] 查询参数 + * @param {string} [options.source] 来源(agent / my_shop),默认取 listShopSources() 第一项 + * @param {number} [options.pageIndex] 页码,从 1 开始 + * @param {number} [options.pageSize] 每页条数(最大 200) + * @param {string} [options.keyword] 关键词(名称/手机号) + * @param {string} [options.status] 授权状态(仅 my_shop:'' 全部 / '1' 授权成功 / '3' 授权过期) + * @param {string|string[]} [options.platformTypes] 平台过滤(仅 my_shop,如 TouTiao,KuaiShou) + * @return {Promise<{total: number, list: Array, source: string}>} 统一的店铺列表 + */ + async listShops(options = {}) { + const sources = this.listShopSources(); + const source = String(options.source || (sources[0] && sources[0].code) || '').trim(); + if (source === 'my_shop') return { ...(await this.listMyShops(options)), source }; + return { ...(await this.listAgentShops(options)), source: 'agent' }; + } + + /** + * 平台商家(「绑定商家」LoadMyAgentList)列表。 + * @param {Object} [options] 查询参数 + * @param {number} [options.pageIndex] 页码,从 1 开始 + * @param {number} [options.pageSize] 每页条数(最大 200) + * @param {string} [options.keyword] 关键词(商家名称/手机号) + * @return {Promise<{total: number, list: Array}>} 统一的店铺列表 + */ + async listAgentShops(options = {}) { + if (!this.token || !this.cookie) { + throw new Error('账号未登录:缺少 token 或 cookie,请先登录'); + } + + const pageIndex = Math.max(1, Number.parseInt(options.pageIndex, 10) || 1); + const pageSize = Math.min(200, Math.max(1, Number.parseInt(options.pageSize, 10) || 20)); + const keyword = String(options.keyword || ''); + const { traceId, dbName } = await this.shopListContext(); const query = new URLSearchParams({ token: this.token, @@ -1335,6 +1383,110 @@ class DgjService extends PrintPlatformService { return { total: Number(data.Total) || list.length, list }; } + /** + * 拉取一页「我的店铺」(国内电商)列表 + * @param {Object} options 查询参数 + * @param {string} options.traceId 登录上下文 traceId + * @param {string} options.dbName 默认分区库名 + * @param {number} options.pageIndex 页码 + * @param {number} options.pageSize 每页条数 + * @param {string} [options.status] 授权状态:'' 全部 / '1' 授权成功 / '3' 授权过期 + * @param {string} [options.platformTypes] 平台过滤(逗号分隔) + * @return {Promise<{rows: Array, total: number}>} 当页原始结构 + */ + async fetchMyShopPage({ traceId, dbName, pageIndex, pageSize, status, platformTypes }) { + const query = new URLSearchParams({ + token: this.token, + traceId: traceId || '', + dbname: dbName || '', + dataFlag: '', + }); + const form = new URLSearchParams({ + '_reqModel[ShopId]': '0', + '_reqModel[ShopIds]': '', + '_reqModel[Status]': status || '0', + '_reqModel[PlatformTypes]': platformTypes || '', + '_reqModel[PageIndex]': String(pageIndex), + '_reqModel[PageSize]': String(pageSize), + '_reqModel[AuthTimeOrderBy]': '', + '_reqModel[IsWherQuery]': 'true', + IsCustomerOrder: 'false', + FxPageType: '1', + }); + + const headers = { + ...WORKBENCH_AJAX_HEADERS, + 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', + referer: `https://${WORKBENCH_HOST}/Partner/Index`, + }; + if (this.cookie) headers.cookie = this.cookie; + + const res = await this.request(`${MY_SHOP_LIST_URL}?${query.toString()}`, { + method: 'POST', + headers, + body: form.toString(), + }); + if (res.status === 401) { + throw new Error(`店管家登录已失效:${(res.json && res.json.Message) || 'token is invalid'}`); + } + if (!res.json || res.json.Success !== true) { + const reason = (res.json && (res.json.Message || res.json.ErrorCode)) || `HTTP ${res.status}`; + throw new Error(`拉取店管家店铺列表失败:${reason}`); + } + + const data = res.json.Data || {}; + const rows = Array.isArray(data.List) ? data.List : []; + return { rows, total: Number(data.Total) || rows.length }; + } + + /** + * 「我的店铺」(国内电商,LoadMyShopList)列表。 + * + * 该接口不支持关键词搜索,带 keyword 时先翻完(封顶 MY_SHOP_MAX_PAGES 页)再按名称过滤, + * 保证 total 与分页一致;不带 keyword 时按平台分页直取。 + * @param {Object} [options] 查询参数 + * @param {number} [options.pageIndex] 页码,从 1 开始 + * @param {number} [options.pageSize] 每页条数(最大 200) + * @param {string} [options.keyword] 店铺名称关键词 + * @param {string} [options.status] 授权状态('' 全部 / '1' 授权成功 / '3' 授权过期) + * @param {string|string[]} [options.platformTypes] 平台过滤 + * @return {Promise<{total: number, list: Array}>} 统一的店铺列表 + */ + async listMyShops(options = {}) { + if (!this.token || !this.cookie) { + throw new Error('账号未登录:缺少 token 或 cookie,请先登录'); + } + + const pageIndex = Math.max(1, Number.parseInt(options.pageIndex, 10) || 1); + const pageSize = Math.min(200, Math.max(1, Number.parseInt(options.pageSize, 10) || 20)); + const keyword = String(options.keyword || '').trim().toLowerCase(); + const status = String(options.status == null ? '' : options.status).trim(); + const platformTypes = Array.isArray(options.platformTypes) + ? options.platformTypes.join(',') + : String(options.platformTypes || ''); + const { traceId, dbName } = await this.shopListContext(); + + const base = { traceId, dbName, pageSize: 200, status, platformTypes }; + + if (!keyword) { + const page = await this.fetchMyShopPage({ ...base, pageIndex, pageSize }); + return { total: page.total, list: page.rows.map(item => this.normalizeMyShop(item)) }; + } + + const all = []; + for (let index = 1; index <= MY_SHOP_MAX_PAGES; index++) { + const page = await this.fetchMyShopPage({ ...base, pageIndex: index }); + all.push(...page.rows); + if (!page.rows.length || all.length >= page.total) break; + } + const matched = all.filter(item => this.normalizeMyShop(item).name.toLowerCase().includes(keyword)); + const offset = (pageIndex - 1) * pageSize; + return { + total: matched.length, + list: matched.slice(offset, offset + pageSize).map(item => this.normalizeMyShop(item)), + }; + } + /** * 把店管家商家结构转换为统一的店铺结构(其他平台按同样结构返回即可) * @param {Object} item 店管家商家原始结构 @@ -1343,16 +1495,92 @@ class DgjService extends PrintPlatformService { normalizeShop(item) { const data = item || {}; return { + source: 'agent', external_id: String(data.Id == null ? '' : data.Id), name: data.Remark || data.UserName || data.NickName || data.RemarkName || '', contact_name: data.SenderName || data.Remark || '', contact_phone: data.SenderMobile || data.Mobile || '', status: Number(data.Status) === 0 ? 0 : 1, + status_label: Number(data.Status) === 0 ? '停用' : '正常', remark: data.RemarkName || '', raw: data, }; } + /** + * 把「我的店铺」结构转换为统一的店铺结构。 + * + * Status:1 授权成功、3 授权过期(页面「授权状态」下拉同口径); + * IsExpire 是服务到期提醒,不影响 Status,单独透出给前端展示。 + * @param {Object} item 店管家「我的店铺」原始结构 + * @return {Object} 统一店铺结构 + */ + normalizeMyShop(item) { + const data = item || {}; + const status = Number(data.Status); + const authExpired = status === 3 || data.IsAuthExpired === true; + const serviceExpired = data.IsExpire === true; + const platform = resolveOrderPlatform(data.PlatformType); + const label = authExpired ? '授权过期' : (serviceExpired ? '服务到期' : '正常'); + return { + source: 'my_shop', + external_id: String(data.ShopId == null ? '' : data.ShopId), + name: String(data.ShopNameRemark || data.NickName || '').trim(), + contact_name: data.FxUserName || '', + contact_phone: data.FxUserMobile || '', + status: authExpired ? 0 : 1, + status_label: label, + platform_code: platform.code, + platform_name: String(data.PlatformTypeName || platform.name || ''), + platform_type: String(data.PlatformType || ''), + auth_expired: authExpired, + service_expired: serviceExpired, + auth_time: data.AuthTime || null, + remark: data.Remark || '', + raw: data, + }; + } + + /** + * 店铺在店管家侧的作用域(上层拉单/拉商品/刷新分区按它取数) + * @param {Object} shop OMS 店铺记录(type=2) + * @return {{source: string, externalId: string, shopId: string, platformType: string, hosts: string[]}} 店铺作用域 + */ + resolveShopScope(shop) { + const data = (shop && shop.external_data) || {}; + const source = String((shop && shop.external_source) || 'agent'); + if (source === 'my_shop') { + const platformType = String(data.PlatformType || ''); + const host = this.resolveMyShopHost(platformType); + return { + source, + externalId: String(data.ShopId == null ? '' : data.ShopId), + shopId: String(data.ShopId == null ? '' : data.ShopId), + platformType, + hosts: host ? [ host ] : [], + }; + } + return { + source: 'agent', + externalId: String(data.Id == null ? '' : data.Id), + shopId: data.ShopId == null ? '' : String(data.ShopId), + platformType: '', + hosts: this.resolveProductHosts(data), + }; + } + + /** + * 「我的店铺」没有分区声明,按平台类型推导订单/商品接口域名。 + * 淘宝/快手/视频号/小红书/1688 都在 fxali(见 ORDER_HOSTS 注释),抖店/拼多多/京东各走自己的域名。 + * @param {string} platformType 店管家 PlatformType(如 TouTiao / Pinduoduo) + * @return {string} 接口域名 + */ + resolveMyShopHost(platformType) { + const key = String(platformType == null ? '' : platformType).trim().toLowerCase(); + if (!key) return ORDER_HOST_FALLBACK; + return ORDER_HOSTS[key] || ORDER_HOST_FALLBACK; + } + /** * 根据商家的分区信息确定要查询的商品域名。 * 商家在店管家的 DbAreas 里记录了所在分区(抖店/拼多多/精选/京东), @@ -1990,6 +2218,11 @@ class DgjService extends PrintPlatformService { if (!this.token || !this.cookie) { throw new Error('账号未登录:缺少 token 或 cookie,请先登录'); } + // 「我的店铺」是自营店:商品要按 SelectShopId 过滤,不能沿用商家的 FxUserId(那是账号自己, + // 会把本账号上游的其它商品/订单拉进来)。接入前先明确拒绝,避免写脏数据 + if (String((shop && shop.external_source) || 'agent') === 'my_shop') { + throw new Error('「我的店铺」暂未支持同步商品(需按店铺ID拉取,下一步接入)'); + } const data = (shop && shop.external_data) || {}; const agentId = String(data.FxUserId || '').trim(); @@ -2137,6 +2370,11 @@ class DgjService extends PrintPlatformService { if (!this.token || !this.cookie) { throw new Error('账号未登录:缺少 token 或 cookie,请先登录'); } + // 「我的店铺」的订单归属键是 LogicOrder.ShopId,不是商家的 FxUserId(自营店的 FxUserId 是账号自己, + // 按它过滤会把本账号上游的其它订单当成该店铺的单)。接入前先明确拒绝,避免写脏数据 + if (String((shop && shop.external_source) || 'agent') === 'my_shop') { + throw new Error('「我的店铺」暂未支持拉取订单(需按店铺ID拉取,下一步接入)'); + } const data = (shop && shop.external_data) || {}; const merchantFxUserId = String(data.FxUserId || '').trim(); diff --git a/backend/app/model/shop.js b/backend/app/model/shop.js index 1d6fd87..402afdc 100644 --- a/backend/app/model/shop.js +++ b/backend/app/model/shop.js @@ -21,7 +21,8 @@ module.exports = app => { status: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' }, type: { type: TINYINT, allowNull: false, defaultValue: 1, comment: '店铺类型:1平台店铺 2外部打单平台商家 3数据库模式(预留)' }, external_print_account_id: { type: BIGINT.UNSIGNED, comment: '来源外部打单账号ID(type=2 时有值)' }, - external_data: { type: JSON, comment: '外部打单平台返回的商家原始结构' }, + external_source: { type: STRING(20), allowNull: false, defaultValue: 'agent', comment: '外部打单平台店铺来源(平台自定义,如 agent/my_shop)' }, + external_data: { type: JSON, comment: '外部打单平台返回的店铺/商家原始结构' }, db_host: { type: STRING(255), comment: '数据库地址(type=3 数据库模式店铺使用,预留)' }, db_port: { type: INTEGER, comment: '数据库端口(type=3 数据库模式店铺使用,预留)' }, db_name: { type: STRING(100), comment: '数据库名(type=3 数据库模式店铺使用,预留)' }, diff --git a/backend/app/router.js b/backend/app/router.js index c18d29b..60f75b2 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -182,7 +182,9 @@ module.exports = app => { // 账号登录态检查 / 登录(需在 resources 之前注册,避免被 /:id 误匹配) router.post('/api/external-print-accounts/:id/check', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.check); router.post('/api/external-print-accounts/:id/login', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.login); - // 平台侧店铺(商家)列表与创建到 OMS 店铺(前端按账号ID调用,后端按平台服务分发) + // 平台侧店铺来源(如店管家的平台商家 / 我的店铺)与店铺列表、创建到 OMS 店铺 + // 前端按账号ID调用,后端按平台服务分发,接口对平台无关 + router.get('/api/external-print-accounts/:id/shop-sources', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.shopSources); router.get('/api/external-print-accounts/:id/merchants', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.merchants); router.post('/api/external-print-accounts/:id/shops', jwtAuth, principalCheck({ model: 'ExternalPrintAccount' }), groupScope(), controller.externalPrintAccount.createShops); // 刷新账号下店铺「所在区」:一次拉取账号全部商家(同账号多店铺共享),商家已解绑的店铺自动禁用 diff --git a/backend/app/service/shopAreaSync.js b/backend/app/service/shopAreaSync.js index bb20a3f..a5d5c47 100644 --- a/backend/app/service/shopAreaSync.js +++ b/backend/app/service/shopAreaSync.js @@ -48,8 +48,13 @@ class ShopAreaSyncService extends Service { if (externalId) merchantMap.set(externalId, item); } + // 只刷新默认来源(店管家为 agent 平台商家)的店铺: + // 其它来源(如「我的店铺」)没有商家分区声明,按商家列表匹配会把它们误判成「已解绑」而自动禁用 + const sources = typeof platformService.listShopSources === 'function' ? platformService.listShopSources() : []; + const defaultSource = (sources[0] && sources[0].code) || 'agent'; + const shops = await ctx.model.Shop.findAll({ - where: { external_print_account_id: account.id, type: SHOP_TYPE_EXTERNAL }, + where: { external_print_account_id: account.id, type: SHOP_TYPE_EXTERNAL, external_source: defaultSource }, order: [[ 'id', 'ASC' ]], }); diff --git a/backend/database/migrations/20261109110000-add-external-source-to-shops.js b/backend/database/migrations/20261109110000-add-external-source-to-shops.js new file mode 100644 index 0000000..cd9f36f --- /dev/null +++ b/backend/database/migrations/20261109110000-add-external-source-to-shops.js @@ -0,0 +1,32 @@ +'use strict'; + +/** + * 店铺表扩展:外部打单平台店铺的「来源」。 + * + * 同一个打单账号下可能有两种来源的店铺: + * - agent:平台侧的商家/合作方(如店管家的「绑定商家」LoadMyAgentList),订单按商家归属过滤 + * - my_shop:账号自己绑定的平台店铺(如店管家的「我的店铺」LoadMyShopList),订单按店铺ID过滤 + * + * 该字段由各平台实现自行解释(取值来自 PrintPlatformService.listShopSources()), + * 通用层只当作字符串使用,用于区分同一账号下两类店铺的编码、归属与同步口径。 + * 老数据(都是商家来源)统一回填为 agent,行为不变。 + */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('shops', 'external_source', { + type: Sequelize.STRING(20), + allowNull: false, + defaultValue: 'agent', + comment: '外部打单平台店铺来源(平台自定义,如 agent/my_shop)', + }); + await queryInterface.addIndex('shops', { + fields: [ 'external_print_account_id', 'external_source' ], + name: 'idx_shops_external_account_source', + }); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('shops', 'idx_shops_external_account_source'); + await queryInterface.removeColumn('shops', 'external_source'); + }, +}; diff --git a/backend/test/app/lib/dgjMyShopList.test.js b/backend/test/app/lib/dgjMyShopList.test.js new file mode 100644 index 0000000..d0318c8 --- /dev/null +++ b/backend/test/app/lib/dgjMyShopList.test.js @@ -0,0 +1,139 @@ +'use strict'; + +const { assert } = require('egg-mock/bootstrap'); +const DgjService = require('../../../app/lib/printPlatform/dgj'); + +/** + * 构造一个只用于纯函数校验的店管家服务实例(不会发请求) + * @return {DgjService} 服务实例 + */ +function createService() { + return new DgjService({ + platform: { code: 'dgj', name: '店管家', url: 'fxali.dgjapp.com' }, + account: { token: 'token', cookie: 'cookie' }, + }); +} + +describe('printPlatform/dgj listShopSources', () => { + it('默认来源为平台商家,且包含我的店铺', () => { + const sources = createService().listShopSources(); + assert.deepStrictEqual(sources.map(item => item.code), [ 'agent', 'my_shop' ]); + assert.strictEqual(sources[0].name, '平台商家'); + }); +}); + +describe('printPlatform/dgj normalizeMyShop', () => { + const service = createService(); + + it('授权成功:启用、平台编码映射到系统预设', () => { + const item = service.normalizeMyShop({ + ShopId: 12345897, + ShopNameRemark: 'Moocola个人护理旗舰店', + NickName: 'Moocola', + PlatformType: 'TouTiao', + PlatformTypeName: '抖店', + Status: 1, + IsExpire: false, + IsAuthExpired: false, + AuthTime: '2026-12-07 21:23:16', + }); + assert.strictEqual(item.source, 'my_shop'); + assert.strictEqual(item.external_id, '12345897'); + assert.strictEqual(item.name, 'Moocola个人护理旗舰店'); + assert.strictEqual(item.status, 1); + assert.strictEqual(item.status_label, '正常'); + assert.strictEqual(item.platform_code, 'DYXD'); + assert.strictEqual(item.platform_name, '抖店'); + assert.strictEqual(item.platform_type, 'TouTiao'); + assert.strictEqual(item.auth_expired, false); + assert.strictEqual(item.service_expired, false); + assert.strictEqual(item.auth_time, '2026-12-07 21:23:16'); + }); + + it('授权过期(Status=3):禁用并给出「授权过期」', () => { + const item = service.normalizeMyShop({ ShopId: 1, ShopNameRemark: '过期店', PlatformType: 'KuaiShou', Status: 3, IsAuthExpired: true }); + assert.strictEqual(item.status, 0); + assert.strictEqual(item.status_label, '授权过期'); + assert.strictEqual(item.auth_expired, true); + assert.strictEqual(item.platform_code, 'KS'); + }); + + it('服务到期但授权仍有效:保持启用,文案为「服务到期」', () => { + const item = service.normalizeMyShop({ ShopId: 2, ShopNameRemark: '临期店', PlatformType: 'XiaoHongShu', Status: 1, IsExpire: true }); + assert.strictEqual(item.status, 1); + assert.strictEqual(item.status_label, '服务到期'); + assert.strictEqual(item.service_expired, true); + assert.strictEqual(item.platform_code, 'XHS'); + }); + + it('线下单映射到线下,名称缺失时兜底为空串', () => { + const item = service.normalizeMyShop({ ShopId: 3, PlatformType: 'Virtual', Status: 1 }); + assert.strictEqual(item.platform_code, 'OFFLINE'); + assert.strictEqual(item.name, ''); + }); +}); + +describe('printPlatform/dgj resolveShopScope', () => { + const service = createService(); + + it('我的店铺:按 ShopId 定位,域名由 PlatformType 推导', () => { + const scope = service.resolveShopScope({ + code: 'dgj-1-my_shop-12345897', + external_source: 'my_shop', + external_data: { ShopId: 12345897, PlatformType: 'TouTiao' }, + }); + assert.deepStrictEqual(scope, { + source: 'my_shop', + externalId: '12345897', + shopId: '12345897', + platformType: 'TouTiao', + hosts: [ 'fxdd.dgjapp.com' ], + }); + }); + + it('平台商家:按商家 Id 定位,域名由分区声明推导', () => { + const scope = service.resolveShopScope({ + code: 'dgj-1-7251148', + external_source: 'agent', + external_data: { Id: 7251148, FxUserId: 953516, DbAreas: [{ DbName: 'alibaba' }] }, + }); + assert.strictEqual(scope.source, 'agent'); + assert.strictEqual(scope.externalId, '7251148'); + assert.deepStrictEqual(scope.hosts, [ 'fxali.dgjapp.com' ]); + }); + + it('来源缺省时按平台商家处理(兼容老数据)', () => { + const scope = service.resolveShopScope({ code: 'dgj-1-100', external_data: { Id: 100 } }); + assert.strictEqual(scope.source, 'agent'); + assert.strictEqual(scope.externalId, '100'); + }); +}); + +describe('printPlatform/dgj 我的店铺暂不支持拉单/拉商品', () => { + const service = createService(); + const shop = { external_source: 'my_shop', external_data: { ShopId: 12345897, FxUserId: 1227061, PlatformType: 'TouTiao' } }; + + it('listOrders 明确拒绝,避免按账号 FxUserId 拉到别人的订单', async () => { + await assert.rejects(() => service.listOrders(shop, {}), /暂未支持拉取订单/); + }); + + it('listProducts 明确拒绝,避免按账号 FxUserId 拉到别人的商品', async () => { + await assert.rejects(() => service.listProducts(shop), /暂未支持同步商品/); + }); +}); + +describe('printPlatform/dgj resolveMyShopHost', () => { + const service = createService(); + + it('按平台类型映射到订单/商品接口域名', () => { + assert.strictEqual(service.resolveMyShopHost('TouTiao'), 'fxdd.dgjapp.com'); + assert.strictEqual(service.resolveMyShopHost('Pinduoduo'), 'fxpdd.dgjapp.com'); + assert.strictEqual(service.resolveMyShopHost('Jingdong'), 'fxjd.dgjapp.com'); + assert.strictEqual(service.resolveMyShopHost('Taobao'), 'fxali.dgjapp.com'); + assert.strictEqual(service.resolveMyShopHost('KuaiShou'), 'fxali.dgjapp.com'); + assert.strictEqual(service.resolveMyShopHost('WxVideo'), 'fxali.dgjapp.com'); + assert.strictEqual(service.resolveMyShopHost('XiaoHongShu'), 'fxali.dgjapp.com'); + assert.strictEqual(service.resolveMyShopHost('Virtual'), 'fxali.dgjapp.com'); + assert.strictEqual(service.resolveMyShopHost(''), 'fxali.dgjapp.com'); + }); +}); diff --git a/frontend/src/api/externalPrintAccount.ts b/frontend/src/api/externalPrintAccount.ts index 02039a2..9732611 100644 --- a/frontend/src/api/externalPrintAccount.ts +++ b/frontend/src/api/externalPrintAccount.ts @@ -76,14 +76,41 @@ export function loginExternalPrintAccount(id: number) { ) } -/** 平台侧店铺(商家)列表项:统一结构,不直接依赖具体平台字段 */ +/** 平台支持的店铺来源(第一个为默认来源) */ +export interface ExternalPrintShopSource { + code: string + name: string +} + +/** 拉取账号所属打单平台支持的店铺来源(如店管家:平台商家 / 我的店铺) */ +export function getExternalPrintShopSources(id: number) { + return get<{ list: ExternalPrintShopSource[] }>(`/external-print-accounts/${id}/shop-sources`) +} + +/** 平台侧店铺列表项:统一结构,不直接依赖具体平台字段 */ export interface ExternalPrintMerchantItem { + /** 店铺来源(agent / my_shop) */ + source?: string external_id: string name: string contact_name?: string contact_phone?: string - /** 1 正常 0 停用 */ + /** 1 正常 0 停用或授权过期 */ status: number + /** 状态文案:正常 / 停用 / 授权过期 / 服务到期 */ + status_label?: string + /** 电商平台编码(系统预设,如 DYXD / PDD / TB) */ + platform_code?: string + /** 电商平台名称(如「抖店」) */ + platform_name?: string + /** 平台原始标识(如 TouTiao) */ + platform_type?: string + /** 平台授权是否过期 */ + auth_expired?: boolean + /** 服务是否到期 */ + service_expired?: boolean + /** 服务到期时间 */ + auth_time?: string | null remark?: string /** 是否已创建到 OMS 店铺 */ added?: boolean @@ -91,12 +118,15 @@ export interface ExternalPrintMerchantItem { raw?: unknown } -/** 拉取账号在外部打单平台的店铺(商家)列表(后端按平台分发,不直连平台) */ +/** 拉取账号在外部打单平台的店铺列表(后端按平台与来源分发,不直连平台) */ export function getExternalPrintMerchants(id: number, params?: object) { - return get<{ list: ExternalPrintMerchantItem[]; total: number; page: number; pageSize: number }>( - `/external-print-accounts/${id}/merchants`, - params, - ) + return get<{ + list: ExternalPrintMerchantItem[] + total: number + page: number + pageSize: number + source?: string + }>(`/external-print-accounts/${id}/merchants`, params) } /** 刷新账号下店铺的「所在区」:一次拉取账号全部商家,商家已解绑的店铺自动禁用 */ @@ -185,11 +215,16 @@ export function syncExternalPrintShopOrders( ) } -/** 把选中的平台店铺(商家)创建到 OMS 店铺:需指定所属货主(下属公司) */ -export function createShopsFromMerchants(id: number, merchants: ExternalPrintMerchantItem[], subsidiaryId: number) { +/** 把选中的平台店铺创建到 OMS 店铺:需指定所属货主(下属公司) */ +export function createShopsFromMerchants( + id: number, + merchants: ExternalPrintMerchantItem[], + subsidiaryId: number, + source?: string, +) { return post<{ created: number; skipped: number; shops: Array<{ id: number; code: string; name: string }> }>( `/external-print-accounts/${id}/shops`, - { merchants, subsidiary_id: subsidiaryId }, + { merchants, subsidiary_id: subsidiaryId, source }, { timeout: 60000 }, ) } diff --git a/frontend/src/views/ExternalPrintPlatform/Index.vue b/frontend/src/views/ExternalPrintPlatform/Index.vue index c30b340..d6d0c7c 100644 --- a/frontend/src/views/ExternalPrintPlatform/Index.vue +++ b/frontend/src/views/ExternalPrintPlatform/Index.vue @@ -13,11 +13,13 @@ import { checkExternalPrintAccount, loginExternalPrintAccount, getExternalPrintMerchants, + getExternalPrintShopSources, refreshExternalPrintShopsArea, createShopsFromMerchants, type ExternalPrintAccountItem, type ExternalPrintAccountPayload, type ExternalPrintMerchantItem, + type ExternalPrintShopSource, } from '@/api/externalPrintAccount' import DataTable from '@/components/DataTable.vue' import ListPager from '@/components/ListPager.vue' @@ -237,7 +239,9 @@ async function fetchSubsidiaryOptions() { } } const merchantTotal = ref(0) -const merchantQuery = reactive({ page: 1, pageSize: 20, keyword: '' }) +/** 店铺来源(由后端平台实现返回,如店管家的平台商家 / 我的店铺) */ +const shopSources = ref([]) +const merchantQuery = reactive({ page: 1, pageSize: 20, keyword: '', source: '' }) const selectedMerchants = ref([]) const addingShops = ref(false) @@ -256,9 +260,11 @@ async function fetchMerchants() { page: merchantQuery.page, pageSize: merchantQuery.pageSize, keyword: merchantQuery.keyword || undefined, + source: merchantQuery.source || undefined, }) merchantList.value = res.list || [] merchantTotal.value = res.total || 0 + if (res.source) merchantQuery.source = res.source selectedMerchants.value = [] } catch { merchantList.value = [] @@ -268,14 +274,38 @@ async function fetchMerchants() { } } +/** 拉取账号所属平台支持的店铺来源(失败时退回单一来源,不影响原有商家列表) */ +async function fetchShopSources(accountId: number) { + try { + const res = await getExternalPrintShopSources(accountId) + shopSources.value = res.list || [] + } catch { + shopSources.value = [] + } +} + function openMerchants(row: ExternalPrintAccountItem) { shopsAccount.value = row merchantQuery.page = 1 merchantQuery.pageSize = 20 merchantQuery.keyword = '' + merchantQuery.source = '' selectedMerchants.value = [] syncMerchantTableHeight() shopsDialogVisible.value = true + fetchShopSources(row.id).then(() => { + if (!merchantQuery.source && shopSources.value.length) { + merchantQuery.source = shopSources.value[0].code + } + fetchMerchants() + }) +} + +/** 切换店铺来源:重置分页与已选 */ +function changeShopSource(code: string) { + merchantQuery.source = code + merchantQuery.page = 1 + selectedMerchants.value = [] fetchMerchants() } @@ -315,6 +345,7 @@ async function handleAddShops() { shopsAccount.value.id, selectedMerchants.value, Number(merchantSubsidiaryId.value), + merchantQuery.source || undefined, ) const extra = res.skipped ? `,跳过 ${res.skipped} 个(已添加或无效)` : '' ElMessage.success(`已添加 ${res.created} 个店铺${extra}`) @@ -499,11 +530,22 @@ onBeforeUnmount(() => { width="920px" top="6vh" > + + + {{ item.name }} + + + @@ -521,14 +563,22 @@ onBeforeUnmount(() => { @selection-change="handleMerchantSelection" > - - - - + + + + + + + + + +