You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudInvoicePageService.php

50 lines
1.7 KiB
PHTML

<?php
namespace App\Services\Cloud;
use App\Models\CloudInvoice;
/**
* Read-only, owner-scoped invoice pagination shared by HTML and JSON entry
* points. Keeping the query here prevents the server-rendered first page and
* later API pages from drifting apart.
*/
final class CloudInvoicePageService
{
public static function forUser(int $userId, int $page = 1, int $perPage = 10): array
{
$page = max(1, $page);
$perPage = max(1, min(100, $perPage));
$base = CloudInvoice::where('user_id', $userId);
$total = (int) (clone $base)->count();
$totalPages = max(1, (int) ceil($total / $perPage));
$page = min($page, $totalPages);
$records = (clone $base)
// Actionable bills stay ahead of historical service dates.
->orderByRaw("CASE WHEN status IN ('open', 'overdue') THEN 0 ELSE 1 END")
->orderByDesc('created_at')
->orderByDesc('id')
->offset(($page - 1) * $perPage)
->limit($perPage)
->get([
'id', 'purpose', 'instance_id', 'order_id', 'user_id',
'due_at', 'amount', 'status', 'created_at',
]);
$count = $records->count();
return [
'invoices' => CloudInvoiceService::listSummaries($records),
'pagination' => [
'page' => $page,
'per_page' => $perPage,
'total' => $total,
'total_pages' => $totalPages,
'has_previous' => $page > 1,
'has_next' => $page < $totalPages,
'from' => $count === 0 ? 0 : (($page - 1) * $perPage) + 1,
'to' => $count === 0 ? 0 : (($page - 1) * $perPage) + $count,
],
];
}
}