From 9ea962557675efaa005d5ecf2cc6e9488d2811a8 Mon Sep 17 00:00:00 2001 From: codex Date: Sun, 1 Nov 2026 20:43:16 +0800 Subject: [PATCH] refactor(billing): remove presentation drift --- web/README.md | 4 + web/app/Controllers/CloudApiController.php | 10 +- web/app/Controllers/CloudPageController.php | 408 +----------------- .../Cloud/CloudInvoicePageService.php | 9 + .../Services/Cloud/CloudInvoiceService.php | 26 +- web/public/cloud/invoices.js | 10 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/AdminBillingApiContractTest.php | 2 +- web/tests/CloudAssetVersionContractTest.php | 2 +- ...AutomaticBackupInvoicePresentationTest.php | 3 +- web/tests/CloudInvoiceDetailContractTest.php | 6 +- web/tests/CloudInvoiceListBehaviorTest.mjs | 5 +- web/tests/CloudInvoicePageServiceTest.php | 21 +- web/tests/CloudInvoicePresentationTest.php | 49 ++- web/tests/CloudPlanDefinitionTest.php | 15 +- 15 files changed, 112 insertions(+), 460 deletions(-) diff --git a/web/README.md b/web/README.md index 79864533..e10be205 100644 --- a/web/README.md +++ b/web/README.md @@ -7,3 +7,7 @@ 部署与安全边界见上层 `docs/DEPLOYMENT.md` 和 `docs/INTEGRATION_PLAN.md`。真实数据库、宿主机与支付通道仍必须在测试环境验收后再开放销售。 管理员虚拟化栏目使用“云镜像模板”“救援镜像”等统一名称。全局备份库提供用户、来源实例、来源宿主机、状态和名称筛选;镜像目录提供即时搜索与进行中/异常筛选;资源摘要直接进入同口径列表。计算节点维护资源配置,Agent API 页面集中维护连接身份、密钥与能力测试。详细职责及验收入口见上层 `docs/ADMIN_VIRTUALIZATION.md`。 + +## 账单展示边界 + +`CloudInvoiceService` 只提供权威业务状态和兼容读取字段;`CloudBillingPresentationCatalog` 统一用途、渠道、金额、时间与状态语义。用户和管理员分别通过 `CloudInvoicePresentation`、`CloudAdminBillingPresentation` 适配自己的页面结构。浏览器脚本与 Smarty 模板只渲染服务端投影,不得重新维护账单标签或状态映射。 diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index d5b4b6da..ea5c4751 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -238,11 +238,13 @@ final class CloudApiController } $user = $this->user($request); $query = $request->getQueryParams(); - $payload = CloudInvoicePageService::queryForUser( - (int) $actor['user_id'], - is_array($query) ? $query : [] + $payload = CloudInvoicePageService::withBalance( + CloudInvoicePageService::queryForUser( + (int) $actor['user_id'], + is_array($query) ? $query : [] + ), + (string) $user->money ); - $payload['balance'] = (string) $user->money; return $this->json($response, $payload); } diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index 6d5bc68c..732ef7b3 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -12,7 +12,6 @@ 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; @@ -305,11 +304,13 @@ final class CloudPageController $actor = CloudAccess::actor(false); $user = $request->getAttribute('auth_user') ?? Auth::getUser(); $query = $request->getQueryParams(); - $payload = CloudInvoicePageService::queryForUser( - (int) $actor['user_id'], - is_array($query) ? $query : [] + $payload = CloudInvoicePageService::withBalance( + CloudInvoicePageService::queryForUser( + (int) $actor['user_id'], + is_array($query) ? $query : [] + ), + (string) $user->money ); - $payload['balance'] = (string) $user->money; $rows = $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); @@ -319,7 +320,7 @@ final class CloudPageController 'cloud_invoice_filter' => $payload['purpose'], 'cloud_invoice_filters' => $payload['filters'], 'cloud_invoice_pagination' => $payload['pagination'], - 'cloud_invoice_balance' => $this->formatUsd($payload['balance']), + 'cloud_invoice_balance' => $payload['balance_display'], 'cloud_invoice_bootstrap_json' => $json === false ? '{}' : $json, ]); } @@ -487,368 +488,6 @@ final class CloudPageController return $response->withHeader('Cache-Control', 'private, no-store'); } - private function invoiceListRow(array $invoice): array - { - $purpose = strtolower((string) ($invoice['purpose'] ?? '')); - $status = strtolower((string) ($invoice['status'] ?? '')); - [$statusLabel, $statusClass] = $this->invoiceStatus( - (string) ($invoice['display_status'] ?? $invoice['status'] ?? '') - ); - $fulfillment = strtolower((string) ($invoice['fulfillment_status'] - ?? $invoice['job_status'] ?? $invoice['order_status'] ?? '')); - [$fulfillmentLabel, $fulfillmentClass] = $this->invoiceFulfillmentStatus( - $fulfillment, $purpose - ); - - $invoice['created_display'] = (int) ($invoice['created_at'] ?? 0) > 0 - ? date('Y/m/d H:i:s', (int) $invoice['created_at']) : '时间未记录'; - $invoice['amount_display'] = $this->formatUsd($invoice['amount'] ?? 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) - && $this->firstText($invoice['task_id'] ?? null, - $invoice['job_status'] ?? null, - $invoice['fulfillment_status'] ?? null) !== '')) - && $fulfillmentLabel !== ''; - $invoice['context_display'] = ''; - if ($purpose === 'renewal') { - $invoice['context_display'] = '对应实例到期 ' - . $this->formatTimestamp( - $invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null, - '时间未记录' - ); - if (in_array($status, ['open', 'overdue'], true)) { - $invoice['context_display'] .= ' · 最晚支付 ' - . $this->formatTimestamp( - $invoice['payment_deadline_at'] ?? null, - '时间未记录' - ); - } - } elseif ($purpose === 'provision') { - $invoice['context_display'] = '支付截止 ' - . $this->formatTimestamp( - $invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null, - '时间未记录' - ); - } elseif (in_array($purpose, ['upgrade', 'ip_change', 'backup_addon'], true)) { - $target = $this->firstText($invoice['instance_name'] ?? null); - if ($target === '' && ($invoice['instance_id'] ?? null) !== null) { - $target = '#' . (string) $invoice['instance_id']; - } - $invoice['context_display'] = '目标实例 ' . ($target !== '' ? $target : '实例'); - } - return $invoice; - } - - private function invoiceDetailView(array $payload): array - { - $invoice = is_array($payload['invoice'] ?? null) ? $payload['invoice'] : []; - $purpose = strtolower((string) ($invoice['purpose'] ?? '')); - [$statusLabel, $statusClass] = $this->invoiceStatus( - (string) ($invoice['display_status'] ?? $invoice['status'] ?? '') - ); - $created = $this->formatTimestamp($invoice['created_at'] ?? null, - '时间未记录'); - $facts = [ - ['label' => '账单编号', 'value' => '#' . (string) ($invoice['id'] ?? '—')], - ['label' => '创建时间', 'value' => $created], - ]; - if ($purpose === 'provision') { - $facts[] = ['label' => '支付截止', 'value' => $this->formatTimestamp( - $invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null - )]; - } elseif ($purpose === 'renewal') { - $facts[] = ['label' => '实例到期', 'value' => $this->formatTimestamp( - $invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null - )]; - if (($invoice['deletion_at'] ?? null) !== null) { - $facts[] = ['label' => '最晚支付', 'value' => $this->formatTimestamp( - $invoice['deletion_at'] - )]; - } - } elseif (($invoice['payment_deadline_at'] ?? null) !== null) { - $facts[] = ['label' => '支付截止', 'value' => $this->formatTimestamp( - $invoice['payment_deadline_at'] - )]; - } - if (($invoice['paid_at'] ?? null) !== null) { - $facts[] = ['label' => '支付时间', 'value' => $this->formatTimestamp( - $invoice['paid_at'] - )]; - } - if (trim((string) ($invoice['paid_via'] ?? '')) !== '') { - $facts[] = ['label' => '支付方式', 'value' => $this->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' => $this->formatUsd($item['amount']), - ]; - } - - $specification = []; - if (in_array($purpose, ['provision', 'renewal', 'upgrade'], true)) { - $subject = $this->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' => $this->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' => $this->formatBytes( - max(0, (int) ($invoice['traffic_quota_bytes'] ?? 0)), true - ), - ]; - } elseif (in_array($purpose, ['ip_change', 'backup_addon'], true)) { - $subject = $this->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' : '自动备份开通', - ]; - } - - $paymentMethods = []; - $payable = ($invoice['payable'] ?? false) === true; - $balancePaymentAllowed = ($payload['balance_payment_allowed'] ?? false) === true; - if ($payable && $balancePaymentAllowed) { - $paymentMethods[] = [ - 'id' => 'balance', - 'name' => '账户余额', - 'description' => '可用余额 ' . $this->formatUsd($payload['balance'] ?? null), - '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; - $activePaymentStatus = strtolower((string) ( - $activePayment['status'] ?? '' - )); - $activePaymentMessage = match ($activePaymentStatus) { - 'creating' => '上一笔支付订单正在创建;您仍可选择其他支付方式。', - 'pending' => '已有待支付订单;可继续原订单或选择其他支付方式。', - 'review' => '上一笔支付订单结果待核对;可选择其他支付方式,原订单若随后到账将计入账户余额。', - default => '', - }; - $hasActivePayment = $activePayment !== null - && $activePaymentMessage !== ''; - - $fulfillment = is_array($invoice['fulfillment'] ?? null) - ? $invoice['fulfillment'] : []; - $fulfillmentStatus = strtolower($this->firstText( - $fulfillment['job_status'] ?? null, - $invoice['job_status'] ?? null, - $invoice['fulfillment_status'] ?? null, - $fulfillment['order_status'] ?? null, - $invoice['order_status'] ?? null - )); - [$fulfillmentLabel, $fulfillmentClass] = $this->invoiceFulfillmentStatus( - $fulfillmentStatus, $purpose - ); - $showFulfillment = in_array( - $purpose, - ['provision', 'upgrade', 'ip_change'], - true - ) - && (in_array(strtolower((string) ($invoice['status'] ?? '')), - ['paid', 'refunded'], true) - || $this->firstText($fulfillment['task_id'] ?? null, - $invoice['task_id'] ?? null) !== ''); - $fulfillmentError = $this->firstText($fulfillment['error'] ?? null, - $invoice['error'] ?? null); - $fulfillmentMessage = $fulfillmentError; - if ($fulfillmentMessage === '') { - $fulfillmentMessage = $fulfillmentLabel !== '' - ? $fulfillmentLabel : match ($purpose) { - 'upgrade' => '等待升级', - 'ip_change' => '等待更换公网 IP', - default => '等待创建', - }; - } - - $fulfillmentTitle = match ($purpose) { - 'upgrade' => '实例升级进度', - 'ip_change' => '公网 IP 更换进度', - default => '实例创建进度', - }; - $fulfillmentDescription = match ($purpose) { - 'upgrade' => '账单扣款后,系统会在后台升级实例;关闭页面不会取消任务。', - 'ip_change' => '账单扣款后,系统会在后台更换公网 IP;关闭页面不会取消任务。', - default => '账单付款后,系统会在后台创建实例;关闭页面不会取消任务。', - }; - - return [ - 'id' => (string) ($invoice['id'] ?? ''), - 'title' => (string) ($invoice['title'] ?? $invoice['type_label'] ?? '账单'), - 'created_display' => $created, - 'amount_display' => $this->formatUsd($invoice['amount'] ?? null), - 'status_label' => $statusLabel, - 'status_class' => $statusClass, - 'facts' => $facts, - 'show_line_items' => $lineItems !== [], - 'line_items' => $lineItems, - 'show_specification' => $specification !== [], - 'specification' => $specification, - 'show_payment' => $hasActivePayment - || ($payable && $paymentMethods !== []), - 'payment_title' => $payable && $paymentMethods !== [] - ? '选择支付方式' : '当前支付状态', - 'payment_description' => $hasActivePayment && $payable - ? '已有未完成支付订单;任一订单先到账即结清账单,后续到账款项将计入账户余额。' - : ($payable - ? '选择支付方式后,点击“立即支付”将直接发起支付,请勿重复点击。' - : '该账单当前不可创建新的支付订单。'), - 'active_payment_message' => $activePaymentMessage, - 'active_payment_class' => $activePaymentStatus === 'review' - ? 'invoice-payment-error' : 'invoice-payment-note', - 'payment_methods' => $paymentMethods, - 'show_fulfillment' => $showFulfillment, - 'fulfillment_title' => $fulfillmentTitle, - 'fulfillment_description' => $fulfillmentDescription, - 'fulfillment_message' => $fulfillmentMessage, - 'fulfillment_label' => $fulfillmentLabel, - 'fulfillment_class' => $fulfillmentClass, - 'fulfillment_failed' => $fulfillmentMessage !== '' - && ($fulfillmentError !== '' - || in_array($fulfillmentStatus, - ['failed', 'refunded', 'cancelled'], true)), - 'task_id' => $this->firstText($fulfillment['task_id'] ?? null, - $invoice['task_id'] ?? null), - 'instance_id' => $this->firstText($fulfillment['instance_id'] ?? null, - $invoice['instance_id'] ?? null), - ]; - } - - private 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'], - }; - } - - private function invoiceFulfillmentStatus(string $status, - string $purpose = 'provision'): 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 function formatTimestamp($value, string $fallback = '暂未提供'): string - { - return is_numeric($value) && (int) $value > 0 - ? date('Y/m/d H:i:s', (int) $value) : $fallback; - } - - private function formatMemory(int $memoryMiB): string - { - $memoryGiB = $memoryMiB / 1024; - return number_format($memoryGiB, $memoryGiB === floor($memoryGiB) ? 0 : 1, - '.', ',') . ' GB'; - } - private function formatBytes(int $bytes, bool $unlimitedZero = false): string { if ($bytes === 0 && $unlimitedZero) { @@ -865,39 +504,6 @@ final class CloudPageController return number_format($amount, $precision, '.', '') . ' ' . $units[$unit]; } - private 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 function firstText(...$values): string - { - foreach ($values as $value) { - $text = trim((string) ($value ?? '')); - if ($text !== '') { - return $text; - } - } - return ''; - } - - private function formatUsd($value): string - { - if (!is_numeric($value) || (float) $value < 0) { - return '$—'; - } - return '$' . number_format((float) $value, 2, '.', ','); - } - private function pageNumber($value): int { return !is_array($value) diff --git a/web/app/Services/Cloud/CloudInvoicePageService.php b/web/app/Services/Cloud/CloudInvoicePageService.php index f8743f88..558e4e52 100644 --- a/web/app/Services/Cloud/CloudInvoicePageService.php +++ b/web/app/Services/Cloud/CloudInvoicePageService.php @@ -54,6 +54,15 @@ final class CloudInvoicePageService ); } + /** 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 diff --git a/web/app/Services/Cloud/CloudInvoiceService.php b/web/app/Services/Cloud/CloudInvoiceService.php index a68cedd3..88a90915 100644 --- a/web/app/Services/Cloud/CloudInvoiceService.php +++ b/web/app/Services/Cloud/CloudInvoiceService.php @@ -879,15 +879,10 @@ final class CloudInvoiceService foreach ($records as $invoice) { $ownerId = (int) $invoice->user_id; $purpose = (string) ($invoice->purpose ?: 'renewal'); - $title = match ($purpose) { - 'recharge' => '余额充值', - 'provision' => '实例开通', - 'renewal' => '实例续费', - 'upgrade' => '实例升级', - 'ip_change' => '更换公网 IP', - 'backup_addon' => '自动备份开通', - default => '账单', - }; + $title = CloudBillingPresentationCatalog::knownPurposeLabel($purpose); + if ($title === '') { + $title = '账单'; + } $order = $purpose === 'provision' && $invoice->order_id !== null ? ($orders[self::listKey($ownerId, (int) $invoice->order_id)] ?? null) : null; @@ -1216,15 +1211,10 @@ final class CloudInvoiceService { $now = time(); $purpose = (string) ($invoice->purpose ?: 'renewal'); - $title = match ($purpose) { - 'recharge' => '余额充值', - 'provision' => '实例开通', - 'renewal' => '实例续费', - 'upgrade' => '实例升级', - 'ip_change' => '更换公网 IP', - 'backup_addon' => '自动备份开通', - default => '账单', - }; + $title = CloudBillingPresentationCatalog::knownPurposeLabel($purpose); + if ($title === '') { + $title = '账单'; + } $order = $purpose !== 'provision' || $invoice->order_id === null ? null : CloudOrder::where('id', $invoice->order_id) ->where('user_id', $invoice->user_id) diff --git a/web/public/cloud/invoices.js b/web/public/cloud/invoices.js index 541244eb..a4a78c34 100644 --- a/web/public/cloud/invoices.js +++ b/web/public/cloud/invoices.js @@ -86,12 +86,6 @@ function makeElement(tag, className = '', content) { return element; } -function formatUsd(value) { - const amount = Number(value); - if (!Number.isFinite(amount) || amount < 0) return '$—'; - return `$${amount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; -} - function invoiceNeedsPolling(invoice) { return invoice?.polling_required === true; } @@ -226,7 +220,9 @@ async function loadInvoices(page = state.page, updateUrl = true, resetBudget = f purpose: payload?.purpose, }); syncFilters(); - if (byId('invoices-balance')) byId('invoices-balance').textContent = formatUsd(payload?.balance); + if (byId('invoices-balance')) { + byId('invoices-balance').textContent = String(payload?.balance_display || '$—'); + } renderInvoices(); if (updateUrl) updatePageUrl(state.page); showError(); diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index f04014ff..7c2fad6f 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026110120' scope='global'} +{assign var=venix_asset_version value='2026110121' scope='global'} diff --git a/web/tests/AdminBillingApiContractTest.php b/web/tests/AdminBillingApiContractTest.php index b9af9236..5e66d714 100644 --- a/web/tests/AdminBillingApiContractTest.php +++ b/web/tests/AdminBillingApiContractTest.php @@ -329,7 +329,7 @@ $assert(str_contains($invoicePresentation, && !str_contains($invoicePresentation, 'match (strtolower($status))'), 'User invoice statuses must translate catalog tones, not rebuild semantics.'); $assert(str_contains($layoutAssets, - "venix_asset_version value='2026110120'") + "venix_asset_version value='2026110121'") && str_contains($template, '/cloud/admin-billing.js?v={$venix_asset_version}'), 'Administrator billing asset changes must advance the shared cache key.'); diff --git a/web/tests/CloudAssetVersionContractTest.php b/web/tests/CloudAssetVersionContractTest.php index b1ad1c31..f21228dd 100644 --- a/web/tests/CloudAssetVersionContractTest.php +++ b/web/tests/CloudAssetVersionContractTest.php @@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void { }; $assert(is_string($assets) - && str_contains($assets, "venix_asset_version value='2026110120'") + && str_contains($assets, "venix_asset_version value='2026110121'") && is_string($cloudShell) && str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'), 'The cloud application entry must use the shared Venix asset version.'); diff --git a/web/tests/CloudAutomaticBackupInvoicePresentationTest.php b/web/tests/CloudAutomaticBackupInvoicePresentationTest.php index 594a996c..a4c64ccb 100644 --- a/web/tests/CloudAutomaticBackupInvoicePresentationTest.php +++ b/web/tests/CloudAutomaticBackupInvoicePresentationTest.php @@ -23,7 +23,8 @@ $adminPresentation = $read('app/Services/Cloud/CloudAdminBillingPresentation.php $assert(str_contains($pageService, "'backup_addon'") && substr_count($invoiceService, - "'backup_addon' => '自动备份开通'") >= 2, + 'CloudBillingPresentationCatalog::knownPurposeLabel(') === 2 + && str_contains($catalog, "'backup_addon' => '自动备份开通'"), 'Automatic-backup bills are not recognized by user invoice services.'); $assert(str_contains($listTemplate, 'value="backup_addon"') && str_contains($listRuntime, 'invoice?.title') diff --git a/web/tests/CloudInvoiceDetailContractTest.php b/web/tests/CloudInvoiceDetailContractTest.php index f8e9e3c7..5fff4870 100644 --- a/web/tests/CloudInvoiceDetailContractTest.php +++ b/web/tests/CloudInvoiceDetailContractTest.php @@ -145,7 +145,11 @@ $listMethod = $section($apiController, 'public function invoices(', 'private function createProvisionInvoice('); $assert(str_contains($listMethod, 'CloudInvoicePageService::queryForUser(') && str_contains($listMethod, 'is_array($query) ? $query : []') - && str_contains($listMethod, "\$payload['balance']"), + && str_contains($listMethod, '(string) $user->money') + && str_contains($invoicePageService, "\$payload['balance']") + && str_contains($invoicePageService, "\$payload['balance_display']") + && str_contains($invoicePageService, + 'CloudBillingPresentationCatalog::money('), 'The invoice list is not using its bounded full-list server-side pagination contract.'); $assert(!str_contains($listMethod, 'CloudInvoiceService::display(') && !str_contains($listMethod, 'CloudInvoicePaymentService::methods(') diff --git a/web/tests/CloudInvoiceListBehaviorTest.mjs b/web/tests/CloudInvoiceListBehaviorTest.mjs index 27e30b3a..4891a318 100644 --- a/web/tests/CloudInvoiceListBehaviorTest.mjs +++ b/web/tests/CloudInvoiceListBehaviorTest.mjs @@ -55,7 +55,7 @@ const payload = (id, overrides = {}) => ({ filters: { purpose: 'all', status: 'all', keyword: '', date_from: '', date_to: '' }, pagination: { page: 1, per_page: 25, total: 1, total_pages: 1, has_previous: false, has_next: false, from: 1, to: 1 }, - balance: '20.00', ...overrides, + balance: '20.00', balance_display: '$20.00', ...overrides, }); const deferred = () => { let resolve; @@ -136,6 +136,7 @@ const response = value => ({ ok: true, status: 200, json: async () => structured 'A superseded invoice read was not aborted.'); second.resolve(response(payload(2, { + balance: '999.00', balance_display: '20.00 EUR', filters: { purpose: 'all', status: 'all', keyword: 'second-vm', date_from: '', date_to: '' }, pagination: { page: 1, per_page: 25, total: 30, total_pages: 2, @@ -157,6 +158,8 @@ const response = value => ({ ok: true, status: 200, json: async () => structured 'Invoice list rebuilt its fulfillment state from raw task fields.'); assert.doesNotMatch(rendered, /\$999\.00/, 'Invoice list formatted the raw amount instead of consuming its presentation.'); + assert.equal(page.nodes.get('invoices-balance').textContent, '20.00 EUR', + 'Invoice list reformatted the raw wallet balance instead of consuming its presentation.'); first.resolve(response(payload(1, { filters: { purpose: 'all', status: 'all', keyword: 'first-vm', diff --git a/web/tests/CloudInvoicePageServiceTest.php b/web/tests/CloudInvoicePageServiceTest.php index 2b9165ae..91bff92b 100644 --- a/web/tests/CloudInvoicePageServiceTest.php +++ b/web/tests/CloudInvoicePageServiceTest.php @@ -353,18 +353,23 @@ Capsule::table('cloud_invoices')->insert([ 'created_at' => $filterCreatedAt, ], ]); -$combined = CloudInvoicePageService::queryForUser(1, [ - 'purpose' => 'ip_change', - 'status' => 'pending', - 'keyword' => 'edge-search-vm', - 'date_from' => '2026-10-20', - 'date_to' => '2026-10-20', -]); +$combined = CloudInvoicePageService::withBalance( + CloudInvoicePageService::queryForUser(1, [ + 'purpose' => 'ip_change', + 'status' => 'pending', + 'keyword' => 'edge-search-vm', + 'date_from' => '2026-10-20', + 'date_to' => '2026-10-20', + ]), + '42.50' +); $assert($combined['pagination']['total'] === 16 && count($combined['invoices']) === 16 && !in_array('200', array_column($combined['invoices'], 'id'), true) && ($combined['filters']['status'] ?? null) === 'pending' - && ($combined['filters']['keyword'] ?? null) === 'edge-search-vm', + && ($combined['filters']['keyword'] ?? null) === 'edge-search-vm' + && ($combined['balance'] ?? null) === '42.50' + && ($combined['balance_display'] ?? null) === '$42.50', 'Combined invoice filters escaped owner scope or changed normalized input.'); $localDate = CloudInvoicePageService::queryForUser(1, [ 'purpose' => 'ip_change', diff --git a/web/tests/CloudInvoicePresentationTest.php b/web/tests/CloudInvoicePresentationTest.php index 9ab7c33b..18420a18 100644 --- a/web/tests/CloudInvoicePresentationTest.php +++ b/web/tests/CloudInvoicePresentationTest.php @@ -2,18 +2,13 @@ require dirname(__DIR__) . '/vendor/autoload.php'; -use App\Controllers\CloudPageController; +use App\Services\Cloud\CloudInvoicePresentation; $assert = static function (bool $condition, string $message): void { if (!$condition) { throw new RuntimeException($message); } }; -$invoke = static function (object $target, string $method, array $arguments = []) { - $reflection = new ReflectionMethod($target, $method); - return $reflection->invokeArgs($target, $arguments); -}; - $payload = [ 'invoice' => [ 'id' => '17', @@ -48,8 +43,7 @@ $payload = [ 'payment_methods' => [], ]; -$controller = new CloudPageController(); -$view = $invoke($controller, 'invoiceDetailView', [$payload]); +$view = CloudInvoicePresentation::detail($payload); $assert(($view['show_line_items'] ?? false) === true, 'Invoice first paint does not expose its frozen line items.'); @@ -77,7 +71,7 @@ $resumePayload['active_payment'] = [ 'payment' => null, 'can_submit' => true, ]; -$resumeView = $invoke($controller, 'invoiceDetailView', [$resumePayload]); +$resumeView = CloudInvoicePresentation::detail($resumePayload); $assert(($resumeView['show_payment'] ?? false) === true && ($resumeView['payment_title'] ?? null) === '选择支付方式' && str_contains( @@ -91,7 +85,7 @@ $gracePayload = $payload; $gracePayload['invoice']['status'] = 'overdue'; $gracePayload['invoice']['display_status'] = 'renewal_grace'; $gracePayload['invoice']['payable'] = true; -$graceView = $invoke($controller, 'invoiceDetailView', [$gracePayload]); +$graceView = CloudInvoicePresentation::detail($gracePayload); $assert(($graceView['status_label'] ?? null) === '已到期,宽限期内可续费' && ($graceView['status_class'] ?? null) === 'warning', 'Payable renewal grace was presented as a failed overdue invoice.'); @@ -117,10 +111,10 @@ $ipChangePayload = [ 'balance_payment_allowed' => false, 'payment_methods' => [], ]; -$ipChangeView = $invoke($controller, 'invoiceDetailView', [$ipChangePayload]); -$ipChangeRow = $invoke($controller, 'invoiceListRow', [ +$ipChangeView = CloudInvoicePresentation::detail($ipChangePayload); +$ipChangeRow = CloudInvoicePresentation::summaries([ $ipChangePayload['invoice'], -]); +])[0]; $assert(($ipChangeView['show_fulfillment'] ?? false) === true && ($ipChangeView['fulfillment_title'] ?? null) === '公网 IP 更换进度' && ($ipChangeView['fulfillment_label'] ?? null) === '待人工核对' @@ -135,6 +129,18 @@ $detailRuntime = file_get_contents( dirname(__DIR__) . '/public/cloud/invoice-detail-runtime.js' ); $listRuntime = file_get_contents(dirname(__DIR__) . '/public/cloud/invoices.js'); +$adminRuntime = file_get_contents( + dirname(__DIR__) . '/public/cloud/admin-billing.js' +); +$adminRows = file_get_contents( + dirname(__DIR__) . '/resources/views/venix/admin/billing_rows.tpl' +); +$pageController = file_get_contents( + dirname(__DIR__) . '/app/Controllers/CloudPageController.php' +); +$invoiceService = file_get_contents( + dirname(__DIR__) . '/app/Services/Cloud/CloudInvoiceService.php' +); $assert(is_string($detailRuntime) && is_string($listRuntime) && str_contains($detailRuntime, 'payload.presentation') && str_contains($detailRuntime, 'result?.presentation_patch') @@ -157,10 +163,27 @@ $assert(is_string($detailRuntime) && is_string($listRuntime) && str_contains($listRuntime, 'invoice?.status_class') && str_contains($listRuntime, 'invoice?.fulfillment_label') && str_contains($listRuntime, 'invoice?.polling_required === true') + && str_contains($listRuntime, 'payload?.balance_display') + && !str_contains($listRuntime, 'function formatUsd(') && !str_contains($listRuntime, 'function invoiceStatusInfo(') && !str_contains($listRuntime, 'function fulfillmentStatusInfo(') && !str_contains($listRuntime, "renewal_grace: ['已到期,宽限期内可续费', 'warning']"), 'Invoice list client must consume the server presentation without rebuilding it.'); +$assert(is_string($adminRuntime) && is_string($adminRows) + && is_string($pageController) && is_string($invoiceService) + && !preg_match('/function\s+(?:formatUsd|formatDate|purposeLabel|providerLabel|statusInfo)\s*\(/', + $adminRuntime) + && !str_contains($adminRows, "['open'=>'待支付'") + && !str_contains($adminRows, "'paytaro'=>'Paytaro'") + && !str_contains($pageController, 'private function invoiceListRow(') + && !str_contains($pageController, 'private function invoiceDetailView(') + && !str_contains($pageController, 'private function invoiceStatus(') + && !str_contains($pageController, 'private function invoiceFulfillmentStatus(') + && !str_contains($pageController, 'private function formatUsd(') + && substr_count($invoiceService, + 'CloudBillingPresentationCatalog::knownPurposeLabel(') === 2, + 'Billing presentation drifted back into a browser, template, controller, or read model.'); + echo "Cloud invoice SSR presentation checks passed.\n"; diff --git a/web/tests/CloudPlanDefinitionTest.php b/web/tests/CloudPlanDefinitionTest.php index baa32747..7607f166 100644 --- a/web/tests/CloudPlanDefinitionTest.php +++ b/web/tests/CloudPlanDefinitionTest.php @@ -72,6 +72,10 @@ namespace { . file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/offer_form.tpl'); $invoiceView = file_get_contents(dirname(__DIR__) . '/resources/views/venix/cloud/pages/invoices.tpl'); $invoiceService = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudInvoiceService.php'); + $invoicePresentation = file_get_contents(dirname(__DIR__) + . '/app/Services/Cloud/CloudInvoicePresentation.php'); + $invoicePageService = file_get_contents(dirname(__DIR__) + . '/app/Services/Cloud/CloudInvoicePageService.php'); $invoicePaymentService = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudInvoicePaymentService.php'); $paymentProviders = implode("\n", [ file_get_contents(dirname(__DIR__) . '/app/Services/Payment/YipayPaymentService.php'), @@ -122,7 +126,10 @@ namespace { 'Invoice API output must expose its deletion deadline and authoritative payable flag.'); $assert(str_contains($client, 'function invoiceCanPay(invoice)') && substr_count($client, 'if (!invoiceCanPay(invoice))') >= 2 - && str_contains($client, '已超过支付截止时间'), + && str_contains($client, + "invoice?.payable === true && invoice?.available_action === 'pay'") + && str_contains($invoicePresentation, + "(\$invoice['payable'] ?? false) === true"), 'Expired invoice rows must not render a balance or provider payment action.'); $assert(str_contains($routes, "['GET', 'POST'], '/invoices'") && str_contains($routes, "'/invoices/by-request/{key:[A-Za-z0-9_.-]+}'") @@ -149,8 +156,10 @@ namespace { && str_contains($client, 'formatUsd(backupPrice)') && str_contains($client, 'formatUsd(total)') && !str_contains($client, 'formatUsd(offer.price)') - && str_contains($client, 'formatUsd(invoice.amount)') - && str_contains($client, 'formatUsd(balance)') + && str_contains($invoicePresentation, + 'CloudBillingPresentationCatalog::money(') + && str_contains($invoicePageService, + "CloudBillingPresentationCatalog::money(\$balance, 'USD')") && !str_contains($client, '¥') && !str_contains($invoiceView, '¥') && str_contains($invoiceView, '$cloud_invoice_balance') && str_contains($invoiceView, '$invoice.amount_display'),