|
|
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', '等待支付'], ['active', '执行中'],
|
|
|
['succeeded', '已成功'], ['failed', '已失败'], ['expired', '已失效'],
|
|
|
['refunded', '已退款'], ['cancelled', '已取消'],
|
|
|
];
|
|
|
const ORDER_OPTIONS = FULFILLMENT_OPTIONS;
|
|
|
const PAYMENT_OPTIONS = [
|
|
|
['', '全部支付状态'], ['creating', '创建中'], ['pending', '待支付'],
|
|
|
['paid_invoice', '已入账单'], ['credited_balance', '已入余额'], ['failed', '支付失败'],
|
|
|
['expired', '已失效'],
|
|
|
];
|
|
|
const PURPOSE_OPTIONS = [
|
|
|
['', '全部账单类型'], ['provision', '实例开通'], ['renewal', '实例续费'],
|
|
|
['upgrade', '实例升级'], ['ip_change', '更换公网 IP'],
|
|
|
['backup_addon', '自动备份开通'], ['recharge', '余额充值'],
|
|
|
];
|
|
|
const PROVIDER_OPTIONS = [
|
|
|
['', '全部支付渠道'], ['balance', '账户余额'], ['usdt', 'USDT-TRC20'],
|
|
|
['yipay_alipay', '易支付 · 支付宝'], ['yipay_wxpay', '易支付 · 微信'], ['paytaro', 'Paytaro'],
|
|
|
['stripe_card', 'Stripe · 银行卡'], ['stripe_alipay', 'Stripe · 支付宝'],
|
|
|
];
|
|
|
|
|
|
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: '', detailClosing: false,
|
|
|
detailClosePromise: null, detailOpener: null,
|
|
|
loadedView: '', loadedFilters: {}, cache: new Map(), scroll: null,
|
|
|
};
|
|
|
|
|
|
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) {
|
|
|
if (value === null || value === undefined || value === '') return '—';
|
|
|
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) {
|
|
|
if (value === null || value === undefined || value === '') return '—';
|
|
|
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 '0 B';
|
|
|
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: '实例续费', upgrade: '实例升级',
|
|
|
ip_change: '更换公网 IP', backup_addon: '自动备份开通',
|
|
|
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',
|
|
|
stripe_card: 'Stripe · 银行卡', stripe_alipay: 'Stripe · 支付宝' })[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'], active: ['执行中', 'info'],
|
|
|
succeeded: ['已成功', '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, purpose = '') {
|
|
|
let [label, tone] = statusInfo(kind, value);
|
|
|
if (kind === 'fulfillment' && purpose === 'renewal' && value === 'succeeded') label = '已续费';
|
|
|
if (kind === 'fulfillment' && purpose === 'upgrade') {
|
|
|
label = ({ active: '升级中', succeeded: '已升级', failed: '升级失败',
|
|
|
cancelled: '已取消' })[value] || label;
|
|
|
}
|
|
|
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 taskStatusBadge(task) {
|
|
|
let label = '任务状态协议无效';
|
|
|
let tone = 'danger';
|
|
|
if (task?.completed === false
|
|
|
&& (!Object.prototype.hasOwnProperty.call(task, 'status')
|
|
|
|| task.status === 'active')) {
|
|
|
label = '执行中'; tone = 'info';
|
|
|
} else if (task?.completed === true) {
|
|
|
const info = { succeeded: ['已成功', 'success'], failed: ['已失败', 'danger'] }[task.status];
|
|
|
if (info) [label, tone] = info;
|
|
|
}
|
|
|
const classes = { success: 'bg-success-subtle text-success-emphasis', danger: 'bg-danger-subtle text-danger-emphasis', info: 'bg-info-subtle text-info-emphasis', neutral: 'bg-light text-dark' };
|
|
|
return element('span', `badge rounded-pill fs-12 px-2 py-1 ${classes[tone]}`, 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, item.purpose), 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.task_id ? `任务 #${item.task_id}` : ''].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', item.fulfillment_status),
|
|
|
stack(item.instance_id ? `实例 #${item.instance_id}` : '实例 —', item.task_id ? `任务 #${item.task_id}` : '后台任务 —'),
|
|
|
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 || '';
|
|
|
control.name = 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-input').value = 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, offerReload = 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 (offerReload) {
|
|
|
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 ([2, 6, 7].includes(index)) cell.classList.add('admin-billing-secondary');
|
|
|
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
|
|
|
? '待收款' : '处理中';
|
|
|
byId('billing-summary-result-label').textContent = invoiceView
|
|
|
? '已支付' : orderView ? '已开通 / 失败' : '入账去向';
|
|
|
for (const id of ['billing-summary-total', 'billing-summary-amount',
|
|
|
'billing-summary-focus', 'billing-summary-result', 'billing-summary-refunded']) byId(id).textContent = '—';
|
|
|
byId('billing-refund-card').hidden = !invoiceView;
|
|
|
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)}`;
|
|
|
byId('billing-summary-refunded').textContent = `${formatInteger(summary.refunded_count)} 笔 · ${formatUsd(summary.refunded_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, ['active']))} 笔`;
|
|
|
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');
|
|
|
byId('billing-refund-card').hidden = state.view !== 'invoices';
|
|
|
}
|
|
|
|
|
|
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 setLoading(loading) {
|
|
|
state.loading = loading;
|
|
|
root.setAttribute('aria-busy', String(loading));
|
|
|
byId('billing-table').setAttribute('aria-busy', String(loading));
|
|
|
byId('billing-refresh').disabled = 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 && !['page', 'per_page', 'view', 'detail'].includes(key)) params.set(key, value);
|
|
|
return `${VIEWS[state.view].endpoint}?${params.toString()}`;
|
|
|
}
|
|
|
|
|
|
function historyData(changes = {}) {
|
|
|
const current = history.state;
|
|
|
if (current !== null && (typeof current !== 'object' || Array.isArray(current))) return current;
|
|
|
const result = { ...(current || {}) };
|
|
|
for (const [key, value] of Object.entries(changes)) {
|
|
|
if (value === undefined) delete result[key];
|
|
|
else result[key] = value;
|
|
|
}
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
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 && !['page', 'per_page', 'view', 'detail'].includes(key)) params.set(key, value);
|
|
|
const detail = new URLSearchParams(location.search).get('detail');
|
|
|
if (detail && /^[1-9][0-9]{0,18}$/.test(detail)) params.set('detail', detail);
|
|
|
const target = `${location.pathname}${params.size ? `?${params.toString()}` : ''}`;
|
|
|
history[push && target !== location.pathname + location.search ? 'pushState' : 'replaceState'](historyData(), '', target);
|
|
|
}
|
|
|
|
|
|
function loadFiltersFromUrl(source = location.search) {
|
|
|
const params = source instanceof URLSearchParams ? source : new URLSearchParams(source);
|
|
|
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) || '';
|
|
|
}
|
|
|
byId('billing-advanced').open = ['created_from', 'created_to', 'purpose', 'provider', 'payment_method', 'invoice_id'].some(key => params.get(key)) || state.perPage !== 30;
|
|
|
}
|
|
|
|
|
|
function cachedParameters(cached) {
|
|
|
const params = new URLSearchParams();
|
|
|
for (const [key, value] of Object.entries(cached.filters || {})) if (value !== null && value !== undefined && value !== '') params.set(key, value);
|
|
|
params.set('page', cached.pagination.page);
|
|
|
params.set('per_page', cached.pagination.per_page);
|
|
|
return params;
|
|
|
}
|
|
|
|
|
|
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, controller) {
|
|
|
const timeout = setTimeout(() => controller.abort('timeout'), 30000);
|
|
|
try {
|
|
|
const response = await fetch(path, { method: 'GET', headers: { Accept: 'application/json' }, credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
|
|
|
let payload;
|
|
|
try { payload = await response.json(); }
|
|
|
catch { throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反向代理配置。'); }
|
|
|
if (response.status === 401) throw new Error('登录已过期,请重新登录后刷新。');
|
|
|
if (!response.ok || payload?.ret === 0) throw new Error(apiError(payload, response.status));
|
|
|
return payload;
|
|
|
} catch (error) {
|
|
|
if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后重试。');
|
|
|
throw error;
|
|
|
} finally { clearTimeout(timeout); }
|
|
|
}
|
|
|
|
|
|
function shownFilters(filters) {
|
|
|
const parts = [];
|
|
|
if (filters.q) parts.push(`关键词「${filters.q}」`);
|
|
|
if (filters.user_id) parts.push(`用户 #${filters.user_id}`);
|
|
|
for (const definition of [VIEWS[state.view].primary, VIEWS[state.view].secondary, VIEWS[state.view].category, VIEWS[state.view].reference]) {
|
|
|
const value = definition && filters[definition.key];
|
|
|
if (value) parts.push(`${definition.label}:${definition.options?.find(option => option[0] === value)?.[1] || value}`);
|
|
|
}
|
|
|
if (filters.created_from || filters.created_to) parts.push(`日期 ${unixToDate(filters.created_from) || '不限'} 至 ${unixToDate(filters.created_to) || '不限'}`);
|
|
|
return parts.join(' · ') || '全部记录';
|
|
|
}
|
|
|
|
|
|
function applyListPayload(payload, filters, replaceRows = true) {
|
|
|
if (!Array.isArray(payload?.items) || !payload?.pagination || !payload?.summary) throw new Error('账单数据格式异常,请重试。');
|
|
|
state.items = payload.items;
|
|
|
state.pagination = normalizePagination(payload.pagination);
|
|
|
state.page = state.pagination.page;
|
|
|
state.perPage = state.pagination.per_page;
|
|
|
state.loadedView = state.view;
|
|
|
state.loadedFilters = { ...filters };
|
|
|
state.cache.set(state.view, { ...payload, filters: { ...filters }, view: state.view });
|
|
|
if (replaceRows) renderRows();
|
|
|
renderSummary(payload.summary);
|
|
|
renderPagination();
|
|
|
byId('billing-result-count').textContent = `本页 ${state.items.length} 条 · 共 ${state.pagination.total} 条`;
|
|
|
byId('billing-shown-filters').textContent = `当前显示:${shownFilters(filters)}`;
|
|
|
}
|
|
|
|
|
|
async function loadList(updateUrl = true, specifiedFilters = null) {
|
|
|
const filters = specifiedFilters || activeFilters();
|
|
|
const url = requestUrl(filters);
|
|
|
if (state.request) state.request.abort();
|
|
|
const controller = new AbortController();
|
|
|
const requestNumber = ++state.requestNumber;
|
|
|
state.request = controller;
|
|
|
setLoading(true);
|
|
|
if (state.loadedView !== state.view) {
|
|
|
resetSummary(true);
|
|
|
state.items = [];
|
|
|
state.pagination = normalizePagination({ total: 0 });
|
|
|
renderPagination();
|
|
|
byId('billing-result-count').textContent = '读取中';
|
|
|
byId('billing-shown-filters').textContent = `正在读取:${shownFilters(filters)}`;
|
|
|
renderState('正在读取数据', '请稍候…');
|
|
|
}
|
|
|
setNotice(`正在读取${VIEWS[state.view].title}…`);
|
|
|
try {
|
|
|
const payload = await api(url, controller);
|
|
|
if (requestNumber !== state.requestNumber || controller.signal.aborted) return;
|
|
|
applyListPayload(payload, filters);
|
|
|
setNotice(`${state.pagination.total} 条 · 更新 ${new Date().toLocaleTimeString('zh-CN', { hour12: false })}`, 'success');
|
|
|
writeUrl(updateUrl, filters);
|
|
|
} catch (error) {
|
|
|
if (requestNumber !== state.requestNumber || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
|
|
|
if (state.loadedView !== state.view) {
|
|
|
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 = '加载失败';
|
|
|
} else {
|
|
|
state.page = state.pagination.page;
|
|
|
state.perPage = state.pagination.per_page;
|
|
|
}
|
|
|
setNotice(`${error?.message || '数据加载失败。'}${state.loadedView === state.view ? ' 已保留上次数据,下方注明实际显示条件。' : ''}`, 'error');
|
|
|
} finally {
|
|
|
if (requestNumber === state.requestNumber) {
|
|
|
state.request = null;
|
|
|
setLoading(false);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function changeView(view, push = true) {
|
|
|
state.request?.abort();
|
|
|
state.requestNumber += 1;
|
|
|
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 = '';
|
|
|
}
|
|
|
const cached = state.cache.get(view);
|
|
|
if (cached) {
|
|
|
loadFiltersFromUrl(cachedParameters(cached));
|
|
|
applyListPayload(cached, cached.filters);
|
|
|
}
|
|
|
if (push) writeUrl(true);
|
|
|
void loadList(false);
|
|
|
}
|
|
|
|
|
|
function definitionList(pairs) {
|
|
|
const list = element('dl', 'admin-instance-details');
|
|
|
for (const [label, value] of pairs) {
|
|
|
if (value === null || value === undefined || value === '') continue;
|
|
|
list.append(element('dt', '', label));
|
|
|
const description = element('dd');
|
|
|
if (value instanceof Node) description.append(value);
|
|
|
else description.textContent = String(value);
|
|
|
list.append(description);
|
|
|
}
|
|
|
return list;
|
|
|
}
|
|
|
|
|
|
function detailSection(title, pairs) {
|
|
|
const section = element('section', 'mb-4');
|
|
|
section.append(element('h3', 'fs-14 fw-semibold mb-3', title), definitionList(pairs));
|
|
|
return section;
|
|
|
}
|
|
|
|
|
|
const detailTabs = ['overview', 'funds', 'fulfillment', 'payments'];
|
|
|
|
|
|
function chooseDetailTab(name, focus = false) {
|
|
|
detailTabs.forEach(tab => {
|
|
|
const selected = name === tab;
|
|
|
byId('billing-tab-' + tab).setAttribute('aria-selected', String(selected));
|
|
|
byId('billing-tab-' + tab).tabIndex = selected ? 0 : -1;
|
|
|
byId('billing-panel-' + tab).hidden = !selected;
|
|
|
});
|
|
|
if (focus) byId('billing-tab-' + name).focus();
|
|
|
}
|
|
|
|
|
|
function safeLink(url, label) {
|
|
|
try {
|
|
|
const target = new URL(url, location.origin);
|
|
|
if (target.origin !== location.origin || !['https:', 'http:'].includes(target.protocol)) return null;
|
|
|
const link = element('a', 'btn btn-light btn-sm', label);
|
|
|
link.href = target.pathname + target.search + target.hash;
|
|
|
return link;
|
|
|
} catch { return null; }
|
|
|
}
|
|
|
|
|
|
function renderDetail(payload) {
|
|
|
const invoice = payload?.invoice;
|
|
|
if (!invoice || String(invoice.id) !== state.detailInvoiceId) throw new Error('账单详情与请求不一致,请重试。');
|
|
|
detailTabs.forEach(tab => byId('billing-panel-' + tab).replaceChildren());
|
|
|
byId('billing-detail-title').textContent = '账单 #' + invoice.id;
|
|
|
const overview = byId('billing-panel-overview');
|
|
|
overview.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, invoice.purpose)],
|
|
|
['支付渠道', 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 || {};
|
|
|
if (invoice.purpose !== 'recharge') overview.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 ? (Number(invoice.traffic_quota_bytes) === 0 ? '不限流量' : formatBytes(invoice.traffic_quota_bytes)) : ''],
|
|
|
['续费后到期', invoice.purpose === 'renewal' ? formatDate(invoice.renews_expires_at) : ''],
|
|
|
]));
|
|
|
|
|
|
const funds = payload.funds || {};
|
|
|
const fundPanel = byId('billing-panel-funds');
|
|
|
fundPanel.append(element('h3', 'h6', firstText(funds.title, '资金记录')),
|
|
|
element('p', 'text-muted', firstText(funds.description, '以已确认的支付和退款记录为准。')),
|
|
|
definitionList([
|
|
|
['确认支付金额', formatUsd(funds.settled_amount)],
|
|
|
['已退款金额', funds.refund_amount != null ? formatUsd(funds.refund_amount) : '无已确认退款记录'],
|
|
|
['退款去向', funds.refund_destination === 'balance' ? '账户余额' : '—'],
|
|
|
['退款时间', formatDate(funds.refunded_at)],
|
|
|
['另行转入余额', formatUsd(funds.balance_retained_amount)],
|
|
|
['转入余额笔数', formatInteger(funds.balance_retained_count)],
|
|
|
]));
|
|
|
for (const note of funds.notes || []) fundPanel.append(element('p', 'text-muted fs-13 mt-3', note));
|
|
|
if (Array.isArray(payload.timeline) && payload.timeline.length) {
|
|
|
const section = element('section', 'mt-4');
|
|
|
section.append(element('h3', 'h6 mb-3', '记录时间线'));
|
|
|
const timeline = element('ol', 'admin-billing-timeline');
|
|
|
for (const entry of payload.timeline) {
|
|
|
const item = element('li');
|
|
|
item.append(element('strong', 'd-block', firstText(entry.title, entry.kind)),
|
|
|
element('span', 'text-muted fs-12 d-block', entry.at ? formatDate(entry.at) : '时间未记录'));
|
|
|
if (entry.description) item.append(element('p', 'fs-13 mb-0', entry.description));
|
|
|
timeline.append(item);
|
|
|
}
|
|
|
section.append(timeline); fundPanel.append(section);
|
|
|
}
|
|
|
|
|
|
const fulfillment = byId('billing-panel-fulfillment');
|
|
|
if (invoice.purpose === 'recharge') {
|
|
|
fulfillment.append(element('p', 'alert alert-light', '余额充值不创建虚拟机,到账信息请查看“资金记录”。'));
|
|
|
} else {
|
|
|
const order = payload.order;
|
|
|
if (invoice.purpose === 'renewal') fulfillment.append(element('p', 'alert alert-light', '续费用于延长现有实例服务周期,不会重新创建虚拟机。'));
|
|
|
if (invoice.purpose === 'upgrade') fulfillment.append(element('p', 'alert alert-light', '升级账单在扣款时已创建后台任务,不可再次支付;请在此核对目标实例和最终任务状态。'));
|
|
|
if (order && invoice.purpose === 'provision') fulfillment.append(detailSection('开通任务', [
|
|
|
['任务 ID', order.id ? '#' + order.id : ''], ['套餐', firstText(order.plan_name)],
|
|
|
['财务状态', statusBadge('financial', firstText(order.financial_status, invoice.financial_status))],
|
|
|
['履约状态', statusBadge('fulfillment', order.fulfillment_status)],
|
|
|
['实例 ID', order.instance_id ? '#' + order.instance_id : ''], ['后台任务', order.task_id ? '#' + order.task_id : ''],
|
|
|
['更新时间', formatDate(order.updated_at)], ['异常摘要', firstText(order.error)],
|
|
|
]));
|
|
|
const task = payload.task;
|
|
|
if (task && ['provision', 'upgrade'].includes(invoice.purpose)) fulfillment.append(detailSection(
|
|
|
invoice.purpose === 'upgrade' ? '升级任务' : '后台任务', [
|
|
|
['任务 ID', task.id ? '#' + task.id : ''], ['类型', firstText(task.kind_label || task.action_label, task.kind)],
|
|
|
['状态', taskStatusBadge(task)], ['异常摘要', firstText(task.error)],
|
|
|
['更新时间', formatDate(task.updated_at)],
|
|
|
]));
|
|
|
const instance = payload.instance;
|
|
|
if (instance) fulfillment.append(detailSection('关联实例', [
|
|
|
['实例', firstText(instance.name, instance.id ? '#' + instance.id : '')],
|
|
|
['实例生命周期', ({ active: '在管', deleted: '已删除', deleting: '删除中', delete_failed: '删除失败' })[instance.status] || firstText(instance.status)],
|
|
|
['服务状态', ({ active: '服务正常', exempt: '免计费', expired: '已到期', expired_grace: '到期宽限期', resume_pending: '等待恢复', resume_failed: '恢复失败', purge_force_required: '等待确认强制删除', purge_deleting: '到期清理中', purge_failed: '到期清理失败' })[instance.service_status] || firstText(instance.service_status)],
|
|
|
['网络状态', ({ active: '正常', blocked_traffic: '流量耗尽已断网', blocked_expired: '到期已断网', blocking: '正在限制网络', blocking_expired: '到期断网中', block_failed: '限制网络失败', restore_pending: '等待恢复', restoring: '恢复中', restore_failed: '恢复失败' })[instance.network_status] || firstText(instance.network_status)],
|
|
|
['到期时间', formatDate(instance.expires_at)],
|
|
|
]));
|
|
|
if (!instance && !order && !task) fulfillment.append(element('p', 'text-muted', '当前无可用关联实例或后台任务,历史账单仍保留。'));
|
|
|
}
|
|
|
|
|
|
const attempts = Array.isArray(payload.payment_attempts) ? payload.payment_attempts : [];
|
|
|
const payments = byId('billing-panel-payments');
|
|
|
payments.append(element('h3', 'h6 mb-3', '支付尝试(' + attempts.length + (payload.payment_attempts_truncated ? '+' : '') + ')'));
|
|
|
if (payload.payment_attempts_truncated) payments.append(element('p', 'text-muted fs-13', '仅显示最近 100 条;可通过底部“全部支付记录”查看本账单完整记录。'));
|
|
|
if (!attempts.length) payments.append(element('p', 'text-muted', '暂无在线支付尝试记录。余额支付请以资金记录为准。'));
|
|
|
for (const attempt of attempts) {
|
|
|
const card = element('article', 'card mb-3');
|
|
|
const body = element('div', 'card-body');
|
|
|
body.append(element('strong', 'd-block mb-2', providerLabel(attempt.provider || attempt.method) + ' · ' + formatUsd(attempt.amount)),
|
|
|
statusBadge('payment', firstText(attempt.payment_status, attempt.status)),
|
|
|
element('span', 'd-block text-muted fs-13 mt-2', '创建 ' + formatDate(attempt.created_at) + (attempt.updated_at ? ' · 更新 ' + formatDate(attempt.updated_at) : '')));
|
|
|
card.append(body); payments.append(card);
|
|
|
}
|
|
|
const links = byId('billing-detail-links');
|
|
|
links.replaceChildren();
|
|
|
for (const [key, label] of [['user', '查看用户'], ['instance', '查看实例'], ['payments', '全部支付记录']]) {
|
|
|
if (payload.links?.[key]) {
|
|
|
const link = safeLink(payload.links[key], label);
|
|
|
if (link) links.append(link);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function finishUnlockDetail() {
|
|
|
state.detailClosing = false;
|
|
|
document.documentElement.classList.remove('admin-instance-detail-open');
|
|
|
document.body.style.removeProperty('--admin-instance-scroll-top');
|
|
|
if (state.scroll) {
|
|
|
window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' });
|
|
|
state.scroll = null;
|
|
|
}
|
|
|
if (state.detailOpener?.isConnected) state.detailOpener.focus({ preventScroll: true });
|
|
|
state.detailOpener = null;
|
|
|
}
|
|
|
|
|
|
function unlockDetail() {
|
|
|
if (state.detailClosing) return Promise.resolve(false);
|
|
|
const dialog = byId('billing-detail-dialog');
|
|
|
state.detailRequest?.abort();
|
|
|
state.detailRequest = null;
|
|
|
state.detailInvoiceId = '';
|
|
|
state.detailClosing = true;
|
|
|
const closing = window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => {
|
|
|
if (closed) finishUnlockDetail();
|
|
|
else state.detailClosing = false;
|
|
|
return closed;
|
|
|
});
|
|
|
state.detailClosePromise = closing;
|
|
|
void closing.then(() => {
|
|
|
if (state.detailClosePromise === closing) state.detailClosePromise = null;
|
|
|
});
|
|
|
return closing;
|
|
|
}
|
|
|
|
|
|
function closeDetail(updateUrl = true) {
|
|
|
if (state.detailClosing) return;
|
|
|
const parent = history.state?.billingDetailParent;
|
|
|
void unlockDetail().then(closed => {
|
|
|
if (!closed || !updateUrl) return;
|
|
|
const url = new URL(location.href);
|
|
|
if (!url.searchParams.has('detail')) return;
|
|
|
url.searchParams.delete('detail');
|
|
|
if (parent === url.pathname + url.search && history.state?.billingDetailPushed) {
|
|
|
history.back();
|
|
|
} else {
|
|
|
history.replaceState(historyData({ billingDetailParent: undefined, billingDetailPushed: undefined, billingDetailScroll: undefined }), '', url);
|
|
|
}
|
|
|
});
|
|
|
}
|
|
|
|
|
|
async function openDetail(invoiceId, opener = null, updateUrl = true) {
|
|
|
const id = String(invoiceId || '').trim();
|
|
|
if (!/^[1-9][0-9]{0,18}$/.test(id)) return;
|
|
|
if (state.detailClosing) {
|
|
|
const closing = state.detailClosePromise;
|
|
|
if (closing) await closing;
|
|
|
if (state.detailClosing) return;
|
|
|
if (!updateUrl && new URL(location.href).searchParams.get('detail') !== id) return;
|
|
|
}
|
|
|
state.detailRequest?.abort();
|
|
|
const controller = new AbortController();
|
|
|
state.detailRequest = controller;
|
|
|
const dialog = byId('billing-detail-dialog');
|
|
|
state.detailInvoiceId = id;
|
|
|
if (opener) state.detailOpener = opener;
|
|
|
else if (!state.detailOpener?.isConnected) {
|
|
|
state.detailOpener = Array.from(byId('billing-table-body').querySelectorAll('[data-invoice-id]'))
|
|
|
.find(button => button.dataset.invoiceId === id) || byId('billing-refresh');
|
|
|
}
|
|
|
if (!state.scroll) {
|
|
|
const stored = history.state?.billingDetailScroll;
|
|
|
state.scroll = !updateUrl && Number.isFinite(stored?.x) && Number.isFinite(stored?.y) ? stored : { x: window.scrollX, y: window.scrollY };
|
|
|
}
|
|
|
if (updateUrl) {
|
|
|
const url = new URL(location.href);
|
|
|
const parent = url.pathname + url.search;
|
|
|
const alreadyOpen = url.searchParams.has('detail');
|
|
|
url.searchParams.set('detail', id);
|
|
|
history[alreadyOpen ? 'replaceState' : 'pushState'](historyData({
|
|
|
billingDetailParent: alreadyOpen ? history.state?.billingDetailParent : parent,
|
|
|
billingDetailPushed: !alreadyOpen || history.state?.billingDetailPushed,
|
|
|
billingDetailScroll: state.scroll,
|
|
|
}), '', url);
|
|
|
}
|
|
|
byId('billing-detail-title').textContent = '账单 #' + id;
|
|
|
detailTabs.forEach(tab => byId('billing-panel-' + tab).replaceChildren());
|
|
|
byId('billing-detail-links').replaceChildren();
|
|
|
chooseDetailTab('overview');
|
|
|
const detailState = byId('billing-detail-state');
|
|
|
detailState.hidden = false;
|
|
|
detailState.className = 'alert alert-info';
|
|
|
detailState.setAttribute('role', 'status');
|
|
|
detailState.textContent = '正在读取账单详情…';
|
|
|
document.body.style.setProperty('--admin-instance-scroll-top', -state.scroll.y + 'px');
|
|
|
document.documentElement.classList.add('admin-instance-detail-open');
|
|
|
if (!dialog.open) window.VenixDrawerMotion.openDrawerWithMotion(dialog);
|
|
|
byId('billing-detail-close').focus({ preventScroll: true });
|
|
|
try {
|
|
|
const payload = await api('/api/v1/admin/billing/invoices/' + encodeURIComponent(id), controller);
|
|
|
if (state.detailRequest !== controller || controller.signal.aborted || state.detailInvoiceId !== id || !dialog.open) return;
|
|
|
renderDetail(payload);
|
|
|
detailState.hidden = true;
|
|
|
} catch (error) {
|
|
|
if (state.detailRequest !== controller || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
|
|
|
detailState.hidden = false;
|
|
|
detailState.className = 'alert alert-danger';
|
|
|
detailState.setAttribute('role', 'alert');
|
|
|
detailState.textContent = error?.message || '账单详情加载失败。';
|
|
|
const reload = element('button', 'btn btn-light btn-sm d-block mt-2', '重新读取详情');
|
|
|
reload.type = 'button';
|
|
|
reload.addEventListener('click', () => { void openDetail(id, null, false); });
|
|
|
detailState.append(reload);
|
|
|
} finally {
|
|
|
if (state.detailRequest === controller) state.detailRequest = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function clearFilters() {
|
|
|
for (const id of ['billing-query', 'billing-user-id', 'billing-created-from', 'billing-created-to',
|
|
|
'billing-status-primary', 'billing-status-secondary', 'billing-category', 'billing-reference-select', 'billing-reference-input']) byId(id).value = '';
|
|
|
state.page = 1;
|
|
|
state.perPage = 30;
|
|
|
byId('billing-per-page').value = '30';
|
|
|
}
|
|
|
|
|
|
function restoreRoute(refresh = true) {
|
|
|
state.request?.abort();
|
|
|
state.request = null;
|
|
|
state.requestNumber += 1;
|
|
|
setLoading(false);
|
|
|
const params = new URLSearchParams(location.search);
|
|
|
const view = VIEWS[params.get('view')] ? params.get('view') : 'invoices';
|
|
|
state.view = view;
|
|
|
configureView();
|
|
|
loadFiltersFromUrl();
|
|
|
const requestedPage = state.page;
|
|
|
const requestedPerPage = state.perPage;
|
|
|
const filters = activeFilters();
|
|
|
const sameList = state.loadedView === view && state.pagination.page === requestedPage
|
|
|
&& state.pagination.per_page === requestedPerPage
|
|
|
&& Object.keys(filters).every(key => String(filters[key] || '') === String(state.loadedFilters[key] || ''));
|
|
|
const cached = state.cache.get(view);
|
|
|
if (cached) applyListPayload(cached, cached.filters, !sameList);
|
|
|
else {
|
|
|
state.loadedView = '';
|
|
|
state.items = [];
|
|
|
state.pagination = normalizePagination({ page: requestedPage, per_page: requestedPerPage, total: 0 });
|
|
|
resetSummary(false);
|
|
|
renderState('正在读取数据', '请稍候…');
|
|
|
}
|
|
|
state.page = requestedPage;
|
|
|
state.perPage = requestedPerPage;
|
|
|
const detail = params.get('detail') || '';
|
|
|
if (/^[1-9][0-9]{0,18}$/.test(detail)) {
|
|
|
if (state.detailInvoiceId !== detail || !byId('billing-detail-dialog').open) void openDetail(detail, null, false);
|
|
|
} else closeDetail(false);
|
|
|
if (refresh && !sameList) void loadList(false, filters);
|
|
|
}
|
|
|
|
|
|
function bindEvents() {
|
|
|
document.querySelectorAll('[data-billing-view]').forEach(link => {
|
|
|
link.addEventListener('click', event => {
|
|
|
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
|
event.preventDefault();
|
|
|
if (link.dataset.billingView !== state.view) 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');
|
|
|
byId('billing-advanced').open = true;
|
|
|
from.focus();
|
|
|
return;
|
|
|
}
|
|
|
if (!event.currentTarget.checkValidity()) {
|
|
|
if (byId('billing-advanced').querySelector(':invalid')) byId('billing-advanced').open = true;
|
|
|
event.currentTarget.reportValidity(); return;
|
|
|
}
|
|
|
state.page = 1;
|
|
|
state.perPage = Number(byId('billing-per-page').value) || 30;
|
|
|
void loadList(true);
|
|
|
});
|
|
|
byId('billing-reset').addEventListener('click', () => { clearFilters(); void loadList(true); });
|
|
|
byId('billing-refresh').addEventListener('click', () => {
|
|
|
void loadList(false, state.loadedView === state.view ? state.loadedFilters : null);
|
|
|
});
|
|
|
byId('billing-previous').addEventListener('click', () => {
|
|
|
if (!state.loading && state.pagination.has_previous) {
|
|
|
state.page = Math.max(1, state.pagination.page - 1); void loadList(true, state.loadedFilters);
|
|
|
}
|
|
|
});
|
|
|
byId('billing-next').addEventListener('click', () => {
|
|
|
if (!state.loading && state.pagination.has_next) {
|
|
|
state.page = state.pagination.page + 1; void loadList(true, state.loadedFilters);
|
|
|
}
|
|
|
});
|
|
|
root.querySelectorAll('[data-billing-preset]').forEach(button => {
|
|
|
button.addEventListener('click', () => {
|
|
|
const value = button.dataset.billingPreset;
|
|
|
state.view = value === 'refunded' ? 'invoices' : 'orders';
|
|
|
configureView();
|
|
|
clearFilters();
|
|
|
byId('billing-status-primary').value = value;
|
|
|
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('cancel', event => { event.preventDefault(); closeDetail(); });
|
|
|
dialog.addEventListener('click', event => {
|
|
|
if (event.target === dialog) {
|
|
|
const rect = dialog.getBoundingClientRect();
|
|
|
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) closeDetail();
|
|
|
}
|
|
|
const tab = event.target.closest('[data-billing-tab]');
|
|
|
if (tab) chooseDetailTab(tab.dataset.billingTab);
|
|
|
const link = event.target.closest('a[href]');
|
|
|
if (link && event.button === 0 && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) closeDetail(false);
|
|
|
});
|
|
|
dialog.addEventListener('keydown', event => {
|
|
|
if (!event.target.matches('[data-billing-tab]')) return;
|
|
|
const index = detailTabs.indexOf(event.target.dataset.billingTab);
|
|
|
const next = ({ ArrowRight: (index + 1) % detailTabs.length, ArrowLeft: (index + detailTabs.length - 1) % detailTabs.length, Home: 0, End: detailTabs.length - 1 })[event.key];
|
|
|
if (next !== undefined) { event.preventDefault(); chooseDetailTab(detailTabs[next], true); }
|
|
|
});
|
|
|
window.addEventListener('popstate', () => restoreRoute());
|
|
|
window.addEventListener('pagehide', () => {
|
|
|
state.request?.abort(); state.detailRequest?.abort();
|
|
|
if (state.scroll) history.replaceState(historyData({ billingDetailScroll: state.scroll }), '', location.href);
|
|
|
});
|
|
|
window.addEventListener('pageshow', event => {
|
|
|
if (event.persisted) { closeDetail(false); restoreRoute(false); 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();
|
|
|
let ready = false;
|
|
|
try {
|
|
|
const payload = JSON.parse(byId('admin-billing-bootstrap').textContent);
|
|
|
if (payload?.view === state.view) {
|
|
|
applyListPayload(payload, payload.filters || activeFilters(), false);
|
|
|
ready = true;
|
|
|
}
|
|
|
} catch { /* Keep the server-rendered error and offer the normal refresh retry. */ }
|
|
|
if (!ready) {
|
|
|
state.loadedView = '';
|
|
|
resetSummary(false);
|
|
|
byId('billing-result-count').textContent = '数据未获取';
|
|
|
setNotice('账单数据暂不可用,请点击刷新重试。', 'error');
|
|
|
}
|
|
|
const linkedInvoice = params.get('detail') || '';
|
|
|
if (/^[1-9][0-9]{0,18}$/.test(linkedInvoice)) void openDetail(linkedInvoice, null, false);
|
|
|
}
|
|
|
|
|
|
initialize();
|