diff --git a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php index 6578f572..8715b1f8 100644 --- a/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php +++ b/modules/EcommerceFinance/Services/Jushuitan/ShippingReplicaSynchronizer.php @@ -110,6 +110,18 @@ class ShippingReplicaSynchronizer private readonly UpstreamReadOnlyQueryFactory $queries; + /** 读到够早就停:窗口开始前多少天(留足预售等「早建单、晚发货」的余量) */ + private const EARLY_STOP_DAYS = 120; + + /** 连续多少页(每页 1500 行)都早于上面的界限才停 */ + private const EARLY_STOP_PAGES = 40; + + /** 本次发货扫描是否因「读到够早」提前结束(进度里显示) */ + public bool $earlyStopped = false; + + /** @var array> 仅缓存需要补齐字段的订单。 */ + private array $orderMetadata = []; + /** 长超时连接的秒数:按 IN 查订单表在副本库忙时会超过默认 15 秒(2026-11/09 整月同步都死在这里) */ private const PATIENT_TIMEOUT_SECONDS = 120; private readonly \Illuminate\Database\ConnectionInterface $db; @@ -219,6 +231,8 @@ class ShippingReplicaSynchronizer ): array { $this->markRunning(); + $this->earlyStopped = false; + $this->orderMetadata = []; try { $windowed = $from && $to; if ($skipFreight && ! $windowed) { @@ -411,6 +425,7 @@ class ShippingReplicaSynchronizer throw $e; } finally { $this->dwsCache = []; + $this->orderMetadata = []; $this->outboundMap = ['byL' => [], 'byO' => [], 'byLO' => [], 'byOAll' => [], 'ioL' => []]; $this->replacementPackages = []; $this->replacementHasFreight = []; @@ -502,6 +517,10 @@ class ShippingReplicaSynchronizer $total = 0; $scanned = 0; $lastId = null; + // 读到够早就停:连续 EARLY_STOP_PAGES 页都没有窗口内的单、且整页最晚发货时间早于窗口开始前 EARLY_STOP_DAYS 天。 + // 以前一直读到表头(全部历史),40 天同步每晚都要读几百万行、查几千次订单表,副本库一忙就超时。 + $oldPages = 0; + $stopBefore = $fromTs !== null ? $fromTs - self::EARLY_STOP_DAYS * 86400 : null; for ($b = 0; $b <= $maxBatches; $b++) { if ($changesOnly) { $where = 'e.updatedAt >= ? AND e.updatedAt < ?'; @@ -522,6 +541,10 @@ class ShippingReplicaSynchronizer $sql = "SELECT TOP {$batch} {$cols} FROM rpt.jst_order_express_details e " . "WHERE {$where} ORDER BY e.id DESC"; } + if (! $changesOnly && $oldPages >= self::EARLY_STOP_PAGES) { + $this->earlyStopped = true; + break; + } $rows = $this->selectWithReconnect($sql, $bind); if ($rows === []) { break; @@ -535,10 +558,14 @@ class ShippingReplicaSynchronizer $lastId = $r['id']; } + // 字段齐全时沿用主线的明细直读;缺发货时间或单号时才查订单镜像/上游。 + $this->loadOrderMetadataForRows($rows); + $rows = array_map(fn (array $row): array => $this->mergeOrderMetadata($row), $rows); if ($windowed) { $kept = []; + $pageHasUnknownDate = false; foreach ($rows as $r) { - $st = $r['send_time'] ?? null; + $st = ($r['send_time'] ?? null) ?: ($r['jo_send'] ?? null); $ts = ($st !== null && $st !== '') ? strtotime((string) $st) : null; $oid = (string) ($r['inner_order_id'] ?? ''); if ($oid !== '' && $ts !== null @@ -550,8 +577,19 @@ class ShippingReplicaSynchronizer if ($ts !== null && $ts >= $fromTs && $ts < $toTs) { $kept[] = $r; } + if ($ts !== null && $ts !== false) { + $pageLatest = max($pageLatest ?? $ts, $ts); + } else { + $pageHasUnknownDate = true; + } } $rows = $kept; + if (! $pageHasUnknownDate && $stopBefore !== null && $kept === [] && isset($pageLatest) && $pageLatest < $stopBefore) { + $oldPages++; + } else { + $oldPages = 0; + } + unset($pageLatest); } $oids = []; @@ -662,13 +700,144 @@ class ShippingReplicaSynchronizer } } if ($progress) { - $progress(sprintf('发货完成:扫描 %d 行,处理 %d 件', $scanned, $total)); + $progress(sprintf('发货完成:扫描 %d 行,处理 %d 件', $scanned, $total) + . ($this->earlyStopped ? sprintf('(已读到窗口开始前 %d 天以前,提前结束)', self::EARLY_STOP_DAYS) : '')); } $this->flushPending(); return $total; } + /** 按当前页订单键补齐订单字段,并复用已缓存的结果。 */ + private function loadOrderMetadataForRows(array $rows): void + { + $oids = []; + foreach ($rows as $row) { + if (trim((string) ($row['send_time'] ?? '')) !== '' && trim((string) ($row['logistic_id'] ?? '')) !== '') { + continue; + } + $oid = (string) ($row['inner_order_id'] ?? ''); + if ($oid !== '' && ! array_key_exists($oid, $this->orderMetadata)) { + $oids[$oid] = true; + } + } + // 先查本地订单镜像 ops_jst_orders(o_id 有索引,毫秒级):已发货的订单直接用镜像; + // 镜像里没有、或镜像里还没发货时间的(镜像每天 05:00 刷新,之后发的单)才去副本库查。 + // 副本库按 o_id IN 查 rpt.jst_Orders 很慢,2026-11/09 整月同步都死在这一步。 + $pending = $this->loadOrderMetadataFromMirror(array_keys($oids)); + foreach (array_chunk($pending, 400) as $chunk) { + if ($chunk === []) { + continue; + } + $ph = implode(',', array_fill(0, count($chunk), '?')); + $sql = "SELECT o_id, l_id, send_date, status, labels, shop_name FROM rpt.jst_Orders om WHERE om.o_id IN ({$ph})"; + foreach ($this->selectWithReconnect($sql, $chunk) as $row) { + $this->rememberOrderMetadata($row); + } + foreach ($chunk as $oid) { + // 记录无匹配订单,避免后续分页反复查询同一个缺失键。 + $this->orderMetadata[$oid] ??= ['l_id' => null, 'send_date' => null, 'status' => null, 'online' => false]; + } + } + } + + /** 全表扫描会缓存数百万订单:只留判断需要的精简字段(状态仅存会被排除的三种,标签只存是否线上发货)。 */ + private function rememberOrderMetadata(array|object $row): void + { + $row = (array) $row; + $oid = (string) ($row['o_id'] ?? ''); + if ($oid === '') { + return; + } + $st = (string) ($row['status'] ?? ''); + $this->orderMetadata[$oid] = [ + 'l_id' => $row['l_id'] ?? null, + 'send_date' => $row['send_date'] ?? null, + 'shop_name' => $row['shop_name'] ?? null, + 'status' => in_array($st, ['Cancelled', 'Split', 'Merged'], true) ? $st : null, + 'online' => $this->excludedByLabel($row['labels'] ?? null), + ]; + } + + /** + * 本地订单镜像里已发货(有发货时间)的订单直接记下,返回还要去副本库查的订单号。 + * 镜像没建好或缺字段时整体退回副本库。 + * + * @param list $oids + * @return list + */ + private function loadOrderMetadataFromMirror(array $oids): array + { + if ($oids === [] || ! $this->orderMirrorReady()) { + return $oids; + } + $found = []; + try { + foreach (array_chunk($oids, 1000) as $chunk) { + $keys = array_map(static fn (string $o) => ctype_digit($o) ? (int) $o : $o, $chunk); + $rows = $this->orderMirror()->table('ops_jst_orders')->whereIn('o_id', $keys) + ->whereNotNull('send_date')->orderBy('Id') + ->get(['o_id', 'l_id', 'send_date', 'status', 'labels', 'shop_name']); + foreach ($rows as $row) { + $this->rememberOrderMetadata($row); + $found[(string) $row->o_id] = true; + } + } + } catch (\Throwable $e) { + // 镜像查不了不影响同步:剩下的全部走副本库 + $this->orderMirrorReady = false; + } + + return array_values(array_filter($oids, static fn (string $o): bool => ! isset($found[$o]))); + } + + private ?bool $orderMirrorReady = null; + + private function orderMirrorReady(): bool + { + if ($this->orderMirrorReady === null) { + try { + $schema = $this->orderMirror()->getSchemaBuilder(); + $this->orderMirrorReady = $schema->hasTable('ops_jst_orders') + && $schema->hasColumns('ops_jst_orders', ['o_id', 'l_id', 'send_date', 'status', 'labels', 'shop_name']); + } catch (\Throwable $e) { + $this->orderMirrorReady = false; + } + } + + return $this->orderMirrorReady; + } + + private function orderMirror(): \Illuminate\Database\ConnectionInterface + { + return DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + } + + /** 将订单元数据映射到发货明细,保留测试/兼容来源已提供的字段。 */ + private function mergeOrderMetadata(array $row): array + { + $oid = (string) ($row['inner_order_id'] ?? ''); + $metadata = $oid !== '' ? ($this->orderMetadata[$oid] ?? []) : []; + if (($row['jo_lid'] ?? '') === '' && ($metadata['l_id'] ?? '') !== '') { + $row['jo_lid'] = $metadata['l_id']; + } + if (($row['jo_send'] ?? '') === '' && ($metadata['send_date'] ?? '') !== '') { + $row['jo_send'] = $metadata['send_date']; + } + if (trim((string) ($row['shop_name'] ?? '')) === '' && ! empty($metadata['shop_name'])) { + $row['shop_name'] = $metadata['shop_name']; + } + // 订单状态/标签:取消/拆分/合并 与 订单级"线上发货"标签的排除判断用 + if (($row['jo_status'] ?? '') === '' && ($metadata['status'] ?? '') !== '') { + $row['jo_status'] = $metadata['status']; + } + if (($row['jo_labels'] ?? '') === '' && ! empty($metadata['online'])) { + $row['jo_labels'] = '线上发货'; + } + + return $row; + } + /** @return list> */ private function selectWithReconnect(string $sql, array $bindings): array { diff --git a/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php b/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php index f6bb3c77..88b46f2f 100644 --- a/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/ShippingReplicaSynchronizerTest.php @@ -151,6 +151,108 @@ class ShippingReplicaSynchronizerTest extends TestCase ); } + public function test_order_metadata_comes_from_local_order_mirror_and_only_unshipped_orders_hit_the_replica(): void + { + \Illuminate\Support\Facades\Schema::connection('business_mirror')->create('ops_jst_orders', function (\Illuminate\Database\Schema\Blueprint $t): void { + $t->unsignedBigInteger('Id')->primary(); + $t->unsignedBigInteger('o_id')->index(); + $t->string('l_id')->nullable(); + $t->dateTime('send_date')->nullable(); + $t->string('status')->nullable(); + $t->text('labels')->nullable(); + $t->string('shop_name')->nullable(); + }); + DB::connection('business_mirror')->table('ops_jst_orders')->insert([ + ['Id' => 1, 'o_id' => 1001, 'l_id' => 'MIRROR-1', 'send_date' => '2026-09-02 12:00:00', 'status' => 'Sent', 'labels' => null, 'shop_name' => '镜像店铺'], + ['Id' => 2, 'o_id' => 1002, 'l_id' => null, 'send_date' => null, 'status' => 'WaitConfirm', 'labels' => null, 'shop_name' => null], // 镜像还没发货时间 + ]); + $orderQueries = []; + $detailCalls = 0; + $upstream = $this->createMock(UpstreamReadOnlyQuery::class); + $upstream->method('select')->willReturnCallback(function (string $sql, array $bindings) use (&$orderQueries, &$detailCalls): array { + if (str_contains($sql, 'FROM rpt.jst_order_express_details e')) { + return $detailCalls++ === 0 ? [ + ['id' => 6001, 'inner_order_id' => '1001', 'send_time' => null, 'logistic_id' => ''], + ['id' => 6002, 'inner_order_id' => '1002', 'send_time' => null, 'logistic_id' => ''], + ] : []; + } + if (str_contains($sql, 'FROM rpt.jst_Orders om WHERE om.o_id IN')) { + $orderQueries[] = $bindings; + + return [['o_id' => '1002', 'l_id' => 'REPLICA-2', 'send_date' => '2026-09-03 08:00:00', 'shop_name' => '副本店铺']]; + } + + return []; + }); + $factory = $this->createMock(UpstreamReadOnlyQueryFactory::class); + $factory->method('forSource')->with('operations_replica')->willReturn($upstream); + + $result = (new ShippingReplicaSynchronizer($factory))->sync(Carbon::parse('2026-09-01'), Carbon::parse('2026-09-05'), 2000, null, true); + + $this->assertEquals([['1002']], $orderQueries); // 只有镜像里还没发货的订单去副本库查 + $this->assertSame(2, $result['processed']); + $shipping = DB::connection('business_mirror')->table('jst_oms_shipping'); + $this->assertSame('MIRROR-1', (clone $shipping)->where('source_id', 6001)->value('express_no')); + $this->assertSame('REPLICA-2', (clone $shipping)->where('source_id', 6002)->value('express_no')); + } + + public function test_windowed_scan_stops_after_many_pages_far_older_than_the_window(): void + { + $page = static fn (int $start, string $sendTime): array => array_map( + static fn (int $i): array => ['id' => $start - $i, 'inner_order_id' => '', 'send_time' => $sendTime, 'logistic_id' => ''], range(0, 1499)); + $detailCalls = 0; + $upstream = $this->createMock(UpstreamReadOnlyQuery::class); + $upstream->method('select')->willReturnCallback(function (string $sql) use (&$detailCalls, $page): array { + if (! str_contains($sql, 'FROM rpt.jst_order_express_details e')) { + return []; + } + $n = $detailCalls++; + if ($n >= 100) { + return []; + } + + // 第 1 页窗口内,之后全是窗口开始前一年多的老单 + return $page(1_000_000 - $n * 1500, $n === 0 ? '2026-09-02 10:00:00' : '2025-06-01 10:00:00'); + }); + $factory = $this->createMock(UpstreamReadOnlyQueryFactory::class); + $factory->method('forSource')->with('operations_replica')->willReturn($upstream); + + $sync = new ShippingReplicaSynchronizer($factory); + $sync->sync(Carbon::parse('2026-09-01'), Carbon::parse('2026-09-05'), 2000, null, true); + + $this->assertTrue($sync->earlyStopped); + $this->assertSame(41, $detailCalls); // 1 页窗口内 + 连续 40 页老单后停,不再往下读 + } + + #[DataProvider('earlyStopGuards')] + public function test_early_stop_does_not_truncate_unknown_dates_or_changes_only_scans(bool $changesOnly): void + { + $calls = 0; + $upstream = $this->createMock(UpstreamReadOnlyQuery::class); + $upstream->method('select')->willReturnCallback(function (string $sql) use (&$calls, $changesOnly): array { + if (! str_contains($sql, 'FROM rpt.jst_order_express_details e')) return []; + $page = $calls++; + if ($page >= 42) return []; + + return array_map(static fn (int $i): array => [ + 'id' => 1000000 - $page * 1500 - $i, 'inner_order_id' => '', 'logistic_id' => '', + 'send_time' => ! $changesOnly && $i === 0 ? null : '2025-06-01 10:00:00', + ], range(0, 1499)); + }); + $factory = $this->createMock(UpstreamReadOnlyQueryFactory::class); + $factory->method('forSource')->with('operations_replica')->willReturn($upstream); + $sync = new ShippingReplicaSynchronizer($factory); + $sync->sync(Carbon::parse('2026-09-01'), Carbon::parse('2026-09-05'), 2000, null, true, $changesOnly); + + $this->assertFalse($sync->earlyStopped); + $this->assertSame(43, $calls); + } + + public static function earlyStopGuards(): array + { + return ['unknown date' => [false], 'changes only' => [true]]; + } + public function test_windowed_outbound_lookup_preloads_date_range_and_reuses_cache_without_in_queries(): void { $from = '2026-09-22 00:00:00';