From 948ae22156442fae17829c21a057ce7316c708cd Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Thu, 3 Dec 2026 13:14:13 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E7=A7=91=E7=9B=AE=E6=98=A0=E5=B0=84):=20?= =?UTF-8?q?=E6=8C=81=E4=B9=85=E5=8C=96=E6=9C=AA=E6=98=A0=E5=B0=84=E6=B8=85?= =?UTF-8?q?=E5=8D=95=E5=BF=AB=E7=85=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Services/AccountMappingCoverage.php | 131 ++++++++++++++++-- .../financial-rules/account-mapping.blade.php | 20 ++- .../Business/AccountMappingPageTest.php | 2 + .../AccountMappingCoverageTest.php | 11 +- 4 files changed, 148 insertions(+), 16 deletions(-) diff --git a/modules/EcommerceFinance/Services/AccountMappingCoverage.php b/modules/EcommerceFinance/Services/AccountMappingCoverage.php index 6e341e5ef..6a8ebebd4 100644 --- a/modules/EcommerceFinance/Services/AccountMappingCoverage.php +++ b/modules/EcommerceFinance/Services/AccountMappingCoverage.php @@ -23,10 +23,14 @@ class AccountMappingCoverage private const CACHE_HOURS = 24; + private const SNAPSHOT_VERSION = 1; + private const STATUS_MINUTES = 30; private const REQUEST_STALE_MINUTES = 15; + private const RETRY_SECONDS = 8; + private const SOURCES = [ '淘系支付宝' => ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null], '淘系微信' => ['table' => 'taobao_wechat_bill_rows', 'date' => 'occurred_at', 'periods' => null], @@ -106,23 +110,39 @@ class AccountMappingCoverage public function missingForMonth(?string $month = null, bool $refresh = false): array { $period = $this->parseMonth($month); - $raw = Cache::get($this->rawCacheKey($period)); + $sourceKey = $this->rawCacheKey($period); + $snapshot = $this->readSnapshot($period, $sourceKey); $status = Cache::get($this->statusCacheKey($period), []); - if (! $refresh && is_array($raw)) { + if (! $refresh && $snapshot !== null) { return $this->missingPayload( $period, - $raw, - is_array($status) ? (string) ($status['refreshed_at'] ?? '') : '', + $snapshot['raw'], + $snapshot['refreshed_at'], ); } - if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'refreshing') { + $raw = Cache::get($sourceKey); + if (! $refresh && is_array($raw)) { + $refreshedAt = is_array($status) ? (string) ($status['refreshed_at'] ?? '') : ''; + $this->writeSnapshot($period, $sourceKey, $raw, $refreshedAt); + + return $this->missingPayload( + $period, + $raw, + $refreshedAt, + ); + } + + if (is_array($status) && ($status['status'] ?? '') === 'refreshing') { return $this->waitingPayload($period, 'refreshing'); } if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'failed') { return $this->waitingPayload($period, 'failed', (string) ($status['message'] ?? '')); } + if ($this->hasLiveRefreshRequest($period)) { + return $this->waitingPayload($period, 'refreshing'); + } $requested = $this->requestRefresh($period); if (($requested['status'] ?? '') === 'failed') { @@ -150,11 +170,14 @@ class AccountMappingCoverage ], now()->addMinutes(self::STATUS_MINUTES)); try { + $sourceKey = $this->rawCacheKey($period); $raw = $this->buildSourceCoverage($period); - Cache::put($this->rawCacheKey($period), $raw, now()->addHours(self::CACHE_HOURS)); + $refreshedAt = now()->toDateTimeString(); + Cache::put($sourceKey, $raw, now()->addHours(self::CACHE_HOURS)); + $this->writeSnapshot($period, $sourceKey, $raw, $refreshedAt); Cache::put($this->statusCacheKey($period), [ 'status' => 'ready', - 'refreshed_at' => now()->toDateTimeString(), + 'refreshed_at' => $refreshedAt, ], now()->addMinutes(self::STATUS_MINUTES)); return $raw; @@ -234,7 +257,7 @@ class AccountMappingCoverage 'pending_sources' => [], 'items' => [], 'months' => $this->monthOptions(), - 'retry_after' => 4, + 'retry_after' => self::RETRY_SECONDS, 'message' => $message, 'refreshed_at' => null, ]; @@ -353,6 +376,98 @@ class AccountMappingCoverage return storage_path('app/account-mapping/coverage-requests'); } + /** + * 持久化快照不放在 storage/framework/cache,避免每次发布 optimize:clear 后重建。 + * + * @return array{ + * raw: array{status:string,source_rows:int,pending_sources:list,pairs:list>}, + * refreshed_at:string + * }|null + */ + private function readSnapshot(string $period, string $sourceKey): ?array + { + $path = $this->snapshotPath($period, $sourceKey); + if (! File::isFile($path)) { + return null; + } + + try { + $snapshot = json_decode(File::get($path), true, 512, JSON_THROW_ON_ERROR); + if (! is_array($snapshot) + || (int) ($snapshot['version'] ?? 0) !== self::SNAPSHOT_VERSION + || (string) ($snapshot['month'] ?? '') !== $period + || (string) ($snapshot['source_key'] ?? '') !== $sourceKey + || ! is_array($snapshot['raw'] ?? null)) { + return null; + } + + $refreshedAt = (string) ($snapshot['refreshed_at'] ?? ''); + $refreshedAtDate = CarbonImmutable::parse($refreshedAt); + if ($refreshedAtDate->lt(now()->subHours(self::CACHE_HOURS))) { + return null; + } + + return [ + 'raw' => $snapshot['raw'], + 'refreshed_at' => $refreshedAt, + ]; + } catch (Throwable) { + return null; + } + } + + /** @param array{status:string,source_rows:int,pending_sources:list,pairs:list>} $raw */ + private function writeSnapshot(string $period, string $sourceKey, array $raw, string $refreshedAt): void + { + $directory = $this->snapshotDirectory(); + File::ensureDirectoryExists($directory, 0775, true); + $path = $this->snapshotPath($period, $sourceKey); + $temporary = $path . '.' . getmypid() . '.tmp'; + $payload = json_encode([ + 'version' => self::SNAPSHOT_VERSION, + 'month' => $period, + 'source_key' => $sourceKey, + 'refreshed_at' => $refreshedAt !== '' ? $refreshedAt : now()->toDateTimeString(), + 'raw' => $raw, + ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); + + if (File::put($temporary, $payload, true) === false || ! File::move($temporary, $path, true)) { + File::delete($temporary); + throw new RuntimeException('无法写入未映射清单快照。'); + } + + foreach (File::glob($directory . DIRECTORY_SEPARATOR . $period . '-*.json') ?: [] as $oldSnapshot) { + if ($oldSnapshot !== $path) { + File::delete($oldSnapshot); + } + } + } + + private function hasLiveRefreshRequest(string $period): bool + { + $staleBefore = now()->subMinutes(self::REQUEST_STALE_MINUTES)->getTimestamp(); + foreach (['.pending', '.running'] as $suffix) { + $path = $this->requestDirectory() . DIRECTORY_SEPARATOR . $period . $suffix; + if (File::isFile($path) && @filemtime($path) > $staleBefore) { + return true; + } + } + + return false; + } + + private function snapshotDirectory(): string + { + return storage_path('app/account-mapping/coverage-snapshots'); + } + + private function snapshotPath(string $period, string $sourceKey): string + { + return $this->snapshotDirectory() + . DIRECTORY_SEPARATOR + . $period . '-' . substr(hash('sha256', $sourceKey), 0, 16) . '.json'; + } + /** * @return array{ * status:string, diff --git a/resources/views/business/pages/financial-rules/account-mapping.blade.php b/resources/views/business/pages/financial-rules/account-mapping.blade.php index 29fca8df1..8d70fc6cd 100644 --- a/resources/views/business/pages/financial-rules/account-mapping.blade.php +++ b/resources/views/business/pages/financial-rules/account-mapping.blade.php @@ -816,7 +816,7 @@ @endforeach - +
{{ $coverageMonth }} @@ -1152,8 +1152,13 @@ url.searchParams.set('am_month', coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH); window.history.replaceState({}, '', url); } - if (selected === 'unmapped' && !coverageData && !coverageLoading) { + if (selected === 'unmapped' + && (!coverageData || coverageData.status === 'refreshing') + && !coverageLoading) { loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH); + } else if (selected !== 'unmapped' && coveragePollTimer) { + clearTimeout(coveragePollTimer); + coveragePollTimer = null; } } @@ -1166,7 +1171,7 @@ coverageSummaryEl.appendChild(title); if (data && (data.status === 'refreshing' || data.status === 'failed')) { var state = document.createElement('span'); - state.textContent = data.status === 'refreshing' ? '后台生成中……' : '生成失败'; + state.textContent = data.status === 'refreshing' ? '生成一次中……' : '生成失败'; if (data.status === 'failed') { state.className = 'is-warning'; } coverageSummaryEl.appendChild(state); return; @@ -1256,7 +1261,7 @@ coverageCountEl.textContent = '…'; coverageStateEl.hidden = false; coverageStateEl.className = 'am-coverage-state'; - coverageStateEl.textContent = '正在后台生成该月未映射清单。账单数据量较大,完成后会自动刷新。'; + coverageStateEl.textContent = '正在生成一次该月未映射清单;完成后会持久缓存,之后再次访问直接读取。'; coverageTableWrapEl.hidden = true; renderCoverageSummary(coverageData); return; @@ -1266,7 +1271,7 @@ coverageCountEl.textContent = '—'; coverageStateEl.hidden = false; coverageStateEl.className = 'am-coverage-state am-coverage-state--error'; - coverageStateEl.textContent = coverageData.message || '该月未映射清单生成失败,请点击“重新读取”重试。'; + coverageStateEl.textContent = coverageData.message || '该月未映射清单生成失败,请点击“生成最新清单”重试。'; coverageTableWrapEl.hidden = true; renderCoverageSummary(coverageData); return; @@ -1331,7 +1336,9 @@ }).finally(function () { coverageLoading = false; renderCoverage(); - if (coverageData && coverageData.status === 'refreshing') { + var unmappedButton = document.querySelector('[data-am-view-tab="unmapped"]'); + var unmappedSelected = unmappedButton?.getAttribute('aria-selected') === 'true'; + if (coverageData && coverageData.status === 'refreshing' && unmappedSelected) { var retrySeconds = Math.max(2, Number(coverageData.retry_after || 4)); coveragePollTimer = setTimeout(function () { coveragePollTimer = null; @@ -2231,7 +2238,6 @@ // 平台 / 大类 的候选过去由 Blade 直接渲染,现在改成多选组件后统一由这里灌一次 rebuildFilterOptions(); selectView(INITIAL_VIEW, false); - loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true, false); // 后台预取账套科目清单(160KB 左右)。不做这一步的话,第一次点「编辑」要等它下载完 // 才有反应,用户会以为按钮坏了。 diff --git a/tests/Feature/Business/AccountMappingPageTest.php b/tests/Feature/Business/AccountMappingPageTest.php index e018d4770..9592841ad 100644 --- a/tests/Feature/Business/AccountMappingPageTest.php +++ b/tests/Feature/Business/AccountMappingPageTest.php @@ -105,6 +105,8 @@ class AccountMappingPageTest extends FeatureTestCase ->assertSee('id="amCoveragePanel"', false) ->assertSee('id="amCoverageMonth"', false) ->assertSee('data-am-coverage-add', false) + ->assertSee('生成最新清单') + ->assertSee('完成后会持久缓存,之后再次访问直接读取', false) ->assertSee('data-am-memo-picker', false) ->assertSee('输入新备注,或点 ▾ 选择', false) ->assertSee('商品名包含词;不限填 -', false) diff --git a/tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php b/tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php index 7ff7d327e..db4899a57 100644 --- a/tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php +++ b/tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php @@ -74,7 +74,7 @@ class AccountMappingCoverageTest extends TestCase $coverage = app(AccountMappingCoverage::class); $cold = $coverage->missingForMonth('2026-11'); $this->assertSame('refreshing', $cold['status']); - $this->assertSame(4, $cold['retry_after']); + $this->assertSame(8, $cold['retry_after']); $request = $coverage->claimPendingRefresh(); $this->assertNotNull($request); @@ -99,6 +99,15 @@ class AccountMappingCoverageTest extends TestCase $this->assertNotContains('上期项目', array_column($first['items'], 'item')); $this->assertNotContains('wx商户费', array_column($first['items'], 'item')); + Cache::flush(); + $persisted = app(AccountMappingCoverage::class)->missingForMonth('2026-11'); + $this->assertSame('ready', $persisted['status']); + $this->assertSame(9, $persisted['source_rows']); + $this->assertSame($this->missingSignature($first['items']), $this->missingSignature($persisted['items'])); + $this->assertCount(1, glob( + $this->storageRoot . '/app/account-mapping/coverage-snapshots/*.json', + ) ?: []); + $this->rule($store, '天猫', '商家货款入账'); $second = app(AccountMappingCoverage::class)->missingForMonth('2026-11'); -- 2.47.2