main

filamentphp/demo

Last updated at: 29/12/2023 09:41

OrderStats.php

TLDR

This file defines a class called OrderStats which extends the StatsOverviewWidget class. It provides methods to retrieve statistics related to orders and display them in a widget.

Classes

OrderStats

The OrderStats class extends the StatsOverviewWidget class and provides methods to retrieve and display statistics related to orders. It includes the following methods:

  • getTablePage(): Returns the class name of the page used for displaying the table of orders.
  • getStats(): Returns an array of statistics related to orders. This includes the total number of orders, the number of open orders, and the average price of orders.
<?php

namespace App\Filament\Resources\Shop\OrderResource\Widgets;

use App\Filament\Resources\Shop\OrderResource\Pages\ListOrders;
use App\Models\Shop\Order;
use Filament\Widgets\Concerns\InteractsWithPageTable;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Flowframe\Trend\Trend;
use Flowframe\Trend\TrendValue;

class OrderStats extends BaseWidget
{
    use InteractsWithPageTable;

    protected static ?string $pollingInterval = null;

    protected function getTablePage(): string
    {
        return ListOrders::class;
    }

    protected function getStats(): array
    {
        $orderData = Trend::model(Order::class)
            ->between(
                start: now()->subYear(),
                end: now(),
            )
            ->perMonth()
            ->count();

        return [
            Stat::make('Orders', $this->getPageTableQuery()->count())
                ->chart(
                    $orderData
                        ->map(fn (TrendValue $value) => $value->aggregate)
                        ->toArray()
                ),
            Stat::make('Open orders', $this->getPageTableQuery()->whereIn('status', ['open', 'processing'])->count()),
            Stat::make('Average price', number_format($this->getPageTableQuery()->avg('total_price'), 2)),
        ];
    }
}