'use strict'; const Service = require('egg').Service; /** 外部发货同步状态 */ const SEND_STATUS = { PENDING: 0, SYNCED: 1, RETRY: 2, EXCEPTION: 3, }; /** 状态文案 */ const SEND_STATUS_LABELS = { 0: '待同步', 1: '已同步', 2: '同步失败待重试', 3: '同步异常', }; /** 失败重试上限:达到后流转为「异常」,等人工批量重试 */ const MAX_SEND_TIMES = 3; /** * 截断字符串,避免超出表字段长度 * @param {*} value 原始值 * @param {number} max 最大长度 * @return {string} 截断后的字符串 */ function truncateText(value, max) { return String(value == null ? '' : value).slice(0, max); } /** * 是否为平台登录态失效类错误(分区接口统一返回「登录信息过期,请重新登录」) * @param {Error} err 异常 * @return {boolean} 是否需要重新登录 */ function isSessionExpiredError(err) { const message = String((err && err.message) || ''); return /登录信息过期|登录已失效|token is invalid|未登录|缺少 token/i.test(message); } /** * 同步外部打单平台发货(店管家 `NewOrder/OnlineSendBatch`) * * 触发链路: * - WMS 回传 `deliveryorder.confirm` → 订单流转到「配送」时把状态置为「待同步」(`markPending`); * - 定时任务 `externalSendSyncWorker` 扫描「待同步 / 失败待重试」的配送单,逐单调平台发货接口; * - 失败累加次数,达到 3 次转「异常」;人工在列表里批量重试(`retry`)会把次数清零重新排队。 */ class ExternalSendSyncService extends Service { /** * 订单流转到配送后标记「待同步」 * * 非外部打单订单(店铺不是 type=2 / 没有打单账号)直接标记为「已同步」,避免污染异常统计。 * @param {number[]} ids 订单ID(order_index.id) * @param {number} principalId 主体ID * @return {Promise} 无返回值 */ async markPending(ids, principalId) { const { ctx } = this; const idList = (Array.isArray(ids) ? ids : [ ids ]).map(Number).filter(Boolean); if (!idList.length) return; const Op = ctx.app.Sequelize.Op; const rows = await ctx.model.OrderStatusDelivery.findAll({ where: { principal_id: principalId, id: { [Op.in]: idList } }, }); for (const row of rows) { const applicable = await this.isExternalPrintOrder(row); await row.update(applicable ? { external_send_status: SEND_STATUS.PENDING, external_send_times: 0, external_send_error: '' } : { external_send_status: SEND_STATUS.SYNCED, external_send_times: 0, external_send_error: '', external_send_at: new Date(), external_sent_at: new Date(), }); } } /** * 是否外部打单平台订单(店铺 type=2 且挂了打单账号) * @param {Object} order 配送表订单行 * @return {Promise} 是否需要同步 */ async isExternalPrintOrder(order) { const { ctx } = this; if (!order || !order.shop_id) return false; const shop = await ctx.model.Shop.findByPk(order.shop_id, { attributes: [ 'id', 'type', 'external_print_account_id' ], }); return !!(shop && Number(shop.type) === 2 && shop.external_print_account_id); } /** * 同步单个订单的发货结果到外部打单平台 * @param {Object} order 配送表订单行(Sequelize 实例) * @param {Object} [options] 参数 * @param {string} [options.trigger] 触发来源(schedule / manual) * @return {Promise<{ok: boolean, message: string, skipped?: boolean}>} 同步结果 */ async syncOrder(order, { trigger = 'schedule' } = {}) { const { ctx } = this; const now = new Date(); try { const target = await this.resolveTarget(order); if (!target) { await order.update({ external_send_status: SEND_STATUS.SYNCED, external_send_error: '', external_send_at: now, external_sent_at: now, }); return { ok: true, skipped: true, message: '非外部打单订单,无需同步' }; } const { service, platformType, dbname, platformCode, template } = target; const host = service.constructor.resolveOrderHost(platformType); const row = await service.findPlatformOrderRow(host, { traceId: await this.resolveTraceId(service), dbname, logicalOrderId: String(order.parent_order_no || order.order_no || ''), platformOrderId: String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || ''), placeOrderTime: order.place_order_time || order.pay_time || order.created_at, }); if (!row) { throw new Error(`外部打单平台未找到该订单(平台 ${platformCode},系统编号 ${order.parent_order_no || order.order_no})`); } await service.sendOrders(host, { traceId: await this.resolveTraceId(service), dbname, rows: [ row ], templateId: template ? template.template_id : '', expressCompanyId: template ? template.express_company_id : '', expressCode: template ? template.express_company_code : '', }); await order.update({ external_send_status: SEND_STATUS.SYNCED, external_send_error: '', external_send_at: now, external_sent_at: now, }); ctx.logger.info('[external-send] 同步外部发货成功 %s(%s)', order.order_no, trigger); return { ok: true, message: 'ok' }; } catch (err) { // 登录态失效:重新登录后重试一次 if (isSessionExpiredError(err)) { try { const target = await this.resolveTarget(order); if (target) { await target.service.loginByPassword(); const host = target.service.constructor.resolveOrderHost(target.platformType); const row = await target.service.findPlatformOrderRow(host, { traceId: await this.resolveTraceId(target.service), dbname: target.dbname, logicalOrderId: String(order.parent_order_no || order.order_no || ''), platformOrderId: String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || ''), placeOrderTime: order.place_order_time || order.pay_time || order.created_at, }); if (!row) throw new Error('外部打单平台未找到该订单'); await target.service.sendOrders(host, { traceId: await this.resolveTraceId(target.service), dbname: target.dbname, rows: [ row ], templateId: target.template ? target.template.template_id : '', expressCompanyId: target.template ? target.template.express_company_id : '', expressCode: target.template ? target.template.express_company_code : '', }); await order.update({ external_send_status: SEND_STATUS.SYNCED, external_send_error: '', external_send_at: now, external_sent_at: now, }); ctx.logger.info('[external-send] 重新登录后同步成功 %s', order.order_no); return { ok: true, message: 'ok' }; } } catch (retryErr) { return await this.recordFailure(order, retryErr, now); } } return await this.recordFailure(order, err, now); } } /** * 记录一次失败:累加次数,达到上限转「异常」 * @param {Object} order 配送表订单行 * @param {Error} err 异常 * @param {Date} now 当前时间 * @return {Promise<{ok: boolean, message: string}>} 结果 */ async recordFailure(order, err, now) { const { ctx } = this; const times = Number(order.external_send_times || 0) + 1; const exception = times >= MAX_SEND_TIMES; const message = truncateText(err && err.message ? err.message : '同步失败', 500); await order.update({ external_send_status: exception ? SEND_STATUS.EXCEPTION : SEND_STATUS.RETRY, external_send_times: times, external_send_error: message, external_send_at: now, }); ctx.logger.warn('[external-send] 同步外部发货失败 %s(第 %d 次%s):%s', order.order_no, times, exception ? ',转异常' : '', message); return { ok: false, message }; } /** * 定位同步目标(打单账号 / 平台服务 / 分区) * @param {Object} order 配送表订单行 * @return {Promise} 目标信息;非外部打单订单返回 null */ async resolveTarget(order) { const { ctx } = this; if (!order || !order.shop_id) return null; const shop = await ctx.model.Shop.findByPk(order.shop_id, { attributes: [ 'id', 'type', 'external_print_account_id' ], }); if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) return null; const account = await ctx.model.ExternalPrintAccount.findByPk(shop.external_print_account_id, { include: [{ model: ctx.model.ExternalPrintPlatform, as: 'platform' }], }); if (!account || !account.platform) return null; const platformCode = String(order.source_platform_code || '').trim(); const service = ctx.service.externalPrintOrder.createPlatformService(account); const resolvePlatformType = service.constructor && service.constructor.resolvePlatformType; const template = await ctx.model.ExternalPrintExpressInterface.findOne({ where: { principal_id: order.principal_id, account_id: account.id, platform_code: platformCode, status: 1 }, attributes: [ 'id', 'platform_type', 'dbname', 'template_id', 'express_company_id', 'express_company_code' ], order: [[ 'id', 'ASC' ]], }); // PlatformType(决定回传发货用哪个域名)优先按「订单原始平台」:1688 分销单在 OMS 里被换算成 // 抖音小店/淘宝(为了选对模板),但订单行仍在 Alibaba 分区(fxali),按换算后的平台找会查错域名 const raw = order.extend_props && typeof order.extend_props === 'object' ? order.extend_props : {}; const originalCode = String(raw.original_platform_code || '').trim(); let platformType = ''; if (originalCode && typeof resolvePlatformType === 'function') { platformType = resolvePlatformType(originalCode) || ''; } if (!platformType) { platformType = template ? template.platform_type : (typeof resolvePlatformType === 'function' ? resolvePlatformType(platformCode) : ''); } if (!platformType) return null; return { service, account, platformType, dbname: template ? template.dbname : '', platformCode, template }; } /** * 取平台登录上下文 traceId(失败不阻断) * @param {Object} service 平台服务实例 * @return {Promise} traceId */ async resolveTraceId(service) { try { const info = await service.getUserInfo(); return (info.data && info.data.TraceId) || ''; } catch (err) { return ''; } } /** * 扫描并同步待同步 / 可重试的配送单(定时任务入口) * @param {Object} [options] 参数 * @param {number} [options.limit] 单批上限 * @return {Promise} 统计结果 */ async syncPending({ limit = 50 } = {}) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; // 主体停用后不再回传平台 const enabledPrincipalIds = await ctx.service.cache.getEnabledPrincipalIds(); if (!enabledPrincipalIds.length) return { total: 0, success: 0, failed: 0, exception: 0 }; const rows = await ctx.model.OrderStatusDelivery.findAll({ where: { external_send_status: { [Op.in]: [ SEND_STATUS.PENDING, SEND_STATUS.RETRY ] }, external_send_times: { [Op.lt]: MAX_SEND_TIMES }, principal_id: { [Op.in]: enabledPrincipalIds }, }, order: [[ 'external_send_at', 'ASC' ]], limit, }); let success = 0; let failed = 0; let exception = 0; for (const row of rows) { const result = await this.syncOrder(row, { trigger: 'schedule' }); if (result.ok) success += 1; else if (row.external_send_status === SEND_STATUS.EXCEPTION) exception += 1; else failed += 1; } return { total: rows.length, success, failed, exception }; } /** * 各状态数量(前端快速查看异常数量) * @param {number} principalId 主体ID * @return {Promise} { pending, retry, exception, synced, total } */ async counts(principalId) { const { ctx } = this; const Sequelize = ctx.app.Sequelize; const rows = await ctx.model.OrderStatusDelivery.findAll({ where: { principal_id: principalId }, attributes: [ 'external_send_status', [ Sequelize.fn('COUNT', Sequelize.col('id')), 'cnt' ]], group: [ 'external_send_status' ], raw: true, }); const result = { pending: 0, retry: 0, exception: 0, synced: 0, total: 0 }; for (const row of rows) { const count = Number(row.cnt) || 0; result.total += count; if (Number(row.external_send_status) === SEND_STATUS.PENDING) result.pending += count; else if (Number(row.external_send_status) === SEND_STATUS.RETRY) result.retry += count; else if (Number(row.external_send_status) === SEND_STATUS.EXCEPTION) result.exception += count; else if (Number(row.external_send_status) === SEND_STATUS.SYNCED) result.synced += count; } return result; } /** * 批量重试同步(人工处理异常单) * * 把状态重置为「待同步」并把次数清零,随后立刻跑一批,避免等定时任务。 * @param {Object} p 参数 * @param {number[]} [p.ids] 指定订单ID;为空时按状态筛选 * @param {number} [p.principalId] 主体ID * @param {number[]} [p.statuses] 状态筛选(默认异常 + 待重试) * @return {Promise} { reset, result } */ async retry({ ids, principalId, statuses = [ SEND_STATUS.EXCEPTION, SEND_STATUS.RETRY ] } = {}) { const { ctx } = this; const Op = ctx.app.Sequelize.Op; const idList = (Array.isArray(ids) ? ids : []).map(Number).filter(Boolean); const where = { principal_id: principalId }; if (idList.length) where.id = { [Op.in]: idList }; else where.external_send_status = { [Op.in]: statuses }; const rows = await ctx.model.OrderStatusDelivery.findAll({ where }); for (const row of rows) { await row.update({ external_send_status: SEND_STATUS.PENDING, external_send_times: 0, external_send_error: '', }); } let success = 0; let failed = 0; for (const row of rows) { const result = await this.syncOrder(row, { trigger: 'manual' }); if (result.ok) success += 1; else failed += 1; } return { reset: rows.length, success, failed }; } } module.exports = ExternalSendSyncService; module.exports.SEND_STATUS = SEND_STATUS; module.exports.SEND_STATUS_LABELS = SEND_STATUS_LABELS; module.exports.MAX_SEND_TIMES = MAX_SEND_TIMES;