|
|
|
|
@ -1,11 +1,10 @@
|
|
|
|
|
// 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: [], regions: [], sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionHostId: '', invoices: [], invoicePage: 1, invoicePagination: { page: 1, per_page: 10, total: 0, total_pages: 1, has_previous: false, has_next: false, from: 0, to: 0 }, invoiceLoading: false, invoiceLoadPromise: null, invoicePaymentMethods: [], invoiceBalance: '0.00', selectedInvoice: null, selectedInvoicePaymentMethod: '', invoiceJobProgress: new Map(), 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: '' }, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false };
|
|
|
|
|
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], regions: [], sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionHostId: '', 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: '' }, 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 CLOUD_PATHS = Object.freeze({
|
|
|
|
|
instances: '/user/cloud/instances',
|
|
|
|
|
deploy: '/user/cloud/deploy',
|
|
|
|
|
@ -13,7 +12,6 @@ const CLOUD_PATHS = Object.freeze({
|
|
|
|
|
invoices: '/user/cloud/invoices',
|
|
|
|
|
});
|
|
|
|
|
const vmPagePath = (id, child = '') => `${CLOUD_PATHS.instances}/${encodeURIComponent(String(id))}${child ? `/${child}` : ''}`;
|
|
|
|
|
const invoicePagePath = (id) => `${CLOUD_PATHS.invoices}/${encodeURIComponent(String(id))}`;
|
|
|
|
|
const navigate = (path) => location.assign(path);
|
|
|
|
|
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?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : [];
|
|
|
|
|
@ -627,31 +625,6 @@ function clearPendingProvisionInvoiceKey() {
|
|
|
|
|
state.provisionFingerprint = '';
|
|
|
|
|
try { sessionStorage.removeItem(provisionInvoiceStorageKey()); } catch {}
|
|
|
|
|
}
|
|
|
|
|
function invoicePaymentStorageKey(invoiceId, methodId) {
|
|
|
|
|
return `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:${methodId}`;
|
|
|
|
|
}
|
|
|
|
|
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 = crypto.randomUUID();
|
|
|
|
|
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 {}
|
|
|
|
|
}
|
|
|
|
|
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; }
|
|
|
|
|
@ -702,573 +675,6 @@ async function buy(event) {
|
|
|
|
|
updateCreateAvailability();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
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 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 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.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 ['succeeded', 'failed', 'refunded', 'needs_attention'].includes(status);
|
|
|
|
|
}
|
|
|
|
|
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 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 validPaymentUrl(value) {
|
|
|
|
|
try {
|
|
|
|
|
const url = new URL(String(value || ''));
|
|
|
|
|
return ['https:', 'weixin:', 'alipays:', 'alipayqr:'].includes(url.protocol) ? url.href : '';
|
|
|
|
|
}
|
|
|
|
|
catch { return ''; }
|
|
|
|
|
}
|
|
|
|
|
function appendPaymentQr(container, value) {
|
|
|
|
|
if (!value || typeof window.QRCode !== 'function') return false;
|
|
|
|
|
const qr = makeElement('div', 'cloud-payment-qr');
|
|
|
|
|
try {
|
|
|
|
|
const levels = window.QRCode.CorrectLevel || { L: 1, M: 0 };
|
|
|
|
|
new window.QRCode(qr, {
|
|
|
|
|
text: String(value), width: 196, height: 196,
|
|
|
|
|
correctLevel: String(value).length > 1200 ? levels.L : levels.M,
|
|
|
|
|
});
|
|
|
|
|
if (!qr.children.length) return false;
|
|
|
|
|
container.append(qr);
|
|
|
|
|
return true;
|
|
|
|
|
} catch { return false; }
|
|
|
|
|
}
|
|
|
|
|
function stopInvoicePoll(invoiceId = null) {
|
|
|
|
|
if (invoiceId !== null) {
|
|
|
|
|
const key = String(invoiceId);
|
|
|
|
|
const timer = state.invoicePollTimers.get(key);
|
|
|
|
|
if (timer !== undefined) clearTimeout(timer);
|
|
|
|
|
state.invoicePollTimers.delete(key);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
for (const timer of state.invoicePollTimers.values()) clearTimeout(timer);
|
|
|
|
|
state.invoicePollTimers.clear();
|
|
|
|
|
}
|
|
|
|
|
async function refreshInvoiceView(invoiceId) {
|
|
|
|
|
if (state.view === 'invoice-detail') return loadInvoiceDetail(invoiceId);
|
|
|
|
|
if (state.view === 'invoices') return loadInvoices();
|
|
|
|
|
}
|
|
|
|
|
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 applyInvoiceStatus(update) {
|
|
|
|
|
if (!update?.id) return null;
|
|
|
|
|
const key = String(update.id);
|
|
|
|
|
if (state.view === 'invoice-detail' && String(state.selectedInvoice?.id || '') === key) {
|
|
|
|
|
const invoice = mergeInvoiceStatus(state.selectedInvoice, update);
|
|
|
|
|
renderInvoiceDetail(invoice, {
|
|
|
|
|
balance: state.invoiceBalance,
|
|
|
|
|
payment_methods: state.invoicePaymentMethods,
|
|
|
|
|
});
|
|
|
|
|
return invoice;
|
|
|
|
|
}
|
|
|
|
|
if (state.view === 'invoices') {
|
|
|
|
|
const index = state.invoices.findIndex(invoice => String(invoice.id) === key);
|
|
|
|
|
if (index >= 0) {
|
|
|
|
|
state.invoices[index] = mergeInvoiceStatus(state.invoices[index], update);
|
|
|
|
|
renderInvoices();
|
|
|
|
|
return state.invoices[index];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return update;
|
|
|
|
|
}
|
|
|
|
|
function scheduleInvoicePoll(invoiceId) {
|
|
|
|
|
const key = String(invoiceId);
|
|
|
|
|
stopInvoicePoll(key);
|
|
|
|
|
const started = Date.now();
|
|
|
|
|
const poll = async () => {
|
|
|
|
|
if (!['invoices', 'invoice-detail'].includes(state.view)) return stopInvoicePoll(key);
|
|
|
|
|
try {
|
|
|
|
|
const result = await api(`/api/v1/invoices/${encodeURIComponent(key)}/status`);
|
|
|
|
|
const invoice = applyInvoiceStatus(result.invoice || {}) || {};
|
|
|
|
|
const status = String(invoice.status || '').toLowerCase();
|
|
|
|
|
if (status === 'paid') {
|
|
|
|
|
if (invoicePurpose(invoice) !== 'provision') {
|
|
|
|
|
const message = invoicePurpose(invoice) === 'renewal'
|
|
|
|
|
? '账单支付成功,服务期限已延长。' : '账单支付成功。';
|
|
|
|
|
stopInvoicePoll(key); toast(message, 'success'); return;
|
|
|
|
|
}
|
|
|
|
|
if (provisionFinished(invoice)) {
|
|
|
|
|
const { status: provisionStatus } = provisionStatusInfo(invoice);
|
|
|
|
|
stopInvoicePoll(key);
|
|
|
|
|
if (provisionStatus === 'succeeded') toast('实例已创建完成。', 'success');
|
|
|
|
|
else if (provisionStatus === 'refunded') toast('实例创建失败,款项已退回账户余额。', 'error');
|
|
|
|
|
else toast('实例开通未完成,请在账单详情查看任务状态。', 'error');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (['void', 'expired'].includes(status)) {
|
|
|
|
|
stopInvoicePoll(key); toast('账单已失效,到账金额会保留在账户余额中。', 'error'); return;
|
|
|
|
|
}
|
|
|
|
|
if (status === 'refunded') {
|
|
|
|
|
stopInvoicePoll(key); toast('实例创建失败,款项已退回账户余额。', 'error'); return;
|
|
|
|
|
}
|
|
|
|
|
if (!invoiceCanPay(invoice) && status !== 'paid') {
|
|
|
|
|
const message = invoicePurpose(invoice) === 'provision'
|
|
|
|
|
? '开通账单已超过支付截止时间。' : invoicePurpose(invoice) === 'renewal'
|
|
|
|
|
? '续费宽限期已经结束,到账金额会保留在账户余额中。' : '账单已超过支付截止时间。';
|
|
|
|
|
stopInvoicePoll(key); toast(message, 'error'); return;
|
|
|
|
|
}
|
|
|
|
|
} catch {}
|
|
|
|
|
if (Date.now() - started < 10 * 60 * 1000) {
|
|
|
|
|
state.invoicePollTimers.set(key, setTimeout(poll, 3000));
|
|
|
|
|
} else {
|
|
|
|
|
stopInvoicePoll(key);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
state.invoicePollTimers.set(key, setTimeout(poll, 3000));
|
|
|
|
|
}
|
|
|
|
|
function renderOnlinePayment(container, payment) {
|
|
|
|
|
let box = container.querySelector('.cloud-payment-instructions');
|
|
|
|
|
if (!box) { box = makeElement('div', 'cloud-payment-instructions'); container.append(box); }
|
|
|
|
|
box.replaceChildren();
|
|
|
|
|
if (payment.payment_kind === 'usdt') {
|
|
|
|
|
box.append(makeElement('strong', '', `请支付 ${payment.actual_amount} USDT(TRC20)`),
|
|
|
|
|
makeElement('code', '', payment.receive_address || '收款地址不可用'),
|
|
|
|
|
makeElement('small', '', `支付订单有效至 ${formatOrderDate(payment.expires_at)};链上确认后自动结清账单。`));
|
|
|
|
|
appendPaymentQr(box, payment.receive_address || '');
|
|
|
|
|
const copy = actionButton('复制收款地址', async () => {
|
|
|
|
|
try { await copyText(payment.receive_address || ''); toast('USDT 收款地址已复制。', 'success'); }
|
|
|
|
|
catch (error) { toast(error.message, 'error'); }
|
|
|
|
|
});
|
|
|
|
|
box.append(copy);
|
|
|
|
|
} else {
|
|
|
|
|
const url = validPaymentUrl(payment.payment_value);
|
|
|
|
|
box.append(makeElement('strong', '', `${payment.label || '在线支付'}订单已生成`));
|
|
|
|
|
appendPaymentQr(box, payment.payment_value || '');
|
|
|
|
|
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', '', payment.payment_value || '支付信息暂不可用'));
|
|
|
|
|
const copy = actionButton('复制支付信息', async () => {
|
|
|
|
|
try { await copyText(payment.payment_value || ''); toast('支付信息已复制。', 'success'); }
|
|
|
|
|
catch (error) { toast(error.message, 'error'); }
|
|
|
|
|
});
|
|
|
|
|
box.append(copy);
|
|
|
|
|
}
|
|
|
|
|
box.append(makeElement('small', '', '完成付款后本页会自动核对账单状态。请勿同时使用多个渠道重复付款。'));
|
|
|
|
|
}
|
|
|
|
|
scheduleInvoicePoll(payment.invoice_id);
|
|
|
|
|
}
|
|
|
|
|
async function payInvoiceBalance(invoice, container, refresh = () => refreshInvoiceView(invoice.id)) {
|
|
|
|
|
if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision'
|
|
|
|
|
? '开通账单已失效,不能支付。' : invoicePurpose(invoice) === 'renewal'
|
|
|
|
|
? '续费宽限期已经结束,账单不可支付。' : '账单已失效,不能支付。', 'error');
|
|
|
|
|
if (state.mutationBusy || !confirm(`确认使用账户余额支付账单 #${invoice.id},金额 ${formatUsd(invoice.amount)}?`)) 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: crypto.randomUUID() },
|
|
|
|
|
});
|
|
|
|
|
const paid = result.invoice || invoice;
|
|
|
|
|
if (invoicePurpose(paid) === 'provision') {
|
|
|
|
|
toast('账单已支付,实例已进入创建队列。', 'success'); await refresh(paid.id || invoice.id); scheduleInvoicePoll(paid.id || invoice.id);
|
|
|
|
|
} else if (invoicePurpose(paid) === 'renewal') {
|
|
|
|
|
toast('账单已支付,服务期限已延长。', 'success'); await refresh(paid.id || invoice.id);
|
|
|
|
|
} else {
|
|
|
|
|
toast('账单已支付。', 'success'); await refresh(paid.id || invoice.id);
|
|
|
|
|
}
|
|
|
|
|
} catch (error) { toast(error.message, 'error'); }
|
|
|
|
|
finally {
|
|
|
|
|
state.mutationBusy = false;
|
|
|
|
|
container.querySelectorAll('button').forEach(button => { button.disabled = false; });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
async function createInvoicePayment(invoice, method, container, paymentResult = container) {
|
|
|
|
|
if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision'
|
|
|
|
|
? '开通账单已失效,不能再生成支付订单。' : invoicePurpose(invoice) === 'renewal'
|
|
|
|
|
? '续费宽限期已经结束,不能再生成支付订单。' : '账单已失效,不能再生成支付订单。', 'error');
|
|
|
|
|
if (state.mutationBusy || !confirm(`确认通过“${method.name}”支付账单 #${invoice.id},金额 ${formatUsd(invoice.amount)}?`)) 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 },
|
|
|
|
|
});
|
|
|
|
|
renderOnlinePayment(paymentResult, result.payment || {});
|
|
|
|
|
} catch (error) {
|
|
|
|
|
// A transport failure may hide a successfully created provider order, so
|
|
|
|
|
// retain the key and recover it on the next click. Only a definite 4xx
|
|
|
|
|
// rejection proves no ambiguous 5xx/network outcome needs reconciling.
|
|
|
|
|
const status = Number(error.status || 0);
|
|
|
|
|
const ambiguousHttpFailure = [408, 425, 429].includes(status);
|
|
|
|
|
if (status >= 400 && status < 500 && !ambiguousHttpFailure
|
|
|
|
|
&& !String(error.message).includes('正在创建')) {
|
|
|
|
|
clearInvoicePaymentKey(invoice.id, method.id);
|
|
|
|
|
}
|
|
|
|
|
toast(error.message, 'error');
|
|
|
|
|
}
|
|
|
|
|
finally { state.mutationBusy = false; container.querySelectorAll('button').forEach(button => { button.disabled = false; }); }
|
|
|
|
|
}
|
|
|
|
|
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 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}` : '', '等待创建');
|
|
|
|
|
}
|
|
|
|
|
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)}`);
|
|
|
|
|
const jobStatus = firstText(job.status).toLowerCase();
|
|
|
|
|
const failed = ['failed', 'refunded', 'needs_attention'].includes(jobStatus) || Boolean(job.error);
|
|
|
|
|
progress.className = `cloud-order-progress ${failed ? 'form-error' : 'muted'}`;
|
|
|
|
|
progress.textContent = invoiceProgressText(job);
|
|
|
|
|
state.invoiceJobProgress.set(String(invoice.id), { message: progress.textContent, failed });
|
|
|
|
|
if (!['succeeded', 'failed', 'refunded', 'needs_attention'].includes(jobStatus)) {
|
|
|
|
|
scheduleInvoicePoll(invoice.id);
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
progress.className = 'cloud-order-progress form-error'; progress.textContent = error.message;
|
|
|
|
|
state.invoiceJobProgress.set(String(invoice.id), { message: error.message, failed: true });
|
|
|
|
|
}
|
|
|
|
|
}));
|
|
|
|
|
if (data.instanceId) {
|
|
|
|
|
const link = makeElement('a', 'row-button', '查看实例');
|
|
|
|
|
link.href = vmPagePath(data.instanceId); actions.append(link);
|
|
|
|
|
} else if (data.instanceUuid) actions.append(actionButton('查看实例', async () => {
|
|
|
|
|
await loadVms();
|
|
|
|
|
const vm = state.vms.find(item => item.uuid === data.instanceUuid);
|
|
|
|
|
if (vm) navigate(vmPagePath(vm.api_id)); else toast('实例尚未出现在列表,请稍后刷新。');
|
|
|
|
|
}));
|
|
|
|
|
}
|
|
|
|
|
function renderInvoices() {
|
|
|
|
|
const container = byId('invoices-list'); container.replaceChildren();
|
|
|
|
|
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 cloud-invoice-list-row');
|
|
|
|
|
const detail = makeElement('div', 'cloud-order-detail cloud-invoice-list-copy');
|
|
|
|
|
detail.append(makeElement('strong', '', invoiceTitle(invoice)),
|
|
|
|
|
makeElement('p', 'muted', `账单 #${invoice.id} · ${formatOrderDate(invoice.created_at)}`));
|
|
|
|
|
|
|
|
|
|
const actions = makeElement('div', 'cloud-order-actions cloud-invoice-list-actions');
|
|
|
|
|
const invoiceStatus = String(invoice.status || '').toLowerCase();
|
|
|
|
|
const [label, className] = invoiceStatusInfo(invoiceStatus);
|
|
|
|
|
actions.append(makeElement('span', `state-pill ${className}`, label));
|
|
|
|
|
if (invoicePurpose(invoice) === 'provision' && ['paid', 'refunded'].includes(invoiceStatus)) {
|
|
|
|
|
const { status, display } = provisionStatusInfo(invoice);
|
|
|
|
|
if (status) actions.append(makeElement('span', `state-pill ${display[1]}`, display[0]));
|
|
|
|
|
}
|
|
|
|
|
const link = makeElement('a', 'row-button', '账单详情');
|
|
|
|
|
link.href = invoicePagePath(invoice.id); actions.append(link);
|
|
|
|
|
|
|
|
|
|
const amount = makeElement('div', 'cloud-invoice-list-amount');
|
|
|
|
|
amount.append(makeElement('span', '', '金额'), makeElement('strong', '', formatUsd(invoice.amount)));
|
|
|
|
|
row.append(detail, actions, amount); container.append(row);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
function renderInvoicePagination() {
|
|
|
|
|
const navigation = byId('invoices-pagination');
|
|
|
|
|
if (!navigation) return;
|
|
|
|
|
const pagination = state.invoicePagination || {};
|
|
|
|
|
const page = Math.max(1, Number(pagination.page) || 1);
|
|
|
|
|
const totalPages = Math.max(1, Number(pagination.total_pages) || 1);
|
|
|
|
|
const total = Math.max(0, Number(pagination.total) || 0);
|
|
|
|
|
navigation.hidden = total === 0;
|
|
|
|
|
navigation.setAttribute('aria-busy', String(state.invoiceLoading));
|
|
|
|
|
text('invoices-page-label', `第 ${page} / ${totalPages} 页 · 共 ${total} 条`);
|
|
|
|
|
const previous = byId('invoices-previous');
|
|
|
|
|
const next = byId('invoices-next');
|
|
|
|
|
if (previous) previous.disabled = state.invoiceLoading || !pagination.has_previous;
|
|
|
|
|
if (next) next.disabled = state.invoiceLoading || !pagination.has_next;
|
|
|
|
|
const refresh = byId('invoices-refresh');
|
|
|
|
|
if (refresh) {
|
|
|
|
|
refresh.disabled = state.invoiceLoading;
|
|
|
|
|
refresh.setAttribute('aria-busy', String(state.invoiceLoading));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
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 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));
|
|
|
|
|
});
|
|
|
|
|
if (byId('invoice-payment-submit')) byId('invoice-payment-submit').disabled = !state.selectedInvoicePaymentMethod;
|
|
|
|
|
}
|
|
|
|
|
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);
|
|
|
|
|
panel.hidden = true; container.replaceChildren(); result.replaceChildren();
|
|
|
|
|
state.selectedInvoicePaymentMethod = ''; return;
|
|
|
|
|
}
|
|
|
|
|
const choices = [{ 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 available = new Set(choices.map(choice => String(choice.id)));
|
|
|
|
|
if (!available.has(state.selectedInvoicePaymentMethod)) state.selectedInvoicePaymentMethod = 'balance';
|
|
|
|
|
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;
|
|
|
|
|
});
|
|
|
|
|
// Returning from an external payment app triggers a visibility refresh. Keep
|
|
|
|
|
// the already-created provider instructions while this same bill is payable;
|
|
|
|
|
// settlement or expiry clears them through the non-payable branch above.
|
|
|
|
|
container.replaceChildren(...cards); panel.hidden = false;
|
|
|
|
|
const submit = byId('invoice-payment-submit');
|
|
|
|
|
submit.disabled = !state.selectedInvoicePaymentMethod;
|
|
|
|
|
submit.onclick = async () => {
|
|
|
|
|
showError('invoice-payment-error', '');
|
|
|
|
|
const choice = choices.find(item => String(item.id) === state.selectedInvoicePaymentMethod);
|
|
|
|
|
if (!choice) return showError('invoice-payment-error', '请选择支付方式。');
|
|
|
|
|
if (choice.kind === 'balance') await payInvoiceBalance(invoice, panel, loadInvoiceDetail);
|
|
|
|
|
else await createInvoicePayment(invoice, choice, panel, result);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
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' && !provisionFinished(invoice)
|
|
|
|
|
&& !state.invoicePollTimers.has(String(invoice.id))) scheduleInvoicePoll(invoice.id);
|
|
|
|
|
else if (terminal) {
|
|
|
|
|
state.invoiceJobProgress.delete(String(invoice.id)); stopInvoicePoll(invoice.id);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
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');
|
|
|
|
|
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('支付方式', String(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);
|
|
|
|
|
}
|
|
|
|
|
async function loadInvoiceDetail(invoiceId = document.body.dataset.invoiceId) {
|
|
|
|
|
const id = String(invoiceId || '');
|
|
|
|
|
if (!/^\d+$/.test(id)) throw new Error('账单编号无效。');
|
|
|
|
|
try {
|
|
|
|
|
const payload = await api(`/api/v1/invoices/${encodeURIComponent(id)}`);
|
|
|
|
|
if (!payload?.invoice) throw new Error('账单信息不完整。');
|
|
|
|
|
const csrfToken = String(payload.csrf_token || '');
|
|
|
|
|
const userId = String(payload.user_id || '');
|
|
|
|
|
if (!/^[a-f0-9]{64}$/.test(csrfToken) || !/^\d+$/.test(userId)) {
|
|
|
|
|
throw new Error('账单会话信息不完整,请重新登录。');
|
|
|
|
|
}
|
|
|
|
|
state.csrfToken = csrfToken;
|
|
|
|
|
state.userId = userId;
|
|
|
|
|
state.username = payload.username || state.username || '用户';
|
|
|
|
|
state.admin = payload.admin === true || Number(payload.admin) === 1;
|
|
|
|
|
state.invoiceBalance = String(payload.balance ?? state.invoiceBalance);
|
|
|
|
|
if (byId('current-username')) text('current-username', state.username);
|
|
|
|
|
for (const adminLinkId of ['cloud-admin-link', 'cloud-admin-menu-link']) {
|
|
|
|
|
const link = byId(adminLinkId);
|
|
|
|
|
if (link) link.hidden = !state.admin;
|
|
|
|
|
}
|
|
|
|
|
if (state.selectedInvoice && String(state.selectedInvoice.id) !== String(payload.invoice.id)) {
|
|
|
|
|
state.selectedInvoicePaymentMethod = '';
|
|
|
|
|
byId('invoice-payment-result')?.replaceChildren();
|
|
|
|
|
}
|
|
|
|
|
state.invoicePaymentMethods = Array.isArray(payload.payment_methods) ? payload.payment_methods : [];
|
|
|
|
|
renderInvoiceDetail(payload.invoice, payload); showError('cloud-page-error', ''); return payload.invoice;
|
|
|
|
|
} catch (error) { showError('cloud-page-error', error.message); throw error; }
|
|
|
|
|
}
|
|
|
|
|
async function loadInvoices(page = state.invoicePage) {
|
|
|
|
|
if (state.invoiceLoading) return state.invoiceLoadPromise;
|
|
|
|
|
const requestedPage = Math.max(1, Math.trunc(Number(page) || state.invoicePage || 1));
|
|
|
|
|
state.invoiceLoading = true;
|
|
|
|
|
renderInvoicePagination();
|
|
|
|
|
const request = (async () => {
|
|
|
|
|
try {
|
|
|
|
|
const payload = await api(`/api/v1/invoices?page=${encodeURIComponent(requestedPage)}`);
|
|
|
|
|
const pagination = payload?.pagination && typeof payload.pagination === 'object'
|
|
|
|
|
? payload.pagination : {};
|
|
|
|
|
const actualPage = Math.max(1, Math.trunc(Number(pagination.page) || requestedPage));
|
|
|
|
|
const totalPages = Math.max(1, Math.trunc(Number(pagination.total_pages) || 1));
|
|
|
|
|
const total = Math.max(0, Math.trunc(Number(pagination.total) || 0));
|
|
|
|
|
state.invoicePage = actualPage;
|
|
|
|
|
state.invoicePagination = {
|
|
|
|
|
page: actualPage,
|
|
|
|
|
per_page: Math.max(1, Math.trunc(Number(pagination.per_page) || 10)),
|
|
|
|
|
total,
|
|
|
|
|
total_pages: totalPages,
|
|
|
|
|
has_previous: pagination.has_previous === true || actualPage > 1,
|
|
|
|
|
has_next: pagination.has_next === true || actualPage < totalPages,
|
|
|
|
|
from: Math.max(0, Math.trunc(Number(pagination.from) || 0)),
|
|
|
|
|
to: Math.max(0, Math.trunc(Number(pagination.to) || 0)),
|
|
|
|
|
};
|
|
|
|
|
state.invoices = Array.isArray(payload.invoices) ? payload.invoices : [];
|
|
|
|
|
text('invoices-balance', formatUsd(payload.balance));
|
|
|
|
|
renderInvoices();
|
|
|
|
|
showError('cloud-page-error', '');
|
|
|
|
|
return payload;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
showError('cloud-page-error', error.message);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
})();
|
|
|
|
|
state.invoiceLoadPromise = request;
|
|
|
|
|
try {
|
|
|
|
|
return await request;
|
|
|
|
|
} finally {
|
|
|
|
|
state.invoiceLoading = false;
|
|
|
|
|
state.invoiceLoadPromise = null;
|
|
|
|
|
renderInvoicePagination();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
async function openReinstall(vm, bootstrap = null) {
|
|
|
|
|
state.view = 'reinstall'; text('reinstall-subtitle', `${vm.name} · 保留原有公网网络参数,重新创建系统盘。`); text('reinstall-public-ip', vmIp(vm)); byId('reinstall-confirm-name').value = ''; byId('reinstall-root-password').value = ''; byId('reinstall-template').value = ''; showError('reinstall-error', ''); byId('reinstall-progress').hidden = true; byId('reinstall-result').hidden = true; byId('reinstall-fields').hidden = false;
|
|
|
|
|
if (!vm?.can_operate) {
|
|
|
|
|
@ -2210,7 +1616,6 @@ function bindPageCleanup() {
|
|
|
|
|
clearCredential();
|
|
|
|
|
stopVmMetrics();
|
|
|
|
|
stopVmTrafficDaily();
|
|
|
|
|
stopInvoicePoll();
|
|
|
|
|
closeConsole();
|
|
|
|
|
state.resourceController?.abort();
|
|
|
|
|
});
|
|
|
|
|
@ -2219,11 +1624,11 @@ function bindPageCleanup() {
|
|
|
|
|
export {
|
|
|
|
|
CLOUD_PATHS, VM_DETAIL_TABS, api, bindPageCleanup, buy, byId, clearCredential,
|
|
|
|
|
clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential,
|
|
|
|
|
drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession, invoicePagePath,
|
|
|
|
|
loadGlobalTemplates, loadInvoiceDetail, loadInvoices, loadKeys, loadVmMetrics, loadVmTrafficDaily,
|
|
|
|
|
drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession,
|
|
|
|
|
loadGlobalTemplates, loadKeys, loadVmMetrics, loadVmTrafficDaily,
|
|
|
|
|
loadVm, loadVmStatus, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall,
|
|
|
|
|
readBootstrap, renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm,
|
|
|
|
|
scheduleInvoicePoll, setVmDetailTab, showError, state, stopInvoicePoll, stopVmMetrics,
|
|
|
|
|
setVmDetailTab, showError, state, stopVmMetrics,
|
|
|
|
|
stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp,
|
|
|
|
|
vmPagePath,
|
|
|
|
|
};
|
|
|
|
|
|