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/admin-billing.js

792 lines
37 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.

const root = document.querySelector('[data-admin-billing]');
const byId = id => document.getElementById(id);
const FINANCIAL_OPTIONS = [
['', '全部财务状态'], ['open', '待支付'], ['overdue', '已逾期'],
['paid', '已支付'], ['refunded', '已退款'], ['expired', '已失效'], ['void', '已作废'],
];
const FULFILLMENT_OPTIONS = [
['', '全部履约状态'], ['awaiting_payment', '等待支付'], ['queued', '已排队'],
['pending', '待处理'], ['running', '开通中'], ['uncertain', '待人工核查'],
['succeeded', '已开通'], ['failed', '开通失败'], ['expired', '已失效'],
['refunded', '已退款'], ['cancelled', '已取消'],
];
const ORDER_OPTIONS = FULFILLMENT_OPTIONS;
const PAYMENT_OPTIONS = [
['', '全部支付状态'], ['creating', '创建中'], ['pending', '待支付'],
['paid_invoice', '已入账单'], ['credited_balance', '已入余额'], ['failed', '支付失败'],
];
const PURPOSE_OPTIONS = [
['', '全部账单类型'], ['provision', '实例开通'], ['renewal', '实例续费'], ['recharge', '余额充值'],
];
const PROVIDER_OPTIONS = [
['', '全部支付渠道'], ['balance', '账户余额'], ['usdt', 'USDT-TRC20'],
['yipay_alipay', '易支付 · 支付宝'], ['yipay_wxpay', '易支付 · 微信'], ['paytaro', 'Paytaro'],
];
const VIEWS = {
invoices: {
title: '全部账单', description: '按财务状态与履约状态核对每一笔账单。',
queryPlaceholder: '账单 / 订单 / 套餐 / 用户 ID',
endpoint: '/api/v1/admin/billing/invoices', caption: '管理员账单列表',
primary: { key: 'financial_status', label: '财务状态', options: FINANCIAL_OPTIONS },
secondary: { key: 'fulfillment_status', label: '履约状态', options: FULFILLMENT_OPTIONS },
category: { key: 'purpose', label: '账单类型', options: PURPOSE_OPTIONS },
reference: { key: 'payment_method', label: '支付渠道', options: PROVIDER_OPTIONS },
columns: ['账单', '用户', '项目', '金额', '财务状态', '履约状态', '支付渠道', '时间', '详情'],
},
orders: {
title: '开通任务', description: '跟踪支付后的实例开通队列、重试与异常结果。',
queryPlaceholder: '任务 / 实例 / 套餐 / 用户 ID',
endpoint: '/api/v1/admin/billing/orders', caption: '管理员实例开通任务列表',
primary: { key: 'status', label: '履约状态', options: ORDER_OPTIONS },
secondary: { key: 'financial_status', label: '财务状态', options: FINANCIAL_OPTIONS },
category: null, reference: null,
columns: ['任务', '用户', '套餐 / 宿主机', '金额', '财务状态', '履约状态', '实例 / 引擎任务', '更新 / 异常', '账单'],
},
payments: {
title: '支付流水', description: '核对支付尝试、入账去向与所属账单的财务状态。',
queryPlaceholder: '流水 / 账单 / 用户 ID',
endpoint: '/api/v1/admin/billing/payments', caption: '管理员支付流水列表',
primary: { key: 'status', label: '支付状态', options: PAYMENT_OPTIONS }, secondary: null,
category: { key: 'provider', label: '支付渠道', options: PROVIDER_OPTIONS },
reference: { key: 'invoice_id', label: '账单 ID', placeholder: '全部账单' },
columns: ['支付流水', '用户', '支付渠道', '金额', '支付状态', '账单财务状态', '用途', '时间', '账单'],
},
};
const state = {
view: 'invoices', page: 1, perPage: 30, items: [], loading: false,
pagination: { page: 1, per_page: 30, total: 0, total_pages: 1, has_previous: false, has_next: false },
request: null, detailRequest: null, requestNumber: 0, detailInvoiceId: '', detailOpener: null,
filtersLocked: false,
};
function element(tag, className = '', text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = String(text);
return node;
}
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)) return '—';
const sign = amount < 0 ? '-$' : '$';
return sign + Math.abs(amount).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function formatInteger(value) {
const number = Number(value);
return Number.isFinite(number) ? Math.trunc(number).toLocaleString('zh-CN') : '—';
}
function formatDate(value) {
if (value === null || value === undefined || value === '') return '—';
const numeric = Number(value);
if (Number.isFinite(numeric) && numeric <= 0) return '—';
const timestamp = Number.isFinite(numeric)
? (numeric < 1e12 ? numeric * 1000 : numeric) : Date.parse(String(value));
const date = new Date(timestamp);
return Number.isFinite(date.getTime())
? date.toLocaleString('zh-CN', { hour12: false }) : '—';
}
function formatBytes(value) {
const bytes = Number(value);
if (!Number.isFinite(bytes) || bytes < 0) return '—';
if (bytes === 0) return '不限';
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
const index = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
return `${(bytes / (1024 ** index)).toLocaleString('zh-CN', { maximumFractionDigits: 2 })} ${units[index]}`;
}
function purposeLabel(value) {
return ({ provision: '实例开通', renewal: '实例续费', recharge: '余额充值' })[String(value || '').toLowerCase()]
|| firstText(value, '未分类');
}
function providerLabel(value) {
const provider = String(value || '').toLowerCase();
return ({ balance: '账户余额', usdt: 'USDT-TRC20', yipay_alipay: '易支付 · 支付宝',
yipay_wxpay: '易支付 · 微信', paytaro: 'Paytaro' })[provider] || firstText(value, '未记录');
}
function statusInfo(kind, value) {
const status = String(value || '').toLowerCase();
if (!status && kind === 'fulfillment') return ['不适用', 'neutral'];
const financial = {
open: ['待支付', 'warning'], overdue: ['已逾期', 'danger'], paid: ['已支付', 'success'],
refunded: ['已退款', 'info'], expired: ['已失效', 'neutral'], void: ['已作废', 'neutral'],
};
const fulfillment = {
awaiting_payment: ['等待支付', 'warning'], queued: ['已排队', 'warning'],
pending: ['待处理', 'warning'], running: ['开通中', 'info'], provisioning: ['开通中', 'info'],
uncertain: ['待人工核查', 'danger'], succeeded: ['已开通', 'success'], completed: ['已开通', 'success'],
active: ['已开通', 'success'], failed: ['开通失败', 'danger'], expired: ['已失效', 'neutral'],
refunded: ['已退款', 'info'], cancelled: ['已取消', 'neutral'],
};
const payment = {
creating: ['创建中', 'info'], pending: ['待支付', 'warning'], paid_invoice: ['已入账单', 'success'],
credited_balance: ['已入余额', 'success'], failed: ['支付失败', 'danger'], expired: ['已失效', 'neutral'],
};
const table = kind === 'financial' ? financial : kind === 'payment' ? payment : fulfillment;
return table[status] || [status || '未记录', 'neutral'];
}
function statusBadge(kind, value) {
const [label, tone] = statusInfo(kind, value);
const badgeTone = {
success: 'bg-success-subtle text-success-emphasis',
warning: 'bg-warning-subtle text-warning-emphasis',
danger: 'bg-danger-subtle text-danger-emphasis',
info: 'bg-info-subtle text-info-emphasis',
neutral: 'bg-light text-dark',
}[tone] || 'bg-light text-dark';
return element('span', `badge rounded-pill fs-12 px-2 py-1 ${badgeTone}`, label);
}
function stack(primary, secondary = '') {
const node = element('span', 'admin-checkout-user text-break');
node.append(element('strong', '', firstText(primary, '—')));
if (firstText(secondary)) node.append(element('span', '', secondary));
return node;
}
function accountCell(item) {
const name = firstText(item.user_name, item.user_email, `用户 #${item.user_id || '—'}`);
const details = [item.user_name ? item.user_email : '', item.user_id ? `ID ${item.user_id}` : ''].filter(Boolean).join(' · ');
return stack(name, details);
}
function detailButton(invoiceId, label = '查看账单') {
if (!invoiceId) return element('span', 'text-muted', '—');
const button = element('button', 'btn btn-primary btn-sm', label);
button.type = 'button';
button.dataset.invoiceId = String(invoiceId);
button.setAttribute('aria-label', `查看账单 ${invoiceId} 详情`);
return button;
}
function invoiceCells(item) {
return [
stack(`#${item.id}`, purposeLabel(item.purpose)), accountCell(item),
stack(firstText(item.subject_name, item.plan_name, '账单项目'), item.plan_id ? `套餐 #${item.plan_id}` : ''),
element('span', 'admin-mono', formatUsd(item.amount)), statusBadge('financial', item.financial_status),
statusBadge('fulfillment', item.fulfillment_status), providerLabel(item.payment_method),
stack(formatDate(item.created_at), item.due_at ? `到期 ${formatDate(item.due_at)}` : ''), detailButton(item.id, '账单详情'),
];
}
function orderCells(item) {
const taskDetails = [item.job_id ? `引擎 #${item.job_id}` : '', Number(item.attempts) > 0 ? `尝试 ${item.attempts}` : ''].filter(Boolean).join(' · ');
return [
stack(`#${item.id}`, taskDetails), accountCell(item),
stack(firstText(item.plan_name, item.plan_id ? `套餐 #${item.plan_id}` : '套餐未记录'), item.host_id ? `宿主机 #${item.host_id}` : ''),
element('span', 'admin-mono', formatUsd(item.amount)), statusBadge('financial', item.financial_status),
statusBadge('fulfillment', firstText(item.fulfillment_status, item.status, item.job_status)),
stack(item.instance_id ? `实例 #${item.instance_id}` : '实例 —', item.job_id ? `任务 #${item.job_id} · ${statusInfo('fulfillment', item.job_status)[0]}` : '引擎任务 —'),
stack(formatDate(firstText(item.updated_at, item.created_at)), firstText(item.error)), detailButton(item.invoice_id),
];
}
function paymentCells(item) {
return [
stack(`#${item.id}`, item.invoice_id ? `账单 #${item.invoice_id}` : '未关联账单'), accountCell(item),
providerLabel(item.provider), element('span', 'admin-mono', formatUsd(item.amount)),
statusBadge('payment', item.payment_status), statusBadge('financial', item.invoice_financial_status),
purposeLabel(item.purpose), stack(formatDate(item.created_at), item.updated_at ? `更新 ${formatDate(item.updated_at)}` : ''),
detailButton(item.invoice_id),
];
}
function setNotice(message, tone = '') {
const notice = byId('billing-notice');
if (!notice) return;
notice.textContent = message;
notice.className = `admin-config-status ${tone === 'error' ? 'is-error' : tone === 'success' ? 'is-success' : 'is-loading'}`;
notice.setAttribute('role', tone === 'error' ? 'alert' : 'status');
}
function fillOptions(select, options, selected = '') {
select.replaceChildren();
for (const [value, label] of options) {
const option = element('option', '', label);
option.value = value;
option.selected = String(value) === String(selected || '');
select.append(option);
}
}
function configureFilter(kind, definition) {
const field = byId(`billing-${kind}-field`);
const control = byId(`billing-${kind}`);
const label = byId(`billing-${kind}-label`);
field.hidden = definition === null;
control.disabled = definition === null;
control.dataset.queryKey = definition?.key || '';
if (!definition) { control.value = ''; return; }
label.textContent = definition.label;
if (control instanceof HTMLSelectElement) fillOptions(control, definition.options);
}
function configureReference(definition) {
const field = byId('billing-reference-field');
const select = byId('billing-reference-select');
const input = byId('billing-reference-input');
field.hidden = definition === null;
select.hidden = true;
select.disabled = true;
select.dataset.queryKey = '';
select.value = '';
input.hidden = true;
input.disabled = true;
input.dataset.queryKey = '';
input.value = '';
if (!definition) return;
byId('billing-reference-label').textContent = definition.label;
if (Array.isArray(definition.options)) {
fillOptions(select, definition.options);
select.hidden = false;
select.disabled = false;
select.dataset.queryKey = definition.key;
field.htmlFor = select.id;
return;
}
input.hidden = false;
input.disabled = false;
input.dataset.queryKey = definition.key;
input.placeholder = definition.placeholder || '';
field.htmlFor = input.id;
}
function configureView() {
const config = VIEWS[state.view];
byId('billing-view-heading').textContent = config.title;
byId('billing-view-description').textContent = config.description;
byId('billing-query').placeholder = config.queryPlaceholder;
byId('billing-table-caption').textContent = config.caption;
document.querySelectorAll('[data-billing-view]').forEach(link => {
const active = link.dataset.billingView === state.view;
link.classList.toggle('active', active);
if (active) link.setAttribute('aria-current', 'page');
else link.removeAttribute('aria-current');
});
configureFilter('status-primary', config.primary);
configureFilter('status-secondary', config.secondary);
configureFilter('category', config.category);
configureReference(config.reference);
renderTableHead();
}
function renderTableHead() {
const row = element('tr');
for (const label of VIEWS[state.view].columns) {
const heading = element('th', '', label);
heading.scope = 'col';
row.append(heading);
}
byId('billing-table-head').replaceChildren(row);
}
function renderState(title, message, retry = false) {
const cell = element('td', 'text-center text-muted py-4');
cell.colSpan = VIEWS[state.view].columns.length;
const content = element('div', 'd-grid justify-content-center gap-2');
if (state.loading) {
const loader = element('span', 'spinner-border spinner-border-sm text-primary mx-auto');
loader.setAttribute('aria-hidden', 'true');
content.append(loader);
}
content.append(element('strong', '', title));
if (message) content.append(element('span', '', message));
if (retry) {
const button = element('button', 'btn btn-light', '重试');
button.type = 'button';
button.addEventListener('click', () => { void loadList(); });
content.append(button);
}
cell.append(content);
const row = element('tr');
row.append(cell);
byId('billing-table-body').replaceChildren(row);
}
function renderRows() {
const body = byId('billing-table-body');
body.replaceChildren();
if (!state.items.length) {
renderState('暂无匹配记录', '请调整筛选条件,或稍后刷新当前视图。');
return;
}
const renderer = state.view === 'orders' ? orderCells : state.view === 'payments' ? paymentCells : invoiceCells;
for (const item of state.items) {
const row = element('tr');
const values = renderer(item);
values.forEach((value, index) => {
const cell = element('td');
cell.dataset.label = VIEWS[state.view].columns[index];
if (value instanceof Node) cell.append(value);
else cell.textContent = firstText(value, '—');
row.append(cell);
});
body.append(row);
}
}
function normalizePagination(value) {
const source = value && typeof value === 'object' ? value : {};
const page = Math.max(1, Math.trunc(Number(source.page) || state.page));
const totalPages = Math.max(1, Math.trunc(Number(source.total_pages) || 1));
return {
page, per_page: Math.max(1, Math.trunc(Number(source.per_page) || state.perPage)),
total: Math.max(0, Math.trunc(Number(source.total) || 0)), total_pages: totalPages,
has_previous: source.has_previous === true || page > 1,
has_next: source.has_next === true || page < totalPages,
};
}
function countStatuses(counts, statuses) {
if (!counts || typeof counts !== 'object') return 0;
return statuses.reduce((total, key) => total + Math.max(0, Number(counts[key]) || 0), 0);
}
function resetSummary(busy) {
const invoiceView = state.view === 'invoices';
const orderView = state.view === 'orders';
byId('billing-summary-amount-label').textContent = invoiceView
? '账单面额' : orderView ? '任务关联金额' : '支付尝试金额';
byId('billing-summary-focus-label').textContent = invoiceView
? '待收款' : orderView ? '处理中 / 待核查' : '处理中';
byId('billing-summary-result-label').textContent = invoiceView
? '已支付' : orderView ? '已开通 / 失败' : '入账去向';
for (const id of ['billing-summary-total', 'billing-summary-amount',
'billing-summary-focus', 'billing-summary-result']) byId(id).textContent = '—';
byId('billing-summary').setAttribute('aria-busy', String(busy));
}
function renderSummary(summary = {}) {
const total = Number(summary.total_records);
byId('billing-summary-total').textContent = Number.isFinite(total) ? formatInteger(total) : formatInteger(state.pagination.total);
byId('billing-summary-amount-label').textContent = state.view === 'payments'
? '支付尝试金额' : state.view === 'orders' ? '任务关联金额' : '账单面额';
byId('billing-summary-amount').textContent = formatUsd(summary.total_amount);
if (state.view === 'invoices') {
byId('billing-summary-focus-label').textContent = '待收款';
byId('billing-summary-focus').textContent = `${formatInteger(summary.outstanding_count)} 笔 · ${formatUsd(summary.outstanding_amount)}`;
byId('billing-summary-result-label').textContent = '已支付';
byId('billing-summary-result').textContent = `${formatInteger(summary.paid_count)} 笔 · ${formatUsd(summary.paid_amount)}`;
} else if (state.view === 'orders') {
const counts = summary.status_counts || {};
byId('billing-summary-focus-label').textContent = '处理中 / 待核查';
byId('billing-summary-focus').textContent = `${formatInteger(countStatuses(counts, ['awaiting_payment', 'queued', 'pending', 'running', 'uncertain']))} 笔`;
byId('billing-summary-result-label').textContent = '已开通 / 失败';
byId('billing-summary-result').textContent = `${formatInteger(countStatuses(counts, ['succeeded']))} / ${formatInteger(countStatuses(counts, ['failed']))}`;
} else {
const counts = summary.status_counts || {};
byId('billing-summary-focus-label').textContent = '处理中';
byId('billing-summary-focus').textContent = `${formatInteger(countStatuses(counts, ['creating', 'pending']))} 笔`;
byId('billing-summary-result-label').textContent = '入账去向';
byId('billing-summary-result').textContent = `账单 ${formatUsd(summary.paid_invoice_amount)} · 余额 ${formatUsd(summary.credited_balance_amount)}`;
}
byId('billing-summary').setAttribute('aria-busy', 'false');
}
function renderPagination() {
const pagination = byId('billing-pagination');
pagination.hidden = state.pagination.total === 0;
pagination.setAttribute('aria-busy', String(state.loading));
byId('billing-page-label').textContent = `第 ${state.pagination.page} / ${state.pagination.total_pages} 页 · 共 ${state.pagination.total} 条`;
byId('billing-previous').disabled = state.loading || !state.pagination.has_previous;
byId('billing-next').disabled = state.loading || !state.pagination.has_next;
}
function lockFilters(locked) {
if (locked === state.filtersLocked) return;
const controls = byId('billing-filter-form').querySelectorAll('input, select, button');
for (const control of controls) {
if (locked) {
control.dataset.billingDisabledBeforeLoad = control.disabled ? '1' : '0';
control.disabled = true;
} else {
control.disabled = control.dataset.billingDisabledBeforeLoad === '1';
delete control.dataset.billingDisabledBeforeLoad;
}
}
state.filtersLocked = locked;
}
function setLoading(loading) {
state.loading = loading;
lockFilters(loading);
root.setAttribute('aria-busy', String(loading));
byId('billing-table').setAttribute('aria-busy', String(loading));
for (const id of ['billing-refresh', 'billing-apply', 'billing-reset']) byId(id).disabled = loading;
document.querySelectorAll('[data-billing-view]').forEach(link => {
link.setAttribute('aria-disabled', String(loading));
});
renderPagination();
}
function dateToUnix(value, endOfDay = false) {
if (!value) return '';
const date = new Date(`${value}T${endOfDay ? '23:59:59' : '00:00:00'}`);
return Number.isFinite(date.getTime()) ? String(Math.floor(date.getTime() / 1000)) : '';
}
function unixToDate(value) {
const number = Number(value);
if (!Number.isFinite(number) || number <= 0) return '';
const date = new Date(number * (number < 1e12 ? 1000 : 1));
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function activeFilters() {
const result = {};
const common = {
q: byId('billing-query').value.trim(), user_id: byId('billing-user-id').value.trim(),
created_from: dateToUnix(byId('billing-created-from').value),
created_to: dateToUnix(byId('billing-created-to').value, true),
};
Object.assign(result, common);
for (const id of ['billing-status-primary', 'billing-status-secondary', 'billing-category', 'billing-reference-select', 'billing-reference-input']) {
const control = byId(id);
if (!control.disabled && control.dataset.queryKey) result[control.dataset.queryKey] = control.value.trim();
}
return result;
}
function requestUrl(filters = activeFilters()) {
const params = new URLSearchParams({ page: String(state.page), per_page: String(state.perPage) });
for (const [key, value] of Object.entries(filters)) if (value) params.set(key, value);
return `${VIEWS[state.view].endpoint}?${params.toString()}`;
}
function writeUrl(push = false, filters = activeFilters()) {
const params = new URLSearchParams();
if (state.view !== 'invoices') params.set('view', state.view);
if (state.page > 1) params.set('page', String(state.page));
if (state.perPage !== 30) params.set('per_page', String(state.perPage));
for (const [key, value] of Object.entries(filters)) if (value) params.set(key, value);
const target = `${location.pathname}${params.size ? `?${params.toString()}` : ''}`;
history[push ? 'pushState' : 'replaceState']({ billing: true }, '', target);
}
function loadFiltersFromUrl() {
const params = new URLSearchParams(location.search);
byId('billing-query').value = params.get('q') || '';
byId('billing-user-id').value = params.get('user_id') || '';
byId('billing-created-from').value = unixToDate(params.get('created_from'));
byId('billing-created-to').value = unixToDate(params.get('created_to'));
const perPage = Number(params.get('per_page'));
state.perPage = [30, 50, 100].includes(perPage) ? perPage : 30;
byId('billing-per-page').value = String(state.perPage);
state.page = Math.max(1, Math.trunc(Number(params.get('page')) || 1));
for (const id of ['billing-status-primary', 'billing-status-secondary', 'billing-category', 'billing-reference-select', 'billing-reference-input']) {
const control = byId(id);
if (!control.disabled && control.dataset.queryKey) control.value = params.get(control.dataset.queryKey) || '';
}
}
function apiError(payload, status) {
if (Array.isArray(payload?.detail)) return payload.detail.map(item => item?.msg || '输入错误').join(';');
return String(payload?.detail || payload?.message || payload?.msg || payload?.error || `请求失败 (${status})`);
}
async function api(path, signal) {
const response = await fetch(path, { method: 'GET', headers: { Accept: 'application/json' }, credentials: 'same-origin', cache: 'no-store', signal });
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) throw new Error(apiError(payload, response.status));
return payload;
}
async function loadList(updateUrl = true) {
const filters = activeFilters();
const url = requestUrl(filters);
if (state.request) state.request.abort();
const controller = new AbortController();
const requestNumber = ++state.requestNumber;
state.request = controller;
setLoading(true);
resetSummary(true);
byId('billing-result-count').textContent = '读取中';
renderState('正在读取数据', '请稍候…');
setNotice(`正在读取${VIEWS[state.view].title}…`);
try {
const payload = await api(url, controller.signal);
if (requestNumber !== state.requestNumber) return;
state.items = Array.isArray(payload?.items) ? payload.items : [];
state.pagination = normalizePagination(payload?.pagination);
state.page = state.pagination.page;
state.perPage = state.pagination.per_page;
byId('billing-per-page').value = String([30, 50, 100].includes(state.perPage) ? state.perPage : 30);
renderRows();
renderSummary(payload?.summary || {});
byId('billing-result-count').textContent = `本页 ${state.items.length} 条 · 共 ${state.pagination.total} 条`;
setNotice(`已加载 ${state.pagination.total} 条${VIEWS[state.view].title}。刷新时间 ${new Date().toLocaleTimeString('zh-CN', { hour12: false })}`, 'success');
if (updateUrl) writeUrl(false, filters);
} catch (error) {
if (error?.name === 'AbortError') return;
state.items = [];
state.pagination = normalizePagination({ page: state.page, per_page: state.perPage, total: 0 });
resetSummary(false);
renderState('数据加载失败', error?.message || '请稍后重试。', true);
byId('billing-result-count').textContent = '加载失败';
setNotice(error?.message || '数据加载失败,请稍后重试。', 'error');
} finally {
if (requestNumber === state.requestNumber) {
state.request = null;
setLoading(false);
}
}
}
function changeView(view, push = true) {
if (state.loading) return;
if (!VIEWS[view]) view = 'invoices';
const changed = view !== state.view;
state.view = view;
state.page = 1;
configureView();
if (changed) {
for (const id of ['billing-status-primary', 'billing-status-secondary', 'billing-category', 'billing-reference-select', 'billing-reference-input']) byId(id).value = '';
}
if (push) writeUrl(true);
void loadList(false);
}
function definitionList(pairs) {
const list = element('dl', 'row g-3 mb-0');
for (const [label, value] of pairs) {
if (value === null || value === undefined || value === '') continue;
const item = element('div', 'col-sm-6');
item.append(element('dt', 'text-muted fs-13 mb-1', label));
const description = element('dd', 'fw-semibold mb-0 text-break');
if (value instanceof Node) description.append(value);
else description.textContent = String(value);
item.append(description);
list.append(item);
}
return list;
}
function detailSection(title, pairs) {
const section = element('section', 'admin-report-card mb-3');
section.append(element('h3', 'fs-14 fw-semibold mb-3', title), definitionList(pairs));
return section;
}
function renderDetail(payload) {
const invoice = payload?.invoice || {};
const body = byId('billing-detail-body');
body.replaceChildren();
byId('billing-detail-title').textContent = `账单 #${invoice.id || state.detailInvoiceId}`;
body.append(detailSection('账单概览', [
['用户', firstText(invoice.user_name, invoice.user_email, invoice.user_id ? `用户 #${invoice.user_id}` : '')],
['账单类型', purposeLabel(invoice.purpose)], ['项目', firstText(invoice.subject_name, invoice.plan_name)],
['金额', formatUsd(invoice.amount)], ['财务状态', statusBadge('financial', invoice.financial_status)],
['履约状态', statusBadge('fulfillment', invoice.fulfillment_status)], ['支付渠道', providerLabel(invoice.payment_method)],
['创建时间', formatDate(invoice.created_at)], ['账单到期', formatDate(invoice.due_at)],
['支付截止', formatDate(invoice.payment_deadline_at)],
['支付时间', formatDate(invoice.paid_at)],
]));
const specification = invoice.specification || {};
const hasSpecification = ['cpu_cores', 'memory_mib', 'disk_gib', 'bandwidth_mbps']
.some((key) => specification[key] !== null && specification[key] !== undefined);
if (invoice.plan_id || hasSpecification || Number(invoice.validity_days) > 0
|| (invoice.traffic_quota_bytes !== null && invoice.traffic_quota_bytes !== undefined)) {
body.append(detailSection('套餐与资源快照', [
['套餐', firstText(invoice.plan_name, invoice.plan_id ? `#${invoice.plan_id}` : '')],
['CPU', specification.cpu_cores != null ? `${specification.cpu_cores} vCPU` : ''],
['内存', specification.memory_mib != null ? `${specification.memory_mib} MiB` : ''],
['磁盘', specification.disk_gib != null ? `${specification.disk_gib} GiB` : ''],
['带宽', specification.bandwidth_mbps != null ? `${specification.bandwidth_mbps} Mbps` : ''],
['有效期', invoice.validity_days != null ? `${invoice.validity_days} 天` : ''],
['流量额度', invoice.traffic_quota_bytes != null ? formatBytes(invoice.traffic_quota_bytes) : ''],
['续费后到期', formatDate(invoice.renews_expires_at)],
]));
}
const order = payload?.order;
if (order) body.append(detailSection('开通任务', [
['任务 ID', order.id ? `#${order.id}` : ''], ['套餐', firstText(order.plan_name, order.plan_id ? `#${order.plan_id}` : '')],
['财务状态', statusBadge('financial', firstText(order.financial_status, invoice.financial_status))],
['履约状态', statusBadge('fulfillment', firstText(order.fulfillment_status, order.status))],
['实例 ID', order.instance_id ? `#${order.instance_id}` : ''], ['引擎任务', order.job_id ? `#${order.job_id}` : ''],
['更新时间', formatDate(order.updated_at)], ['异常摘要', firstText(order.error)],
]));
const job = payload?.job;
if (job) body.append(detailSection('引擎执行', [
['任务 ID', job.id ? `#${job.id}` : ''], ['类型', firstText(job.kind)],
['状态', statusBadge('fulfillment', job.status)], ['阶段', firstText(job.phase)],
['尝试次数', job.attempts !== undefined ? formatInteger(job.attempts) : ''], ['异常摘要', firstText(job.error)],
['更新时间', formatDate(job.updated_at)],
]));
const instance = payload?.instance;
if (instance) body.append(detailSection('实例结果', [
['实例', firstText(instance.name, instance.id ? `#${instance.id}` : '')], ['计算状态', firstText(instance.status)],
['服务状态', firstText(instance.service_status)], ['网络状态', firstText(instance.network_status)],
['到期时间', formatDate(instance.expires_at)],
]));
const attempts = Array.isArray(payload?.payment_attempts) ? payload.payment_attempts : [];
const attemptsSection = element('section', 'admin-report-card');
const attemptsTruncated = payload?.payment_attempts_truncated === true;
attemptsSection.append(element('h3', 'fs-14 fw-semibold mb-3', `支付尝试 (${attempts.length}${attemptsTruncated ? '+' : ''})`));
const attemptsList = element('div', 'd-grid gap-2');
if (attemptsTruncated) {
attemptsList.append(element('p', 'alert alert-light mb-0', '仅显示最近 100 条;完整记录请在“支付流水”中筛选此账单。'));
}
if (!attempts.length) attemptsList.append(element('p', 'text-muted mb-0', '暂无支付尝试记录。'));
for (const attempt of attempts) {
const item = element('article', 'admin-report-card');
item.append(element('strong', 'd-block mb-1', `${providerLabel(attempt.provider || attempt.method)} · ${formatUsd(attempt.amount)}`));
item.append(statusBadge('payment', firstText(attempt.payment_status, attempt.status)));
item.append(element('span', 'd-block text-muted fs-13 mt-2', `创建 ${formatDate(attempt.created_at)}${attempt.updated_at ? ` · 更新 ${formatDate(attempt.updated_at)}` : ''}`));
attemptsList.append(item);
}
attemptsSection.append(attemptsList);
body.append(attemptsSection);
}
function closeDetail() {
const dialog = byId('billing-detail-dialog');
if (state.detailRequest) state.detailRequest.abort();
state.detailRequest = null;
if (dialog.open && typeof dialog.close === 'function') dialog.close();
else {
dialog.removeAttribute('open');
document.body.classList.remove('billing-detail-open');
const opener = state.detailOpener;
state.detailOpener = null;
if (opener?.isConnected) opener.focus({ preventScroll: true });
}
}
async function openDetail(invoiceId, opener) {
const id = String(invoiceId || '').trim();
if (!/^\d+$/.test(id)) return;
if (state.detailRequest) state.detailRequest.abort();
const controller = new AbortController();
state.detailRequest = controller;
state.detailInvoiceId = id;
state.detailOpener = opener || null;
const dialog = byId('billing-detail-dialog');
byId('billing-detail-title').textContent = `账单 #${id}`;
byId('billing-detail-body').replaceChildren();
const detailState = byId('billing-detail-state');
detailState.hidden = false;
detailState.className = 'alert alert-info mb-3';
detailState.setAttribute('role', 'status');
detailState.textContent = '正在读取账单详情…';
if (!dialog.open) {
if (typeof dialog.showModal === 'function') dialog.showModal();
else dialog.setAttribute('open', '');
}
document.body.classList.add('billing-detail-open');
byId('billing-detail-close').focus();
try {
const payload = await api(`/api/v1/admin/billing/invoices/${encodeURIComponent(id)}`, controller.signal);
if (state.detailInvoiceId !== id || !dialog.open) return;
renderDetail(payload);
detailState.hidden = true;
} catch (error) {
if (error?.name === 'AbortError') return;
detailState.hidden = false;
detailState.className = 'alert alert-danger mb-3';
detailState.setAttribute('role', 'alert');
detailState.textContent = error?.message || '账单详情加载失败。';
} finally {
if (state.detailRequest === controller) state.detailRequest = null;
}
}
function bindEvents() {
document.querySelectorAll('[data-billing-view]').forEach(link => {
link.addEventListener('click', event => {
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
if (state.loading) return;
changeView(link.dataset.billingView, true);
});
});
byId('billing-filter-form').addEventListener('submit', event => {
event.preventDefault();
const from = byId('billing-created-from');
const to = byId('billing-created-to');
if (from.value && to.value && from.value > to.value) {
setNotice('开始日期不能晚于结束日期。', 'error');
from.focus();
return;
}
if (!event.currentTarget.checkValidity()) { event.currentTarget.reportValidity(); return; }
state.page = 1;
state.perPage = Number(byId('billing-per-page').value) || 30;
void loadList(true);
});
byId('billing-reset').addEventListener('click', () => {
byId('billing-filter-form').reset();
configureView();
state.page = 1;
state.perPage = 30;
byId('billing-per-page').value = '30';
void loadList(true);
});
byId('billing-refresh').addEventListener('click', () => { void loadList(false); });
byId('billing-previous').addEventListener('click', () => {
if (!state.loading && state.pagination.has_previous) { state.page = Math.max(1, state.page - 1); void loadList(true); }
});
byId('billing-next').addEventListener('click', () => {
if (!state.loading && state.pagination.has_next) { state.page += 1; void loadList(true); }
});
byId('billing-table-body').addEventListener('click', event => {
const button = event.target.closest('[data-invoice-id]');
if (button) void openDetail(button.dataset.invoiceId, button);
});
const dialog = byId('billing-detail-dialog');
byId('billing-detail-close').addEventListener('click', closeDetail);
dialog.addEventListener('click', event => { if (event.target === dialog) closeDetail(); });
dialog.addEventListener('close', () => {
document.body.classList.remove('billing-detail-open');
if (state.detailRequest) state.detailRequest.abort();
state.detailRequest = null;
const opener = state.detailOpener;
state.detailOpener = null;
if (opener?.isConnected) opener.focus({ preventScroll: true });
});
window.addEventListener('popstate', () => {
if (state.request) state.request.abort();
state.request = null;
state.requestNumber += 1;
setLoading(false);
const params = new URLSearchParams(location.search);
state.view = VIEWS[params.get('view')] ? params.get('view') : 'invoices';
configureView();
loadFiltersFromUrl();
void loadList(false);
});
}
function initialize() {
if (!root) return;
const params = new URLSearchParams(location.search);
state.view = VIEWS[params.get('view')] ? params.get('view') : 'invoices';
configureView();
loadFiltersFromUrl();
bindEvents();
void loadList(true);
}
initialize();