diff --git a/WMS-OMS-取号对接.md b/WMS-OMS-取号对接.md index ed08844..e5f2ddd 100644 --- a/WMS-OMS-取号对接.md +++ b/WMS-OMS-取号对接.md @@ -508,7 +508,7 @@ async oms(bizcontent = {}) { 3. **多包裹 / 拆单取号(已跑通)**:店管家用 `PrintMethod=NewPrint` + `IsIgnoreWaybillRepeat=false` 分配新号, 每次调用 pid 第二段自增(`63274907ebce8f6b_1_1` → `_2_1` → `_3_1`),实测连续 3 次均拿到不同运单号。 WMS 按包裹各调一次即可;多一次调用 = 多一张面单,重试必须复用 `request_id`。 - 详见 `店管家取号-旧系统提取.md` §4.2.1。 + 详见 `店管家取号-旧系统提取.md` §4.2.4。 4. **平台字典维护**:`external_print_platforms.fetch_waybill_no` 由迁移维护(当前 `dgj = 1`)。如需前端可配,另开需求。 5. **生产 app_key/callback_url**:需要与 WMS 对齐生产环境的 `warehouse_apis` 与 `api_app` 记录。 diff --git a/backend/app/contract/index.js b/backend/app/contract/index.js index 8536e74..74acd27 100644 --- a/backend/app/contract/index.js +++ b/backend/app/contract/index.js @@ -1200,6 +1200,26 @@ module.exports = { setShopDefaultWarehouseRequest: { default_warehouse_id: { type: 'integer', description: '默认发货仓库ID,须属于店铺货主且启用;传 null 清除设置' }, }, + shopAreaBrief: { + id: { type: 'integer', description: '店铺主键' }, + code: { type: 'string', description: '店铺编码' }, + name: { type: 'string', description: '店铺名称' }, + }, + shopAreaRefreshResult: { + account_id: { type: 'integer', description: '打单账号ID' }, + merchants: { type: 'integer', description: '平台返回的商家数量' }, + shops: { type: 'integer', description: '账号下本地店铺数量' }, + updated: { type: 'integer', description: '商家结构(含所在区)有变化并写回的店铺数' }, + disabled: { type: 'array', itemType: 'shopAreaBrief', description: '本次被自动禁用的店铺(商家已不在合作列表)' }, + voided: { type: 'integer', description: '因店铺禁用而作废的待审核订单数(店铺重新启用后自动恢复)' }, + missing: { type: 'array', itemType: 'shopAreaBrief', description: '平台商家列表里找不到的店铺' }, + restored: { type: 'array', itemType: 'shopAreaBrief', description: '重新出现在合作列表的店铺(保持禁用,需人工启用)' }, + }, + shopAreaRefreshResponse: { + code: { type: 'integer', description: '业务状态码,0 成功' }, + message: { type: 'string', description: '提示信息' }, + data: { type: 'shopAreaRefreshResult', description: '刷新结果' }, + }, // ---------- 数据库店铺配置 shop_database_configs ---------- /** 数据库店铺字段映射:OMS 字段 key → 源表列名 */ diff --git a/backend/app/controller/externalPrintAccount.js b/backend/app/controller/externalPrintAccount.js index 5ddc677..e39b716 100644 --- a/backend/app/controller/externalPrintAccount.js +++ b/backend/app/controller/externalPrintAccount.js @@ -374,6 +374,36 @@ class ExternalPrintAccountController extends Controller { } } + /** + * @summary 刷新账号下店铺的「所在区」 + * @description 一次拉取账号在平台的完整商家列表(同账号下多个店铺共享,只请求平台一次), + * 把最新的商家结构(FxUserId、分区声明 DbAreas 等)写回店铺; + * 商家已不在合作列表(解绑/停用)时把店铺自动禁用,之后不再参与自动拉单与一键拉单, + * 需人工把店铺状态改回启用才会恢复 + * @router post /api/external-print-accounts/{id}/refresh-shops-area + * @apikey + * @request path integer *id 账号主键ID + * @response 200 shopAreaRefreshResponse success + */ + async refreshShopAreas() { + 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 data = await ctx.service.shopAreaSync.refreshAccount(account); + ctx.body = { code: 0, message: 'success', data }; + } catch (err) { + ctx.status = 400; + ctx.body = { code: 400, message: err.message }; + } + } + /** * @summary 把外部打单平台的店铺(商家)创建到 OMS 店铺 * @description merchants 为商家列表接口返回的项(含 raw),按 external_id 去重;已存在的跳过 diff --git a/backend/app/controller/shop.js b/backend/app/controller/shop.js index 9f5abcd..f55f531 100644 --- a/backend/app/controller/shop.js +++ b/backend/app/controller/shop.js @@ -445,6 +445,9 @@ class ShopController extends Controller { delete ctx.request.body.principal_id; + // 状态变更前后的对比基准(禁用/启用会联动处理该店铺的待审核订单) + const previousStatus = Number(shop.status); + // 所在公司权限:仅可维护自己所属公司(货主)的店铺 if (!(await this.canAccess(ctx, shop))) { ctx.status = 403; @@ -576,13 +579,54 @@ class ShopController extends Controller { const applied = await ctx.service.shopWarehouse.applyToPendingOrders(shop, { previousWarehouseId }); pendingUpdated = applied.updated; } + // 状态变更联动:禁用后无法取号,待审核订单立即作废;重新启用后把因此暂停的订单恢复回待审核 + const statusChange = await this.applyStatusOrderGuard(ctx, shop, previousStatus); ctx.body = { code: 0, message: 'success', - data: { id: shop.id, code: shop.code, pending_orders_updated: pendingUpdated }, + data: { + id: shop.id, + code: shop.code, + pending_orders_updated: pendingUpdated, + pending_orders_voided: statusChange.voided, + pending_orders_restored: statusChange.restored, + }, }; } + /** + * 店铺状态(启用/禁用)变更时联动处理待审核订单 + * @param {Object} ctx egg context + * @param {Object} shop 店铺实例(已保存最新状态) + * @param {number} previousStatus 变更前状态 + * @return {Promise<{voided: number, restored: number}>} 作废 / 恢复的订单数 + */ + async applyStatusOrderGuard(ctx, shop, previousStatus) { + const status = Number(shop.status); + const result = { voided: 0, restored: 0 }; + if (status === previousStatus) return result; + + try { + if (status === 0) { + const guarded = await ctx.service.shopOrderGuard.voidPendingOrders(shop); + result.voided = guarded.count; + } else if (status === 1) { + const guarded = await ctx.service.shopOrderGuard.restorePendingOrders(shop); + result.restored = guarded.count; + // 人工改回启用:清掉系统自动禁用的标记,避免状态列一直提示「系统已自动禁用」 + if (shop.extra && shop.extra.auto_disabled) { + const extra = { ...shop.extra }; + delete extra.auto_disabled; + extra.area_restored_at = new Date(); + await shop.update({ extra }); + } + } + } catch (err) { + ctx.logger.warn('[shop] 店铺 %s 状态切换联动订单处理失败:%s', shop.id, err.message); + } + return result; + } + /** * @summary 设置店铺默认发货仓库 * @description 单独维护「默认发货仓库」(外部打单平台店铺所在的公司在只读模式下也可配置): @@ -641,6 +685,60 @@ class ShopController extends Controller { }; } + /** + * @summary 刷新店铺的「所在区」 + * @description 重新拉取店铺所属打单账号的商家列表(同账号下的店铺只请求平台一次), + * 更新分区声明等拉单必需字段;商家已不在合作列表时把店铺自动禁用 + * @router post /api/shops/{id}/refresh-area + * @apikey + * @request path integer *id 店铺主键ID + * @response 200 shopAreaRefreshResponse success + */ + async refreshArea() { + const { ctx } = this; + const shop = await ctx.model.Shop.findByPk(ctx.params.id); + if (!shop) { + ctx.status = 404; + ctx.body = { code: 404, message: '店铺不存在' }; + return; + } + // 所在公司权限:仅可刷新自己所属公司(货主)的店铺;集团权限不限 + if (!(await this.canAccess(ctx, shop))) { + ctx.status = 403; + ctx.body = { code: 403, message: '仅可刷新自己所属公司(货主)的店铺' }; + return; + } + if (Number(shop.type) !== SHOP_TYPE_EXTERNAL || !shop.external_print_account_id) { + ctx.status = 400; + ctx.body = { code: 400, message: '仅外部打单平台店铺支持刷新所在区' }; + return; + } + + const account = await ctx.model.ExternalPrintAccount.findOne({ + where: { id: shop.external_print_account_id, principal_id: shop.principal_id }, + include: [ + { + model: ctx.model.ExternalPrintPlatform, + as: 'platform', + attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ], + }, + ], + }); + if (!account) { + ctx.status = 404; + ctx.body = { code: 404, message: '店铺关联的打单账号不存在' }; + return; + } + + try { + const data = await ctx.service.shopAreaSync.refreshAccount(account); + ctx.body = { code: 0, message: 'success', data }; + } catch (err) { + ctx.status = 400; + ctx.body = { code: 400, message: err.message }; + } + } + /** * @summary 删除店铺 * @description 物理删除店铺,其下店铺商品会一并删除;存在订单引用时请先处理 diff --git a/backend/app/router.js b/backend/app/router.js index 0d08037..7a86935 100644 --- a/backend/app/router.js +++ b/backend/app/router.js @@ -162,6 +162,8 @@ module.exports = app => { router.post('/api/shops/:id/database-config/pull-orders', jwtAuth, principalCheck({ model: 'Shop' }), controller.shopDatabase.pullOrders); // 店铺默认发货仓库:单独维护(外部打单平台店铺的所在公司权限也可配置),需在 resources('shops') 之前注册 router.put('/api/shops/:id/default-warehouse', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop.setDefaultWarehouse); + // 刷新店铺「所在区」(重新拉取所属打单账号的商家列表,写回分区声明;商家已解绑则自动禁用店铺) + router.post('/api/shops/:id/refresh-area', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop.refreshArea); router.resources('shops', '/api/shops', jwtAuth, principalCheck({ model: 'Shop' }), controller.shop); // 店铺商品完全来自平台采集:不提供手工新增 / 编辑 / 删除,只保留查询与绑定; // 同步商品时平台已不存在的商品会自动移除 @@ -181,6 +183,8 @@ module.exports = app => { // 平台侧店铺(商家)列表与创建到 OMS 店铺(前端按账号ID调用,后端按平台服务分发) 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); + // 刷新账号下店铺「所在区」:一次拉取账号全部商家(同账号多店铺共享),商家已解绑的店铺自动禁用 + 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单独补拉(订单明细匹配不到店铺商品时使用,不做下架处理) diff --git a/backend/app/schedule/refreshExternalShopAreas.js b/backend/app/schedule/refreshExternalShopAreas.js new file mode 100644 index 0000000..585d5fb --- /dev/null +++ b/backend/app/schedule/refreshExternalShopAreas.js @@ -0,0 +1,105 @@ +'use strict'; + +/** + * 定时刷新外部打单平台店铺的「所在区」。 + * + * 店管家把商家挂在若干分区(`DbAreas[]`,页面上的「所在区」)下,平台迁移分区或解绑时这份声明会变, + * 声明过期会导致拉单漏单/报错,因此每小时检查一次,按账号维度刷新: + * - 同一账号下的店铺共享一次商家列表拉取(只请求平台一次); + * - 账号下最近一次刷新时间(shops.extra.area_synced_at)未超过间隔(默认 6 小时,可用 + * DGJ_AREA_REFRESH_HOURS 调整)时跳过; + * - 商家已不在合作列表(解绑/停用)时把店铺自动禁用,自动拉单与一键拉单都会跳过, + * 需人工把店铺状态改回启用才会恢复。 + */ +const AREA_REFRESH_INTERVAL_HOURS = Math.max(1, Number(process.env.DGJ_AREA_REFRESH_HOURS) || 6); + +/** 防止上一轮未结束时重复触发(单进程内串行) */ +let running = false; + +module.exports = { + schedule: { + cron: '0 37 * * * *', + type: 'worker', + disable: false, + }, + + async task(ctx) { + if (running) { + ctx.logger.info('[external-shop-area] 上一轮仍在执行,跳过本次'); + return { skipped: true }; + } + + running = true; + try { + const Op = ctx.app.Sequelize.Op; + // 主体停用后不再刷新 + const enabledPrincipalIds = await ctx.service.cache.getEnabledPrincipalIds(); + if (!enabledPrincipalIds.length) return { accounts: 0 }; + + const shops = await ctx.model.Shop.findAll({ + where: { + type: 2, + principal_id: { [Op.in]: enabledPrincipalIds }, + external_print_account_id: { [Op.ne]: null }, + }, + attributes: [ 'id', 'external_print_account_id', 'extra' ], + order: [[ 'id', 'ASC' ]], + }); + if (!shops.length) return { accounts: 0 }; + + // 同账号下的店铺共享一次拉取结果:按账号分组,再逐个账号判断是否到期 + const groups = new Map(); + for (const shop of shops) { + const accountId = Number(shop.external_print_account_id); + if (!groups.has(accountId)) groups.set(accountId, []); + groups.get(accountId).push(shop); + } + + const now = new Date(); + const intervalMs = AREA_REFRESH_INTERVAL_HOURS * 3600 * 1000; + const dueAccountIds = []; + for (const [ accountId, list ] of groups) { + const last = ctx.service.shopAreaSync.lastSyncedAt(list); + if (!last || now.getTime() - last.getTime() >= intervalMs) dueAccountIds.push(accountId); + } + if (!dueAccountIds.length) return { accounts: groups.size, refreshed: 0 }; + + const accounts = await ctx.model.ExternalPrintAccount.findAll({ + where: { id: { [Op.in]: dueAccountIds } }, + include: [ + { + model: ctx.model.ExternalPrintPlatform, + as: 'platform', + attributes: [ 'id', 'code', 'name', 'url', 'fetch_waybill_no' ], + }, + ], + }); + + let refreshed = 0; + let failed = 0; + let disabled = 0; + let voided = 0; + for (const account of accounts) { + try { + const result = await ctx.service.shopAreaSync.refreshAccount(account); + refreshed++; + disabled += result.disabled.length; + voided += result.voided; + ctx.logger.info( + `[external-shop-area] 账号 ${account.id} 刷新店铺所在区:商家 ${result.merchants},` + + `本地店铺 ${result.shops},更新 ${result.updated},自动禁用 ${result.disabled.length}` + + (result.voided ? `,作废待审核订单 ${result.voided}` : '') + + (result.missing.length ? `,已不在合作列表 ${result.missing.length}` : '') + ); + } catch (err) { + failed++; + ctx.logger.warn(`[external-shop-area] 账号 ${account.id} 刷新店铺所在区失败:${err.message}`); + } + } + + return { accounts: groups.size, refreshed, failed, disabled, voided }; + } finally { + running = false; + } + }, +}; diff --git a/backend/app/service/externalPrintOrder.js b/backend/app/service/externalPrintOrder.js index 3f7ba5c..e92f47a 100644 --- a/backend/app/service/externalPrintOrder.js +++ b/backend/app/service/externalPrintOrder.js @@ -66,6 +66,12 @@ function buildPlatformSnapshot(line, lineNo) { /** 平台「查不到」的最大回看天数:平台对久远订单返回不可靠,避免把老单误判为消失 */ const MISSING_CHECK_MAX_DAYS = 45; +/** 单次核对的最大订单数(按 LogicOrderId 批量回读,防止一次核对把平台请求打满) */ +const MAX_VERIFY_ORDERS = 300; + +/** 每次回读携带的订单号个数(平台 Contract=in 支持逗号分隔多值) */ +const VERIFY_CHUNK_SIZE = 50; + /** * 外部打单平台订单拉取服务 * @@ -114,6 +120,10 @@ class ExternalPrintOrderService extends Service { * @return {Promise} 拉取与写入统计 */ async syncOrders(shop, account, { startTime, endTime }) { + // 禁用的店铺不再拉单:拉回来的订单无法取号,只会在待审核列表里堆积报错 + if (Number(shop.status) === 0) { + throw new Error('店铺已禁用,请先启用后再拉取订单'); + } const platformService = this.createPlatformService(account); const shopPlain = shop.get ? shop.get({ plain: true }) : shop; let result; @@ -130,7 +140,26 @@ class ExternalPrintOrderService extends Service { const saved = await this.saveOrders(shop, account, result.list); - // 平台侧已发货/已终结、但本地仍停留在待审核的副本:自动作废(备注写清具体依据) + // 老分区不支持状态/商家过滤时会退化为全量拉取,留痕便于判断该店铺为何拉得多 + if (Array.isArray(result.fallbackHosts) && result.fallbackHosts.length) { + this.ctx.logger.warn( + '[externalPrintOrder] 店铺 %s 有 %d 个老分区不支持状态过滤,已退化为按时间窗全量拉取:%s', + shop.id, + result.fallbackHosts.length, + result.fallbackHosts.join('、') + ); + } + // 店铺只声明了新系统分区时,该平台的老分区属于迁移前遗留数据,直接跳过 + if (Array.isArray(result.skippedLegacy) && result.skippedLegacy.length) { + this.ctx.logger.info( + '[externalPrintOrder] 店铺 %s 跳过 %d 个迁移前的老分区(商家分区声明中无老分区):%s', + shop.id, + result.skippedLegacy.length, + result.skippedLegacy.join('、') + ); + } + + // 旧系统分区不支持状态过滤,退化查询会带回已发货/已终结的单:这部分直接作废本地未处理副本 const shipped = await this.voidUnavailableOrders(shop, (result.finished || []).map(item => ({ external_order_id: item.external_order_id, platform_status: item.platform_status || null, @@ -138,46 +167,52 @@ class ExternalPrintOrderService extends Service { reason: item.reason ? `店管家侧已发货或已终结(${item.reason})` : '店管家侧已发货或已终结', }))); - // 本次拉取窗口内本地仍是待审核、但平台已查不到的订单:也作废,并注明是「查不到」而非「已发货」 - const missingItems = await this.findMissingOrders(shop, result, { startTime, endTime }); - const missing = await this.voidUnavailableOrders(shop, missingItems); + // 新系统分区只返回「待发货」,结果里没有的本地待审核单需要按单号精确回读后区分 + // 「已发货/已终结」与「平台已查不到」,再决定是否作废 + const verified = await this.verifyPendingOrders(shop, platformService, result, { startTime, endTime }); return { startTime, endTime, orders: result.total, skipped: result.skipped || 0, - voided: shipped.count + missing.count, - voidedShipped: shipped.count, - voidedMissing: missing.count, + voided: shipped.count + verified.shipped + verified.missing, + voidedShipped: shipped.count + verified.shipped, + voidedMissing: verified.missing, created: saved.created, updated: saved.updated, items: saved.items, itemsBound: saved.itemsBound, itemsUnbound: saved.itemsUnbound, hosts: result.hosts, + fallbackHosts: result.fallbackHosts || [], }; } /** - * 找出「本次拉取窗口内本地仍是待审核、但平台返回结果里没有」的订单 + * 核对「本次拉取窗口内本地仍是待审核、但平台待发货结果里没有」的订单 * - * 用于区分「平台已发货」与「平台已查不到」两种消失原因: - * - 候选范围严格限定为「本店铺 + 待审核 + 下单时间落在本次查询窗口内」; - * - 窗口最长回看 MISSING_CHECK_MAX_DAYS 天(平台对久远订单的返回不可靠,避免误作废); - * - 本次没有成功命中任何分区(hosts 为空)时不判定,避免平台异常导致整批误作废; - * - 可用 AUTO_VOID_MISSING_ORDER=0 关闭该能力。 + * 拉单已按 ErpState=waitsellersend + 商家过滤,结果里没有的本地待审核单只有三种可能: + * 已发货 / 已终结 / 平台已查不到。逐单按 LogicOrderId 精确回读(一次最多带 50 个单号) + * 来区分: + * - 回读到且已发货/已终结 → 作废,备注写清平台依据; + * - 回读到仍是待发货 → 保留(可能是分页/分区抖动); + * - 回读不到 → 按「查不到」作废(可用 AUTO_VOID_MISSING_ORDER=0 关闭)。 + * + * 候选严格限定为「本店铺 + 待审核 + 下单时间落在本次窗口内」,且窗口最多回看 + * MISSING_CHECK_MAX_DAYS 天;本次没有任何分区命中时不判定,避免平台异常导致整批误作废。 * @param {Object} shop 店铺实例 - * @param {Object} result 平台返回(list / finished / hosts) + * @param {Object} platformService 平台服务实例 + * @param {Object} result 平台返回(list / hosts / traceId) * @param {Object} range 本次查询时间窗 * @param {Date} range.startTime 开始时间 * @param {Date} range.endTime 结束时间 - * @return {Promise} 待作废项(含 reason_code=missing) + * @return {Promise<{shipped: number, missing: number}>} 按原因统计的作废数量 */ - async findMissingOrders(shop, result, { startTime, endTime }) { + async verifyPendingOrders(shop, platformService, result, { startTime, endTime }) { const { ctx } = this; - if (String(process.env.AUTO_VOID_MISSING_ORDER || '1') === '0') return []; - if (!Array.isArray(result.hosts) || !result.hosts.length) return []; + const summary = { shipped: 0, missing: 0 }; + if (!Array.isArray(result.hosts) || !result.hosts.length) return summary; const Op = this.app.Sequelize.Op; const end = new Date(endTime); @@ -188,6 +223,7 @@ class ExternalPrintOrderService extends Service { for (const row of result.list || []) { if (row && row.external_order_id) known.add(String(row.external_order_id)); } + // 退化分区会带回已发货单(已单独作废),这些订单无需再做精确核对 for (const row of result.finished || []) { if (row && row.external_order_id) known.add(String(row.external_order_id)); } @@ -198,18 +234,105 @@ class ExternalPrintOrderService extends Service { shop_id: shop.id, place_order_time: { [Op.between]: [ start, end ] }, }, - attributes: [ 'id', 'order_no', 'parent_order_no', 'place_order_time', 'source_platform_code', 'oaid_order_source_code' ], + attributes: [ 'id', 'order_no', 'parent_order_no', 'place_order_time', 'source_platform_code' ], raw: true, }); - - return candidates + const targets = candidates .filter(row => row.parent_order_no && !known.has(String(row.parent_order_no))) - .map(row => ({ - external_order_id: String(row.parent_order_no), + .slice(0, MAX_VERIFY_ORDERS); + if (!targets.length) return summary; + + const platformRows = await this.fetchRowsForVerify(platformService, result, targets); + const describe = platformService.constructor.describeFinishedOrder; + const items = []; + for (const row of targets) { + const orderId = String(row.parent_order_no); + const platformRow = platformRows.get(orderId); + if (platformRow) { + const detail = typeof describe === 'function' ? describe(platformRow) : { finished: false, reason: '' }; + // 仍是待发货:可能只是本次分页/分区抖动,保留不动 + if (!detail.finished) continue; + items.push({ + external_order_id: orderId, + platform_status: platformRow.ErpState || null, + reason_code: 'shipped', + reason: `店管家侧已发货或已终结(${detail.reason || `ErpState=${platformRow.ErpState || '-'}`})`, + }); + summary.shipped += 1; + continue; + } + if (String(process.env.AUTO_VOID_MISSING_ORDER || '1') === '0') continue; + items.push({ + external_order_id: orderId, platform_status: null, reason_code: 'missing', - reason: `店管家侧已查不到该订单(${formatTimeText(start)} 至 ${formatTimeText(end)} 的拉取结果中没有该单,可能已删除、合并或转出本店铺)`, - })); + reason: `店管家侧已查不到该订单(${formatTimeText(start)} 至 ${formatTimeText(end)} 的待发货结果中没有该单,且按系统编号回读也查不到,可能已删除、合并或转出本店铺)`, + }); + summary.missing += 1; + } + + if (items.length) await this.voidUnavailableOrders(shop, items); + return summary; + } + + /** + * 按系统编号批量回读平台订单行(按平台域名 + 分区逐个命中,命中即停) + * @param {Object} platformService 平台服务实例 + * @param {Object} result 平台返回(traceId) + * @param {Array} targets 待核对的本地订单(parent_order_no / source_platform_code) + * @return {Promise>} 系统编号 → 平台订单行 + */ + async fetchRowsForVerify(platformService, result, targets) { + const found = new Map(); + if (typeof platformService.fetchOrdersByIds !== 'function') return found; + + const resolveHost = platformService.constructor && platformService.constructor.resolveOrderHost; + if (typeof resolveHost !== 'function') return found; + + const byHost = new Map(); + for (const row of targets) { + const host = resolveHost(String(row.source_platform_code || '')); + if (!host) continue; + if (!byHost.has(host)) byHost.set(host, []); + byHost.get(host).push(String(row.parent_order_no)); + } + + for (const [ host, ids ] of byHost) { + let areas = []; + try { + areas = await platformService.listProductAreas(host); + } catch { + areas = [{ dbname: '', name: '' }]; + } + if (!areas.length) areas = [{ dbname: '', name: '' }]; + + for (let start = 0; start < ids.length; start += VERIFY_CHUNK_SIZE) { + const chunk = ids.slice(start, start + VERIFY_CHUNK_SIZE); + const pending = new Set(chunk); + for (const area of areas) { + if (!pending.size) break; + let rows = []; + try { + rows = await platformService.fetchOrdersByIds(host, { + traceId: result.traceId || '', + dbname: area.dbname, + ids: Array.from(pending), + }); + } catch (err) { + this.ctx.logger.warn('[externalPrintOrder] 订单核对失败 host=%s dbname=%s:%s', host, area.dbname, err.message); + continue; + } + for (const row of rows) { + const id = String(row.LogicOrderId || ''); + if (!id || !pending.has(id)) continue; + found.set(id, row); + pending.delete(id); + } + } + } + } + + return found; } /** diff --git a/backend/app/service/orderStatus.js b/backend/app/service/orderStatus.js index 383e202..c979d51 100644 --- a/backend/app/service/orderStatus.js +++ b/backend/app/service/orderStatus.js @@ -1335,7 +1335,7 @@ class OrderStatusService extends Service { * * 与老发货单一致:**曾推送过的单据恢复时换号**(WMS 侧单号唯一,取消/作废后原号仍被占用), * 并清空审核 / 推送痕迹与作废原因(重回待审核,重试计数归零) - * @param {Object} p { ids } + * @param {Object} p { ids, principalId } * @return {Promise} { count, status, status_label, items } */ async restore(p = {}) { @@ -1347,6 +1347,8 @@ class OrderStatusService extends Service { renameIfPushed: true, clearAudit: true, clearVoid: true, + // 无登录态的内部任务(如店铺重新启用后批量恢复)需显式传主体 + principalId: p.principalId, }); } @@ -1362,11 +1364,12 @@ class OrderStatusService extends Service { * @param {Boolean} [p.renameIfPushed] 仅在推送过时换号 * @param {Boolean} [p.clearAudit] 是否清空审核 / 推送痕迹 * @param {Boolean} [p.clearVoid] 是否清空作废痕迹 + * @param {Number} [p.principalId] 主体ID(无登录态的内部任务显式传入) * @return {Promise} { count, status, status_label, items } */ async _singleFlow(p) { const { ctx } = this; - const principalId = ctx.state.principalId; + const principalId = p.principalId || ctx.state.principalId; const idList = this._normalizeIds(p.ids); const indexRows = await this._loadIndexRows(idList, principalId); diff --git a/backend/app/service/shopAreaSync.js b/backend/app/service/shopAreaSync.js new file mode 100644 index 0000000..9abf8f3 --- /dev/null +++ b/backend/app/service/shopAreaSync.js @@ -0,0 +1,242 @@ +'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: [], + voided: 0, + }; + + for (const shop of shops) { + const externalId = this.resolveExternalId(shop); + const merchant = externalId ? merchantMap.get(externalId) : null; + if (merchant) { + await this.applyMerchant(shop, merchant, now, result); + } else { + await this.markMissing(shop, now, { disableMissing, result }); + } + } + + 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:优先取 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; diff --git a/backend/app/service/shopOrderGuard.js b/backend/app/service/shopOrderGuard.js new file mode 100644 index 0000000..061b8b4 --- /dev/null +++ b/backend/app/service/shopOrderGuard.js @@ -0,0 +1,167 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 因店铺禁用而写入的作废原因前缀。 + * 店铺重新启用时只按此前缀找回「被暂停」的订单,避免把平台已发货等其它原因作废的单恢复回来。 + */ +const DISABLED_VOID_REASON_PREFIX = '店铺已禁用,暂停处理'; + +/** 单次流转的订单条数(避免一次 IN / 事务过大) */ +const BATCH_SIZE = 200; + +/** + * 店铺禁用 / 启用时的待审核订单守卫 + * + * 店铺禁用后无法再取号(平台账号或商家已不可用),留在「待审核」的订单一旦被审核/取号就会报错, + * 因此: + * 1. 禁用 → 立即把该店铺的待审核订单作废(备注写明原因,可追溯); + * 2. 启用 → 把**因禁用被作废**的订单恢复回待审核(按 void_reason 前缀识别,不影响其它作废单)。 + * + * 只处理 `pending → void`,已审核(待推送/委外中/配送)的订单不动:那些单据的库存与仓库动作已发生。 + */ +class ShopOrderGuardService extends Service { + /** + * 店铺禁用后作废其待审核订单 + * @param {Object} shop 店铺实例(或含 id/name/code/principal_id 的普通对象) + * @param {Object} [options] 选项 + * @param {string} [options.reason] 自定义作废原因(默认按店铺生成) + * @return {Promise<{count: number}>} 作废数量 + */ + async voidPendingOrders(shop, options = {}) { + const { ctx } = this; + const pendingModel = ctx.model.OrderStatusPending; + if (!pendingModel) return { count: 0 }; + + const rows = await pendingModel.findAll({ + where: { principal_id: shop.principal_id, shop_id: shop.id }, + attributes: [ 'id', 'order_no' ], + raw: true, + }); + if (!rows.length) return { count: 0 }; + + const reason = options.reason || `${DISABLED_VOID_REASON_PREFIX}(店铺「${shopName(shop)}」禁用后无法取号;重新启用后自动恢复)`; + const moved = await this.runFlow(rows, async ids => { + return await ctx.service.orderStatus.voidOrder({ + ids, + void_reason: reason, + principalId: shop.principal_id, + }); + }); + + await ctx.service.operationLog.recordMany( + (moved.length ? moved : rows).map(row => ({ + principalId: shop.principal_id, + targetType: 'order', + targetId: Number(row.id), + action: 'void', + title: `店铺禁用作废:${row.order_no || row.id}`, + detail: { reason, shop_id: Number(shop.id), shop_name: shopName(shop) }, + })), + { source: 'system' } + ); + + this.ctx.logger.warn('[shopOrderGuard] 店铺 %s 已禁用,作废待审核订单 %d 单', shop.id, moved.length); + return { count: moved.length }; + } + + /** + * 店铺重新启用后恢复「因禁用被作废」的订单 + * @param {Object} shop 店铺实例 + * @return {Promise<{count: number}>} 恢复数量 + */ + async restorePendingOrders(shop) { + const { ctx } = this; + const Op = ctx.app.Sequelize.Op; + const voidModel = ctx.model.OrderStatusVoid; + if (!voidModel) return { count: 0 }; + + const rows = await voidModel.findAll({ + where: { + principal_id: shop.principal_id, + shop_id: shop.id, + void_reason: { [Op.like]: `${DISABLED_VOID_REASON_PREFIX}%` }, + }, + attributes: [ 'id', 'order_no' ], + raw: true, + }); + if (!rows.length) return { count: 0 }; + + const moved = await this.runFlow(rows, async ids => { + return await ctx.service.orderStatus.restore({ ids, principalId: shop.principal_id }); + }); + + await ctx.service.operationLog.recordMany( + (moved.length ? moved : rows).map(row => ({ + principalId: shop.principal_id, + targetType: 'order', + targetId: Number(row.id), + action: 'restore', + title: `店铺启用恢复:${row.order_no || row.id}`, + detail: { shop_id: Number(shop.id), shop_name: shopName(shop) }, + })), + { source: 'system' } + ); + + ctx.logger.info('[shopOrderGuard] 店铺 %s 已启用,恢复待审核订单 %d 单', shop.id, moved.length); + return { count: moved.length }; + } + + /** + * 分批执行状态流转;某批里有单据状态已变(如刚好被人工审核)时降级为逐单执行, + * 避免个别单据阻塞整批。 + * @param {Array} rows 待流转的订单行(需含 id / order_no) + * @param {Function} flow 流转函数:ids → { count, items } + * @return {Promise>} 实际流转成功的订单 + */ + async runFlow(rows, flow) { + const succeeded = []; + for (const chunk of chunksOf(rows, BATCH_SIZE)) { + try { + const result = await flow(chunk.map(row => Number(row.id))); + const items = Array.isArray(result && result.items) ? result.items : []; + if (items.length) { + succeeded.push(...items.map(item => ({ id: Number(item.id), order_no: item.order_no }))); + } else { + succeeded.push(...chunk); + } + } catch (err) { + this.ctx.logger.warn('[shopOrderGuard] 批量流转失败,改为逐单处理:%s', err.message); + for (const row of chunk) { + try { + const result = await flow([ Number(row.id) ]); + const item = result && Array.isArray(result.items) ? result.items[0] : null; + succeeded.push(item ? { id: Number(item.id), order_no: item.order_no } : row); + } catch (singleErr) { + this.ctx.logger.warn('[shopOrderGuard] 订单 %s 流转失败:%s', row.order_no || row.id, singleErr.message); + } + } + } + } + return succeeded; + } +} + +/** + * 店铺展示名(备注里用,缺名称时退回编码 / ID) + * @param {Object} shop 店铺实例 + * @return {string} 展示名 + */ +function shopName(shop) { + return String((shop && (shop.name || shop.code)) || (shop && shop.id) || '').slice(0, 50); +} + +/** + * 按固定大小切分数组 + * @param {Array} list 原数组 + * @param {number} size 每段大小 + * @return {Array} 分段结果 + */ +function chunksOf(list, size) { + const chunks = []; + for (let i = 0; i < list.length; i += size) chunks.push(list.slice(i, i + size)); + return chunks; +} + +module.exports = ShopOrderGuardService; diff --git a/frontend/src/api/externalPrintAccount.ts b/frontend/src/api/externalPrintAccount.ts index 625e7e3..0a479a0 100644 --- a/frontend/src/api/externalPrintAccount.ts +++ b/frontend/src/api/externalPrintAccount.ts @@ -1,5 +1,6 @@ import { get, post, put, del } from '@/utils/request' import type { ExternalPrintPlatformItem } from '@/api/externalPrintPlatform' +import type { ShopAreaRefreshResult } from '@/api/shop' export interface ExternalPrintAccountItem { id: number @@ -98,6 +99,13 @@ export function getExternalPrintMerchants(id: number, params?: object) { ) } +/** 刷新账号下店铺的「所在区」:一次拉取账号全部商家,商家已解绑的店铺自动禁用 */ +export function refreshExternalPrintShopsArea(id: number) { + return post(`/external-print-accounts/${id}/refresh-shops-area`, undefined, { + timeout: 120000, + }) +} + /** 商品同步时单个分区的拉取明细(同一域名下可能有多套库,如「新系统区」) */ export interface ExternalPrintShopProductSyncArea { dbname: string diff --git a/frontend/src/api/shop.ts b/frontend/src/api/shop.ts index 9908afd..099e797 100644 --- a/frontend/src/api/shop.ts +++ b/frontend/src/api/shop.ts @@ -100,9 +100,16 @@ export function createShop(data: ShopPayload) { return post<{ id: number; code: string }>('/shops', data) } -/** 更新店铺 */ +/** 更新店铺(禁用会导致待审核订单作废、启用会恢复,返回对应数量) */ export function updateShop(id: number, data: Partial) { - return put<{ id: number; pending_orders_updated?: number }>(`/shops/${id}`, data) + return put<{ + id: number + pending_orders_updated?: number + /** 因禁用而作废的待审核订单数 */ + pending_orders_voided?: number + /** 因启用而恢复回待审核的订单数 */ + pending_orders_restored?: number + }>(`/shops/${id}`, data) } /** 设置店铺默认发货仓库(外部打单平台店铺的所在公司权限也可维护;null 表示清除) */ @@ -117,3 +124,34 @@ export function setShopDefaultWarehouse(id: number, defaultWarehouseId: number | export function deleteShop(id: number) { return del<{ id: number }>(`/shops/${id}`) } + +/** 刷新所在区结果里的店铺摘要 */ +export interface ShopAreaBrief { + id: number + code: string + name: string +} + +/** 刷新店铺「所在区」的结果(同账号下的店铺共享一次平台拉取) */ +export interface ShopAreaRefreshResult { + account_id: number + /** 平台返回的商家数量 */ + merchants: number + /** 账号下本地店铺数量 */ + shops: number + /** 商家结构(含所在区)有变化并写回的店铺数 */ + updated: number + /** 本次被自动禁用的店铺(商家已不在合作列表) */ + disabled: ShopAreaBrief[] + /** 因禁用被作废的待审核订单数(启用后可恢复) */ + voided: number + /** 平台商家列表里找不到的店铺 */ + missing: ShopAreaBrief[] + /** 重新出现在合作列表的店铺(保持禁用,需人工启用) */ + restored: ShopAreaBrief[] +} + +/** 刷新店铺「所在区」:重新拉取所属打单账号的商家列表,商家已解绑时自动禁用店铺 */ +export function refreshShopArea(id: number) { + return post(`/shops/${id}/refresh-area`, undefined, { timeout: 120000 }) +} diff --git a/frontend/src/views/ExternalPrintPlatform/Index.vue b/frontend/src/views/ExternalPrintPlatform/Index.vue index 1c940f9..c30b340 100644 --- a/frontend/src/views/ExternalPrintPlatform/Index.vue +++ b/frontend/src/views/ExternalPrintPlatform/Index.vue @@ -13,6 +13,7 @@ import { checkExternalPrintAccount, loginExternalPrintAccount, getExternalPrintMerchants, + refreshExternalPrintShopsArea, createShopsFromMerchants, type ExternalPrintAccountItem, type ExternalPrintAccountPayload, @@ -325,6 +326,27 @@ async function handleAddShops() { } } +/** 正在刷新所在区的账号ID */ +const refreshingAreaAccountId = ref(null) + +/** 刷新账号下店铺的「所在区」:一次拉取账号全部商家,商家已解绑的店铺自动禁用 */ +async function handleRefreshShopsArea(row: ExternalPrintAccountItem) { + refreshingAreaAccountId.value = row.id + try { + const res = await refreshExternalPrintShopsArea(row.id) + const parts = [ `平台商家 ${res.merchants} 个`, `${res.shops} 个店铺中更新 ${res.updated} 个` ] + if (res.disabled.length) parts.push(`自动禁用 ${res.disabled.length} 个(已不在合作列表)`) + if (res.voided) parts.push(`作废待审核订单 ${res.voided} 个(启用后自动恢复)`) + if (res.restored.length) parts.push(`${res.restored.length} 个已重新回到合作列表,可手动启用`) + ElMessage.success(`刷新完成:${parts.join(',')}`) + await fetchList() + } catch { + // 拦截器已提示 + } finally { + refreshingAreaAccountId.value = null + } +} + /** 行登录状态:优先用本次检查/登录结果,否则用后端记录的最新状态 */ function isRowLoggedIn(row: ExternalPrintAccountItem) { const local = loginStatus[row.id] @@ -401,9 +423,17 @@ onBeforeUnmount(() => { - +