File size: 1,634 Bytes
70ba896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class AnalyticsSnapshot extends Model
{
    protected $fillable = [
        'date',
        'hour',
        'revenue',
        'profit',
        'orders_count',
        'customers_count',
        'avg_order_value',
        'conversion_rate'
    ];

    protected $casts = [
        'date' => 'date',
        'revenue' => 'decimal:2',
        'profit' => 'decimal:2',
        'avg_order_value' => 'decimal:2',
        'conversion_rate' => 'decimal:4'
    ];

    // Scopes for different time periods
    public function scopeDaily($query, Carbon $date)
    {
        return $query->where('date', $date->format('Y-m-d'))
                    ->whereNotNull('hour')
                    ->orderBy('hour');
    }

    public function scopeWeekly($query, Carbon $startDate)
    {
        return $query->whereBetween('date', [
                        $startDate->format('Y-m-d'),
                        $startDate->copy()->addDays(6)->format('Y-m-d')
                    ])
                    ->whereNull('hour')
                    ->orderBy('date');
    }

    public function scopeMonthly($query, Carbon $date)
    {
        return $query->whereYear('date', $date->year)
                    ->whereMonth('date', $date->month)
                    ->whereNull('hour')
                    ->orderBy('date');
    }

    // Helper method to get profit margin percentage
    public function getProfitMarginAttribute()
    {
        if ($this->revenue > 0) {
            return ($this->profit / $this->revenue) * 100;
        }
        return 0;
    }
}