refactor(billing): centralize invoice presentation

go
codex 2 weeks ago
parent 9f827c12c8
commit 5ef048cbba

@ -12,6 +12,7 @@ use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInstancePageService;
use App\Services\Cloud\CloudInvoiceDetailPageService;
use App\Services\Cloud\CloudInvoicePageService;
use App\Services\Cloud\CloudInvoicePresentation;
use App\Services\Cloud\CloudTrafficPoolReadModel;
use App\Services\Cloud\CloudUserIsoFeature;
use App\Services\Cloud\CloudUserIsoService;
@ -309,8 +310,7 @@ final class CloudPageController
is_array($query) ? $query : []
);
$payload['balance'] = (string) $user->money;
$rows = array_map(fn (array $invoice): array => $this->invoiceListRow($invoice),
$payload['invoices']);
$rows = CloudInvoicePresentation::summaries($payload['invoices']);
$json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_HEX_TAG
| JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_INVALID_UTF8_SUBSTITUTE);
@ -347,7 +347,7 @@ final class CloudPageController
}
return $this->render($response, 'invoice-detail', '账单详情', '', $invoiceId, [
'cloud_invoice_detail_view' => $this->invoiceDetailView($payload),
'cloud_invoice_detail_view' => CloudInvoicePresentation::detail($payload),
'cloud_invoice_detail_bootstrap_json' => $this->safeJson($payload),
]);
}

