diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index 802766be..6d5bc68c 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -347,7 +347,7 @@ final class CloudPageController } return $this->render($response, 'invoice-detail', '账单详情', '', $invoiceId, [ - 'cloud_invoice_detail_view' => CloudInvoicePresentation::detail($payload), + 'cloud_invoice_detail_view' => $payload['presentation'], 'cloud_invoice_detail_bootstrap_json' => $this->safeJson($payload), ]); } diff --git a/web/app/Services/Cloud/CloudInvoiceDetailPageService.php b/web/app/Services/Cloud/CloudInvoiceDetailPageService.php index b80e14c1..00414131 100644 --- a/web/app/Services/Cloud/CloudInvoiceDetailPageService.php +++ b/web/app/Services/Cloud/CloudInvoiceDetailPageService.php @@ -53,7 +53,7 @@ final class CloudInvoiceDetailPageService if ($activePayment !== null) { $activePayment['can_submit'] = $canStartPayment; } - return [ + $payload = [ 'invoice' => $detail, 'active_payment' => $activePayment, 'payment_methods' => $canStartPayment @@ -66,6 +66,8 @@ final class CloudInvoiceDetailPageService 'username' => (string) ($user->user_name ?: $user->email), 'admin' => $isAdmin, ]; + $payload['presentation'] = CloudInvoicePresentation::detail($payload); + return $payload; } /** @@ -149,10 +151,13 @@ final class CloudInvoiceDetailPageService $activePayment['can_submit'] = ($status['payable'] ?? false) === true; } - return [ + $payload = [ 'invoice' => $status, 'active_payment' => $activePayment, ]; + $payload['presentation_patch'] = + CloudInvoicePresentation::statusPatch($payload); + return $payload; }, 3 ); } diff --git a/web/app/Services/Cloud/CloudInvoicePresentation.php b/web/app/Services/Cloud/CloudInvoicePresentation.php index 3b08e842..a79e28ce 100644 --- a/web/app/Services/Cloud/CloudInvoicePresentation.php +++ b/web/app/Services/Cloud/CloudInvoicePresentation.php @@ -117,6 +117,10 @@ final class CloudInvoicePresentation return [ 'id' => (string) ($invoice['id'] ?? ''), 'title' => self::invoiceTitle($invoice, $purpose), + 'number_text' => '账单 #' . (string) ($invoice['id'] ?? '—'), + 'created_text' => '创建于 ' . $created, + 'subtitle' => '账单 #' . (string) ($invoice['id'] ?? '—') + . ' · ' . $created, 'created_display' => $created, 'amount_display' => self::formatMoney( $invoice['amount'] ?? null, @@ -144,6 +148,16 @@ final class CloudInvoicePresentation '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 + ), ]; } @@ -190,6 +204,8 @@ final class CloudInvoicePresentation 'invoice' => $mutable, 'active_payment' => $activePayment, 'status' => [ + 'code' => (string) ($invoice['display_status'] + ?? $invoice['status'] ?? ''), 'label' => $statusLabel, 'class' => $statusClass, ], @@ -201,6 +217,11 @@ final class CloudInvoicePresentation ], 'fulfillment' => $fulfillment, 'polling' => [ + 'required' => self::pollingRequired( + $invoice, + $activePayment, + $fulfillment + ), 'task_id' => self::firstText( $rawFulfillment['task_id'] ?? null, $invoice['task_id'] ?? null @@ -215,6 +236,11 @@ final class CloudInvoicePresentation 'job_updated_at' => ($invoice['job_updated_at'] ?? null) === null ? null : max(0, (int) $invoice['job_updated_at']), ], + 'completion_notice' => self::completionNotice( + $invoice, + $purpose, + $fulfillment + ), ]; } @@ -455,9 +481,118 @@ final class CloudInvoicePresentation $fulfillment['instance_id'] ?? null, $invoice['instance_id'] ?? null ), + 'status_code' => $fulfillmentStatus, ]; } + /** + * @param array $invoice + * @param array|null $activePayment + * @param array $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 $invoice + * @param array $fulfillment + * @return array{message: 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' => [ + 'message' => '实例升级完成。', 'tone' => 'success', + ], + 'failed', 'cancelled', 'canceled' => [ + 'message' => '实例升级未完成,请在账单详情查看任务状态。', + 'tone' => 'error', + ], + default => null, + }; + } + if ($purpose === 'ip_change') { + return match ($taskStatus) { + 'succeeded', 'completed' => [ + 'message' => '公网 IP 已更换。', 'tone' => 'success', + ], + 'review' => [ + 'message' => '公网 IP 更换结果待人工核对,请勿重复提交。', + 'tone' => 'error', + ], + 'failed', 'cancelled', 'canceled' => [ + 'message' => '公网 IP 更换未完成,请在账单详情查看任务状态。', + 'tone' => 'error', + ], + default => null, + }; + } + if ($purpose === 'provision') { + return match ($taskStatus) { + 'succeeded', 'completed' => [ + 'message' => '实例已创建完成。', 'tone' => 'success', + ], + 'refunded' => [ + 'message' => '实例创建失败,款项已退回账户余额。', + 'tone' => 'error', + ], + 'failed', 'expired', 'cancelled', 'canceled' => [ + 'message' => '实例开通未完成,请在账单详情查看任务状态。', + 'tone' => 'error', + ], + default => null, + }; + } + return [ + 'message' => $purpose === 'renewal' + ? '账单支付成功,服务期限已延长。' : '账单支付成功。', + 'tone' => 'success', + ]; + } + if (in_array($status, ['void', 'expired'], true)) { + return [ + 'message' => '账单已失效,到账金额会保留在账户余额中。', + 'tone' => 'error', + ]; + } + if ($status === 'refunded') { + return [ + 'message' => '实例创建失败,款项已退回账户余额。', + 'tone' => 'error', + ]; + } + if (($invoice['payable'] ?? false) !== true + && in_array($status, ['open', 'overdue'], true)) { + return [ + 'message' => match ($purpose) { + 'provision' => '开通账单已超过支付截止时间。', + 'renewal' => '续费宽限期已经结束,到账金额会保留在账户余额中。', + default => '账单已超过支付截止时间。', + }, + 'tone' => 'error', + ]; + } + return null; + } + /** * @param array $invoice * @return array diff --git a/web/public/cloud/invoice-detail-runtime.js b/web/public/cloud/invoice-detail-runtime.js index 41ed1d16..a75aa1ac 100644 --- a/web/public/cloud/invoice-detail-runtime.js +++ b/web/public/cloud/invoice-detail-runtime.js @@ -35,12 +35,9 @@ const state = { username: '', admin: false, selectedInvoice: null, + presentation: null, selectedInvoicePaymentMethod: '', - invoicePaymentMethods: [], activePayment: null, - balancePaymentAllowed: false, - invoiceBalance: '0.00', - invoiceJobProgress: new Map(), mutationBusy: false, onlinePaymentPending: false, onlinePaymentExpiresAt: 0, @@ -86,15 +83,6 @@ function terminalTaskProblem(task, fallback) { : message; } -function firstNumber(...values) { - for (const value of values) { - if (value === null || value === undefined || value === '') continue; - const number = Number(value); - if (Number.isFinite(number) && number >= 0) return number; - } - return null; -} - function makeElement(tag, className = '', content) { const element = document.createElement(tag); if (className) element.className = className; @@ -210,8 +198,6 @@ function applySession(payload) { state.username = firstText(payload?.username, nested.username, nested.name, state.username, '用户'); state.admin = payload?.admin === true || Number(payload?.admin) === 1 || nested.admin === true || Number(nested.admin) === 1; - state.invoiceBalance = String(payload?.balance ?? state.invoiceBalance); - state.balancePaymentAllowed = payload?.balance_payment_allowed === true; text('current-username', state.username); for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) { const link = byId(id); @@ -230,207 +216,8 @@ function serviceTimestamp(value) { return Number.isFinite(parsed) ? parsed : null; } -function formatOrderDate(value) { - const timestamp = serviceTimestamp(value); - const date = new Date(timestamp ?? Number.NaN); - return Number.isFinite(date.getTime()) - ? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录'; -} - -function formatServiceDate(value) { - const timestamp = serviceTimestamp(value); - return timestamp === null ? '暂未提供' - : new Date(timestamp).toLocaleString('zh-CN', { hour12: false }); -} - -function formatUsd(value) { - const amount = Number(value); - if (!Number.isFinite(amount) || amount < 0) return '$—'; - return `$${amount.toLocaleString('en-US', { - minimumFractionDigits: 2, - maximumFractionDigits: 2, - })}`; -} - -function formatMemoryGiB(memoryMib) { - const amount = Number(memoryMib); - if (!Number.isFinite(amount) || amount < 0) return '— GB'; - return `${(amount / 1024).toLocaleString('en-US', { maximumFractionDigits: 1 })} GB`; -} - -function formatBytes(value) { - if (value === null || !Number.isFinite(value) || value < 0) return '暂未提供'; - const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; - let amount = value; - let unit = 0; - while (amount >= 1024 && unit < units.length - 1) { - amount /= 1024; - unit += 1; - } - const precision = unit === 0 ? 0 : amount >= 100 ? 0 : amount >= 10 ? 1 : 2; - return `${amount.toFixed(precision)} ${units[unit]}`; -} - -function formatTrafficQuota(value) { - return value === 0 ? '不限流量' : formatBytes(value); -} - -function invoicePurpose(invoice) { - const value = firstText(invoice?.purpose, invoice?.kind, - invoice?.invoice_type, invoice?.type).toLowerCase(); - if (['recharge', 'topup', 'top_up', 'balance', 'deposit'].includes(value)) return 'recharge'; - if (['provision', 'provisioning', 'initial', 'create'].includes(value)) return 'provision'; - if (['renewal', 'renew', 'subscription'].includes(value)) return 'renewal'; - if (value === 'upgrade') return 'upgrade'; - if (value === 'ip_change') return 'ip_change'; - if (value === 'backup_addon') return 'backup_addon'; - return ''; -} - -function invoiceTitle(invoice) { - const purpose = invoicePurpose(invoice); - return firstText(invoice?.type_label, invoice?.title, { - recharge: '余额充值', - provision: '实例开通', - renewal: '实例续费', - upgrade: '实例升级', - ip_change: '更换公网 IP', - backup_addon: '自动备份开通', - }[purpose], '账单'); -} - -function invoiceStatusInfo(status) { - const values = { - open: ['待支付', 'warning'], - renewal_grace: ['已到期,宽限期内可续费', 'warning'], - overdue: ['已逾期', 'failed'], - paid: ['已支付', 'running'], - refunded: ['已退款', 'other'], - void: ['已失效', 'other'], - expired: ['已失效', 'failed'], - deleting: ['实例删除中', 'failed'], - delete_failed: ['自动删除失败', 'failed'], - purge_pending: ['等待永久删除', 'failed'], - purge_stopping: ['删除前正在关机', 'failed'], - purge_force_required: ['等待管理员确认强制删除', 'failed'], - purge_deleting: ['实例删除中', 'failed'], - purge_stop_failed: ['删除前关机失败', 'failed'], - purge_failed: ['自动删除失败', 'failed'], - }; - return values[String(status || '').toLowerCase()] - || [String(status || '未知'), 'other']; -} - -function paymentLabel(value) { - const method = String(value || '').trim(); - const labels = { - balance: '账户余额', - yipay_alipay: '易支付 · 支付宝', - yipay_wxpay: '易支付 · 微信', - paytaro: 'Paytaro · 支付宝', - stripe_card: 'Stripe · 银行卡', - stripe_alipay: 'Stripe · 支付宝', - usdt: 'USDT-TRC20', - }; - return labels[method.toLowerCase()] || method; -} - -function invoiceDeletionTimestamp(invoice) { - return serviceTimestamp(invoice?.deletion_at ?? invoice?.delete_at - ?? invoice?.grace_ends_at ?? null); -} - -function invoicePaymentDeadlineTimestamp(invoice) { - return serviceTimestamp(invoice?.payment_deadline_at ?? invoice?.payable_until - ?? invoice?.payment_due_at ?? null); -} - function invoiceCanPay(invoice) { - const purpose = invoicePurpose(invoice); - if (!['provision', 'renewal'].includes(purpose)) return false; - if (!['open', 'overdue'].includes(String(invoice?.status || '').toLowerCase())) return false; - if (invoice?.payable === false) return false; - if (invoice?.payable === true) return true; - const deadline = purpose === 'renewal' - ? invoiceDeletionTimestamp(invoice) : invoicePaymentDeadlineTimestamp(invoice); - return deadline === null || Date.now() < deadline; -} - -function provisionInvoiceData(invoice) { - const fulfillment = invoice?.fulfillment && typeof invoice.fulfillment === 'object' - ? invoice.fulfillment : {}; - return { - status: firstText(fulfillment.fulfillment_status, invoice?.fulfillment_status).toLowerCase(), - taskId: firstText(fulfillment.task_id, invoice?.task_id), - instanceId: firstText(fulfillment.instance_id, invoice?.instance_id), - instanceUuid: firstText(fulfillment.instance_uuid, invoice?.instance_uuid), - phase: firstText(fulfillment.phase, invoice?.phase), - error: firstText(fulfillment.error, invoice?.error), - }; -} - -function provisionStatusInfo(invoice) { - const data = provisionInvoiceData(invoice); - const status = data.status; - const values = { - awaiting_payment: ['等待支付', 'warning'], - active: ['创建中', 'warning'], - succeeded: ['已开通', 'running'], - failed: ['创建失败', 'failed'], - expired: ['已失效', 'failed'], - refunded: ['开通失败,已退款', 'failed'], - cancelled: ['已取消', 'failed'], - }; - return { data, status, display: values[status] || ['履约状态协议无效', 'failed'] }; -} - -function provisionFinished(invoice) { - const { status } = provisionStatusInfo(invoice); - return ['succeeded', 'failed', 'expired', 'refunded', 'cancelled'].includes(status); -} - -function upgradeInvoiceData(invoice) { - return { - status: firstText(invoice?.job_status, invoice?.fulfillment_status).toLowerCase(), - taskId: firstText(invoice?.task_id), - instanceId: firstText(invoice?.instance_id), - phase: firstText(invoice?.phase), - error: firstText(invoice?.error), - }; -} - -function upgradeStatusInfo(invoice) { - const data = upgradeInvoiceData(invoice); - const values = { - active: ['升级中', 'warning'], - succeeded: ['已升级', 'running'], - failed: ['升级失败', 'failed'], - cancelled: ['已取消', 'failed'], - }; - return { data, status: data.status, - display: values[data.status] || ['等待升级任务', 'warning'] }; -} - -function upgradeFinished(invoice) { - return ['succeeded', 'failed', 'cancelled'].includes(upgradeStatusInfo(invoice).status); -} - -function ipChangeStatusInfo(invoice) { - const data = upgradeInvoiceData(invoice); - const values = { - active: ['更换中', 'warning'], - succeeded: ['已更换', 'running'], - review: ['待人工核对', 'warning'], - failed: ['更换失败', 'failed'], - cancelled: ['已取消', 'failed'], - }; - return { data, status: data.status, - display: values[data.status] || ['等待更换任务', 'warning'] }; -} - -function ipChangeFinished(invoice) { - return ['succeeded', 'review', 'failed', 'cancelled'] - .includes(ipChangeStatusInfo(invoice).status); + return invoice?.payable === true && invoice?.available_action === 'pay'; } function invoiceFact(label, value) { @@ -442,90 +229,37 @@ function invoiceFact(label, value) { return item; } -function invoiceSpecification(invoice) { - const candidates = [invoice?.specification, invoice?.spec, invoice?.plan_snapshot, - invoice?.order_snapshot, invoice?.fulfillment?.specification, - invoice?.fulfillment?.spec]; - const spec = candidates.find(value => value && typeof value === 'object') || {}; - return { - cpu: firstNumber(invoice?.cpu_cores, invoice?.vcpu, spec.cpu_cores, spec.vcpu), - memoryMib: firstNumber(invoice?.memory_mib, spec.memory_mib), - memoryGib: firstNumber(invoice?.memory_gib, spec.memory_gib), - diskGib: firstNumber(invoice?.disk_gib, invoice?.disk_size_gib, - spec.disk_gib, spec.disk_size_gib), - bandwidthMbps: firstNumber(invoice?.bandwidth_mbps, spec.bandwidth_mbps), - }; -} - -function renderInvoiceLineItems(invoice) { +function renderInvoiceLineItems(presentation) { const panel = byId('invoice-line-items-panel'); const container = byId('invoice-line-items'); if (!panel || !container) return; - const items = Array.isArray(invoice?.items) ? invoice.items : []; + const items = Array.isArray(presentation?.line_items) + ? presentation.line_items : []; const rows = items.flatMap(item => { if (!item || typeof item !== 'object' || Array.isArray(item)) return []; - const amount = Number(item.amount); - if (!Number.isFinite(amount) || amount < 0) return []; const row = makeElement('div', 'invoice-line-item'); row.setAttribute('role', 'listitem'); row.append( makeElement('span', '', firstText(item.label, '费用项目')), - makeElement('strong', '', formatUsd(item.amount)), + makeElement('strong', '', firstText(item.amount_display, '$—')), ); return [row]; }); container.replaceChildren(...rows); - panel.hidden = rows.length === 0; + panel.hidden = presentation?.show_line_items !== true || rows.length === 0; } -function renderInvoiceSpecification(invoice) { +function renderInvoiceSpecification(presentation) { const panel = byId('invoice-specification-panel'); const container = byId('invoice-specification'); if (!panel || !container) return; - const purpose = invoicePurpose(invoice); - if (!['provision', 'renewal', 'upgrade', 'ip_change', 'backup_addon'].includes(purpose)) { - panel.hidden = true; - container.replaceChildren(); - return; - } - const subject = firstText(invoice.requested_name, invoice.instance_name, - purpose === 'provision' ? '待创建实例' : '实例'); - if (purpose === 'ip_change' || purpose === 'backup_addon') { - const facts = [ - invoiceFact('实例', subject), - invoiceFact('服务内容', purpose === 'ip_change' - ? '更换公网 IP' : '自动备份服务开通'), - ]; - if (firstText(invoice?.instance_id)) { - const item = makeElement('div', 'invoice-detail-fact'); - const value = makeElement('dd'); - const link = makeElement('a', 'row-button', '查看实例'); - link.href = `/user/cloud/instances/${encodeURIComponent(String(invoice.instance_id))}`; - value.append(link); - item.append(makeElement('dt', '', '关联实例'), value); - facts.push(item); - } - container.replaceChildren(...facts); - panel.hidden = false; - return; - } - const spec = invoiceSpecification(invoice); - const facts = [ - invoiceFact('实例', subject), - invoiceFact('套餐', firstText(invoice.plan_name, '云服务器套餐')), - ]; - if (spec.cpu !== null) facts.push(invoiceFact('CPU', `${spec.cpu} 核`)); - if (spec.memoryMib !== null) facts.push(invoiceFact('内存', formatMemoryGiB(spec.memoryMib))); - else if (spec.memoryGib !== null) facts.push(invoiceFact('内存', `${spec.memoryGib} GB`)); - if (spec.diskGib !== null) facts.push(invoiceFact('系统盘', `${spec.diskGib} GB`)); - if (spec.bandwidthMbps !== null) facts.push(invoiceFact('带宽', `${spec.bandwidthMbps} Mbps`)); - if (purpose !== 'upgrade') { - facts.push(invoiceFact('服务周期', `${Number(invoice.validity_days || 0)} 天`)); - } - facts.push(invoiceFact(purpose === 'upgrade' ? '目标周期流量' : '周期流量', - formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0)))); + const facts = (Array.isArray(presentation?.specification) + ? presentation.specification : []).flatMap(item => ( + item && typeof item === 'object' && !Array.isArray(item) + ? [invoiceFact(item.label, item.value)] : [] + )); container.replaceChildren(...facts); - panel.hidden = false; + panel.hidden = presentation?.show_specification !== true || facts.length === 0; } function invoicePaymentStorageKey(invoiceId, methodId) { @@ -714,8 +448,10 @@ function mergeInvoiceStatus(invoice, update) { function onlinePaymentFallbackExpiresAt(invoice = state.selectedInvoice) { const now = Date.now(); const maximum = now + STATUS_POLL_MAX_LIFETIME_MS; - const invoiceDeadline = invoicePurpose(invoice) === 'renewal' - ? invoiceDeletionTimestamp(invoice) : invoicePaymentDeadlineTimestamp(invoice); + const invoiceDeadline = serviceTimestamp( + String(invoice?.purpose || '').toLowerCase() === 'renewal' + ? invoice?.deletion_at : invoice?.payment_deadline_at, + ); return invoiceDeadline !== null && invoiceDeadline > now ? Math.min(invoiceDeadline, maximum) : maximum; } @@ -788,30 +524,18 @@ function scheduleOnlinePaymentExpiry(generation) { } function invoiceNeedsPolling(invoice = state.selectedInvoice) { - if (!invoice?.id) return false; - if (invoicePurpose(invoice) === 'upgrade' - && upgradeStatusInfo(invoice).status === 'active') return true; - if (invoicePurpose(invoice) === 'ip_change' - && ipChangeStatusInfo(invoice).status === 'active') return true; - if (state.onlinePaymentPending && !onlinePaymentHasExpired() - && (invoiceCanPay(invoice) - || firstText(state.activePayment?.status).toLowerCase() === 'pending')) { - return true; - } - if (invoiceCanPay(invoice) - && ['creating', 'pending', 'review'].includes( - firstText(state.activePayment?.status).toLowerCase() - )) return true; - return false; + return Boolean(invoice?.id) + && state.presentation?.polling_required === true + && !onlinePaymentHasExpired(); } function entersProvisioningAfterPayment(previousInvoice, nextInvoice, - wasAwaitingOnlinePayment) { + nextPresentation, wasAwaitingOnlinePayment) { return wasAwaitingOnlinePayment && invoiceCanPay(previousInvoice) - && invoicePurpose(nextInvoice) === 'provision' + && String(nextInvoice?.purpose || '').toLowerCase() === 'provision' && String(nextInvoice?.status || '').toLowerCase() === 'paid' - && !provisionFinished(nextInvoice); + && nextPresentation?.polling_required === true; } function resetProvisioningPollWindow() { @@ -843,54 +567,57 @@ function nextInvoicePollDelay() { ? STATUS_POLL_INTERVAL_MS : STATUS_POLL_SLOW_INTERVAL_MS; } -function pollCompletionMessage(invoice) { - const status = String(invoice?.status || '').toLowerCase(); - if (status === 'paid') { - const purpose = invoicePurpose(invoice); - if (purpose === 'upgrade') { - if (!upgradeFinished(invoice)) return null; - return upgradeStatusInfo(invoice).status === 'succeeded' - ? ['实例升级完成。', 'success'] - : ['实例升级未完成,请在账单详情查看任务状态。', 'error']; - } - if (purpose === 'ip_change') { - if (!ipChangeFinished(invoice)) return null; - const taskStatus = ipChangeStatusInfo(invoice).status; - if (taskStatus === 'succeeded') return ['公网 IP 已更换。', 'success']; - if (taskStatus === 'review') { - return ['公网 IP 更换结果待人工核对,请勿重复提交。', 'error']; - } - return ['公网 IP 更换未完成,请在账单详情查看任务状态。', 'error']; - } - if (purpose !== 'provision') { - return [purpose === 'renewal' - ? '账单支付成功,服务期限已延长。' : '账单支付成功。', 'success']; - } - if (provisionFinished(invoice)) { - const provisionStatus = provisionStatusInfo(invoice).status; - if (provisionStatus === 'succeeded') { - return ['实例已创建完成。', 'success']; - } - if (provisionStatus === 'refunded') { - return ['实例创建失败,款项已退回账户余额。', 'error']; - } - return ['实例开通未完成,请在账单详情查看任务状态。', 'error']; - } +function mergePresentationPatch(current, patch) { + const presentation = current && typeof current === 'object' ? current : {}; + const next = patch && typeof patch === 'object' ? patch : {}; + const merged = { ...presentation }; + if (next.status && typeof next.status === 'object') { + merged.status_label = firstText(next.status.label, + presentation.status_label, '未知'); + merged.status_class = firstText(next.status.class, + presentation.status_class, 'other'); + } + if (next.payment && typeof next.payment === 'object') { + merged.show_payment = next.payment.payable === true + || Boolean(next.payment.active); + merged.active_payment_message = firstText(next.payment.message); + merged.active_payment_class = firstText( + next.payment.message_class, 'invoice-payment-note', + ); } - if (['void', 'expired'].includes(status)) { - return ['账单已失效,到账金额会保留在账户余额中。', 'error']; + if (next.fulfillment && typeof next.fulfillment === 'object') { + Object.assign(merged, next.fulfillment); } - if (status === 'refunded') { - return ['实例创建失败,款项已退回账户余额。', 'error']; + if (next.polling && typeof next.polling === 'object') { + merged.polling_required = next.polling.required === true; + } + if (Object.prototype.hasOwnProperty.call(next, 'completion_notice')) { + merged.completion_notice = next.completion_notice ?? null; + } + return merged; +} + +function applyActivePaymentPatch(patch, fallbackPayload = null) { + const source = patch && Object.prototype.hasOwnProperty.call( + patch, 'active_payment', + ) ? patch : fallbackPayload; + if (!source || !Object.prototype.hasOwnProperty.call(source, 'active_payment')) { + return; } - if (!invoiceCanPay(invoice) && status !== 'paid') { - return [invoicePurpose(invoice) === 'provision' - ? '开通账单已超过支付截止时间。' - : invoicePurpose(invoice) === 'renewal' - ? '续费宽限期已经结束,到账金额会保留在账户余额中。' - : '账单已超过支付截止时间。', 'error']; + const previousActivePayment = state.activePayment; + state.activePayment = source.active_payment + && typeof source.active_payment === 'object' + && !Array.isArray(source.active_payment) + ? source.active_payment : null; + if (!state.activePayment + && (previousActivePayment || state.onlinePaymentPending)) { + clearOnlinePaymentState(true); + clearInvoicePaymentKeys(state.selectedInvoice?.id); + byId('invoice-payment-result')?.replaceChildren(); + } else if (state.activePayment + && firstText(state.activePayment.status).toLowerCase() !== 'pending') { + clearOnlinePaymentState(); } - return null; } async function pollInvoiceStatus(generation) { @@ -914,43 +641,34 @@ async function pollInvoiceStatus(generation) { timeoutMs: 10_000, }); if (generation !== state.pollGeneration) return; - const update = result?.invoice; + const patch = result?.presentation_patch; + const update = patch?.invoice ?? result?.invoice; if (readSequence >= state.appliedReadSequence && update?.id && String(update.id) === String(state.selectedInvoice?.id || '')) { state.appliedReadSequence = readSequence; - if (Object.prototype.hasOwnProperty.call(result || {}, 'active_payment')) { - const previousActivePayment = state.activePayment; - state.activePayment = result.active_payment - && typeof result.active_payment === 'object' - && !Array.isArray(result.active_payment) - ? result.active_payment : null; - if (!state.activePayment - && (previousActivePayment || state.onlinePaymentPending)) { - clearOnlinePaymentState(true); - clearInvoicePaymentKeys(state.selectedInvoice?.id); - byId('invoice-payment-result')?.replaceChildren(); - } else if (state.activePayment - && firstText(state.activePayment.status).toLowerCase() !== 'pending') { - clearOnlinePaymentState(); - } - } + applyActivePaymentPatch(patch, result); const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update); + const nextPresentation = mergePresentationPatch(state.presentation, patch); + state.selectedInvoice = nextInvoice; + state.presentation = nextPresentation; if (entersProvisioningAfterPayment(previousInvoice, nextInvoice, - wasAwaitingOnlinePayment)) { + nextPresentation, wasAwaitingOnlinePayment)) { resetProvisioningPollWindow(); } - renderInvoiceDetail(nextInvoice, { - balance: state.invoiceBalance, - payment_methods: state.invoicePaymentMethods, - }); + const completion = patch?.completion_notice; + if (completion?.message) { + stopInvoicePoll(); + const refreshed = await refreshInvoiceDetail(nextInvoice.id); + if (refreshed !== null) { + toast(String(completion.message), firstText(completion.tone, 'success')); + } else { + renderInvoiceDetail(nextPresentation); + } + return; + } + renderInvoiceDetail(nextPresentation); } if (generation !== state.pollGeneration) return; - const completion = pollCompletionMessage(state.selectedInvoice); - if (completion) { - stopInvoicePoll(); - toast(completion[0], completion[1]); - return; - } } catch (error) { if (error?.code === 'REQUEST_ABORTED' || generation !== state.pollGeneration) return; } finally { @@ -1021,7 +739,7 @@ function renderOnlinePayment(container, payment) { box.append( makeElement('strong', '', `请支付 ${payment.actual_amount} USDT(TRC20)`), makeElement('code', '', qrValue || '收款地址不可用'), - makeElement('small', '', `支付订单有效至 ${formatOrderDate(payment.expires_at)};链上确认后自动结清账单。`), + makeElement('small', '', '支付订单具有时效;链上确认后自动结清账单。'), ); box.append(actionButton('复制收款地址', async () => { try { @@ -1064,11 +782,7 @@ function renderOnlinePayment(container, payment) { async function payInvoiceBalance(invoice, container) { if (!invoiceCanPay(invoice)) { - toast(invoicePurpose(invoice) === 'provision' - ? '开通账单已失效,不能支付。' - : invoicePurpose(invoice) === 'renewal' - ? '续费宽限期已经结束,账单不可支付。' - : '账单已失效,不能支付。', 'error'); + toast('账单当前不可支付,请刷新后重试。', 'error'); return; } if (state.mutationBusy) return; @@ -1104,26 +818,20 @@ async function payInvoiceBalance(invoice, container) { void refreshInvoiceDetail(invoice.id); return; } - state.invoiceBalance = String(result?.balance ?? state.invoiceBalance); const paid = mergeInvoiceStatus(invoice, result?.invoice || {}); - const startsProvisioning = invoicePurpose(paid) === 'provision'; + const startsProvisioning = String(paid?.purpose || '').toLowerCase() === 'provision'; // A successful mutation is newer than every GET that was already in // flight. Prevent a late pre-payment response from restoring old payment // controls over this authoritative paid state. state.appliedReadSequence = ++state.readSequence; if (startsProvisioning) resetProvisioningPollWindow(); - renderInvoiceDetail(paid, { - balance: state.invoiceBalance, - payment_methods: state.invoicePaymentMethods, - }); - if (startsProvisioning) { - toast('账单已支付,实例已进入创建队列。', 'success'); - resumeInvoicePolling(); - } else if (invoicePurpose(paid) === 'renewal') { - toast('账单已支付,服务期限已延长。', 'success'); - } else { - toast('账单已支付。', 'success'); - } + state.selectedInvoice = paid; + await refreshInvoiceDetail(invoice.id); + const notice = state.presentation?.completion_notice; + toast(firstText(notice?.message, startsProvisioning + ? '账单已支付,实例已进入创建队列。' : '账单已支付。'), + firstText(notice?.tone, 'success')); + if (startsProvisioning) resumeInvoicePolling(); } catch (error) { toast(error.message, 'error'); if ([403, 409].includes(Number(error.status || 0))) { @@ -1138,11 +846,7 @@ async function payInvoiceBalance(invoice, container) { async function createInvoicePayment(invoice, method, container, paymentResult) { if (!invoiceCanPay(invoice)) { - toast(invoicePurpose(invoice) === 'provision' - ? '开通账单已失效,不能再生成支付订单。' - : invoicePurpose(invoice) === 'renewal' - ? '续费宽限期已经结束,不能再生成支付订单。' - : '账单已失效,不能再生成支付订单。', 'error'); + toast('账单当前不可创建支付订单,请刷新后重试。', 'error'); return; } if (state.mutationBusy) return; @@ -1219,7 +923,7 @@ async function createInvoicePayment(invoice, method, container, paymentResult) { } } -function renderActiveInvoicePayment(activePayment, result) { +function renderActiveInvoicePayment(activePayment, presentation, result) { const status = firstText(activePayment?.status).toLowerCase(); if (status === 'pending' && activePayment?.payment && typeof activePayment.payment === 'object') { @@ -1229,32 +933,27 @@ function renderActiveInvoicePayment(activePayment, result) { clearOnlinePaymentState(); const taskId = firstText(activePayment?.task_id); const prefix = taskId ? `任务 #${taskId} · ` : ''; - const message = status === 'review' - ? '上一笔支付订单结果待核对;可选择其他支付方式,原订单若随后到账将计入账户余额。' - : '上一笔支付订单正在创建;您仍可选择其他支付方式。'; - result.replaceChildren(makeElement('p', status === 'review' - ? 'invoice-payment-error' : 'invoice-payment-note', `${prefix}${message}`)); + const message = firstText(presentation?.active_payment_message, + '支付订单状态正在核对,请稍后刷新。'); + result.replaceChildren(makeElement('p', firstText( + presentation?.active_payment_class, 'invoice-payment-note', + ), `${prefix}${message}`)); } -function renderInvoicePaymentMethods(invoice, balance, methods, activePayment) { +function renderInvoicePaymentMethods(invoice, presentation, activePayment) { const panel = byId('invoice-payment-panel'); const container = byId('invoice-payment-methods'); const result = byId('invoice-payment-result'); if (!panel || !container || !result) return; - const invoiceStatus = firstText(invoice?.status).toLowerCase(); - const hasActivePayment = activePayment && typeof activePayment === 'object' - && ['open', 'overdue'].includes(invoiceStatus); + const hasActivePayment = activePayment && typeof activePayment === 'object'; + text('invoice-payment-title', firstText( + presentation?.payment_title, '当前支付状态', + )); + text('invoice-payment-description', firstText( + presentation?.payment_description, '账单支付状态由服务端确认。', + )); if (hasActivePayment) { - text('invoice-payment-title', invoiceCanPay(invoice) - ? '选择支付方式' : '当前支付状态'); - text('invoice-payment-description', invoiceCanPay(invoice) - ? '已有未完成支付订单;任一订单先到账即结清账单,后续到账款项将计入账户余额。' - : '该账单当前不可创建新的支付订单。'); - renderActiveInvoicePayment(activePayment, result); - } else { - text('invoice-payment-title', '选择支付方式'); - text('invoice-payment-description', - '选择支付方式后,点击“立即支付”将直接发起支付,请勿重复点击。'); + renderActiveInvoicePayment(activePayment, presentation, result); } if (!invoiceCanPay(invoice)) { container.replaceChildren(); @@ -1269,35 +968,37 @@ function renderInvoicePaymentMethods(invoice, balance, methods, activePayment) { clearOnlinePaymentState(); result.replaceChildren(); } - panel.hidden = !hasActivePayment; + panel.hidden = presentation?.show_payment !== true; return; } - const choices = []; - if (state.balancePaymentAllowed) { - choices.push({ - id: 'balance', - name: '账户余额', - description: `可用余额 ${formatUsd(balance)}`, - kind: 'balance', - }); - } - for (const method of methods) { - if (method?.id === null || method?.id === undefined || !firstText(method.name)) continue; - choices.push({ ...method, id: String(method.id), kind: 'online' }); - } + const choices = (Array.isArray(presentation?.payment_methods) + ? presentation.payment_methods : []).flatMap(method => { + if (method?.id === null || method?.id === undefined + || !firstText(method.name)) return []; + const id = String(method.id); + return [{ ...method, id, kind: id === 'balance' ? 'balance' : 'online' }]; + }); if (!choices.length) { clearInvoicePaymentKeys(invoice.id); - clearOnlinePaymentState(); - panel.hidden = true; container.replaceChildren(); - result.replaceChildren(); state.selectedInvoicePaymentMethod = ''; + const submit = byId('invoice-payment-submit'); + if (submit) { + submit.disabled = true; + submit.onclick = null; + } + if (!hasActivePayment) { + clearOnlinePaymentState(); + result.replaceChildren(); + } + panel.hidden = presentation?.show_payment !== true; return; } const available = new Set(choices.map(choice => String(choice.id))); if (!available.has(state.selectedInvoicePaymentMethod)) { - state.selectedInvoicePaymentMethod = String(choices[0].id); + const selected = choices.find(choice => choice.selected === true) || choices[0]; + state.selectedInvoicePaymentMethod = String(selected.id); } const cards = choices.map(choice => { const card = makeElement('button', 'invoice-payment-method-card'); @@ -1309,8 +1010,7 @@ function renderInvoicePaymentMethods(invoice, balance, methods, activePayment) { card.setAttribute('aria-checked', String(selected)); card.append( makeElement('strong', '', choice.name), - makeElement('small', '', firstText(choice.description, choice.label, - choice.kind === 'balance' ? `可用余额 ${formatUsd(balance)}` : '在线支付')), + makeElement('small', '', firstText(choice.description, '在线支付')), makeElement('span', 'invoice-payment-method-check', '✓'), ); card.addEventListener('click', () => selectInvoicePaymentMethod(choice.id)); @@ -1333,35 +1033,14 @@ function renderInvoicePaymentMethods(invoice, balance, methods, activePayment) { }; } -function invoiceProgressText(job) { - const status = firstText(job?.status).toLowerCase(); - const labels = { - awaiting_payment: '等待支付', - active: '正在创建', - succeeded: '实例创建完成', - failed: '实例创建失败', - expired: '实例开通已失效', - refunded: '创建失败,已退款', - cancelled: '实例创建已取消', - }; - if (!Object.prototype.hasOwnProperty.call(labels, status)) return '履约状态协议无效,请联系管理员。'; - const resultMessage = typeof job?.result === 'object' - ? firstText(job.result.message, job.result.status) : ''; - return firstText(job?.error, job?.phase, resultMessage, labels[status]); -} - -async function findInstanceByUuid(uuid) { - const payload = await api('/api/v1/vms', { timeoutMs: 20_000 }); - const values = Array.isArray(payload) ? payload - : Array.isArray(payload?.items) ? payload.items - : Array.isArray(payload?.vms) ? payload.vms : []; - return values.find(vm => String(vm?.uuid || vm?.id || '') === String(uuid)); -} - -function appendProvisionInvoiceActions(invoice, detail, actions) { - const { data, status, display } = provisionStatusInfo(invoice); - if (status) actions.append(makeElement('span', `state-pill ${display[1]}`, display[0])); - if (data.taskId) { +function appendProvisionInvoiceActions(invoice, presentation, detail, actions) { + if (firstText(presentation?.fulfillment_label)) { + actions.append(makeElement('span', `state-pill ${firstText( + presentation.fulfillment_class, 'other', + )}`, presentation.fulfillment_label)); + } + const taskId = firstText(presentation?.task_id); + if (taskId) { actions.append(actionButton('刷新账单状态', async () => { if (state.refreshPromise) { toast('账单正在刷新,请稍候。'); @@ -1377,25 +1056,30 @@ function appendProvisionInvoiceActions(invoice, detail, actions) { const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/status`, { timeoutMs: 12_000, }); - const update = result?.invoice; + const patch = result?.presentation_patch; + const update = patch?.invoice ?? result?.invoice; if (!update?.id || String(update.id) !== String(invoice.id)) { throw new Error('创建进度与当前账单不匹配,请刷新后重试。'); } if (readSequence < state.appliedReadSequence) return; state.appliedReadSequence = readSequence; + applyActivePaymentPatch(patch, result); const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update); - const taskStatus = firstText(update.fulfillment_status).toLowerCase(); - const failed = ['failed', 'expired', 'refunded', 'cancelled'].includes(taskStatus) - || Boolean(update.error); - state.invoiceJobProgress.set(String(invoice.id), { - message: invoiceProgressText({ status: taskStatus, - error: update.error, phase: update.phase }), - failed, - }); - renderInvoiceDetail(nextInvoice, { - balance: state.invoiceBalance, - payment_methods: state.invoicePaymentMethods, - }); + const nextPresentation = mergePresentationPatch(state.presentation, patch); + state.selectedInvoice = nextInvoice; + state.presentation = nextPresentation; + if (patch?.completion_notice?.message) { + const refreshed = await refreshInvoiceDetail(invoice.id); + if (refreshed !== null) { + toast(String(patch.completion_notice.message), firstText( + patch.completion_notice.tone, 'success', + )); + } else { + renderInvoiceDetail(nextPresentation); + } + return; + } + renderInvoiceDetail(nextPresentation); } catch (error) { if (readSequence < state.appliedReadSequence) return; progress.className = 'cloud-order-progress form-error'; @@ -1403,39 +1087,19 @@ function appendProvisionInvoiceActions(invoice, detail, actions) { } })); } - if (data.instanceId) { + const instanceId = firstText(presentation?.instance_id); + if (instanceId) { const link = makeElement('a', 'row-button', '查看实例'); - link.href = `/user/cloud/instances/${encodeURIComponent(data.instanceId)}`; + link.href = `/user/cloud/instances/${encodeURIComponent(instanceId)}`; actions.append(link); - } else if (data.instanceUuid) { - actions.append(actionButton('查看实例', async () => { - try { - const vm = await findInstanceByUuid(data.instanceUuid); - const id = firstText(vm?.api_id, vm?.id); - if (id) location.assign(`/user/cloud/instances/${encodeURIComponent(id)}`); - else toast('实例尚未出现在列表,请稍后刷新。'); - } catch (error) { - toast(error.message, 'error'); - } - })); } } -function renderInvoiceFulfillment(invoice) { +function renderInvoiceFulfillment(invoice, presentation) { const panel = byId('invoice-fulfillment-panel'); const content = byId('invoice-fulfillment-content'); if (!panel || !content) return; - const invoiceStatus = firstText(invoice.status).toLowerCase(); - const purpose = invoicePurpose(invoice); - const visible = (purpose === 'provision' - && (['paid', 'refunded'].includes(invoiceStatus) - || Boolean(provisionInvoiceData(invoice).taskId))) - || (purpose === 'upgrade' - && (invoiceStatus === 'paid' || Boolean(upgradeInvoiceData(invoice).taskId))) - || (purpose === 'ip_change' - && (['paid', 'refunded'].includes(invoiceStatus) - || Boolean(upgradeInvoiceData(invoice).taskId))); - if (!visible) { + if (presentation?.show_fulfillment !== true) { panel.hidden = true; content.replaceChildren(); return; @@ -1443,129 +1107,59 @@ function renderInvoiceFulfillment(invoice) { const detail = makeElement('div', 'invoice-fulfillment-detail'); const actions = makeElement('div', 'cloud-order-actions invoice-fulfillment-actions'); - if (purpose === 'upgrade') { - text('invoice-fulfillment-title', '实例升级进度'); - text('invoice-fulfillment-description', - '账单扣款后,系统会在后台升级实例;关闭页面不会取消任务。'); - const { data, status, display } = upgradeStatusInfo(invoice); - const failed = Boolean(data.error) || ['failed', 'cancelled'].includes(status); - const summary = firstText(data.error, data.phase, display[0]); - const prefix = data.taskId ? `任务 #${data.taskId} · ` : ''; - detail.append(makeElement('p', - `cloud-order-progress ${failed ? 'form-error' : 'muted'}`, `${prefix}${summary}`)); - actions.append(makeElement('span', `state-pill ${display[1]}`, display[0])); - if (data.instanceId) { - const link = makeElement('a', 'row-button', '查看实例'); - link.href = `/user/cloud/instances/${encodeURIComponent(data.instanceId)}`; - actions.append(link); - } - content.replaceChildren(detail, actions); - panel.hidden = false; - if (invoiceStatus === 'paid' && status === 'active') scheduleInvoicePoll(invoice.id); - else if (upgradeFinished(invoice) - && state.pollInvoiceId === String(invoice.id) && !state.pollController) { - stopInvoicePoll(); - } - return; - } - if (purpose === 'ip_change') { - text('invoice-fulfillment-title', '公网 IP 更换进度'); - text('invoice-fulfillment-description', - '账单扣款后,系统会在后台更换公网 IP;关闭页面不会取消任务。'); - const { data, status, display } = ipChangeStatusInfo(invoice); - const failed = ['failed', 'cancelled'].includes(status); - const summary = firstText(data.error, data.phase, display[0]); - const prefix = data.taskId ? `任务 #${data.taskId} · ` : ''; - detail.append(makeElement('p', - `cloud-order-progress ${failed ? 'form-error' : 'muted'}`, `${prefix}${summary}`)); - actions.append(makeElement('span', `state-pill ${display[1]}`, display[0])); - if (data.instanceId) { - const link = makeElement('a', 'row-button', '查看实例'); - link.href = `/user/cloud/instances/${encodeURIComponent(data.instanceId)}`; - actions.append(link); - } - content.replaceChildren(detail, actions); - panel.hidden = false; - if (invoiceStatus === 'paid' && status === 'active') scheduleInvoicePoll(invoice.id); - else if (ipChangeFinished(invoice) - && state.pollInvoiceId === String(invoice.id) && !state.pollController) { - stopInvoicePoll(); - } - return; - } - text('invoice-fulfillment-title', '实例创建进度'); - text('invoice-fulfillment-description', - '账单付款后,系统会在后台创建实例;关闭页面不会取消任务。'); - const { data, status, display } = provisionStatusInfo(invoice); - const cached = state.invoiceJobProgress.get(String(invoice.id)); - const terminal = provisionFinished(invoice); - const failed = Boolean(data.error) || ['failed', 'expired', 'refunded', 'cancelled'].includes(status) - || (!terminal && cached?.failed === true); - const progress = makeElement('p', `cloud-order-progress ${failed ? 'form-error' : 'muted'}`, - firstText(data.error, data.phase, terminal ? display[0] : cached?.message, display[0])); + text('invoice-fulfillment-title', firstText( + presentation?.fulfillment_title, '任务进度', + )); + text('invoice-fulfillment-description', firstText( + presentation?.fulfillment_description, '任务由系统在后台执行。', + )); + const taskId = firstText(presentation?.task_id); + const prefix = taskId ? `任务 #${taskId} · ` : ''; + const progress = makeElement('p', `cloud-order-progress ${ + presentation?.fulfillment_failed === true ? 'form-error' : 'muted' + }`, `${prefix}${firstText(presentation?.fulfillment_message, '等待任务状态')}`); detail.append(progress); - appendProvisionInvoiceActions(invoice, detail, actions); + appendProvisionInvoiceActions(invoice, presentation, detail, actions); content.replaceChildren(detail, actions); panel.hidden = false; - if (invoiceStatus === 'paid' && !terminal) scheduleInvoicePoll(invoice.id); - else if (terminal) { - state.invoiceJobProgress.delete(String(invoice.id)); - if (state.pollInvoiceId === String(invoice.id) && !state.pollController) stopInvoicePoll(); + if (presentation?.polling_required === true) scheduleInvoicePoll(invoice.id); + else if (state.pollInvoiceId === String(invoice.id) && !state.pollController) { + stopInvoicePoll(); } } -function renderInvoiceDetail(invoice, payload) { - state.selectedInvoice = invoice; - text('invoice-detail-kind', invoiceTitle(invoice)); - text('invoice-detail-number', `账单 #${invoice.id}`); - text('invoice-detail-created', `创建于 ${formatOrderDate(invoice.created_at)}`); - text('invoice-detail-subtitle', `账单 #${invoice.id} · ${formatOrderDate(invoice.created_at)}`); - text('invoice-detail-amount', formatUsd(invoice.amount)); - const [statusLabel, statusClass] = invoiceStatusInfo( - invoice.display_status ?? invoice.status, - ); +function renderInvoiceDetail(presentation) { + state.presentation = presentation; + text('invoice-detail-kind', firstText(presentation?.title, '账单')); + text('invoice-detail-number', firstText(presentation?.number_text, '账单')); + text('invoice-detail-created', firstText(presentation?.created_text, '时间未记录')); + text('invoice-detail-subtitle', firstText(presentation?.subtitle, '账单详情')); + text('invoice-detail-amount', firstText(presentation?.amount_display, '$—')); const status = byId('invoice-detail-status'); if (status) { - status.className = `state-pill ${statusClass}`; - status.textContent = statusLabel; + status.className = `state-pill ${firstText(presentation?.status_class, 'other')}`; + status.textContent = firstText(presentation?.status_label, '未知'); } - const purpose = invoicePurpose(invoice); - const facts = [ - invoiceFact('账单编号', `#${invoice.id}`), - invoiceFact('创建时间', formatOrderDate(invoice.created_at)), - ]; - if (purpose === 'provision') { - facts.push(invoiceFact('支付截止', formatServiceDate( - invoicePaymentDeadlineTimestamp(invoice) ?? invoice.due_at, - ))); - } else if (purpose === 'renewal') { - facts.push(invoiceFact('实例到期', formatOrderDate( - invoice.renews_expires_at ?? invoice.due_at, - ))); - if (invoiceDeletionTimestamp(invoice) !== null) { - facts.push(invoiceFact('最晚支付', formatServiceDate(invoiceDeletionTimestamp(invoice)))); - } - } else if (invoicePaymentDeadlineTimestamp(invoice) !== null) { - facts.push(invoiceFact('支付截止', - formatServiceDate(invoicePaymentDeadlineTimestamp(invoice)))); - } - if (invoice.paid_at) facts.push(invoiceFact('支付时间', formatOrderDate(invoice.paid_at))); - if (invoice.paid_via) facts.push(invoiceFact('支付方式', paymentLabel(invoice.paid_via))); + const facts = (Array.isArray(presentation?.facts) ? presentation.facts : []) + .flatMap(item => item && typeof item === 'object' && !Array.isArray(item) + ? [invoiceFact(item.label, item.value)] : []); byId('invoice-detail-facts')?.replaceChildren(...facts); - renderInvoiceLineItems(invoice); - renderInvoiceSpecification(invoice); - renderInvoicePaymentMethods(invoice, payload.balance, - Array.isArray(payload.payment_methods) ? payload.payment_methods : [], - state.activePayment); - renderInvoiceFulfillment(invoice); + renderInvoiceLineItems(presentation); + renderInvoiceSpecification(presentation); + renderInvoicePaymentMethods(state.selectedInvoice, presentation, state.activePayment); + renderInvoiceFulfillment(state.selectedInvoice, presentation); } function hydrateInvoiceDetail(payload, expectedInvoiceId = document.body.dataset.invoiceId) { if (!payload?.invoice || typeof payload.invoice !== 'object') { throw new Error('账单信息不完整,请刷新页面后重试。'); } + if (!payload?.presentation || typeof payload.presentation !== 'object' + || Array.isArray(payload.presentation)) { + throw new Error('账单展示信息不完整,请刷新页面后重试。'); + } const expected = String(expectedInvoiceId || ''); if (!/^[1-9]\d*$/.test(expected) || String(payload.invoice.id || '') !== expected) { @@ -1580,8 +1174,6 @@ function hydrateInvoiceDetail(payload, expectedInvoiceId = document.body.dataset clearOnlinePaymentState(); byId('invoice-payment-result')?.replaceChildren(); } - state.invoicePaymentMethods = Array.isArray(payload.payment_methods) - ? payload.payment_methods : []; state.activePayment = payload.active_payment && typeof payload.active_payment === 'object' && !Array.isArray(payload.active_payment) @@ -1604,10 +1196,11 @@ function hydrateInvoiceDetail(payload, expectedInvoiceId = document.body.dataset } } if (entersProvisioningAfterPayment(previousInvoice, payload.invoice, - wasAwaitingOnlinePayment)) { + payload.presentation, wasAwaitingOnlinePayment)) { resetProvisioningPollWindow(); } - renderInvoiceDetail(payload.invoice, payload); + state.selectedInvoice = payload.invoice; + renderInvoiceDetail(payload.presentation); if (state.onlinePaymentPending) { scheduleOnlinePaymentExpiry(state.paymentRenderGeneration); } diff --git a/web/tests/CloudInvoiceDetailContractTest.php b/web/tests/CloudInvoiceDetailContractTest.php index 99e44f4c..4dafa2a5 100644 --- a/web/tests/CloudInvoiceDetailContractTest.php +++ b/web/tests/CloudInvoiceDetailContractTest.php @@ -31,6 +31,9 @@ $invoicePageService = file_get_contents($root . '/app/Services/Cloud/CloudInvoic $invoiceDetailPageService = file_get_contents( $root . '/app/Services/Cloud/CloudInvoiceDetailPageService.php' ); +$invoicePresentation = file_get_contents( + $root . '/app/Services/Cloud/CloudInvoicePresentation.php' +); $invoiceDetailTemplate = file_get_contents( $root . '/resources/views/venix/cloud/pages/invoice-detail.tpl' ); @@ -116,7 +119,7 @@ $assert(str_contains($lineItemRuntime, "byId('invoice-line-items-panel')") && str_contains($lineItemRuntime, 'replaceChildren(') && !str_contains($lineItemRuntime, 'innerHTML') && !str_contains($lineItemRuntime, 'snapshot_json') - && str_contains($invoiceDetailRuntime, 'renderInvoiceLineItems(invoice);'), + && str_contains($invoiceDetailRuntime, 'renderInvoiceLineItems(presentation);'), 'Invoice-detail refresh must replace safe text-only line items.'); $assert(str_contains($invoiceDetailTemplate, 'id="invoice-payment-title"') && str_contains($invoiceDetailTemplate, 'id="invoice-payment-description"') @@ -128,12 +131,11 @@ $assert(str_contains($invoiceDetailTemplate, 'id="invoice-payment-title"') && str_contains($invoiceDetailRuntime, 'state.activePayment = payload.active_payment') && str_contains($invoiceDetailRuntime, - 'renderActiveInvoicePayment(activePayment, result);'), + 'renderActiveInvoicePayment(activePayment, presentation, result);'), 'Invoice detail must restore durable payment attempts while retaining payment choices.'); -$assert(str_contains($pageController, +$assert(str_contains($invoicePresentation, "\$invoice['renews_expires_at'] ?? \$invoice['due_at'] ?? null") - && str_contains($invoiceDetailRuntime, - 'invoice.renews_expires_at ?? invoice.due_at'), + && str_contains($invoiceDetailRuntime, 'payload.presentation'), 'Renewal invoice details must render their authoritative target expiry.'); $listMethod = $section($apiController, 'public function invoices(', @@ -203,10 +205,11 @@ $assert(!str_contains($invoiceDetailRuntime, '/api/v1/jobs/') '/api/v1/invoices/${encodeURIComponent(invoice.id)}/status') === 1 && str_contains($invoiceDetailRuntime, "actionButton('刷新账单状态'") && str_contains($invoiceDetailRuntime, - 'const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update);'), + 'const nextPresentation = mergePresentationPatch(state.presentation, patch);'), 'Manual creation-progress refresh must use one invoice-scoped lightweight request.'); $manualProgress = $section($invoiceDetailRuntime, - 'function appendProvisionInvoiceActions(', ' if (data.instanceId) {'); + 'function appendProvisionInvoiceActions(', + 'function renderInvoiceFulfillment('); $manualProgressCatch = $section($manualProgress, '} catch (error) {', ' }'); $assert(str_contains($manualProgress, 'const readSequence = ++state.readSequence;') @@ -215,6 +218,7 @@ $assert(str_contains($manualProgress, 'const readSequence = ++state.readSequence < strpos($manualProgress, 'try {') && str_contains($manualProgressCatch, 'if (readSequence < state.appliedReadSequence) return;') + && str_contains($manualProgress, 'applyActivePaymentPatch(patch, result);') && !str_contains($manualProgressCatch, 'state.invoiceJobProgress.set('), 'Manual creation-progress errors must ignore stale reads and remain transient.'); $assert(substr_count($invoiceDetailPageService, '->sharedLock()') >= 4 @@ -247,34 +251,29 @@ $assert(str_contains($apiMiddleware, 'CloudAccess::actor(!$databaseOnly)') 'Invoice-only API calls must authenticate without a cloud_sessions lookup.'); $pollMethod = $section($invoiceDetailRuntime, 'async function pollInvoiceStatus(', 'function scheduleInvoicePoll('); +$activePaymentPatch = $section($invoiceDetailRuntime, + 'function applyActivePaymentPatch(', 'async function pollInvoiceStatus('); $assert(str_contains($pollMethod, 'api(`/api/v1/invoices/${encodeURIComponent(state.pollInvoiceId)}/status`') && substr_count($pollMethod, 'api(') === 1 - && str_contains($pollMethod, - "Object.prototype.hasOwnProperty.call(result || {}, 'active_payment')") - && str_contains($pollMethod, - 'state.activePayment = result.active_payment') - && str_contains($pollMethod, 'clearOnlinePaymentState(true);') + && str_contains($pollMethod, 'const patch = result?.presentation_patch;') + && str_contains($pollMethod, 'applyActivePaymentPatch(patch, result);') + && str_contains($activePaymentPatch, 'state.activePayment = source.active_payment') + && str_contains($activePaymentPatch, 'clearOnlinePaymentState(true);') && str_contains($pollMethod, 'entersProvisioningAfterPayment(') && str_contains($pollMethod, 'resetProvisioningPollWindow();') - && !str_contains($pollMethod, 'refreshInvoiceDetail('), - 'Each invoice poll must issue one lightweight request and preserve the provisioning window.'); + && str_contains($pollMethod, + 'const refreshed = await refreshInvoiceDetail(nextInvoice.id);') + && str_contains($pollMethod, 'if (refreshed !== null)') + && str_contains($pollMethod, 'renderInvoiceDetail(nextPresentation);'), + 'Each invoice poll must consume one lightweight presentation patch and fully refresh terminal state.'); $needsPolling = $section($invoiceDetailRuntime, 'function invoiceNeedsPolling(', 'function stopInvoicePoll('); -$provisionFinished = $section($invoiceDetailRuntime, 'function provisionFinished(', - 'function invoiceFact('); -$assert(str_contains($needsPolling, 'state.onlinePaymentPending') +$assert(str_contains($needsPolling, 'state.presentation?.polling_required === true') && str_contains($needsPolling, '!onlinePaymentHasExpired()') - && str_contains($needsPolling, 'invoiceCanPay(invoice)') - && str_contains($needsPolling, "['creating', 'pending', 'review'].includes(") - && str_contains($needsPolling, 'return false;') - && !str_contains($needsPolling, 'provisionFinished(invoice)') - && str_contains($provisionFinished, - "['succeeded', 'failed', 'expired', 'refunded', 'cancelled'].includes(status)") - && !str_contains($provisionFinished, "'active'") - && !str_contains($provisionFinished, "'uncertain'") - && !str_contains($provisionFinished, "'needs_attention'"), - 'Invoice polling must be bounded to active provider payment while task receipts expose provisioning outcome.'); + && !str_contains($needsPolling, "['creating', 'pending', 'review'].includes(") + && !str_contains($invoiceDetailRuntime, 'function provisionFinished('), + 'Invoice polling must consume the server projection instead of rebuilding task state.'); $paymentExpiry = $section($invoiceDetailRuntime, 'function onlinePaymentFallbackExpiresAt(', 'function invoiceNeedsPolling('); $onlinePaymentRender = $section($invoiceDetailRuntime, @@ -289,7 +288,7 @@ $assert(!str_contains($invoiceDetailRuntime, 'function hasPendingInvoicePaymentK 'state.onlinePaymentPending = Boolean(serverPendingPayment);') && str_contains($invoiceDetailRuntime, 'resumeInvoicePolling();') && str_contains($paymentExpiry, 'STATUS_POLL_MAX_LIFETIME_MS') - && str_contains($paymentExpiry, 'invoicePaymentDeadlineTimestamp(invoice)') + && str_contains($paymentExpiry, 'serviceTimestamp(') && str_contains($paymentExpiry, 'function onlinePaymentHasExpired(') && str_contains($paymentExpiry, 'function expireOnlinePaymentInstructions(') && str_contains($paymentExpiry, 'clearOnlinePaymentState(true);') @@ -355,16 +354,21 @@ $balanceRequest = strpos($balancePayment, 'api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`'); $assert(str_contains($balancePayment, 'state.appliedReadSequence = ++state.readSequence;') - && strpos($balancePayment, - 'state.appliedReadSequence = ++state.readSequence;') - < strpos($balancePayment, 'renderInvoiceDetail(paid,'), + && str_contains($balancePayment, 'await refreshInvoiceDetail(invoice.id);'), 'A successful balance payment must invalidate every older in-flight read.'); +$balanceReset = strpos($balancePayment, 'resetProvisioningPollWindow();'); +$balanceRefreshAfterReset = $balanceReset === false ? false : strpos( + $balancePayment, + 'await refreshInvoiceDetail(invoice.id);', + $balanceReset +); $assert(str_contains($balancePayment, - "const startsProvisioning = invoicePurpose(paid) === 'provision';") + "String(paid?.purpose || '').toLowerCase() === 'provision'") && str_contains($balancePayment, 'if (startsProvisioning) resetProvisioningPollWindow();') - && strpos($balancePayment, 'resetProvisioningPollWindow();') - < strpos($balancePayment, 'renderInvoiceDetail(paid,'), + && $balanceReset !== false + && $balanceRefreshAfterReset !== false + && $balanceReset < $balanceRefreshAfterReset, 'Balance payment must start a fresh provisioning poll window before rendering paid state.'); $assert(str_contains($balancePayment, 'if ([403, 409].includes(Number(error.status || 0)))') @@ -416,17 +420,17 @@ $assert(!str_contains($providerPayment, 'confirm(') $assert(str_contains($onlinePaymentRender, 'container.replaceChildren(box);'), 'Rendered provider instructions must replace stale task-status notices.'); $paymentChoices = $section($invoiceDetailRuntime, - 'function renderInvoicePaymentMethods(', 'function invoiceProgressText('); + 'function renderInvoicePaymentMethods(', + 'function appendProvisionInvoiceActions('); $activePaymentRender = strpos($paymentChoices, - 'renderActiveInvoicePayment(activePayment, result);'); -$choicesStart = strpos($paymentChoices, 'const choices = [];'); -$assert(str_contains($invoiceDetailRuntime, 'balancePaymentAllowed: false') - && str_contains($invoiceDetailRuntime, - 'state.balancePaymentAllowed = payload?.balance_payment_allowed === true') - && str_contains($paymentChoices, 'if (state.balancePaymentAllowed)') + 'renderActiveInvoicePayment(activePayment, presentation, result);'); +$choicesStart = strpos($paymentChoices, + 'Array.isArray(presentation?.payment_methods)'); +$assert(str_contains($paymentChoices, 'if (!choices.length)') + && str_contains($paymentChoices, "id === 'balance' ? 'balance' : 'online'") && str_contains($paymentChoices, 'if (!choices.length)') && str_contains($paymentChoices, - 'state.selectedInvoicePaymentMethod = String(choices[0].id);') + 'choices.find(choice => choice.selected === true) || choices[0]') && $activePaymentRender !== false && $choicesStart !== false && $activePaymentRender < $choicesStart, @@ -506,11 +510,10 @@ $assert(str_contains($statusService, "->where('user_id', \$invoice->user_id)") && str_contains($statusService, '$instanceId = $linkedInstance?->id;'), 'Polling must validate the linked instance owner before exposing its id.'); -$assert(str_contains($displayMethod, "'recharge' => '余额充值'") - && str_contains($displayMethod, "'provision' => '实例开通'") - && str_contains($displayMethod, "'renewal' => '实例续费'") - && str_contains($displayMethod, "'title' => \$title") - && str_contains($displayMethod, "'type_label' => \$title"), +$assert(str_contains($invoicePresentation, "'recharge' => '余额充值'") + && str_contains($invoicePresentation, "'provision' => '实例开通'") + && str_contains($invoicePresentation, "'renewal' => '实例续费'") + && str_contains($invoicePresentation, "'title' => self::invoiceTitle("), 'Invoice purpose labels are incomplete.'); $assert(!str_contains($displayMethod, "'invoice_no' =>"), 'The internal invoice number is still exposed to users.'); diff --git a/web/tests/CloudInvoicePaymentResumeTest.php b/web/tests/CloudInvoicePaymentResumeTest.php index 2be305e0..8ad6775f 100644 --- a/web/tests/CloudInvoicePaymentResumeTest.php +++ b/web/tests/CloudInvoicePaymentResumeTest.php @@ -172,7 +172,12 @@ $assert(($creating['active_payment']['status'] ?? null) === 'creating' && ($creating['active_payment']['payment'] ?? null) === null && ($creating['active_payment']['can_submit'] ?? false) === true && $creating['payment_methods'] === [] - && $creating['balance_payment_allowed'] === true, + && $creating['balance_payment_allowed'] === true + && ($creating['presentation']['show_payment'] ?? false) === true + && str_contains( + (string) ($creating['presentation']['active_payment_message'] ?? ''), + '仍可选择其他支付方式' + ), 'A durable payment-create task blocked a new payment choice.'); Capsule::table('cloud_jobs')->where('id', 31)->update([ @@ -223,7 +228,11 @@ $pendingStatus = CloudInvoiceDetailPageService::statusForUser(21, 1); $assert(($pendingStatus['invoice']['id'] ?? null) === '21' && ($pendingStatus['active_payment']['status'] ?? null) === 'pending' && ($pendingStatus['active_payment']['payment']['payment_value'] ?? null) - === 'https://checkout.stripe.test/resume-safe', + === 'https://checkout.stripe.test/resume-safe' + && ($pendingStatus['presentation_patch']['payment']['message'] ?? null) + === '已有待支付订单;可继续原订单或选择其他支付方式。' + && ($pendingStatus['presentation_patch']['polling']['required'] ?? false) + === true, 'Lightweight invoice polling omitted the active provider payment.'); Capsule::table('cloud_invoice_payments')->where('id', 41)->update([ diff --git a/web/tests/CloudInvoicePaymentRuntimeBehaviorTest.mjs b/web/tests/CloudInvoicePaymentRuntimeBehaviorTest.mjs index 4f31e686..53d98b01 100644 --- a/web/tests/CloudInvoicePaymentRuntimeBehaviorTest.mjs +++ b/web/tests/CloudInvoicePaymentRuntimeBehaviorTest.mjs @@ -6,6 +6,27 @@ import { createRequire } from 'node:module'; import { join, normalize } from 'node:path'; import { fileURLToPath } from 'node:url'; +const publicRoot = fileURLToPath(new URL('../public/', import.meta.url)) + .replace(/\/+$/, ''); +const runtimePath = join(publicRoot, 'cloud/invoice-detail-runtime.js'); +const runtimeSource = await readFile(runtimePath, 'utf8'); +for (const legacyFunction of [ + 'formatOrderDate', 'formatServiceDate', 'formatUsd', 'formatMemoryGiB', + 'formatBytes', 'formatTrafficQuota', 'invoicePurpose', 'invoiceTitle', + 'invoiceStatusInfo', 'paymentLabel', 'invoiceSpecification', + 'provisionStatusInfo', 'upgradeStatusInfo', 'ipChangeStatusInfo', + 'invoiceProgressText', 'pollCompletionMessage', +]) { + assert.doesNotMatch(runtimeSource, new RegExp(`function ${legacyFunction}\\(`), + `Invoice detail runtime still rebuilds presentation in ${legacyFunction}().`); +} +assert.match(runtimeSource, /payload\.presentation/, + 'Invoice detail runtime does not consume the full server presentation.'); +assert.match(runtimeSource, /function renderInvoiceDetail\(presentation\)/, + 'Invoice detail renderer does not use the server presentation as its sole display input.'); +assert.match(runtimeSource, /result\?\.presentation_patch/, + 'Invoice polling does not consume the server presentation patch.'); + const require = createRequire(import.meta.url); let chromium; try { @@ -25,13 +46,17 @@ if (!browserExecutable) { console.log('Cloud invoice payment runtime browser checks skipped: Chromium is unavailable.'); process.exit(0); } -const publicRoot = fileURLToPath(new URL('../public/', import.meta.url)) - .replace(/\/+$/, ''); -const runtimePath = join(publicRoot, 'cloud/invoice-detail-runtime.js'); -const runtimeSource = await readFile(runtimePath, 'utf8'); const ids = [...runtimeSource.matchAll(/byId\('([^']+)'\)/g)] .map(match => match[1]) .filter((id, index, all) => all.indexOf(id) === index); +for (const id of [ + 'invoice-detail-kind', 'invoice-detail-number', 'invoice-detail-created', + 'invoice-detail-subtitle', 'invoice-detail-amount', 'invoice-payment-title', + 'invoice-payment-description', 'invoice-fulfillment-title', + 'invoice-fulfillment-description', 'current-username', +]) { + if (!ids.includes(id)) ids.push(id); +} const html = `${ids.map(id => { if (['invoice-payment-submit', 'invoice-detail-refresh'].includes(id)) { @@ -87,7 +112,10 @@ try { const path = new URL(String(input), location.href).pathname; if (path === '/api/v1/invoices/21/status') { return new Promise(resolve => { - window.__resolveOldStatus = payload => resolve(jsonResponse(200, payload)); + window.__resolveOldStatus = payload => { + window.__resolveOldStatus = null; + resolve(jsonResponse(200, payload)); + }; }); } if (path === '/api/v1/invoices/21/payments') { @@ -112,11 +140,12 @@ try { const invoice = { id: '21', purpose: 'renewal', - title: '实例续费', + title: '原始标题不应显示', status: 'open', display_status: 'open', payable: true, - amount: '10.00', + available_action: 'pay', + amount: '999.00', currency: 'USD', created_at: now - 60, due_at: now + 86400, @@ -125,6 +154,41 @@ try { traffic_quota_bytes: 0, items: [], }; + const presentation = { + id: '21', + title: '服务端账单标题', + number_text: '服务端账单编号', + created_text: '服务端创建时间', + subtitle: '服务端账单副标题', + amount_display: '$10.00', + status_label: '服务端待支付', + status_class: 'warning', + facts: [{ label: '服务端事实', value: '服务端事实值' }], + show_line_items: false, + line_items: [], + show_specification: false, + specification: [], + show_payment: true, + payment_title: '服务端支付标题', + payment_description: '服务端支付说明', + active_payment_message: '服务端待支付订单', + active_payment_class: 'invoice-payment-note', + payment_methods: [ + { id: 'stripe_card', name: 'Stripe Card', description: 'Card', selected: true }, + { id: 'usdt', name: 'USDT', description: 'USDT', selected: false }, + ], + show_fulfillment: false, + fulfillment_title: '', + fulfillment_description: '', + fulfillment_message: '', + fulfillment_label: '', + fulfillment_class: 'other', + fulfillment_failed: false, + task_id: '', + instance_id: '', + polling_required: true, + completion_notice: null, + }; const oldPayment = { invoice_id: '21', method: 'stripe_card', @@ -155,7 +219,7 @@ try { { id: 'usdt', name: 'USDT' }, ], }; - await page.evaluate(async ({ base, invoice, oldPayment, newPayment }) => { + await page.evaluate(async ({ base, invoice, presentation, oldPayment, newPayment }) => { window.__newPayment = newPayment; window.__invoiceRuntime = await import( `/cloud/invoice-detail-runtime.js?behavior=${Date.now()}` @@ -163,6 +227,7 @@ try { window.__invoicePayload = { ...base, invoice, + presentation, active_payment: { status: 'pending', task_id: null, @@ -171,12 +236,57 @@ try { }, }; window.__invoiceRuntime.hydrateInvoiceDetail(window.__invoicePayload, '21'); - }, { base, invoice, oldPayment, newPayment }); + }, { base, invoice, presentation, oldPayment, newPayment }); + assert.equal(await page.locator('#invoice-detail-kind').textContent(), + '服务端账单标题'); + assert.equal(await page.locator('#invoice-detail-amount').textContent(), '$10.00'); + assert.equal(await page.locator('#invoice-detail-status').textContent(), + '服务端待支付'); + assert.match(await page.locator('#invoice-detail-facts').textContent(), + /服务端事实值/); assert.equal(await page.locator('.invoice-payment-method-card').count(), 2); assert.equal(await page.locator('#invoice-payment-submit').isEnabled(), true); assert.equal(await page.locator('a[href="https://checkout.stripe.test/old"]').count(), 1); + await page.waitForFunction(() => typeof window.__resolveOldStatus === 'function', + null, { timeout: 5000 }); + await page.evaluate(({ invoice, oldPayment }) => { + window.__resolveOldStatus({ + invoice, + active_payment: { + status: 'pending', task_id: null, payment: oldPayment, can_submit: true, + }, + presentation_patch: { + invoice: { + id: '21', status: 'raw-status-must-not-render', + display_status: 'raw-status-must-not-render', payable: true, + available_action: 'pay', + }, + active_payment: { + status: 'pending', task_id: null, payment: oldPayment, can_submit: true, + }, + status: { code: 'open', label: '服务端轮询状态', class: 'warning' }, + payment: { + payable: true, active: { status: 'pending' }, + message: '服务端待支付订单', message_class: 'invoice-payment-note', + }, + fulfillment: { + show_fulfillment: false, fulfillment_title: '', + fulfillment_description: '', fulfillment_message: '', + fulfillment_label: '', fulfillment_class: 'other', + fulfillment_failed: false, task_id: '', instance_id: '', status_code: '', + }, + polling: { required: true, task_id: '', job_status: '' }, + completion_notice: null, + }, + }); + }, { invoice, oldPayment }); + await page.waitForFunction(() => document.querySelector( + '#invoice-detail-status' + )?.textContent === '服务端轮询状态', null, { timeout: 5000 }); + assert.equal(await page.locator('#invoice-detail-status').textContent(), + '服务端轮询状态'); await page.waitForFunction(() => typeof window.__resolveOldStatus === 'function', null, { timeout: 5000 }); await page.locator('.invoice-payment-method-card[data-method-id="usdt"]').click(); @@ -195,6 +305,29 @@ try { payment: oldPayment, can_submit: true, }, + presentation_patch: { + invoice: { + id: '21', status: 'raw-stale-status', + display_status: 'raw-stale-status', payable: true, + available_action: 'pay', + }, + active_payment: { + status: 'pending', task_id: null, payment: oldPayment, can_submit: true, + }, + status: { code: 'open', label: '过期轮询状态不应显示', class: 'failed' }, + payment: { + payable: true, active: { status: 'pending' }, + message: '过期支付状态', message_class: 'invoice-payment-error', + }, + fulfillment: { + show_fulfillment: false, fulfillment_title: '', + fulfillment_description: '', fulfillment_message: '', + fulfillment_label: '', fulfillment_class: 'other', + fulfillment_failed: false, task_id: '', instance_id: '', status_code: '', + }, + polling: { required: true, task_id: '', job_status: '' }, + completion_notice: null, + }, }); await page.waitForTimeout(50); assert.match( @@ -202,9 +335,11 @@ try { /USDT/, 'A late status response replaced the newer provider order.', ); + assert.equal(await page.locator('#invoice-detail-status').textContent(), + '服务端轮询状态', 'A stale raw/status patch replaced the newer presentation.'); assert.equal(await page.locator('a[href="https://checkout.stripe.test/old"]').count(), 0); - await page.evaluate(({ base, invoice }) => { + await page.evaluate(({ base, invoice, presentation }) => { sessionStorage.setItem('virt-cloud:invoice-payment:1:21:stripe_card', 'stripe-runtime-stale-key-0001'); sessionStorage.setItem('virt-cloud:invoice-payment:1:21:usdt', @@ -213,9 +348,10 @@ try { window.__invoiceRuntime.hydrateInvoiceDetail({ ...base, invoice, + presentation, active_payment: null, }, '21'); - }, { base, invoice }); + }, { base, invoice, presentation }); assert.equal(await page.locator('.cloud-payment-instructions').count(), 0); assert.equal(await page.locator('.invoice-payment-method-card').count(), 2); diff --git a/web/tests/CloudInvoicePresentationModuleTest.php b/web/tests/CloudInvoicePresentationModuleTest.php index 534b5089..dc1da1b7 100644 --- a/web/tests/CloudInvoicePresentationModuleTest.php +++ b/web/tests/CloudInvoicePresentationModuleTest.php @@ -71,7 +71,10 @@ $assert($detail['show_line_items'] === true 'amount_display' => '$2.50', ], ] - && $detail['amount_display'] === '$12.51', + && $detail['amount_display'] === '$12.51' + && $detail['number_text'] === '账单 #17' + && str_starts_with($detail['created_text'], '创建于 ') + && $detail['polling_required'] === false, 'Detail projection changed frozen line-item labels or authoritative total.'); $switchable = CloudInvoicePresentation::detail([ @@ -94,7 +97,8 @@ $assert($switchable['show_payment'] === true && str_contains($switchable['active_payment_message'], '可选择其他支付方式') && count($switchable['payment_methods']) === 2 && $switchable['payment_methods'][0]['id'] === 'balance' - && $switchable['payment_methods'][0]['selected'] === true, + && $switchable['payment_methods'][0]['selected'] === true + && $switchable['polling_required'] === true, 'Unfinished payment did not remain switchable through the public module.'); $ipChange = [ @@ -124,7 +128,9 @@ $assert($ipView['show_fulfillment'] === true && $ipView['instance_id'] === '41' && $ipRow['show_fulfillment'] === true && $ipRow['fulfillment_label'] === '待人工核对' - && $ipRow['context_display'] === '目标实例 vm-audit', + && $ipRow['context_display'] === '目标实例 vm-audit' + && ($ipView['completion_notice']['message'] ?? null) + === '公网 IP 更换结果待人工核对,请勿重复提交。', 'IP-change presentation lost its target or review-only fulfillment state.'); $unknown = CloudInvoicePresentation::summaries([[ @@ -155,11 +161,14 @@ $patch = CloudInvoicePresentation::statusPatch([ 'can_submit' => true, ], ]); -$assert($patch['status'] === ['label' => '已支付', 'class' => 'running'] +$assert($patch['status']['code'] === 'paid' + && $patch['status']['label'] === '已支付' + && $patch['status']['class'] === 'running' && $patch['payment']['message'] === '已有待支付订单;可继续原订单或选择其他支付方式。' && $patch['fulfillment']['fulfillment_label'] === '待人工核对' && $patch['polling']['task_id'] === '82' + && $patch['polling']['required'] === false && $patch['polling']['job_attempts'] === 2 && !array_key_exists('amount', $patch['invoice']), 'Sparse status projection did not isolate mutable payment and polling fields.'); @@ -173,6 +182,9 @@ $controllerSource = file_get_contents( $pageServiceSource = file_get_contents( dirname(__DIR__) . '/app/Services/Cloud/CloudInvoicePageService.php' ); +$detailServiceSource = file_get_contents( + dirname(__DIR__) . '/app/Services/Cloud/CloudInvoiceDetailPageService.php' +); $assert(is_string($source) && !str_contains($source, 'App\\Models') && !preg_match('/\\btime\\s*\\(/', $source) @@ -180,11 +192,16 @@ $assert(is_string($source) && !str_contains($source, 'CloudInvoiceService::'), 'Presentation module acquired an ORM, clock, payment-provider or domain-service dependency.'); $assert(is_string($controllerSource) && is_string($pageServiceSource) + && is_string($detailServiceSource) && str_contains($pageServiceSource, 'CloudInvoicePresentation::summaries(') && str_contains($controllerSource, "\$rows = \$payload['invoices'];") + && str_contains($detailServiceSource, + 'CloudInvoicePresentation::detail($payload)') + && str_contains($detailServiceSource, + 'CloudInvoicePresentation::statusPatch($payload)') && str_contains($controllerSource, - 'CloudInvoicePresentation::detail($payload)'), + "'cloud_invoice_detail_view' => \$payload['presentation']"), 'Invoice SSR adapters do not consume the unified presentation module.'); echo "Cloud invoice presentation module checks passed.\n"; diff --git a/web/tests/CloudInvoicePresentationTest.php b/web/tests/CloudInvoicePresentationTest.php index c7456c73..9ab7c33b 100644 --- a/web/tests/CloudInvoicePresentationTest.php +++ b/web/tests/CloudInvoicePresentationTest.php @@ -136,14 +136,23 @@ $detailRuntime = file_get_contents( ); $listRuntime = file_get_contents(dirname(__DIR__) . '/public/cloud/invoices.js'); $assert(is_string($detailRuntime) && is_string($listRuntime) - && str_contains($detailRuntime, + && str_contains($detailRuntime, 'payload.presentation') + && str_contains($detailRuntime, 'result?.presentation_patch') + && str_contains($detailRuntime, 'presentation?.status_label') + && str_contains($detailRuntime, 'presentation?.status_class') + && str_contains($detailRuntime, 'presentation?.fulfillment_label') + && str_contains($detailRuntime, 'presentation?.polling_required') + && str_contains($detailRuntime, 'function renderInvoiceDetail(presentation)') + && !str_contains($detailRuntime, + 'function renderInvoiceDetail(invoice, presentation)') + && !str_contains($detailRuntime, 'function invoiceTitle(') + && !str_contains($detailRuntime, 'function invoiceStatusInfo(') + && !str_contains($detailRuntime, 'function paymentLabel(') + && !str_contains($detailRuntime, 'function provisionStatusInfo(') + && !str_contains($detailRuntime, 'function upgradeStatusInfo(') + && !str_contains($detailRuntime, 'function ipChangeStatusInfo(') + && !str_contains($detailRuntime, "renewal_grace: ['已到期,宽限期内可续费', 'warning']") - && str_contains($detailRuntime, - 'invoice.display_status ?? invoice.status') - && str_contains($detailRuntime, - "review: ['待人工核对', 'warning']") - && str_contains($detailRuntime, - "invoicePurpose(invoice) === 'ip_change'") && str_contains($listRuntime, 'invoice?.status_label') && str_contains($listRuntime, 'invoice?.status_class') && str_contains($listRuntime, 'invoice?.fulfillment_label')