From dc6dc8bca51a7dd2cc1ac19e26f745425f076c8a Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Wed, 2 Dec 2026 18:15:01 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E7=A7=91=E7=9B=AE?= =?UTF-8?q?=E6=98=A0=E5=B0=84=E6=9C=AA=E6=98=A0=E5=B0=84=E8=B4=A6=E5=8D=95?= =?UTF-8?q?=E9=A1=B9=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RefreshAccountMappingCoverage.php | 50 +++ .../Business/AccountMappingActions.php | 2 + .../Services/AccountMappingCoverage.php | 392 ++++++++++++------ .../financial-rules/account-mapping.blade.php | 81 +++- .../Business/AccountMappingPageTest.php | 2 +- .../AccountMappingCoverageTest.php | 17 +- 6 files changed, 404 insertions(+), 140 deletions(-) create mode 100644 app/Console/Commands/RefreshAccountMappingCoverage.php diff --git a/app/Console/Commands/RefreshAccountMappingCoverage.php b/app/Console/Commands/RefreshAccountMappingCoverage.php new file mode 100644 index 000000000..53ede92fa --- /dev/null +++ b/app/Console/Commands/RefreshAccountMappingCoverage.php @@ -0,0 +1,50 @@ +argument('month')) ?: null; + + try { + $raw = $coverage->refreshForMonth($month); + if (($raw['status'] ?? '') === 'refreshing') { + $this->warn('已有刷新任务正在执行,本次跳过。'); + + return self::SUCCESS; + } + + $summary = $coverage->missingForMonth($month); + $this->info(sprintf( + '%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d。', + (string) $summary['month'], + (int) $summary['missing_item_count'], + (int) $summary['missing_row_count'], + (int) $summary['source_rows'], + )); + + return self::SUCCESS; + } catch (Throwable $exception) { + report($exception); + if ($month !== null) { + $coverage->markFailed($month, $exception->getMessage()); + } + $this->error('未映射账单项目刷新失败:' . $exception->getMessage()); + + return self::FAILURE; + } + } +} diff --git a/app/Http/Controllers/Business/AccountMappingActions.php b/app/Http/Controllers/Business/AccountMappingActions.php index cb73d748b..425b713e5 100644 --- a/app/Http/Controllers/Business/AccountMappingActions.php +++ b/app/Http/Controllers/Business/AccountMappingActions.php @@ -77,11 +77,13 @@ class AccountMappingActions extends Controller { $data = $request->validate([ 'month' => ['nullable', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'], + 'refresh' => ['nullable', 'boolean'], ]); try { return response()->json($this->coverage->missingForMonth( trim((string) ($data['month'] ?? '')) ?: null, + (bool) ($data['refresh'] ?? false), )); } catch (\InvalidArgumentException $exception) { throw ValidationException::withMessages(['month' => $exception->getMessage()]); diff --git a/modules/EcommerceFinance/Services/AccountMappingCoverage.php b/modules/EcommerceFinance/Services/AccountMappingCoverage.php index 21bff7476..2fcd41368 100644 --- a/modules/EcommerceFinance/Services/AccountMappingCoverage.php +++ b/modules/EcommerceFinance/Services/AccountMappingCoverage.php @@ -5,20 +5,26 @@ namespace Modules\EcommerceFinance\Services; use Carbon\CarbonImmutable; use Illuminate\Database\DatabaseManager; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Log; use RuntimeException; +use Symfony\Component\Process\Process; use Throwable; /** * 从已导入账单反推「平台 + 账单项目」覆盖情况。 * - * 原始账单项目按月份聚合后缓存;每次请求再用当前科目映射过滤。 - * 因此补完一条映射后,不用重新扫描数百万行账单就能立刻从待补清单消失。 + * 原始账单项目由后台命令按月份聚合后缓存,页面只读缓存并用当前科目映射过滤。 + * 因此页面请求不会被数百万行账单扫描卡住;补完一条映射后也能立刻从待补清单消失。 */ class AccountMappingCoverage { - private const CACHE_PREFIX = 'account-mapping-coverage-source:v1:'; + private const CACHE_PREFIX = 'account-mapping-coverage-source:v3:'; - private const CACHE_MINUTES = 10; + private const STATUS_PREFIX = 'account-mapping-coverage-status:v1:'; + + private const CACHE_HOURS = 24; + + private const STATUS_MINUTES = 30; private const SOURCES = [ '淘系支付宝' => ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null], @@ -96,16 +102,93 @@ class AccountMappingCoverage * months:list * } */ - public function missingForMonth(?string $month = null): array + public function missingForMonth(?string $month = null, bool $refresh = false): array { $period = $this->parseMonth($month); - $raw = $this->sourceCoverage($period); - [$exact, $normalized] = $this->coverageMappingKeys($this->store->all()); + $raw = Cache::get($this->rawCacheKey($period)); + if (! $refresh && is_array($raw)) { + return $this->missingPayload($period, $raw); + } + + $status = Cache::get($this->statusCacheKey($period), []); + if (! $refresh && 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'] ?? '')); + } + + $requested = $this->requestRefresh($period); + if (($requested['status'] ?? '') === 'failed') { + return $this->waitingPayload($period, 'failed', (string) ($requested['message'] ?? '')); + } + + return $this->waitingPayload($period, 'refreshing'); + } + + /** + * 后台命令使用:重建某月账单项目聚合,并写入长期缓存。 + * + * @return array{status:string,source_rows:int,pending_sources:list,pairs:list>} + */ + public function refreshForMonth(?string $month = null): array + { + $period = $this->parseMonth($month); + $lock = Cache::lock('account-mapping-coverage-refresh:' . $period, 900); + + try { + return $lock->block(20, function () use ($period): array { + Cache::put($this->statusCacheKey($period), [ + 'status' => 'refreshing', + 'started_at' => now()->toDateTimeString(), + ], now()->addMinutes(self::STATUS_MINUTES)); + + try { + $raw = $this->buildSourceCoverage($period); + Cache::put($this->rawCacheKey($period), $raw, now()->addHours(self::CACHE_HOURS)); + Cache::put($this->statusCacheKey($period), [ + 'status' => 'ready', + 'refreshed_at' => now()->toDateTimeString(), + ], now()->addMinutes(self::STATUS_MINUTES)); + + return $raw; + } catch (Throwable $exception) { + $this->markFailed($period, $exception->getMessage()); + throw $exception; + } + }); + } catch (\Illuminate\Contracts\Cache\LockTimeoutException) { + return [ + 'status' => 'refreshing', + 'source_rows' => 0, + 'pending_sources' => [], + 'pairs' => [], + ]; + } + } + + public function markFailed(string $month, string $message): void + { + $period = $this->parseMonth($month); + Cache::put($this->statusCacheKey($period), [ + 'status' => 'failed', + 'message' => $message, + 'failed_at' => now()->toDateTimeString(), + ], now()->addMinutes(self::STATUS_MINUTES)); + } + + /** + * @param array{status:string,source_rows:int,pending_sources:list,pairs:list>} $raw + * @return array + */ + private function missingPayload(string $period, array $raw): array + { + $mapping = $this->coverageMappingKeys($this->store->all()); $items = []; $missingRows = 0; foreach ($raw['pairs'] as $pair) { - if ($this->isMapped($pair, $exact, $normalized)) { + if ($this->isMapped($pair, $mapping)) { continue; } @@ -128,9 +211,59 @@ class AccountMappingCoverage 'pending_sources' => $raw['pending_sources'], 'items' => $items, 'months' => $this->monthOptions(), + 'retry_after' => null, + 'message' => '', ]; } + /** @return array */ + private function waitingPayload(string $period, string $status, string $message = ''): array + { + return [ + 'status' => $status, + 'month' => $period, + 'source_rows' => 0, + 'missing_item_count' => 0, + 'missing_row_count' => 0, + 'pending_sources' => [], + 'items' => [], + 'months' => $this->monthOptions(), + 'retry_after' => 4, + 'message' => $message, + ]; + } + + /** @return array{status:string,message:string} */ + private function requestRefresh(string $period): array + { + Cache::put($this->statusCacheKey($period), [ + 'status' => 'refreshing', + '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(); + } catch (Throwable $exception) { + $this->markFailed($period, $exception->getMessage()); + Log::warning('科目映射未映射清单后台刷新启动失败:' . $exception->getMessage()); + + return ['status' => 'failed', 'message' => '后台刷新进程启动失败,请稍后重试。']; + } + + return ['status' => 'refreshing', 'message' => '']; + } + /** * @return array{ * status:string, @@ -139,7 +272,104 @@ class AccountMappingCoverage * pairs:list> * } */ - private function sourceCoverage(string $month): array + private function buildSourceCoverage(string $month): array + { + $start = CarbonImmutable::createFromFormat('!Y-m', $month)->startOfMonth(); + $end = $start->endOfMonth(); + $connection = $this->databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + $schema = $connection->getSchemaBuilder(); + $pairs = []; + $sourceRows = 0; + $pendingSources = []; + + foreach (self::SOURCES as $label => $source) { + $table = (string) $source['table']; + if (! $schema->hasTable($table)) { + throw new RuntimeException('账单表尚未迁移:' . $table); + } + + $query = $connection->table($table); + $dateColumn = (string) $source['date']; + if ($dateColumn === 'bill_date') { + $query->whereBetween($dateColumn, [$start->toDateString(), $end->toDateString()]); + } else { + $query->whereBetween($dateColumn, [ + $start->toDateString() . ' 00:00:00', + $end->toDateString() . ' 23:59:59', + ]); + } + + if ($source['periods'] !== null) { + $generations = $this->generations( + (string) $source['periods'], + $start->toDateString(), + $end->toDateString(), + ); + if ($generations === []) { + $pendingSources[] = $label; + continue; + } + $query->whereIn('generation', $generations); + } + + $platformExpression = $this->platformSql($connection); + $itemExpression = $this->normalizedItemSql(); + $groups = $query + ->selectRaw($platformExpression . ' AS platform, ' . $itemExpression . ' AS item') + ->selectRaw('COUNT(*) AS source_rows, COUNT(DISTINCT store_name) AS store_count') + ->groupByRaw($platformExpression . ', ' . $itemExpression) + ->cursor(); + + foreach ($groups as $group) { + $rows = (int) $group->source_rows; + $sourceRows += $rows; + $item = trim((string) $group->item); + $displayItem = $item === '' ? '(未填写账单项目)' : $item; + $platform = trim((string) $group->platform); + $key = $platform . "\0" . $displayItem; + + if (! isset($pairs[$key])) { + $pairs[$key] = [ + 'platform' => $platform, + 'platform_label' => $platform === '' ? '未识别平台' : $platform, + 'item' => $displayItem, + 'source_rows' => 0, + 'store_count' => 0, + 'source_labels' => [], + 'raw_items' => [], + ]; + } + + $pairs[$key]['source_rows'] += $rows; + $pairs[$key]['source_labels'][$label] = ($pairs[$key]['source_labels'][$label] ?? 0) + $rows; + $pairs[$key]['raw_items'][$displayItem] = true; + $pairs[$key]['store_count'] = max( + (int) $pairs[$key]['store_count'], + (int) $group->store_count, + ); + } + } + + foreach ($pairs as &$pair) { + $pair['raw_items'] = array_values(array_filter( + array_keys($pair['raw_items']), + static fn (string $item): bool => $item !== '', + )); + $pair['source_labels'] = array_keys($pair['source_labels']); + } + unset($pair); + + return [ + 'status' => $sourceRows > 0 ? 'ready' : 'unavailable', + 'source_rows' => $sourceRows, + 'pending_sources' => $pendingSources, + 'pairs' => array_values($pairs), + ]; + } + + private function rawCacheKey(string $month): string { $start = CarbonImmutable::createFromFormat('!Y-m', $month)->startOfMonth(); $end = $start->endOfMonth(); @@ -156,140 +386,39 @@ class AccountMappingCoverage )); } - $cacheKey = self::CACHE_PREFIX . $month . ':' . hash('sha256', implode('|', $parts)); - - return Cache::remember($cacheKey, now()->addMinutes(self::CACHE_MINUTES), function () use ($start, $end): array { - $connection = $this->databases->connection( - (string) config('upstream_mirrors.connection', 'business_mirror'), - ); - $schema = $connection->getSchemaBuilder(); - $pairs = []; - $sourceRows = 0; - $pendingSources = []; - - foreach (self::SOURCES as $label => $source) { - $table = (string) $source['table']; - if (! $schema->hasTable($table)) { - throw new RuntimeException('账单表尚未迁移:' . $table); - } - - $query = $connection->table($table); - $dateColumn = (string) $source['date']; - if ($dateColumn === 'bill_date') { - $query->whereBetween($dateColumn, [$start->toDateString(), $end->toDateString()]); - } else { - $query->whereBetween($dateColumn, [ - $start->toDateString() . ' 00:00:00', - $end->toDateString() . ' 23:59:59', - ]); - } - - if ($source['periods'] !== null) { - $generations = $this->generations( - (string) $source['periods'], - $start->toDateString(), - $end->toDateString(), - ); - if ($generations === []) { - $pendingSources[] = $label; - continue; - } - $query->whereIn('generation', $generations); - } - - $groups = $query - ->select(['store_name', 'bill_item']) - ->selectRaw('COUNT(*) AS source_rows') - ->groupBy('store_name', 'bill_item') - ->cursor(); - - foreach ($groups as $group) { - $rows = (int) $group->source_rows; - $sourceRows += $rows; - $rawItem = trim((string) $group->bill_item); - $displayItem = $rawItem === '' ? '(未填写账单项目)' : $this->normalizeItem($rawItem); - $store = trim((string) $group->store_name); - $platform = $this->platformFromStore($store); - $key = $platform . "\0" . $displayItem; - - if (! isset($pairs[$key])) { - $pairs[$key] = [ - 'platform' => $platform, - 'platform_label' => $platform === '' ? '未识别平台' : $platform, - 'item' => $displayItem, - 'source_rows' => 0, - 'store_count' => 0, - 'store_samples' => [], - 'source_labels' => [], - 'raw_items' => [], - ]; - } - - $pairs[$key]['source_rows'] += $rows; - $pairs[$key]['source_labels'][$label] = ($pairs[$key]['source_labels'][$label] ?? 0) + $rows; - $pairs[$key]['raw_items'][$rawItem] = true; - if ($store !== '' && ! in_array($store, $pairs[$key]['store_samples'], true)) { - $pairs[$key]['store_count']++; - if (count($pairs[$key]['store_samples']) < 5) { - $pairs[$key]['store_samples'][] = $store; - } - } - } - } - - foreach ($pairs as &$pair) { - $pair['raw_items'] = array_values(array_filter( - array_keys($pair['raw_items']), - static fn (string $item): bool => $item !== '', - )); - $pair['source_labels'] = array_keys($pair['source_labels']); - } - unset($pair); - - return [ - 'status' => $sourceRows > 0 ? 'ready' : 'unavailable', - 'source_rows' => $sourceRows, - 'pending_sources' => $pendingSources, - 'pairs' => array_values($pairs), - ]; - }); + return self::CACHE_PREFIX . $month . ':' . hash('sha256', implode('|', $parts)); } - /** @return array{array,array} */ + private function statusCacheKey(string $month): string + { + return self::STATUS_PREFIX . $month; + } + + /** @return array */ private function coverageMappingKeys(array $rules): array { - $exact = []; - $normalized = []; + $keys = []; foreach ($rules as $rule) { $platform = trim((string) ($rule['platform'] ?? '')); $item = trim((string) ($rule['item'] ?? '')); if ($platform === '' || $item === '') { continue; } - $exact[$platform . '|' . $item] = true; - $normalized[$platform . '|' . $this->normalizeItem($item)] = true; + $keys[$platform . '|' . $this->normalizeItem($item)] = true; } - return [$exact, $normalized]; + return $keys; } - private function isMapped(array $pair, array $exact, array $normalized): bool + private function isMapped(array $pair, array $mapping): bool { $platform = (string) ($pair['platform'] ?? ''); $item = (string) ($pair['item'] ?? ''); if ($platform === '' || $item === '') { return false; } - if (isset($normalized[$platform . '|' . $item])) { - return true; - } - foreach ((array) ($pair['raw_items'] ?? []) as $rawItem) { - if (isset($exact[$platform . '|' . $rawItem])) { - return true; - } - } - return false; + return isset($mapping[$platform . '|' . $item]); } /** @return list */ @@ -325,11 +454,18 @@ class AccountMappingCoverage return $this->generationCache[$cacheKey] = $generations; } - private function platformFromStore(string $store): string + private function platformSql(\Illuminate\Database\ConnectionInterface $connection): string { - $prefix = $store === '' ? '' : explode('-', $store, 2)[0]; + $cases = []; + foreach (self::PLATFORM_PREFIX as $prefix => $platform) { + $quotedPrefix = $connection->getPdo()->quote($prefix); + $quotedPlatform = $connection->getPdo()->quote($platform); + $cases[] = 'WHEN store_name = ' . $quotedPrefix + . ' OR store_name LIKE ' . $connection->getPdo()->quote($prefix . '-%') + . ' THEN ' . $quotedPlatform; + } - return self::PLATFORM_PREFIX[$prefix] ?? ''; + return 'CASE ' . implode(' ', $cases) . " ELSE '' END"; } private function normalizeItem(string $item): string @@ -339,6 +475,12 @@ class AccountMappingCoverage return preg_match('/^wx/i', $item) === 1 ? ltrim(substr($item, 2)) : $item; } + private function normalizedItemSql(): string + { + return "(CASE WHEN LOWER(COALESCE(bill_item, '')) LIKE 'wx%' " + . "THEN LTRIM(SUBSTR(bill_item, 3)) ELSE COALESCE(bill_item, '') END)"; + } + private function parseMonth(?string $month): string { $month = trim((string) $month); 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 67e3bb978..c58fd802e 100644 --- a/resources/views/business/pages/financial-rules/account-mapping.blade.php +++ b/resources/views/business/pages/financial-rules/account-mapping.blade.php @@ -138,7 +138,10 @@ border: 0; background: transparent; color: var(--vip-content-muted, #595959); - font: 600 0.875rem/1.25 inherit; + font-family: inherit; + font-size: 0.875rem; + font-weight: 600; + line-height: 1.25; cursor: pointer; transition: color 150ms ease; } @@ -207,7 +210,10 @@ border-radius: 8px; background: #fff; color: var(--vip-content-ink, #171717); - font: 400 0.8125rem/1.5 inherit; + font-family: inherit; + font-size: 0.8125rem; + font-weight: 400; + line-height: 1.5; } .am-coverage-toolbar select:focus { border-color: var(--vip-content-accent-dark, #856632); @@ -224,6 +230,7 @@ line-height: 1.5; } .am-coverage-summary strong { color: var(--vip-content-ink, #171717); font-size: 0.8125rem; } + .am-coverage-summary .is-warning { color: #935f07; } .am-coverage-state { margin-top: 0.75rem; padding: 2rem 1rem; @@ -562,7 +569,7 @@
· 同一个账单项目在业务上不是同一件事时,用财务备注/商品名称关键词区分:财务备注匹配账单的二次备注、账务备注等(202607订单 这类月份式备注不参与匹配),商品名称按包含匹配;两个都填最优先,其次商品名称,再次财务备注,都不填就是兜底规则。
- 点行展开看两种收支下的最终分录与校验结果;点「编辑」可直接改这一行;有新增账单项目时用「导入」追加。 + 点行展开看两种收支下的最终分录与校验结果;点「编辑」可直接改这一行。新增账单项目先去「未映射账单项目」核对,再点「补映射」填写规则。 @if ($amError) @@ -577,6 +584,7 @@ aria-selected="{{ $coverageInitialView === 'rules' ? 'true' : 'false' }}" aria-controls="amRulesPanel" data-am-view-tab="rules" + tabindex="{{ $coverageInitialView === 'rules' ? '0' : '-1' }}" > 已配置规则 {{ number_format((int) $amSummary['total']) }} @@ -587,6 +595,7 @@ aria-selected="{{ $coverageInitialView === 'unmapped' ? 'true' : 'false' }}" aria-controls="amCoveragePanel" data-am-view-tab="unmapped" + tabindex="{{ $coverageInitialView === 'unmapped' ? '0' : '-1' }}" > 未映射账单项目 — @@ -728,7 +737,7 @@