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/invoices.js

260 lines
11 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.

// The first ten records are server-rendered and embedded below the markup.
// This module deliberately avoids the all-feature cloud runtime and session
// endpoint, leaving only pagination and conditional refresh work to JS.
const byId = id => document.getElementById(id);
const state = {
invoices: [], page: 1,
pagination: { page: 1, per_page: 10, total: 0, total_pages: 1,
has_previous: false, has_next: false, from: 0, to: 0 },
loading: false, pollTimer: null,
};
function showError(message = '') {
const target = byId('cloud-page-error');
if (!target) return;
target.textContent = message;
target.hidden = !message;
}
async function api(path) {
const response = await fetch(path, { method: 'GET', headers: { Accept: 'application/json' },
credentials: 'same-origin', cache: 'no-store' });
let payload;
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;
throw new Error(String(detail || payload?.message || payload?.msg || payload?.error
|| `请求失败 (${response.status})`));
}
return payload;
}
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 firstText(...values) {
for (const value of values) {
if (value !== null && value !== undefined && String(value).trim() !== '') return String(value).trim();
}
return '';
}
function formatUsd(value) {
const amount = Number(value);
if (!Number.isFinite(amount) || amount < 0) return '$—';
return `$${amount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}
function formatDate(value) {
const raw = Number(value);
const timestamp = Number.isFinite(raw) && raw > 0
? (raw < 1e12 ? raw * 1000 : raw) : Date.parse(String(value || ''));
const date = new Date(timestamp);
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) {
return firstText(invoice?.type_label, invoice?.title,
{ recharge: '余额充值', provision: '实例开通', renewal: '实例续费' }[invoicePurpose(invoice)], '账单');
}
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 fulfillmentStatus(invoice) {
return firstText(invoice?.fulfillment_status, invoice?.job_status, invoice?.order_status).toLowerCase();
}
function fulfillmentStatusInfo(invoice) {
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'],
};
const status = fulfillmentStatus(invoice);
return { status, display: values[status] || [status, 'warning'] };
}
function invoiceNeedsPolling(invoice) {
const status = String(invoice?.status || '').toLowerCase();
if (['open', 'overdue'].includes(status)) return true;
if (status !== 'paid' || invoicePurpose(invoice) !== 'provision') return false;
return !['completed', 'succeeded', 'active', 'failed', 'refunded', 'needs_attention']
.includes(fulfillmentStatus(invoice));
}
function renderInvoices() {
const container = byId('invoices-list');
if (!container) return;
container.replaceChildren();
if (!state.invoices.length) {
container.append(makeElement('p', 'muted',
'暂无账单。部署实例后会先生成开通账单;续费账单会在实例到期前 7 天自动生成。'));
return;
}
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} · ${formatDate(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 } = fulfillmentStatusInfo(invoice);
if (status) actions.append(makeElement('span', `state-pill ${display[1]}`, display[0]));
}
const link = makeElement('a', 'row-button', '账单详情');
link.href = `/user/cloud/invoices/${encodeURIComponent(String(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 normalizePagination(value, fallbackPage) {
const source = value && typeof value === 'object' ? value : {};
const page = Math.max(1, Math.trunc(Number(source.page) || fallbackPage));
const totalPages = Math.max(1, Math.trunc(Number(source.total_pages) || 1));
const total = Math.max(0, Math.trunc(Number(source.total) || 0));
return { page, per_page: Math.max(1, Math.trunc(Number(source.per_page) || 10)), total,
total_pages: totalPages, has_previous: source.has_previous === true || page > 1,
has_next: source.has_next === true || page < totalPages,
from: Math.max(0, Math.trunc(Number(source.from) || 0)),
to: Math.max(0, Math.trunc(Number(source.to) || 0)) };
}
function renderPagination() {
const navigation = byId('invoices-pagination');
if (!navigation) return;
const page = Math.max(1, Number(state.pagination.page) || 1);
const totalPages = Math.max(1, Number(state.pagination.total_pages) || 1);
const total = Math.max(0, Number(state.pagination.total) || 0);
navigation.hidden = total === 0;
navigation.setAttribute('aria-busy', String(state.loading));
if (byId('invoices-page-label')) byId('invoices-page-label').textContent = `第 ${page} / ${totalPages} 页 · 共 ${total} 条`;
if (byId('invoices-previous')) byId('invoices-previous').disabled = state.loading || !state.pagination.has_previous;
if (byId('invoices-next')) byId('invoices-next').disabled = state.loading || !state.pagination.has_next;
if (byId('invoices-refresh')) {
byId('invoices-refresh').disabled = state.loading;
byId('invoices-refresh').setAttribute('aria-busy', String(state.loading));
}
}
function updatePageUrl(page) {
const url = new URL(location.href);
if (page > 1) url.searchParams.set('page', String(page));
else url.searchParams.delete('page');
history.replaceState(history.state, '', `${url.pathname}${url.search}${url.hash}`);
}
function stopPolling() {
if (state.pollTimer !== null) window.clearTimeout(state.pollTimer);
state.pollTimer = null;
}
function startPolling() {
stopPolling();
if (document.hidden || !state.invoices.some(invoiceNeedsPolling)) return;
state.pollTimer = window.setTimeout(async () => {
state.pollTimer = null;
await loadInvoices(state.page, false);
}, 15000);
}
async function loadInvoices(page = state.page, updateUrl = true) {
if (state.loading) return;
const requestedPage = Math.max(1, Math.trunc(Number(page) || state.page || 1));
state.loading = true;
stopPolling();
renderPagination();
try {
const payload = await api(`/api/v1/invoices?page=${encodeURIComponent(requestedPage)}`);
state.pagination = normalizePagination(payload?.pagination, requestedPage);
state.page = state.pagination.page;
state.invoices = Array.isArray(payload?.invoices) ? payload.invoices : [];
if (byId('invoices-balance')) byId('invoices-balance').textContent = formatUsd(payload?.balance);
renderInvoices();
if (updateUrl) updatePageUrl(state.page);
showError();
} catch (error) {
showError(error?.message || '账单加载失败,请稍后重试。');
} finally {
state.loading = false;
renderPagination();
startPolling();
}
}
function hydrate() {
const source = byId('invoices-bootstrap');
if (!source) return false;
try {
const payload = JSON.parse(source.textContent || '{}');
if (!Array.isArray(payload?.invoices)) return false;
state.invoices = payload.invoices;
state.pagination = normalizePagination(payload.pagination, 1);
state.page = state.pagination.page;
renderPagination();
return true;
} catch { return false; }
}
export async function initialize() {
const hydrated = hydrate();
byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout'));
byId('invoices-refresh')?.addEventListener('click', () => { void loadInvoices(state.page, false); });
byId('invoices-previous')?.addEventListener('click', () => {
if (!state.loading && state.pagination.has_previous) void loadInvoices(Math.max(1, state.page - 1));
});
byId('invoices-next')?.addEventListener('click', () => {
if (!state.loading && state.pagination.has_next) void loadInvoices(state.page + 1);
});
window.addEventListener('pagehide', stopPolling);
window.addEventListener('pageshow', event => {
if (!event.persisted) return;
if (state.invoices.some(invoiceNeedsPolling)) void loadInvoices(state.page, false);
else startPolling();
});
document.addEventListener('visibilitychange', () => {
if (document.hidden) stopPolling();
else if (state.invoices.some(invoiceNeedsPolling)) void loadInvoices(state.page, false);
});
if (!hydrated) await loadInvoices(1, false);
else startPolling();
}