'use strict'; const Service = require('egg').Service; /** 单页拉取的商家数量(店管家商家列表上限 200) */ const MERCHANT_PAGE_SIZE = 200; /** 最多翻页次数:防止平台返回异常总数时死循环 */ const MAX_MERCHANT_PAGES = 50; /** 店铺类型:外部打单平台商家 */ const SHOP_TYPE_EXTERNAL = 2; /** 平台登录态失效的报错特征(各分区接口统一返回「登录信息过期」/token is invalid) */ const SESSION_EXPIRED_RE = /登录信息过期|登录已失效|token is invalid|未登录|缺少 token/i; /** 商家已不在合作列表时写入店铺 extra 的原因(前端据此提示) */ const AUTO_DISABLED_REASON = '店铺已不在打单平台合作列表(可能已解绑或停用),系统已自动禁用'; /** * 店铺「所在区」同步服务 * * 店管家把每个商家挂在若干个分区(`DbAreas[]`,页面上叫「所在区」)下,拉单要靠这份声明 * 决定查哪些分区库。商家可能被平台迁移分区或解绑,声明过期会让拉单漏单/报错,因此需要定期刷新: * 1. 同一账号下所有店铺共享一份商家列表,一次拉取只请求平台一次(定时任务里按账号去重); * 2. 拉到的商家原样写回 shops.external_data(FxUserId、DbAreas 等拉单必需字段); * 3. 商家已不在合作列表(解绑/删除/停用)时把店铺自动禁用,之后自动拉单与一键拉单都会跳过 * (两条链路都只取 status=1 的店铺),需人工把状态改回启用才会恢复。 */ class ShopAreaSyncService extends Service { /** * 刷新某账号下全部店铺的「所在区」等信息 * @param {Object} account 账号实例(需 include platform) * @param {Object} [options] 选项 * @param {boolean} [options.disableMissing] 商家已不在合作列表时是否自动禁用店铺(默认 true) * @return {Promise} 刷新结果统计 */ async refreshAccount(account, options = {}) { const { ctx } = this; const disableMissing = options.disableMissing !== false; const platformService = ctx.service.externalPrintOrder.createPlatformService(account); const merchants = await this.fetchMerchants(platformService); const merchantMap = new Map(); for (const item of merchants) { const externalId = String((item && item.external_id) || '').trim(); if (externalId) merchantMap.set(externalId, item); } const shops = await ctx.model.Shop.findAll({ where: { external_print_account_id: account.id, type: SHOP_TYPE_EXTERNAL }, order: [[ 'id', 'ASC' ]], }); const now = new Date(); const result = { account_id: Number(account.id), merchants: merchants.length, shops: shops.length, updated: 0, disabled: [], missing: [], restored: [], // 平台重新授权/换绑后商家ID会变(店铺存的 external_data.Id 失效),按名称唯一命中时自动重新绑定 rebound: [], voided: 0, }; // 第一轮:按商家ID精确绑定(平台没变的情况) const pending = []; const usedIds = new Set(); for (const shop of shops) { const externalId = this.resolveExternalId(shop); const merchant = externalId ? merchantMap.get(externalId) : null; if (merchant) { usedIds.add(externalId); await this.applyMerchant(shop, merchant, now, result); } else { pending.push(shop); } } // 第二轮:ID 失效的店铺按名称唯一匹配重新绑定,避免「商家明明还在、只是换了ID」被当成已解绑 for (const shop of pending) { const merchant = this.matchMerchantByName(shop, merchants, usedIds); if (merchant) { const externalId = String(merchant.external_id || ''); usedIds.add(externalId); await this.applyMerchant(shop, merchant, now, result); result.rebound.push({ id: Number(shop.id), code: shop.code, name: shop.name, external_id: externalId }); continue; } await this.markMissing(shop, now, { disableMissing, result }); } if (result.rebound.length) { ctx.logger.warn( '[shopAreaSync] 账号 %s 有 %d 个店铺的商家ID已变化,已按名称重新绑定:%s', account.id, result.rebound.length, result.rebound.map(item => `${item.id}(${item.name}) → 商家 ${item.external_id}`).join('、') ); } if (result.disabled.length) { ctx.logger.warn( '[shopAreaSync] 账号 %s 有 %d 个店铺已不在平台合作列表,自动禁用:%s', account.id, result.disabled.length, result.disabled.map(item => `${item.id}(${item.name})`).join('、') ); } if (result.restored.length) { ctx.logger.info( '[shopAreaSync] 账号 %s 有 %d 个店铺重新出现在平台合作列表(保持禁用,等待人工启用):%s', account.id, result.restored.length, result.restored.map(item => `${item.id}(${item.name})`).join('、') ); } return result; } /** * 拉取账号下全部商家(分页汇总) * @param {Object} platformService 平台服务实例 * @return {Promise} 商家列表(统一结构) */ async fetchMerchants(platformService) { try { return await this.pullAllMerchants(platformService); } catch (err) { // 会话过期时重新登录一次再拉,避免定时任务因为登录态失效整天刷不到分区 const expired = SESSION_EXPIRED_RE.test(String((err && err.message) || '')); if (!expired || typeof platformService.loginByPassword !== 'function') throw err; this.ctx.logger.warn('[shopAreaSync] 刷新店铺所在区时登录态失效,重新登录后重试:%s', err.message); await platformService.loginByPassword(); return await this.pullAllMerchants(platformService); } } /** * 逐页拉取商家列表 * @param {Object} platformService 平台服务实例 * @return {Promise} 商家列表 */ async pullAllMerchants(platformService) { const all = []; for (let pageIndex = 1; pageIndex <= MAX_MERCHANT_PAGES; pageIndex++) { const page = await platformService.listShops({ pageIndex, pageSize: MERCHANT_PAGE_SIZE }); const list = Array.isArray(page && page.list) ? page.list : []; all.push(...list); const total = Number(page && page.total) || all.length; if (!list.length || all.length >= total) break; } return all; } /** * 按店铺名称唯一匹配平台商家(ID 失效时的补救) * * 平台重新授权/换绑后商家ID会变,但商家名称通常不变(如「13668975305(意洁)」)。 * 只有在「名称包含店铺名」的候选**唯一**、且该商家还没被别的店铺占用时才返回, * 避免同名多商家时绑错。 * @param {Object} shop 店铺实例 * @param {Array} merchants 平台商家列表 * @param {Set} usedIds 已被其它店铺占用的商家ID * @return {Object|null} 命中的商家 */ matchMerchantByName(shop, merchants, usedIds) { const name = String((shop && shop.name) || '').trim(); if (!name) return null; const candidates = (merchants || []).filter(item => { const externalId = String((item && item.external_id) || '').trim(); if (!externalId || (usedIds && usedIds.has(externalId))) return false; const raw = (item && item.raw) || {}; // 平台把商家名放在不同字段里(NickName 常是账号手机号),逐个字段比,别被第一个非空值挡住 const names = [ raw.ShopName, raw.AgentShopName, raw.SelfShopName, raw.Name, raw.NickName, item && item.name, ] .map(value => String(value == null ? '' : value).trim()) .filter(Boolean); return names.some(value => value === name || value.includes(name)); }); if (candidates.length !== 1) return null; return candidates[0]; } /** * 店铺在平台的商家ID:优先取 external_data.Id,缺失时按编码(平台-账号-商家ID)兜底解析 * @param {Object} shop 店铺实例 * @return {string} 商家ID,取不到返回空串 */ resolveExternalId(shop) { const data = shop.external_data || {}; if (data.Id != null && data.Id !== '') return String(data.Id); const code = String(shop.code || ''); const index = code.lastIndexOf('-'); return index >= 0 ? code.slice(index + 1) : ''; } /** * 商家仍在合作列表:写回最新商家结构(含分区声明),并清掉「已解绑」标记 * @param {Object} shop 店铺实例 * @param {Object} merchant 平台商家(统一结构,raw 为原始结构) * @param {Date} now 本次刷新时间 * @param {Object} result 累计统计 * @return {Promise} 无返回值 */ async applyMerchant(shop, merchant, now, result) { const nextExternalData = merchant.raw || merchant; const changed = JSON.stringify(shop.external_data || {}) !== JSON.stringify(nextExternalData); const extra = { ...(shop.extra || {}) }; if (changed) shop.external_data = nextExternalData; extra.area_synced_at = now; if (extra.area_missing) delete extra.area_missing; if (extra.auto_disabled) { // 商家回到合作列表:只记录提示,是否启用由人工决定(自动启用可能与人工停用的意图冲突) delete extra.auto_disabled; extra.area_restored_at = now; if (Number(shop.status) !== 1) { shop.last_order_sync_msg = '店铺已重新出现在打单平台合作列表,可手动启用后继续拉单'; } result.restored.push({ id: Number(shop.id), code: shop.code, name: shop.name }); } shop.extra = extra; await shop.save(); if (changed) result.updated++; } /** * 商家已不在合作列表:标记 + (启用中时)自动禁用 * @param {Object} shop 店铺实例 * @param {Date} now 本次刷新时间 * @param {Object} params 参数 * @param {boolean} params.disableMissing 是否自动禁用 * @param {Object} params.result 累计统计 * @return {Promise} 无返回值 */ async markMissing(shop, now, { disableMissing, result }) { const { ctx } = this; const extra = { ...(shop.extra || {}) }; const item = { id: Number(shop.id), code: shop.code, name: shop.name }; extra.area_synced_at = now; extra.area_missing = true; result.missing.push(item); const justDisabled = disableMissing && Number(shop.status) === 1; if (justDisabled) { shop.status = 0; extra.auto_disabled = { at: now, reason: AUTO_DISABLED_REASON }; } shop.extra = extra; await shop.save(); if (!justDisabled) return; // 禁用后无法取号:立即作废该店铺的待审核订单,避免继续审核/取号时报错(启用后自动恢复) let voided = 0; try { const guarded = await ctx.service.shopOrderGuard.voidPendingOrders(shop); voided = guarded.count; } catch (err) { ctx.logger.warn('[shopAreaSync] 店铺 %s 作废待审核订单失败:%s', shop.id, err.message); } result.voided += voided; result.disabled.push(item); await shop.update({ last_order_sync_msg: `${AUTO_DISABLED_REASON};改回启用后会继续拉单` + (voided ? `(已作废待审核订单 ${voided} 单,启用后自动恢复)` : ''), }); } /** * 账号下店铺最近一次刷新「所在区」的时间(同账号一次拉取会写全部店铺,取最大值) * @param {Array} shops 账号下的店铺实例 * @return {Date|null} 最近刷新时间 */ lastSyncedAt(shops) { let latest = null; for (const shop of shops) { const at = shop.extra && shop.extra.area_synced_at; if (!at) return null; const time = new Date(at).getTime(); if (Number.isNaN(time)) return null; if (!latest || time > latest.getTime()) latest = new Date(time); } return latest; } } module.exports = ShopAreaSyncService;