@ -0,0 +1,695 @@
<?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);
[$statusLabel, $statusClass] = self::invoiceStatus(
(string) ($invoice['display_status'] ?? $invoice['status'] ?? '')
);
$created = self::formatTimestamp(
$invoice['created_at'] ?? null,
'时间未记录'
);
$facts = [
['label' => '账单编号', 'value' => '#' . (string) ($invoice['id'] ?? '—')],
['label' => '创建时间', 'value' => $created],
];
if ($purpose === 'provision') {
$facts[] = [
'label' => '支付截止',
'value' => self::formatTimestamp(
$invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null
),
];
} elseif ($purpose === 'renewal') {
$facts[] = [
'label' => '实例到期',
'value' => self::formatTimestamp(
$invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null
),
];
if (($invoice['deletion_at'] ?? null) !== null) {
$facts[] = [
'label' => '最晚支付',
'value' => self::formatTimestamp($invoice['deletion_at']),
];
}
} elseif (($invoice['payment_deadline_at'] ?? null) !== null) {
$facts[] = [
'label' => '支付截止',
'value' => self::formatTimestamp($invoice['payment_deadline_at']),
];
}
if (($invoice['paid_at'] ?? null) !== null) {
$facts[] = [
'label' => '支付时间',
'value' => self::formatTimestamp($invoice['paid_at']),
];
}
if (trim((string) ($invoice['paid_via'] ?? '')) !== '') {
$facts[] = [
'label' => '支付方式',
'value' => self::paymentLabel((string) $invoice['paid_via']),
];
}
$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 : '费用项目',
'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' => self::invoiceTitle($invoice, $purpose),
'created_display' => $created,
'amount_display' => self::formatMoney(
$invoice['amount'] ?? null,
$currency
),
'status_label' => $statusLabel,
'status_class' => $statusClass,
'facts' => $facts,
'show_line_items' => $lineItems !== [],
'line_items' => $lineItems,
'show_specification' => $specification !== [],
'specification' => $specification,
'show_payment' => $payment['show_payment'],
'payment_title' => $payment['payment_title'],
'payment_description' => $payment['payment_description'],
'active_payment_message' => $payment['active_payment_message'],
'active_payment_class' => $payment['active_payment_class'],
'payment_methods' => $payment['payment_methods'],
'show_fulfillment' => $fulfillment['show_fulfillment'],
'fulfillment_title' => $fulfillment['fulfillment_title'],
'fulfillment_description' => $fulfillment['fulfillment_description'],
'fulfillment_message' => $fulfillment['fulfillment_message'],
'fulfillment_label' => $fulfillment['fulfillment_label'],
'fulfillment_class' => $fulfillment['fulfillment_class'],
'fulfillment_failed' => $fulfillment['fulfillment_failed'],
'task_id' => $fulfillment['task_id'],
'instance_id' => $fulfillment['instance_id'],
];
}
/**
* 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);
[$statusLabel, $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' => [
'label' => $statusLabel,
'class' => $statusClass,
],
'payment' => [
'payable' => ($invoice['payable'] ?? false) === true,
'active' => $activePayment,
'message' => $activePaymentMessage,
'message_class' => $activePaymentClass,
],
'fulfillment' => $fulfillment,
'polling' => [
'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']),
],
];
}
/** @param array<string, mixed> $invoice */
private static function summary(array $invoice): array
{
$purpose = self::purpose($invoice);
$status = strtolower((string) ($invoice['status'] ?? ''));
[$statusLabel, $statusClass] = self::invoiceStatus(
(string) ($invoice['display_status'] ?? $invoice['status'] ?? '')
);
$fulfillmentStatus = strtolower((string) (
$invoice['fulfillment_status']
?? $invoice['job_status']
?? $invoice['order_status']
?? ''
));
[$fulfillmentLabel, $fulfillmentClass] = self::invoiceFulfillmentStatus(
$fulfillmentStatus,
$purpose
);
$invoice['title'] = self::invoiceTitle($invoice, $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_label'] = $statusLabel;
$invoice['status_class'] = $statusClass;
$invoice['fulfillment_label'] = $fulfillmentLabel;
$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
) !== ''))
&& $fulfillmentLabel !== '';
$invoice['context_display'] = self::context($invoice, $purpose, $status);
return $invoice;
}
/** @param array<string, mixed> $invoice */
private static function context(array $invoice, string $purpose,
string $status): string
{
if ($purpose === 'renewal') {
$context = '对应实例到期 ' . self::formatTimestamp(
$invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null,
'时间未记录'
);
if (in_array($status, ['open', 'overdue'], true)) {
$context .= ' · 最晚支付 ' . self::formatTimestamp(
$invoice['payment_deadline_at'] ?? null,
'时间未记录'
);
}
return $context;
}
if ($purpose === 'provision') {
return '支付截止 ' . self::formatTimestamp(
$invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null,
'时间未记录'
);
}
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 '目标实例 ' . ($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' => '账户余额',
'description' => '可用余额 ' . 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;
}
$paymentMethods[] = [
'id' => (string) $method['id'],
'name' => (string) $method['name'],
'description' => trim((string) (
$method['description'] ?? $method['label'] ?? ''
)) ?: '在线支付',
'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' => $payable && $paymentMethods !== []
? '选择支付方式' : '当前支付状态',
'payment_description' => $hasActivePayment && $payable
? '已有未完成支付订单;任一订单先到账即结清账单,后续到账款项将计入账户余额。'
: ($payable
? '选择支付方式后,点击“立即支付”将直接发起支付,请勿重复点击。'
: '该账单当前不可创建新的支付订单。'),
'active_payment_message' => $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' => '上一笔支付订单正在创建;您仍可选择其他支付方式。',
'pending' => '已有待支付订单;可继续原订单或选择其他支付方式。',
'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
));
[$label, $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
) !== '');
$error = self::firstText(
$fulfillment['error'] ?? null,
$invoice['error'] ?? null
);
$message = $error;
if ($message === '') {
$message = $label !== '' ? $label : match ($purpose) {
'upgrade' => '等待升级',
'ip_change' => '等待更换公网 IP',
default => '等待创建',
};
}
return [
'show_fulfillment' => $show,
'fulfillment_title' => match ($purpose) {
'upgrade' => '实例升级进度',
'ip_change' => '公网 IP 更换进度',
default => '实例创建进度',
},
'fulfillment_description' => match ($purpose) {
'upgrade' => '账单扣款后,系统会在后台升级实例;关闭页面不会取消任务。',
'ip_change' => '账单扣款后,系统会在后台更换公网 IP;关闭页面不会取消任务。',
default => '账单付款后,系统会在后台创建实例;关闭页面不会取消任务。',
},
'fulfillment_message' => $message,
'fulfillment_label' => $label,
'fulfillment_class' => $class,
'fulfillment_failed' => $message !== ''
&& ($error !== '' || 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
),
];
}
/**
* @param array<string, mixed> $invoice
* @return array<int, array{label: string, value: string}>
*/
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' => '实例',
'value' => $subject !== ''
? $subject
: ($purpose === 'provision' ? '待创建实例' : '实例'),
];
$planName = trim((string) ($invoice['plan_name'] ?? ''));
$specification[] = [
'label' => '套餐',
'value' => $planName !== '' ? $planName : '云服务器套餐',
];
if (($invoice['cpu_cores'] ?? null) !== null) {
$specification[] = [
'label' => 'CPU',
'value' => (string) $invoice['cpu_cores'] . ' 核',
];
}
if (($invoice['memory_mib'] ?? null) !== null) {
$specification[] = [
'label' => '内存',
'value' => self::formatMemory((int) $invoice['memory_mib']),
];
}
if (($invoice['disk_gib'] ?? null) !== null) {
$specification[] = [
'label' => '系统盘',
'value' => (string) $invoice['disk_gib'] . ' GB',
];
}
if (($invoice['bandwidth_mbps'] ?? null) !== null) {
$specification[] = [
'label' => '带宽',
'value' => (string) $invoice['bandwidth_mbps'] . ' Mbps',
];
}
if ($purpose !== 'upgrade') {
$specification[] = [
'label' => '服务周期',
'value' => max(0, (int) ($invoice['validity_days'] ?? 0)) . ' 天',
];
}
$specification[] = [
'label' => $purpose === 'upgrade'
? '目标周期流量' : '周期流量',
'value' => self::formatBytes(
max(0, (int) ($invoice['traffic_quota_bytes'] ?? 0)),
true
),
];
} 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' => '实例',
'value' => $subject !== '' ? $subject : '实例',
];
$specification[] = [
'label' => '服务内容',
'value' => $purpose === 'ip_change'
? '更换公网 IP' : '自动备份开通',
];
}
return $specification;
}
/** @param array<string, mixed> $invoice */
private static function purpose(array $invoice): string
{
return strtolower(trim((string) ($invoice['purpose'] ?? '')));
}
/** @param array<string, mixed> $invoice */
private static function invoiceTitle(array $invoice, string $purpose): string
{
$known = match ($purpose) {
'recharge' => '余额充值',
'provision' => '实例开通',
'renewal' => '实例续费',
'upgrade' => '实例升级',
'ip_change' => '更换公网 IP',
'backup_addon' => '自动备份开通',
default => '',
};
return $known !== '' ? $known : self::firstText(
$invoice['title'] ?? null,
$invoice['type_label'] ?? null,
'账单'
);
}
/** @return array{0: string, 1: string} */
private static function invoiceStatus(string $status): array
{
return match (strtolower($status)) {
'open' => ['待支付', 'warning'],
'renewal_grace' => ['已到期,宽限期内可续费', 'warning'],
'overdue' => ['已逾期', 'failed'],
'paid' => ['已支付', 'running'],
'refunded' => ['已退款', 'other'],
'void' => ['已失效', 'other'],
'expired' => ['已失效', 'failed'],
'deleting', 'purge_deleting' => ['实例删除中', 'failed'],
'purge_pending' => ['等待永久删除', 'failed'],
'purge_stopping' => ['删除前正在关机', 'failed'],
'purge_force_required' => ['等待管理员确认强制删除', 'failed'],
'delete_failed' => ['自动删除失败', 'failed'],
'purge_stop_failed' => ['删除前关机失败', 'failed'],
'purge_failed' => ['自动删除失败', 'failed'],
default => [$status !== '' ? $status : '未知', 'other'],
};
}
/** @return array{0: string, 1: string} */
private static function invoiceFulfillmentStatus(string $status,
string $purpose): array
{
if ($purpose === 'upgrade') {
return match (strtolower($status)) {
'queued', 'pending', 'running', 'active' => ['升级中', 'warning'],
'completed', 'succeeded' => ['已升级', 'running'],
'failed' => ['升级失败', 'failed'],
'cancelled', 'canceled' => ['已取消', 'other'],
default => ['', ''],
};
}
if ($purpose === 'ip_change') {
return match (strtolower($status)) {
'queued', 'pending', 'running', 'active' => ['更换中', 'warning'],
'completed', 'succeeded' => ['已更换', 'running'],
'review' => ['待人工核对', 'warning'],
'failed' => ['更换失败', 'failed'],
'cancelled', 'canceled' => ['已取消', 'other'],
default => ['', ''],
};
}
return match (strtolower($status)) {
'awaiting_payment', 'payment_pending', 'draft'
=> ['等待支付', 'warning'],
'queued', 'pending', 'provisioning', 'running', 'active'
=> ['创建中', 'warning'],
'completed', 'succeeded' => ['已开通', 'running'],
'failed' => ['创建失败', 'failed'],
'refunded' => ['开通失败,已退款', 'failed'],
'cancelled', 'canceled' => ['已取消', 'other'],
default => ['', ''],
};
}
private static function formatTimestamp($value,
string $fallback = '暂未提供'): string
{
return is_numeric($value) && (int) $value > 0
? date('Y/m/d H:i:s', (int) $value) : $fallback;
}
private static function formatMemory(int $memoryMiB): string
{
$memoryGiB = $memoryMiB / 1024;
return number_format(
$memoryGiB,
$memoryGiB === floor($memoryGiB) ? 0 : 1,
'.',
','
) . ' GB';
}
private static function formatBytes(int $bytes,
bool $unlimitedZero = false): string
{
if ($bytes === 0 && $unlimitedZero) {
return '不限流量';
}
$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 paymentLabel(string $paidVia): string
{
return match (strtolower(trim($paidVia))) {
'balance' => '账户余额',
'yipay_alipay' => '易支付 · 支付宝',
'yipay_wxpay' => '易支付 · 微信',
'paytaro' => 'Paytaro · 支付宝',
'stripe_card' => 'Stripe · 银行卡',
'stripe_alipay' => 'Stripe · 支付宝',
'usdt' => 'USDT-TRC20',
default => $paidVia,
};
}
private static function currency($value): string
{
$currency = strtoupper(trim((string) ($value ?? '')));
return preg_match('/^[A-Z][A-Z0-9]{2,7}$/D', $currency) === 1
? $currency : 'USD';
}
private static function formatMoney($value, string $currency): string
{
if (!is_numeric($value) || (float) $value < 0) {
return $currency === 'USD' ? '$—' : '— ' . $currency;
}
$amount = number_format((float) $value, 2, '.', ',');
return $currency === 'USD' ? '$' . $amount : $amount . ' ' . $currency;
}
private static function firstText(...$values): string
{
foreach ($values as $value) {
$text = trim((string) ($value ?? ''));
if ($text !== '') {
return $text;
}
}
return '';
}
}

