From 8d2c59070c3b7bac174f7db714de0b37b331e78e Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Thu, 3 Dec 2026 09:10:07 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=9C=AA=E6=98=A0=E5=B0=84=E6=B8=85?= =?UTF-8?q?=E5=8D=95=E6=94=B9=E7=94=B1=E5=8F=97=E9=99=90=E6=89=B9=E5=A4=84?= =?UTF-8?q?=E7=90=86=E5=88=B7=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RefreshAccountMappingCoverage.php | 27 +++- deploy/activate-incremental-release.sh | 2 + deploy/activate-release.sh | 2 + deploy/run-finance-batch.sh | 21 ++- .../Services/AccountMappingCoverage.php | 137 +++++++++++++++--- .../financial-rules/account-mapping.blade.php | 5 + .../Business/AccountMappingPageTest.php | 1 + .../Deployment/BusinessMirrorScheduleTest.php | 23 +++ .../AccountMappingCoverageTest.php | 23 ++- 9 files changed, 218 insertions(+), 23 deletions(-) diff --git a/app/Console/Commands/RefreshAccountMappingCoverage.php b/app/Console/Commands/RefreshAccountMappingCoverage.php index 53ede92fa..6a962f539 100644 --- a/app/Console/Commands/RefreshAccountMappingCoverage.php +++ b/app/Console/Commands/RefreshAccountMappingCoverage.php @@ -11,30 +11,50 @@ use Throwable; */ class RefreshAccountMappingCoverage extends Command { - protected $signature = 'account-mapping:refresh-coverage {month? : 账单月份,格式 YYYY-MM}'; + protected $signature = 'account-mapping:refresh-coverage + {month? : 账单月份,格式 YYYY-MM} + {--pending : 处理页面登记的下一个刷新请求}'; protected $description = '刷新科目映射的未映射账单项目清单'; public function handle(AccountMappingCoverage $coverage): int { + $runningPath = null; $month = trim((string) $this->argument('month')) ?: null; + if ($this->option('pending')) { + $request = $coverage->claimPendingRefresh(); + if ($request === null) { + $this->line('没有待处理的未映射清单刷新请求。'); + + return self::SUCCESS; + } + $month = $request['month']; + $runningPath = $request['path']; + } try { $raw = $coverage->refreshForMonth($month); if (($raw['status'] ?? '') === 'refreshing') { $this->warn('已有刷新任务正在执行,本次跳过。'); + if ($runningPath !== null) { + $coverage->requeuePendingRefresh($runningPath); + } return self::SUCCESS; } $summary = $coverage->missingForMonth($month); $this->info(sprintf( - '%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d。', + '%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。', (string) $summary['month'], (int) $summary['missing_item_count'], (int) $summary['missing_row_count'], (int) $summary['source_rows'], + memory_get_peak_usage(true) / 1048576, )); + if ($runningPath !== null) { + $coverage->finishPendingRefresh($runningPath, true); + } return self::SUCCESS; } catch (Throwable $exception) { @@ -42,6 +62,9 @@ class RefreshAccountMappingCoverage extends Command if ($month !== null) { $coverage->markFailed($month, $exception->getMessage()); } + if ($runningPath !== null) { + $coverage->finishPendingRefresh($runningPath, false, $exception->getMessage()); + } $this->error('未映射账单项目刷新失败:' . $exception->getMessage()); return self::FAILURE; diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index b2218f4ea..6be7d2e0f 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -263,6 +263,8 @@ CRON_TZ=Asia/Shanghai */15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 +# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。 +* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1 # 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index 4b380ebb4..70c3dd9ba 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -267,6 +267,8 @@ CRON_TZ=Asia/Shanghai */15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 +# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。 +* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1 # 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。 diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index d2b81db3c..f13d5a3b5 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -12,7 +12,7 @@ case "${1:-}" in planting-reimbursement:auto-confirm) is_import=1 ;; jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;; - jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; + jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|account-mapping:refresh-coverage|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; *) echo 'Unsupported finance batch command' >&2; exit 64 ;; esac case "${1:-}" in @@ -58,6 +58,15 @@ if [ "$1" = 'business-mirror:process-ding-refresh-requests' ]; then pending_request="$(find "$storage_root/app/ding-process-refresh" -maxdepth 1 -type f -name '*.pending' -print -quit)" [ -n "$pending_request" ] || exit 0 fi +if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = '--pending' ]; then + storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" + [ -n "$storage_root" ] || exit 0 + pending_request="$(find "$storage_root/app/account-mapping/coverage-requests" -maxdepth 1 -type f -name '*.pending' -print -quit 2>/dev/null || true)" + if [ -z "$pending_request" ]; then + pending_request="$(find "$storage_root/app/account-mapping/coverage-requests" -maxdepth 1 -type f -name '*.running' -mmin +15 -print -quit 2>/dev/null || true)" + fi + [ -n "$pending_request" ] || exit 0 +fi if [ "$1" = 'ding-invoices:process-refresh-requests' ]; then storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" [ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0 @@ -106,4 +115,14 @@ if [ "$1" = 'jushuitan:sync-shipping' ]; then sleep "${CAIWU_JST_SYNC_RETRY_WAIT:-300}" done fi +if [ "$1" = 'account-mapping:refresh-coverage' ]; then + container_name="caiwu_account_mapping_coverage_$$" + cleanup_coverage_batch() { + docker rm --force "$container_name" >/dev/null 2>&1 || true + } + trap cleanup_coverage_batch EXIT INT TERM + /usr/bin/timeout 1800 docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps \ + --name "$container_name" batch "$@" + exit $? +fi docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps batch "$@" diff --git a/modules/EcommerceFinance/Services/AccountMappingCoverage.php b/modules/EcommerceFinance/Services/AccountMappingCoverage.php index 2fcd41368..6e341e5ef 100644 --- a/modules/EcommerceFinance/Services/AccountMappingCoverage.php +++ b/modules/EcommerceFinance/Services/AccountMappingCoverage.php @@ -5,9 +5,8 @@ namespace Modules\EcommerceFinance\Services; use Carbon\CarbonImmutable; use Illuminate\Database\DatabaseManager; use Illuminate\Support\Facades\Cache; -use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\File; use RuntimeException; -use Symfony\Component\Process\Process; use Throwable; /** @@ -26,6 +25,8 @@ class AccountMappingCoverage private const STATUS_MINUTES = 30; + private const REQUEST_STALE_MINUTES = 15; + private const SOURCES = [ '淘系支付宝' => ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null], '淘系微信' => ['table' => 'taobao_wechat_bill_rows', 'date' => 'occurred_at', 'periods' => null], @@ -106,12 +107,16 @@ class AccountMappingCoverage { $period = $this->parseMonth($month); $raw = Cache::get($this->rawCacheKey($period)); + $status = Cache::get($this->statusCacheKey($period), []); if (! $refresh && is_array($raw)) { - return $this->missingPayload($period, $raw); + return $this->missingPayload( + $period, + $raw, + is_array($status) ? (string) ($status['refreshed_at'] ?? '') : '', + ); } - $status = Cache::get($this->statusCacheKey($period), []); if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'refreshing') { return $this->waitingPayload($period, 'refreshing'); } @@ -182,7 +187,7 @@ class AccountMappingCoverage * @param array{status:string,source_rows:int,pending_sources:list,pairs:list>} $raw * @return array */ - private function missingPayload(string $period, array $raw): array + private function missingPayload(string $period, array $raw, string $refreshedAt = ''): array { $mapping = $this->coverageMappingKeys($this->store->all()); $items = []; @@ -213,6 +218,7 @@ class AccountMappingCoverage 'months' => $this->monthOptions(), 'retry_after' => null, 'message' => '', + 'refreshed_at' => $refreshedAt, ]; } @@ -230,6 +236,7 @@ class AccountMappingCoverage 'months' => $this->monthOptions(), 'retry_after' => 4, 'message' => $message, + 'refreshed_at' => null, ]; } @@ -241,29 +248,111 @@ class AccountMappingCoverage 'started_at' => now()->toDateTimeString(), ], now()->addMinutes(self::STATUS_MINUTES)); - if (app()->environment('testing')) { - return ['status' => 'refreshing', 'message' => '']; - } - try { - $php = escapeshellarg(PHP_BINARY ?: 'php'); - $command = 'cd ' . escapeshellarg(base_path()) - . ' && nohup ' . $php . ' artisan account-mapping:refresh-coverage ' - . escapeshellarg($period) . ' >/dev/null 2>&1 &'; - Process::fromShellCommandline($command, base_path()) - ->disableOutput() - ->setTimeout(10) - ->run(); + $directory = $this->requestDirectory(); + File::ensureDirectoryExists($directory, 0775, true); + $pending = $directory . DIRECTORY_SEPARATOR . $period . '.pending'; + $temporary = $pending . '.' . getmypid() . '.tmp'; + $payload = json_encode([ + 'month' => $period, + 'requested_at' => now()->toDateTimeString(), + ], JSON_UNESCAPED_UNICODE); + if ($payload === false || File::put($temporary, $payload, true) === false) { + throw new RuntimeException('无法写入未映射清单刷新请求。'); + } + File::move($temporary, $pending, true); } catch (Throwable $exception) { $this->markFailed($period, $exception->getMessage()); - Log::warning('科目映射未映射清单后台刷新启动失败:' . $exception->getMessage()); + report($exception); - return ['status' => 'failed', 'message' => '后台刷新进程启动失败,请稍后重试。']; + return ['status' => 'failed', 'message' => '刷新请求写入失败,请稍后重试。']; } return ['status' => 'refreshing', 'message' => '']; } + /** @return array{month:string,path:string}|null */ + public function claimPendingRefresh(): ?array + { + $directory = $this->requestDirectory(); + if (! File::isDirectory($directory)) { + return null; + } + + $staleBefore = now()->subMinutes(self::REQUEST_STALE_MINUTES)->getTimestamp(); + foreach (File::glob($directory . DIRECTORY_SEPARATOR . '*.running') as $running) { + if (@filemtime($running) > $staleBefore) { + continue; + } + $month = basename((string) $running, '.running'); + if ($this->isValidMonth($month)) { + File::move($running, $directory . DIRECTORY_SEPARATOR . $month . '.pending', true); + } + } + + $pendingFiles = File::glob($directory . DIRECTORY_SEPARATOR . '*.pending') ?: []; + sort($pendingFiles); + foreach ($pendingFiles as $pending) { + $month = basename((string) $pending, '.pending'); + if (! $this->isValidMonth($month)) { + continue; + } + $running = $directory . DIRECTORY_SEPARATOR . $month . '.running'; + if (File::exists($running) && @filemtime($running) > $staleBefore) { + continue; + } + File::move($pending, $running, true); + + return ['month' => $month, 'path' => $running]; + } + + return null; + } + + public function finishPendingRefresh(string $runningPath, bool $succeeded, string $error = ''): void + { + if (! File::exists($runningPath)) { + return; + } + + if ($succeeded) { + File::delete($runningPath); + + return; + } + + $directory = dirname($runningPath); + $month = basename($runningPath, '.running'); + $failed = $directory . DIRECTORY_SEPARATOR . $month . '.failed'; + File::move($runningPath, $failed, true); + File::put($failed, json_encode([ + 'month' => $month, + 'failed_at' => now()->toDateTimeString(), + 'message' => $error, + ], JSON_UNESCAPED_UNICODE), true); + } + + public function requeuePendingRefresh(string $runningPath): void + { + if (! File::exists($runningPath)) { + return; + } + $month = basename($runningPath, '.running'); + if (! $this->isValidMonth($month)) { + return; + } + File::move( + $runningPath, + dirname($runningPath) . DIRECTORY_SEPARATOR . $month . '.pending', + true, + ); + } + + public function requestDirectory(): string + { + return storage_path('app/account-mapping/coverage-requests'); + } + /** * @return array{ * status:string, @@ -501,4 +590,14 @@ class AccountMappingCoverage return $month; } + + private function isValidMonth(string $month): bool + { + try { + return preg_match('/^\d{4}-\d{2}$/', $month) === 1 + && CarbonImmutable::createFromFormat('!Y-m', $month)->format('Y-m') === $month; + } catch (Throwable) { + return false; + } + } } 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 c58fd802e..44d0f209d 100644 --- a/resources/views/business/pages/financial-rules/account-mapping.blade.php +++ b/resources/views/business/pages/financial-rules/account-mapping.blade.php @@ -1091,6 +1091,11 @@ warning.textContent = '待同步:' + data.pending_sources.join('、'); coverageSummaryEl.appendChild(warning); } + if (data && data.refreshed_at) { + var refreshedAt = document.createElement('span'); + refreshedAt.textContent = '更新于 ' + data.refreshed_at; + coverageSummaryEl.appendChild(refreshedAt); + } } function coverageRowHtml(row, index) { diff --git a/tests/Feature/Business/AccountMappingPageTest.php b/tests/Feature/Business/AccountMappingPageTest.php index 6bae6b6b1..c0b0a283b 100644 --- a/tests/Feature/Business/AccountMappingPageTest.php +++ b/tests/Feature/Business/AccountMappingPageTest.php @@ -105,6 +105,7 @@ class AccountMappingPageTest extends FeatureTestCase ->assertSee('id="amCoveragePanel"', false) ->assertSee('id="amCoverageMonth"', false) ->assertSee('data-am-coverage-add', false) + ->assertSee('class="upstream-data-table am-coverage-table" data-finance-table-native', false) // 序号列表头固定为「序号」且宽度 3.5rem:2.5rem 时三位数会被省略号截成「1…」 ->assertSee('class="am-index" style="width:3.5rem;">序号', false) // ENDPOINT 经 @json 输出,斜杠会被转义成 \/,所以只断言变量名 diff --git a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php index d9932ea7d..e460d49a9 100644 --- a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php +++ b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php @@ -114,6 +114,12 @@ class BusinessMirrorScheduleTest extends TestCase $contents, $script, ); + $this->assertStringContainsString( + '* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock ' + . '/bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet', + $contents, + $script, + ); $this->assertStringContainsString( "40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet'", $contents, @@ -209,6 +215,23 @@ class BusinessMirrorScheduleTest extends TestCase "pending_request=\"\$(find \"\$storage_root/app/ding-process-refresh\" -maxdepth 1 -type f -name '*.pending' -print -quit)\"", $contents, ); + $this->assertStringContainsString( + "if [ \"\$1\" = 'account-mapping:refresh-coverage' ] && [ \"\${2:-}\" = '--pending' ]; then", + $contents, + ); + $this->assertStringContainsString( + "find \"\$storage_root/app/account-mapping/coverage-requests\" -maxdepth 1 -type f -name '*.pending'", + $contents, + ); + $this->assertStringContainsString( + "find \"\$storage_root/app/account-mapping/coverage-requests\" -maxdepth 1 -type f -name '*.running' -mmin +15", + $contents, + ); + $this->assertStringContainsString( + '/usr/bin/timeout 1800 docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps', + $contents, + ); + $this->assertStringContainsString('--name "$container_name" batch "$@"', $contents); } public function test_release_scripts_install_supplier_statement_reminder_cron(): void diff --git a/tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php b/tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php index 89bec8c7e..7ff7d327e 100644 --- a/tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php +++ b/tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php @@ -76,7 +76,14 @@ class AccountMappingCoverageTest extends TestCase $this->assertSame('refreshing', $cold['status']); $this->assertSame(4, $cold['retry_after']); - $coverage->refreshForMonth('2026-11'); + $request = $coverage->claimPendingRefresh(); + $this->assertNotNull($request); + $this->assertSame('2026-11', $request['month']); + $this->assertFileExists($request['path']); + $coverage->refreshForMonth($request['month']); + $coverage->finishPendingRefresh($request['path'], true); + $this->assertFileDoesNotExist($request['path']); + $this->assertSame([], glob($coverage->requestDirectory() . '/*.pending') ?: []); $first = $coverage->missingForMonth('2026-11'); $this->assertSame('ready', $first['status']); @@ -100,6 +107,20 @@ class AccountMappingCoverageTest extends TestCase $this->assertNotContains('商家货款入账', array_column($second['items'], 'item')); } + public function test_interrupted_refresh_request_is_recovered_after_stale_timeout(): void + { + $coverage = app(AccountMappingCoverage::class); + $coverage->missingForMonth('2026-11'); + $claimed = $coverage->claimPendingRefresh(); + $this->assertNotNull($claimed); + + touch($claimed['path'], now()->subMinutes(20)->getTimestamp()); + $recovered = $coverage->claimPendingRefresh(); + $this->assertNotNull($recovered); + $this->assertSame('2026-11', $recovered['month']); + $coverage->finishPendingRefresh($recovered['path'], true); + } + private function rule(AccountMappingStore $store, string $platform, string $item): void { $store->create([