fedi-feed-router/backend/app/Services/DashboardStatsService.php

88 lines
No EOL
2.8 KiB
PHP

<?php
namespace App\Services;
use App\Models\Article;
use App\Models\ArticlePublication;
use Carbon\Carbon;
class DashboardStatsService
{
/**
* @return array
*/
public function getStats(string $period = 'today'): array
{
$dateRange = $this->getDateRange($period);
// Get articles fetched for the period
$articlesFetchedQuery = Article::query();
if ($dateRange) {
$articlesFetchedQuery->whereBetween('created_at', $dateRange);
}
$articlesFetched = $articlesFetchedQuery->count();
// Get articles published for the period
$articlesPublishedQuery = ArticlePublication::query()
->whereNotNull('published_at');
if ($dateRange) {
$articlesPublishedQuery->whereBetween('published_at', $dateRange);
}
$articlesPublished = $articlesPublishedQuery->count();
// Calculate published percentage
$publishedPercentage = $articlesFetched > 0 ? round(($articlesPublished / $articlesFetched) * 100, 1) : 0.0;
return [
'articles_fetched' => $articlesFetched,
'articles_published' => $articlesPublished,
'published_percentage' => $publishedPercentage,
];
}
/**
* @return array<string, string>
*/
public function getAvailablePeriods(): array
{
return [
'today' => 'Today',
'week' => 'This Week',
'month' => 'This Month',
'year' => 'This Year',
'all' => 'All Time',
];
}
/**
* @return array{0: Carbon, 1: Carbon}|null
*/
private function getDateRange(string $period): ?array
{
$now = Carbon::now();
return match ($period) {
'today' => [$now->copy()->startOfDay(), $now->copy()->endOfDay()],
'week' => [$now->copy()->startOfWeek(), $now->copy()->endOfWeek()],
'month' => [$now->copy()->startOfMonth(), $now->copy()->endOfMonth()],
'year' => [$now->copy()->startOfYear(), $now->copy()->endOfYear()],
'all' => null, // No date filtering for all-time stats
default => [$now->copy()->startOfDay(), $now->copy()->endOfDay()],
};
}
/**
* Get additional stats for dashboard
*/
public function getSystemStats(): array
{
return [
'total_feeds' => \App\Models\Feed::count(),
'active_feeds' => \App\Models\Feed::where('is_active', true)->count(),
'total_channels' => \App\Models\PlatformChannel::count(),
'active_channels' => \App\Models\PlatformChannel::where('is_active', true)->count(),
'total_routes' => \App\Models\Route::count(),
'active_routes' => \App\Models\Route::where('is_active', true)->count(),
];
}
}