/** * Pinduoduo Scheduled Order Sync Job * 拼多多定时订单同步任务 (错峰智能调度与异常保护) */ import type { JsonObject } from '../../types/json.js' import { logDebug, logInfo } from '../../utils/logger.js' import { syncAllPddStores } from '../platforms/pdd/pdd-sync-service.js' import { getPddSourcesConfig } from '../platforms/pdd/pdd-source-config-service.js' export async function runPddOrderSyncJob(job: JsonObject) { const config = job.config && typeof job.config === 'object' && !Array.isArray(job.config) ? (job.config as JsonObject) : {} const sourcesConfig = getPddSourcesConfig() const pageSize = Math.min( 100, Math.max(1, Number(config.pageSize || sourcesConfig.pageSize || 50)), ) const maxPages = Math.min(20, Math.max(1, Number(config.maxPages || sourcesConfig.maxPages || 5))) const orderType = Number(config.orderType ?? sourcesConfig.orderType ?? 2) const syncResult = await syncAllPddStores({ pageSize, maxPages, orderType }) if (!syncResult.enabled) { return { ok: true, status: 'disabled', message: '拼多多同步子服务已全局停用', accountCount: syncResult.storeCount, checkedCount: 0, okCount: 0, failedCount: 0, suspendedCount: 0, } } const okCount = syncResult.results.filter((r) => !r.error).length const failedCount = syncResult.results.filter((r) => Boolean(r.error)).length const totalUpserted = syncResult.results.reduce((acc, r) => acc + r.upsertedCount, 0) const totalFetched = syncResult.results.reduce((acc, r) => acc + r.fetchedCount, 0) const totalNewOrders = syncResult.results.reduce((acc, r) => acc + r.newOrderCount, 0) // 有店铺被熔断时必须留在 info 级:否则"全部店铺已停止同步"会因新单为 0 被降级成 debug 而不可见。 const jobLog = totalNewOrders > 0 || failedCount > 0 || syncResult.suspendedCount > 0 ? logInfo : logDebug jobLog('[pdd-order-sync-job]', '拼多多定时拉单执行完成', { storeCount: syncResult.storeCount, syncedCount: syncResult.syncedCount, suspendedCount: syncResult.suspendedCount, okCount, failedCount, totalFetched, totalUpserted, totalNewOrders, }) return { ok: failedCount === 0, status: failedCount > 0 ? (okCount > 0 ? 'partial_error' : 'failed') : 'ok', message: `已同步 ${syncResult.syncedCount} 个店铺,拉取 ${totalFetched} 单,新单 ${totalNewOrders},入库/更新 ${totalUpserted} 单${failedCount > 0 ? `,失败 ${failedCount} 个店铺` : ''}${syncResult.suspendedCount > 0 ? `,${syncResult.suspendedCount} 个店铺已熔断待更新 Cookie` : ''}`, accountCount: syncResult.storeCount, checkedCount: syncResult.syncedCount, okCount, failedCount, suspendedCount: syncResult.suspendedCount, asset: totalNewOrders, totalUpserted, totalNewOrders, } }