@ -0,0 +1,185 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudInvoicePresentation;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$renewal = [
'id' => '17',
'purpose' => 'renewal',
'title' => '实例续费',
'currency' => 'USD',
'created_at' => 2_000_000_000,
'amount' => '12.51',
'status' => 'overdue',
'display_status' => 'renewal_grace',
'renews_expires_at' => 2_000_100_000,
'payment_deadline_at' => 2_000_359_200,
'deletion_at' => 2_000_359_200,
'payable' => true,
'validity_days' => 30,
'traffic_quota_bytes' => 0,
'items' => [
[
'id' => '31',
'code' => 'instance',
'label' => '实例套餐续费',
'amount' => '10.00',
'currency' => 'USD',
],
[
'id' => '32',
'code' => 'automatic_backup',
'label' => '<img src=x onerror=alert(1)>自动备份',
'amount' => '2.50',
'currency' => 'USD',
],
],
];
$rows = CloudInvoicePresentation::summaries([$renewal]);
$assert(count($rows) === 1
&& $rows[0]['status_label'] === '已到期,宽限期内可续费'
&& $rows[0]['status_class'] === 'warning'
&& $rows[0]['amount_display'] === '$12.51'
&& str_contains($rows[0]['context_display'], '最晚支付'),
'Renewal grace summary did not preserve its canonical status and deadline.');
$wrongLegacyTitle = $renewal;
$wrongLegacyTitle['title'] = '旧调用方错误标题';
$assert(CloudInvoicePresentation::summaries([$wrongLegacyTitle])[0]['title']
=== '实例续费',
'Known invoice title was still controlled by a legacy caller mapping.');
$detail = CloudInvoicePresentation::detail([
'invoice' => $renewal,
'balance_payment_allowed' => false,
'payment_methods' => [],
]);
$assert($detail['show_line_items'] === true
&& $detail['line_items'] === [
['label' => '实例套餐续费', 'amount_display' => '$10.00'],
[
'label' => '<img src=x onerror=alert(1)>自动备份',
'amount_display' => '$2.50',
],
]
&& $detail['amount_display'] === '$12.51',
'Detail projection changed frozen line-item labels or authoritative total.');
$switchable = CloudInvoicePresentation::detail([
'invoice' => $renewal,
'balance_payment_allowed' => true,
'balance' => '20.00',
'payment_methods' => [[
'id' => 'stripe_card',
'name' => 'Stripe · 银行卡',
]],
'active_payment' => [
'status' => 'review',
'task_id' => '91',
'payment' => null,
'can_submit' => true,
],
]);
$assert($switchable['show_payment'] === true
&& $switchable['payment_title'] === '选择支付方式'
&& str_contains($switchable['active_payment_message'], '可选择其他支付方式')
&& count($switchable['payment_methods']) === 2
&& $switchable['payment_methods'][0]['id'] === 'balance'
&& $switchable['payment_methods'][0]['selected'] === true,
'Unfinished payment did not remain switchable through the public module.');
$ipChange = [
'id' => '81',
'purpose' => 'ip_change',
'title' => '更换公网 IP',
'currency' => 'USD',
'created_at' => 2_000_000_000,
'amount' => '5.00',
'status' => 'paid',
'paid_at' => 2_000_000_000,
'paid_via' => 'balance',
'instance_id' => '41',
'instance_name' => 'vm-audit',
'task_id' => '82',
'job_status' => 'review',
'fulfillment_status' => 'review',
'error' => '操作效果待人工核对,请勿重复提交。',
'items' => [],
];
$ipView = CloudInvoicePresentation::detail(['invoice' => $ipChange]);
$ipRow = CloudInvoicePresentation::summaries([$ipChange])[0];
$assert($ipView['show_fulfillment'] === true
&& $ipView['fulfillment_title'] === '公网 IP 更换进度'
&& $ipView['fulfillment_label'] === '待人工核对'
&& $ipView['fulfillment_class'] === 'warning'
&& $ipView['instance_id'] === '41'
&& $ipRow['show_fulfillment'] === true
&& $ipRow['fulfillment_label'] === '待人工核对'
&& $ipRow['context_display'] === '目标实例 vm-audit',
'IP-change presentation lost its target or review-only fulfillment state.');
$unknown = CloudInvoicePresentation::summaries([[
'id' => '99',
'purpose' => 'custom',
'currency' => 'XTS',
'amount' => '7.25',
'status' => 'provider_unknown',
'created_at' => 0,
]])[0];
$assert($unknown['title'] === '账单'
&& $unknown['status_label'] === 'provider_unknown'
&& $unknown['status_class'] === 'other'
&& $unknown['amount_display'] === '7.25 XTS'
&& $unknown['created_display'] === '时间未记录',
'Unknown status or currency did not degrade to a safe display.');
$patch = CloudInvoicePresentation::statusPatch([
'invoice' => $ipChange + [
'display_status' => 'paid',
'job_completed' => false,
'job_attempts' => 2,
'job_updated_at' => 2_000_000_001,
],
'active_payment' => [
'status' => 'pending',
'payment' => ['payment_id' => 'pay-1'],
'can_submit' => true,
],
]);
$assert($patch['status'] === ['label' => '已支付', 'class' => 'running']
&& $patch['payment']['message']
=== '已有待支付订单;可继续原订单或选择其他支付方式。'
&& $patch['fulfillment']['fulfillment_label'] === '待人工核对'
&& $patch['polling']['task_id'] === '82'
&& $patch['polling']['job_attempts'] === 2
&& !array_key_exists('amount', $patch['invoice']),
'Sparse status projection did not isolate mutable payment and polling fields.');
$source = file_get_contents(
dirname(__DIR__) . '/app/Services/Cloud/CloudInvoicePresentation.php'
);
$controllerSource = file_get_contents(
dirname(__DIR__) . '/app/Controllers/CloudPageController.php'
);
$assert(is_string($source)
&& !str_contains($source, 'App\\Models')
&& !preg_match('/\\btime\\s*\\(/', $source)
&& !str_contains($source, 'CloudInvoicePaymentService')
&& !str_contains($source, 'CloudInvoiceService::'),
'Presentation module acquired an ORM, clock, payment-provider or domain-service dependency.');
$assert(is_string($controllerSource)
&& str_contains($controllerSource,
'CloudInvoicePresentation::summaries($payload[\'invoices\'])')
&& str_contains($controllerSource,
'CloudInvoicePresentation::detail($payload)'),
'Invoice SSR adapters do not consume the unified presentation module.');
echo "Cloud invoice presentation module checks passed.\n";
Loading…
Cancel
Save