select('period') ->whereNotNull('period') ->where('period', '<>', '') ->distinct() ->orderByDesc('period') ->pluck('period') ->map(static fn ($period): string => trim((string) $period)) ->filter(fn (string $period): bool => $this->normalizePeriod($period) !== null) ->unique() ->values(); $requestedPeriod = $this->normalizePeriod( trim((string) request()->query('period', '')) ); $period = $requestedPeriod ?? $periodOptions->first() ?? ''; $sellerEntity = mb_substr( trim((string) request()->query('seller_entity', '')), 0, 100 ); $query = InvoiceBasic::query()->select([ 'id', 'store_name', 'store_entity', 'invoice_issuer', 'invoice_limit', 'output_amount', 'period', ]); if ($period !== '') { $query->where('period', $period); } else { $query->where(function ($query): void { $query->whereNull('period')->orWhere('period', ''); }); } if ($sellerEntity !== '') { $needle = '%' . addcslashes($sellerEntity, '%_\\') . '%'; $query->where('store_entity', 'like', $needle); } $snapshots = $this->piaojuQuotas->byNormalizedName(); $rows = $query ->orderBy('store_entity') ->orderByDesc('id') ->get() ->map(fn (InvoiceBasic $row): object => $this->presentRow( $row, $snapshots->get(PiaojuSellerQuotaRepository::normalizeName((string) $row->store_entity)) )) ->sortBy(static fn (object $row): string => sprintf( '%02d|%s', $row->status_rank, (string) $row->store_entity )) ->values(); $total = $rows->count(); $lastPage = max(1, (int) ceil($total / self::PER_PAGE)); $currentPage = min(max((int) request()->query('page', 1), 1), $lastPage); $pageRows = $rows ->slice(($currentPage - 1) * self::PER_PAGE, self::PER_PAGE) ->values(); $paginator = new LengthAwarePaginator( $pageRows, $total, self::PER_PAGE, $currentPage, [ 'path' => request()->url(), 'query' => request()->query(), ] ); $quotaTotal = round($rows->sum(static fn (object $row): float => (float) $row->invoice_limit), 2); $usedTotal = round($rows->sum(static fn (object $row): float => (float) $row->output_amount), 2); $availableRows = $rows->filter( static fn (object $row): bool => $row->available_amount !== null ); $availableTotal = round($availableRows->sum( static fn (object $row): float => (float) $row->available_amount ), 2); $matchedCount = $rows->where('snapshot_matched', true)->count(); $unmatchedCount = $rows->where('snapshot_matched', false)->count(); $unavailableCount = $rows->where('snapshot_unavailable', true)->count(); $insufficientCount = $rows->where('insufficient', true)->count(); return [ 'view' => 'business.pages.invoice_quota', 'title' => '发票额度', 'period' => $period, 'periodOptions' => $periodOptions, 'sellerEntity' => $sellerEntity, 'rows' => $paginator, 'summary' => [ 'record_count' => $total, 'quota_total' => $quotaTotal, 'used_total' => $usedTotal, 'available_total' => $availableTotal, 'matched_count' => $matchedCount, 'unmatched_count' => $unmatchedCount, 'unavailable_count' => $unavailableCount, 'insufficient_count' => $insufficientCount, 'latest_quota_updated_at' => $this->latestDateTime( $rows->pluck('quota_updated_at') ), 'latest_source_fetched_at' => $this->latestDateTime( $rows->pluck('source_fetched_at') ), ], 'loadError' => null, ]; } catch (Throwable $exception) { report($exception); return $this->errorPayload(); } } private function presentRow(InvoiceBasic $row, ?object $snapshot): object { $invoiceLimit = round((float) $row->invoice_limit, 2); $outputAmount = round((float) $row->output_amount, 2); $availableAmount = $snapshot !== null && is_numeric($snapshot->invoice_limit) ? round((float) $snapshot->invoice_limit, 2) : null; $authStatus = strtoupper(trim((string) ($snapshot->auth_status ?? ''))); if ($snapshot === null) { $status = '未匹配'; $statusTone = 'muted'; $statusIcon = 'link_off'; $statusRank = 0; } elseif ($authStatus === 'AUTHENTICATED_EXPIRED') { $status = '授权过期'; $statusTone = 'warning'; $statusIcon = 'schedule'; $statusRank = 1; } elseif ($authStatus !== 'AUTHENTICATED') { $status = '不可查看'; $statusTone = 'muted'; $statusIcon = 'visibility_off'; $statusRank = 1; } elseif ($availableAmount === null) { $status = '未获取额度'; $statusTone = 'muted'; $statusIcon = 'cloud_off'; $statusRank = 1; } elseif ($availableAmount <= 0) { $status = '额度不足'; $statusTone = 'danger'; $statusIcon = 'error'; $statusRank = 2; } else { $status = '正常'; $statusTone = 'success'; $statusIcon = 'check_circle_outline'; $statusRank = 3; } return (object) [ 'id' => $row->id, 'store_name' => $row->store_name, 'store_entity' => $row->store_entity, 'invoice_issuer' => $row->invoice_issuer, 'invoice_limit' => $invoiceLimit, 'output_amount' => $outputAmount, 'available_amount' => $availableAmount, 'quota_updated_at' => $this->formatDateTime($snapshot->invoice_limit_updated_at ?? null), 'source_fetched_at' => $this->formatDateTime($snapshot->source_fetched_at ?? null), 'snapshot_matched' => $snapshot !== null, 'snapshot_unavailable' => $snapshot !== null && ($authStatus !== 'AUTHENTICATED' || $availableAmount === null), 'insufficient' => $snapshot !== null && $authStatus === 'AUTHENTICATED' && $availableAmount !== null && $availableAmount <= 0, 'status' => $status, 'status_tone' => $statusTone, 'status_icon' => $statusIcon, 'status_rank' => $statusRank, 'period' => $row->period, ]; } private function formatDateTime(mixed $value): ?string { $text = trim((string) ($value ?? '')); if ($text === '') { return null; } try { return Carbon::parse($text, 'Asia/Shanghai')->format('Y-m-d H:i'); } catch (Throwable) { return null; } } private function latestDateTime(Collection $values): ?string { return $values ->filter(static fn (mixed $value): bool => trim((string) $value) !== '') ->sortDesc() ->first(); } private function normalizePeriod(string $period): ?string { return preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1 ? $period : null; } private function errorPayload(): array { return [ 'view' => 'business.pages.invoice_quota', 'title' => '发票额度', 'period' => '', 'periodOptions' => collect(), 'sellerEntity' => '', 'rows' => new LengthAwarePaginator([], 0, self::PER_PAGE, 1, [ 'path' => request()->url(), 'query' => request()->query(), ]), 'summary' => [ 'record_count' => 0, 'quota_total' => 0.0, 'used_total' => 0.0, 'available_total' => 0.0, 'matched_count' => 0, 'unmatched_count' => 0, 'unavailable_count' => 0, 'insufficient_count' => 0, 'latest_quota_updated_at' => null, 'latest_source_fetched_at' => null, ], 'loadError' => '发票额度数据暂时无法读取,请稍后重试。', ]; } }