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/CloudInvoicePresentation.php

932 lines
37 KiB
PHP

<?php
namespace App\Services\Cloud;
/**
* Pure presentation projection for canonical invoice read models.
*
* The caller owns invoice state, payment eligibility and fulfillment truth.
* This module only turns those canonical values into stable, escaped-by-the-
* caller display fields. It performs no I/O and never derives business state.
*/
final class CloudInvoicePresentation
{
/**
* Project canonical invoice summaries into the existing list-template
* contract while preserving their machine-readable fields.
*
* @param iterable<array<string, mixed>> $invoices
* @return array<int, array<string, mixed>>
*/
public static function summaries(iterable $invoices): array
{
$rows = [];
foreach ($invoices as $invoice) {
if (!is_array($invoice)) {
continue;
}
$rows[] = self::summary($invoice);
}
return $rows;
}
/**
* Project a complete owner-scoped invoice payload into the existing
* detail-template contract.
*
* @param array<string, mixed> $payload
* @return array<string, mixed>
*/
public static function detail(array $payload): array
{
$invoice = is_array($payload['invoice'] ?? null)
? $payload['invoice'] : [];
$purpose = self::purpose($invoice);
$currency = self::currency($invoice['currency'] ?? null);
[$statusKey, $statusClass] = self::invoiceStatus(
(string) ($invoice['display_status'] ?? $invoice['status'] ?? '')
);
$created = self::formatTimestamp(
$invoice['created_at'] ?? null,
''
);
$facts = [
['label_key' => 'billing.fact.invoice_number',
'value' => '#' . (string) ($invoice['id'] ?? '—')],
self::timestampFact('billing.fact.created_at',
$invoice['created_at'] ?? null, ''),
];
if ($purpose === 'provision') {
$facts[] = self::timestampFact('billing.fact.payment_deadline',
$invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null);
} elseif ($purpose === 'renewal') {
$facts[] = self::timestampFact('billing.fact.instance_expiry',
$invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null);
if (($invoice['deletion_at'] ?? null) !== null) {
$facts[] = self::timestampFact('billing.fact.latest_payment',
$invoice['deletion_at']);
}
} elseif (($invoice['payment_deadline_at'] ?? null) !== null) {
$facts[] = self::timestampFact('billing.fact.payment_deadline',
$invoice['payment_deadline_at']);
}
if (($invoice['paid_at'] ?? null) !== null) {
$facts[] = self::timestampFact('billing.fact.paid_at',
$invoice['paid_at']);
}
if (trim((string) ($invoice['paid_via'] ?? '')) !== '') {
$provider = strtolower(trim((string) $invoice['paid_via']));
$facts[] = [
'label_key' => 'billing.fact.payment_method',
'value' => self::providerKey($provider) === ''
? $provider : '',
'value_key' => self::providerKey($provider),
];
}
$lineItems = [];
foreach (is_array($invoice['items'] ?? null) ? $invoice['items'] : []
as $item) {
if (!is_array($item) || !is_numeric($item['amount'] ?? null)) {
continue;
}
$label = trim((string) ($item['label'] ?? ''));
$lineItems[] = [
'label' => $label,
'label_key' => self::lineItemKey(
(string) ($item['code'] ?? ''),
$purpose
),
'amount_display' => self::formatMoney(
$item['amount'],
self::currency($item['currency'] ?? $currency)
),
];
}
$specification = self::specification($invoice, $purpose);
$payment = self::paymentProjection($payload, $invoice, $currency);
$fulfillment = self::fulfillmentProjection($invoice, $purpose);
return [
'id' => (string) ($invoice['id'] ?? ''),
'title_key' => self::invoiceTitleKey($purpose),
'number_parameters' => ['id' => (string) ($invoice['id'] ?? '—')],
'created_at' => self::timestampValue($invoice['created_at'] ?? null),
'created_display' => $created,
'amount_display' => self::formatMoney(
$invoice['amount'] ?? null,
$currency
),
'status_key' => $statusKey,
'status_class' => $statusClass,
'facts' => $facts,
'show_line_items' => $lineItems !== [],
'line_items' => $lineItems,
'show_specification' => $specification !== [],
'specification' => $specification,
'show_payment' => $payment['show_payment'],
'payment_title_key' => $payment['payment_title_key'],
'payment_description_key' => $payment['payment_description_key'],
'active_payment_key' => $payment['active_payment_key'],
'active_payment_class' => $payment['active_payment_class'],
'payment_methods' => $payment['payment_methods'],
'show_fulfillment' => $fulfillment['show_fulfillment'],
'fulfillment_title_key' => $fulfillment['fulfillment_title_key'],
'fulfillment_description_key' =>
$fulfillment['fulfillment_description_key'],
'fulfillment_message_key' =>
$fulfillment['fulfillment_message_key'],
'fulfillment_key' => $fulfillment['fulfillment_key'],
'fulfillment_class' => $fulfillment['fulfillment_class'],
'fulfillment_failed' => $fulfillment['fulfillment_failed'],
'task_id' => $fulfillment['task_id'],
'instance_id' => $fulfillment['instance_id'],
'polling_required' => self::pollingRequired(
$invoice,
$payload['active_payment'] ?? null,
$fulfillment
),
'completion_notice' => self::completionNotice(
$invoice,
$purpose,
$fulfillment
),
];
}
/**
* Project a sparse status response without pretending it is a full detail
* payload. The raw mutable invoice fields remain grouped separately from
* their presentation so a browser can merge them deterministically.
*
* @param array<string, mixed> $payload
* @return array<string, mixed>
*/
public static function statusPatch(array $payload): array
{
$invoice = is_array($payload['invoice'] ?? null)
? $payload['invoice'] : $payload;
$purpose = self::purpose($invoice);
[$statusKey, $statusClass] = self::invoiceStatus(
(string) ($invoice['display_status'] ?? $invoice['status'] ?? '')
);
$fulfillment = self::fulfillmentProjection($invoice, $purpose);
$activePayment = is_array($payload['active_payment'] ?? null)
? $payload['active_payment'] : null;
[$activePaymentMessage, $activePaymentClass] = self::activePaymentMessage(
$activePayment
);
$rawFulfillment = is_array($invoice['fulfillment'] ?? null)
? $invoice['fulfillment'] : [];
$mutableKeys = [
'id', 'purpose', 'status', 'display_status', 'available_action',
'payable', 'paid_at', 'paid_via', 'payment_deadline_at',
'deletion_at', 'instance_id', 'order_status', 'fulfillment_status',
'task_id', 'job_status', 'job_completed', 'job_attempts',
'job_updated_at', 'phase', 'error', 'fulfillment',
];
$mutable = [];
foreach ($mutableKeys as $key) {
if (array_key_exists($key, $invoice)) {
$mutable[$key] = $invoice[$key];
}
}
return [
'invoice' => $mutable,
'active_payment' => $activePayment,
'status' => [
'code' => (string) ($invoice['display_status']
?? $invoice['status'] ?? ''),
'copy_key' => $statusKey,
'class' => $statusClass,
],
'payment' => [
'payable' => ($invoice['payable'] ?? false) === true,
'active' => $activePayment,
'message_key' => $activePaymentMessage,
'message_class' => $activePaymentClass,
],
'fulfillment' => $fulfillment,
'polling' => [
'required' => self::pollingRequired(
$invoice,
$activePayment,
$fulfillment
),
'task_id' => self::firstText(
$rawFulfillment['task_id'] ?? null,
$invoice['task_id'] ?? null
),
'job_status' => self::firstText(
$rawFulfillment['job_status'] ?? null,
$invoice['job_status'] ?? null,
$invoice['fulfillment_status'] ?? null
),
'job_completed' => $invoice['job_completed'] ?? null,
'job_attempts' => max(0, (int) ($invoice['job_attempts'] ?? 0)),
'job_updated_at' => ($invoice['job_updated_at'] ?? null) === null
? null : max(0, (int) $invoice['job_updated_at']),
],
'completion_notice' => self::completionNotice(
$invoice,
$purpose,
$fulfillment
),
];
}
/** @param array<string, mixed> $invoice */
private static function summary(array $invoice): array
{
$purpose = self::purpose($invoice);
$status = strtolower((string) ($invoice['status'] ?? ''));
[$statusKey, $statusClass] = self::invoiceStatus(
(string) ($invoice['display_status'] ?? $invoice['status'] ?? '')
);
$fulfillmentStatus = strtolower((string) (
$invoice['fulfillment_status']
?? $invoice['job_status']
?? $invoice['order_status']
?? ''
));
[$fulfillmentKey, $fulfillmentClass] = self::invoiceFulfillmentStatus(
$fulfillmentStatus,
$purpose
);
$invoice['title_key'] = self::invoiceTitleKey($purpose);
$invoice['created_display'] = self::formatTimestamp(
$invoice['created_at'] ?? null,
''
);
$invoice['amount_display'] = self::formatMoney(
$invoice['amount'] ?? null,
self::currency($invoice['currency'] ?? null)
);
$invoice['status_key'] = $statusKey;
$invoice['status_class'] = $statusClass;
$invoice['fulfillment_key'] = $fulfillmentKey;
$invoice['fulfillment_class'] = $fulfillmentClass;
$invoice['show_fulfillment'] = (($purpose === 'provision'
&& in_array($status, ['paid', 'refunded'], true))
|| (in_array($purpose, ['upgrade', 'ip_change'], true)
&& self::firstText(
$invoice['task_id'] ?? null,
$invoice['job_status'] ?? null,
$invoice['fulfillment_status'] ?? null
) !== ''))
&& $fulfillmentKey !== '';
$invoice['context_segments'] = self::contextSegments(
$invoice, $purpose, $status
);
$invoice['polling_required'] = in_array($status, ['open', 'overdue'], true)
|| (in_array($purpose, ['upgrade', 'ip_change'], true)
&& $fulfillmentStatus === 'active');
return $invoice;
}
/** @param array<string, mixed> $invoice */
/**
* Preserve the server-owned context vocabulary while exposing canonical
* timestamps for browser-local formatting.
*
* @param array<string, mixed> $invoice
* @return array<int, array<string, mixed>>
*/
private static function contextSegments(array $invoice, string $purpose,
string $status): array
{
if ($purpose === 'renewal') {
$segments = [
['kind' => 'copy',
'key' => 'billing.context.renewal_expiry'],
['kind' => 'timestamp', 'value' => self::timestampValue(
$invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null
) ?? 0],
];
if (in_array($status, ['open', 'overdue'], true)) {
$segments[] = ['kind' => 'copy',
'key' => 'billing.context.latest_payment'];
$segments[] = ['kind' => 'timestamp', 'value' =>
self::timestampValue($invoice['payment_deadline_at'] ?? null)
?? 0];
}
return $segments;
}
if ($purpose === 'provision') {
return [
['kind' => 'copy',
'key' => 'billing.context.payment_deadline'],
['kind' => 'timestamp', 'value' => self::timestampValue(
$invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null
) ?? 0],
];
}
if (in_array($purpose, ['upgrade', 'ip_change', 'backup_addon'], true)) {
$target = self::firstText($invoice['instance_name'] ?? null);
if ($target === '' && ($invoice['instance_id'] ?? null) !== null) {
$target = '#' . (string) $invoice['instance_id'];
}
return [[
'kind' => 'copy',
'key' => 'billing.context.target_instance',
'parameters' => [
'name' => $target !== '' ? $target : '—',
],
]];
}
return [];
}
/**
* @param array<string, mixed> $payload
* @param array<string, mixed> $invoice
* @return array<string, mixed>
*/
private static function paymentProjection(array $payload, array $invoice,
string $currency): array
{
$paymentMethods = [];
$payable = ($invoice['payable'] ?? false) === true;
$balancePaymentAllowed = ($payload['balance_payment_allowed'] ?? false) === true;
if ($payable && $balancePaymentAllowed) {
$paymentMethods[] = [
'id' => 'balance',
'name_key' => 'billing.payment.balance.name',
'description_key' => 'billing.payment.balance.description',
'description_parameters' => [
'amount' => self::formatMoney(
$payload['balance'] ?? null,
$currency
),
],
'selected' => true,
];
}
if ($payable) {
foreach (is_array($payload['payment_methods'] ?? null)
? $payload['payment_methods'] : [] as $method) {
if (!is_array($method) || !isset($method['id'], $method['name'])) {
continue;
}
$methodId = (string) $method['id'];
$paymentMethods[] = [
'id' => $methodId,
'name' => (string) $method['name'],
'name_key' => self::providerKey($methodId),
'description' => trim((string) (
$method['description'] ?? $method['label'] ?? ''
)),
'description_key' => trim((string) (
$method['description'] ?? $method['label'] ?? ''
)) === '' ? 'billing.payment.online_fallback' : '',
'selected' => false,
];
}
}
if ($paymentMethods !== []
&& !in_array(true, array_column($paymentMethods, 'selected'), true)) {
$paymentMethods[0]['selected'] = true;
}
$activePayment = is_array($payload['active_payment'] ?? null)
? $payload['active_payment'] : null;
[$activePaymentMessage, $activePaymentClass] = self::activePaymentMessage(
$activePayment
);
$hasActivePayment = $activePayment !== null
&& $activePaymentMessage !== '';
return [
'show_payment' => $hasActivePayment
|| ($payable && $paymentMethods !== []),
'payment_title_key' => $payable && $paymentMethods !== []
? 'billing.payment.select_title'
: 'billing.payment.status_title',
'payment_description_key' => $hasActivePayment && $payable
? 'billing.payment.description.active'
: ($payable
? 'billing.payment.description.choose'
: 'billing.payment.description.unavailable'),
'active_payment_key' => $activePaymentMessage,
'active_payment_class' => $activePaymentClass,
'payment_methods' => $paymentMethods,
];
}
/**
* @param array<string, mixed>|null $activePayment
* @return array{0: string, 1: string}
*/
private static function activePaymentMessage(?array $activePayment): array
{
$status = strtolower((string) ($activePayment['status'] ?? ''));
$message = match ($status) {
'creating' => 'billing.payment.active.creating',
'pending' => 'billing.payment.active.pending',
'review' => 'billing.payment.active.review',
default => '',
};
return [
$message,
$status === 'review'
? 'invoice-payment-error' : 'invoice-payment-note',
];
}
/**
* @param array<string, mixed> $invoice
* @return array<string, mixed>
*/
private static function fulfillmentProjection(array $invoice,
string $purpose): array
{
$fulfillment = is_array($invoice['fulfillment'] ?? null)
? $invoice['fulfillment'] : [];
$fulfillmentStatus = strtolower(self::firstText(
$fulfillment['job_status'] ?? null,
$invoice['job_status'] ?? null,
$invoice['fulfillment_status'] ?? null,
$fulfillment['order_status'] ?? null,
$invoice['order_status'] ?? null
));
[$labelKey, $class] = self::invoiceFulfillmentStatus(
$fulfillmentStatus,
$purpose
);
$show = in_array($purpose, ['provision', 'upgrade', 'ip_change'], true)
&& (in_array(strtolower((string) ($invoice['status'] ?? '')),
['paid', 'refunded'], true)
|| self::firstText(
$fulfillment['task_id'] ?? null,
$invoice['task_id'] ?? null
) !== '');
$hasError = self::firstText(
$fulfillment['error'] ?? null,
$invoice['error'] ?? null
) !== '';
$messageKey = $labelKey !== '' ? $labelKey : match ($purpose) {
'upgrade' => 'billing.fulfillment.waiting.upgrade',
'ip_change' => 'billing.fulfillment.waiting.ip_change',
'provision' => 'billing.fulfillment.waiting.provision',
default => 'billing.fulfillment.waiting.generic',
};
return [
'show_fulfillment' => $show,
'fulfillment_title_key' => match ($purpose) {
'upgrade' => 'billing.fulfillment.title.upgrade',
'ip_change' => 'billing.fulfillment.title.ip_change',
'provision' => 'billing.fulfillment.title.provision',
default => 'billing.fulfillment.title.generic',
},
'fulfillment_description_key' => match ($purpose) {
'upgrade' => 'billing.fulfillment.description.upgrade',
'ip_change' => 'billing.fulfillment.description.ip_change',
'provision' => 'billing.fulfillment.description.provision',
default => 'billing.fulfillment.description.generic',
},
'fulfillment_message_key' => $messageKey,
'fulfillment_key' => $labelKey,
'fulfillment_class' => $class,
'fulfillment_failed' => $messageKey !== ''
&& ($hasError || in_array(
$fulfillmentStatus,
['failed', 'refunded', 'cancelled'],
true
)),
'task_id' => self::firstText(
$fulfillment['task_id'] ?? null,
$invoice['task_id'] ?? null
),
'instance_id' => self::firstText(
$fulfillment['instance_id'] ?? null,
$invoice['instance_id'] ?? null
),
'status_code' => $fulfillmentStatus,
];
}
/**
* @param array<string, mixed> $invoice
* @param array<string, mixed>|null $activePayment
* @param array<string, mixed> $fulfillment
*/
private static function pollingRequired(array $invoice, $activePayment,
array $fulfillment): bool
{
$fulfillmentStatus = strtolower((string) (
$fulfillment['status_code'] ?? ''
));
if (in_array($fulfillmentStatus,
['queued', 'pending', 'provisioning', 'running', 'active'], true)) {
return true;
}
$activeStatus = is_array($activePayment)
? strtolower((string) ($activePayment['status'] ?? '')) : '';
return ($invoice['payable'] ?? false) === true
&& in_array($activeStatus, ['creating', 'pending', 'review'], true);
}
/**
* @param array<string, mixed> $invoice
* @param array<string, mixed> $fulfillment
* @return array{copy_key: string, tone: string}|null
*/
private static function completionNotice(array $invoice, string $purpose,
array $fulfillment): ?array
{
$status = strtolower((string) ($invoice['status'] ?? ''));
$taskStatus = strtolower((string) ($fulfillment['status_code'] ?? ''));
if ($status === 'paid') {
if ($purpose === 'upgrade') {
return match ($taskStatus) {
'succeeded', 'completed' => [
'copy_key' => 'billing.notice.upgrade_succeeded',
'tone' => 'success',
],
'failed', 'cancelled', 'canceled' => [
'copy_key' => 'billing.notice.upgrade_failed',
'tone' => 'error',
],
default => null,
};
}
if ($purpose === 'ip_change') {
return match ($taskStatus) {
'succeeded', 'completed' => [
'copy_key' => 'billing.notice.ip_change_succeeded',
'tone' => 'success',
],
'review' => [
'copy_key' => 'billing.notice.ip_change_review',
'tone' => 'error',
],
'failed', 'cancelled', 'canceled' => [
'copy_key' => 'billing.notice.ip_change_failed',
'tone' => 'error',
],
default => null,
};
}
if ($purpose === 'provision') {
return match ($taskStatus) {
'succeeded', 'completed' => [
'copy_key' => 'billing.notice.provision_succeeded',
'tone' => 'success',
],
'refunded' => [
'copy_key' => 'billing.notice.provision_refunded',
'tone' => 'error',
],
'failed', 'expired', 'cancelled', 'canceled' => [
'copy_key' => 'billing.notice.provision_failed',
'tone' => 'error',
],
default => null,
};
}
return [
'copy_key' => $purpose === 'renewal'
? 'billing.notice.renewal_paid' : 'billing.notice.paid',
'tone' => 'success',
];
}
if (in_array($status, ['void', 'expired'], true)) {
return [
'copy_key' => 'billing.notice.expired',
'tone' => 'error',
];
}
if ($status === 'refunded') {
return [
'copy_key' => 'billing.notice.refunded',
'tone' => 'error',
];
}
if (($invoice['payable'] ?? false) !== true
&& in_array($status, ['open', 'overdue'], true)) {
return [
'copy_key' => match ($purpose) {
'provision' => 'billing.notice.provision_deadline',
'renewal' => 'billing.notice.renewal_deadline',
default => 'billing.notice.deadline',
},
'tone' => 'error',
];
}
return null;
}
/**
* @param array<string, mixed> $invoice
* @return array<int, array<string, mixed>>
*/
private static function specification(array $invoice, string $purpose): array
{
$specification = [];
if (in_array($purpose, ['provision', 'renewal', 'upgrade'], true)) {
$subject = self::firstText(
$invoice['requested_name'] ?? null,
$invoice['instance_name'] ?? null
);
$specification[] = [
'label_key' => 'billing.spec.instance',
'value' => $subject !== ''
? $subject
: '',
'value_key' => $subject !== '' ? ''
: ($purpose === 'provision'
? 'billing.spec.pending_instance'
: 'billing.spec.instance_fallback'),
];
$planName = trim((string) ($invoice['plan_name'] ?? ''));
$specification[] = [
'label_key' => 'billing.spec.plan',
'value' => $planName,
'value_key' => $planName !== '' ? ''
: 'billing.spec.plan_fallback',
];
if (($invoice['cpu_cores'] ?? null) !== null) {
$specification[] = [
'label_key' => 'billing.spec.cpu',
'value_key' => 'billing.spec.cpu_value',
'value_parameters' => [
'value' => (float) $invoice['cpu_cores'],
],
];
}
if (($invoice['memory_mib'] ?? null) !== null) {
$specification[] = [
'label_key' => 'billing.spec.memory',
'value_key' => 'billing.spec.memory_value',
'value_parameters' => [
'value' => self::formatMemory(
(int) $invoice['memory_mib']
),
],
];
}
if (($invoice['disk_gib'] ?? null) !== null) {
$specification[] = [
'label_key' => 'billing.spec.disk',
'value_key' => 'billing.spec.disk_value',
'value_parameters' => [
'value' => (float) $invoice['disk_gib'],
],
];
}
if (($invoice['bandwidth_mbps'] ?? null) !== null) {
$specification[] = [
'label_key' => 'billing.spec.bandwidth',
'value_key' => 'billing.spec.bandwidth_value',
'value_parameters' => [
'value' => (float) $invoice['bandwidth_mbps'],
],
];
}
if ($purpose !== 'upgrade') {
$specification[] = [
'label_key' => 'billing.spec.service_period',
'value_key' => 'billing.spec.days_value',
'value_parameters' => [
'value' => max(0,
(int) ($invoice['validity_days'] ?? 0)),
],
];
}
$specification[] = [
'label_key' => $purpose === 'upgrade'
? 'billing.spec.target_period_traffic'
: 'billing.spec.period_traffic',
'value' => max(0,
(int) ($invoice['traffic_quota_bytes'] ?? 0)) === 0
? '' : self::formatBytes(max(0,
(int) ($invoice['traffic_quota_bytes'] ?? 0))),
'value_key' => max(0,
(int) ($invoice['traffic_quota_bytes'] ?? 0)) === 0
? 'billing.spec.unlimited_traffic' : '',
];
} elseif (in_array($purpose, ['ip_change', 'backup_addon'], true)) {
$subject = self::firstText($invoice['instance_name'] ?? null);
if ($subject === '' && ($invoice['instance_id'] ?? null) !== null) {
$subject = '#' . (string) $invoice['instance_id'];
}
$specification[] = [
'label_key' => 'billing.spec.instance',
'value' => $subject,
'value_key' => $subject !== '' ? ''
: 'billing.spec.instance_fallback',
];
$specification[] = [
'label_key' => 'billing.spec.service_content',
'value_key' => $purpose === 'ip_change'
? 'billing.spec.ip_change'
: 'billing.spec.backup_addon',
];
}
return $specification;
}
/** @param array<string, mixed> $invoice */
private static function purpose(array $invoice): string
{
return CloudBillingPresentationCatalog::purposeCode(
$invoice['purpose'] ?? ''
);
}
private static function invoiceTitleKey(string $purpose): string
{
return in_array($purpose, [
'provision', 'renewal', 'upgrade', 'ip_change',
'backup_addon', 'recharge',
], true) ? 'billing.purpose.' . $purpose : 'billing.purpose.invoice';
}
/** @return array{0: string, 1: string} */
private static function invoiceStatus(string $status): array
{
$entry = CloudBillingPresentationCatalog::status(
'financial', $status
);
$known = [
'open', 'renewal_grace', 'overdue', 'paid', 'refunded',
'expired', 'void', 'deleting', 'purge_deleting',
'purge_pending', 'purge_stopping', 'purge_force_required',
'delete_failed', 'purge_stop_failed', 'purge_failed',
];
return [
in_array($entry['code'], $known, true)
? 'billing.status.financial.' . $entry['code']
: 'billing.status.financial.unknown',
self::userStatusClass($entry['tone']),
];
}
/** @return array{0: string, 1: string} */
private static function invoiceFulfillmentStatus(string $status,
string $purpose): array
{
$entry = CloudBillingPresentationCatalog::status(
'fulfillment', $status, ['purpose' => $purpose]
);
if ($entry['code'] === '') {
return ['', ''];
}
$code = $entry['code'];
$inProgress = in_array($code,
['queued', 'pending', 'provisioning', 'running', 'active'], true);
$succeeded = in_array($code, ['completed', 'succeeded'], true);
$key = match (true) {
$purpose === 'renewal' && $succeeded =>
'billing.status.fulfillment.renewal_succeeded',
$purpose === 'upgrade' && $inProgress =>
'billing.status.fulfillment.upgrade_running',
$purpose === 'upgrade' && $succeeded =>
'billing.status.fulfillment.upgrade_succeeded',
$purpose === 'upgrade' && $code === 'failed' =>
'billing.status.fulfillment.upgrade_failed',
$purpose === 'ip_change' && $inProgress =>
'billing.status.fulfillment.ip_change_running',
$purpose === 'ip_change' && $succeeded =>
'billing.status.fulfillment.ip_change_succeeded',
$purpose === 'ip_change' && $code === 'failed' =>
'billing.status.fulfillment.ip_change_failed',
$purpose === 'provision' && $inProgress =>
'billing.status.fulfillment.provision_running',
$purpose === 'provision' && $succeeded =>
'billing.status.fulfillment.provision_succeeded',
$purpose === 'provision' && $code === 'failed' =>
'billing.status.fulfillment.provision_failed',
$purpose === 'provision' && $code === 'refunded' =>
'billing.status.fulfillment.provision_refunded',
in_array($code, ['awaiting_payment', 'payment_pending', 'draft'], true)
=> 'billing.status.fulfillment.awaiting_payment',
$inProgress => 'billing.status.fulfillment.running',
$succeeded => 'billing.status.fulfillment.succeeded',
$code === 'review' => 'billing.status.fulfillment.review',
$code === 'failed' => 'billing.status.fulfillment.failed',
$code === 'expired' => 'billing.status.fulfillment.expired',
$code === 'refunded' => 'billing.status.fulfillment.refunded',
in_array($code, ['cancelled', 'canceled'], true) =>
'billing.status.fulfillment.cancelled',
default => 'billing.status.fulfillment.none',
};
return [$key, self::userStatusClass($entry['tone'])];
}
private static function userStatusClass(string $tone): string
{
return match ($tone) {
'success' => 'running',
'warning', 'info' => 'warning',
'danger' => 'failed',
default => 'other',
};
}
private static function formatTimestamp($value,
string $fallback = ''): string
{
return CloudBillingPresentationCatalog::timestamp(
$value, $fallback, 'Y/m/d H:i:s'
);
}
/** @return array{label_key: string, value: string, value_key: string, timestamp: int|null} */
private static function timestampFact(string $labelKey, $value,
string $fallback = ''): array
{
$timestamp = self::timestampValue($value);
return [
'label_key' => $labelKey,
'value' => self::formatTimestamp($value, $fallback),
'value_key' => $timestamp === null
? 'billing.value.time_missing' : '',
'timestamp' => $timestamp,
];
}
private static function lineItemKey(string $code, string $purpose): string
{
return match (strtolower(trim($code))) {
'base', 'plan', 'instance', 'provision' => $purpose === 'renewal'
? 'billing.line_items.renewal_plan'
: 'billing.line_items.plan',
'renewal', 'plan_renewal', 'base_renewal' =>
'billing.line_items.renewal_plan',
'backup', 'automatic_backup' => $purpose === 'renewal'
? 'billing.line_items.backup_renewal'
: 'billing.line_items.backup',
'backup_renewal' => 'billing.line_items.backup_renewal',
'backup_addon', 'automatic_backup_activation' =>
'billing.line_items.backup_addon',
default => '',
};
}
private static function timestampValue($value): ?int
{
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
}
private static function formatMemory(int $memoryMiB): string
{
$memoryGiB = $memoryMiB / 1024;
return number_format(
$memoryGiB,
$memoryGiB === floor($memoryGiB) ? 0 : 1,
'.',
','
);
}
private static function formatBytes(int $bytes): string
{
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
$amount = (float) $bytes;
$unit = 0;
while ($amount >= 1024 && $unit < count($units) - 1) {
$amount /= 1024;
++$unit;
}
$precision = $unit === 0 ? 0 : ($amount >= 100 ? 0 : ($amount >= 10 ? 1 : 2));
return number_format($amount, $precision, '.', '') . ' ' . $units[$unit];
}
private static function providerKey(string $paidVia): string
{
$code = strtolower(trim($paidVia));
return in_array($code, [
'balance', 'usdt', 'yipay_alipay', 'yipay_wxpay', 'paytaro',
'stripe_card', 'stripe_alipay',
], true) ? 'billing.payment.provider.' . $code : '';
}
private static function currency($value): string
{
return CloudBillingPresentationCatalog::currency($value);
}
private static function formatMoney($value, string $currency): string
{
return CloudBillingPresentationCatalog::money($value, $currency);
}
private static function firstText(...$values): string
{
foreach ($values as $value) {
$text = trim((string) ($value ?? ''));
if ($text !== '') {
return $text;
}
}
return '';
}
}