Passed
Push — master ( 4f5b3b...1c5d75 )
by Darko
09:48
created

UserActivityStat::getTotalApiHits()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace App\Models;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Factories\HasFactory;
7
use Illuminate\Database\Eloquent\Model;
8
9
class UserActivityStat extends Model
10
{
11
    use HasFactory;
0 ignored issues
show
Bug introduced by
The trait Illuminate\Database\Eloquent\Factories\HasFactory requires the property $factoryClass which is not provided by App\Models\UserActivityStat.
Loading history...
12
13
    protected $guarded = [];
14
15
    protected $casts = [
16
        'stat_date' => 'date',
17
    ];
18
19
    /**
20
     * Collect and store user activity stats for a specific date
21
     * This aggregates data from user_downloads and user_requests tables
22
     */
23
    public static function collectDailyStats(?string $date = null): void
24
    {
25
        $statDate = $date ? Carbon::parse($date)->format('Y-m-d') : Carbon::yesterday()->format('Y-m-d');
26
27
        // Count downloads for the date
28
        $downloadsCount = UserDownload::query()
29
            ->whereRaw('DATE(timestamp) = ?', [$statDate])
30
            ->count();
31
32
        // Count API hits for the date
33
        $apiHitsCount = UserRequest::query()
34
            ->whereRaw('DATE(timestamp) = ?', [$statDate])
35
            ->count();
36
37
        // Store or update the stats
38
        self::updateOrCreate(
39
            ['stat_date' => $statDate],
40
            [
41
                'downloads_count' => $downloadsCount,
42
                'api_hits_count' => $apiHitsCount,
43
            ]
44
        );
45
    }
46
47
    /**
48
     * Get download stats for the last N days
49
     */
50
    public static function getDownloadsPerDay(int $days = 30): array
51
    {
52
        $startDate = Carbon::now()->subDays($days - 1)->format('Y-m-d');
53
54
        $stats = self::query()
55
            ->select('stat_date', 'downloads_count')
56
            ->where('stat_date', '>=', $startDate)
57
            ->orderBy('stat_date', 'asc')
0 ignored issues
show
Bug introduced by
'stat_date' of type string is incompatible with the type Closure|Illuminate\Datab...\Database\Query\Builder expected by parameter $column of Illuminate\Database\Query\Builder::orderBy(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

57
            ->orderBy(/** @scrutinizer ignore-type */ 'stat_date', 'asc')
Loading history...
58
            ->get()
59
            ->keyBy('stat_date');
60
61
        // Fill in missing days with zero counts
62
        $result = [];
63
        for ($i = $days - 1; $i >= 0; $i--) {
64
            $date = Carbon::now()->subDays($i)->format('Y-m-d');
65
            $stat = $stats->get($date);
66
            $result[] = [
67
                'date' => Carbon::parse($date)->format('M d'),
68
                'count' => $stat ? $stat->downloads_count : 0,
0 ignored issues
show
Bug introduced by
The property downloads_count does not seem to exist on App\Models\UserActivityStat. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
69
            ];
70
        }
71
72
        return $result;
73
    }
74
75
    /**
76
     * Get API hits stats for the last N days
77
     */
78
    public static function getApiHitsPerDay(int $days = 30): array
79
    {
80
        $startDate = Carbon::now()->subDays($days - 1)->format('Y-m-d');
81
82
        $stats = self::query()
83
            ->select('stat_date', 'api_hits_count')
84
            ->where('stat_date', '>=', $startDate)
85
            ->orderBy('stat_date', 'asc')
0 ignored issues
show
Bug introduced by
'stat_date' of type string is incompatible with the type Closure|Illuminate\Datab...\Database\Query\Builder expected by parameter $column of Illuminate\Database\Query\Builder::orderBy(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

85
            ->orderBy(/** @scrutinizer ignore-type */ 'stat_date', 'asc')
Loading history...
86
            ->get()
87
            ->keyBy('stat_date');
88
89
        // Fill in missing days with zero counts
90
        $result = [];
91
        for ($i = $days - 1; $i >= 0; $i--) {
92
            $date = Carbon::now()->subDays($i)->format('Y-m-d');
93
            $stat = $stats->get($date);
94
            $result[] = [
95
                'date' => Carbon::parse($date)->format('M d'),
96
                'count' => $stat ? $stat->api_hits_count : 0,
0 ignored issues
show
Bug introduced by
The property api_hits_count does not seem to exist on App\Models\UserActivityStat. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
97
            ];
98
        }
99
100
        return $result;
101
    }
102
103
    /**
104
     * Get total downloads for the last N days
105
     */
106
    public static function getTotalDownloads(int $days = 7): int
107
    {
108
        return self::query()
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::query()->wh...>sum('downloads_count') could return the type Illuminate\Database\Eloquent\Builder which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
109
            ->where('stat_date', '>=', Carbon::now()->subDays($days)->format('Y-m-d'))
110
            ->sum('downloads_count');
111
    }
112
113
    /**
114
     * Get total API hits for the last N days
115
     */
116
    public static function getTotalApiHits(int $days = 7): int
117
    {
118
        return self::query()
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::query()->wh...->sum('api_hits_count') could return the type Illuminate\Database\Eloquent\Builder which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
119
            ->where('stat_date', '>=', Carbon::now()->subDays($days)->format('Y-m-d'))
120
            ->sum('api_hits_count');
121
    }
122
123
    /**
124
     * Cleanup old stats (keep last N days)
125
     */
126
    public static function cleanupOldStats(int $keepDays = 90): int
127
    {
128
        $cutoffDate = Carbon::now()->subDays($keepDays)->format('Y-m-d');
129
130
        return self::query()
131
            ->where('stat_date', '<', $cutoffDate)
132
            ->delete();
133
    }
134
}
135