From 22c258b24e5129b3a88fdfdbcf8f958b70576ad5 Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Thu, 3 Dec 2026 15:37:02 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E7=A7=91=E7=9B=AE=E6=98=A0=E5=B0=84):=20?= =?UTF-8?q?=E6=9C=AA=E6=98=A0=E5=B0=84=E6=B8=85=E5=8D=95=E6=94=B9=E4=B8=BA?= =?UTF-8?q?=E8=B7=A8=E6=9C=88=E6=B1=87=E6=80=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../RefreshAccountMappingCoverage.php | 15 +- .../Business/AccountMappingActions.php | 12 +- .../Services/AccountMappingCoverage.php | 331 +++++++++++++++++- .../financial-rules/account-mapping.blade.php | 109 +++--- .../Business/AccountMappingPageTest.php | 29 +- .../AccountMappingCoverageTest.php | 44 +++ 6 files changed, 449 insertions(+), 91 deletions(-) diff --git a/app/Console/Commands/RefreshAccountMappingCoverage.php b/app/Console/Commands/RefreshAccountMappingCoverage.php index 6a962f539..fc3b478a8 100644 --- a/app/Console/Commands/RefreshAccountMappingCoverage.php +++ b/app/Console/Commands/RefreshAccountMappingCoverage.php @@ -7,12 +7,12 @@ use Modules\EcommerceFinance\Services\AccountMappingCoverage; use Throwable; /** - * 后台重建某月账单项目覆盖快照,供科目映射页即时读取。 + * 后台重建跨月或指定月份账单项目覆盖快照,供科目映射页即时读取。 */ class RefreshAccountMappingCoverage extends Command { protected $signature = 'account-mapping:refresh-coverage - {month? : 账单月份,格式 YYYY-MM} + {month? : all 或账单月份 YYYY-MM} {--pending : 处理页面登记的下一个刷新请求}'; protected $description = '刷新科目映射的未映射账单项目清单'; @@ -33,7 +33,10 @@ class RefreshAccountMappingCoverage extends Command } try { - $raw = $coverage->refreshForMonth($month); + $isAll = $month === 'all'; + $raw = $isAll + ? $coverage->refreshAllMonths() + : $coverage->refreshForMonth($month); if (($raw['status'] ?? '') === 'refreshing') { $this->warn('已有刷新任务正在执行,本次跳过。'); if ($runningPath !== null) { @@ -43,10 +46,12 @@ class RefreshAccountMappingCoverage extends Command return self::SUCCESS; } - $summary = $coverage->missingForMonth($month); + $summary = $isAll + ? $coverage->missingAcrossMonths() + : $coverage->missingForMonth($month); $this->info(sprintf( '%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。', - (string) $summary['month'], + $isAll ? '跨月全部账单' : (string) $summary['month'], (int) $summary['missing_item_count'], (int) $summary['missing_row_count'], (int) $summary['source_rows'], diff --git a/app/Http/Controllers/Business/AccountMappingActions.php b/app/Http/Controllers/Business/AccountMappingActions.php index 623aeeb20..0d5047a6d 100644 --- a/app/Http/Controllers/Business/AccountMappingActions.php +++ b/app/Http/Controllers/Business/AccountMappingActions.php @@ -96,11 +96,13 @@ class AccountMappingActions extends Controller ]); try { - return response()->json($this->coverage->missingForMonth( - trim((string) ($data['month'] ?? '')) ?: null, - (bool) ($data['refresh'] ?? false), - false, - )); + $month = trim((string) ($data['month'] ?? '')); + $refresh = (bool) ($data['refresh'] ?? false); + $payload = $month === '' + ? $this->coverage->missingAcrossMonths($refresh, false) + : $this->coverage->missingForMonth($month, $refresh, false); + + return response()->json($payload); } catch (\InvalidArgumentException $exception) { throw ValidationException::withMessages(['month' => $exception->getMessage()]); } catch (Throwable $exception) { diff --git a/modules/EcommerceFinance/Services/AccountMappingCoverage.php b/modules/EcommerceFinance/Services/AccountMappingCoverage.php index ea9d734c9..7928a2787 100644 --- a/modules/EcommerceFinance/Services/AccountMappingCoverage.php +++ b/modules/EcommerceFinance/Services/AccountMappingCoverage.php @@ -31,6 +31,10 @@ class AccountMappingCoverage private const RETRY_SECONDS = 8; + private const ALL_SCOPE = 'all'; + + private const ALL_SCOPE_MONTHS = 60; + private const SOURCES = [ '淘系支付宝' => ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null], '淘系微信' => ['table' => 'taobao_wechat_bill_rows', 'date' => 'occurred_at', 'periods' => null], @@ -203,9 +207,99 @@ class AccountMappingCoverage } } + /** + * 页面使用:读取跨月账单项目清单;不会在读取时自动创建扫描任务。 + * + * @return array + */ + public function missingAcrossMonths(bool $refresh = false, bool $queueIfMissing = false): array + { + $snapshotKey = self::ALL_SCOPE; + $sourceKey = $this->allSourceKey(); + $snapshot = $this->readSnapshot($snapshotKey, $sourceKey); + $status = Cache::get($this->statusCacheKey($snapshotKey), []); + + if (! $refresh && $snapshot !== null) { + return $this->missingAcrossPayload($snapshot['raw'], $snapshot['refreshed_at']); + } + + $raw = Cache::get($sourceKey); + if (! $refresh && is_array($raw)) { + $refreshedAt = is_array($status) ? (string) ($status['refreshed_at'] ?? '') : ''; + $this->writeSnapshot($snapshotKey, $sourceKey, $raw, $refreshedAt); + + return $this->missingAcrossPayload($raw, $refreshedAt); + } + + if (is_array($status) && ($status['status'] ?? '') === 'refreshing') { + return $this->waitingPayload($snapshotKey, 'refreshing'); + } + if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'failed') { + return $this->waitingPayload($snapshotKey, 'failed', (string) ($status['message'] ?? '')); + } + if ($this->hasLiveRefreshRequest($snapshotKey)) { + return $this->waitingPayload($snapshotKey, 'refreshing'); + } + if (! $refresh && ! $queueIfMissing) { + return $this->waitingPayload($snapshotKey, 'missing'); + } + + $requested = $this->requestRefresh($snapshotKey); + if (($requested['status'] ?? '') === 'failed') { + return $this->waitingPayload($snapshotKey, 'failed', (string) ($requested['message'] ?? '')); + } + + return $this->waitingPayload($snapshotKey, 'refreshing'); + } + + /** + * 后台命令使用:一次性按月份聚合最近 60 个月的全部账单项目。 + * + * @return array{status:string,source_rows:int,pending_sources:list,pairs:list>} + */ + public function refreshAllMonths(): array + { + $snapshotKey = self::ALL_SCOPE; + $lock = Cache::lock('account-mapping-coverage-refresh:' . $snapshotKey, 900); + + try { + return $lock->block(20, function () use ($snapshotKey): array { + Cache::put($this->statusCacheKey($snapshotKey), [ + 'status' => 'refreshing', + 'started_at' => now()->toDateTimeString(), + ], now()->addMinutes(self::STATUS_MINUTES)); + + try { + $sourceKey = $this->allSourceKey(); + [$start, $end] = $this->allPeriodBounds(); + $raw = $this->buildAllSourceCoverage($start, $end); + $refreshedAt = now()->toDateTimeString(); + Cache::put($sourceKey, $raw, now()->addHours(self::CACHE_HOURS)); + $this->writeSnapshot($snapshotKey, $sourceKey, $raw, $refreshedAt); + Cache::put($this->statusCacheKey($snapshotKey), [ + 'status' => 'ready', + 'refreshed_at' => $refreshedAt, + ], now()->addMinutes(self::STATUS_MINUTES)); + + return $raw; + } catch (Throwable $exception) { + $this->markFailed($snapshotKey, $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); + $period = $this->normalizeRefreshKey($month); Cache::put($this->statusCacheKey($period), [ 'status' => 'failed', 'message' => $message, @@ -239,6 +333,7 @@ class AccountMappingCoverage return [ 'status' => $raw['status'], + 'scope' => 'month', 'month' => $period, 'source_rows' => $raw['source_rows'], 'missing_item_count' => count($items), @@ -252,12 +347,60 @@ class AccountMappingCoverage ]; } + /** + * @param array{status:string,source_rows:int,pending_sources:list,pairs:list>} $raw + * @return array + */ + private function missingAcrossPayload(array $raw, string $refreshedAt = ''): array + { + $mapping = $this->coverageMappingKeys($this->store->all()); + $items = []; + $missingRows = 0; + + foreach ($raw['pairs'] as $pair) { + if ($this->isMapped($pair, $mapping)) { + continue; + } + + $months = array_values(array_filter( + (array) ($pair['months'] ?? []), + static fn (mixed $month): bool => is_string($month) && $month !== '', + )); + sort($months); + $pair['months'] = $months; + $missingRows += (int) $pair['source_rows']; + $items[] = $pair; + } + + usort($items, static fn (array $left, array $right): int => ( + $right['source_rows'] <=> $left['source_rows'] + ) ?: ( + strcmp((string) $left['platform'], (string) $right['platform']) + ) ?: strcmp((string) $left['item'], (string) $right['item'])); + + return [ + 'status' => $raw['status'], + 'scope' => self::ALL_SCOPE, + 'month' => null, + 'source_rows' => $raw['source_rows'], + 'missing_item_count' => count($items), + 'missing_row_count' => $missingRows, + 'pending_sources' => $raw['pending_sources'], + 'items' => $items, + 'months' => [], + 'retry_after' => null, + 'message' => '', + 'refreshed_at' => $refreshedAt, + ]; + } + /** @return array */ private function waitingPayload(string $period, string $status, string $message = ''): array { return [ 'status' => $status, - 'month' => $period, + 'scope' => $period === self::ALL_SCOPE ? self::ALL_SCOPE : 'month', + 'month' => $period === self::ALL_SCOPE ? null : $period, 'source_rows' => 0, 'missing_item_count' => 0, 'missing_row_count' => 0, @@ -273,6 +416,7 @@ class AccountMappingCoverage /** @return array{status:string,message:string} */ private function requestRefresh(string $period): array { + $period = $this->normalizeRefreshKey($period); Cache::put($this->statusCacheKey($period), [ 'status' => 'refreshing', 'started_at' => now()->toDateTimeString(), @@ -315,7 +459,7 @@ class AccountMappingCoverage continue; } $month = basename((string) $running, '.running'); - if ($this->isValidMonth($month)) { + if ($this->isValidRefreshKey($month)) { File::move($running, $directory . DIRECTORY_SEPARATOR . $month . '.pending', true); } } @@ -324,7 +468,7 @@ class AccountMappingCoverage sort($pendingFiles); foreach ($pendingFiles as $pending) { $month = basename((string) $pending, '.pending'); - if (! $this->isValidMonth($month)) { + if (! $this->isValidRefreshKey($month)) { continue; } $running = $directory . DIRECTORY_SEPARATOR . $month . '.running'; @@ -368,7 +512,7 @@ class AccountMappingCoverage return; } $month = basename($runningPath, '.running'); - if (! $this->isValidMonth($month)) { + if (! $this->isValidRefreshKey($month)) { return; } File::move( @@ -472,6 +616,168 @@ class AccountMappingCoverage . $period . '-' . substr(hash('sha256', $sourceKey), 0, 16) . '.json'; } + /** @return array{0:CarbonImmutable,1:CarbonImmutable} */ + private function allPeriodBounds(): array + { + $timezone = trim((string) config('app.platform_timezone', '')); + if ($timezone === '') { + $timezone = (string) config('app.timezone', 'UTC'); + } + + try { + $end = CarbonImmutable::now($timezone)->endOfMonth(); + } catch (Throwable) { + $end = CarbonImmutable::now()->endOfMonth(); + } + + return [ + $end->startOfMonth()->subMonthsNoOverflow(self::ALL_SCOPE_MONTHS - 1), + $end, + ]; + } + + private function allSourceKey(): string + { + [$start, $end] = $this->allPeriodBounds(); + $parts = [$start->format('Y-m-d'), $end->format('Y-m-d')]; + foreach (self::SOURCES as $label => $source) { + if ($source['periods'] === null) { + $parts[] = $label . ':none'; + continue; + } + $parts[] = $label . ':' . implode(',', $this->generations( + (string) $source['periods'], + $start->toDateString(), + $end->toDateString(), + )); + } + + return self::CACHE_PREFIX . self::ALL_SCOPE . ':' . hash('sha256', implode('|', $parts)); + } + + private function monthSql(\Illuminate\Database\ConnectionInterface $connection, string $dateColumn): string + { + return match ($connection->getDriverName()) { + 'mysql', 'mariadb' => "DATE_FORMAT({$dateColumn}, '%Y-%m')", + 'pgsql' => "TO_CHAR({$dateColumn}, 'YYYY-MM')", + 'sqlite' => "strftime('%Y-%m', {$dateColumn})", + default => throw new RuntimeException('当前数据库不支持跨月账单聚合。'), + }; + } + + /** + * @return array{ + * status:string, + * source_rows:int, + * pending_sources:list, + * pairs:list> + * } + */ + private function buildAllSourceCoverage(CarbonImmutable $start, CarbonImmutable $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); + } + + $dateColumn = (string) $source['date']; + $query = $connection->table($table); + 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); + } + + $monthExpression = $this->monthSql($connection, $dateColumn); + $platformExpression = $this->platformSql($connection); + $itemExpression = $this->normalizedItemSql(); + $groups = $query + ->selectRaw($monthExpression . ' AS bill_month') + ->selectRaw($platformExpression . ' AS platform, ' . $itemExpression . ' AS item') + ->selectRaw('COUNT(*) AS source_rows, COUNT(DISTINCT store_name) AS store_count') + ->groupByRaw($monthExpression . ', ' . $platformExpression . ', ' . $itemExpression) + ->cursor(); + + foreach ($groups as $group) { + $month = trim((string) $group->bill_month); + if (! $this->isValidMonth($month)) { + continue; + } + $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' => [], + 'month_rows' => [], + ]; + } + + $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]['month_rows'][$month] = ($pairs[$key]['month_rows'][$month] ?? 0) + $rows; + $pairs[$key]['store_count'] = max( + (int) $pairs[$key]['store_count'], + (int) $group->store_count, + ); + } + } + + foreach ($pairs as &$pair) { + ksort($pair['month_rows']); + $pair['months'] = array_keys($pair['month_rows']); + $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 array{ * status:string, @@ -710,6 +1016,21 @@ class AccountMappingCoverage return $month; } + private function normalizeRefreshKey(string $key): string + { + $key = trim($key); + if ($key === self::ALL_SCOPE) { + return self::ALL_SCOPE; + } + + return $this->parseMonth($key); + } + + private function isValidRefreshKey(string $key): bool + { + return $key === self::ALL_SCOPE || $this->isValidMonth($key); + } + private function isValidMonth(string $month): bool { try { 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 5d7101e48..ec84fa86b 100644 --- a/resources/views/business/pages/financial-rules/account-mapping.blade.php +++ b/resources/views/business/pages/financial-rules/account-mapping.blade.php @@ -11,22 +11,6 @@ $platforms = $amOptions['platforms'] ?? []; $categories = $amOptions['categories'] ?? []; - $coverageTimezone = trim((string) config('app.platform_timezone', '')) - ?: (string) config('app.timezone', 'UTC'); - $coverageDefaultMonth = \Carbon\CarbonImmutable::now($coverageTimezone) - ->subMonthNoOverflow() - ->format('Y-m'); - $coverageMonth = trim((string) request()->query('am_month', $coverageDefaultMonth)); - if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $coverageMonth) !== 1) { - $coverageMonth = $coverageDefaultMonth; - } - $coverageMonths = []; - $coverageMonthCursor = \Carbon\CarbonImmutable::createFromFormat('!Y-m', $coverageMonth); - for ($coverageMonthIndex = 0; $coverageMonthIndex < 18; $coverageMonthIndex++) { - $coverageMonths[] = $coverageMonthCursor - ->subMonthsNoOverflow($coverageMonthIndex) - ->format('Y-m'); - } $coverageInitialView = request()->query('am_view') === 'unmapped' ? 'unmapped' : 'rules'; $outBase = 0; $inBase = 0; @@ -202,6 +186,11 @@ font-size: 0.75rem; font-weight: 500; } + .am-coverage-range { + color: var(--vip-content-muted, #595959); + font-size: 0.75rem; + line-height: 1.5; + } .am-coverage-toolbar select { min-width: 9rem; height: 2.125rem; @@ -254,12 +243,13 @@ line-height: 1.5; } .am-coverage-notice[hidden] { display: none; } - .am-coverage-table { min-width: 62rem; table-layout: fixed; } + .am-coverage-table { min-width: 72rem; table-layout: fixed; } .am-coverage-table th, .am-coverage-table td { overflow: hidden; text-overflow: ellipsis; } .am-coverage-table .am-coverage-index { width: 3.5rem; } .am-coverage-table .am-coverage-platform { width: 7.5rem; } .am-coverage-table .am-coverage-item { width: 18rem; } + .am-coverage-table .am-coverage-months { width: 10rem; } .am-coverage-table .am-coverage-source { width: 12rem; } .am-coverage-table .am-coverage-count { width: 7rem; text-align: right; font-variant-numeric: tabular-nums; } .am-coverage-table .am-coverage-stores { width: 10rem; text-align: right; font-variant-numeric: tabular-nums; } @@ -274,6 +264,18 @@ font-size: 0.6875rem; white-space: nowrap; } + .am-coverage-month-tag { + display: inline-block; + margin: 0.1rem 0.2rem 0.1rem 0; + padding: 0.1rem 0.4rem; + border: 1px solid #ddd5c7; + border-radius: 999px; + background: #fff; + color: #595959; + font-size: 0.6875rem; + font-variant-numeric: tabular-nums; + white-space: nowrap; + } .am-coverage-store-hint { color: var(--vip-content-muted, #595959); font-size: 0.6875rem; } /* 表格必须锁列宽(table-layout:fixed)。默认的自动列宽会按内容互相挤压, @@ -876,24 +878,17 @@ >
- + 统计最近 60 个月的已导入账单
- {{ $coverageMonth }} - 正在读取该月账单项目…… + 跨月全部账单 + 正在读取未映射账单项目……
- 正在读取该月账单项目,请稍候。 + 正在读取最近 60 个月的账单项目,请稍候。