*/ public function page(): array { $month = $this->selectedMonth(); $periodStart = $month['start']; $periodEnd = $month['end']; $accountError = null; try { $accountData = $this->accounts->page([ 'from' => $periodStart, 'to' => $periodEnd, ]); } catch (Throwable $exception) { report($exception); $accountData = []; $accountError = '非店铺账户余额暂时无法读取。'; } $storeError = null; try { $storeDaily = $this->cachedStoreDaily($periodStart, $periodEnd); } catch (Throwable $exception) { report($exception); $storeDaily = []; $storeError = '店铺每日余额暂时无法读取。'; } return $this->build( $month, $accountData, $storeDaily, $accountError, $storeError, ); } /** * 月度资金页默认查看最近已结束月份;本次进入页面即为 2026 年 10 月。 * * @return array{ * value:string,label:string,start:string,end:string, * options:array * } */ private function selectedMonth(): array { $now = CarbonImmutable::now('Asia/Shanghai')->startOfDay(); $default = $now->subMonthNoOverflow()->startOfMonth(); $requested = trim((string) request('month', '')); $selected = $default; if (preg_match('/^\d{4}-\d{2}$/', $requested) === 1) { try { $candidate = CarbonImmutable::createFromFormat( '!Y-m', $requested, 'Asia/Shanghai', ); if ($candidate instanceof CarbonImmutable && $candidate->format('Y-m') === $requested) { $selected = $candidate; } } catch (Throwable) { // 非法月份回落到最近已结束月份。 } } $periodStart = $selected->startOfMonth(); $periodEnd = $selected->endOfMonth(); if ($selected->isSameMonth($now)) { $periodEnd = $now; } $options = []; for ($offset = 0; $offset < 12; $offset++) { $month = $default->subMonthsNoOverflow($offset); $options[] = [ 'value' => $month->format('Y-m'), 'label' => $month->format('Y年n月'), ]; } return [ 'value' => $selected->format('Y-m'), 'label' => $selected->format('Y年n月'), 'start' => $periodStart->format('Y-m-d'), 'end' => $periodEnd->format('Y-m-d'), 'options' => $options, ]; } /** @return array */ private function cachedStoreDaily(string $start, string $end): array { $cacheKey = implode(':', [ 'ecommerce-finance', 'fund-balance-monitor-month', 'v2', (string) company_id(), $start, $end, $this->pinduoduoOpeningBalances->cacheVersion(), ]); return Cache::remember( $cacheKey, now()->addMinutes(self::STORE_CACHE_MINUTES), fn (): array => $this->stores->dailyBalances($start, $end), ); } /** * @param array $month * @param array $accountData * @param array $storeDaily * @return array */ private function build( array $month, array $accountData, array $storeDaily, ?string $accountError, ?string $storeError, ): array { $accountReady = $accountError === null && $accountData !== []; $storeReady = $storeError === null && $storeDaily !== []; $fundOverview = (array) ($accountData['fundOverview'] ?? []); $distribution = collect((array) ($fundOverview['distribution'] ?? [])) ->keyBy(static fn (array $row): string => (string) ($row['category'] ?? '')); $retainedCard = (array) ($accountData['retainedCard'] ?? []); $unretainedCard = (array) ($accountData['unretainedCard'] ?? []); $storePlatforms = $this->storePlatformRows( (array) ($storeDaily['platforms'] ?? []), $month['end'], ); $storeReadyPlatforms = count(array_filter( $storePlatforms, static fn (array $row): bool => $row['available'], )); $storePlatformTotal = count(StoreReceivingBalanceOverviewService::PLATFORMS); $storeComplete = $storeReady && $storeReadyPlatforms === $storePlatformTotal && $storePlatformTotal > 0; $storeBalance = round(array_sum(array_column($storePlatforms, 'balance')), 2); $accountLinks = $this->accountLinks($month); $storeLink = $this->storeLink($month); $categories = [ $this->accountCategory( 'bank', '银行账户余额', '保留银行账户', (array) $distribution->get('bank', []), $accountLinks['bank'], '查看银行余额明细', ), $this->accountCategory( 'alipay', '非店铺支付宝余额', '保留非店铺支付宝账户', (array) $distribution->get('alipay', []), $accountLinks['alipay'], '查看支付宝账户明细', ), $this->accountCategory( 'wangshang', '网商银行余额', '保留网商银行账户', (array) $distribution->get('wangshang', []), $accountLinks['wangshang'], '查看网商银行明细', ), $this->accountCategory( 'other', '其他账户余额', '其他支付宝、微信等保留账户', (array) $distribution->get('other', []), $accountLinks['other'], '查看其他账户明细', ), [ 'key' => 'store', 'label' => '店铺余额', 'description' => '8 个店铺平台每日余额汇总', 'count' => $storeReadyPlatforms, 'count_label' => $storeReadyPlatforms . '/' . $storePlatformTotal . ' 个平台', 'balance' => $storeBalance, 'available' => $storeBalance, 'blocked' => 0.0, 'share' => 0.0, 'status' => $storeComplete ? '完整' : ($storeReady ? '部分平台未就绪' : '暂不可用'), 'status_level' => $storeComplete ? 'complete' : 'warning', 'link' => $storeLink, 'link_label' => '查看店铺每日余额明细', ], ]; $totalBalance = round(array_sum(array_column($categories, 'balance')), 2); $availableBalance = round(array_sum(array_column($categories, 'available')), 2); $blockedBalance = round(array_sum(array_column($categories, 'blocked')), 2); foreach ($categories as &$category) { $category['share'] = $totalBalance > 0 ? round(max(0.0, (float) $category['balance']) / $totalBalance * 100, 1) : 0.0; } unset($category); $complete = $accountReady && $storeComplete; $status = $this->status( $complete, $accountReady, $storeReady, $storeReadyPlatforms, $storePlatformTotal, $accountError, $storeError, ); return [ 'view' => 'business.pages.fund-management.balance-monitor', 'month' => $month, 'periodLabel' => $month['start'] . ' 至 ' . $month['end'], 'summary' => [ 'total' => $totalBalance, 'available' => $availableBalance, 'blocked' => $blockedBalance, 'available_percent' => $totalBalance > 0 ? round($availableBalance / $totalBalance * 100, 1) : 0.0, 'blocked_percent' => $totalBalance > 0 ? round($blockedBalance / $totalBalance * 100, 1) : 0.0, 'retained_account_count' => (int) ($retainedCard['count'] ?? 0), 'unretained_account_count' => (int) ($unretainedCard['count'] ?? 0), 'unretained_balance' => $this->number($unretainedCard['current_balance'] ?? null), 'store_platform_ready' => $storeReadyPlatforms, 'store_platform_total' => $storePlatformTotal, 'complete' => $complete, ], 'categories' => $categories, 'status' => $status, 'links' => [ 'refresh' => route('business.pages.show', [ 'section' => 'fund-management', 'page' => 'fund-balance-monitor', 'month' => $month['value'], ]), ], ]; } /** * @param array $rowData * @return array */ private function accountCategory( string $key, string $label, string $description, array $rowData, string $link, string $linkLabel, ): array { $balance = $this->number($rowData['current_balance'] ?? null); $available = $this->number($rowData['available_balance'] ?? null); $blocked = $this->number($rowData['blocked_balance'] ?? null); $count = (int) ($rowData['count'] ?? 0); $missing = array_key_exists('current_balance', $rowData) && $rowData['current_balance'] === null; return [ 'key' => $key, 'label' => $label, 'description' => $description, 'count' => $count, 'count_label' => number_format($count) . ' 户', 'balance' => $balance, 'available' => $available, 'blocked' => $blocked, 'share' => 0.0, 'status' => $missing ? '余额待核对' : ($count > 0 ? '正常' : '无账户'), 'status_level' => $missing ? 'warning' : 'complete', 'link' => $link, 'link_label' => $linkLabel, ]; } /** * @param array> $platforms * @return array> */ private function storePlatformRows(array $platforms, string $asOf): array { $bySlug = collect($platforms)->keyBy( static fn (array $platform): string => (string) ($platform['slug'] ?? ''), ); $rows = []; foreach (StoreReceivingBalanceOverviewService::PLATFORMS as $definition) { $platform = (array) $bySlug->get((string) $definition['slug'], []); $daily = (array) ($platform['daily'][$asOf] ?? []); $closing = $daily['closing'] ?? null; $available = is_numeric($closing); $rows[] = [ 'slug' => (string) $definition['slug'], 'name' => (string) $definition['name'], 'available' => $available, 'balance' => $available ? round((float) $closing, 2) : 0.0, 'date' => $asOf, 'error' => $available ? '' : trim((string) ( $platform['daily_error'] ?? $platform['error'] ?? '月末余额未就绪' )), ]; } return $rows; } /** * @param array $month * @return array */ private function accountLinks(array $month): array { $query = [ 'section' => 'financial-operations', 'page' => 'ledger', 'tab' => 'overview', 'view' => 'accounts', 'keep' => 'retained', 'period_from' => $month['start'], 'period_to' => $month['end'], ]; return [ 'bank' => route('business.pages.show', [ 'section' => 'financial-operations', 'page' => 'fund-ledger', 'tab' => 'bank_balance', 'period_from' => $month['start'], 'period_to' => $month['end'], ]), 'alipay' => route('business.pages.show', [ ...$query, 'account_category' => 'alipay', ]), 'wangshang' => route('business.pages.show', [ ...$query, 'account_category' => 'wangshang', ]), 'other' => route('business.pages.show', [ ...$query, 'account_category' => 'other', ]), ]; } /** @param array $month */ private function storeLink(array $month): string { $url = route('business.pages.show', [ 'section' => 'billing-transactions', 'page' => 'store-receiving-bills', 'tab' => 'balance-overview', 'month' => $month['value'], ]); return $url . '#trend-table-title'; } /** @return array{level:string,title:string,message:string} */ private function status( bool $complete, bool $accountReady, bool $storeReady, int $readyPlatforms, int $platformTotal, ?string $accountError, ?string $storeError, ): array { if (! $accountReady) { return [ 'level' => 'warning', 'title' => '账户余额待补齐', 'message' => $accountError ?: '非店铺账户余额暂时无法读取。', ]; } if (! $storeReady) { return [ 'level' => 'warning', 'title' => '店铺余额待补齐', 'message' => $storeError ?: '店铺每日余额暂时无法读取,当前总资金为已接入数据小计。', ]; } if (! $complete) { return [ 'level' => 'warning', 'title' => '部分店铺平台未就绪', 'message' => $readyPlatforms . '/' . $platformTotal . ' 个平台已返回月末余额,当前总资金为已接入数据小计。', ]; } return [ 'level' => 'complete', 'title' => '本月数据完整', 'message' => '五类资金均已按月末口径汇总,可直接用于资金审阅。', ]; } private function number(mixed $value): float { return is_numeric($value) ? round((float) $value, 2) : 0.0; } }