| 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; | |
| } | |
| } | |