File: /home/armgroup/libs/app/Charts/OrdersCountChart.php
<?php
declare(strict_types=1);
namespace App\Charts;
use App\Enums\OrderStatus;
use App\Models\Order;
use Carbon\Carbon;
use Chartisan\PHP\Chartisan;
use ConsoleTVs\Charts\BaseChart;
use Illuminate\Http\Request;
class OrdersCountChart extends BaseChart
{
public ?array $middlewares = ['auth', 'permission:manage all orders', 'isActive'];
private const MONTH = 6;
/**
* Handles the HTTP request for the given chart.
* It must always return an instance of Chartisan
* and never a string or an array.
*/
public function handler(Request $request): Chartisan
{
$months = $this->getPersianMonths();
return Chartisan::build()
->labels($months)
->dataset(OrderStatus::CANCELED()->description, $this->getOrderCountPerPersianMonth($months, OrderStatus::CANCELED))
->dataset(OrderStatus::PROCESSING()->description, $this->getOrderCountPerPersianMonth($months, OrderStatus::PROCESSING))
->dataset(OrderStatus::SENT()->description, $this->getOrderCountPerPersianMonth($months, OrderStatus::SENT))
->dataset(OrderStatus::RETURNED()->description, $this->getOrderCountPerPersianMonth($months, OrderStatus::RETURNED))
->dataset(OrderStatus::COMPLETED()->description, $this->getOrderCountPerPersianMonth($months, OrderStatus::COMPLETED));
}
private function getPersianMonths(): array
{
$months = [];
for ($i = 0; $i < self::MONTH; $i++) {
$months[] = jdate(Carbon::now()->subMonths($i))->format('%B');
}
return array_reverse($months);
}
private function getOrderCountPerPersianMonth(array $months, $status): array
{
$data = array_fill(0, self::MONTH, 0);
foreach ($this->getOrders($status) as $order) {
$data[array_search(jdate($order->date)->format('%B'), $months)] += $order->count;
}
return $data;
}
private function getOrders($status)
{
return Order::where('created_at', '>', Carbon::now()->subMonths(self::MONTH))
->where('status', $status)
->selectRaw("DATE_FORMAT(created_at, '%Y-%m-%d') as date, COUNT(*) count, status")
->groupByRaw('date, status')
->latest()
->get();
}
}