Files
portal-api/app/Http/Controllers/Api/Admin/Dashboard/DashboardController.php
T

85 lines
2.8 KiB
PHP

<?php
namespace App\Http\Controllers\Api\Admin\Dashboard;
use App\Enums\TransactionStatus;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\Transaction;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function stats(): JsonResponse
{
$total_customers = Customer::count();
$total_deposits = (float) Transaction::where('type', 'manual')
->where('status', TransactionStatus::COMPLETED->value)
->sum('amount');
return response()->json([
'error' => false,
'data' => [
'total_customers' => $total_customers,
'total_deposits' => $total_deposits,
],
]);
}
public function monthlyStats(Request $request): JsonResponse
{
$year = $request->integer('year', now()->year);
$deposits = Transaction::where('type', 'manual')
->where('status', TransactionStatus::COMPLETED->value)
->whereYear('created_at', $year)
->selectRaw('MONTH(created_at) as month, SUM(amount) as total_deposits')
->groupBy('month')
->pluck('total_deposits', 'month');
$newCustomers = Customer::whereYear('created_at', $year)
->selectRaw('MONTH(created_at) as month, COUNT(*) as new_customers')
->groupBy('month')
->pluck('new_customers', 'month');
$months = ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12'];
$data = collect(range(1, 12))->map(function ($m) use ($months, $deposits, $newCustomers) {
return [
'month' => $months[$m - 1],
'deposits' => (float) ($deposits[$m] ?? 0),
'new_customers' => (int) ($newCustomers[$m] ?? 0),
];
})->values();
return response()->json([
'error' => false,
'data' => $data,
]);
}
public function latestCustomers(): JsonResponse
{
$customers = Customer::orderByDesc('created_at')
->limit(5)
->get(['id', 'uuid', 'fullname', 'email', 'total', 'created_at']);
return response()->json([
'error' => false,
'data' => [
'items' => $customers->map(fn(Customer $c) => [
'id' => $c->id,
'uuid' => $c->uuid,
'fullname' => $c->fullname,
'email' => $c->email,
'total' => (float) $c->total,
'created_at' => $c->created_at?->toISOString(),
])->values(),
'total' => Customer::count(),
],
]);
}
}