You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/invoice-detail-runtime.js

1372 lines
51 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { toast } from './toast.js?v=2026100102';
// Lightweight invoice-detail runtime. This module deliberately contains no VM,
// deployment, metrics or console code so the bill is interactive without
// downloading the all-feature cloud runtime.
const INVOICE_PAYMENT_STORAGE_PREFIX = 'virt-cloud:invoice-payment:';
const REQUEST_TIMEOUT_MS = 15_000;
const STATUS_POLL_INTERVAL_MS = 3_000;
const STATUS_POLL_SLOW_INTERVAL_MS = 30_000;
const STATUS_POLL_WINDOW_MS = 10 * 60 * 1_000;
const STATUS_POLL_MAX_LIFETIME_MS = 24 * 60 * 60 * 1_000;
const byId = id => document.getElementById(id);
const state = {
view: '',
csrfToken: '',
userId: '',
username: '',
admin: false,
selectedInvoice: null,
selectedInvoicePaymentMethod: '',
invoicePaymentMethods: [],
balancePaymentAllowed: false,
invoiceBalance: '0.00',
invoiceJobProgress: new Map(),
mutationBusy: false,
onlinePaymentPending: false,
onlinePaymentExpiresAt: 0,
onlinePaymentInvoiceId: '',
onlinePaymentMethodId: '',
onlinePaymentExpiryTimer: null,
paymentRenderGeneration: 0,
refreshPromise: null,
refreshController: null,
readSequence: 0,
appliedReadSequence: 0,
pollInvoiceId: '',
pollTimer: null,
pollController: null,
pollStartedAt: 0,
pollUntil: 0,
pollGeneration: 0,
};
const text = (id, value) => {
const element = byId(id);
if (element) element.textContent = value ?? '—';
};
function firstText(...values) {
for (const value of values) {
if (value !== null && value !== undefined && String(value).trim() !== '') {
return String(value).trim();
}
}
return '';
}
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;
if (content !== undefined) element.textContent = String(content);
return element;
}
function showError(id, message) {
const element = byId(id);
if (!element) return;
element.textContent = message || '';
element.hidden = !message;
}
function readInvoiceDetailBootstrap() {
const source = byId('invoice-detail-bootstrap');
if (!source) throw new Error('账单首屏数据缺失,请刷新页面后重试。');
let payload;
try {
payload = JSON.parse(source.textContent || '{}');
} catch {
throw new Error('账单首屏数据无效,请刷新页面后重试。');
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
throw new Error('账单首屏数据无效,请刷新页面后重试。');
}
return payload;
}
function requireSecureTransport() {
if (location.protocol !== 'https:'
&& !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) {
throw new Error('请通过 HTTPS 使用账单支付功能。');
}
}
async function api(path, options = {}) {
const method = String(options.method || 'GET').toUpperCase();
if (!['GET', 'HEAD'].includes(method)) requireSecureTransport();
const timeoutMs = Math.max(1_000, Number(options.timeoutMs) || REQUEST_TIMEOUT_MS);
const controller = new AbortController();
const externalSignal = options.signal;
let timedOut = false;
const abortFromExternal = () => controller.abort();
if (externalSignal?.aborted) controller.abort();
else externalSignal?.addEventListener('abort', abortFromExternal, { once: true });
const timeout = setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs);
const headers = new Headers(options.headers || {});
if (!headers.has('Accept')) headers.set('Accept', 'application/json');
if (!['GET', 'HEAD'].includes(method)) {
headers.set('X-CSRF-Token', state.csrfToken);
if (options.body !== undefined) headers.set('Content-Type', 'application/json');
}
try {
const response = await fetch(path, {
method,
headers,
credentials: 'same-origin',
cache: 'no-store',
signal: controller.signal,
body: options.body === undefined ? undefined : JSON.stringify(options.body),
});
let payload = null;
if (response.status !== 204) {
try {
payload = await response.json();
} catch {
throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。');
}
}
if (response.status === 401) {
location.assign('/auth/login');
throw new Error('登录已过期。');
}
if (!response.ok || payload?.ret === 0) {
const detail = Array.isArray(payload?.detail)
? payload.detail.map(item => item.msg || '输入错误').join(';')
: payload?.detail;
const error = new Error(String(detail || payload?.message || payload?.msg
|| payload?.error || `请求失败 (${response.status})`));
error.status = response.status;
throw error;
}
return payload;
} catch (error) {
if (error?.name === 'AbortError') {
const aborted = new Error(timedOut ? '请求超时,请稍后重试。' : '请求已取消。');
aborted.code = timedOut ? 'REQUEST_TIMEOUT' : 'REQUEST_ABORTED';
throw aborted;
}
if (error instanceof TypeError) throw new Error('网络请求失败,请检查连接后重试。');
throw error;
} finally {
clearTimeout(timeout);
externalSignal?.removeEventListener('abort', abortFromExternal);
}
}
function applySession(payload) {
const nested = payload?.user && typeof payload.user === 'object' ? payload.user : {};
const csrfToken = String(payload?.csrf_token ?? nested.csrf_token ?? '');
const userId = String(payload?.user_id ?? nested.user_id ?? nested.id ?? '');
if (!/^[a-f0-9]{64}$/.test(csrfToken) || !/^[1-9]\d*$/.test(userId)) {
throw new Error('账单会话信息不完整,请重新登录。');
}
state.csrfToken = csrfToken;
state.userId = userId;
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);
if (link) link.hidden = !state.admin;
}
}
function serviceTimestamp(value) {
if (value === null || value === undefined || value === '') return null;
if (typeof value === 'number' || /^\d+$/.test(String(value).trim())) {
const numeric = Number(value);
if (!Number.isFinite(numeric) || numeric <= 0) return null;
return numeric < 1e12 ? numeric * 1_000 : numeric;
}
const parsed = Date.parse(String(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';
return '';
}
function invoiceTitle(invoice) {
const purpose = invoicePurpose(invoice);
return firstText(invoice?.type_label, invoice?.title, {
recharge: '余额充值',
provision: '实例开通',
renewal: '实例续费',
}[purpose], '账单');
}
function invoiceStatusInfo(status) {
const values = {
open: ['待支付', 'warning'],
overdue: ['已逾期', 'failed'],
paid: ['已支付', 'running'],
refunded: ['已退款', 'other'],
void: ['已失效', 'other'],
expired: ['已失效', 'failed'],
deleting: ['实例删除中', 'failed'],
delete_failed: ['自动删除失败', 'failed'],
purge_pending: ['等待永久删除', 'failed'],
purge_stopping: ['删除前正在关机', '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 · 支付宝',
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) {
if (!['open', 'overdue'].includes(String(invoice?.status || '').toLowerCase())) return false;
if (invoice?.payable === false) return false;
if (invoice?.payable === true) return true;
const deadline = invoicePurpose(invoice) === '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.status, fulfillment.fulfillment_status,
invoice?.fulfillment_status, fulfillment.job_status, invoice?.job_status,
fulfillment.order_status, invoice?.order_status).toLowerCase(),
jobId: firstText(fulfillment.job_id, invoice?.job_id),
jobStatus: firstText(fulfillment.job_status, invoice?.job_status).toLowerCase(),
instanceId: firstText(fulfillment.instance_id, invoice?.instance_id),
instanceUuid: firstText(fulfillment.instance_uuid, fulfillment.vm_uuid,
invoice?.instance_uuid, invoice?.vm_uuid),
phase: firstText(fulfillment.phase, invoice?.phase),
error: firstText(fulfillment.error, invoice?.error),
};
}
function provisionStatusInfo(invoice) {
const data = provisionInvoiceData(invoice);
const status = data.status || data.jobStatus;
const values = {
awaiting_payment: ['等待支付', 'warning'],
payment_pending: ['等待支付', 'warning'],
draft: ['等待支付', 'warning'],
queued: ['等待创建', 'warning'],
pending: ['等待创建', 'warning'],
provisioning: ['创建中', 'warning'],
running: ['创建中', 'warning'],
completed: ['已开通', 'running'],
succeeded: ['已开通', 'running'],
active: ['已开通', 'running'],
failed: ['创建失败', 'failed'],
refunded: ['开通失败,已退款', 'failed'],
needs_attention: ['需要管理员核查', 'failed'],
uncertain: ['正在核对结果', 'warning'],
};
return { data, status, display: values[status] || [status || '等待支付', 'warning'] };
}
function provisionFinished(invoice) {
const { status } = provisionStatusInfo(invoice);
return ['completed', 'succeeded', 'active', 'failed', 'refunded',
'needs_attention'].includes(status);
}
function invoiceFact(label, value) {
const item = makeElement('div', 'invoice-detail-fact');
item.append(
makeElement('dt', '', label),
makeElement('dd', '', value === null || value === undefined || value === '' ? '—' : 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 renderInvoiceSpecification(invoice) {
const panel = byId('invoice-specification-panel');
const container = byId('invoice-specification');
if (!panel || !container) return;
const purpose = invoicePurpose(invoice);
if (!['provision', 'renewal'].includes(purpose)) {
panel.hidden = true;
container.replaceChildren();
return;
}
const spec = invoiceSpecification(invoice);
const subject = firstText(invoice.requested_name, invoice.instance_name,
purpose === 'provision' ? '待创建实例' : '实例');
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`));
facts.push(
invoiceFact('服务周期', `${Number(invoice.validity_days || 0)} 天`),
invoiceFact('周期流量', formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))),
);
container.replaceChildren(...facts);
panel.hidden = false;
}
function invoicePaymentStorageKey(invoiceId, methodId) {
return `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:${methodId}`;
}
function randomRequestId() {
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();
const bytes = new Uint8Array(24);
crypto.getRandomValues(bytes);
return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
}
function pendingInvoicePaymentKey(invoiceId, methodId) {
const storageKey = invoicePaymentStorageKey(invoiceId, methodId);
let key = '';
try { key = String(sessionStorage.getItem(storageKey) || ''); } catch {}
if (!/^[A-Za-z0-9_.-]{16,128}$/.test(key)) key = randomRequestId();
try { sessionStorage.setItem(storageKey, key); } catch {}
return key;
}
function clearInvoicePaymentKey(invoiceId, methodId) {
try { sessionStorage.removeItem(invoicePaymentStorageKey(invoiceId, methodId)); } catch {}
}
function clearInvoicePaymentKeys(invoiceId) {
const prefix = `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:`;
try {
const keys = [];
for (let index = 0; index < sessionStorage.length; index += 1) {
const key = sessionStorage.key(index);
if (key?.startsWith(prefix)) keys.push(key);
}
keys.forEach(key => sessionStorage.removeItem(key));
} catch {}
}
function hasPendingInvoicePaymentKey(invoiceId) {
const prefix = `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:`;
try {
for (let index = 0; index < sessionStorage.length; index += 1) {
const storageKey = sessionStorage.key(index);
if (!storageKey?.startsWith(prefix)) continue;
if (/^[A-Za-z0-9_.-]{16,128}$/.test(String(sessionStorage.getItem(storageKey) || ''))) {
return true;
}
}
} catch {}
return false;
}
async function copyText(value) {
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(value);
return;
} catch {}
}
const area = document.createElement('textarea');
area.value = value;
area.style.position = 'fixed';
area.style.opacity = '0';
document.body.append(area);
area.select();
try {
if (!document.execCommand('copy')) throw new Error('浏览器无法复制,请手动选择文本。');
} finally {
area.value = '';
area.remove();
}
}
function actionButton(label, handler) {
const button = makeElement('button', 'row-button', label);
button.type = 'button';
button.addEventListener('click', async () => {
if (button.getAttribute('aria-busy') === 'true') return;
button.disabled = true;
button.setAttribute('aria-busy', 'true');
try {
await handler();
} finally {
button.disabled = false;
button.removeAttribute('aria-busy');
}
});
return button;
}
function validPaymentUrl(value) {
try {
const url = new URL(String(value || ''));
return ['https:', 'weixin:', 'alipays:', 'alipayqr:'].includes(url.protocol)
? url.href : '';
} catch {
return '';
}
}
let qrCodePromise = null;
function loadQrCode() {
if (typeof window.QRCode === 'function') return Promise.resolve(window.QRCode);
if (qrCodePromise) return qrCodePromise;
qrCodePromise = new Promise((resolve, reject) => {
const script = document.createElement('script');
const url = new URL('/theme/venix/js/qrcode.min.js', location.origin);
const version = document.body.dataset.assetVersion;
if (version) url.searchParams.set('v', version);
const timer = setTimeout(() => {
script.remove();
reject(new Error('二维码组件加载超时'));
}, 10_000);
script.src = url.href;
script.async = true;
script.dataset.invoiceQr = 'true';
script.onload = () => {
clearTimeout(timer);
if (typeof window.QRCode === 'function') resolve(window.QRCode);
else reject(new Error('二维码组件不可用'));
};
script.onerror = () => {
clearTimeout(timer);
script.remove();
reject(new Error('二维码组件加载失败'));
};
document.head.append(script);
}).catch(error => {
qrCodePromise = null;
throw error;
});
return qrCodePromise;
}
async function appendPaymentQr(container, value, generation) {
if (!value) return false;
const qr = makeElement('div', 'cloud-payment-qr cloud-payment-qr-loading');
qr.setAttribute('role', 'status');
qr.setAttribute('aria-label', '正在生成支付二维码');
qr.append(makeElement('span', '', '二维码生成中…'));
container.append(qr);
try {
const QRCode = await loadQrCode();
if (!container.isConnected || !qr.isConnected || !state.onlinePaymentPending
|| generation !== state.paymentRenderGeneration) {
qr.remove();
return false;
}
qr.classList.remove('cloud-payment-qr-loading');
qr.removeAttribute('role');
qr.removeAttribute('aria-label');
qr.replaceChildren();
const levels = QRCode.CorrectLevel || { L: 1, M: 0 };
new QRCode(qr, {
text: String(value),
width: 196,
height: 196,
correctLevel: String(value).length > 1200 ? levels.L : levels.M,
});
if (!qr.children.length) throw new Error('二维码组件未生成内容');
return true;
} catch {
if (container.isConnected && qr.isConnected && state.onlinePaymentPending
&& generation === state.paymentRenderGeneration) {
qr.className = 'cloud-payment-qr cloud-payment-qr-error';
qr.setAttribute('role', 'status');
qr.setAttribute('aria-label', '支付二维码暂时无法显示');
qr.replaceChildren(makeElement('span', 'cloud-payment-qr-note',
'二维码暂时无法显示,请使用支付按钮或复制支付信息。'));
} else {
qr.remove();
}
return false;
}
}
function selectInvoicePaymentMethod(methodId) {
state.selectedInvoicePaymentMethod = String(methodId || '');
byId('invoice-payment-methods')?.querySelectorAll('.invoice-payment-method-card')
.forEach(card => {
const selected = card.dataset.methodId === state.selectedInvoicePaymentMethod;
card.setAttribute('aria-pressed', String(selected));
card.setAttribute('aria-checked', String(selected));
});
const submit = byId('invoice-payment-submit');
if (submit) submit.disabled = !state.selectedInvoicePaymentMethod;
}
function mergeInvoiceStatus(invoice, update) {
const current = invoice && typeof invoice === 'object' ? invoice : {};
const next = update && typeof update === 'object' ? update : {};
const merged = { ...current, ...next };
if (current.fulfillment && typeof current.fulfillment === 'object'
&& next.fulfillment && typeof next.fulfillment === 'object') {
merged.fulfillment = { ...current.fulfillment, ...next.fulfillment };
}
return merged;
}
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);
return invoiceDeadline !== null && invoiceDeadline > now
? Math.min(invoiceDeadline, maximum) : maximum;
}
function clearOnlinePaymentExpiryTimer() {
if (state.onlinePaymentExpiryTimer !== null) {
clearTimeout(state.onlinePaymentExpiryTimer);
}
state.onlinePaymentExpiryTimer = null;
}
function onlinePaymentHasExpired() {
return state.onlinePaymentPending && state.onlinePaymentExpiresAt > 0
&& Date.now() >= state.onlinePaymentExpiresAt;
}
function clearOnlinePaymentState(clearStoredKey = false) {
clearOnlinePaymentExpiryTimer();
const invoiceId = state.onlinePaymentInvoiceId || state.selectedInvoice?.id;
const methodId = state.onlinePaymentMethodId;
if (clearStoredKey && invoiceId) {
if (methodId) clearInvoicePaymentKey(invoiceId, methodId);
else clearInvoicePaymentKeys(invoiceId);
}
state.onlinePaymentPending = false;
state.onlinePaymentExpiresAt = 0;
state.onlinePaymentInvoiceId = '';
state.onlinePaymentMethodId = '';
state.paymentRenderGeneration += 1;
}
function expireOnlinePaymentInstructions(generation = state.paymentRenderGeneration) {
if (!state.onlinePaymentPending || generation !== state.paymentRenderGeneration) {
return false;
}
const invoiceId = String(state.onlinePaymentInvoiceId
|| state.selectedInvoice?.id || '');
clearOnlinePaymentState(true);
const result = byId('invoice-payment-result');
if (result) {
const notice = makeElement('div',
'cloud-payment-instructions cloud-payment-expired');
notice.append(
makeElement('strong', '', '支付订单已过期'),
makeElement('small', '', '请重新选择支付方式并确认,以生成新的支付订单。'),
);
result.replaceChildren(notice);
}
stopInvoicePoll();
if (/^[1-9]\d*$/.test(invoiceId) && !state.refreshPromise) {
void refreshInvoiceDetail(invoiceId);
} else if (invoiceNeedsPolling()) {
scheduleInvoicePoll(state.selectedInvoice?.id);
}
return true;
}
function scheduleOnlinePaymentExpiry(generation) {
clearOnlinePaymentExpiryTimer();
if (!state.onlinePaymentPending || state.onlinePaymentExpiresAt <= 0) return;
const remaining = state.onlinePaymentExpiresAt - Date.now();
if (remaining <= 0) {
expireOnlinePaymentInstructions(generation);
return;
}
state.onlinePaymentExpiryTimer = setTimeout(() => {
state.onlinePaymentExpiryTimer = null;
expireOnlinePaymentInstructions(generation);
}, remaining);
}
function invoiceNeedsPolling(invoice = state.selectedInvoice) {
if (!invoice?.id) return false;
if (state.onlinePaymentPending && !onlinePaymentHasExpired()
&& invoiceCanPay(invoice)) return true;
return invoicePurpose(invoice) === 'provision'
&& String(invoice.status || '').toLowerCase() === 'paid'
&& !provisionFinished(invoice);
}
function entersProvisioningAfterPayment(previousInvoice, nextInvoice,
wasAwaitingOnlinePayment) {
return wasAwaitingOnlinePayment
&& invoiceCanPay(previousInvoice)
&& invoicePurpose(nextInvoice) === 'provision'
&& String(nextInvoice?.status || '').toLowerCase() === 'paid'
&& !provisionFinished(nextInvoice);
}
function resetProvisioningPollWindow() {
state.pollStartedAt = Date.now();
state.pollUntil = state.pollStartedAt + STATUS_POLL_WINDOW_MS;
}
function stopInvoicePoll() {
state.pollGeneration += 1;
if (state.pollTimer !== null) clearTimeout(state.pollTimer);
state.pollTimer = null;
state.pollController?.abort();
state.pollController = null;
state.pollInvoiceId = '';
state.pollStartedAt = 0;
state.pollUntil = 0;
}
function queueInvoicePoll(generation, delay = STATUS_POLL_INTERVAL_MS) {
if (generation !== state.pollGeneration) return;
state.pollTimer = setTimeout(() => {
state.pollTimer = null;
void pollInvoiceStatus(generation);
}, delay);
}
function nextInvoicePollDelay() {
return Date.now() - state.pollStartedAt < STATUS_POLL_WINDOW_MS
? STATUS_POLL_INTERVAL_MS : STATUS_POLL_SLOW_INTERVAL_MS;
}
function pollCompletionMessage(invoice) {
const status = String(invoice?.status || '').toLowerCase();
if (status === 'paid') {
if (invoicePurpose(invoice) !== 'provision') {
return [invoicePurpose(invoice) === 'renewal'
? '账单支付成功,服务期限已延长。' : '账单支付成功。', 'success'];
}
if (provisionFinished(invoice)) {
const provisionStatus = provisionStatusInfo(invoice).status;
if (['succeeded', 'completed', 'active'].includes(provisionStatus)) {
return ['实例已创建完成。', 'success'];
}
if (provisionStatus === 'refunded') {
return ['实例创建失败,款项已退回账户余额。', 'error'];
}
return ['实例开通未完成,请在账单详情查看任务状态。', 'error'];
}
}
if (['void', 'expired'].includes(status)) {
return ['账单已失效,到账金额会保留在账户余额中。', 'error'];
}
if (status === 'refunded') {
return ['实例创建失败,款项已退回账户余额。', 'error'];
}
if (!invoiceCanPay(invoice) && status !== 'paid') {
return [invoicePurpose(invoice) === 'provision'
? '开通账单已超过支付截止时间。'
: invoicePurpose(invoice) === 'renewal'
? '续费宽限期已经结束,到账金额会保留在账户余额中。'
: '账单已超过支付截止时间。', 'error'];
}
return null;
}
async function pollInvoiceStatus(generation) {
if (generation !== state.pollGeneration) return;
if (onlinePaymentHasExpired()) {
expireOnlinePaymentInstructions();
return;
}
if (document.hidden || !state.pollInvoiceId || !invoiceNeedsPolling()) {
stopInvoicePoll();
return;
}
const controller = new AbortController();
const readSequence = ++state.readSequence;
const previousInvoice = state.selectedInvoice;
const wasAwaitingOnlinePayment = state.onlinePaymentPending;
state.pollController = controller;
try {
const result = await api(`/api/v1/invoices/${encodeURIComponent(state.pollInvoiceId)}/status`, {
signal: controller.signal,
timeoutMs: 10_000,
});
if (generation !== state.pollGeneration) return;
const update = result?.invoice;
if (readSequence >= state.appliedReadSequence
&& update?.id && String(update.id) === String(state.selectedInvoice?.id || '')) {
state.appliedReadSequence = readSequence;
const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update);
if (entersProvisioningAfterPayment(previousInvoice, nextInvoice,
wasAwaitingOnlinePayment)) {
resetProvisioningPollWindow();
}
renderInvoiceDetail(nextInvoice, {
balance: state.invoiceBalance,
payment_methods: state.invoicePaymentMethods,
});
}
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 {
if (generation === state.pollGeneration) state.pollController = null;
}
if (generation !== state.pollGeneration) return;
if (onlinePaymentHasExpired()) {
expireOnlinePaymentInstructions();
} else if (invoiceNeedsPolling() && Date.now() < state.pollUntil) {
queueInvoicePoll(generation, nextInvoicePollDelay());
} else {
stopInvoicePoll();
}
}
function scheduleInvoicePoll(invoiceId) {
const key = String(invoiceId || '');
if (!key || document.hidden || state.refreshPromise) return;
if (onlinePaymentHasExpired()) {
expireOnlinePaymentInstructions();
return;
}
if (!invoiceNeedsPolling()) return;
if (state.pollInvoiceId === key && (state.pollTimer !== null || state.pollController)) {
state.pollUntil = Math.max(state.pollUntil, state.onlinePaymentExpiresAt);
return;
}
stopInvoicePoll();
state.pollInvoiceId = key;
state.pollStartedAt = Date.now();
state.pollUntil = Math.max(state.pollStartedAt + STATUS_POLL_WINDOW_MS,
state.onlinePaymentExpiresAt);
const generation = ++state.pollGeneration;
queueInvoicePoll(generation);
}
function resumeInvoicePolling() {
if (onlinePaymentHasExpired()) {
expireOnlinePaymentInstructions();
return;
}
if (invoiceNeedsPolling()) scheduleInvoicePoll(state.selectedInvoice.id);
}
function renderOnlinePayment(container, payment) {
clearOnlinePaymentExpiryTimer();
const generation = ++state.paymentRenderGeneration;
let box = container.querySelector('.cloud-payment-instructions');
if (!box) {
box = makeElement('div', 'cloud-payment-instructions');
container.append(box);
}
box.className = 'cloud-payment-instructions';
box.replaceChildren();
state.onlinePaymentPending = true;
state.onlinePaymentInvoiceId = String(payment.invoice_id || state.selectedInvoice?.id || '');
state.onlinePaymentMethodId = firstText(payment.method,
state.selectedInvoicePaymentMethod);
const paymentExpiresAt = serviceTimestamp(payment.expires_at);
state.onlinePaymentExpiresAt = paymentExpiresAt === null
? onlinePaymentFallbackExpiresAt(state.selectedInvoice)
: Math.min(paymentExpiresAt, Date.now() + STATUS_POLL_MAX_LIFETIME_MS);
let qrValue = '';
if (payment.payment_kind === 'usdt') {
qrValue = payment.receive_address || '';
box.append(
makeElement('strong', '', `请支付 ${payment.actual_amount} USDT(TRC20)`),
makeElement('code', '', qrValue || '收款地址不可用'),
makeElement('small', '', `支付订单有效至 ${formatOrderDate(payment.expires_at)};链上确认后自动结清账单。`),
);
box.append(actionButton('复制收款地址', async () => {
try {
await copyText(qrValue);
toast('USDT 收款地址已复制。', 'success');
} catch (error) {
toast(error.message, 'error');
}
}));
} else {
qrValue = payment.payment_value || '';
const url = validPaymentUrl(qrValue);
box.append(makeElement('strong', '', `${payment.label || '在线支付'}订单已生成`));
if (url) {
const link = makeElement('a', 'button button-primary small', '前往支付');
link.href = url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
box.append(link);
} else {
box.append(makeElement('code', '', qrValue || '支付信息暂不可用'));
box.append(actionButton('复制支付信息', async () => {
try {
await copyText(qrValue);
toast('支付信息已复制。', 'success');
} catch (error) {
toast(error.message, 'error');
}
}));
}
box.append(makeElement('small', '',
'完成付款后本页会自动核对账单状态。请勿同时使用多个渠道重复付款。'));
}
void appendPaymentQr(box, qrValue, generation);
scheduleOnlinePaymentExpiry(generation);
if (generation === state.paymentRenderGeneration && state.onlinePaymentPending) {
scheduleInvoicePoll(state.onlinePaymentInvoiceId);
}
}
async function payInvoiceBalance(invoice, container) {
if (!invoiceCanPay(invoice)) {
toast(invoicePurpose(invoice) === 'provision'
? '开通账单已失效,不能支付。'
: invoicePurpose(invoice) === 'renewal'
? '续费宽限期已经结束,账单不可支付。'
: '账单已失效,不能支付。', 'error');
return;
}
if (state.mutationBusy) return;
state.mutationBusy = true;
container.querySelectorAll('button').forEach(button => { button.disabled = true; });
try {
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, {
method: 'POST',
body: { idempotency_key: randomRequestId() },
timeoutMs: 20_000,
});
state.invoiceBalance = String(result?.balance ?? state.invoiceBalance);
const paid = mergeInvoiceStatus(invoice, result?.invoice || {});
const startsProvisioning = invoicePurpose(paid) === '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');
}
} catch (error) {
toast(error.message, 'error');
if ([403, 409].includes(Number(error.status || 0))) {
await refreshInvoiceDetail(invoice.id);
}
} finally {
state.mutationBusy = false;
container.querySelectorAll('button').forEach(button => { button.disabled = false; });
}
}
async function createInvoicePayment(invoice, method, container, paymentResult) {
if (!invoiceCanPay(invoice)) {
toast(invoicePurpose(invoice) === 'provision'
? '开通账单已失效,不能再生成支付订单。'
: invoicePurpose(invoice) === 'renewal'
? '续费宽限期已经结束,不能再生成支付订单。'
: '账单已失效,不能再生成支付订单。', 'error');
return;
}
if (state.mutationBusy) return;
state.mutationBusy = true;
container.querySelectorAll('button').forEach(button => { button.disabled = true; });
const idempotencyKey = pendingInvoicePaymentKey(invoice.id, method.id);
try {
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/payments`, {
method: 'POST',
body: { method: method.id, idempotency_key: idempotencyKey },
timeoutMs: 20_000,
});
renderOnlinePayment(paymentResult, result.payment || {});
} catch (error) {
const status = Number(error.status || 0);
const ambiguousHttpFailure = [408, 425, 429].includes(status);
const creationStillInProgress = String(error.message).includes('正在创建');
if (status >= 400 && status < 500 && !ambiguousHttpFailure
&& !creationStillInProgress) {
clearInvoicePaymentKey(invoice.id, method.id);
}
toast(error.message, 'error');
if ([403, 409].includes(status) && !creationStillInProgress) {
await refreshInvoiceDetail(invoice.id);
}
} finally {
state.mutationBusy = false;
container.querySelectorAll('button').forEach(button => { button.disabled = false; });
}
}
function renderInvoicePaymentMethods(invoice, balance, methods) {
const panel = byId('invoice-payment-panel');
const container = byId('invoice-payment-methods');
const result = byId('invoice-payment-result');
if (!panel || !container || !result) return;
if (!invoiceCanPay(invoice)) {
clearInvoicePaymentKeys(invoice.id);
clearOnlinePaymentState();
panel.hidden = true;
container.replaceChildren();
result.replaceChildren();
state.selectedInvoicePaymentMethod = '';
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' });
}
if (!choices.length) {
clearInvoicePaymentKeys(invoice.id);
clearOnlinePaymentState();
panel.hidden = true;
container.replaceChildren();
result.replaceChildren();
state.selectedInvoicePaymentMethod = '';
return;
}
const available = new Set(choices.map(choice => String(choice.id)));
if (!available.has(state.selectedInvoicePaymentMethod)) {
state.selectedInvoicePaymentMethod = String(choices[0].id);
}
const cards = choices.map(choice => {
const card = makeElement('button', 'invoice-payment-method-card');
card.type = 'button';
card.dataset.methodId = String(choice.id);
card.setAttribute('role', 'radio');
const selected = String(choice.id) === state.selectedInvoicePaymentMethod;
card.setAttribute('aria-pressed', String(selected));
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('span', 'invoice-payment-method-check', '✓'),
);
card.addEventListener('click', () => selectInvoicePaymentMethod(choice.id));
return card;
});
container.replaceChildren(...cards);
panel.hidden = false;
const submit = byId('invoice-payment-submit');
if (!submit) return;
submit.disabled = !state.selectedInvoicePaymentMethod;
submit.onclick = async () => {
showError('invoice-payment-error', '');
const choice = choices.find(item => String(item.id) === state.selectedInvoicePaymentMethod);
if (!choice) {
showError('invoice-payment-error', '请选择支付方式。');
return;
}
if (choice.kind === 'balance') await payInvoiceBalance(invoice, panel);
else await createInvoicePayment(invoice, choice, panel, result);
};
}
function invoiceProgressText(job) {
const status = firstText(job?.status).toLowerCase();
const labels = {
queued: '等待创建',
pending: '等待创建',
running: '正在创建',
provisioning: '正在创建',
uncertain: '正在核对创建结果',
succeeded: '实例创建完成',
completed: '实例创建完成',
failed: '实例创建失败',
refunded: '创建失败,已退款',
needs_attention: '需要管理员核查',
};
const resultMessage = typeof job?.result === 'object'
? firstText(job.result.message, job.result.status) : '';
return firstText(job?.error, job?.phase, resultMessage, labels[status],
status ? `任务状态:${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.jobId) {
actions.append(actionButton('查看创建进度', async () => {
if (state.refreshPromise) {
toast('账单正在刷新,请稍候。');
return;
}
let progress = detail.querySelector('.cloud-order-progress');
if (!progress) {
progress = makeElement('p', 'cloud-order-progress muted');
detail.append(progress);
}
const readSequence = ++state.readSequence;
try {
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/status`, {
timeoutMs: 12_000,
});
const update = result?.invoice;
if (!update?.id || String(update.id) !== String(invoice.id)) {
throw new Error('创建进度与当前账单不匹配,请刷新后重试。');
}
if (readSequence < state.appliedReadSequence) return;
state.appliedReadSequence = readSequence;
const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update);
const jobStatus = firstText(update.job_status,
update.fulfillment_status).toLowerCase();
const failed = ['failed', 'refunded', 'needs_attention'].includes(jobStatus)
|| Boolean(update.error);
state.invoiceJobProgress.set(String(invoice.id), {
message: invoiceProgressText({ status: jobStatus,
error: update.error, phase: update.phase }),
failed,
});
renderInvoiceDetail(nextInvoice, {
balance: state.invoiceBalance,
payment_methods: state.invoicePaymentMethods,
});
} catch (error) {
if (readSequence < state.appliedReadSequence) return;
progress.className = 'cloud-order-progress form-error';
progress.textContent = error.message;
}
}));
}
if (data.instanceId) {
const link = makeElement('a', 'row-button', '查看实例');
link.href = `/user/cloud/instances/${encodeURIComponent(data.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) {
const panel = byId('invoice-fulfillment-panel');
const content = byId('invoice-fulfillment-content');
if (!panel || !content) return;
const invoiceStatus = firstText(invoice.status).toLowerCase();
const visible = invoicePurpose(invoice) === 'provision'
&& (['paid', 'refunded'].includes(invoiceStatus)
|| Boolean(provisionInvoiceData(invoice).jobId));
if (!visible) {
panel.hidden = true;
content.replaceChildren();
return;
}
const detail = makeElement('div', 'invoice-fulfillment-detail');
const actions = makeElement('div', 'cloud-order-actions invoice-fulfillment-actions');
const { data, status, display } = provisionStatusInfo(invoice);
const cached = state.invoiceJobProgress.get(String(invoice.id));
const terminal = provisionFinished(invoice);
const failed = Boolean(data.error) || ['failed', 'refunded', 'needs_attention'].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,
status === 'uncertain' ? '后台正在核对实例创建结果,请勿重复提交。' : display[0]));
detail.append(progress);
appendProvisionInvoiceActions(invoice, 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();
}
}
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.status);
const status = byId('invoice-detail-status');
if (status) {
status.className = `state-pill ${statusClass}`;
status.textContent = statusLabel;
}
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.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)));
byId('invoice-detail-facts')?.replaceChildren(...facts);
renderInvoiceSpecification(invoice);
renderInvoicePaymentMethods(invoice, payload.balance,
Array.isArray(payload.payment_methods) ? payload.payment_methods : []);
renderInvoiceFulfillment(invoice);
}
function hydrateInvoiceDetail(payload, expectedInvoiceId = document.body.dataset.invoiceId) {
if (!payload?.invoice || typeof payload.invoice !== 'object') {
throw new Error('账单信息不完整,请刷新页面后重试。');
}
const expected = String(expectedInvoiceId || '');
if (!/^[1-9]\d*$/.test(expected)
|| String(payload.invoice.id || '') !== expected) {
throw new Error('账单初始数据与当前地址不匹配,请返回账单列表重试。');
}
const previousInvoice = state.selectedInvoice;
const wasAwaitingOnlinePayment = state.onlinePaymentPending;
applySession(payload);
if (state.selectedInvoice
&& String(state.selectedInvoice.id) !== String(payload.invoice.id)) {
state.selectedInvoicePaymentMethod = '';
clearOnlinePaymentState();
byId('invoice-payment-result')?.replaceChildren();
}
state.invoicePaymentMethods = Array.isArray(payload.payment_methods)
? payload.payment_methods : [];
if (onlinePaymentHasExpired()) expireOnlinePaymentInstructions();
const restoredProviderPayment = hasPendingInvoicePaymentKey(payload.invoice.id);
state.onlinePaymentPending = invoiceCanPay(payload.invoice)
&& (state.onlinePaymentPending || restoredProviderPayment);
if (state.onlinePaymentPending) {
state.onlinePaymentInvoiceId = String(payload.invoice.id);
if (state.onlinePaymentExpiresAt <= 0) {
state.onlinePaymentExpiresAt = onlinePaymentFallbackExpiresAt(payload.invoice);
}
}
if (entersProvisioningAfterPayment(previousInvoice, payload.invoice,
wasAwaitingOnlinePayment)) {
resetProvisioningPollWindow();
}
renderInvoiceDetail(payload.invoice, payload);
if (state.onlinePaymentPending) {
scheduleOnlinePaymentExpiry(state.paymentRenderGeneration);
}
resumeInvoicePolling();
showError('cloud-page-error', '');
return payload.invoice;
}
async function refreshInvoiceDetail(invoiceId = document.body.dataset.invoiceId) {
const id = String(invoiceId || '');
if (!/^[1-9]\d*$/.test(id)) {
showError('cloud-page-error', '账单编号无效。');
return null;
}
if (state.refreshPromise) return state.refreshPromise;
// A status response is intentionally sparse. Do not let it overtake this
// full read and cause balance, payment methods or a rotated CSRF token to be
// discarded as though the whole response were stale.
stopInvoicePoll();
const button = byId('invoice-detail-refresh');
const workspace = byId('invoice-detail-workspace');
const controller = new AbortController();
state.refreshController = controller;
const readSequence = ++state.readSequence;
if (button) {
button.disabled = true;
button.setAttribute('aria-busy', 'true');
}
workspace?.setAttribute('aria-busy', 'true');
const request = (async () => {
try {
const payload = await api(`/api/v1/invoices/${encodeURIComponent(id)}`, {
signal: controller.signal,
timeoutMs: 12_000,
});
if (readSequence < state.appliedReadSequence) return state.selectedInvoice;
state.appliedReadSequence = readSequence;
return hydrateInvoiceDetail(payload, id);
} catch (error) {
if (error?.code !== 'REQUEST_ABORTED') {
showError('cloud-page-error', error.message || '账单刷新失败,请稍后重试。');
}
return null;
} finally {
if (state.refreshController === controller) state.refreshController = null;
state.refreshPromise = null;
if (button) {
button.disabled = false;
button.removeAttribute('aria-busy');
}
workspace?.removeAttribute('aria-busy');
if (!controller.signal.aborted) resumeInvoicePolling();
}
})();
state.refreshPromise = request;
return request;
}
let cleanupBound = false;
function bindInvoiceDetailCleanup() {
if (cleanupBound) return;
cleanupBound = true;
window.addEventListener('pagehide', () => {
state.refreshController?.abort();
stopInvoicePoll();
const element = byId('toast');
if (element) element.hidden = true;
clearOnlinePaymentExpiryTimer();
});
}
export {
bindInvoiceDetailCleanup,
byId,
hydrateInvoiceDetail,
readInvoiceDetailBootstrap,
refreshInvoiceDetail,
resumeInvoicePolling,
showError,
state,
stopInvoicePoll,
};