feat: improve admin billing views and detail drawer

dev
admin 2 months ago
parent 5905699742
commit eca57ab75f

@ -4,10 +4,11 @@ namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAdminBillingService;
use App\Services\Cloud\CloudAdminInstanceService;
use App\Services\Cloud\CloudError;
/** Page shells only; the scoped JSON API owns authorisation and mutations. */
/** Admin pages use database-only first paints; JSON APIs repeat authorisation. */
final class CloudPageController extends AdminController
{
public function hosts($request, $response, $args)
@ -62,7 +63,39 @@ final class CloudPageController extends AdminController
public function billing($request, $response, $args)
{
return $this->view()->display('admin/billing.tpl');
try {
$actor = CloudAccess::actor(false);
} catch (CloudError $exception) {
return $response->withStatus($exception->httpStatus)
->withHeader('Cache-Control', 'private, no-store');
}
if (!($actor['is_admin'] ?? false)) {
return $response->withStatus(403)->withHeader('Cache-Control', 'private, no-store');
}
$payload = null;
$error = '';
$status = 200;
$requestedView = $request->getQueryParams()['view'] ?? 'invoices';
$view = is_string($requestedView) && in_array($requestedView, ['invoices', 'orders', 'payments'], true)
? $requestedView : 'invoices';
try {
$payload = CloudAdminBillingService::page($request->getQueryParams());
} catch (CloudError $exception) {
$error = $exception->getMessage();
$status = $exception->httpStatus;
} catch (\Throwable $exception) {
error_log('Admin billing snapshot failed: ' . get_class($exception));
$error = '账单数据暂时无法读取,请稍后重试。';
$status = 503;
}
$smarty = $this->view()->assign([
'billing_page' => $payload, 'billing_error' => $error, 'billing_view' => $view,
'billing_bootstrap_json' => json_encode($payload,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR),
]);
$response->getBody()->write($smarty->fetch('admin/billing.tpl'));
return $response->withStatus($status)->withHeader('Cache-Control', 'private, no-store');
}
public function update($request, $response, $args)

@ -9,6 +9,7 @@ use App\Models\CloudOrder;
use App\Models\Shop;
use App\Models\User;
use App\Services\AdminDataMasker;
use App\Services\AdminPermission;
/**
* Read-only, administrator-scoped billing queries.
@ -42,6 +43,21 @@ final class CloudAdminBillingService
'succeeded', 'failed', 'expired', 'refunded', 'cancelled',
];
/** The SSR page and its JSON refreshes share the same read-only queries. */
public static function page(array $input): array
{
$view = $input['view'] ?? 'invoices';
if (!is_string($view) || !in_array($view, ['invoices', 'orders', 'payments'], true)) {
throw new CloudError('账单视图无效', 400);
}
$payload = match ($view) {
'orders' => self::orders($input),
'payments' => self::payments($input),
default => self::invoices($input),
};
return ['view' => $view] + $payload;
}
public static function invoices(array $input): array
{
$filters = self::invoiceFilters($input);
@ -104,9 +120,14 @@ final class CloudAdminBillingService
&& !self::sameIdentifier($instance->user_id, $invoice->user_id)) {
$instance = null;
}
$payments = CloudInvoicePayment::where('invoice_id', $invoice->id)
->where('user_id', $invoice->user_id)->orderByDesc('id')
->limit(self::DETAIL_PAYMENT_LIMIT + 1)->get()->all();
$paymentQuery = CloudInvoicePayment::where('invoice_id', $invoice->id)
->where('user_id', $invoice->user_id);
$retained = (clone $paymentQuery)->where('status', 'credited_balance')
->selectRaw('COUNT(*) AS retained_count, COALESCE(SUM(amount), 0) AS retained_amount')->first();
$payments = (clone $paymentQuery)->orderByDesc('id')
->limit(self::DETAIL_PAYMENT_LIMIT + 1)
->get(['id', 'invoice_id', 'user_id', 'provider', 'amount', 'status', 'created_at', 'updated_at'])
->all();
$paymentsTruncated = count($payments) > self::DETAIL_PAYMENT_LIMIT;
if ($paymentsTruncated) {
$payments = array_slice($payments, 0, self::DETAIL_PAYMENT_LIMIT);
@ -135,9 +156,138 @@ final class CloudAdminBillingService
$payments
),
'payment_attempts_truncated' => $paymentsTruncated,
'funds' => self::funds($invoice, $order, $retained, $paymentsTruncated,
$row['financial_status']),
'timeline' => self::timeline($invoice, $order, $job, $payments,
$row['financial_status']),
'links' => self::links($invoice, $instance, $context['users']),
];
}
/** Explain recorded outcomes, not an inferred wallet balance or cash ledger. */
private static function funds($invoice, $order, $retained, bool $truncated,
string $financialStatus): array
{
$status = (string) $invoice->status;
$paid = $status === 'paid' || self::recordedTime($invoice->paid_at) !== null;
$refundedAt = $status === 'refunded' && (string) $invoice->purpose === 'provision'
&& $order !== null ? self::recordedTime($order->refunded_at) : null;
$refundAmount = $refundedAt === null ? null : self::money($order->amount);
$titles = ['paid' => '账单已结清', 'refunded' => '账单标记已退款',
'open' => '账单尚未结清', 'overdue' => '账单尚未结清',
'expired' => '账单已失效', 'void' => '账单已作废'];
$title = $titles[$financialStatus] ?? '资金状态待核对';
$description = '请结合账单状态与支付记录核对;支付尝试金额不等同于实际到账金额。';
if ($status === 'paid') {
$description = (string) $invoice->paid_via === 'balance'
? '该账单已使用账户余额结清;余额支付不是一次新的外部充值。'
: '该账单已结清。在线支付记录单独记录网关支付结果,不应与账单金额重复计算收入。';
} elseif ($refundedAt !== null) {
$title = '开通款项已退回账户余额';
$description = '关联开通订单记录已将款项退回该用户的账户余额,不代表支付网关原路退款。';
} elseif ($status === 'refunded') {
$description = '账单记录为已退款,但现有记录不足以确认退款去向或具体时间,请人工核对。';
} elseif (in_array($financialStatus, ['expired', 'void'], true)) {
$description = '失效或作废表示账单不可继续支付;这个状态本身不表示发生过扣款或退款。';
}
$retainedCount = max(0, (int) ($retained?->retained_count ?? 0));
$notes = ['此处汇总该账单的现有业务记录,不是完整账户余额变动流水,也不表示用户当前余额。'];
if ($retainedCount > 0) {
$notes[] = '存在已到账但未由该次付款结清目标账单、因而留在账户余额的款项;这不是账单退款,现有记录未保存具体留存原因。';
}
if ($refundAmount !== null && $refundAmount !== self::money($invoice->amount)) {
$notes[] = '关联订单记录的退款金额与账单面额不同,请核对历史记录。';
}
if ($truncated) {
$notes[] = '下方仅展示最近 100 条支付记录;留存余额金额按该账单全部关联支付记录汇总。';
}
return [
'title' => $title, 'description' => $description,
'settled_amount' => $paid ? self::money($invoice->amount) : null,
'refund_amount' => $refundAmount,
'refund_destination' => $refundedAt === null ? null : 'balance',
'refunded_at' => $refundedAt,
'balance_retained_amount' => self::money($retained?->retained_amount ?? '0'),
'balance_retained_count' => $retainedCount,
'payment_records_truncated' => $truncated, 'notes' => $notes,
];
}
/** Only dedicated timestamps imply events; updated_at means last update. */
private static function timeline($invoice, $order, $job, array $payments,
string $financialStatus): array
{
$events = [[
'kind' => 'invoice_created', 'title' => '账单创建',
'description' => '创建账单 #' . $invoice->id . ',不表示已付款。',
'at' => self::recordedTime($invoice->created_at),
]];
if (self::recordedTime($invoice->paid_at) !== null || (string) $invoice->status === 'paid') {
$events[] = ['kind' => 'invoice_paid', 'title' => '账单结清',
'description' => (string) $invoice->paid_via === 'balance'
? '使用账户余额结清账单。' : '记录已结清账单,原支付渠道见账单概览。',
'at' => self::recordedTime($invoice->paid_at)];
}
if ((string) $invoice->status === 'refunded') {
$at = (string) $invoice->purpose === 'provision' && $order !== null
? self::recordedTime($order->refunded_at) : null;
$events[] = ['kind' => 'invoice_refunded',
'title' => $at === null ? '账单当前标记已退款' : '开通款项退回余额',
'description' => $at === null ? '没有可确认退款时间及去向的独立记录。'
: '关联开通订单记录款项退回账户余额;不是网关原路退款。',
'at' => $at];
} elseif (in_array($financialStatus, ['expired', 'void'], true)) {
$events[] = ['kind' => 'invoice_closed',
'title' => $financialStatus === 'void' ? '账单当前已作废' : '账单当前已失效',
'description' => '此状态不是退款记录;未保存独立的状态变更时间。', 'at' => null];
}
if ($job !== null) {
$labels = ['queued' => '排队中', 'running' => '执行中', 'uncertain' => '待核对',
'succeeded' => '已完成', 'failed' => '失败'];
$events[] = ['kind' => 'job_updated', 'title' => '开通任务最近更新',
'description' => '任务 #' . $job->id . ',当前状态:'
. ($labels[(string) $job->status] ?? '其他状态') . '。此时间不是完整的任务事件历史。',
'at' => self::recordedTime($job->updated_at)];
}
$outcomes = ['creating' => '支付订单创建中', 'pending' => '等待支付结果',
'failed' => '支付记录失败', 'paid_invoice' => '该次付款已用于结清账单',
'credited_balance' => '该次款项留在账户余额,不属于账单退款'];
foreach ($payments as $payment) {
$events[] = ['kind' => 'payment_updated', 'title' => '在线支付记录最近更新',
'description' => '支付记录 #' . $payment->id . ':'
. ($outcomes[(string) $payment->status] ?? '其他状态')
. '。此时间来自记录更新时间,不代表网关实际到账时间。',
'at' => self::recordedTime($payment->updated_at)];
}
usort($events, static function (array $left, array $right): int {
if ($left['at'] === null || $right['at'] === null) {
return $left['at'] === $right['at'] ? 0 : ($left['at'] === null ? 1 : -1);
}
return $left['at'] <=> $right['at'];
});
return $events;
}
private static function links($invoice, $instance, array $users): array
{
$user = self::recordById($users, $invoice->user_id);
$uuid = $instance === null ? '' : (string) $instance->uuid;
$visibleInstance = $instance !== null && (string) $instance->status !== 'deleted'
&& self::sameIdentifier($instance->user_id, $invoice->user_id)
&& preg_match('/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iD', $uuid) === 1;
return [
'user' => $user !== null && AdminPermission::isSuperAdmin()
? '/admin/user/' . $invoice->user_id . '/edit' : null,
'instance' => $visibleInstance ? '/admin/cloud/instances?q=' . rawurlencode($uuid) : null,
'payments' => '/admin/billing?view=payments&invoice_id=' . $invoice->id,
];
}
private static function recordedTime($value): ?int
{
return $value !== null && (int) $value > 0 ? (int) $value : null;
}
public static function orders(array $input): array
{
$filters = self::orderFilters($input);
@ -607,7 +757,7 @@ final class CloudAdminBillingService
$invoiceInstanceIds, $orderInstanceIds
)));
$instances = self::keyed(CloudInstance::whereIn('id', $instanceIds)
->get(['id', 'user_id', 'plan_id', 'name', 'status',
->get(['id', 'uuid', 'user_id', 'plan_id', 'name', 'status',
'service_status', 'network_status', 'expires_at', 'spec_json'])
->all());
$planIds = array_values(array_unique(array_merge($planIds,

@ -59,7 +59,7 @@ 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,
loadedView: '', loadedFilters: {}, cache: new Map(), scroll: null,
};
function element(tag, className = '', text) {
@ -77,6 +77,7 @@ function firstText(...values) {
}
function formatUsd(value) {
if (value === null || value === undefined || value === '') return '—';
const amount = Number(value);
if (!Number.isFinite(amount)) return '—';
const sign = amount < 0 ? '-$' : '$';
@ -84,6 +85,7 @@ function formatUsd(value) {
}
function formatInteger(value) {
if (value === null || value === undefined || value === '') return '—';
const number = Number(value);
return Number.isFinite(number) ? Math.trunc(number).toLocaleString('zh-CN') : '—';
}
@ -102,7 +104,7 @@ function formatDate(value) {
function formatBytes(value) {
const bytes = Number(value);
if (!Number.isFinite(bytes) || bytes < 0) return '—';
if (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]}`;
@ -141,8 +143,9 @@ function statusInfo(kind, value) {
return table[status] || [status || '未记录', 'neutral'];
}
function statusBadge(kind, value) {
const [label, tone] = statusInfo(kind, value);
function statusBadge(kind, value, purpose = '') {
let [label, tone] = statusInfo(kind, value);
if (kind === 'fulfillment' && purpose === 'renewal' && ['active', 'succeeded', 'completed'].includes(value)) label = '已续费';
const badgeTone = {
success: 'bg-success-subtle text-success-emphasis',
warning: 'bg-warning-subtle text-warning-emphasis',
@ -180,7 +183,7 @@ function invoiceCells(item) {
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),
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, '账单详情'),
];
}
@ -232,6 +235,7 @@ function configureFilter(kind, definition) {
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);
@ -269,6 +273,7 @@ function configureReference(definition) {
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;
@ -333,6 +338,7 @@ function renderRows() {
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);
@ -368,7 +374,8 @@ function resetSummary(busy) {
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 = '—';
'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));
}
@ -383,6 +390,7 @@ function renderSummary(summary = {}) {
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 = '处理中 / 待核查';
@ -397,6 +405,7 @@ function renderSummary(summary = {}) {
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() {
@ -408,30 +417,11 @@ function renderPagination() {
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));
});
byId('billing-refresh').disabled = loading;
renderPagination();
}
@ -468,22 +458,35 @@ function activeFilters() {
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);
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) params.set(key, value);
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 ? 'pushState' : 'replaceState']({ billing: true }, '', target);
history[push && target !== location.pathname + location.search ? 'pushState' : 'replaceState'](historyData(), '', target);
}
function loadFiltersFromUrl() {
const params = new URLSearchParams(location.search);
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'));
@ -496,6 +499,15 @@ function loadFiltersFromUrl() {
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) {
@ -503,49 +515,87 @@ function apiError(payload, status) {
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 });
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) { location.assign('/auth/login'); throw new Error('登录已过期。'); }
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) {
const filters = activeFilters();
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);
resetSummary(true);
byId('billing-result-count').textContent = '读取中';
renderState('正在读取数据', '请稍候…');
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.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} 条`;
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');
if (updateUrl) writeUrl(false, filters);
writeUrl(updateUrl, 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');
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;
@ -555,7 +605,8 @@ async function loadList(updateUrl = true) {
}
function changeView(view, push = true) {
if (state.loading) return;
state.request?.abort();
state.requestNumber += 1;
if (!VIEWS[view]) view = 'invoices';
const changed = view !== state.view;
state.view = view;
@ -564,161 +615,303 @@ function changeView(view, push = true) {
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', 'row g-3 mb-0');
const list = element('dl', 'admin-instance-details');
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');
list.append(element('dt', '', label));
const description = element('dd');
if (value instanceof Node) description.append(value);
else description.textContent = String(value);
item.append(description);
list.append(item);
list.append(description);
}
return list;
}
function detailSection(title, pairs) {
const section = element('section', 'admin-report-card mb-3');
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 || {};
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}` : '')],
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)], ['支付渠道', providerLabel(invoice.payment_method)],
['创建时间', formatDate(invoice.created_at)], ['账单到期', formatDate(invoice.due_at)],
['支付截止', formatDate(invoice.payment_deadline_at)],
['履约状态', 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 || {};
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)],
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 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 条;完整记录请在“支付流水”中筛选此账单。'));
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 (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', 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 && invoice.purpose === 'provision') fulfillment.append(detailSection('引擎执行', [
['任务 ID', job.id ? '#' + job.id : ''], ['类型', ({ create: '创建实例', action: '电源操作', reinstall: '重装系统', rescue: '救援', delete: '删除实例' })[job.kind] || 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) 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_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) fulfillment.append(element('p', 'text-muted', '当前无可用关联实例或开通任务,历史账单仍保留。'));
}
if (!attempts.length) attemptsList.append(element('p', 'text-muted mb-0', '暂无支付尝试记录。'));
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 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);
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);
}
}
attemptsSection.append(attemptsList);
body.append(attemptsSection);
}
function closeDetail() {
function unlockDetail() {
const dialog = byId('billing-detail-dialog');
if (state.detailRequest) state.detailRequest.abort();
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 });
state.detailInvoiceId = '';
if (dialog.open) dialog.close();
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 closeDetail(updateUrl = true) {
const parent = history.state?.billingDetailParent;
unlockDetail();
if (!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) {
async function openDetail(invoiceId, opener = null, updateUrl = true) {
const id = String(invoiceId || '').trim();
if (!/^\d+$/.test(id)) return;
if (state.detailRequest) state.detailRequest.abort();
if (!/^[1-9][0-9]{0,18}$/.test(id)) return;
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();
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 mb-3';
detailState.className = 'alert alert-info';
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();
document.body.style.setProperty('--admin-instance-scroll-top', -state.scroll.y + 'px');
document.documentElement.classList.add('admin-instance-detail-open');
if (!dialog.open) dialog.showModal();
byId('billing-detail-close').focus({ preventScroll: true });
try {
const payload = await api(`/api/v1/admin/billing/invoices/${encodeURIComponent(id)}`, controller.signal);
if (state.detailInvoiceId !== id || !dialog.open) return;
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 (error?.name === 'AbortError') return;
if (state.detailRequest !== controller || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
detailState.hidden = false;
detailState.className = 'alert alert-danger mb-3';
detailState.className = 'alert alert-danger';
detailState.setAttribute('role', 'alert');
detailState.textContent = error?.message || '账单详情加载失败。';
const retry = element('button', 'btn btn-light btn-sm d-block mt-2', '重试详情');
retry.type = 'button';
retry.addEventListener('click', () => { void openDetail(id, null, false); });
detailState.append(retry);
} 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.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
if (state.loading) return;
changeView(link.dataset.billingView, true);
if (link.dataset.billingView !== state.view) changeView(link.dataset.billingView, true);
});
});
byId('billing-filter-form').addEventListener('submit', event => {
@ -727,54 +920,72 @@ function bindEvents() {
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()) { event.currentTarget.reportValidity(); 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', () => {
byId('billing-filter-form').reset();
configureView();
state.page = 1;
state.perPage = 30;
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-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); }
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 += 1; void loadList(true); }
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('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 });
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', () => {
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);
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); }
});
}
@ -785,10 +996,22 @@ function initialize() {
configureView();
loadFiltersFromUrl();
bindEvents();
void loadList(true);
// Instance management links to this existing detail view by exact invoice ID.
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);
if (/^[1-9][0-9]{0,18}$/.test(linkedInvoice)) void openDetail(linkedInvoice, null, false);
}
initialize();

@ -933,44 +933,52 @@ html.admin-instance-detail-open body {
margin-top: 24px;
}
.admin-billing-dialog {
width: min(584px, calc(100vw - 24px));
max-width: none;
max-height: calc(100dvh - 24px);
margin: auto;
padding: 0;
overflow: visible;
border: 0;
border-radius: 10px;
background: transparent;
[data-admin-billing] .admin-billing-stat-value {
font-size: clamp(18px, 1.35vw, 26px);
line-height: 1.45;
overflow-wrap: anywhere;
}
.admin-billing-dialog::backdrop {
background: rgba(0, 8, 26, 0.46);
[data-admin-billing] .admin-billing-advanced summary {
cursor: pointer;
font-size: 13px;
}
.admin-billing-dialog-panel {
width: 100%;
max-height: calc(100dvh - 24px);
display: flex;
flex-direction: column;
overflow: hidden;
[data-admin-billing] [hidden] {
display: none !important;
}
.admin-billing-dialog-body {
min-width: 0;
min-height: 0;
overflow-y: auto;
overflow-wrap: anywhere;
[data-admin-billing-drawer] .admin-billing-timeline {
padding-left: 20px;
display: grid;
gap: 18px;
}
.admin-billing-dialog .admin-modal-close {
[data-admin-billing-drawer] .admin-modal-close {
width: 44px;
height: 44px;
}
body.billing-detail-open {
overflow: hidden;
@media (max-width: 575.98px) {
[data-admin-billing] .admin-billing-secondary {
display: none;
}
[data-admin-billing] .admin-billing-table tr {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0 12px;
}
[data-admin-billing] .admin-billing-table td:last-child,
[data-admin-billing] .admin-billing-table td[colspan] {
grid-column: 1 / -1;
}
[data-admin-billing] .admin-billing-table td {
min-width: 0;
overflow-wrap: anywhere;
}
}
.admin-toast {

@ -1,190 +1,91 @@
{assign var=admin_title value='账单系统'}
{assign var=admin_active value='billing'}
{include file='admin/static_header.tpl'}
{assign var=billing_view value=$billing_page.view|default:$billing_view|default:'invoices'}
{assign var=billing_filters value=$billing_page.filters|default:[]}
{assign var=billing_titles value=['invoices'=>'全部账单', 'orders'=>'开通任务', 'payments'=>'支付流水']}
{assign var=billing_financial value=[''=>'全部财务状态','open'=>'待支付','overdue'=>'已逾期','paid'=>'已支付','refunded'=>'已退款','expired'=>'已失效','void'=>'已作废']}
{assign var=billing_fulfillment value=[''=>'全部履约状态','awaiting_payment'=>'等待支付','queued'=>'已排队','pending'=>'待处理','running'=>'开通中','uncertain'=>'待人工核查','succeeded'=>'已开通','failed'=>'开通失败','expired'=>'已失效','refunded'=>'已退款','cancelled'=>'已取消']}
{assign var=billing_payment value=[''=>'全部支付状态','creating'=>'创建中','pending'=>'待支付','paid_invoice'=>'已入账单','credited_balance'=>'已入余额','failed'=>'支付失败']}
{assign var=billing_purpose value=[''=>'全部账单类型','provision'=>'实例开通','renewal'=>'实例续费','recharge'=>'余额充值']}
{assign var=billing_providers value=[''=>'全部支付渠道','balance'=>'账户余额','usdt'=>'USDT-TRC20','yipay_alipay'=>'易支付 · 支付宝','yipay_wxpay'=>'易支付 · 微信','paytaro'=>'Paytaro']}
{function name=billing_options options=[] selected=''}
{foreach $options as $value=>$label}<option value="{$value|escape}" {if $selected == $value}selected{/if}>{$label|escape}</option>{/foreach}
{/function}
<main data-admin-billing>
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column gap-3">
<div class="flex-grow-1">
<h1 class="fs-20 fw-semibold mb-1">账单系统</h1>
<p class="text-muted mb-0">统一查看账单、实例开通任务与支付流水,财务和履约状态互不混用。</p>
<p class="text-muted mb-0">集中核对账单、开通任务与支付记录,财务状态与履约状态分别展示。</p>
</div>
<div class="text-sm-end mt-2 mt-sm-0 admin-checkout-actions">
<span class="admin-config-status is-loading" id="billing-notice" role="status" aria-live="polite">正在读取账单数据…</span>
<button class="btn btn-light" id="billing-refresh" type="button">
<i class="mdi mdi-refresh me-1" aria-hidden="true"></i>刷新
</button>
<div class="admin-checkout-actions">
<span class="admin-config-status {if $billing_error|default:''}is-error{else}is-success{/if}" id="billing-notice" role="status" aria-live="polite">{if $billing_error|default:''}{$billing_error|escape}{else}已读取 {$billing_page.pagination.total|default:0|escape} 条{/if}</span>
<button class="btn btn-light" id="billing-refresh" type="button"><i class="mdi mdi-refresh me-1" aria-hidden="true"></i>刷新</button>
</div>
</div>
<nav class="admin-ticket-tabs mb-3" aria-label="账单视图">
<a href="/admin/billing" data-billing-view="invoices" aria-current="page">全部账单</a>
<a href="/admin/billing?view=orders" data-billing-view="orders">开通任务</a>
<a href="/admin/billing?view=payments" data-billing-view="payments">支付流水</a>
{foreach $billing_titles as $view=>$label}<a href="/admin/billing{if $view != 'invoices'}?view={$view|escape}{/if}" data-billing-view="{$view|escape}" {if $billing_view == $view}aria-current="page"{/if}>{$label|escape}</a>{/foreach}
</nav>
<section class="row g-3 mb-3 admin-billing-summary" id="billing-summary" aria-label="当前视图摘要" aria-busy="true">
<div class="col-md-6 col-xxl-3">
<article class="card overflow-hidden admin-stat-card admin-billing-stat">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between gap-3">
<div class="admin-billing-stat-copy">
<h2 class="text-muted fs-14 fw-normal mb-1">记录总数</h2>
<strong class="admin-stat-value admin-billing-stat-value d-block mb-0" id="billing-summary-total">—</strong>
</div>
<span class="admin-stat-icon text-primary"><i class="mdi mdi-file-document-multiple-outline" aria-hidden="true"></i></span>
</div>
</div>
</article>
</div>
<div class="col-md-6 col-xxl-3">
<article class="card overflow-hidden admin-stat-card admin-billing-stat">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between gap-3">
<div class="admin-billing-stat-copy">
<h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-amount-label">总金额</h2>
<strong class="admin-stat-value admin-billing-stat-value d-block mb-0" id="billing-summary-amount">—</strong>
</div>
<span class="admin-stat-icon text-success"><i class="mdi mdi-currency-usd" aria-hidden="true"></i></span>
</div>
</div>
</article>
</div>
<div class="col-md-6 col-xxl-3">
<article class="card overflow-hidden admin-stat-card admin-billing-stat">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between gap-3">
<div class="admin-billing-stat-copy">
<h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-focus-label">待处理</h2>
<strong class="admin-stat-value admin-billing-stat-value d-block mb-0" id="billing-summary-focus">—</strong>
</div>
<span class="admin-stat-icon text-warning"><i class="mdi mdi-alert-circle-outline" aria-hidden="true"></i></span>
</div>
</div>
</article>
</div>
<div class="col-md-6 col-xxl-3">
<article class="card overflow-hidden admin-stat-card admin-billing-stat">
<div class="card-body">
<div class="d-flex align-items-center justify-content-between gap-3">
<div class="admin-billing-stat-copy">
<h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-result-label">已完成</h2>
<strong class="admin-stat-value admin-billing-stat-value d-block mb-0" id="billing-summary-result">—</strong>
</div>
<span class="admin-stat-icon text-success"><i class="mdi mdi-check-circle-outline" aria-hidden="true"></i></span>
</div>
</div>
</article>
</div>
<section class="row g-3 mb-3 admin-billing-summary" id="billing-summary" aria-label="当前筛选摘要" aria-busy="false">
{include file='admin/billing_summary.tpl'}
</section>
<section class="card mb-3 admin-billing-filter" aria-labelledby="billing-filter-title">
<div class="card-header">
<h2 class="h5 card-title mb-1" id="billing-filter-title">筛选条件</h2>
<span class="text-muted fs-13">缩小数据范围后再对账;清空条件可恢复默认列表。</span>
<div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
<div><h2 class="h5 card-title mb-1" id="billing-filter-title">筛选条件</h2><span class="text-muted fs-13">统计基于当前筛选,支付尝试金额不代表实际收入。</span></div>
<div class="d-flex gap-2 flex-wrap" aria-label="常用筛选"><button class="btn btn-light btn-sm" type="button" data-billing-preset="uncertain">待核对</button><button class="btn btn-light btn-sm" type="button" data-billing-preset="failed">开通失败</button><button class="btn btn-light btn-sm" type="button" data-billing-preset="refunded">已退款</button></div>
</div>
<div class="card-body">
<form id="billing-filter-form" class="row g-2 align-items-end">
<label class="col-xl-4 col-lg-6" for="billing-query">
<span class="form-label d-block">关键词</span>
<input class="form-control" id="billing-query" name="q" type="search" maxlength="80"
placeholder="账单 / 订单 / 套餐 / 用户 ID">
<form id="billing-filter-form" class="row g-2 align-items-end" method="get" action="/admin/billing" novalidate>
<input type="hidden" name="view" id="billing-view-input" value="{$billing_view|escape}">
<label class="col-xl-4 col-lg-6" for="billing-query"><span class="form-label d-block">关键词</span><input class="form-control" id="billing-query" name="q" type="search" maxlength="80" value="{$billing_filters.q|default:''|escape}" placeholder="账单 / 订单 / 套餐 / 用户 ID"></label>
<label class="col-xl-2 col-lg-3 col-6" for="billing-user-id"><span class="form-label d-block">用户 ID</span><input class="form-control" id="billing-user-id" name="user_id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20" value="{$billing_filters.user_id|default:''|escape}" placeholder="全部用户"></label>
<label class="col-xl-3 col-lg-3 col-6" for="billing-status-primary" id="billing-status-primary-field"><span class="form-label d-block" id="billing-status-primary-label">{if $billing_view == 'invoices'}财务状态{elseif $billing_view == 'orders'}履约状态{else}支付状态{/if}</span>
<select class="form-select" id="billing-status-primary" name="{if $billing_view == 'invoices'}financial_status{else}status{/if}">{if $billing_view == 'invoices'}{billing_options options=$billing_financial selected=$billing_filters.financial_status|default:''}{elseif $billing_view == 'orders'}{billing_options options=$billing_fulfillment selected=$billing_filters.status|default:''}{else}{billing_options options=$billing_payment selected=$billing_filters.status|default:''}{/if}</select>
</label>
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-user-id">
<span class="form-label d-block">用户 ID</span>
<input class="form-control" id="billing-user-id" name="user_id" type="text"
inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20" placeholder="全部用户">
<label class="col-xl-3 col-lg-4 col-6" for="billing-status-secondary" id="billing-status-secondary-field" {if $billing_view == 'payments'}hidden{/if}><span class="form-label d-block" id="billing-status-secondary-label">{if $billing_view == 'orders'}财务状态{else}履约状态{/if}</span>
<select class="form-select" id="billing-status-secondary" name="{if $billing_view == 'orders'}financial_status{else}fulfillment_status{/if}" {if $billing_view == 'payments'}disabled{/if}>{if $billing_view == 'orders'}{billing_options options=$billing_financial selected=$billing_filters.financial_status|default:''}{else}{billing_options options=$billing_fulfillment selected=$billing_filters.fulfillment_status|default:''}{/if}</select>
</label>
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-status-primary" id="billing-status-primary-field">
<span class="form-label d-block" id="billing-status-primary-label">财务状态</span>
<select class="form-select" id="billing-status-primary"></select>
</label>
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-status-secondary" id="billing-status-secondary-field">
<span class="form-label d-block" id="billing-status-secondary-label">履约状态</span>
<select class="form-select" id="billing-status-secondary"></select>
</label>
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-category" id="billing-category-field">
<span class="form-label d-block" id="billing-category-label">账单类型</span>
<select class="form-select" id="billing-category"></select>
</label>
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-reference-select" id="billing-reference-field">
<span class="form-label d-block" id="billing-reference-label">支付渠道</span>
<select class="form-select" id="billing-reference-select"></select>
<input class="form-control" id="billing-reference-input" type="text"
inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20"
placeholder="全部账单" hidden disabled>
</label>
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-created-from">
<span class="form-label d-block">开始日期</span>
<input class="form-control" id="billing-created-from" name="created_from" type="date">
</label>
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-created-to">
<span class="form-label d-block">结束日期</span>
<input class="form-control" id="billing-created-to" name="created_to" type="date">
</label>
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-per-page">
<span class="form-label d-block">每页条数</span>
<select class="form-select" id="billing-per-page" name="per_page">
<option value="30">30 条</option>
<option value="50">50 条</option>
<option value="100">100 条</option>
</select>
</label>
<div class="col-xl-4 col-lg-6 col-12 admin-form-actions admin-billing-filter-actions mt-0">
<button class="btn btn-primary" id="billing-apply" type="submit">应用筛选</button>
<button class="btn btn-light" id="billing-reset" type="button">清空条件</button>
</div>
<details class="col-12 admin-billing-advanced" id="billing-advanced">
<summary class="text-primary py-2">更多筛选:类型、渠道、日期和每页条数</summary>
<div class="row g-2 align-items-end pt-2">
<label class="col-lg-3 col-6" for="billing-category" id="billing-category-field" {if $billing_view == 'orders'}hidden{/if}><span class="form-label d-block" id="billing-category-label">{if $billing_view == 'payments'}支付渠道{else}账单类型{/if}</span><select class="form-select" id="billing-category" name="{if $billing_view == 'payments'}provider{else}purpose{/if}" {if $billing_view == 'orders'}disabled{/if}>{if $billing_view == 'payments'}{billing_options options=$billing_providers selected=$billing_filters.provider|default:''}{else}{billing_options options=$billing_purpose selected=$billing_filters.purpose|default:''}{/if}</select></label>
<label class="col-lg-3 col-6" for="{if $billing_view == 'payments'}billing-reference-input{else}billing-reference-select{/if}" id="billing-reference-field" {if $billing_view == 'orders'}hidden{/if}><span class="form-label d-block" id="billing-reference-label">{if $billing_view == 'payments'}账单 ID{else}支付渠道{/if}</span><select class="form-select" id="billing-reference-select" name="payment_method" {if $billing_view != 'invoices'}hidden disabled{/if}>{billing_options options=$billing_providers selected=$billing_filters.payment_method|default:''}</select><input class="form-control" id="billing-reference-input" name="invoice_id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20" value="{$billing_filters.invoice_id|default:''|escape}" placeholder="全部账单" {if $billing_view != 'payments'}hidden disabled{/if}></label>
<label class="col-lg-2 col-6" for="billing-created-from"><span class="form-label d-block">开始日期</span><input class="form-control" id="billing-created-from" type="date" value="{if $billing_filters.created_from|default:0}{$billing_filters.created_from|date_format:'%Y-%m-%d'|escape}{/if}"></label>
<label class="col-lg-2 col-6" for="billing-created-to"><span class="form-label d-block">结束日期</span><input class="form-control" id="billing-created-to" type="date" value="{if $billing_filters.created_to|default:0}{$billing_filters.created_to|date_format:'%Y-%m-%d'|escape}{/if}"></label>
<label class="col-lg-2 col-6" for="billing-per-page"><span class="form-label d-block">每页条数</span><select class="form-select" id="billing-per-page" name="per_page">{foreach [30,50,100] as $size}<option value="{$size}" {if $billing_page.pagination.per_page|default:30 == $size}selected{/if}>{$size} 条</option>{/foreach}</select></label>
</div>
</details>
<div class="col-12 admin-form-actions admin-billing-filter-actions mt-2"><button class="btn btn-primary" id="billing-apply" type="submit">应用筛选</button><button class="btn btn-light" id="billing-reset" type="button">清空条件</button></div>
</form>
</div>
</section>
<section class="card" id="billing-panel" aria-labelledby="billing-view-heading">
<div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-2">
<div>
<h2 class="h5 card-title mb-1" id="billing-view-heading">全部账单</h2>
<span class="text-muted fs-13" id="billing-view-description">按财务状态与履约状态核对每一笔账单。</span>
</div>
<span class="badge text-bg-light" id="billing-result-count" aria-live="polite">读取中</span>
<div><h2 class="h5 card-title mb-1" id="billing-view-heading">{$billing_titles[$billing_view]|escape}</h2><span class="text-muted fs-13" id="billing-view-description">财务状态、履约状态与支付尝试分别核对。</span></div>
<span class="badge text-bg-light" id="billing-result-count" aria-live="polite">{if $billing_page}本页 {$billing_page.items|count} 条 · 共 {$billing_page.pagination.total|escape} 条{else}数据未获取{/if}</span>
<p class="text-muted fs-12 mb-0 w-100" id="billing-shown-filters">下列记录对应当前筛选条件。</p>
</div>
<div class="card-body">
<div class="table-responsive admin-checkout-table-wrap">
<table class="table table-hover align-middle mb-0 admin-checkout-table admin-billing-table" id="billing-table">
<caption class="visually-hidden" id="billing-table-caption">管理员账单列表</caption>
<thead id="billing-table-head"></thead>
<tbody id="billing-table-body">
<tr><td class="text-center text-muted py-4">正在加载…</td></tr>
</tbody>
</table>
</div>
<nav class="admin-user-pagination" id="billing-pagination" aria-label="账单列表分页" hidden>
<button class="btn btn-light" id="billing-previous" type="button">
<i class="mdi mdi-chevron-left me-1" aria-hidden="true"></i>上一页
</button>
<span id="billing-page-label">第 1 / 1 页</span>
<button class="btn btn-light" id="billing-next" type="button">
下一页<i class="mdi mdi-chevron-right ms-1" aria-hidden="true"></i>
</button>
<div class="table-responsive admin-checkout-table-wrap"><table class="table table-hover align-middle mb-0 admin-checkout-table admin-billing-table" id="billing-table"><caption class="visually-hidden" id="billing-table-caption">管理员账单列表</caption>
{include file='admin/billing_rows.tpl'}
</table></div>
<nav class="admin-user-pagination" id="billing-pagination" aria-label="账单列表分页" {if !$billing_page || !$billing_page.pagination.total}hidden{/if}>
<button class="btn btn-light" id="billing-previous" type="button" {if !$billing_page || !$billing_page.pagination.has_previous}disabled{/if}>上一页</button>
<span id="billing-page-label">第 {$billing_page.pagination.page|default:1|escape} / {$billing_page.pagination.total_pages|default:1|escape} 页 · 共 {$billing_page.pagination.total|default:0|escape} 条</span>
<button class="btn btn-light" id="billing-next" type="button" {if !$billing_page || !$billing_page.pagination.has_next}disabled{/if}>下一页</button>
</nav>
</div>
</section>
<noscript><p class="alert alert-warning mt-3">此页需要 JavaScript 才能读取账单数据。</p></noscript>
<noscript><p class="alert alert-info mt-3">已显示数据库账单快照。启用 JavaScript 后可查看详情、分页及日期筛选。</p></noscript>
</main>
<dialog class="admin-billing-dialog" id="billing-detail-dialog" aria-labelledby="billing-detail-title">
<div class="admin-modal-panel admin-billing-dialog-panel">
<header class="d-flex align-items-start justify-content-between gap-3 pb-3">
<div>
<p class="admin-eyebrow mb-1">Invoice detail</p>
<h2 class="h3 fw-bold text-dark mb-0" id="billing-detail-title">账单详情</h2>
</div>
<button class="admin-modal-close position-static flex-shrink-0" id="billing-detail-close" type="button" aria-label="关闭账单详情">
<i class="mdi mdi-close" aria-hidden="true"></i>
</button>
</header>
<p class="alert alert-info mb-3" id="billing-detail-state" role="status" aria-live="polite">正在读取账单详情…</p>
<div class="admin-billing-dialog-body" id="billing-detail-body"></div>
<dialog data-admin-instance-drawer data-admin-billing-drawer id="billing-detail-dialog" aria-labelledby="billing-detail-title">
<header class="admin-instance-drawer-header"><div><p class="text-muted fs-13 mb-1">账单详情</p><h2 class="h4 fw-semibold mb-0" id="billing-detail-title">账单</h2></div><button class="admin-modal-close position-static flex-shrink-0" id="billing-detail-close" type="button" aria-label="关闭账单详情" autofocus><i class="mdi mdi-close" aria-hidden="true"></i></button></header>
<div class="admin-instance-drawer-body"><p class="alert alert-info" id="billing-detail-state" role="status" aria-live="polite">正在读取账单详情…</p>
<div class="admin-instance-tabs" role="tablist" aria-label="账单详情分类">{foreach ['overview'=>'账单概览','funds'=>'资金记录','fulfillment'=>'履约信息','payments'=>'支付记录'] as $tab=>$label}<button class="btn btn-light" type="button" id="billing-tab-{$tab}" data-billing-tab="{$tab}" role="tab" aria-controls="billing-panel-{$tab}" aria-selected="{if $tab == 'overview'}true{else}false{/if}" tabindex="{if $tab == 'overview'}0{else}-1{/if}">{$label}</button>{/foreach}</div>
<div id="billing-detail-body">{foreach ['overview','funds','fulfillment','payments'] as $tab}<section id="billing-panel-{$tab}" role="tabpanel" aria-labelledby="billing-tab-{$tab}" tabindex="0" {if $tab != 'overview'}hidden{/if}></section>{/foreach}</div>
</div>
<footer class="admin-instance-drawer-footer"><span class="text-muted fs-12">只读核对,不会触发退款或重复执行开通。</span><div class="d-flex gap-2 flex-wrap" id="billing-detail-links"></div></footer>
</dialog>
<script id="admin-billing-bootstrap" type="application/json">{$billing_bootstrap_json|default:'null' nofilter}</script>
<script type="module" src="/cloud/admin-billing.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -0,0 +1,29 @@
{assign var=billing_columns value=['账单','用户','项目','金额','财务状态','履约状态','支付渠道','时间','详情']}
{if $billing_view == 'orders'}{assign var=billing_columns value=['任务','用户','套餐 / 宿主机','金额','财务状态','履约状态','实例 / 引擎任务','更新 / 异常','账单']}{/if}
{if $billing_view == 'payments'}{assign var=billing_columns value=['支付流水','用户','支付渠道','金额','支付状态','账单财务状态','用途','时间','账单']}{/if}
{function name=billing_badge value='' kind='financial' purpose=''}
{assign var=labels value=$billing_financial}
{if $kind == 'fulfillment'}{assign var=labels value=$billing_fulfillment}{elseif $kind == 'payment'}{assign var=labels value=$billing_payment}{/if}
{assign var=tone value='light text-dark'}
{if in_array($value,['paid','succeeded','paid_invoice','credited_balance'])}{assign var=tone value='success-subtle text-success-emphasis'}{elseif in_array($value,['failed','uncertain','overdue'])}{assign var=tone value='danger-subtle text-danger-emphasis'}{elseif in_array($value,['open','pending','queued','awaiting_payment'])}{assign var=tone value='warning-subtle text-warning-emphasis'}{elseif in_array($value,['refunded','running','creating'])}{assign var=tone value='info-subtle text-info-emphasis'}{/if}
<span class="badge rounded-pill fs-12 px-2 py-1 bg-{$tone|escape}">{if $kind == 'fulfillment' && $purpose == 'renewal' && $value == 'succeeded'}已续费{elseif !$value}不适用{else}{$labels[$value]|default:$value|escape}{/if}</span>
{/function}
<thead id="billing-table-head"><tr>{foreach $billing_columns as $column}<th scope="col">{$column|escape}</th>{/foreach}</tr></thead>
<tbody id="billing-table-body">
{foreach $billing_page.items|default:[] as $item}
{assign var=purpose_key value=$item.purpose|default:''}
{assign var=provider_key value=$item.provider|default:''}
{assign var=method_key value=$item.payment_method|default:''}
<tr>
<td data-label="{$billing_columns[0]|escape}"><span class="admin-checkout-user"><strong>#{$item.id|escape}</strong><span>{if $billing_view == 'invoices'}{$billing_purpose[$purpose_key]|default:$purpose_key|escape}{elseif $billing_view == 'orders'}{if $item.job_id}引擎 #{$item.job_id|escape} · {/if}尝试 {$item.attempts|escape}{else}账单 #{$item.invoice_id|escape}{/if}</span></span></td>
<td data-label="用户"><span class="admin-checkout-user"><strong>{$item.user_name|default:$item.user_email|default:'用户'|escape}</strong><span>{if $item.user_name && $item.user_email}{$item.user_email|escape} · {/if}ID {$item.user_id|escape}</span></span></td>
<td data-label="{$billing_columns[2]|escape}" class="admin-billing-secondary"><span class="admin-checkout-user"><strong>{if $billing_view == 'payments'}{$billing_providers[$provider_key]|default:$provider_key|escape}{else}{$item.subject_name|default:$item.plan_name|default:'套餐未记录'|escape}{/if}</strong>{if $billing_view == 'orders'}<span>宿主机 #{$item.host_id|escape}</span>{elseif $billing_view == 'invoices' && $item.plan_id}<span>套餐 #{$item.plan_id|escape}</span>{/if}</span></td>
<td data-label="金额"><span class="admin-mono">${$item.amount|string_format:'%.2f'|escape}</span></td>
<td data-label="{$billing_columns[4]|escape}">{if $billing_view == 'payments'}{billing_badge kind='payment' value=$item.payment_status}{else}{billing_badge value=$item.financial_status}{/if}</td>
<td data-label="{$billing_columns[5]|escape}">{if $billing_view == 'payments'}{billing_badge value=$item.invoice_financial_status}{else}{billing_badge kind='fulfillment' value=$item.fulfillment_status purpose=$item.purpose|default:'provision'}{/if}</td>
<td data-label="{$billing_columns[6]|escape}" class="admin-billing-secondary">{if $billing_view == 'invoices'}{if $method_key}{$billing_providers[$method_key]|default:$method_key|escape}{else}未记录{/if}{elseif $billing_view == 'orders'}<span class="admin-checkout-user"><strong>{if $item.instance_id}实例 #{$item.instance_id|escape}{else}实例 —{/if}</strong><span>{if $item.job_id}任务 #{$item.job_id|escape} · {$billing_fulfillment[$item.job_status]|default:$item.job_status|escape}{else}引擎任务 —{/if}</span></span>{else}{if $purpose_key}{$billing_purpose[$purpose_key]|default:$purpose_key|escape}{else}未分类{/if}{/if}</td>
<td data-label="{$billing_columns[7]|escape}" class="admin-billing-secondary"><span class="admin-checkout-user"><strong>{if $billing_view == 'orders' && $item.updated_at}{$item.updated_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}{elseif $item.created_at}{$item.created_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}{else}—{/if}</strong>{if $billing_view == 'orders' && $item.error}<span>{$item.error|escape}</span>{elseif $billing_view == 'invoices' && $item.due_at}<span>到期 {$item.due_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}</span>{elseif $billing_view == 'payments' && $item.updated_at}<span>更新 {$item.updated_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}</span>{/if}</span></td>
<td data-label="{$billing_columns[8]|escape}">{assign var=detail_id value=$item.invoice_id|default:''}{if $billing_view == 'invoices'}{assign var=detail_id value=$item.id}{/if}{if $detail_id}<button class="btn btn-primary btn-sm" type="button" data-invoice-id="{$detail_id|escape}" aria-label="查看账单 {$detail_id|escape} 详情">账单详情</button>{else}—{/if}</td>
</tr>
{foreachelse}<tr><td colspan="9" class="text-center text-muted py-4">{if $billing_error|default:''}账单数据暂不可用,请点击刷新重试。{else}暂无匹配记录,请调整筛选条件。{/if}</td></tr>{/foreach}
</tbody>

@ -0,0 +1,10 @@
{assign var=billing_summary value=$billing_page.summary|default:[]}
{assign var=billing_counts value=$billing_summary.status_counts|default:[]}
{assign var=billing_processing value=0}
{if $billing_view == 'orders'}{foreach ['awaiting_payment','queued','pending','running','uncertain'] as $status}{assign var=billing_count value=$billing_counts[$status]|default:0}{assign var=billing_processing value=$billing_processing+$billing_count}{/foreach}{/if}
{if $billing_view == 'payments'}{foreach ['creating','pending'] as $status}{assign var=billing_count value=$billing_counts[$status]|default:0}{assign var=billing_processing value=$billing_processing+$billing_count}{/foreach}{/if}
<div class="col-6 col-xl"><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1">记录总数</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-total">{if $billing_page}{$billing_summary.total_records|escape}{else}—{/if}</strong></div></article></div>
<div class="col-6 col-xl"><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-amount-label">{if $billing_view == 'invoices'}账单面额{elseif $billing_view == 'orders'}任务关联金额{else}支付尝试金额{/if}</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-amount">{if $billing_page}${$billing_summary.total_amount|string_format:'%.2f'|escape}{else}—{/if}</strong></div></article></div>
<div class="col-6 col-xl"><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-focus-label">{if $billing_view == 'invoices'}待收款{elseif $billing_view == 'orders'}处理中 / 待核查{else}处理中{/if}</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-focus">{if !$billing_page}—{elseif $billing_view == 'invoices'}{$billing_summary.outstanding_count|escape} 笔 · ${$billing_summary.outstanding_amount|string_format:'%.2f'|escape}{else}{$billing_processing|escape} 笔{/if}</strong></div></article></div>
<div class="col-6 col-xl"><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-result-label">{if $billing_view == 'invoices'}已支付{elseif $billing_view == 'orders'}已开通 / 失败{else}入账去向{/if}</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-result">{if !$billing_page}—{elseif $billing_view == 'invoices'}{$billing_summary.paid_count|escape} 笔 · ${$billing_summary.paid_amount|string_format:'%.2f'|escape}{elseif $billing_view == 'orders'}{$billing_counts.succeeded|default:0|escape} / {$billing_counts.failed|default:0|escape}{else}账单 ${$billing_summary.paid_invoice_amount|string_format:'%.2f'|escape} · 余额 ${$billing_summary.credited_balance_amount|string_format:'%.2f'|escape}{/if}</strong></div></article></div>
<div class="col-6 col-xl" id="billing-refund-card" {if $billing_view != 'invoices'}hidden{/if}><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1">已退款</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-refunded">{if $billing_page && $billing_view == 'invoices'}{$billing_summary.refunded_count|escape} 笔 · ${$billing_summary.refunded_amount|string_format:'%.2f'|escape}{else}—{/if}</strong></div></article></div>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026093005' scope='global'}
{assign var=venix_asset_version value='2026093006' scope='global'}

@ -0,0 +1,200 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
if ((error_reporting() & $severity) && ($severity & (E_WARNING | E_USER_WARNING))) {
throw new ErrorException($message, 0, $severity, $file, $line);
}
return false;
});
// Non-production records shared by the rendering test and the local browser preview.
$now = time();
$common = ['user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test',
'plan_id' => '3', 'plan_name' => '标准云服务器', 'subject_name' => 'vm-production',
'amount' => '10.00', 'payment_method' => 'balance', 'due_at' => $now + 86400,
'paid_at' => $now - 3500, 'created_at' => $now - 3600, 'updated_at' => $now - 3400,
'order_id' => '301', 'job_id' => '501', 'instance_id' => '101', 'renewal_id' => null];
$invoices = [
array_replace($common, ['id' => '201', 'purpose' => 'provision', 'financial_status' => 'paid', 'fulfillment_status' => 'succeeded']),
array_replace($common, ['id' => '202', 'purpose' => 'provision', 'financial_status' => 'refunded', 'fulfillment_status' => 'failed', 'instance_id' => null]),
array_replace($common, ['id' => '203', 'purpose' => 'recharge', 'financial_status' => 'paid', 'fulfillment_status' => null,
'amount' => '100.00', 'plan_id' => null, 'plan_name' => '', 'subject_name' => '', 'order_id' => null,
'instance_id' => null, 'job_id' => null, 'payment_method' => 'yipay_alipay']),
array_replace($common, ['id' => '204', 'purpose' => 'renewal', 'financial_status' => 'paid', 'fulfillment_status' => 'succeeded', 'renewal_id' => '1', 'order_id' => null, 'job_id' => null]),
array_replace($common, ['id' => '205', 'purpose' => 'provision', 'financial_status' => 'expired', 'fulfillment_status' => 'expired',
'amount' => '100.00', 'paid_at' => null, 'payment_method' => null, 'order_id' => '305', 'job_id' => null, 'instance_id' => null]),
];
$orders = [[
'id' => '301', 'user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test',
'plan_id' => '3', 'plan_name' => '标准云服务器', 'host_id' => '7', 'amount' => '10.00',
'financial_status' => 'paid', 'fulfillment_status' => 'uncertain', 'invoice_id' => '201',
'job_id' => '501', 'job_status' => 'uncertain', 'instance_id' => '101', 'attempts' => 3,
'error' => '等待引擎核对操作结果', 'refunded_at' => null, 'created_at' => $now - 3600, 'updated_at' => $now - 60,
]];
$paymentBase = ['user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test',
'provider' => 'yipay_alipay', 'purpose' => 'provision', 'created_at' => $now - 3500, 'updated_at' => $now - 3400];
$payments = [
array_replace($paymentBase, ['id' => '701', 'invoice_id' => '201', 'amount' => '10.00', 'payment_status' => 'paid_invoice', 'invoice_financial_status' => 'paid']),
array_replace($paymentBase, ['id' => '702', 'invoice_id' => '205', 'amount' => '100.00', 'payment_status' => 'credited_balance', 'invoice_financial_status' => 'expired']),
];
$filters = ['page' => 1, 'per_page' => 30, 'q' => '', 'user_id' => null,
'created_from' => null, 'created_to' => null];
$viewFilters = [
'invoices' => ['financial_status' => '', 'fulfillment_status' => '', 'payment_method' => '', 'purpose' => ''],
'orders' => ['status' => '', 'financial_status' => ''],
'payments' => ['status' => '', 'provider' => '', 'invoice_id' => null],
];
$pages = [];
foreach (['invoices' => $invoices, 'orders' => $orders, 'payments' => $payments] as $view => $items) {
$pages[$view] = ['view' => $view, 'items' => $items, 'filters' => $filters + $viewFilters[$view],
'pagination' => ['page' => 1, 'per_page' => 30, 'total' => count($items), 'total_pages' => 1,
'has_previous' => false, 'has_next' => false], 'generated_at' => $now];
}
$pages['invoices']['summary'] = ['total_records' => 5, 'total_amount' => '230.00',
'outstanding_count' => 0, 'outstanding_amount' => '0.00', 'paid_count' => 3, 'paid_amount' => '120.00',
'refunded_count' => 1, 'refunded_amount' => '10.00'];
$pages['orders']['summary'] = ['total_records' => 1, 'total_amount' => '10.00', 'status_counts' => ['uncertain' => 1]];
$pages['payments']['summary'] = ['total_records' => 2, 'total_amount' => '110.00',
'paid_invoice_amount' => '10.00', 'credited_balance_amount' => '100.00',
'status_counts' => ['paid_invoice' => 1, 'credited_balance' => 1]];
$details = [];
foreach ($invoices as $row) {
$recharge = $row['purpose'] === 'recharge';
$refunded = $row['financial_status'] === 'refunded';
$expired = $row['financial_status'] === 'expired';
$detailInvoice = $row + ['validity_days' => $recharge ? 0 : 30,
'traffic_quota_bytes' => $recharge ? 0 : 107374182400,
'renews_expires_at' => $row['purpose'] === 'renewal' ? $now + 30 * 86400 : null,
'payment_deadline_at' => $now + 86400,
'specification' => $recharge ? [] : ['cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100]];
$details[$row['id']] = ['invoice' => $detailInvoice,
'order' => $row['order_id'] ? array_replace($orders[0], ['id' => $row['order_id'], 'invoice_id' => $row['id'],
'fulfillment_status' => $row['fulfillment_status'], 'refunded_at' => $refunded ? $now - 3300 : null]) : null,
'job' => $row['job_id'] ? ['id' => '501', 'kind' => 'create', 'status' => $row['fulfillment_status'],
'attempts' => 1, 'phase' => 'complete', 'error' => $refunded ? '实例创建失败,已确认清理' : null,
'created_at' => $now - 3500, 'updated_at' => $now - 3400] : null,
'instance' => $row['instance_id'] ? ['id' => '101', 'name' => 'vm-production', 'status' => 'active',
'service_status' => 'active', 'network_status' => 'active', 'expires_at' => $now + 30 * 86400] : null,
'payment_attempts' => $expired ? [$payments[1]] : [], 'payment_attempts_truncated' => false,
'funds' => ['title' => $refunded ? '已退回账户余额' : ($expired ? '款项保留在账户余额' : '账单已结清'),
'description' => $refunded ? '开通失败退款记入账户余额,不是原支付渠道原路退款。'
: ($expired ? '支付记录标记为已入余额,该次款项未结清目标账单。' : '款项已用于结清账单。'),
'settled_amount' => $expired ? null : $row['amount'], 'refund_amount' => $refunded ? $row['amount'] : null,
'refund_destination' => $refunded ? 'balance' : null, 'refunded_at' => $refunded ? $now - 3300 : null,
'balance_retained_amount' => $expired ? '100.00' : '0.00', 'balance_retained_count' => $expired ? 1 : 0,
'payment_records_truncated' => false, 'notes' => ['仅根据现有业务记录展示,不是完整钱包变动账本。']],
'timeline' => [['kind' => 'created', 'title' => '账单创建', 'description' => '已记录账单创建时间', 'at' => $row['created_at']]],
'links' => ['user' => '/admin/user/42/edit',
'instance' => $row['instance_id'] ? '/admin/cloud/instances?q=11111111-1111-4111-8111-111111111111' : null,
'payments' => '/admin/billing?view=payments&invoice_id=' . $row['id']],
];
if ($row['paid_at']) $details[$row['id']]['timeline'][] = ['kind' => 'paid', 'title' => '账单结清', 'description' => '账户余额支付', 'at' => $row['paid_at']];
if ($refunded) $details[$row['id']]['timeline'][] = ['kind' => 'refunded', 'title' => '退款退回余额', 'description' => '开通失败后退回账户余额', 'at' => $now - 3300];
}
$smarty = new Smarty();
$compileDir = sys_get_temp_dir() . '/admin-billing-view-' . bin2hex(random_bytes(6));
mkdir($compileDir);
$smarty->setCompileDir($compileDir);
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
$smarty->assign('config', ['appName' => 'Venix Test']);
$smarty->assign('cdn', '');
$smarty->assign('user', (object) ['isLogin' => false]);
$smarty->assign('admin_can_manage', true);
$smarty->assign('admin_csrf_token', 'fixture-not-a-real-token');
$render = static function (?array $payload, string $error = '', string $view = 'invoices') use ($smarty): string {
$smarty->assign('billing_page', $payload);
$smarty->assign('billing_view', $payload['view'] ?? $view);
$smarty->assign('billing_error', $error);
$smarty->assign('billing_bootstrap_json', json_encode($payload,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
| JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
return $smarty->fetch('admin/billing.tpl');
};
$assert = static function (bool $ok, string $message): void {
if (!$ok) throw new RuntimeException($message);
};
// Test-only input used by the local preview to exercise refresh/deep-link SSR.
foreach ($argv ?? [] as $arg) {
if (str_starts_with($arg, '--render-page=')) {
$payload = json_decode(base64_decode(substr($arg, 14), true), true, 512, JSON_THROW_ON_ERROR);
echo $render($payload);
exit;
}
}
$html = [];
foreach ($pages as $view => $page) $html[$view] = $render($page);
$failedHtml = $render(null, '账单数据暂不可用,请稍后重试');
if (in_array('--fixture', $argv ?? [], true)) {
echo json_encode(['html' => $html, 'failed_html' => $failedHtml, 'pages' => $pages, 'details' => $details],
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
exit;
}
$dom = new DOMDocument();
libxml_use_internal_errors(true);
foreach ($pages as $view => $page) {
$dom->loadHTML('<?xml encoding="UTF-8">' . $html[$view]);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//tbody[@id="billing-table-body"]/tr')->length === count($page['items']),
'Server-rendered rows missing for billing view: ' . $view);
$assert(str_contains($dom->textContent, '演示客户'), 'The first paint must contain meaningful account data.');
$assert($xpath->query('//dialog[@id="billing-detail-dialog" and @data-admin-instance-drawer]')->length === 1,
'Billing details must reuse the existing administrator instance drawer.');
}
$assert(str_contains($html['invoices'], '已续费'), 'Renewal completion must not be labelled instance provisioning.');
$dom->loadHTML('<?xml encoding="UTF-8">' . $html['invoices']);
$xpath = new DOMXPath($dom);
$assert(trim($xpath->query('//*[@id="billing-summary-result"]')->item(0)->textContent) === '3 笔 · $120.00'
&& trim($xpath->query('//*[@id="billing-summary-refunded"]')->item(0)->textContent) === '1 笔 · $10.00',
'SSR must show paid and refunded totals separately, without subtracting refunds a second time.');
$unsafe = $pages['invoices'];
$unsafe['items'][0]['subject_name'] = '</script><img src=x onerror=alert(1)>';
$unsafe['items'][0]['user_name'] = '<script>window.bad=1</script>';
$unsafe['filters']['q'] = '" autofocus onfocus="alert(2)';
$unsafeHtml = $render($unsafe);
$dom->loadHTML('<?xml encoding="UTF-8">' . $unsafeHtml);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//*[@onerror or @onfocus]')->length === 0
&& !str_contains($unsafeHtml, '<script>window.bad=1</script>'), 'Untrusted billing fields escaped into executable markup.');
$assert(str_contains($dom->textContent, '</script><img src=x onerror=alert(1)>'), 'Escaped names must remain visible text.');
$bootstrap = json_decode($xpath->query('//*[@id="admin-billing-bootstrap"]')->item(0)->textContent, true, 512, JSON_THROW_ON_ERROR);
$assert($bootstrap['items'][0]['subject_name'] === $unsafe['items'][0]['subject_name']
&& $bootstrap['filters']['q'] === $unsafe['filters']['q'], 'Safe bootstrap encoding changed the original data.');
foreach (['invoices' => ['financial_status', 'paid'], 'orders' => ['status', 'uncertain'],
'payments' => ['status', 'credited_balance']] as $view => [$key, $value]) {
$filtered = $pages[$view];
$filtered['filters'][$key] = $value;
$filtered['filters']['user_id'] = '42';
$filtered['pagination'] = ['page' => 2, 'per_page' => 50, 'total' => 80, 'total_pages' => 2,
'has_previous' => true, 'has_next' => false];
$dom->loadHTML('<?xml encoding="UTF-8">' . $render($filtered));
$xpath = new DOMXPath($dom);
$assert($xpath->query('//*[@id="billing-status-primary"]/option[@selected and @value="' . $value . '"]')->length === 1
&& $xpath->query('//*[@id="billing-per-page"]/option[@selected and @value="50"]')->length === 1
&& $xpath->query('//*[@id="billing-user-id" and @value="42"]')->length === 1
&& str_contains($xpath->query('//*[@id="billing-page-label"]')->item(0)->textContent, '第 2 / 2 页'),
'SSR discarded the active filter or page: ' . $view);
}
$empty = $pages['invoices'];
$empty['items'] = [];
$empty['pagination']['total'] = 0;
$empty['summary'] = array_fill_keys(array_keys($empty['summary']), 0);
$emptyHtml = $render($empty);
$assert(!str_contains($emptyHtml, 'vm-production'), 'Empty billing response retained an old record.');
$assert(str_contains($failedHtml, '账单数据暂不可用,请稍后重试')
&& !str_contains($failedHtml, 'vm-production'), 'Failed read was rendered as a successful old list.');
foreach (array_keys($pages) as $view) {
$failure = $render(null, '账单数据暂不可用,请稍后重试', $view);
$dom->loadHTML('<?xml encoding="UTF-8">' . $failure);
$xpath = new DOMXPath($dom);
$assert($xpath->query('//*[@data-billing-view="' . $view . '" and @aria-current="page"]')->length === 1,
'A failed snapshot must keep the requested view selected: ' . $view);
$assert(trim($xpath->query('//*[@id="billing-summary-total"]')->item(0)->textContent) === '—',
'A failed snapshot must not appear as zero financial records.');
$assert(json_decode($xpath->query('//*[@id="admin-billing-bootstrap"]')->item(0)->textContent, true, 512, JSON_THROW_ON_ERROR) === null,
'A failed snapshot must not bootstrap a successful list.');
}
echo "Administrator billing three-view SSR, shared drawer, escaping and empty/error rendering passed.\n";

@ -96,6 +96,10 @@ $assert = static function (bool $ok, string $message): void {
};
$html = $render($page);
if (in_array('--fixture', $argv ?? [], true)) {
$smarty->assign('billing_page', null);
$smarty->assign('billing_view', 'invoices');
$smarty->assign('billing_error', '账单预览未加载数据');
$smarty->assign('billing_bootstrap_json', 'null');
echo json_encode(['html' => $html, 'billing_html' => $smarty->fetch('admin/billing.tpl'),
'page' => $page, 'detail' => $detail],
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);

@ -0,0 +1,614 @@
<?php
namespace App\Services {
final class AdminPermission
{
public static bool $superAdmin = true;
public static function isSuperAdmin(): bool
{
return self::$superAdmin;
}
}
final class Auth
{
public static $user = null;
public static function getUser()
{
return self::$user;
}
}
}
namespace App\Services\Cloud {
final class CloudSessionService
{
public static int $calls = 0;
public static function current($user): string
{
self::$calls++;
throw new \RuntimeException('Read-only billing requested an engine session.');
}
}
final class CloudEngineClient
{
public static int $calls = 0;
public function __construct()
{
self::$calls++;
throw new \RuntimeException('Read-only billing contacted the private engine.');
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\User;
use App\Services\AdminPermission;
use App\Services\Auth;
use App\Services\Cloud\CloudAdminBillingService;
use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudSessionService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
use Slim\Http\Environment;
use Slim\Http\Request;
use Slim\Http\Response;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expectError = static function (callable $callback, int $status, string $message) use ($assert): void {
try {
$callback();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
$message . ': unexpected HTTP status ' . $error->httpStatus);
return;
}
throw new RuntimeException($message . ': request was accepted.');
};
$ids = static fn (array $rows): array => array_map('intval', array_column($rows, 'id'));
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
$table->string('user_name');
$table->string('email');
$table->boolean('is_admin')->default(false);
$table->boolean('enable')->default(true);
$table->string('money')->default('999.99');
$table->string('pass')->default('must-not-expose-account-password');
});
$schema->create('shop', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->string('uuid');
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->string('name');
$table->string('status')->default('active');
$table->string('service_status')->default('active');
$table->string('network_status')->default('active');
$table->integer('expires_at')->nullable();
$table->text('spec_json')->default('{}');
$table->text('credential_cipher')->default('must-not-expose-instance-credential');
});
$schema->create('cloud_orders', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('host_id')->default(7);
$table->string('amount')->default('1.25');
$table->string('status')->default('queued');
$table->text('spec_json')->default('{}');
$table->text('payload_cipher')->default('must-not-expose-order-payload');
$table->integer('instance_id')->nullable();
$table->integer('refunded_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id')->default('must-not-expose-operation-id');
$table->integer('order_id')->nullable();
$table->integer('instance_id')->nullable();
$table->integer('user_id');
$table->integer('host_id')->default(7);
$table->string('kind')->default('create');
$table->string('status')->default('running');
$table->integer('attempts')->default(1);
$table->string('error_code')->nullable();
$table->text('result_json')->nullable();
$table->text('payload_cipher')->default('must-not-expose-job-payload');
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->increments('id');
$table->string('invoice_no')->default('must-not-expose-invoice-number');
$table->string('purpose')->default('provision');
$table->integer('instance_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('renewal_id')->nullable();
$table->integer('renews_expires_at')->nullable();
$table->integer('due_at');
$table->string('amount')->default('1.25');
$table->integer('validity_days')->default(30);
$table->integer('traffic_quota_bytes')->default(107374182400);
$table->string('status')->default('paid');
$table->string('paid_via')->nullable();
$table->string('payment_reference')->default('must-not-expose-payment-reference');
$table->integer('paid_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_invoice_payments', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('invoice_id');
$table->integer('user_id');
$table->string('provider')->default('yipay_alipay');
$table->string('provider_order_no')->default('must-not-expose-provider-reference');
$table->string('idempotency_key')->default('must-not-expose-idempotency-key');
$table->string('amount')->default('1.25');
$table->string('status')->default('pending');
$table->integer('created_at');
$table->integer('updated_at');
});
$now = time();
Capsule::table('user')->insert([
['id' => 1, 'user_name' => 'Alice Finance', 'email' => 'alice@example.test'],
['id' => 2, 'user_name' => 'Bob Client', 'email' => 'bob@example.test'],
['id' => 3, 'user_name' => 'Foreign Owner', 'email' => 'foreign@example.test'],
['id' => 10, 'user_name' => 'Bulk Customer', 'email' => 'bulk@example.test'],
]);
Capsule::table('shop')->insert(['id' => 7, 'name' => 'Standard Cloud']);
$spec = json_encode([
'name' => 'production-vm', 'plan_name' => 'Historical Plan',
'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100,
'password' => 'must-not-expose-spec-password',
'unreviewed_note' => 'must-not-expose-unknown-spec-field',
]);
$insertInstance = static function (int $id, array $overrides = []) use ($now, $spec): void {
Capsule::table('cloud_instances')->insert(array_replace([
'id' => $id, 'user_id' => 1, 'plan_id' => 7, 'name' => 'vm-' . $id,
'uuid' => sprintf('11111111-1111-4111-8111-%012d', $id),
'expires_at' => $now + 30 * 86400, 'spec_json' => $spec,
], $overrides));
};
$insertOrder = static function (int $id, array $overrides = []) use ($now, $spec): void {
Capsule::table('cloud_orders')->insert(array_replace([
'id' => $id, 'user_id' => 1, 'plan_id' => 7, 'spec_json' => $spec,
'created_at' => $now - 1000, 'updated_at' => $now - 100,
], $overrides));
};
$insertJob = static function (int $id, array $overrides = []) use ($now): void {
Capsule::table('cloud_jobs')->insert(array_replace([
'id' => $id, 'user_id' => 1,
'created_at' => $now - 900, 'updated_at' => $now - 100,
'result_json' => json_encode([
'phase' => 'complete', 'password' => 'must-not-expose-job-password',
'unreviewed_note' => 'must-not-expose-unknown-job-field',
]),
], $overrides));
};
$insertInvoice = static function (int $id, array $overrides = []) use ($now): void {
Capsule::table('cloud_invoices')->insert(array_replace([
'id' => $id, 'user_id' => 1, 'plan_id' => 7,
'due_at' => $now + 3600, 'created_at' => $now - 1000, 'updated_at' => $now - 100,
], $overrides));
};
$insertPayment = static function (int $id, array $overrides = []) use ($now): void {
Capsule::table('cloud_invoice_payments')->insert(array_replace([
'id' => $id, 'invoice_id' => $id, 'user_id' => 1,
'created_at' => $now - 800, 'updated_at' => $now - 100,
], $overrides));
};
$insertInstance(501);
$insertInstance(502, ['status' => 'deleted']);
$insertOrder(101, ['instance_id' => 501, 'status' => 'succeeded', 'amount' => '100.00']);
$insertOrder(102, ['status' => 'failed', 'amount' => '30.00', 'refunded_at' => $now - 200]);
$insertOrder(103, ['status' => 'awaiting_payment', 'amount' => '40.00']);
$insertOrder(109, ['user_id' => 3, 'status' => 'refunded', 'refunded_at' => $now - 200]);
$insertOrder(110, ['user_id' => 3, 'status' => 'refunded', 'refunded_at' => $now - 200]);
$insertJob(201, ['order_id' => 101, 'instance_id' => 501, 'status' => 'succeeded']);
$insertJob(202, ['order_id' => 102, 'status' => 'failed', 'error_code' => 'provision_failed']);
// Financial state is independent from fulfilment and payment-attempt state.
$insertInvoice(1, ['order_id' => 101, 'instance_id' => 501,
'amount' => '100.00', 'status' => 'paid', 'paid_via' => 'balance', 'paid_at' => $now - 700]);
$insertInvoice(2, ['order_id' => 102, 'amount' => '30.00', 'status' => 'refunded',
'paid_via' => 'yipay_alipay', 'paid_at' => $now - 700]);
$insertInvoice(3, ['order_id' => 103, 'amount' => '40.00', 'status' => 'open']);
$insertInvoice(4, ['purpose' => 'renewal', 'instance_id' => 501,
'amount' => '50.00', 'status' => 'open', 'due_at' => $now - 60]);
$insertInvoice(5, ['purpose' => 'recharge', 'plan_id' => null, 'amount' => '60.00',
'status' => 'paid', 'paid_via' => 'yipay_wxpay', 'paid_at' => $now - 700]);
$insertInvoice(6, ['purpose' => 'renewal', 'instance_id' => 501, 'renewal_id' => 301,
'amount' => '20.00', 'status' => 'paid', 'paid_via' => 'balance', 'paid_at' => $now - 700]);
$insertInvoice(7, ['purpose' => 'recharge', 'plan_id' => null,
'amount' => '10.00', 'status' => 'expired', 'due_at' => $now - 4 * 86400]);
$insertInvoice(8, ['purpose' => 'renewal', 'instance_id' => 502,
'amount' => '80.00', 'status' => 'open', 'due_at' => $now - 60]);
$insertInvoice(9, ['user_id' => 2, 'order_id' => 109, 'instance_id' => 501]);
$insertInvoice(10, ['user_id' => 2, 'order_id' => 110, 'status' => 'refunded']);
$insertInvoice(11, ['user_id' => 404, 'purpose' => 'recharge', 'plan_id' => null, 'status' => 'open']);
foreach ([
1 => ['amount' => '100.00', 'status' => 'paid_invoice'],
2 => ['amount' => '30.00', 'status' => 'paid_invoice'],
3 => ['amount' => '40.00', 'status' => 'pending'],
4 => ['amount' => '50.00', 'status' => 'failed'],
5 => ['amount' => '60.00', 'status' => 'credited_balance', 'provider' => 'yipay_wxpay'],
6 => ['amount' => '20.00', 'status' => 'paid_invoice'],
7 => ['amount' => '10.00', 'status' => 'credited_balance'],
8 => ['invoice_id' => 3, 'amount' => '40.00', 'status' => 'creating'],
] as $id => $values) {
$insertPayment($id, $values);
}
$insertPayment(9, ['invoice_id' => 9, 'user_id' => 3, 'status' => 'credited_balance', 'amount' => '999.00']);
$insertInvoice(12, ['user_id' => 2, 'purpose' => 'recharge', 'plan_id' => null, 'status' => 'expired']);
for ($id = 6000; $id < 6105; $id++) {
$insertPayment($id, ['invoice_id' => 12, 'user_id' => 2,
'status' => 'credited_balance', 'amount' => '1.10']);
}
$insertPayment(6200, ['invoice_id' => 12, 'user_id' => 3,
'status' => 'credited_balance', 'amount' => '999.00']);
$insertInvoice(13, ['user_id' => 2, 'purpose' => 'recharge', 'plan_id' => null,
'status' => 'paid', 'amount' => '12.00', 'paid_at' => null]);
$insertOrder(114, ['user_id' => 2, 'status' => 'refunded',
'amount' => '9.00', 'refunded_at' => $now - 200]);
$insertInvoice(14, ['user_id' => 2, 'order_id' => 114,
'status' => 'refunded', 'amount' => '10.00', 'paid_at' => $now - 700]);
$insertInvoice(15, ['user_id' => 2, 'purpose' => 'renewal', 'instance_id' => 999999,
'status' => 'open', 'paid_at' => null]);
$insertInvoice(16, ['user_id' => 2, 'purpose' => 'renewal', 'instance_id' => 999999,
'status' => 'overdue', 'paid_at' => null]);
// More than one page for every view, with identical timestamps to require
// an ID tie-breaker and a complete summary independent of the visible page.
for ($offset = 0; $offset < 135; $offset++) {
$created = $offset === 0 ? $now - 2 * 86400 : $now - 100;
$insertInstance(3000 + $offset, ['user_id' => 10]);
$insertOrder(2000 + $offset, ['user_id' => 10, 'instance_id' => 3000 + $offset,
'status' => 'queued', 'created_at' => $created]);
$insertJob(4000 + $offset, ['user_id' => 10, 'order_id' => 2000 + $offset,
'instance_id' => 3000 + $offset, 'status' => 'running']);
$insertInvoice(1000 + $offset, ['user_id' => 10, 'order_id' => 2000 + $offset,
'instance_id' => 3000 + $offset, 'status' => 'paid', 'paid_at' => $now - 50,
'created_at' => $created]);
$insertPayment(5000 + $offset, ['user_id' => 10, 'invoice_id' => 1000 + $offset,
'created_at' => $created]);
}
// Exercise the real SQL implementation, including the existing invoice
// service's deadline calculation. Only authentication/infrastructure edges
// above are test doubles; no financial service or model is substituted.
$before = [];
foreach (['user', 'cloud_orders', 'cloud_jobs', 'cloud_invoices', 'cloud_invoice_payments'] as $table) {
$before[$table] = Capsule::table($table)->orderBy('id')->get()->toJson();
}
$queryCounts = [];
foreach (['invoices' => 1000, 'orders' => 2000, 'payments' => 5000] as $view => $baseId) {
$page = CloudAdminBillingService::page(['view' => $view, 'user_id' => '10']);
$assert($page['view'] === $view && $page['pagination']['total'] === 135
&& count($page['items']) === 30 && $page['summary']['total_records'] === 135
&& $page['summary']['total_amount'] === '168.75'
&& $ids($page['items']) === range($baseId + 134, $baseId + 105),
'Three-view page routing, full-population summary, or stable newest-first ordering failed: ' . $view);
$seen = [];
for ($number = 1; $number <= 2; $number++) {
$chunk = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '10', 'page' => (string) $number, 'per_page' => '100',
]);
$seen = array_merge($seen, $ids($chunk['items']));
}
$assert($seen === range($baseId + 134, $baseId),
'Pagination duplicated, omitted, or truncated billing records: ' . $view);
$last = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '10', 'page' => '9999', 'per_page' => '1000',
]);
$assert($last['pagination']['page'] === 2 && $last['pagination']['per_page'] === 100
&& count($last['items']) === 35, 'Pagination bounds were not enforced: ' . $view);
$dateFiltered = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '10',
'created_from' => (string) ($now - 100), 'created_to' => (string) ($now - 100),
]);
$assert($dateFiltered['pagination']['total'] === 134,
'Date filters must include their boundary and apply to the summary: ' . $view);
$empty = CloudAdminBillingService::page(['view' => $view, 'user_id' => '999999']);
$assert($empty['items'] === [] && $empty['pagination']['total'] === 0
&& $empty['pagination']['total_pages'] === 1 && $empty['summary']['total_amount'] === '0.00',
'Empty billing results reused old data or reported invalid totals: ' . $view);
$search = CloudAdminBillingService::page(['view' => $view, 'q' => 'bulk@example.test']);
$assert($search['pagination']['total'] === 135, 'Account search failed: ' . $view);
$quoted = CloudAdminBillingService::page(['view' => $view, 'q' => "' OR 1=1 --"]);
$assert($quoted['items'] === [], 'Quoted search escaped its SQL parameter: ' . $view);
$counts = [];
foreach ([30, 100] as $size) {
$connection = Capsule::connection('default');
$connection->flushQueryLog();
$connection->enableQueryLog();
CloudAdminBillingService::page(['view' => $view, 'user_id' => '10', 'per_page' => (string) $size]);
$queries = $connection->getQueryLog();
$connection->disableQueryLog();
$counts[] = count($queries);
foreach ($queries as $query) {
$assert(preg_match('/^\s*(select|with)\b/i', $query['query']) === 1,
'Billing list performed a write instead of a read: ' . $view);
}
}
$assert($counts[0] <= 12 && $counts[1] === $counts[0],
'Billing rows introduced N+1 queries: ' . $view . ' ' . implode('/', $counts));
$queryCounts[$view] = $counts;
}
$ledger = CloudAdminBillingService::page(['user_id' => '1']);
$assert($ledger['view'] === 'invoices' && $ledger['summary']['total_records'] === 8
&& $ledger['summary']['total_amount'] === '390.00'
&& $ledger['summary']['paid_count'] === 3 && $ledger['summary']['paid_amount'] === '180.00'
&& $ledger['summary']['refunded_count'] === 1 && $ledger['summary']['refunded_amount'] === '30.00'
&& $ledger['summary']['outstanding_count'] === 2 && $ledger['summary']['outstanding_amount'] === '90.00',
'Paid invoices must exclude refunds once; refunded 30 must not be subtracted again from paid 180.');
$paymentSummary = CloudAdminBillingService::payments(['user_id' => '1'])['summary'];
$assert($paymentSummary['total_records'] === 8 && $paymentSummary['total_amount'] === '350.00'
&& $paymentSummary['paid_invoice_amount'] === '150.00'
&& $paymentSummary['credited_balance_amount'] === '70.00'
&& $paymentSummary['status_counts']['creating'] === 1
&& $paymentSummary['status_counts']['pending'] === 1
&& $paymentSummary['status_counts']['failed'] === 1,
'Attempted amounts, invoice settlement records, and retained balance were incorrectly combined.');
foreach ([
['financial_status' => 'paid', 'expected' => [6, 5, 1]],
['financial_status' => 'refunded', 'expected' => [2]],
['financial_status' => 'open', 'expected' => [3]],
['financial_status' => 'overdue', 'expected' => [4]],
['financial_status' => 'void', 'expected' => [8]],
['purpose' => 'recharge', 'expected' => [7, 5]],
['purpose' => 'renewal', 'expected' => [8, 6, 4]],
['payment_method' => 'balance', 'expected' => [6, 1]],
['fulfillment_status' => 'failed', 'expected' => [2]],
] as $case) {
$expected = $case['expected'];
unset($case['expected']);
$filtered = CloudAdminBillingService::invoices(['user_id' => '1'] + $case);
$assert($ids($filtered['items']) === $expected
&& $filtered['summary']['total_records'] === count($expected),
'Invoice filter disagreed with the displayed financial/fulfilment state: ' . json_encode($case));
}
$running = CloudAdminBillingService::orders(['user_id' => '10', 'status' => 'running']);
$assert($running['summary']['total_records'] === 135
&& $running['summary']['status_counts']['running'] === 135,
'Order filters must use the current task state rather than the stale queued order state.');
$queued = CloudAdminBillingService::orders(['user_id' => '10', 'status' => 'queued']);
$assert($queued['items'] === [], 'The same order appeared in both queued and running filters.');
$refundedOrder = CloudAdminBillingService::orders(['user_id' => '1', 'financial_status' => 'refunded']);
$assert($ids($refundedOrder['items']) === [102], 'Order financial filtering lost its owner-scoped invoice relation.');
$retainedPayments = CloudAdminBillingService::payments(['user_id' => '1', 'status' => 'credited_balance']);
$assert($ids($retainedPayments['items']) === [7, 5], 'Retained-balance payment filter was confused with refunds.');
$providerPayments = CloudAdminBillingService::payments(['user_id' => '1', 'provider' => 'yipay_wxpay']);
$assert($ids($providerPayments['items']) === [5], 'Payment provider filtering was ignored.');
$invoicePayments = CloudAdminBillingService::payments(['user_id' => '1', 'invoice_id' => '3']);
$assert($ids($invoicePayments['items']) === [8, 3], 'Exact invoice payment filtering crossed another invoice.');
$expectError(static fn () => CloudAdminBillingService::page(['view' => ['invoices']]), 400,
'An array cannot select a billing view');
$expectError(static fn () => CloudAdminBillingService::page(['view' => 'invented']), 400,
'An unknown billing view must not silently become invoices');
foreach (['invoices', 'orders', 'payments'] as $view) {
foreach (['page', 'per_page', 'user_id', 'q', 'created_from', 'created_to'] as $key) {
$expectError(static fn () => CloudAdminBillingService::page(['view' => $view, $key => ['bad']]), 422,
'Array filter must be rejected: ' . $view . '/' . $key);
}
$expectError(static fn () => CloudAdminBillingService::page([
'view' => $view, 'created_from' => (string) $now, 'created_to' => (string) ($now - 1),
]), 422, 'An inverted date interval must not be queried');
}
$expectError(static fn () => CloudAdminBillingService::invoice('999999'), 404,
'A missing invoice must not fabricate details');
$details = [];
foreach (range(1, 16) as $id) {
$details[$id] = CloudAdminBillingService::invoice((string) $id);
}
$assert($details[1]['funds']['settled_amount'] === '100.00'
&& $details[1]['funds']['refund_amount'] === null
&& $details[1]['invoice']['payment_deadline_at'] === $now + 3600
&& $details[1]['invoice']['specification']['cpu_cores'] === 2,
'Settled provisioning detail lost its specification, deadline, or financial meaning.');
$assert($details[2]['funds']['settled_amount'] === '30.00'
&& $details[2]['funds']['refund_amount'] === '30.00'
&& $details[2]['funds']['refund_destination'] === 'balance'
&& $details[2]['funds']['refunded_at'] === $now - 200
&& $details[2]['job']['status'] === 'failed',
'A confirmed failed-provision refund must identify the original settlement and balance return independently.');
$assert($details[3]['funds']['settled_amount'] === null
&& $details[3]['funds']['refund_amount'] === null
&& $details[3]['funds']['refund_destination'] === null,
'An unpaid order was described as a paid or refunded order.');
$assert($details[4]['invoice']['financial_status'] === 'overdue'
&& $details[4]['invoice']['fulfillment_status'] === 'awaiting_payment'
&& $details[4]['invoice']['payment_deadline_at'] === $now - 60 + 3 * 86400
&& $details[6]['invoice']['fulfillment_status'] === 'succeeded',
'Renewal detail lost its grace deadline or mixed renewal completion with payment state.');
$assert($details[5]['invoice']['purpose'] === 'recharge'
&& $details[5]['job'] === null && $details[5]['instance'] === null
&& $details[5]['invoice']['fulfillment_status'] === null,
'Recharge detail fabricated a virtual machine or provisioning task.');
$assert($details[7]['funds']['settled_amount'] === null
&& $details[7]['funds']['refund_amount'] === null
&& $details[7]['funds']['balance_retained_amount'] === '10.00'
&& $details[7]['funds']['balance_retained_count'] === 1,
'An expired unpaid invoice with retained payment funds was incorrectly called a refund.');
$assert($details[8]['invoice']['financial_status'] === 'void'
&& $details[8]['links']['instance'] === null,
'An orphan renewal still offered payment or a deleted-instance link.');
$assert($details[9]['order'] === null && $details[9]['job'] === null
&& $details[9]['instance'] === null && $details[9]['payment_attempts'] === []
&& $details[9]['links']['instance'] === null
&& $details[9]['funds']['balance_retained_amount'] === '0.00',
'Invoice detail crossed ownership through orders, instances or gateway attempts.');
$assert($details[10]['funds']['refund_amount'] === null
&& $details[10]['funds']['refund_destination'] === null
&& $details[10]['funds']['refunded_at'] === null,
'A foreign order\'s refund timestamp falsely confirmed another user\'s refund.');
$assert($details[11]['links']['user'] === null, 'A missing account received a fabricated administrative link.');
$assert(count($details[12]['payment_attempts']) === 100
&& $details[12]['payment_attempts_truncated'] === true
&& $ids($details[12]['payment_attempts']) === range(6104, 6005)
&& $details[12]['funds']['balance_retained_count'] === 105
&& $details[12]['funds']['balance_retained_amount'] === '115.50'
&& $details[12]['funds']['payment_records_truncated'] === true,
'Retained balance must aggregate every same-owner payment, not just the latest 100 display rows.');
$assert($details[14]['funds']['refund_amount'] === '9.00'
&& str_contains(implode(' ', $details[14]['funds']['notes']), '不同'),
'Refund explanation replaced the recorded order amount with a conflicting invoice face value.');
$eventsOf = static fn (array $detail, string $kind): array => array_values(array_filter(
$detail['timeline'], static fn (array $event): bool => $event['kind'] === $kind
));
$assert($eventsOf($details[2], 'invoice_refunded')[0]['at'] === $now - 200
&& $eventsOf($details[10], 'invoice_refunded')[0]['at'] === null
&& $eventsOf($details[13], 'invoice_paid')[0]['at'] === null,
'Timeline invented missing financial event timestamps from generic updated_at values.');
$assert($eventsOf($details[3], 'invoice_paid') === []
&& $eventsOf($details[3], 'invoice_refunded') === []
&& $eventsOf($details[7], 'invoice_refunded') === []
&& $eventsOf($details[7], 'invoice_closed')[0]['at'] === null,
'Unpaid/expired timeline fabricated settlement or refund events.');
foreach ([8, 15, 16] as $id) {
$void = $details[$id];
$assert($void['invoice']['financial_status'] === 'void'
&& $void['funds']['title'] === '账单已作废'
&& $void['funds']['settled_amount'] === null
&& $void['funds']['refund_amount'] === null
&& $void['funds']['refund_destination'] === null
&& $eventsOf($void, 'invoice_paid') === []
&& $eventsOf($void, 'invoice_refunded') === []
&& count($eventsOf($void, 'invoice_closed')) === 1
&& $eventsOf($void, 'invoice_closed')[0]['at'] === null,
'Deleted/missing renewal targets must show the same derived void state in funds and timeline without inventing financial events.');
}
foreach ($eventsOf($details[7], 'payment_updated') as $event) {
$assert($event['at'] === $now - 100 && str_contains($event['description'], '更新时间')
&& str_contains($event['description'], '不代表'),
'A payment record update was presented as the gateway receipt time.');
}
foreach ($details as $detail) {
$dated = array_values(array_filter(array_column($detail['timeline'], 'at'),
static fn ($at): bool => $at !== null));
$sorted = $dated;
sort($sorted);
$assert($dated === $sorted, 'Timeline did not preserve chronological order.');
}
$assert($details[1]['links']['user'] === '/admin/user/1/edit'
&& $details[1]['links']['instance'] === '/admin/cloud/instances?q=11111111-1111-4111-8111-000000000501'
&& $details[1]['links']['payments'] === '/admin/billing?view=payments&invoice_id=1',
'Validated account, exact-instance, or payment deep links were lost.');
AdminPermission::$superAdmin = false;
$masked = CloudAdminBillingService::invoice('1');
$assert($masked['invoice']['user_email'] !== 'alice@example.test'
&& $masked['invoice']['user_name'] !== 'Alice Finance'
&& $masked['links']['user'] === null && $masked['links']['instance'] !== null,
'Read-only admins gained unmasked account data or a restricted account-edit link.');
foreach (['invoices', 'orders', 'payments'] as $view) {
$hidden = CloudAdminBillingService::page(['view' => $view, 'q' => 'alice@example.test']);
$assert($hidden['items'] === [], 'Masked account search disclosed a hidden identity: ' . $view);
}
AdminPermission::$superAdmin = true;
$serialized = json_encode([$details, $ledger, $masked], JSON_THROW_ON_ERROR);
$assert(!str_contains($serialized, 'must-not-expose')
&& !str_contains($serialized, 'credential_cipher')
&& !str_contains($serialized, 'provider_order_no')
&& !str_contains($serialized, 'idempotency_key')
&& !str_contains($serialized, 'payment_reference')
&& !str_contains($serialized, 'unreviewed_note'),
'Billing detail leaked unreviewed provider, credential or metadata fields.');
$login = static function (bool $admin, bool $super = false): void {
$user = new User();
$user->id = 1;
$user->enable = 1;
$user->is_admin = $admin;
$user->isLogin = true;
Auth::$user = $user;
AdminPermission::$superAdmin = $super;
};
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
require dirname(__DIR__) . '/config/routes_cloud.php';
$requestApi = static function (string $path, array $query = []) use ($app): array {
$request = Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => $path,
]))->withQueryParams($query);
$response = $app->process($request, new Response());
return [$response, json_decode((string) $response->getBody(), true)];
};
$login(true, true);
foreach (['invoices', 'orders', 'payments'] as $view) {
[$response, $payload] = $requestApi('/api/v1/admin/billing/' . $view, ['user_id' => '10']);
$assert($response->getStatusCode() === 200 && $payload['pagination']['total'] === 135
&& $response->getHeaderLine('Cache-Control') === 'private, no-store',
'Registered billing route lost its private database response: ' . $view);
}
[$response, $payload] = $requestApi('/api/v1/admin/billing/invoices/2');
$assert($response->getStatusCode() === 200 && $payload['funds']['refund_destination'] === 'balance',
'The invoice API did not expose the verified read-only funds explanation.');
$login(true);
[$response, $payload] = $requestApi('/api/v1/admin/billing/invoices/1');
$assert($response->getStatusCode() === 200 && $payload['links']['user'] === null,
'Read-only admins lost billing detail access or gained account-edit permission.');
$login(false);
foreach (['invoices', 'orders', 'payments', 'invoices/1'] as $suffix) {
[$response] = $requestApi('/api/v1/admin/billing/' . $suffix);
$assert($response->getStatusCode() === 403, 'Customer access to an admin billing route was not denied.');
}
Auth::$user = null;
[$response] = $requestApi('/api/v1/admin/billing/invoices');
$assert($response->getStatusCode() === 401, 'Anonymous access bypassed billing authentication.');
// Authentication rejection must return before the inherited constructor's
// Redis/theme work or view rendering is needed. This invokes the real page
// controller and CloudAccess, with no substitute business or view service.
$pageController = (new \ReflectionClass(\App\Controllers\Admin\CloudPageController::class))
->newInstanceWithoutConstructor();
$pageRequest = Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/admin/billing',
]));
foreach (['disabled' => 401, 'anonymous' => 401, 'customer' => 403] as $identity => $status) {
$login($identity !== 'customer', true);
if ($identity === 'disabled') Auth::$user->enable = 0;
if ($identity === 'anonymous') Auth::$user = null;
$response = $pageController->billing($pageRequest, new Response(), []);
$assert($response->getStatusCode() === $status
&& $response->getHeaderLine('Cache-Control') === 'private, no-store'
&& (string) $response->getBody() === '',
'Page authentication failure became a 500 or rendered the admin shell: ' . $identity);
}
foreach ($before as $table => $snapshot) {
$assert(Capsule::table($table)->orderBy('id')->get()->toJson() === $snapshot,
'Read-only billing mutated financial/account records: ' . $table);
}
$assert(CloudEngineClient::$calls === 0 && CloudSessionService::$calls === 0,
'Database-only billing reads created an engine session or contacted the engine.');
echo 'Administrator billing SQL pagination/filtering, financial separation, funds/timeline/links, ownership and API access passed. Queries for 30/100 rows: '
. json_encode($queryCounts) . ".\n";
}

@ -749,16 +749,20 @@ foreach (['hosts/index.tpl', 'cloud/rescue.tpl', 'cloud/templates.tpl'] as $temp
'Cloud admin script cache busting missing: ' . $template);
}
$adminBillingSource = file_get_contents($adminBillingTemplate);
$adminBillingMarkup = $adminBillingSource
. file_get_contents($views . '/admin/billing_rows.tpl')
. file_get_contents($views . '/admin/billing_summary.tpl');
$assert(str_contains($adminBillingSource,
'/cloud/admin-billing.js?v={$venix_asset_version}')
&& str_contains($adminBillingSource, "{include file='admin/static_footer.tpl'}")
&& !str_contains($adminBillingSource, '/cloud/admin-billing.css')
&& !is_file($adminBillingStyles)
&& str_contains($adminBillingSource, 'admin-billing-summary')
&& preg_match_all('/<article class="[^"]*\badmin-billing-stat\b/', $adminBillingSource) === 4
&& preg_match_all('/<article class="[^"]*\badmin-billing-stat\b/', $adminBillingMarkup) === 5
&& !str_contains($adminBillingSource, 'admin-ticket-stat h-100')
&& str_contains($adminBillingSource, 'admin-checkout-table')
&& str_contains($adminBillingSource, 'admin-modal-panel'),
&& str_contains($adminBillingSource, '<dialog data-admin-instance-drawer data-admin-billing-drawer')
&& str_contains($adminBillingSource, 'admin-billing-bootstrap'),
'Unified administrator billing must reuse Venix admin styles and version its functional script');
$billingIds = [
'billing-notice', 'billing-refresh', 'billing-summary', 'billing-summary-total',
@ -775,13 +779,16 @@ $billingIds = [
'billing-table-caption', 'billing-table-head', 'billing-table-body', 'billing-pagination',
'billing-previous', 'billing-page-label', 'billing-next', 'billing-detail-dialog',
'billing-detail-close', 'billing-detail-title', 'billing-detail-state', 'billing-detail-body',
'billing-summary-refunded', 'billing-refund-card', 'billing-detail-links',
'billing-advanced', 'billing-shown-filters',
];
foreach ($billingIds as $billingId) {
$assert(substr_count($adminBillingSource, 'id="' . $billingId . '"') === 1,
$assert(substr_count($adminBillingMarkup, 'id="' . $billingId . '"') === 1,
'Unified administrator billing hook missing or duplicated: ' . $billingId);
}
$assert(str_contains($adminBillingSource, '<main data-admin-billing>')
&& substr_count($adminBillingSource, 'data-billing-view=') === 3
&& str_contains($adminBillingSource, '{foreach $billing_titles as $view=>$label}')
&& str_contains($adminBillingSource, 'data-billing-view="{$view|escape}"')
&& str_contains($adminBillingSource, 'admin-billing-filter-actions')
&& str_contains($adminSharedStyles, '.admin-billing-summary .admin-billing-stat-value')
&& str_contains($adminSharedStyles, '.admin-billing-filter-actions')
@ -795,17 +802,17 @@ $assert($billingMobileStyles !== false
&& preg_match('/\[data-admin-billing\] \.form-control,\s*\[data-admin-billing\] \.form-select\s*\{(?=[^}]*min-height:\s*44px)(?=[^}]*font-size:\s*16px)[^}]*\}/s', $billingMobileStyles)
&& preg_match('/\[data-admin-billing\] \.btn,\s*\.admin-ticket-tabs a\s*\{[^}]*min-height:\s*44px/s', $billingMobileStyles),
'Administrator billing controls must remain zoom-safe and touch-friendly on phones');
$assert(preg_match('/\.admin-billing-dialog \.admin-modal-close\s*\{(?=[^}]*width:\s*44px)(?=[^}]*height:\s*44px)[^}]*\}/s', $adminSharedStyles)
$assert(preg_match('/\[data-admin-billing-drawer\] \.admin-modal-close\s*\{(?=[^}]*width:\s*44px)(?=[^}]*height:\s*44px)[^}]*\}/s', $adminSharedStyles)
&& preg_match('/\.admin-checkout-user\s*\{[^}]*min-width:\s*0/s', $adminSharedStyles)
&& preg_match('/\.admin-checkout-user strong,\s*\.admin-checkout-user span\s*\{[^}]*overflow-wrap:\s*anywhere/s', $adminSharedStyles),
'Administrator billing dialog controls and long table values must remain usable on narrow screens');
$assert(str_contains($adminBillingSource, '<header class="d-flex align-items-start justify-content-between')
$assert(str_contains($adminBillingSource, '<header class="admin-instance-drawer-header')
&& str_contains($adminBillingSource, 'admin-modal-close position-static flex-shrink-0')
&& preg_match('/\.admin-billing-dialog-panel\s*\{(?=[^}]*display:\s*flex)(?=[^}]*flex-direction:\s*column)(?=[^}]*overflow:\s*hidden)[^}]*\}/s', $adminSharedStyles)
&& preg_match('/\.admin-billing-dialog-body\s*\{(?=[^}]*min-height:\s*0)(?=[^}]*overflow-y:\s*auto)(?=[^}]*overflow-wrap:\s*anywhere)[^}]*\}/s', $adminSharedStyles)
&& str_contains($adminBillingRuntime, "dialog.addEventListener('close'")
&& str_contains($adminBillingRuntime, "document.body.classList.remove('billing-detail-open')")
&& str_contains($adminBillingRuntime, 'opener.focus({ preventScroll: true })'),
&& preg_match('/\[data-admin-instance-drawer\]\[open\]\s*\{(?=[^}]*display:\s*flex)(?=[^}]*flex-direction:\s*column)[^}]*\}/s', $adminSharedStyles)
&& preg_match('/\[data-admin-instance-drawer\] \.admin-instance-drawer-body\s*\{(?=[^}]*min-height:\s*0)(?=[^}]*overflow-y:\s*auto)[^}]*\}/s', $adminSharedStyles)
&& str_contains($adminBillingRuntime, "dialog.addEventListener('cancel'")
&& str_contains($adminBillingRuntime, "document.documentElement.classList.remove('admin-instance-detail-open')")
&& str_contains($adminBillingRuntime, 'state.detailOpener.focus({ preventScroll: true })'),
'Administrator billing detail must keep its close action visible and restore page state after scrolling');
$assert(!preg_match('/text-bg-(?:success|info|warning|danger)/', $adminBillingRuntime)
&& str_contains($adminBillingRuntime, 'bg-success-subtle text-success-emphasis')

Loading…
Cancel
Save