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.
235 lines
8.4 KiB
PHP
235 lines
8.4 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudInstance;
|
|
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 const USER_PAGE_SIZE = 25;
|
|
|
|
private const PURPOSES = [
|
|
'all', 'renewal', 'provision', 'upgrade', 'ip_change',
|
|
'backup_addon',
|
|
];
|
|
|
|
private const STATUS_GROUPS = ['all', 'pending', 'paid', 'closed'];
|
|
|
|
/** Normalize the complete list query once for both HTML and JSON. */
|
|
public static function normalizeQuery(array $query): array
|
|
{
|
|
return [
|
|
'page' => self::normalizePage($query['page'] ?? '1'),
|
|
'purpose' => self::normalizePurpose($query['purpose'] ?? 'all'),
|
|
'status' => self::normalizeStatus($query['status'] ?? 'all'),
|
|
'keyword' => self::normalizeKeyword($query['keyword'] ?? ''),
|
|
];
|
|
}
|
|
|
|
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 queryForUser(int $userId, array $query): array
|
|
{
|
|
$filters = self::normalizeQuery($query);
|
|
return self::readForUser(
|
|
$userId,
|
|
$filters,
|
|
self::USER_PAGE_SIZE
|
|
);
|
|
}
|
|
|
|
/** Attach the caller-owned wallet balance without adding another query. */
|
|
public static function withBalance(array $payload, $balance): array
|
|
{
|
|
$payload['balance'] = (string) $balance;
|
|
$payload['balance_display'] =
|
|
CloudBillingPresentationCatalog::money($balance, 'USD');
|
|
return $payload;
|
|
}
|
|
|
|
public static function forUser(int $userId, int $page = 1,
|
|
int $perPage = self::USER_PAGE_SIZE,
|
|
string $purpose = 'all'): array
|
|
{
|
|
return self::readForUser($userId, [
|
|
'page' => max(1, $page),
|
|
'purpose' => self::normalizePurpose($purpose),
|
|
'status' => 'all',
|
|
'keyword' => '',
|
|
], $perPage);
|
|
}
|
|
|
|
private static function readForUser(int $userId, array $filters,
|
|
int $perPage): array
|
|
{
|
|
$page = max(1, (int) $filters['page']);
|
|
$perPage = max(1, min(100, $perPage));
|
|
$purpose = (string) $filters['purpose'];
|
|
$base = CloudInvoice::where('user_id', $userId);
|
|
if ($purpose !== 'all') {
|
|
$base->where('purpose', $purpose);
|
|
}
|
|
$now = time();
|
|
$status = (string) $filters['status'];
|
|
if ($status === 'pending') {
|
|
$base->whereIn('status', ['open', 'overdue'])
|
|
->where(function ($visible) use ($userId, $now): void {
|
|
$visible->where('purpose', '<>', 'renewal')
|
|
->orWhere(function ($renewal) use ($userId, $now): void {
|
|
$renewal->where('purpose', 'renewal');
|
|
self::whereRenewalTargetExists($renewal, $userId);
|
|
self::whereRenewalDeadlineAfter($renewal, $now);
|
|
});
|
|
});
|
|
} elseif ($status === 'paid') {
|
|
$base->where('status', 'paid');
|
|
} elseif ($status === 'closed') {
|
|
$base->where(function ($closed) use ($userId, $now): void {
|
|
$closed->whereIn('status', ['refunded', 'void', 'expired'])
|
|
->orWhere(function ($renewal) use ($userId, $now): void {
|
|
$renewal->where('purpose', 'renewal')
|
|
->whereIn('status', ['open', 'overdue'])
|
|
->where(function ($unavailable) use (
|
|
$userId,
|
|
$now
|
|
): void {
|
|
$unavailable->whereNotExists(
|
|
self::renewalTargetQuery($userId)
|
|
)->orWhere(function ($expired) use ($now): void {
|
|
self::whereRenewalDeadlineAtOrBefore(
|
|
$expired,
|
|
$now
|
|
);
|
|
});
|
|
});
|
|
});
|
|
});
|
|
}
|
|
$keyword = (string) $filters['keyword'];
|
|
if ($keyword !== '') {
|
|
$instanceIds = CloudInstance::where('user_id', $userId)
|
|
->where('name', 'like', '%' . $keyword . '%')
|
|
->select('id');
|
|
$base->where(function ($filter) use ($keyword, $instanceIds): void {
|
|
if (preg_match('/^[1-9][0-9]{0,19}$/D', $keyword) === 1) {
|
|
$filter->where('id', $keyword)
|
|
->orWhereIn('instance_id', $instanceIds);
|
|
return;
|
|
}
|
|
$filter->whereIn('instance_id', $instanceIds);
|
|
});
|
|
}
|
|
$total = (int) (clone $base)->count();
|
|
$totalPages = max(1, (int) ceil($total / $perPage));
|
|
$page = min($page, $totalPages);
|
|
$records = clone $base;
|
|
$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', 'currency', 'status',
|
|
'created_at',
|
|
]);
|
|
$count = $records->count();
|
|
|
|
return [
|
|
'invoices' => CloudInvoicePresentation::summaries(
|
|
CloudInvoiceService::listSummaries($records)
|
|
),
|
|
'purpose' => $purpose,
|
|
'filters' => $filters,
|
|
'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,
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function normalizePage($value): int
|
|
{
|
|
if (is_array($value) || is_object($value)
|
|
|| preg_match('/^[1-9][0-9]{0,8}$/D', (string) $value) !== 1) {
|
|
return 1;
|
|
}
|
|
return (int) $value;
|
|
}
|
|
|
|
private static function normalizeStatus($value): string
|
|
{
|
|
if (is_array($value) || is_object($value)) {
|
|
return 'all';
|
|
}
|
|
$status = strtolower(trim((string) $value));
|
|
return in_array($status, self::STATUS_GROUPS, true) ? $status : 'all';
|
|
}
|
|
|
|
private static function normalizeKeyword($value): string
|
|
{
|
|
if (is_array($value) || is_object($value)) {
|
|
return '';
|
|
}
|
|
$keyword = trim((string) $value);
|
|
return mb_strlen($keyword) <= 100 ? $keyword : '';
|
|
}
|
|
|
|
private static function renewalTargetQuery(int $userId): callable
|
|
{
|
|
return static function ($target) use ($userId): void {
|
|
$target->selectRaw('1')->from('cloud_instances')
|
|
->whereColumn(
|
|
'cloud_instances.id',
|
|
'cloud_invoices.instance_id'
|
|
)
|
|
->where('cloud_instances.user_id', $userId)
|
|
->where('cloud_instances.status', '<>', 'deleted');
|
|
};
|
|
}
|
|
|
|
private static function whereRenewalTargetExists($query, int $userId): void
|
|
{
|
|
$query->whereExists(self::renewalTargetQuery($userId));
|
|
}
|
|
|
|
private static function whereRenewalDeadlineAfter($query, int $now): void
|
|
{
|
|
$query->whereRaw(self::renewalDeadlineSql() . ' > ?', [$now]);
|
|
}
|
|
|
|
private static function whereRenewalDeadlineAtOrBefore(
|
|
$query,
|
|
int $now
|
|
): void {
|
|
$query->whereRaw(self::renewalDeadlineSql() . ' <= ?', [$now]);
|
|
}
|
|
|
|
private static function renewalDeadlineSql(): string
|
|
{
|
|
return '(CASE WHEN renews_expires_at IS NOT NULL '
|
|
. 'AND renews_expires_at > due_at THEN renews_expires_at '
|
|
. 'ELSE due_at END) + '
|
|
. CloudInvoiceService::PAYMENT_GRACE_SECONDS;
|
|
}
|
|
}
|