|
|
|
|
@ -1,11 +1,13 @@
|
|
|
|
|
// PHP owns authentication, authorisation, ownership and purchasing. No engine
|
|
|
|
|
// address, token, host credential or unrestricted create API exists in this UI.
|
|
|
|
|
const byId = (id) => document.getElementById(id);
|
|
|
|
|
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, invoices: [], invoicePaymentMethods: [], invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, orderPoll: null, mutationBusy: false, orderIdempotency: '', orderFingerprint: '', rescueActive: false, rescueStaged: false };
|
|
|
|
|
const ORDER_STORAGE_PREFIX = 'virt-cloud:pending-order:';
|
|
|
|
|
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, invoices: [], invoicePaymentMethods: [], invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false };
|
|
|
|
|
// Keep the historical storage key so an interrupted deployment made just
|
|
|
|
|
// before an online update can still reconcile to the same opening invoice.
|
|
|
|
|
const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:';
|
|
|
|
|
const INVOICE_PAYMENT_STORAGE_PREFIX = 'virt-cloud:invoice-payment:';
|
|
|
|
|
const text = (id, value) => { byId(id).textContent = value ?? '—'; };
|
|
|
|
|
const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.orders) ? payload.orders : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : [];
|
|
|
|
|
const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : [];
|
|
|
|
|
function showError(id, message) { text(id, message); byId(id).hidden = !message; }
|
|
|
|
|
let toastTimer;
|
|
|
|
|
function toast(message, kind = '') { const element = byId('toast'); element.textContent = message; element.className = `toast ${kind}`; element.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { element.hidden = true; }, 5000); }
|
|
|
|
|
@ -146,8 +148,8 @@ function setVmDetailTab(tab, focus = false) {
|
|
|
|
|
function showView(view) {
|
|
|
|
|
clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); state.view = view;
|
|
|
|
|
if (view !== 'invoices' && state.invoicePollTimers.size) stopInvoicePoll();
|
|
|
|
|
byId('vm-workspace').hidden = ['keys', 'orders', 'invoices'].includes(view);
|
|
|
|
|
byId('ssh-keys-workspace').hidden = view !== 'keys'; byId('orders-workspace').hidden = view !== 'orders'; byId('invoices-workspace').hidden = view !== 'invoices';
|
|
|
|
|
byId('vm-workspace').hidden = ['keys', 'invoices'].includes(view);
|
|
|
|
|
byId('ssh-keys-workspace').hidden = view !== 'keys'; byId('invoices-workspace').hidden = view !== 'invoices';
|
|
|
|
|
const sections = { list: 'vm-list-view', detail: 'vm-detail-view', create: 'create-view', reinstall: 'reinstall-view', rescue: 'rescue-view' };
|
|
|
|
|
for (const [name, id] of Object.entries(sections)) byId(id).hidden = view !== name;
|
|
|
|
|
const navigationView = ['detail', 'reinstall', 'rescue'].includes(view) ? 'list' : view;
|
|
|
|
|
@ -157,13 +159,13 @@ function showView(view) {
|
|
|
|
|
if (active) button.setAttribute('aria-current', 'page');
|
|
|
|
|
else button.removeAttribute('aria-current');
|
|
|
|
|
});
|
|
|
|
|
text('breadcrumb-current', ({ list: '实例管理', detail: '虚拟机详情', create: '部署实例', reinstall: '重装系统', rescue: '紧急救援', keys: 'SSH 公钥', orders: '开通订单', invoices: '续费账单' })[view]);
|
|
|
|
|
const hash = ({ list: '', create: 'plans', keys: 'keys', orders: 'orders', invoices: 'invoices' })[view] ?? (selectedVm() ? `vm=${encodeURIComponent(selectedVm().api_id)}` : '');
|
|
|
|
|
text('breadcrumb-current', ({ list: '实例管理', detail: '虚拟机详情', create: '部署实例', reinstall: '重装系统', rescue: '紧急救援', keys: 'SSH 公钥', invoices: '账单信息' })[view]);
|
|
|
|
|
const hash = ({ list: '', create: 'plans', keys: 'keys', invoices: 'invoices' })[view] ?? (selectedVm() ? `vm=${encodeURIComponent(selectedVm().api_id)}` : '');
|
|
|
|
|
history.replaceState(null, '', `${location.pathname}${location.search}${hash ? '#' + hash : ''}`);
|
|
|
|
|
window.scrollTo({ top: 0, behavior: 'auto' });
|
|
|
|
|
if (view === 'detail') setVmDetailTab(state.detailTab);
|
|
|
|
|
}
|
|
|
|
|
async function routeHash(hash = location.hash) { const target = hash.replace(/^#/, ''); try { if (target === 'plans') await openCreate(); else if (target === 'keys') { showView('keys'); await loadKeys(); } else if (target === 'orders') { showView('orders'); await loadOrders(); } else if (target === 'invoices') { showView('invoices'); await loadInvoices(); } else if (target.startsWith('vm=')) { const id = decodeURIComponent(target.slice(3)); const vm = state.vms.find(item => item.api_id === id); if (vm) openVmDetail(vm.uuid); else showView('list'); } else showView('list'); } catch (error) { showError('cloud-page-error', error.message); } }
|
|
|
|
|
async function routeHash(hash = location.hash) { const target = hash.replace(/^#/, ''); try { if (target === 'plans') await openCreate(); else if (target === 'keys') { showView('keys'); await loadKeys(); } else if (target === 'orders' || target === 'invoices') { showView('invoices'); await loadInvoices(); } else if (target.startsWith('vm=')) { const id = decodeURIComponent(target.slice(3)); const vm = state.vms.find(item => item.api_id === id); if (vm) openVmDetail(vm.uuid); else showView('list'); } else showView('list'); } catch (error) { showError('cloud-page-error', error.message); } }
|
|
|
|
|
async function loadVms() {
|
|
|
|
|
if (state.loadingVMs) return;
|
|
|
|
|
state.loadingVMs = true;
|
|
|
|
|
@ -271,28 +273,28 @@ async function loadPlanResources() {
|
|
|
|
|
try { const resources = await api(`/api/v1/resources?plan_id=${encodeURIComponent(planId)}`, { signal: state.resourceController.signal }); if (epoch !== state.formEpoch) return; state.resources = resources; state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('vm-template'); const isos = items(resources.isos || resources.iso_images); const select = byId('vm-iso'); select.replaceChildren(makeElement('option', '', isos.length ? '选择安装镜像' : '没有可用 ISO')); select.firstElementChild.value = ''; for (const iso of isos) { const path = typeof iso === 'string' ? iso : iso.path || iso.name; if (!path) continue; const option = makeElement('option', '', typeof iso === 'string' ? iso.split('/').pop() : iso.name || iso.path.split('/').pop()); option.value = path; select.append(option); } byId('create-submit').disabled = false; }
|
|
|
|
|
catch (error) { if (epoch === state.formEpoch && error.name !== 'AbortError') showError('create-error', error.message); }
|
|
|
|
|
}
|
|
|
|
|
function orderStorageKey() { return `${ORDER_STORAGE_PREFIX}${state.userId || 'unknown'}`; }
|
|
|
|
|
async function purchaseFingerprint(body) {
|
|
|
|
|
if (!globalThis.crypto?.subtle) throw new Error('当前浏览器不支持安全订单核对,请更新浏览器。');
|
|
|
|
|
function provisionInvoiceStorageKey() { return `${PROVISION_INVOICE_STORAGE_PREFIX}${state.userId || 'unknown'}`; }
|
|
|
|
|
async function provisionInvoiceFingerprint(body) {
|
|
|
|
|
if (!globalThis.crypto?.subtle) throw new Error('当前浏览器不支持安全账单核对,请更新浏览器。');
|
|
|
|
|
const canonical = {}; for (const key of Object.keys(body).sort()) canonical[key] = body[key];
|
|
|
|
|
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(canonical)));
|
|
|
|
|
return Array.from(new Uint8Array(digest), value => value.toString(16).padStart(2, '0')).join('');
|
|
|
|
|
}
|
|
|
|
|
async function pendingOrderKey(fingerprint) {
|
|
|
|
|
if (state.orderIdempotency && state.orderFingerprint === fingerprint) return state.orderIdempotency;
|
|
|
|
|
async function pendingProvisionInvoiceKey(fingerprint) {
|
|
|
|
|
if (state.provisionIdempotency && state.provisionFingerprint === fingerprint) return state.provisionIdempotency;
|
|
|
|
|
let saved = null;
|
|
|
|
|
try { saved = JSON.parse(sessionStorage.getItem(orderStorageKey()) || 'null'); } catch {}
|
|
|
|
|
try { saved = JSON.parse(sessionStorage.getItem(provisionInvoiceStorageKey()) || 'null'); } catch {}
|
|
|
|
|
let key = saved && saved.fingerprint === fingerprint ? String(saved.key || '') : '';
|
|
|
|
|
if (!/^[A-Za-z0-9_.-]{16,128}$/.test(key)) key = crypto.randomUUID();
|
|
|
|
|
state.orderIdempotency = key;
|
|
|
|
|
state.orderFingerprint = fingerprint;
|
|
|
|
|
try { sessionStorage.setItem(orderStorageKey(), JSON.stringify({ key, fingerprint })); } catch {}
|
|
|
|
|
state.provisionIdempotency = key;
|
|
|
|
|
state.provisionFingerprint = fingerprint;
|
|
|
|
|
try { sessionStorage.setItem(provisionInvoiceStorageKey(), JSON.stringify({ key, fingerprint })); } catch {}
|
|
|
|
|
return key;
|
|
|
|
|
}
|
|
|
|
|
function clearPendingOrderKey() {
|
|
|
|
|
state.orderIdempotency = '';
|
|
|
|
|
state.orderFingerprint = '';
|
|
|
|
|
try { sessionStorage.removeItem(orderStorageKey()); } catch {}
|
|
|
|
|
function clearPendingProvisionInvoiceKey() {
|
|
|
|
|
state.provisionIdempotency = '';
|
|
|
|
|
state.provisionFingerprint = '';
|
|
|
|
|
try { sessionStorage.removeItem(provisionInvoiceStorageKey()); } catch {}
|
|
|
|
|
}
|
|
|
|
|
function invoicePaymentStorageKey(invoiceId, methodId) {
|
|
|
|
|
return `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:${methodId}`;
|
|
|
|
|
@ -319,8 +321,8 @@ function clearInvoicePaymentKeys(invoiceId) {
|
|
|
|
|
keys.forEach(key => sessionStorage.removeItem(key));
|
|
|
|
|
} catch {}
|
|
|
|
|
}
|
|
|
|
|
async function existingPendingOrder(key) {
|
|
|
|
|
try { return await api(`/api/v1/orders/by-request/${encodeURIComponent(key)}`); }
|
|
|
|
|
async function existingProvisionInvoice(key) {
|
|
|
|
|
try { return await api(`/api/v1/invoices/by-request/${encodeURIComponent(key)}`); }
|
|
|
|
|
catch (error) { if (error.status === 404) return null; throw error; }
|
|
|
|
|
}
|
|
|
|
|
async function buy(event) {
|
|
|
|
|
@ -330,74 +332,75 @@ async function buy(event) {
|
|
|
|
|
if (cloud && !byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。');
|
|
|
|
|
if (!byId('vm-plan').value || !state.resources) return showError('create-error', '请先选择可用套餐。');
|
|
|
|
|
const selectedPlan = state.plans.find(plan => String(plan.id) === byId('vm-plan').value);
|
|
|
|
|
const purchaseSummary = selectedPlan ? `每期 ¥${selectedPlan.price},${planBillingLabel(selectedPlan)}` : '所选套餐';
|
|
|
|
|
if (!confirm(`确认从账户余额支付并开通虚拟机?${purchaseSummary}。到期前 7 天会自动生成续费账单。`)) return;
|
|
|
|
|
const purchaseSummary = selectedPlan ? `¥${selectedPlan.price},${planBillingLabel(selectedPlan)}` : '所选套餐';
|
|
|
|
|
if (!confirm(`确认为该实例生成开通账单?账单金额 ${purchaseSummary}。支付完成后才会开始创建实例。`)) return;
|
|
|
|
|
state.mutationBusy = true; byId('create-submit').disabled = true; showError('create-error', '');
|
|
|
|
|
const body = { plan_id: Number(byId('vm-plan').value), name: byId('vm-name').value.trim(), source: sourceMode() };
|
|
|
|
|
if (cloud) { body.template_id = byId('vm-template').value; if (state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; if (password) body.root_password = password; } else body.iso_path = byId('vm-iso').value;
|
|
|
|
|
try {
|
|
|
|
|
const fingerprint = await purchaseFingerprint(body);
|
|
|
|
|
const orderIdempotency = await pendingOrderKey(fingerprint);
|
|
|
|
|
body.idempotency_key = orderIdempotency;
|
|
|
|
|
const recovered = await existingPendingOrder(orderIdempotency);
|
|
|
|
|
if (!recovered) await api('/api/v1/orders', { method: 'POST', body });
|
|
|
|
|
clearPendingOrderKey(); byId('vm-root-password').value = '';
|
|
|
|
|
toast(recovered ? '已找回之前提交的订单,没有重复扣款。' : '订单已提交,后台持续开通中。', 'success');
|
|
|
|
|
showView('orders'); await loadOrders();
|
|
|
|
|
const fingerprint = await provisionInvoiceFingerprint(body);
|
|
|
|
|
const invoiceIdempotency = await pendingProvisionInvoiceKey(fingerprint);
|
|
|
|
|
body.idempotency_key = invoiceIdempotency;
|
|
|
|
|
const recovered = await existingProvisionInvoice(invoiceIdempotency);
|
|
|
|
|
if (!recovered) await api('/api/v1/invoices', { method: 'POST', body });
|
|
|
|
|
clearPendingProvisionInvoiceKey(); byId('vm-root-password').value = '';
|
|
|
|
|
toast(recovered ? '已找回之前生成的开通账单,没有重复创建。' : '开通账单已生成,请完成支付。', 'success');
|
|
|
|
|
showView('invoices'); await loadInvoices();
|
|
|
|
|
}
|
|
|
|
|
catch (error) {
|
|
|
|
|
// A timeout or 409 can mean the first request committed but its response
|
|
|
|
|
// was lost. Reconcile by the same durable key before reporting failure.
|
|
|
|
|
try {
|
|
|
|
|
const orderIdempotency = state.orderIdempotency;
|
|
|
|
|
const recovered = orderIdempotency ? await existingPendingOrder(orderIdempotency) : null;
|
|
|
|
|
const invoiceIdempotency = state.provisionIdempotency;
|
|
|
|
|
const recovered = invoiceIdempotency ? await existingProvisionInvoice(invoiceIdempotency) : null;
|
|
|
|
|
if (recovered) {
|
|
|
|
|
clearPendingOrderKey(); byId('vm-root-password').value = '';
|
|
|
|
|
toast('已核对到订单,没有重复扣款。', 'success'); showView('orders'); await loadOrders(); return;
|
|
|
|
|
clearPendingProvisionInvoiceKey(); byId('vm-root-password').value = '';
|
|
|
|
|
toast('已核对到开通账单,没有重复创建。', 'success'); showView('invoices'); await loadInvoices(); return;
|
|
|
|
|
}
|
|
|
|
|
} catch {}
|
|
|
|
|
showError('create-error', `${error.message} 可再次点击提交安全核对同一订单。`);
|
|
|
|
|
showError('create-error', `${error.message} 可再次点击提交安全核对同一张账单。`);
|
|
|
|
|
}
|
|
|
|
|
finally { delete body.root_password; state.mutationBusy = false; byId('create-submit').disabled = !state.resources; }
|
|
|
|
|
}
|
|
|
|
|
function formatOrderDate(value) { const date = new Date(typeof value === 'number' ? value * 1000 : value); return Number.isFinite(date.getTime()) ? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录'; }
|
|
|
|
|
async function loadOrders() {
|
|
|
|
|
try {
|
|
|
|
|
const orders = items(await api('/api/v1/orders'));
|
|
|
|
|
const container = byId('orders-list');
|
|
|
|
|
container.replaceChildren();
|
|
|
|
|
if (!orders.length) return container.append(makeElement('p', 'muted', '暂无订单。'));
|
|
|
|
|
const labels = { queued: '等待开通', pending: '等待开通', provisioning: '开通中', running: '开通中', completed: '已开通', succeeded: '已开通', active: '已开通', failed: '失败', refunded: '已退款', needs_attention: '需要管理员核查', uncertain: '需要管理员核查' };
|
|
|
|
|
for (const order of orders) {
|
|
|
|
|
const row = makeElement('div', 'cloud-order');
|
|
|
|
|
const detail = makeElement('div', 'cloud-order-detail');
|
|
|
|
|
detail.append(makeElement('strong', '', order.name || order.plan_name || `订单 #${order.id} · 套餐 #${order.plan_id ?? '—'}`), makeElement('p', 'muted', `¥${order.price ?? order.amount ?? '—'} · ${formatOrderDate(order.created_at)}`));
|
|
|
|
|
if (order.error || order.message || order.phase) detail.append(makeElement('p', 'cloud-order-message', order.error || order.message || order.phase));
|
|
|
|
|
const completed = ['completed', 'succeeded', 'active'].includes(order.status);
|
|
|
|
|
const failed = ['failed', 'refunded'].includes(order.status);
|
|
|
|
|
const stateClass = completed ? 'running' : failed ? 'failed' : 'other';
|
|
|
|
|
const actions = makeElement('div', 'cloud-order-actions');
|
|
|
|
|
actions.append(makeElement('span', `state-pill ${stateClass}`, labels[order.status] || order.status));
|
|
|
|
|
if (order.job_id) actions.append(actionButton('查看任务进度', async () => {
|
|
|
|
|
let progress = detail.querySelector('.cloud-order-progress');
|
|
|
|
|
if (!progress) { progress = makeElement('p', 'cloud-order-progress muted'); detail.append(progress); }
|
|
|
|
|
try { const job = await api(`/api/v1/jobs/${encodeURIComponent(order.job_id)}`); progress.className = `cloud-order-progress ${job.error ? 'form-error' : 'muted'}`; progress.textContent = job.error || job.phase || `任务状态:${job.status}`; }
|
|
|
|
|
catch (error) { toast(error.message, 'error'); }
|
|
|
|
|
}));
|
|
|
|
|
if (order.vm_id || order.instance_id || order.vm_uuid) actions.append(actionButton('查看虚拟机', async () => {
|
|
|
|
|
await loadVms();
|
|
|
|
|
const vm = state.vms.find(item => item.api_id === String(order.vm_id || order.instance_id) || item.uuid === order.vm_uuid);
|
|
|
|
|
if (vm) openVmDetail(vm.uuid); else toast('虚拟机尚未出现在列表,请稍后刷新。');
|
|
|
|
|
}));
|
|
|
|
|
row.append(detail, actions);
|
|
|
|
|
container.append(row);
|
|
|
|
|
}
|
|
|
|
|
} catch (error) { showError('cloud-page-error', error.message); }
|
|
|
|
|
function invoicePurpose(invoice) {
|
|
|
|
|
const value = firstText(invoice?.purpose, invoice?.kind, invoice?.invoice_type, invoice?.type).toLowerCase();
|
|
|
|
|
return ['provision', 'provisioning', 'initial', 'create'].includes(value) ? 'provision' : 'renewal';
|
|
|
|
|
}
|
|
|
|
|
function provisionInvoiceData(invoice) {
|
|
|
|
|
const fulfillment = invoice?.fulfillment && typeof invoice.fulfillment === 'object' ? invoice.fulfillment : {};
|
|
|
|
|
return {
|
|
|
|
|
orderId: firstText(fulfillment.order_id, invoice?.order_id),
|
|
|
|
|
status: firstText(fulfillment.status, fulfillment.fulfillment_status, invoice?.fulfillment_status,
|
|
|
|
|
fulfillment.order_status, invoice?.order_status, fulfillment.job_status, invoice?.job_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: ['需要管理员核查', 'failed'],
|
|
|
|
|
};
|
|
|
|
|
return { data, status, display: values[status] || [status || '等待支付', 'warning'] };
|
|
|
|
|
}
|
|
|
|
|
function provisionFinished(invoice) {
|
|
|
|
|
const { status } = provisionStatusInfo(invoice);
|
|
|
|
|
return ['completed', 'succeeded', 'active', 'failed', 'refunded', 'needs_attention', 'uncertain'].includes(status);
|
|
|
|
|
}
|
|
|
|
|
function invoiceStatusInfo(status) {
|
|
|
|
|
const values = {
|
|
|
|
|
open: ['待支付', 'warning'], overdue: ['已逾期', 'failed'],
|
|
|
|
|
paid: ['已支付', 'running'], void: ['已失效', 'other'], expired: ['宽限期已结束', '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'],
|
|
|
|
|
@ -407,12 +410,16 @@ function invoiceStatusInfo(status) {
|
|
|
|
|
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 deletionAt = invoiceDeletionTimestamp(invoice);
|
|
|
|
|
return deletionAt === null || Date.now() < deletionAt;
|
|
|
|
|
const deadline = invoicePurpose(invoice) === 'provision'
|
|
|
|
|
? invoicePaymentDeadlineTimestamp(invoice) : invoiceDeletionTimestamp(invoice);
|
|
|
|
|
return deadline === null || Date.now() < deadline;
|
|
|
|
|
}
|
|
|
|
|
function validPaymentUrl(value) {
|
|
|
|
|
try {
|
|
|
|
|
@ -454,14 +461,32 @@ function scheduleInvoicePoll(invoiceId) {
|
|
|
|
|
if (state.view !== 'invoices') return stopInvoicePoll(key);
|
|
|
|
|
try {
|
|
|
|
|
const result = await api(`/api/v1/invoices/${encodeURIComponent(key)}`);
|
|
|
|
|
if (result.invoice?.status === 'paid') {
|
|
|
|
|
stopInvoicePoll(key); toast('账单支付成功,服务期限已延长。', 'success'); await loadInvoices(); await loadVms(); return;
|
|
|
|
|
const invoice = result.invoice || {};
|
|
|
|
|
const status = String(invoice.status || '').toLowerCase();
|
|
|
|
|
if (status === 'paid') {
|
|
|
|
|
await loadInvoices(); await loadVms();
|
|
|
|
|
if (invoicePurpose(invoice) !== 'provision') {
|
|
|
|
|
stopInvoicePoll(key); toast('账单支付成功,服务期限已延长。', 'success'); return;
|
|
|
|
|
}
|
|
|
|
|
if (provisionFinished(invoice)) {
|
|
|
|
|
const { status: provisionStatus } = provisionStatusInfo(invoice);
|
|
|
|
|
stopInvoicePoll(key);
|
|
|
|
|
if (['completed', 'succeeded', 'active'].includes(provisionStatus)) toast('实例已创建完成。', 'success');
|
|
|
|
|
else if (provisionStatus === 'refunded') toast('实例创建失败,款项已退回账户余额。', 'error');
|
|
|
|
|
else toast('实例开通未完成,请在账单中查看任务状态。', 'error');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (['void'].includes(result.invoice?.status)) {
|
|
|
|
|
if (['void', 'expired'].includes(status)) {
|
|
|
|
|
stopInvoicePoll(key); toast('账单已失效,到账金额会保留在账户余额中。', 'error'); await loadInvoices(); return;
|
|
|
|
|
}
|
|
|
|
|
if (!invoiceCanPay(result.invoice)) {
|
|
|
|
|
stopInvoicePoll(key); toast('续费宽限期已经结束,到账金额会保留在账户余额中。', 'error'); await loadInvoices(); return;
|
|
|
|
|
if (status === 'refunded') {
|
|
|
|
|
stopInvoicePoll(key); toast('实例创建失败,款项已退回账户余额。', 'error'); await loadInvoices(); return;
|
|
|
|
|
}
|
|
|
|
|
if (!invoiceCanPay(invoice) && status !== 'paid') {
|
|
|
|
|
const message = invoicePurpose(invoice) === 'provision'
|
|
|
|
|
? '开通账单已超过支付截止时间。' : '续费宽限期已经结束,到账金额会保留在账户余额中。';
|
|
|
|
|
stopInvoicePoll(key); toast(message, 'error'); await loadInvoices(); return;
|
|
|
|
|
}
|
|
|
|
|
} catch {}
|
|
|
|
|
if (Date.now() - started < 10 * 60 * 1000) {
|
|
|
|
|
@ -507,15 +532,21 @@ function renderOnlinePayment(container, payment) {
|
|
|
|
|
scheduleInvoicePoll(payment.invoice_id);
|
|
|
|
|
}
|
|
|
|
|
async function payInvoiceBalance(invoice, row) {
|
|
|
|
|
if (!invoiceCanPay(invoice)) return toast('续费宽限期已经结束,账单不可支付。', 'error');
|
|
|
|
|
if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision'
|
|
|
|
|
? '开通账单已失效,不能支付。' : '续费宽限期已经结束,账单不可支付。', 'error');
|
|
|
|
|
if (state.mutationBusy || !confirm(`确认使用账户余额支付账单 ${invoice.invoice_no},金额 ¥${invoice.amount}?`)) return;
|
|
|
|
|
state.mutationBusy = true;
|
|
|
|
|
row.querySelectorAll('button').forEach(button => { button.disabled = true; });
|
|
|
|
|
try {
|
|
|
|
|
await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, {
|
|
|
|
|
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, {
|
|
|
|
|
method: 'POST', body: { idempotency_key: crypto.randomUUID() },
|
|
|
|
|
});
|
|
|
|
|
toast('账单已支付,服务期限已延长。', 'success'); await loadInvoices(); await loadVms();
|
|
|
|
|
const paid = result.invoice || invoice;
|
|
|
|
|
if (invoicePurpose(paid) === 'provision') {
|
|
|
|
|
toast('账单已支付,实例已进入创建队列。', 'success'); await loadInvoices(); await loadVms(); scheduleInvoicePoll(paid.id || invoice.id);
|
|
|
|
|
} else {
|
|
|
|
|
toast('账单已支付,服务期限已延长。', 'success'); await loadInvoices(); await loadVms();
|
|
|
|
|
}
|
|
|
|
|
} catch (error) { toast(error.message, 'error'); }
|
|
|
|
|
finally {
|
|
|
|
|
state.mutationBusy = false;
|
|
|
|
|
@ -523,7 +554,8 @@ async function payInvoiceBalance(invoice, row) {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
async function createInvoicePayment(invoice, method, row) {
|
|
|
|
|
if (!invoiceCanPay(invoice)) return toast('续费宽限期已经结束,不能再生成支付订单。', 'error');
|
|
|
|
|
if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision'
|
|
|
|
|
? '开通账单已失效,不能再生成支付订单。' : '续费宽限期已经结束,不能再生成支付订单。', 'error');
|
|
|
|
|
if (state.mutationBusy || !confirm(`确认通过“${method.name}”生成 ¥${invoice.amount} 的支付订单?`)) return;
|
|
|
|
|
state.mutationBusy = true;
|
|
|
|
|
row.querySelectorAll('button').forEach(button => { button.disabled = true; });
|
|
|
|
|
@ -547,54 +579,99 @@ async function createInvoicePayment(invoice, method, row) {
|
|
|
|
|
}
|
|
|
|
|
finally { state.mutationBusy = false; row.querySelectorAll('button').forEach(button => { button.disabled = false; }); }
|
|
|
|
|
}
|
|
|
|
|
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 () => {
|
|
|
|
|
let progress = detail.querySelector('.cloud-order-progress');
|
|
|
|
|
if (!progress) { progress = makeElement('p', 'cloud-order-progress muted'); detail.append(progress); }
|
|
|
|
|
try {
|
|
|
|
|
const job = await api(`/api/v1/jobs/${encodeURIComponent(data.jobId)}`);
|
|
|
|
|
progress.className = `cloud-order-progress ${job.error ? 'form-error' : 'muted'}`;
|
|
|
|
|
progress.textContent = job.error || job.phase || `任务状态:${job.status}`;
|
|
|
|
|
if (['completed', 'succeeded', 'failed', 'cancelled', 'needs_attention', 'uncertain'].includes(String(job.status || '').toLowerCase())) {
|
|
|
|
|
await loadInvoices(); await loadVms();
|
|
|
|
|
}
|
|
|
|
|
} catch (error) { toast(error.message, 'error'); }
|
|
|
|
|
}));
|
|
|
|
|
if (data.instanceId || data.instanceUuid) actions.append(actionButton('查看实例', async () => {
|
|
|
|
|
await loadVms();
|
|
|
|
|
const vm = state.vms.find(item => item.api_id === data.instanceId || item.uuid === data.instanceUuid);
|
|
|
|
|
if (vm) openVmDetail(vm.uuid); else toast('实例尚未出现在列表,请稍后刷新。');
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
function renderInvoices() {
|
|
|
|
|
const container = byId('invoices-list'); container.replaceChildren();
|
|
|
|
|
if (!state.invoices.length) return container.append(makeElement('p', 'muted', '暂无续费账单。账单会在实例到期前 7 天自动生成。'));
|
|
|
|
|
if (!state.invoices.length) return container.append(makeElement('p', 'muted', '暂无账单。部署实例后会先生成开通账单;续费账单会在实例到期前 7 天自动生成。'));
|
|
|
|
|
for (const invoice of state.invoices) {
|
|
|
|
|
const row = makeElement('article', 'cloud-order cloud-invoice');
|
|
|
|
|
const detail = makeElement('div', 'cloud-order-detail');
|
|
|
|
|
const purpose = invoicePurpose(invoice);
|
|
|
|
|
const provision = purpose === 'provision';
|
|
|
|
|
const invoiceStatus = String(invoice.status || '').toLowerCase();
|
|
|
|
|
const deletionAt = invoiceDeletionTimestamp(invoice);
|
|
|
|
|
const paymentDeadline = invoicePaymentDeadlineTimestamp(invoice);
|
|
|
|
|
const payable = invoiceCanPay(invoice);
|
|
|
|
|
detail.append(makeElement('strong', '', `${invoice.instance_name || '实例'} · ¥${invoice.amount}`),
|
|
|
|
|
makeElement('p', 'muted', `账单 ${invoice.invoice_no} · 到期时间 ${formatOrderDate(invoice.due_at)}`),
|
|
|
|
|
makeElement('p', 'cloud-order-message', `支付后增加 ${invoice.validity_days} 天服务期 · 新账期流量 ${formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))}`));
|
|
|
|
|
if (['open', 'overdue'].includes(invoice.status) && deletionAt !== null) {
|
|
|
|
|
const subject = provision
|
|
|
|
|
? invoice.requested_name || invoice.instance_name || '待创建实例'
|
|
|
|
|
: invoice.instance_name || '实例';
|
|
|
|
|
const dueText = provision
|
|
|
|
|
? `支付截止 ${formatServiceDate(paymentDeadline ?? invoice.due_at)}`
|
|
|
|
|
: `实例到期 ${formatOrderDate(invoice.due_at)}`;
|
|
|
|
|
detail.append(makeElement('strong', '', `${subject} · ¥${invoice.amount}`),
|
|
|
|
|
makeElement('p', 'muted', `${provision ? '开通账单' : '续费账单'} ${invoice.invoice_no} · ${dueText}`),
|
|
|
|
|
makeElement('p', 'cloud-order-message', provision
|
|
|
|
|
? `${invoice.plan_name || '云服务器套餐'} · 支付后创建 ${invoice.validity_days} 天服务期 · 每期流量 ${formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))}`
|
|
|
|
|
: `支付后增加 ${invoice.validity_days} 天服务期 · 新账期流量 ${formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))}`));
|
|
|
|
|
if (provision) {
|
|
|
|
|
const task = provisionInvoiceData(invoice);
|
|
|
|
|
if (task.phase || task.error) {
|
|
|
|
|
const progress = makeElement('p', `cloud-order-progress ${task.error ? 'form-error' : 'muted'}`, task.error || task.phase);
|
|
|
|
|
detail.append(progress);
|
|
|
|
|
} else if (invoiceStatus === 'paid' && !provisionFinished(invoice)) {
|
|
|
|
|
detail.append(makeElement('p', 'cloud-order-message', '账单已支付,实例正在等待后台创建;关闭页面不会取消任务。'));
|
|
|
|
|
} else if (['void', 'expired'].includes(invoiceStatus)) {
|
|
|
|
|
detail.append(makeElement('p', 'cloud-order-message', '开通账单已失效,不会创建实例。'));
|
|
|
|
|
}
|
|
|
|
|
} else if (['open', 'overdue'].includes(invoiceStatus) && deletionAt !== null) {
|
|
|
|
|
detail.append(makeElement('p', 'cloud-order-message', payable
|
|
|
|
|
? `实例到期后会立即停用网络;若在 ${formatServiceDate(deletionAt)} 前仍未支付,实例及系统盘将被永久删除。续费成功后网络会自动恢复。`
|
|
|
|
|
: '三天续费宽限期已经结束,账单不可支付;实例及系统盘已进入永久删除流程。'));
|
|
|
|
|
} else if (['delete_failed', 'purge_stop_failed', 'purge_failed'].includes(invoice.status)) {
|
|
|
|
|
} else if (['delete_failed', 'purge_stop_failed', 'purge_failed'].includes(invoiceStatus)) {
|
|
|
|
|
detail.append(makeElement('p', 'cloud-order-message', '三天续费宽限期已经结束,账单不可支付;自动清理尚未完成,请联系管理员处理。'));
|
|
|
|
|
} else if (['expired', 'deleting', 'purge_pending', 'purge_stopping', 'purge_deleting'].includes(invoice.status)) {
|
|
|
|
|
} else if (['expired', 'deleting', 'purge_pending', 'purge_stopping', 'purge_deleting'].includes(invoiceStatus)) {
|
|
|
|
|
detail.append(makeElement('p', 'cloud-order-message', '三天续费宽限期已经结束,账单不可支付;实例及系统盘已进入永久删除流程。'));
|
|
|
|
|
}
|
|
|
|
|
const actions = makeElement('div', 'cloud-order-actions');
|
|
|
|
|
const [label, className] = invoiceStatusInfo(invoice.status);
|
|
|
|
|
const [label, className] = invoiceStatusInfo(invoiceStatus);
|
|
|
|
|
actions.append(makeElement('span', `state-pill ${className}`, label));
|
|
|
|
|
if (payable) {
|
|
|
|
|
actions.append(actionButton('余额支付', () => payInvoiceBalance(invoice, row)));
|
|
|
|
|
for (const method of state.invoicePaymentMethods) actions.append(actionButton(method.name, () => createInvoicePayment(invoice, method, row)));
|
|
|
|
|
} else if (['open', 'overdue'].includes(invoice.status)) {
|
|
|
|
|
} else if (['open', 'overdue'].includes(invoiceStatus)) {
|
|
|
|
|
stopInvoicePoll(invoice.id);
|
|
|
|
|
clearInvoicePaymentKeys(invoice.id);
|
|
|
|
|
actions.append(makeElement('span', 'muted', '已超过支付截止时间'));
|
|
|
|
|
} else if (invoice.status === 'paid') {
|
|
|
|
|
stopInvoicePoll(invoice.id);
|
|
|
|
|
} else if (invoiceStatus === 'paid') {
|
|
|
|
|
clearInvoicePaymentKeys(invoice.id);
|
|
|
|
|
if (!provision) stopInvoicePoll(invoice.id);
|
|
|
|
|
actions.append(makeElement('span', 'muted', invoice.paid_at ? `支付于 ${formatOrderDate(invoice.paid_at)}` : '已结清'));
|
|
|
|
|
} else if (invoice.status === 'void') {
|
|
|
|
|
stopInvoicePoll(invoice.id);
|
|
|
|
|
clearInvoicePaymentKeys(invoice.id);
|
|
|
|
|
} else if (['expired', 'deleting', 'delete_failed', 'purge_pending', 'purge_stopping', 'purge_stop_failed', 'purge_deleting', 'purge_failed'].includes(invoice.status)) {
|
|
|
|
|
} else if (['refunded', 'void', 'expired', 'deleting', 'delete_failed', 'purge_pending', 'purge_stopping', 'purge_stop_failed', 'purge_deleting', 'purge_failed'].includes(invoiceStatus)) {
|
|
|
|
|
stopInvoicePoll(invoice.id);
|
|
|
|
|
clearInvoicePaymentKeys(invoice.id);
|
|
|
|
|
}
|
|
|
|
|
if (provision && ['paid', 'refunded'].includes(invoiceStatus)) appendProvisionInvoiceActions(invoice, detail, actions);
|
|
|
|
|
if (provision && invoiceStatus === 'paid' && !provisionFinished(invoice)
|
|
|
|
|
&& !state.invoicePollTimers.has(String(invoice.id))) scheduleInvoicePoll(invoice.id);
|
|
|
|
|
row.append(detail, actions); container.append(row);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
async function loadInvoices() {
|
|
|
|
|
try {
|
|
|
|
|
const payload = await api('/api/v1/invoices');
|
|
|
|
|
state.invoices = Array.isArray(payload.invoices) ? payload.invoices : [];
|
|
|
|
|
state.invoices = (Array.isArray(payload.invoices) ? payload.invoices : []).slice()
|
|
|
|
|
.sort((left, right) => Number(right.created_at || 0) - Number(left.created_at || 0)
|
|
|
|
|
|| Number(right.id || 0) - Number(left.id || 0));
|
|
|
|
|
state.invoicePaymentMethods = Array.isArray(payload.payment_methods) ? payload.payment_methods : [];
|
|
|
|
|
text('invoices-balance', `¥${payload.balance ?? '—'}`); renderInvoices(); showError('cloud-page-error', '');
|
|
|
|
|
} catch (error) { showError('cloud-page-error', error.message); }
|
|
|
|
|
@ -1358,7 +1435,7 @@ function renderTemplateCatalog(inputId) {
|
|
|
|
|
}
|
|
|
|
|
container.replaceChildren(...cards);
|
|
|
|
|
}
|
|
|
|
|
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', async event => { event.preventDefault(); const view = button.dataset.view; button.closest('details')?.removeAttribute('open'); try { if (view === 'create') await openCreate(); else { showView(view); if (view === 'keys') await loadKeys(); if (view === 'orders') await loadOrders(); if (view === 'invoices') await loadInvoices(); } } catch (error) { showError('cloud-page-error', error.message); } }));
|
|
|
|
|
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', async event => { event.preventDefault(); const view = button.dataset.view; button.closest('details')?.removeAttribute('open'); try { if (view === 'create') await openCreate(); else { showView(view); if (view === 'keys') await loadKeys(); if (view === 'invoices') await loadInvoices(); } } catch (error) { showError('cloud-page-error', error.message); } }));
|
|
|
|
|
byId('refresh-button').addEventListener('click', loadVms);
|
|
|
|
|
byId('vm-detail-refresh-button').addEventListener('click', async () => {
|
|
|
|
|
await loadVms();
|
|
|
|
|
@ -1367,7 +1444,7 @@ byId('vm-detail-refresh-button').addEventListener('click', async () => {
|
|
|
|
|
byId('create-button').addEventListener('click', openCreate); byId('create-back').addEventListener('click', () => showView('list')); byId('vm-detail-back-button').addEventListener('click', () => { state.selectedVmId = null; showView('list'); }); byId('ssh-keys-back-button').addEventListener('click', () => showView('list'));
|
|
|
|
|
for (const id of ['reinstall-back', 'reinstall-cancel', 'rescue-back']) byId(id).addEventListener('click', () => { if (!state.mutationBusy) { const vm = selectedVm(); if (vm) openVmDetail(vm.uuid); else showView('list'); } });
|
|
|
|
|
byId('search-input').addEventListener('input', () => renderVMs()); byId('state-filter').addEventListener('change', () => renderVMs()); byId('vm-plan').addEventListener('change', () => { void loadPlanResources(); }); byId('create-form').querySelectorAll('[name="source"]').forEach(radio => radio.addEventListener('change', updateSource));
|
|
|
|
|
byId('create-form').addEventListener('submit', buy); byId('reinstall-form').addEventListener('submit', reinstall); byId('rescue-form').addEventListener('submit', event => { event.preventDefault(); void rescueAction('load'); }); byId('rescue-force-start').addEventListener('click', () => rescueAction('force-start')); byId('rescue-exit').addEventListener('click', () => rescueAction('exit')); byId('orders-refresh').addEventListener('click', loadOrders); byId('invoices-refresh').addEventListener('click', loadInvoices);
|
|
|
|
|
byId('create-form').addEventListener('submit', buy); byId('reinstall-form').addEventListener('submit', reinstall); byId('rescue-form').addEventListener('submit', event => { event.preventDefault(); void rescueAction('load'); }); byId('rescue-force-start').addEventListener('click', () => rescueAction('force-start')); byId('rescue-exit').addEventListener('click', () => rescueAction('exit')); byId('invoices-refresh').addEventListener('click', loadInvoices);
|
|
|
|
|
for (const id of ['vm-open-ssh-keys', 'reinstall-open-ssh-keys']) byId(id).addEventListener('click', async () => { showView('keys'); try { await loadKeys(); } catch (error) { toast(error.message, 'error'); } });
|
|
|
|
|
byId('ssh-key-form').addEventListener('submit', async event => { event.preventDefault(); const button = byId('ssh-key-save-button'); button.disabled = true; showError('ssh-key-form-error', ''); try { await api('/api/v1/ssh-keys', { method: 'POST', body: { name: byId('ssh-key-name').value.trim(), public_key: byId('ssh-key-public-key').value.trim() } }); byId('ssh-key-form').reset(); await loadKeys(); toast('公钥已保存。', 'success'); } catch (error) { showError('ssh-key-form-error', error.message); } finally { button.disabled = false; } });
|
|
|
|
|
byId('ssh-key-file').addEventListener('change', async event => { const file = event.target.files?.[0]; if (!file) return; if (file.size > 16384) return showError('ssh-key-form-error', '公钥文件超过 16 KiB 限制。'); const content = await file.text(); if (/PRIVATE KEY/.test(content)) return showError('ssh-key-form-error', '不能导入私钥,只能导入 .pub 公钥。'); byId('ssh-key-public-key').value = content.trim(); });
|
|
|
|
|
@ -1394,6 +1471,6 @@ byId('vm-metrics-range').addEventListener('change', () => { state.metricsRange =
|
|
|
|
|
});
|
|
|
|
|
byId('console-modal').querySelector('[data-close-modal]').addEventListener('click', closeConsole); byId('console-cad').addEventListener('click', () => state.rfb?.sendCtrlAltDel()); byId('console-fullscreen').addEventListener('click', () => { byId('console-stage').requestFullscreen?.().catch(error => toast(error.message, 'error')); }); byId('console-password-form').addEventListener('submit', event => { event.preventDefault(); state.rfb?.sendCredentials({ password: byId('console-password').value }); byId('console-password').value = ''; byId('console-password-form').hidden = true; }); window.addEventListener('keydown', event => { if (event.key === 'Escape') closeConsole(); });
|
|
|
|
|
document.addEventListener('visibilitychange', () => { if (document.hidden) { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); stopInvoicePoll(); } else { void loadVms(); if (state.view === 'detail') setVmDetailTab(state.detailTab); if (state.view === 'invoices') void loadInvoices(); } }); window.addEventListener('pagehide', () => { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); stopInvoicePoll(); closeConsole(); state.resourceController?.abort(); }); byId('logout-button').addEventListener('click', () => { clearCredential(); closeConsole(); location.assign('/user/logout'); });
|
|
|
|
|
async function initialize() { const initialHash = location.hash; try { const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return; } state.csrfToken = session.csrf_token || ''; if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); state.userId = String(session.user_id || ''); if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。'); state.username = session.username || session.user_name || session.email || session.user?.email || '用户'; state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1; 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; } showView('list'); updateSource(); await loadVms(); await routeHash(initialHash); setInterval(() => { if (!document.hidden) { void loadVms(); if (trafficDailyViewVisible()) void loadVmTrafficDaily(); if (state.view === 'orders') void loadOrders(); if (state.view === 'invoices' && state.invoicePollTimers.size === 0) void loadInvoices(); } }, 15000); } catch (error) { showError('cloud-page-error', error.message); } }
|
|
|
|
|
async function initialize() { const initialHash = location.hash; try { const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return; } state.csrfToken = session.csrf_token || ''; if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); state.userId = String(session.user_id || ''); if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。'); state.username = session.username || session.user_name || session.email || session.user?.email || '用户'; state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1; 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; } showView('list'); updateSource(); await loadVms(); await routeHash(initialHash); setInterval(() => { if (!document.hidden) { void loadVms(); if (trafficDailyViewVisible()) void loadVmTrafficDaily(); if (state.view === 'invoices' && state.invoicePollTimers.size === 0) void loadInvoices(); } }, 15000); } catch (error) { showError('cloud-page-error', error.message); } }
|
|
|
|
|
window.addEventListener('hashchange', () => { if (state.csrfToken) void routeHash(); });
|
|
|
|
|
void initialize();
|
|
|
|
|
|