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

72 lines
2.4 KiB
PHP

<?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
{
private const PURPOSES = ['all', 'renewal', 'provision', 'ip_change'];
public static function normalizePurpose($value): string
{
if (is_array($value) || is_object($value)) {
return 'all';
}
$purpose = strtolower(trim((string) $value));
return in_array($purpose, self::PURPOSES, true) ? $purpose : 'all';
}
public static function forUser(int $userId, int $page = 1, int $perPage = 10,
string $purpose = 'all'): array
{
$page = max(1, $page);
$perPage = max(1, min(100, $perPage));
$purpose = self::normalizePurpose($purpose);
$base = CloudInvoice::where('user_id', $userId);
if ($purpose !== 'all') {
$base->where('purpose', $purpose);
}
$total = (int) (clone $base)->count();
$totalPages = max(1, (int) ceil($total / $perPage));
$page = min($page, $totalPages);
$records = clone $base;
if ($purpose === 'all') {
// Keep bills requiring action prominent in the combined view.
$records->orderByRaw(
"CASE WHEN status IN ('open', 'overdue') THEN 0 ELSE 1 END"
);
}
$records = $records
->orderByDesc('created_at')
->orderByDesc('id')
->offset(($page - 1) * $perPage)
->limit($perPage)
->get([
'id', 'purpose', 'instance_id', 'order_id', 'user_id',
'renews_expires_at', 'due_at', 'amount', 'status', 'created_at',
]);
$count = $records->count();
return [
'invoices' => CloudInvoiceService::listSummaries($records),
'purpose' => $purpose,
'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,
],
];
}
}