refactor(billing): unify administrator presentation

go
codex 3 weeks ago
parent 1bf1c7aec9
commit f665246d25

@ -0,0 +1,252 @@
<?php
namespace App\Services\Cloud;
/**
* Pure administrator billing adapter.
*
* It deliberately keeps invoice, order and payment records independent and
* only adds display fields beneath `presentation`.
*/
final class CloudAdminBillingPresentation
{
public static function page(string $view, array $payload): array
{
$view = in_array($view, ['invoices', 'orders', 'payments'], true)
? $view : 'invoices';
$items = [];
foreach (is_array($payload['items'] ?? null) ? $payload['items'] : []
as $item) {
if (!is_array($item)) {
continue;
}
$item['presentation'] = self::row($view, $item);
$items[] = $item;
}
$payload['items'] = $items;
if (is_array($payload['summary'] ?? null)) {
$summary = $payload['summary'];
$summary['presentation'] = self::summary($summary);
$payload['summary'] = $summary;
}
$payload['presentation'] = [
'catalog' => CloudBillingPresentationCatalog::filterOptions(),
];
return $payload;
}
public static function detail(array $payload): array
{
$invoice = is_array($payload['invoice'] ?? null)
? $payload['invoice'] : [];
if ($invoice !== []) {
$invoice['presentation'] = self::invoice($invoice);
$payload['invoice'] = $invoice;
}
if (is_array($payload['order'] ?? null)) {
$order = $payload['order'];
$order['presentation'] = self::order($order);
$payload['order'] = $order;
}
if (is_array($payload['job'] ?? null)) {
$job = $payload['job'];
$job['presentation'] = [
'status' => self::taskStatus($job),
'updated_display' => CloudBillingPresentationCatalog::timestamp(
$job['updated_at'] ?? null
),
];
$payload['job'] = $job;
}
if (is_array($payload['instance'] ?? null)) {
$instance = $payload['instance'];
$instance['presentation'] = [
'expires_display' => CloudBillingPresentationCatalog::timestamp(
$instance['expires_at'] ?? null
),
];
$payload['instance'] = $instance;
}
$attempts = [];
foreach (is_array($payload['payment_attempts'] ?? null)
? $payload['payment_attempts'] : [] as $attempt) {
if (!is_array($attempt)) {
continue;
}
$attempt['presentation'] = self::payment($attempt);
$attempts[] = $attempt;
}
$payload['payment_attempts'] = $attempts;
if (is_array($payload['funds'] ?? null)) {
$funds = $payload['funds'];
$currency = $invoice['currency'] ?? 'USD';
$funds['presentation'] = [
'settled_amount_display' => CloudBillingPresentationCatalog::money(
$funds['settled_amount'] ?? null, $currency
),
'refund_amount_display' => ($funds['refund_amount'] ?? null) === null
? '无已确认退款记录'
: CloudBillingPresentationCatalog::money(
$funds['refund_amount'], $currency
),
'balance_retained_amount_display' =>
CloudBillingPresentationCatalog::money(
$funds['balance_retained_amount'] ?? null, $currency
),
'refunded_at_display' => CloudBillingPresentationCatalog::timestamp(
$funds['refunded_at'] ?? null
),
];
$payload['funds'] = $funds;
}
$timeline = [];
foreach (is_array($payload['timeline'] ?? null)
? $payload['timeline'] : [] as $entry) {
if (!is_array($entry)) {
continue;
}
$entry['at_display'] = CloudBillingPresentationCatalog::timestamp(
$entry['at'] ?? null, '时间未记录'
);
$timeline[] = $entry;
}
$payload['timeline'] = $timeline;
return $payload;
}
private static function row(string $view, array $item): array
{
return match ($view) {
'orders' => self::order($item),
'payments' => self::payment($item),
default => self::invoice($item),
};
}
private static function summary(array $summary): array
{
$fields = ['total_amount', 'outstanding_amount', 'paid_amount',
'refunded_amount', 'paid_invoice_amount',
'credited_balance_amount'];
$presentation = [];
$mixedCurrency = ($summary['mixed_currency'] ?? false) === true
|| (int) ($summary['currency_count'] ?? 0) > 1;
foreach ($fields as $field) {
if (array_key_exists($field, $summary)) {
$presentation[$field . '_display'] = $mixedCurrency
? '多币种'
: CloudBillingPresentationCatalog::money(
$summary[$field], $summary['currency'] ?? 'USD'
);
}
}
$presentation['mixed_currency'] = $mixedCurrency;
return $presentation;
}
private static function invoice(array $invoice): array
{
$purpose = $invoice['purpose'] ?? null;
return [
'purpose_label' => CloudBillingPresentationCatalog::purposeLabel($purpose),
'amount_display' => CloudBillingPresentationCatalog::money(
$invoice['amount'] ?? null, $invoice['currency'] ?? 'USD'
),
'financial_status' => CloudBillingPresentationCatalog::status(
'financial', $invoice['financial_status'] ?? null
),
'fulfillment_status' => CloudBillingPresentationCatalog::status(
'fulfillment', $invoice['fulfillment_status'] ?? null, $purpose
),
'provider_label' => CloudBillingPresentationCatalog::providerLabel(
$invoice['payment_method'] ?? null
),
'created_display' => CloudBillingPresentationCatalog::timestamp(
$invoice['created_at'] ?? null
),
'updated_display' => CloudBillingPresentationCatalog::timestamp(
$invoice['updated_at'] ?? null
),
'due_display' => CloudBillingPresentationCatalog::timestamp(
$invoice['due_at'] ?? null
),
'payment_deadline_display' => CloudBillingPresentationCatalog::timestamp(
$invoice['payment_deadline_at'] ?? null
),
'paid_display' => CloudBillingPresentationCatalog::timestamp(
$invoice['paid_at'] ?? null
),
'renews_expires_display' => CloudBillingPresentationCatalog::timestamp(
$invoice['renews_expires_at'] ?? null
),
];
}
private static function order(array $order): array
{
return [
'amount_display' => CloudBillingPresentationCatalog::money(
$order['amount'] ?? null, $order['currency'] ?? 'USD'
),
'financial_status' => CloudBillingPresentationCatalog::status(
'financial', $order['financial_status'] ?? null
),
'fulfillment_status' => CloudBillingPresentationCatalog::status(
'fulfillment', $order['fulfillment_status'] ?? null
),
'created_display' => CloudBillingPresentationCatalog::timestamp(
$order['created_at'] ?? null
),
'updated_display' => CloudBillingPresentationCatalog::timestamp(
$order['updated_at'] ?? $order['created_at'] ?? null
),
];
}
private static function payment(array $payment): array
{
return [
'provider_label' => CloudBillingPresentationCatalog::providerLabel(
$payment['provider'] ?? null
),
'amount_display' => CloudBillingPresentationCatalog::money(
$payment['amount'] ?? null, $payment['currency'] ?? 'USD'
),
'payment_status' => CloudBillingPresentationCatalog::status(
'payment', $payment['payment_status'] ?? $payment['status'] ?? null
),
'invoice_financial_status' => CloudBillingPresentationCatalog::status(
'financial', $payment['invoice_financial_status'] ?? null
),
'purpose_label' => CloudBillingPresentationCatalog::purposeLabel(
$payment['purpose'] ?? null
),
'created_display' => CloudBillingPresentationCatalog::timestamp(
$payment['created_at'] ?? null
),
'updated_display' => CloudBillingPresentationCatalog::timestamp(
$payment['updated_at'] ?? null
),
];
}
private static function taskStatus(array $task): array
{
if (($task['completed'] ?? null) === false
&& (!array_key_exists('status', $task)
|| ($task['status'] ?? null) === 'active')) {
return CloudBillingPresentationCatalog::status('fulfillment', 'active');
}
if (($task['completed'] ?? null) === true
&& in_array($task['status'] ?? null, ['succeeded', 'failed'], true)) {
return CloudBillingPresentationCatalog::status(
'fulfillment', $task['status']
);
}
return [
'code' => 'invalid', 'label' => '任务状态协议无效',
'tone' => 'danger',
'class' => CloudBillingPresentationCatalog::badgeClass('danger'),
];
}
}

@ -81,18 +81,19 @@ final class CloudAdminBillingService
'cloud_invoices.user_id', 'cloud_invoices.plan_id',
'cloud_invoices.renewal_id', 'cloud_invoices.renews_expires_at',
'cloud_invoices.due_at', 'cloud_invoices.amount',
'cloud_invoices.currency',
'cloud_invoices.validity_days',
'cloud_invoices.traffic_quota_bytes', 'cloud_invoices.status',
'cloud_invoices.paid_via', 'cloud_invoices.paid_at',
'cloud_invoices.created_at', 'cloud_invoices.updated_at',
]);
return [
return CloudAdminBillingPresentation::page('invoices', [
'items' => self::invoiceRows($records->all()),
'pagination' => $pagination,
'summary' => $summary,
'filters' => $filters,
];
]);
}
public static function invoice(string $id): array
@ -164,7 +165,7 @@ final class CloudAdminBillingService
$row['specification'] = self::specification($order, $instance);
}
return [
return CloudAdminBillingPresentation::detail([
'invoice' => $row,
'order' => $order === null ? null
: self::orderRow($order, self::orderContext([$order])),
@ -185,7 +186,7 @@ final class CloudAdminBillingService
'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. */
@ -341,13 +342,14 @@ final class CloudAdminBillingService
->get([
'cloud_orders.id', 'cloud_orders.user_id', 'cloud_orders.plan_id',
'cloud_orders.host_id', 'cloud_orders.amount',
'cloud_orders.currency',
'cloud_orders.status', 'cloud_orders.spec_json',
'cloud_orders.instance_id', 'cloud_orders.refunded_at',
'cloud_orders.created_at', 'cloud_orders.updated_at',
]);
$context = self::orderContext($records->all());
return [
return CloudAdminBillingPresentation::page('orders', [
'items' => array_map(
static fn ($order): array => self::orderRow($order, $context),
$records->all()
@ -355,7 +357,7 @@ final class CloudAdminBillingService
'pagination' => $pagination,
'summary' => $summary,
'filters' => $filters,
];
]);
}
public static function payments(array $input): array
@ -392,7 +394,7 @@ final class CloudAdminBillingService
]);
$context = self::paymentContext($records->all());
return [
return CloudAdminBillingPresentation::page('payments', [
'items' => array_map(
static fn ($payment): array => self::paymentRow($payment, $context),
$records->all()
@ -400,7 +402,7 @@ final class CloudAdminBillingService
'pagination' => $pagination,
'summary' => $summary,
'filters' => $filters,
];
]);
}
private static function invoiceFilters(array $input): array
@ -858,7 +860,7 @@ final class CloudAdminBillingService
$users = self::keyed(User::whereIn('id', $userIds)
->get(['id', 'user_name', 'email'])->all());
$orders = self::keyed(CloudOrder::whereIn('id', $orderIds)
->get(['id', 'user_id', 'plan_id', 'host_id', 'amount', 'status',
->get(['id', 'user_id', 'plan_id', 'host_id', 'amount', 'currency', 'status',
'spec_json', 'instance_id', 'refunded_at', 'created_at',
'updated_at'])->all());
$jobRecords = CloudJob::where(function ($query) use ($orderIds, $invoiceIds): void {
@ -945,6 +947,9 @@ final class CloudAdminBillingService
'plan_name' => $planName,
'subject_name' => $subject,
'amount' => self::money($invoice->amount),
'currency' => CloudBillingPresentationCatalog::currency(
$invoice->currency ?? 'USD'
),
'financial_status' => $financialStatus,
'fulfillment_status' => self::fulfillmentStatus(
$invoice, $order, $job, $financialStatus
@ -990,7 +995,7 @@ final class CloudAdminBillingService
->get(['id', 'name'])->all()),
'invoices' => self::keyed(CloudInvoice::whereIn('order_id', $orderIds)
->get(['id', 'purpose', 'order_id', 'instance_id', 'user_id',
'due_at', 'amount', 'status', 'paid_via', 'paid_at',
'due_at', 'amount', 'currency', 'status', 'paid_via', 'paid_at',
'created_at', 'updated_at'])->all(), 'order_id'),
'jobs' => self::keyed(CloudJob::whereIn('order_id', $orderIds)
->get(['id', 'order_id', 'instance_id', 'user_id', 'kind',
@ -1026,6 +1031,9 @@ final class CloudAdminBillingService
'plan_name' => trim((string) ($spec['plan_name'] ?? $plan?->name ?? '')),
'host_id' => (string) $order->host_id,
'amount' => self::money($order->amount),
'currency' => CloudBillingPresentationCatalog::currency(
$order->currency ?? $invoice?->currency ?? 'USD'
),
'financial_status' => $invoice === null ? null
: self::financialStatus($invoice, null),
'fulfillment_status' => $jobStatus
@ -1056,7 +1064,7 @@ final class CloudAdminBillingService
$invoiceIds = self::ids($records, 'invoice_id');
$invoices = self::keyed(CloudInvoice::whereIn('id', $invoiceIds)
->get(['id', 'purpose', 'instance_id', 'user_id', 'due_at',
'status'])->all());
'currency', 'status'])->all());
$instanceIds = self::ids(array_values($invoices), 'instance_id');
return [
'users' => self::keyed(User::whereIn('id', $userIds)
@ -1089,6 +1097,9 @@ final class CloudAdminBillingService
'user_email' => AdminDataMasker::email($user?->email ?? ''),
'provider' => (string) $payment->provider,
'amount' => self::money($payment->amount),
'currency' => CloudBillingPresentationCatalog::currency(
$invoice?->currency ?? 'USD'
),
'payment_status' => (string) $payment->status,
'invoice_financial_status' => $invoice === null ? null
: self::financialStatus($invoice, $instance, true),
@ -1288,37 +1299,46 @@ final class CloudAdminBillingService
private static function invoiceSummary($query): array
{
$currency = self::summaryCurrencyExpression('cloud_invoices.currency');
$singleCurrency = "COUNT(DISTINCT {$currency}) <= 1";
$liveRenewalTarget = "(purpose <> 'renewal' OR EXISTS ("
. 'SELECT 1 FROM cloud_instances AS billing_instance '
. 'WHERE billing_instance.id = cloud_invoices.instance_id '
. 'AND billing_instance.user_id = cloud_invoices.user_id '
. "AND billing_instance.status <> 'deleted'))";
$row = $query->selectRaw(
"COUNT(*) AS total_records, COALESCE(SUM(amount), 0) AS total_amount, "
"COUNT(*) AS total_records, COUNT(DISTINCT {$currency}) AS currency_count, "
. "MIN({$currency}) AS currency, "
. "CASE WHEN {$singleCurrency} THEN COALESCE(SUM(amount), 0) "
. "ELSE NULL END AS total_amount, "
. "SUM(CASE WHEN status IN ('open','overdue') AND {$liveRenewalTarget} "
. "THEN 1 ELSE 0 END) AS outstanding_count, "
. "COALESCE(SUM(CASE WHEN status IN ('open','overdue') "
. "CASE WHEN {$singleCurrency} THEN COALESCE(SUM(CASE WHEN status IN ('open','overdue') "
. "AND {$liveRenewalTarget} THEN amount ELSE 0 END), 0) "
. "AS outstanding_amount, "
. "ELSE NULL END AS outstanding_amount, "
. "SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_count, "
. "COALESCE(SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END), 0) AS paid_amount, "
. "CASE WHEN {$singleCurrency} THEN COALESCE(SUM(CASE WHEN status = 'paid' "
. "THEN amount ELSE 0 END), 0) ELSE NULL END AS paid_amount, "
. "SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded_count, "
. "COALESCE(SUM(CASE WHEN status = 'refunded' THEN amount ELSE 0 END), 0) AS refunded_amount"
. "CASE WHEN {$singleCurrency} THEN COALESCE(SUM(CASE WHEN status = 'refunded' "
. "THEN amount ELSE 0 END), 0) ELSE NULL END AS refunded_amount"
)->first();
return [
return self::withSummaryCurrency([
'total_records' => (int) ($row?->total_records ?? 0),
'total_amount' => self::money($row?->total_amount ?? '0'),
'total_amount' => self::nullableMoney($row?->total_amount),
'outstanding_count' => (int) ($row?->outstanding_count ?? 0),
'outstanding_amount' => self::money($row?->outstanding_amount ?? '0'),
'outstanding_amount' => self::nullableMoney($row?->outstanding_amount),
'paid_count' => (int) ($row?->paid_count ?? 0),
'paid_amount' => self::money($row?->paid_amount ?? '0'),
'paid_amount' => self::nullableMoney($row?->paid_amount),
'refunded_count' => (int) ($row?->refunded_count ?? 0),
'refunded_amount' => self::money($row?->refunded_amount ?? '0'),
];
'refunded_amount' => self::nullableMoney($row?->refunded_amount),
], $row);
}
private static function orderSummary($query): array
{
$currency = self::summaryCurrencyExpression('cloud_orders.currency');
$singleCurrency = "COUNT(DISTINCT {$currency}) <= 1";
$state = "CASE WHEN cloud_jobs.id IS NOT NULL THEN "
. "CASE WHEN cloud_jobs.phase = 'terminal' THEN "
. "COALESCE(cloud_jobs.outcome, 'failed') ELSE 'active' END "
@ -1326,7 +1346,11 @@ final class CloudAdminBillingService
. 'ELSE cloud_orders.status END';
$select = [
'COUNT(*) AS total_records',
'COALESCE(SUM(cloud_orders.amount), 0) AS total_amount',
"COUNT(DISTINCT {$currency}) AS currency_count",
"MIN({$currency}) AS currency",
"CASE WHEN {$singleCurrency} "
. 'THEN COALESCE(SUM(cloud_orders.amount), 0) '
. 'ELSE NULL END AS total_amount',
];
foreach (self::ORDER_STATUSES as $status) {
$select[] = "SUM(CASE WHEN {$state} = '{$status}' "
@ -1343,24 +1367,41 @@ final class CloudAdminBillingService
$counts[$status] = $count;
}
}
return [
return self::withSummaryCurrency([
'total_records' => (int) ($row?->total_records ?? 0),
'total_amount' => self::money($row?->total_amount ?? '0'),
'total_amount' => self::nullableMoney($row?->total_amount),
'status_counts' => $counts,
];
], $row);
}
private static function paymentSummary($query): array
{
$query->leftJoin('cloud_invoices AS billing_currency_invoice',
function ($join): void {
$join->on('billing_currency_invoice.id', '=',
'cloud_invoice_payments.invoice_id')
->on('billing_currency_invoice.user_id', '=',
'cloud_invoice_payments.user_id');
});
$currency = self::summaryCurrencyExpression(
'billing_currency_invoice.currency'
);
$singleCurrency = "COUNT(DISTINCT {$currency}) <= 1";
$select = [
'COUNT(*) AS total_records',
'COALESCE(SUM(cloud_invoice_payments.amount), 0) AS total_amount',
"COALESCE(SUM(CASE WHEN cloud_invoice_payments.status = 'paid_invoice' "
"COUNT(DISTINCT {$currency}) AS currency_count",
"MIN({$currency}) AS currency",
"CASE WHEN {$singleCurrency} "
. 'THEN COALESCE(SUM(cloud_invoice_payments.amount), 0) '
. 'ELSE NULL END AS total_amount',
"CASE WHEN {$singleCurrency} THEN COALESCE(SUM(CASE WHEN "
. "cloud_invoice_payments.status = 'paid_invoice' "
. 'THEN cloud_invoice_payments.amount ELSE 0 END), 0) '
. 'AS paid_invoice_amount',
"COALESCE(SUM(CASE WHEN cloud_invoice_payments.status = 'credited_balance' "
. 'ELSE NULL END AS paid_invoice_amount',
"CASE WHEN {$singleCurrency} THEN COALESCE(SUM(CASE WHEN "
. "cloud_invoice_payments.status = 'credited_balance' "
. 'THEN cloud_invoice_payments.amount ELSE 0 END), 0) '
. 'AS credited_balance_amount',
. 'ELSE NULL END AS credited_balance_amount',
];
foreach (self::PAYMENT_STATUSES as $status) {
$select[] = "SUM(CASE WHEN cloud_invoice_payments.status = '{$status}' "
@ -1374,16 +1415,40 @@ final class CloudAdminBillingService
$counts[$status] = $count;
}
}
return [
return self::withSummaryCurrency([
'total_records' => (int) ($row?->total_records ?? 0),
'total_amount' => self::money($row?->total_amount ?? '0'),
'total_amount' => self::nullableMoney($row?->total_amount),
'status_counts' => $counts,
'paid_invoice_amount' => self::money(
$row?->paid_invoice_amount ?? '0'
'paid_invoice_amount' => self::nullableMoney(
$row?->paid_invoice_amount
),
'credited_balance_amount' => self::money(
$row?->credited_balance_amount ?? '0'
'credited_balance_amount' => self::nullableMoney(
$row?->credited_balance_amount
),
], $row);
}
private static function summaryCurrencyExpression(string $column): string
{
return "UPPER(COALESCE(NULLIF(TRIM({$column}), ''), 'USD'))";
}
private static function nullableMoney($value): ?string
{
return $value === null ? null : self::money($value);
}
private static function withSummaryCurrency(array $summary, $row): array
{
$count = max(0, (int) ($row?->currency_count ?? 0));
$mixed = $count > 1;
return $summary + [
'currency_count' => $count,
'currency' => $mixed ? null
: CloudBillingPresentationCatalog::currency(
$row?->currency ?? 'USD'
),
'mixed_currency' => $mixed,
];
}

@ -0,0 +1,215 @@
<?php
namespace App\Services\Cloud;
/** Pure, shared billing vocabulary. No I/O or business-state derivation. */
final class CloudBillingPresentationCatalog
{
private const PURPOSES = [
'provision' => '实例开通', 'renewal' => '实例续费',
'upgrade' => '实例升级', 'ip_change' => '更换公网 IP',
'backup_addon' => '自动备份开通', 'recharge' => '余额充值',
];
private const PROVIDERS = [
'balance' => '账户余额', 'usdt' => 'USDT-TRC20',
'yipay_alipay' => '易支付 · 支付宝',
'yipay_wxpay' => '易支付 · 微信',
'paytaro' => 'Paytaro · 支付宝',
'stripe_card' => 'Stripe · 银行卡',
'stripe_alipay' => 'Stripe · 支付宝',
];
private const FINANCIAL = [
'open' => ['待支付', 'warning'],
'renewal_grace' => ['已到期,宽限期内可续费', 'warning'],
'overdue' => ['已逾期', 'danger'], 'paid' => ['已支付', 'success'],
'refunded' => ['已退款', 'info'], 'expired' => ['已失效', 'neutral'],
'void' => ['已作废', 'neutral'],
'deleting' => ['实例删除中', 'danger'],
'purge_deleting' => ['实例删除中', 'danger'],
'purge_pending' => ['等待永久删除', 'danger'],
'purge_stopping' => ['删除前正在关机', 'danger'],
'purge_force_required' => ['等待管理员确认强制删除', 'danger'],
'delete_failed' => ['自动删除失败', 'danger'],
'purge_stop_failed' => ['删除前关机失败', 'danger'],
'purge_failed' => ['自动删除失败', 'danger'],
];
private const FULFILLMENT = [
'awaiting_payment' => ['等待支付', 'warning'],
'payment_pending' => ['等待支付', 'warning'],
'draft' => ['等待支付', 'warning'],
'queued' => ['执行中', 'info'], 'pending' => ['执行中', 'info'],
'provisioning' => ['执行中', 'info'],
'running' => ['执行中', 'info'], 'active' => ['执行中', 'info'],
'completed' => ['已成功', 'success'], 'succeeded' => ['已成功', 'success'],
'review' => ['待人工核对', 'warning'],
'failed' => ['已失败', 'danger'], 'expired' => ['已失效', 'neutral'],
'refunded' => ['已退款', 'info'], 'cancelled' => ['已取消', 'neutral'],
'canceled' => ['已取消', 'neutral'],
];
private const PAYMENT = [
'creating' => ['创建中', 'info'], 'pending' => ['待支付', 'warning'],
'paid_invoice' => ['已入账单', 'success'],
'credited_balance' => ['已入余额', 'success'],
'failed' => ['支付失败', 'danger'], 'expired' => ['已失效', 'neutral'],
];
public static function purposeCode($value): string
{
return strtolower(trim((string) ($value ?? '')));
}
public static function purposeLabel($value, string $fallback = '未分类'): string
{
$code = self::purposeCode($value);
return self::PURPOSES[$code] ?? ($code !== '' ? (string) $value : $fallback);
}
public static function knownPurposeLabel($value): string
{
return self::PURPOSES[self::purposeCode($value)] ?? '';
}
public static function providerLabel($value, string $fallback = '未记录'): string
{
$code = strtolower(trim((string) ($value ?? '')));
return self::PROVIDERS[$code] ?? ($code !== '' ? (string) $value : $fallback);
}
public static function currency($value): string
{
$currency = strtoupper(trim((string) ($value ?? '')));
return preg_match('/^[A-Z][A-Z0-9]{2,7}$/D', $currency) === 1
? $currency : 'USD';
}
public static function money($value, $currency = 'USD'): string
{
$code = self::currency($currency);
if (!is_numeric($value) || (float) $value < 0) {
return $code === 'USD' ? '$—' : '— ' . $code;
}
$amount = number_format((float) $value, 2, '.', ',');
return $code === 'USD' ? '$' . $amount : $amount . ' ' . $code;
}
public static function timestamp($value, string $fallback = '—',
string $format = 'Y-m-d H:i:s'): string
{
return is_numeric($value) && (int) $value > 0
? date($format, (int) $value) : $fallback;
}
/** @return array{code: string, label: string, tone: string, class: string} */
public static function status(string $kind, $value, $context = null): array
{
$code = strtolower(trim((string) ($value ?? '')));
$table = match ($kind) {
'financial' => self::FINANCIAL,
'payment' => self::PAYMENT,
default => self::FULFILLMENT,
};
[$label, $tone] = $table[$code]
?? [$code !== '' ? (string) $value : ($kind === 'fulfillment'
? '不适用' : '未记录'), 'neutral'];
$purposeCode = self::purposeCode(is_array($context)
? ($context['purpose'] ?? null) : $context);
if ($kind === 'fulfillment') {
[$label, $tone] = self::fulfillmentContext(
$purposeCode, $code, $label, $tone
);
}
return [
'code' => $code, 'label' => $label, 'tone' => $tone,
'class' => self::badgeClass($tone),
];
}
public static function badgeClass(string $tone): string
{
return match ($tone) {
'success' => 'bg-success-subtle text-success-emphasis',
'warning' => 'bg-warning-subtle text-warning-emphasis',
'danger' => 'bg-danger-subtle text-danger-emphasis',
'info' => 'bg-info-subtle text-info-emphasis',
default => 'bg-light text-dark',
};
}
/** @return array<string, array<int, array{value: string, label: string}>> */
public static function filterOptions(): array
{
return [
'financial' => self::options(self::FINANCIAL, '全部财务状态'),
'fulfillment' => self::options(array_intersect_key(
self::FULFILLMENT,
array_flip(['awaiting_payment', 'active', 'succeeded',
'failed', 'expired', 'refunded', 'cancelled'])
), '全部履约状态'),
'payment' => self::options(self::PAYMENT, '全部支付状态'),
'purpose' => self::labelOptions(self::PURPOSES, '全部账单类型'),
'provider' => self::labelOptions(self::PROVIDERS, '全部支付渠道'),
];
}
private static function options(array $values, string $all): array
{
$options = [['value' => '', 'label' => $all]];
foreach ($values as $value => [$label]) {
if (!in_array($value, ['renewal_grace', 'deleting',
'purge_deleting', 'purge_pending', 'purge_stopping',
'purge_force_required', 'delete_failed', 'purge_stop_failed',
'purge_failed', 'canceled'], true)) {
$options[] = ['value' => $value, 'label' => $label];
}
}
return $options;
}
private static function labelOptions(array $values, string $all): array
{
$options = [['value' => '', 'label' => $all]];
foreach ($values as $value => $label) {
$options[] = ['value' => $value, 'label' => $label];
}
return $options;
}
/** @return array{0: string, 1: string} */
private static function fulfillmentContext(string $purpose, string $code,
string $label, string $tone): array
{
$inProgress = in_array(
$code, ['queued', 'pending', 'provisioning', 'running', 'active'], true
);
$succeeded = in_array($code, ['completed', 'succeeded'], true);
if ($purpose === 'renewal' && $succeeded) {
return ['已续费', $tone];
}
if ($purpose === 'upgrade') {
return match (true) {
$inProgress => ['升级中', $tone],
$succeeded => ['已升级', $tone],
$code === 'failed' => ['升级失败', $tone],
default => [$label, $tone],
};
}
if ($purpose === 'ip_change') {
return match (true) {
$inProgress => ['更换中', $tone],
$succeeded => ['已更换', $tone],
$code === 'failed' => ['更换失败', $tone],
default => [$label, $tone],
};
}
if ($purpose === 'provision') {
return match (true) {
$inProgress => ['创建中', $tone],
$succeeded => ['已开通', $tone],
$code === 'failed' => ['创建失败', $tone],
$code === 'refunded' => ['开通失败,已退款', 'danger'],
default => [$label, $tone],
};
}
return [$label, $tone];
}
}

@ -675,21 +675,15 @@ final class CloudInvoicePresentation
/** @param array<string, mixed> $invoice */
private static function purpose(array $invoice): string
{
return strtolower(trim((string) ($invoice['purpose'] ?? '')));
return CloudBillingPresentationCatalog::purposeCode(
$invoice['purpose'] ?? ''
);
}
/** @param array<string, mixed> $invoice */
private static function invoiceTitle(array $invoice, string $purpose): string
{
$known = match ($purpose) {
'recharge' => '余额充值',
'provision' => '实例开通',
'renewal' => '实例续费',
'upgrade' => '实例升级',
'ip_change' => '更换公网 IP',
'backup_addon' => '自动备份开通',
default => '',
};
$known = CloudBillingPresentationCatalog::knownPurposeLabel($purpose);
return $known !== '' ? $known : self::firstText(
$invoice['title'] ?? null,
$invoice['type_label'] ?? null,
@ -700,66 +694,44 @@ final class CloudInvoicePresentation
/** @return array{0: string, 1: string} */
private static function invoiceStatus(string $status): array
{
return match (strtolower($status)) {
'open' => ['待支付', 'warning'],
'renewal_grace' => ['已到期,宽限期内可续费', 'warning'],
'overdue' => ['已逾期', 'failed'],
'paid' => ['已支付', 'running'],
'refunded' => ['已退款', 'other'],
'void' => ['已失效', 'other'],
'expired' => ['已失效', 'failed'],
'deleting', 'purge_deleting' => ['实例删除中', 'failed'],
'purge_pending' => ['等待永久删除', 'failed'],
'purge_stopping' => ['删除前正在关机', 'failed'],
'purge_force_required' => ['等待管理员确认强制删除', 'failed'],
'delete_failed' => ['自动删除失败', 'failed'],
'purge_stop_failed' => ['删除前关机失败', 'failed'],
'purge_failed' => ['自动删除失败', 'failed'],
default => [$status !== '' ? $status : '未知', 'other'],
};
$entry = CloudBillingPresentationCatalog::status(
'financial', $status
);
return [
$entry['code'] === '' ? '未知' : $entry['label'],
self::userStatusClass($entry['tone']),
];
}
/** @return array{0: string, 1: string} */
private static function invoiceFulfillmentStatus(string $status,
string $purpose): array
{
if ($purpose === 'upgrade') {
return match (strtolower($status)) {
'queued', 'pending', 'running', 'active' => ['升级中', 'warning'],
'completed', 'succeeded' => ['已升级', 'running'],
'failed' => ['升级失败', 'failed'],
'cancelled', 'canceled' => ['已取消', 'other'],
default => ['', ''],
};
}
if ($purpose === 'ip_change') {
return match (strtolower($status)) {
'queued', 'pending', 'running', 'active' => ['更换中', 'warning'],
'completed', 'succeeded' => ['已更换', 'running'],
'review' => ['待人工核对', 'warning'],
'failed' => ['更换失败', 'failed'],
'cancelled', 'canceled' => ['已取消', 'other'],
default => ['', ''],
};
$entry = CloudBillingPresentationCatalog::status(
'fulfillment', $status, ['purpose' => $purpose]
);
if ($entry['code'] === '') {
return ['', ''];
}
return match (strtolower($status)) {
'awaiting_payment', 'payment_pending', 'draft'
=> ['等待支付', 'warning'],
'queued', 'pending', 'provisioning', 'running', 'active'
=> ['创建中', 'warning'],
'completed', 'succeeded' => ['已开通', 'running'],
'failed' => ['创建失败', 'failed'],
'refunded' => ['开通失败,已退款', 'failed'],
'cancelled', 'canceled' => ['已取消', 'other'],
default => ['', ''],
return [$entry['label'], self::userStatusClass($entry['tone'])];
}
private static function userStatusClass(string $tone): string
{
return match ($tone) {
'success' => 'running',
'warning', 'info' => 'warning',
'danger' => 'failed',
default => 'other',
};
}
private static function formatTimestamp($value,
string $fallback = '暂未提供'): string
{
return is_numeric($value) && (int) $value > 0
? date('Y/m/d H:i:s', (int) $value) : $fallback;
return CloudBillingPresentationCatalog::timestamp(
$value, $fallback, 'Y/m/d H:i:s'
);
}
private static function formatMemory(int $memoryMiB): string
@ -792,32 +764,17 @@ final class CloudInvoicePresentation
private static function paymentLabel(string $paidVia): string
{
return match (strtolower(trim($paidVia))) {
'balance' => '账户余额',
'yipay_alipay' => '易支付 · 支付宝',
'yipay_wxpay' => '易支付 · 微信',
'paytaro' => 'Paytaro · 支付宝',
'stripe_card' => 'Stripe · 银行卡',
'stripe_alipay' => 'Stripe · 支付宝',
'usdt' => 'USDT-TRC20',
default => $paidVia,
};
return CloudBillingPresentationCatalog::providerLabel($paidVia, '');
}
private static function currency($value): string
{
$currency = strtoupper(trim((string) ($value ?? '')));
return preg_match('/^[A-Z][A-Z0-9]{2,7}$/D', $currency) === 1
? $currency : 'USD';
return CloudBillingPresentationCatalog::currency($value);
}
private static function formatMoney($value, string $currency): string
{
if (!is_numeric($value) || (float) $value < 0) {
return $currency === 'USD' ? '$—' : '— ' . $currency;
}
$amount = number_format((float) $value, 2, '.', ',');
return $currency === 'USD' ? '$' . $amount : $amount . ' ' . $currency;
return CloudBillingPresentationCatalog::money($value, $currency);
}
private static function firstText(...$values): string

@ -1,49 +1,23 @@
const root = document.querySelector('[data-admin-billing]');
const byId = id => document.getElementById(id);
const FINANCIAL_OPTIONS = [
['', '全部财务状态'], ['open', '待支付'], ['overdue', '已逾期'],
['paid', '已支付'], ['refunded', '已退款'], ['expired', '已失效'], ['void', '已作废'],
];
const FULFILLMENT_OPTIONS = [
['', '全部履约状态'], ['awaiting_payment', '等待支付'], ['active', '执行中'],
['succeeded', '已成功'], ['failed', '已失败'], ['expired', '已失效'],
['refunded', '已退款'], ['cancelled', '已取消'],
];
const ORDER_OPTIONS = FULFILLMENT_OPTIONS;
const PAYMENT_OPTIONS = [
['', '全部支付状态'], ['creating', '创建中'], ['pending', '待支付'],
['paid_invoice', '已入账单'], ['credited_balance', '已入余额'], ['failed', '支付失败'],
['expired', '已失效'],
];
const PURPOSE_OPTIONS = [
['', '全部账单类型'], ['provision', '实例开通'], ['renewal', '实例续费'],
['upgrade', '实例升级'], ['ip_change', '更换公网 IP'],
['backup_addon', '自动备份开通'], ['recharge', '余额充值'],
];
const PROVIDER_OPTIONS = [
['', '全部支付渠道'], ['balance', '账户余额'], ['usdt', 'USDT-TRC20'],
['yipay_alipay', '易支付 · 支付宝'], ['yipay_wxpay', '易支付 · 微信'], ['paytaro', 'Paytaro'],
['stripe_card', 'Stripe · 银行卡'], ['stripe_alipay', 'Stripe · 支付宝'],
];
const VIEWS = {
invoices: {
title: '全部账单', description: '按财务状态与履约状态核对每一笔账单。',
queryPlaceholder: '账单 / 订单 / 套餐 / 用户 ID',
endpoint: '/api/v1/admin/billing/invoices', caption: '管理员账单列表',
primary: { key: 'financial_status', label: '财务状态', options: FINANCIAL_OPTIONS },
secondary: { key: 'fulfillment_status', label: '履约状态', options: FULFILLMENT_OPTIONS },
category: { key: 'purpose', label: '账单类型', options: PURPOSE_OPTIONS },
reference: { key: 'payment_method', label: '支付渠道', options: PROVIDER_OPTIONS },
primary: { key: 'financial_status', label: '财务状态', optionsKey: 'financial' },
secondary: { key: 'fulfillment_status', label: '履约状态', optionsKey: 'fulfillment' },
category: { key: 'purpose', label: '账单类型', optionsKey: 'purpose' },
reference: { key: 'payment_method', label: '支付渠道', optionsKey: 'provider' },
columns: ['账单', '用户', '项目', '金额', '财务状态', '履约状态', '支付渠道', '时间', '详情'],
},
orders: {
title: '开通任务', description: '跟踪支付后的实例开通队列与最终结果。',
queryPlaceholder: '任务 / 实例 / 套餐 / 用户 ID',
endpoint: '/api/v1/admin/billing/orders', caption: '管理员实例开通任务列表',
primary: { key: 'status', label: '履约状态', options: ORDER_OPTIONS },
secondary: { key: 'financial_status', label: '财务状态', options: FINANCIAL_OPTIONS },
primary: { key: 'status', label: '履约状态', optionsKey: 'fulfillment' },
secondary: { key: 'financial_status', label: '财务状态', optionsKey: 'financial' },
category: null, reference: null,
columns: ['任务', '用户', '套餐 / 宿主机', '金额', '财务状态', '履约状态', '实例 / 后台任务', '更新 / 异常', '账单'],
},
@ -51,8 +25,8 @@ const VIEWS = {
title: '支付流水', description: '核对支付尝试、入账去向与所属账单的财务状态。',
queryPlaceholder: '流水 / 账单 / 用户 ID',
endpoint: '/api/v1/admin/billing/payments', caption: '管理员支付流水列表',
primary: { key: 'status', label: '支付状态', options: PAYMENT_OPTIONS }, secondary: null,
category: { key: 'provider', label: '支付渠道', options: PROVIDER_OPTIONS },
primary: { key: 'status', label: '支付状态', optionsKey: 'payment' }, secondary: null,
category: { key: 'provider', label: '支付渠道', optionsKey: 'provider' },
reference: { key: 'invoice_id', label: '账单 ID', placeholder: '全部账单' },
columns: ['支付流水', '用户', '支付渠道', '金额', '支付状态', '账单财务状态', '用途', '时间', '账单'],
},
@ -63,7 +37,7 @@ const state = {
pagination: { page: 1, per_page: 30, total: 0, total_pages: 1, has_previous: false, has_next: false },
request: null, detailRequest: null, requestNumber: 0, detailInvoiceId: '', detailClosing: false,
detailClosePromise: null, detailOpener: null,
loadedView: '', loadedFilters: {}, cache: new Map(), scroll: null,
loadedView: '', loadedFilters: {}, cache: new Map(), scroll: null, catalog: {},
};
function element(tag, className = '', text) {
@ -80,31 +54,12 @@ function firstText(...values) {
return '';
}
function formatUsd(value) {
if (value === null || value === undefined || value === '') return '—';
const amount = Number(value);
if (!Number.isFinite(amount)) return '—';
const sign = amount < 0 ? '-$' : '$';
return sign + Math.abs(amount).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
function formatInteger(value) {
if (value === null || value === undefined || value === '') return '—';
const number = Number(value);
return Number.isFinite(number) ? Math.trunc(number).toLocaleString('zh-CN') : '—';
}
function formatDate(value) {
if (value === null || value === undefined || value === '') return '—';
const numeric = Number(value);
if (Number.isFinite(numeric) && numeric <= 0) return '—';
const timestamp = Number.isFinite(numeric)
? (numeric < 1e12 ? numeric * 1000 : numeric) : Date.parse(String(value));
const date = new Date(timestamp);
return Number.isFinite(date.getTime())
? date.toLocaleString('zh-CN', { hour12: false }) : '—';
}
function formatBytes(value) {
const bytes = Number(value);
if (!Number.isFinite(bytes) || bytes < 0) return '—';
@ -114,71 +69,14 @@ function formatBytes(value) {
return `${(bytes / (1024 ** index)).toLocaleString('zh-CN', { maximumFractionDigits: 2 })} ${units[index]}`;
}
function purposeLabel(value) {
return ({ provision: '实例开通', renewal: '实例续费', upgrade: '实例升级',
ip_change: '更换公网 IP', backup_addon: '自动备份开通',
recharge: '余额充值' })[String(value || '').toLowerCase()]
|| firstText(value, '未分类');
}
function providerLabel(value) {
const provider = String(value || '').toLowerCase();
return ({ balance: '账户余额', usdt: 'USDT-TRC20', yipay_alipay: '易支付 · 支付宝',
yipay_wxpay: '易支付 · 微信', paytaro: 'Paytaro',
stripe_card: 'Stripe · 银行卡', stripe_alipay: 'Stripe · 支付宝' })[provider] || firstText(value, '未记录');
}
function statusInfo(kind, value) {
const status = String(value || '').toLowerCase();
if (!status && kind === 'fulfillment') return ['不适用', 'neutral'];
const financial = {
open: ['待支付', 'warning'], overdue: ['已逾期', 'danger'], paid: ['已支付', 'success'],
refunded: ['已退款', 'info'], expired: ['已失效', 'neutral'], void: ['已作废', 'neutral'],
};
const fulfillment = {
awaiting_payment: ['等待支付', 'warning'], active: ['执行中', 'info'],
succeeded: ['已成功', 'success'], failed: ['已失败', 'danger'],
expired: ['已失效', 'neutral'], refunded: ['已退款', 'info'],
cancelled: ['已取消', 'neutral'],
};
const payment = {
creating: ['创建中', 'info'], pending: ['待支付', 'warning'], paid_invoice: ['已入账单', 'success'],
credited_balance: ['已入余额', 'success'], failed: ['支付失败', 'danger'], expired: ['已失效', 'neutral'],
};
const table = kind === 'financial' ? financial : kind === 'payment' ? payment : fulfillment;
return table[status] || [status || '未记录', 'neutral'];
}
function statusBadge(kind, value, purpose = '') {
let [label, tone] = statusInfo(kind, value);
if (kind === 'fulfillment' && purpose === 'renewal' && value === 'succeeded') label = '已续费';
if (kind === 'fulfillment' && purpose === 'upgrade') {
label = ({ active: '升级中', succeeded: '已升级', failed: '升级失败',
cancelled: '已取消' })[value] || label;
}
const badgeTone = {
success: 'bg-success-subtle text-success-emphasis',
warning: 'bg-warning-subtle text-warning-emphasis',
danger: 'bg-danger-subtle text-danger-emphasis',
info: 'bg-info-subtle text-info-emphasis',
neutral: 'bg-light text-dark',
}[tone] || 'bg-light text-dark';
return element('span', `badge rounded-pill fs-12 px-2 py-1 ${badgeTone}`, label);
function statusBadge(presentation) {
return element('span', `badge rounded-pill fs-12 px-2 py-1 ${firstText(
presentation?.class, 'bg-light text-dark',
)}`, firstText(presentation?.label, '未记录'));
}
function taskStatusBadge(task) {
let label = '任务状态协议无效';
let tone = 'danger';
if (task?.completed === false
&& (!Object.prototype.hasOwnProperty.call(task, 'status')
|| task.status === 'active')) {
label = '执行中'; tone = 'info';
} else if (task?.completed === true) {
const info = { succeeded: ['已成功', 'success'], failed: ['已失败', 'danger'] }[task.status];
if (info) [label, tone] = info;
}
const classes = { success: 'bg-success-subtle text-success-emphasis', danger: 'bg-danger-subtle text-danger-emphasis', info: 'bg-info-subtle text-info-emphasis', neutral: 'bg-light text-dark' };
return element('span', `badge rounded-pill fs-12 px-2 py-1 ${classes[tone]}`, label);
return statusBadge(task?.presentation?.status);
}
function stack(primary, secondary = '') {
@ -204,33 +102,40 @@ function detailButton(invoiceId, label = '查看账单') {
}
function invoiceCells(item) {
const display = item.presentation || {};
return [
stack(`#${item.id}`, purposeLabel(item.purpose)), accountCell(item),
stack(`#${item.id}`, firstText(display.purpose_label, '未分类')), accountCell(item),
stack(firstText(item.subject_name, item.plan_name, '账单项目'), item.plan_id ? `套餐 #${item.plan_id}` : ''),
element('span', 'admin-mono', formatUsd(item.amount)), statusBadge('financial', item.financial_status),
statusBadge('fulfillment', item.fulfillment_status, item.purpose), providerLabel(item.payment_method),
stack(formatDate(item.created_at), item.due_at ? `到期 ${formatDate(item.due_at)}` : ''), detailButton(item.id, '账单详情'),
element('span', 'admin-mono', firstText(display.amount_display, '—')),
statusBadge(display.financial_status), statusBadge(display.fulfillment_status),
firstText(display.provider_label, '未记录'),
stack(firstText(display.created_display, '—'), item.due_at ? `到期 ${firstText(display.due_display, '—')}` : ''),
detailButton(item.id, '账单详情'),
];
}
function orderCells(item) {
const display = item.presentation || {};
const taskDetails = [item.task_id ? `任务 #${item.task_id}` : ''].filter(Boolean).join(' · ');
return [
stack(`#${item.id}`, taskDetails), accountCell(item),
stack(firstText(item.plan_name, item.plan_id ? `套餐 #${item.plan_id}` : '套餐未记录'), item.host_id ? `宿主机 #${item.host_id}` : ''),
element('span', 'admin-mono', formatUsd(item.amount)), statusBadge('financial', item.financial_status),
statusBadge('fulfillment', item.fulfillment_status),
element('span', 'admin-mono', firstText(display.amount_display, '—')),
statusBadge(display.financial_status), statusBadge(display.fulfillment_status),
stack(item.instance_id ? `实例 #${item.instance_id}` : '实例 —', item.task_id ? `任务 #${item.task_id}` : '后台任务 —'),
stack(formatDate(firstText(item.updated_at, item.created_at)), firstText(item.error)), detailButton(item.invoice_id),
stack(firstText(display.updated_display, '—'), firstText(item.error)), detailButton(item.invoice_id),
];
}
function paymentCells(item) {
const display = item.presentation || {};
return [
stack(`#${item.id}`, item.invoice_id ? `账单 #${item.invoice_id}` : '未关联账单'), accountCell(item),
providerLabel(item.provider), element('span', 'admin-mono', formatUsd(item.amount)),
statusBadge('payment', item.payment_status), statusBadge('financial', item.invoice_financial_status),
purposeLabel(item.purpose), stack(formatDate(item.created_at), item.updated_at ? `更新 ${formatDate(item.updated_at)}` : ''),
firstText(display.provider_label, '未记录'),
element('span', 'admin-mono', firstText(display.amount_display, '—')),
statusBadge(display.payment_status), statusBadge(display.invoice_financial_status),
firstText(display.purpose_label, '未分类'),
stack(firstText(display.created_display, '—'), item.updated_at ? `更新 ${firstText(display.updated_display, '—')}` : ''),
detailButton(item.invoice_id),
];
}
@ -245,10 +150,11 @@ function setNotice(message, tone = '') {
function fillOptions(select, options, selected = '') {
select.replaceChildren();
for (const [value, label] of options) {
const option = element('option', '', label);
for (const entry of options) {
const value = firstText(entry?.value);
const option = element('option', '', firstText(entry?.label, value));
option.value = value;
option.selected = String(value) === String(selected || '');
option.selected = value === String(selected || '');
select.append(option);
}
}
@ -263,7 +169,9 @@ function configureFilter(kind, definition) {
control.name = definition?.key || '';
if (!definition) { control.value = ''; return; }
label.textContent = definition.label;
if (control instanceof HTMLSelectElement) fillOptions(control, definition.options);
if (control instanceof HTMLSelectElement) {
fillOptions(control, state.catalog[definition.optionsKey] || []);
}
}
function configureReference(definition) {
@ -281,8 +189,8 @@ function configureReference(definition) {
input.value = '';
if (!definition) return;
byId('billing-reference-label').textContent = definition.label;
if (Array.isArray(definition.options)) {
fillOptions(select, definition.options);
if (definition.optionsKey) {
fillOptions(select, state.catalog[definition.optionsKey] || []);
select.hidden = false;
select.disabled = false;
select.dataset.queryKey = definition.key;
@ -405,17 +313,18 @@ function resetSummary(busy) {
}
function renderSummary(summary = {}) {
const display = summary.presentation || {};
const total = Number(summary.total_records);
byId('billing-summary-total').textContent = Number.isFinite(total) ? formatInteger(total) : formatInteger(state.pagination.total);
byId('billing-summary-amount-label').textContent = state.view === 'payments'
? '支付尝试金额' : state.view === 'orders' ? '任务关联金额' : '账单面额';
byId('billing-summary-amount').textContent = formatUsd(summary.total_amount);
byId('billing-summary-amount').textContent = firstText(display.total_amount_display, '—');
if (state.view === 'invoices') {
byId('billing-summary-focus-label').textContent = '待收款';
byId('billing-summary-focus').textContent = `${formatInteger(summary.outstanding_count)} 笔 · ${formatUsd(summary.outstanding_amount)}`;
byId('billing-summary-focus').textContent = `${formatInteger(summary.outstanding_count)} 笔 · ${firstText(display.outstanding_amount_display, '—')}`;
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)}`;
byId('billing-summary-result').textContent = `${formatInteger(summary.paid_count)} 笔 · ${firstText(display.paid_amount_display, '—')}`;
byId('billing-summary-refunded').textContent = `${formatInteger(summary.refunded_count)} 笔 · ${firstText(display.refunded_amount_display, '—')}`;
} else if (state.view === 'orders') {
const counts = summary.status_counts || {};
byId('billing-summary-focus-label').textContent = '处理中';
@ -427,7 +336,7 @@ function renderSummary(summary = {}) {
byId('billing-summary-focus-label').textContent = '处理中';
byId('billing-summary-focus').textContent = `${formatInteger(countStatuses(counts, ['creating', 'pending']))} 笔`;
byId('billing-summary-result-label').textContent = '入账去向';
byId('billing-summary-result').textContent = `账单 ${formatUsd(summary.paid_invoice_amount)} · 余额 ${formatUsd(summary.credited_balance_amount)}`;
byId('billing-summary-result').textContent = `账单 ${firstText(display.paid_invoice_amount_display, '—')} · 余额 ${firstText(display.credited_balance_amount_display, '—')}`;
}
byId('billing-summary').setAttribute('aria-busy', 'false');
byId('billing-refund-card').hidden = state.view !== 'invoices';
@ -562,7 +471,9 @@ function shownFilters(filters) {
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}`);
const options = definition?.optionsKey
? state.catalog[definition.optionsKey] || [] : [];
if (value) parts.push(`${definition.label}:${options.find(option => String(option?.value) === value)?.label || value}`);
}
if (filters.created_from || filters.created_to) parts.push(`日期 ${unixToDate(filters.created_from) || '不限'} 至 ${unixToDate(filters.created_to) || '不限'}`);
return parts.join(' · ') || '全部记录';
@ -570,6 +481,10 @@ function shownFilters(filters) {
function applyListPayload(payload, filters, replaceRows = true) {
if (!Array.isArray(payload?.items) || !payload?.pagination || !payload?.summary) throw new Error('账单数据格式异常,请重试。');
if (!payload?.presentation?.catalog || typeof payload.presentation.catalog !== 'object') {
throw new Error('账单展示目录缺失,请重试。');
}
state.catalog = payload.presentation.catalog;
state.items = payload.items;
state.pagination = normalizePagination(payload.pagination);
state.page = state.pagination.page;
@ -577,6 +492,10 @@ function applyListPayload(payload, filters, replaceRows = true) {
state.loadedView = state.view;
state.loadedFilters = { ...filters };
state.cache.set(state.view, { ...payload, filters: { ...filters }, view: state.view });
configureView();
loadFiltersFromUrl(cachedParameters({
filters, pagination: state.pagination,
}));
if (replaceRows) renderRows();
renderSummary(payload.summary);
renderPagination();
@ -693,17 +612,22 @@ function safeLink(url, label) {
function renderDetail(payload) {
const invoice = payload?.invoice;
if (!invoice || String(invoice.id) !== state.detailInvoiceId) throw new Error('账单详情与请求不一致,请重试。');
const invoiceDisplay = invoice.presentation || {};
detailTabs.forEach(tab => byId('billing-panel-' + tab).replaceChildren());
byId('billing-detail-title').textContent = '账单 #' + invoice.id;
const overview = byId('billing-panel-overview');
overview.append(detailSection('账单概览', [
['用户', firstText(invoice.user_name, invoice.user_email, invoice.user_id ? '用户 #' + invoice.user_id : '')],
['账单类型', purposeLabel(invoice.purpose)], ['项目', firstText(invoice.subject_name, invoice.plan_name)],
['金额', formatUsd(invoice.amount)], ['财务状态', statusBadge('financial', invoice.financial_status)],
['履约状态', statusBadge('fulfillment', invoice.fulfillment_status, invoice.purpose)],
['支付渠道', providerLabel(invoice.payment_method)], ['创建时间', formatDate(invoice.created_at)],
['账单到期', formatDate(invoice.due_at)], ['支付截止', formatDate(invoice.payment_deadline_at)],
['支付时间', formatDate(invoice.paid_at)],
['账单类型', firstText(invoiceDisplay.purpose_label, '未分类')],
['项目', firstText(invoice.subject_name, invoice.plan_name)],
['金额', firstText(invoiceDisplay.amount_display, '—')],
['财务状态', statusBadge(invoiceDisplay.financial_status)],
['履约状态', statusBadge(invoiceDisplay.fulfillment_status)],
['支付渠道', firstText(invoiceDisplay.provider_label, '未记录')],
['创建时间', firstText(invoiceDisplay.created_display, '—')],
['账单到期', firstText(invoiceDisplay.due_display, '—')],
['支付截止', firstText(invoiceDisplay.payment_deadline_display, '—')],
['支付时间', firstText(invoiceDisplay.paid_display, '—')],
]));
const specification = invoice.specification || {};
if (invoice.purpose !== 'recharge') overview.append(detailSection('套餐与资源快照', [
@ -714,19 +638,21 @@ function renderDetail(payload) {
['带宽', 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) : ''],
['续费后到期', invoice.purpose === 'renewal'
? firstText(invoiceDisplay.renews_expires_display, '—') : ''],
]));
const funds = payload.funds || {};
const fundsDisplay = funds.presentation || {};
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) : '无已确认退款记录'],
['确认支付金额', firstText(fundsDisplay.settled_amount_display, '—')],
['已退款金额', firstText(fundsDisplay.refund_amount_display, '无已确认退款记录')],
['退款去向', funds.refund_destination === 'balance' ? '账户余额' : '—'],
['退款时间', formatDate(funds.refunded_at)],
['另行转入余额', formatUsd(funds.balance_retained_amount)],
['退款时间', firstText(fundsDisplay.refunded_at_display, '—')],
['另行转入余额', firstText(fundsDisplay.balance_retained_amount_display, '—')],
['转入余额笔数', formatInteger(funds.balance_retained_count)],
]));
for (const note of funds.notes || []) fundPanel.append(element('p', 'text-muted fs-13 mt-3', note));
@ -737,7 +663,7 @@ function renderDetail(payload) {
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) : '时间未记录'));
element('span', 'text-muted fs-12 d-block', firstText(entry.at_display, '时间未记录')));
if (entry.description) item.append(element('p', 'fs-13 mb-0', entry.description));
timeline.append(item);
}
@ -753,17 +679,18 @@ function renderDetail(payload) {
if (invoice.purpose === 'upgrade') fulfillment.append(element('p', 'alert alert-light', '升级账单在扣款时已创建后台任务,不可再次支付;请在此核对目标实例和最终任务状态。'));
if (order && invoice.purpose === 'provision') fulfillment.append(detailSection('开通任务', [
['任务 ID', order.id ? '#' + order.id : ''], ['套餐', firstText(order.plan_name)],
['财务状态', statusBadge('financial', firstText(order.financial_status, invoice.financial_status))],
['履约状态', statusBadge('fulfillment', order.fulfillment_status)],
['财务状态', statusBadge(order.presentation?.financial_status)],
['履约状态', statusBadge(order.presentation?.fulfillment_status)],
['实例 ID', order.instance_id ? '#' + order.instance_id : ''], ['后台任务', order.task_id ? '#' + order.task_id : ''],
['更新时间', formatDate(order.updated_at)], ['异常摘要', firstText(order.error)],
['更新时间', firstText(order.presentation?.updated_display, '—')],
['异常摘要', firstText(order.error)],
]));
const task = payload.task;
const task = payload.job;
if (task && ['provision', 'upgrade'].includes(invoice.purpose)) fulfillment.append(detailSection(
invoice.purpose === 'upgrade' ? '升级任务' : '后台任务', [
['任务 ID', task.id ? '#' + task.id : ''], ['类型', firstText(task.kind_label || task.action_label, task.kind)],
['状态', taskStatusBadge(task)], ['异常摘要', firstText(task.error)],
['更新时间', formatDate(task.updated_at)],
['更新时间', firstText(task.presentation?.updated_display, '—')],
]));
const instance = payload.instance;
if (instance) fulfillment.append(detailSection('关联实例', [
@ -771,7 +698,7 @@ function renderDetail(payload) {
['实例生命周期', ({ active: '在管', deleted: '已删除', deleting: '删除中', delete_failed: '删除失败' })[instance.status] || firstText(instance.status)],
['服务状态', ({ active: '服务正常', exempt: '免计费', expired: '已到期', expired_grace: '到期宽限期', resume_pending: '等待恢复', resume_failed: '恢复失败', purge_force_required: '等待确认强制删除', purge_deleting: '到期清理中', purge_failed: '到期清理失败' })[instance.service_status] || firstText(instance.service_status)],
['网络状态', ({ active: '正常', blocked_traffic: '流量耗尽已断网', blocked_expired: '到期已断网', blocking: '正在限制网络', blocking_expired: '到期断网中', block_failed: '限制网络失败', restore_pending: '等待恢复', restoring: '恢复中', restore_failed: '恢复失败' })[instance.network_status] || firstText(instance.network_status)],
['到期时间', formatDate(instance.expires_at)],
['到期时间', firstText(instance.presentation?.expires_display, '—')],
]));
if (!instance && !order && !task) fulfillment.append(element('p', 'text-muted', '当前无可用关联实例或后台任务,历史账单仍保留。'));
}
@ -782,11 +709,16 @@ function renderDetail(payload) {
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 attemptDisplay = attempt.presentation || {};
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) : '')));
body.append(element('strong', 'd-block mb-2', firstText(
attemptDisplay.provider_label, '未记录',
) + ' · ' + firstText(attemptDisplay.amount_display, '—')),
statusBadge(attemptDisplay.payment_status),
element('span', 'd-block text-muted fs-13 mt-2', `创建 ${firstText(
attemptDisplay.created_display, '—',
)}${attempt.updated_at ? ` · 更新 ${firstText(attemptDisplay.updated_display, '—')}` : ''}`));
card.append(body); payments.append(card);
}
const links = byId('billing-detail-links');
@ -1042,12 +974,19 @@ function initialize() {
if (!root) return;
const params = new URLSearchParams(location.search);
state.view = VIEWS[params.get('view')] ? params.get('view') : 'invoices';
let payload = null;
try {
payload = JSON.parse(byId('admin-billing-bootstrap').textContent);
if (payload?.presentation?.catalog
&& typeof payload.presentation.catalog === 'object') {
state.catalog = payload.presentation.catalog;
}
} catch { /* The normal refresh path handles an invalid bootstrap. */ }
configureView();
loadFiltersFromUrl();
bindEvents();
let ready = false;
try {
const payload = JSON.parse(byId('admin-billing-bootstrap').textContent);
if (payload?.view === state.view) {
applyListPayload(payload, payload.filters || activeFilters(), false);
ready = true;

@ -4,13 +4,14 @@
{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'=>'等待支付','active'=>'执行中','succeeded'=>'已成功','failed'=>'已失败','expired'=>'已失效','refunded'=>'已退款','cancelled'=>'已取消']}
{assign var=billing_payment value=[''=>'全部支付状态','creating'=>'创建中','pending'=>'待支付','paid_invoice'=>'已入账单','credited_balance'=>'已入余额','failed'=>'支付失败','expired'=>'已失效']}
{assign var=billing_purpose value=[''=>'全部账单类型','provision'=>'实例开通','renewal'=>'实例续费','upgrade'=>'实例升级','ip_change'=>'更换公网 IP','recharge'=>'余额充值']}
{assign var=billing_providers value=[''=>'全部支付渠道','balance'=>'账户余额','usdt'=>'USDT-TRC20','yipay_alipay'=>'易支付 · 支付宝','yipay_wxpay'=>'易支付 · 微信','paytaro'=>'Paytaro','stripe_card'=>'Stripe · 银行卡','stripe_alipay'=>'Stripe · 支付宝']}
{assign var=billing_catalog value=$billing_page.presentation.catalog|default:[]}
{assign var=billing_financial value=$billing_catalog.financial|default:[]}
{assign var=billing_fulfillment value=$billing_catalog.fulfillment|default:[]}
{assign var=billing_payment value=$billing_catalog.payment|default:[]}
{assign var=billing_purpose value=$billing_catalog.purpose|default:[]}
{assign var=billing_providers value=$billing_catalog.provider|default:[]}
{function name=billing_options options=[] selected=''}
{foreach $options as $value=>$label}<option value="{$value|escape}" {if $selected == $value}selected{/if}>{$label|escape}</option>{/foreach}
{foreach $options as $option}<option value="{$option.value|escape}" {if $selected == $option.value}selected{/if}>{$option.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">

@ -1,28 +1,22 @@
{assign var=billing_columns value=['账单','用户','项目','金额','财务状态','履约状态','支付渠道','时间','详情']}
{if $billing_view == 'orders'}{assign var=billing_columns value=['任务','用户','套餐 / 宿主机','金额','财务状态','履约状态','实例 / Agent 任务','更新 / 异常','账单']}{/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','overdue'])}{assign var=tone value='danger-subtle text-danger-emphasis'}{elseif in_array($value,['open','pending','awaiting_payment'])}{assign var=tone value='warning-subtle text-warning-emphasis'}{elseif in_array($value,['refunded','active','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 $kind == 'fulfillment' && $purpose == 'upgrade' && $value == 'active'}升级中{elseif $kind == 'fulfillment' && $purpose == 'upgrade' && $value == 'succeeded'}已升级{elseif $kind == 'fulfillment' && $purpose == 'upgrade' && $value == 'failed'}升级失败{elseif !$value}不适用{else}{$labels[$value]|default:$value|escape}{/if}</span>
{function name=billing_badge presentation=[]}
<span class="badge rounded-pill fs-12 px-2 py-1 {$presentation.class|default:'bg-light text-dark'|escape}">{$presentation.label|default:'未记录'|escape}</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:''}
{assign var=presentation value=$item.presentation|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.task_id}任务 #{$item.task_id|escape}{else}后台任务未记录{/if}{else}账单 #{$item.invoice_id|escape}{/if}</span></span></td>
<td data-label="{$billing_columns[0]|escape}"><span class="admin-checkout-user"><strong>#{$item.id|escape}</strong><span>{if $billing_view == 'invoices'}{$presentation.purpose_label|default:'未分类'|escape}{elseif $billing_view == 'orders'}{if $item.task_id}任务 #{$item.task_id|escape}{else}后台任务未记录{/if}{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.task_id}任务 #{$item.task_id|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[2]|escape}" class="admin-billing-secondary"><span class="admin-checkout-user"><strong>{if $billing_view == 'payments'}{$presentation.provider_label|default:'未记录'|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">{$presentation.amount_display|default:'—'|escape}</span></td>
<td data-label="{$billing_columns[4]|escape}">{if $billing_view == 'payments'}{billing_badge presentation=$presentation.payment_status}{else}{billing_badge presentation=$presentation.financial_status}{/if}</td>
<td data-label="{$billing_columns[5]|escape}">{if $billing_view == 'payments'}{billing_badge presentation=$presentation.invoice_financial_status}{else}{billing_badge presentation=$presentation.fulfillment_status}{/if}</td>
<td data-label="{$billing_columns[6]|escape}" class="admin-billing-secondary">{if $billing_view == 'invoices'}{$presentation.provider_label|default:'未记录'|escape}{elseif $billing_view == 'orders'}<span class="admin-checkout-user"><strong>{if $item.instance_id}实例 #{$item.instance_id|escape}{else}实例 —{/if}</strong><span>{if $item.task_id}任务 #{$item.task_id|escape}{else}后台任务 —{/if}</span></span>{else}{$presentation.purpose_label|default:'未分类'|escape}{/if}</td>
<td data-label="{$billing_columns[7]|escape}" class="admin-billing-secondary"><span class="admin-checkout-user"><strong>{if $billing_view == 'orders'}{$presentation.updated_display|default:'—'|escape}{else}{$presentation.created_display|default:'—'|escape}{/if}</strong>{if $billing_view == 'orders' && $item.error}<span>{$item.error|escape}</span>{elseif $billing_view == 'invoices' && $item.due_at}<span>到期 {$presentation.due_display|default:'—'|escape}</span>{elseif $billing_view == 'payments' && $item.updated_at}<span>更新 {$presentation.updated_display|default:'—'|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}

@ -1,10 +1,11 @@
{assign var=billing_summary value=$billing_page.summary|default:[]}
{assign var=billing_counts value=$billing_summary.status_counts|default:[]}
{assign var=billing_summary_display value=$billing_summary.presentation|default:[]}
{assign var=billing_processing value=0}
{if $billing_view == 'orders'}{assign var=billing_processing value=$billing_counts.active|default:0}{/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'}待收款{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>
<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_display.total_amount_display|default:'—'|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'}待收款{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_display.outstanding_amount_display|default:'—'|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_display.paid_amount_display|default:'—'|escape}{elseif $billing_view == 'orders'}{$billing_counts.succeeded|default:0|escape} / {$billing_counts.failed|default:0|escape}{else}账单 {$billing_summary_display.paid_invoice_amount_display|default:'—'|escape} · 余额 {$billing_summary_display.credited_balance_amount_display|default:'—'|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_display.refunded_amount_display|default:'—'|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='2026110119' scope='global'}
{assign var=venix_asset_version value='2026110120' scope='global'}

@ -81,10 +81,13 @@ $routes = $read('config/routes_cloud.php');
$middleware = $read('app/Middleware/CloudApi.php');
$controller = $read('app/Controllers/CloudAdminBillingController.php');
$service = $read('app/Services/Cloud/CloudAdminBillingService.php');
$catalog = $read('app/Services/Cloud/CloudBillingPresentationCatalog.php');
$presentation = $read('app/Services/Cloud/CloudAdminBillingPresentation.php');
$client = $read('public/cloud/admin-billing.js');
$template = $read('resources/views/venix/admin/billing.tpl');
$rowsTemplate = $read('resources/views/venix/admin/billing_rows.tpl');
$summaryTemplate = $read('resources/views/venix/admin/billing_summary.tpl');
$layoutAssets = $read('resources/views/venix/layout_assets.tpl');
$schema = $read('sql/cloud.sql');
$routeContracts = [
@ -293,10 +296,43 @@ $assert(str_contains($detail, 'self::DETAIL_PAYMENT_LIMIT + 1')
&& str_contains($client, 'payment_attempts_truncated')
&& str_contains($client, '仅显示最近 100 条'),
'Invoice detail must bound and disclose truncated payment-attempt history.');
$assert(str_contains($client, "['支付截止', formatDate(invoice.payment_deadline_at)]")
$assert(str_contains($client, "invoiceDisplay.payment_deadline_display")
&& str_contains($client, 'resetSummary(false)')
&& str_contains($client, "setAttribute('aria-busy', String(busy))"),
'Billing detail deadlines and failed-list summary state must remain accurate.');
$assert(str_contains($service, "CloudAdminBillingPresentation::page('invoices'")
&& str_contains($service, 'CloudAdminBillingPresentation::detail(')
&& str_contains($presentation, 'CloudBillingPresentationCatalog::status(')
&& str_contains($catalog, "'backup_addon' => '自动备份开通'")
&& str_contains($catalog, "'paytaro' => 'Paytaro · 支付宝'")
&& !str_contains($client, 'function purposeLabel(')
&& !str_contains($client, 'function providerLabel(')
&& !str_contains($client, 'function statusInfo(')
&& !str_contains($client, 'function formatUsd(')
&& !str_contains($client, 'function formatDate('),
'Billing presentation labels or formatting drifted back into the browser.');
$assert(str_contains($invoiceSummary, 'COUNT(DISTINCT')
&& str_contains($invoiceSummary, 'ELSE NULL END AS total_amount')
&& str_contains($orderSummary, 'COUNT(DISTINCT')
&& str_contains($orderSummary, 'ELSE NULL END AS total_amount')
&& str_contains($paymentSummary,
"leftJoin('cloud_invoices AS billing_currency_invoice'")
&& str_contains($paymentSummary, 'COUNT(DISTINCT')
&& str_contains($paymentSummary, 'ELSE NULL END AS total_amount')
&& str_contains($presentation, "? '多币种'")
&& !str_contains($summaryTemplate, 'string_format'),
'Administrator summaries must never combine amounts across currencies.');
$invoicePresentation = $read('app/Services/Cloud/CloudInvoicePresentation.php');
$assert(str_contains($invoicePresentation,
'CloudBillingPresentationCatalog::status(')
&& str_contains($invoicePresentation, 'self::userStatusClass(')
&& !str_contains($invoicePresentation, 'match (strtolower($status))'),
'User invoice statuses must translate catalog tones, not rebuild semantics.');
$assert(str_contains($layoutAssets,
"venix_asset_version value='2026110120'")
&& str_contains($template,
'/cloud/admin-billing.js?v={$venix_asset_version}'),
'Administrator billing asset changes must advance the shared cache key.');
$assert(preg_match("/private const ORDER_STATUSES = \\[[^]]*'active'[^]]*'succeeded'[^]]*'failed'[^]]*'cancelled'/s", $service) === 1
&& preg_match("/private const FULFILLMENT_STATUSES = \\[[^]]*'active'[^]]*'succeeded'[^]]*'failed'[^]]*'cancelled'/s", $service) === 1
&& !str_contains($service, "'needs_attention'")

@ -12,7 +12,7 @@ set_error_handler(static function (int $severity, string $message, string $file,
$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,
'amount' => '10.00', 'currency' => 'USD', 'payment_method' => 'balance', 'due_at' => $now + 86400,
'paid_at' => $now - 3500, 'created_at' => $now - 3600, 'updated_at' => $now - 3400,
'order_id' => '301', 'task_id' => '501', 'instance_id' => '101', 'renewal_id' => null];
$invoices = [
@ -28,7 +28,7 @@ $invoices = [
$orders = [
[
'id' => '301', 'user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test',
'plan_id' => '3', 'plan_name' => '标准云服务器', 'host_id' => '7', 'amount' => '10.00',
'plan_id' => '3', 'plan_name' => '标准云服务器', 'host_id' => '7', 'amount' => '10.00', 'currency' => 'USD',
'financial_status' => 'paid', 'fulfillment_status' => 'active', 'invoice_id' => '201',
'task_id' => '501', 'job_status' => 'active', 'job_completed' => false,
'instance_id' => '101', 'attempts' => 1,
@ -36,14 +36,14 @@ $orders = [
],
[
'id' => '302', 'user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test',
'plan_id' => '3', 'plan_name' => '标准云服务器', 'host_id' => '7', 'amount' => '10.00',
'plan_id' => '3', 'plan_name' => '标准云服务器', 'host_id' => '7', 'amount' => '10.00', 'currency' => 'USD',
'financial_status' => 'paid', 'fulfillment_status' => 'failed', 'invoice_id' => '206',
'task_id' => '502', 'job_status' => 'failed', 'job_completed' => true,
'instance_id' => '102', 'attempts' => 1,
'error' => '任务已失败,不会自动重试', 'refunded_at' => null, 'created_at' => $now - 7200, 'updated_at' => $now - 120,
],
];
$paymentBase = ['user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test',
$paymentBase = ['user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test', 'currency' => 'USD',
'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']),
@ -64,12 +64,19 @@ foreach (['invoices' => $invoices, 'orders' => $orders, 'payments' => $payments]
}
$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'];
'refunded_count' => 1, 'refunded_amount' => '10.00',
'currency_count' => 1, 'currency' => 'USD', 'mixed_currency' => false];
$pages['orders']['summary'] = ['total_records' => 2, 'total_amount' => '20.00',
'status_counts' => ['active' => 1, 'failed' => 1]];
'status_counts' => ['active' => 1, 'failed' => 1],
'currency_count' => 1, 'currency' => 'USD', 'mixed_currency' => false];
$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]];
'status_counts' => ['paid_invoice' => 1, 'credited_balance' => 1],
'currency_count' => 1, 'currency' => 'USD', 'mixed_currency' => false];
foreach ($pages as $view => $page) {
$pages[$view] = ['view' => $view]
+ \App\Services\Cloud\CloudAdminBillingPresentation::page($view, $page);
}
$details = [];
foreach ($invoices as $row) {
@ -106,6 +113,9 @@ foreach ($invoices as $row) {
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];
}
foreach ($details as $id => $detail) {
$details[$id] = \App\Services\Cloud\CloudAdminBillingPresentation::detail($detail);
}
$smarty = new Smarty();
$compileDir = sys_get_temp_dir() . '/admin-billing-view-' . bin2hex(random_bytes(6));
@ -158,6 +168,64 @@ foreach ($pages as $view => $page) {
'Billing details must reuse the existing administrator instance drawer.');
}
$assert(str_contains($html['invoices'], '已续费'), 'Renewal completion must not be labelled instance provisioning.');
$catalogProbe = ['view' => 'invoices']
+ \App\Services\Cloud\CloudAdminBillingPresentation::page('invoices', [
'items' => [array_replace($common, [
'id' => '299', 'purpose' => 'backup_addon',
'amount' => '12.50', 'currency' => 'EUR',
'payment_method' => 'paytaro', 'financial_status' => 'paid',
'fulfillment_status' => null,
])],
'filters' => $filters + $viewFilters['invoices'],
'pagination' => ['page' => 1, 'per_page' => 30, 'total' => 1,
'total_pages' => 1, 'has_previous' => false, 'has_next' => false],
'summary' => ['total_records' => 1, 'total_amount' => '12.50',
'outstanding_count' => 0, 'outstanding_amount' => '0.00',
'paid_count' => 1, 'paid_amount' => '12.50',
'refunded_count' => 0, 'refunded_amount' => '0.00',
'currency_count' => 1, 'currency' => 'EUR',
'mixed_currency' => false],
]);
$catalogHtml = $render($catalogProbe);
$assert(str_contains($catalogHtml, '自动备份开通')
&& str_contains($catalogHtml, 'Paytaro · 支付宝')
&& str_contains($catalogHtml, '12.50 EUR')
&& str_contains($catalogHtml,
$catalogProbe['summary']['presentation']['total_amount_display'])
&& str_contains($catalogHtml,
$catalogProbe['items'][0]['presentation']['created_display']),
'SSR did not consume the same backup, provider, currency or time presentation as refresh JSON.');
$mixedProbe = ['view' => 'invoices']
+ \App\Services\Cloud\CloudAdminBillingPresentation::page('invoices', [
'items' => [
array_replace($common, [
'id' => '300', 'amount' => '10.00', 'currency' => 'USD',
'financial_status' => 'paid', 'fulfillment_status' => null,
]),
array_replace($common, [
'id' => '301', 'amount' => '12.50', 'currency' => 'EUR',
'financial_status' => 'paid', 'fulfillment_status' => null,
]),
],
'filters' => $filters + $viewFilters['invoices'],
'pagination' => ['page' => 1, 'per_page' => 30, 'total' => 2,
'total_pages' => 1, 'has_previous' => false, 'has_next' => false],
'summary' => ['total_records' => 2, 'total_amount' => null,
'outstanding_count' => 0, 'outstanding_amount' => null,
'paid_count' => 2, 'paid_amount' => null,
'refunded_count' => 0, 'refunded_amount' => null,
'currency_count' => 2, 'currency' => null,
'mixed_currency' => true],
]);
$mixedHtml = $render($mixedProbe);
$dom->loadHTML('<?xml encoding="UTF-8">' . $mixedHtml);
$xpath = new DOMXPath($dom);
$assert(trim($xpath->query('//*[@id="billing-summary-amount"]')
->item(0)->textContent) === '多币种'
&& str_contains($dom->textContent, '$10.00')
&& str_contains($dom->textContent, '12.50 EUR')
&& !str_contains($dom->textContent, '$22.50'),
'SSR mixed-currency summary fabricated a total or disagreed with its rows.');
$assert(str_contains($html['orders'], '执行中')
&& str_contains($html['orders'], '已失败'),
'Active and terminal task receipts must be visible in the first billing paint and summary.');

@ -127,6 +127,7 @@ namespace {
$table->integer('plan_id')->nullable();
$table->integer('host_id')->default(7);
$table->string('amount')->default('1.25');
$table->string('currency')->default('USD');
$table->string('status')->default('queued');
$table->text('spec_json')->default('{}');
$table->text('sealed_payload')->default('must-not-expose-order-payload');
@ -203,6 +204,8 @@ namespace {
['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'],
['id' => 20, 'user_name' => 'Mixed Currency', 'email' => 'mixed@example.test'],
['id' => 21, 'user_name' => 'Euro Customer', 'email' => 'euro@example.test'],
]);
Capsule::table('shop')->insert([
['id' => 7, 'name' => 'Standard Cloud'],
@ -374,6 +377,27 @@ namespace {
'payment_reference' => 'instance-upgrade-203',
'paid_at' => $now - 90]);
// Currency is frozen on invoices/orders. Payment rows inherit the
// owner-scoped invoice currency because the payment table has no currency.
$insertOrder(320, ['user_id' => 21, 'amount' => '12.50',
'currency' => 'EUR']);
$insertInvoice(320, ['user_id' => 21, 'order_id' => 320,
'purpose' => 'recharge', 'amount' => '12.50', 'currency' => 'EUR',
'status' => 'paid', 'paid_at' => $now - 70]);
$insertPayment(320, ['user_id' => 21, 'invoice_id' => 320,
'amount' => '12.50', 'status' => 'paid_invoice']);
foreach ([330 => ['USD', '10.00'], 331 => ['EUR', '12.50']]
as $id => [$currency, $amount]) {
$insertOrder($id, ['user_id' => 20, 'amount' => $amount,
'currency' => $currency]);
$insertInvoice($id, ['user_id' => 20, 'order_id' => $id,
'purpose' => 'recharge', 'amount' => $amount,
'currency' => $currency, 'status' => 'paid',
'paid_at' => $now - 70]);
$insertPayment($id, ['user_id' => 20, 'invoice_id' => $id,
'amount' => $amount, 'status' => 'paid_invoice']);
}
// 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++) {
@ -405,6 +429,10 @@ namespace {
&& $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);
$assert(isset($page['presentation']['catalog'])
&& isset($page['items'][0]['presentation'])
&& ($page['items'][0]['presentation']['amount_display'] ?? '') === '$1.25',
'Administrator billing page did not attach its shared presentation: ' . $view);
$seen = [];
for ($number = 1; $number <= 2; $number++) {
$chunk = CloudAdminBillingService::page([
@ -468,6 +496,45 @@ namespace {
&& $paymentSummary['status_counts']['pending'] === 1
&& $paymentSummary['status_counts']['failed'] === 1,
'Attempted amounts, invoice settlement records, and retained balance were incorrectly combined.');
foreach (['invoices', 'orders', 'payments'] as $view) {
$euro = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '21',
]);
$assert($euro['summary']['currency_count'] === 1
&& $euro['summary']['currency'] === 'EUR'
&& $euro['summary']['mixed_currency'] === false
&& $euro['summary']['total_amount'] === '12.50'
&& $euro['summary']['presentation']['total_amount_display']
=== '12.50 EUR'
&& $euro['items'][0]['currency'] === 'EUR'
&& $euro['items'][0]['presentation']['amount_display']
=== '12.50 EUR',
'Single EUR row and summary diverged: ' . $view);
$mixed = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '20',
]);
$rowCurrencies = array_column($mixed['items'], 'currency');
sort($rowCurrencies);
$assert($mixed['summary']['currency_count'] === 2
&& $mixed['summary']['currency'] === null
&& $mixed['summary']['mixed_currency'] === true
&& $mixed['summary']['total_amount'] === null
&& $mixed['summary']['presentation']['total_amount_display']
=== '多币种'
&& $rowCurrencies === ['EUR', 'USD'],
'Mixed currencies were combined into a fabricated amount: ' . $view);
}
$mixedInvoices = CloudAdminBillingService::invoices(['user_id' => '20']);
$assert($mixedInvoices['summary']['paid_amount'] === null
&& $mixedInvoices['summary']['presentation']['paid_amount_display']
=== '多币种',
'Mixed-currency invoice paid amount was still combined.');
$mixedPayments = CloudAdminBillingService::payments(['user_id' => '20']);
$assert($mixedPayments['summary']['paid_invoice_amount'] === null
&& $mixedPayments['summary']['presentation']['paid_invoice_amount_display']
=== '多币种',
'Mixed-currency payment settlement amount was still combined.');
foreach ([
['financial_status' => 'paid', 'expected' => [6, 5, 1]],
['financial_status' => 'refunded', 'expected' => [2]],
@ -536,6 +603,12 @@ namespace {
&& $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[1]['invoice']['presentation']['amount_display'] ?? null)
=== '$100.00'
&& ($details[1]['invoice']['presentation']['financial_status']['label'] ?? null)
=== '已支付'
&& ($details[1]['timeline'][0]['at_display'] ?? '') !== '',
'Administrator invoice detail did not attach stable display fields.');
$assert($details[2]['funds']['settled_amount'] === '30.00'
&& $details[2]['funds']['refund_amount'] === '30.00'
&& $details[2]['funds']['refund_destination'] === 'balance'

@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void {
};
$assert(is_string($assets)
&& preg_match("/venix_asset_version value='[0-9]+'/", $assets) === 1
&& str_contains($assets, "venix_asset_version value='2026110120'")
&& is_string($cloudShell)
&& str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'),
'The cloud application entry must use the shared Venix asset version.');

@ -17,25 +17,28 @@ $listTemplate = $read('resources/views/venix/cloud/pages/invoices.tpl');
$listRuntime = $read('public/cloud/invoices.js');
$detailRuntime = $read('public/cloud/invoice-detail-runtime.js');
$adminRuntime = $read('public/cloud/admin-billing.js');
$catalog = $read('app/Services/Cloud/CloudBillingPresentationCatalog.php');
$presentation = $read('app/Services/Cloud/CloudInvoicePresentation.php');
$adminPresentation = $read('app/Services/Cloud/CloudAdminBillingPresentation.php');
$assert(str_contains($pageService, "'backup_addon'")
&& substr_count($invoiceService,
"'backup_addon' => '自动备份开通'") >= 2,
'Automatic-backup bills are not recognized by user invoice services.');
$assert(str_contains($listTemplate, 'value="backup_addon"')
&& str_contains($listRuntime, "value === 'backup_addon'")
&& str_contains($listRuntime, "backup_addon: '自动备份开通'")
&& str_contains($detailRuntime, "value === 'backup_addon'")
&& str_contains($detailRuntime, "backup_addon: '自动备份开通'")
&& str_contains($detailRuntime, "purpose === 'backup_addon'")
&& str_contains($listRuntime, 'invoice?.title')
&& str_contains($detailRuntime, 'payload?.presentation')
&& str_contains($presentation,
'CloudBillingPresentationCatalog::knownPurposeLabel($purpose)')
&& str_contains($catalog, "'backup_addon' => '自动备份开通'")
&& str_contains($detailRuntime, '/user/cloud/instances/'),
'User invoice UI hides the add-on type or its linked instance.');
$assert(str_contains($adminService,
"'provision', 'renewal', 'upgrade', 'ip_change', 'backup_addon', 'recharge'")
&& str_contains($adminRuntime,
"['backup_addon', '自动备份开通']")
&& str_contains($adminRuntime,
"backup_addon: '自动备份开通'"),
'state.catalog[definition.optionsKey]')
&& str_contains($adminPresentation,
'CloudBillingPresentationCatalog::filterOptions()'),
'Administrator billing filters or labels omit automatic-backup add-ons.');
echo "Automatic-backup invoice presentation contract passed.\n";

@ -0,0 +1,146 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudAdminBillingPresentation;
use App\Services\Cloud\CloudBillingPresentationCatalog;
use App\Services\Cloud\CloudInvoicePresentation;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$previousTimezone = date_default_timezone_get();
date_default_timezone_set('Asia/Shanghai');
try {
$assert(CloudBillingPresentationCatalog::purposeLabel('backup_addon')
=== '自动备份开通'
&& CloudBillingPresentationCatalog::providerLabel('paytaro')
=== 'Paytaro · 支付宝'
&& CloudBillingPresentationCatalog::money('12.5', 'USD') === '$12.50'
&& CloudBillingPresentationCatalog::money('12.5', 'EUR') === '12.50 EUR'
&& CloudBillingPresentationCatalog::timestamp(1761984000)
=== date('Y-m-d H:i:s', 1761984000),
'Shared billing vocabulary drifted for backup, Paytaro, currency or time.');
$upgradeStatus = CloudBillingPresentationCatalog::status(
'fulfillment', 'running', ['purpose' => 'upgrade']
);
$ipReviewStatus = CloudBillingPresentationCatalog::status(
'fulfillment', 'review', ['purpose' => 'ip_change']
);
$provisionRefundStatus = CloudBillingPresentationCatalog::status(
'fulfillment', 'refunded', ['purpose' => 'provision']
);
$assert($upgradeStatus['label'] === '升级中'
&& $upgradeStatus['tone'] === 'info'
&& $ipReviewStatus['label'] === '待人工核对'
&& $ipReviewStatus['tone'] === 'warning'
&& $provisionRefundStatus['label'] === '开通失败,已退款'
&& $provisionRefundStatus['tone'] === 'danger'
&& CloudBillingPresentationCatalog::status(
'financial', 'void'
)['label'] === '已作废',
'Purpose-aware status semantics escaped the shared catalog.');
$row = [
'id' => '9', 'purpose' => 'backup_addon', 'amount' => '12.50',
'currency' => 'EUR', 'financial_status' => 'paid',
'fulfillment_status' => null, 'payment_method' => 'paytaro',
'created_at' => 1761984000, 'updated_at' => 1761984000,
'due_at' => 1762070400,
];
$page = CloudAdminBillingPresentation::page('invoices', [
'items' => [$row], 'summary' => [
'total_records' => 1, 'total_amount' => '12.50',
'currency_count' => 1, 'currency' => 'EUR',
'mixed_currency' => false,
],
]);
$display = $page['items'][0]['presentation'];
$assert($display['purpose_label'] === '自动备份开通'
&& $display['provider_label'] === 'Paytaro · 支付宝'
&& $display['amount_display'] === '12.50 EUR'
&& $display['financial_status']['label'] === '已支付'
&& $display['created_display']
=== CloudBillingPresentationCatalog::timestamp(1761984000)
&& ($page['items'][0]['financial_status'] ?? null) === 'paid',
'Administrator adapter changed machine fields or diverged from the catalog.');
$assert($page['summary']['presentation']['total_amount_display']
=== '12.50 EUR'
&& $page['summary']['presentation']['mixed_currency'] === false,
'Single-currency administrator summary ignored its frozen currency.');
$mixed = CloudAdminBillingPresentation::page('payments', [
'items' => [],
'summary' => [
'total_records' => 2, 'total_amount' => null,
'paid_invoice_amount' => null,
'credited_balance_amount' => null,
'currency_count' => 2, 'currency' => null,
'mixed_currency' => true,
],
]);
$assert($mixed['summary']['presentation']['total_amount_display']
=== '多币种'
&& $mixed['summary']['presentation']['paid_invoice_amount_display']
=== '多币种'
&& $mixed['summary']['presentation']['mixed_currency'] === true,
'Mixed-currency administrator summary fabricated a combined amount.');
$user = CloudInvoicePresentation::detail([
'invoice' => [
'id' => '9', 'purpose' => 'backup_addon', 'amount' => '12.50',
'currency' => 'EUR', 'status' => 'paid',
'created_at' => 1761984000, 'paid_via' => 'paytaro',
],
]);
$facts = array_column($user['facts'], 'value', 'label');
$assert($user['title'] === $display['purpose_label']
&& $user['amount_display'] === $display['amount_display']
&& ($facts['支付方式'] ?? null) === $display['provider_label'],
'User and administrator presentation stopped sharing billing vocabulary.');
$voidUser = CloudInvoicePresentation::summaries([[
'id' => '10', 'purpose' => 'recharge', 'amount' => '1.00',
'currency' => 'USD', 'status' => 'void', 'created_at' => 1761984000,
]])[0];
$assert($voidUser['status_label']
=== CloudBillingPresentationCatalog::status(
'financial', 'void'
)['label']
&& $voidUser['status_class'] === 'other',
'User adapter overrode the catalog financial label or tone.');
$options = $page['presentation']['catalog'];
$find = static function (array $options, string $value): ?string {
foreach ($options as $option) {
if (($option['value'] ?? null) === $value) {
return $option['label'] ?? null;
}
}
return null;
};
$assert($find($options['purpose'], 'backup_addon') === '自动备份开通'
&& $find($options['provider'], 'paytaro') === 'Paytaro · 支付宝'
&& $find($options['fulfillment'], 'queued') === null
&& $find($options['fulfillment'], 'review') === null,
'Server filter options diverged from row presentation labels.');
$userSource = file_get_contents(
dirname(__DIR__) . '/app/Services/Cloud/CloudInvoicePresentation.php'
);
$assert(is_string($userSource)
&& str_contains($userSource,
"CloudBillingPresentationCatalog::status(\n 'financial'")
&& str_contains($userSource,
"CloudBillingPresentationCatalog::status(\n 'fulfillment'")
&& !str_contains($userSource, 'match (strtolower($status))'),
'User invoice adapter rebuilt status labels outside the shared catalog.');
} finally {
date_default_timezone_set($previousTimezone);
}
echo "Shared billing presentation catalog and administrator adapter checks passed.\n";

@ -34,6 +34,9 @@ $invoiceDetailPageService = file_get_contents(
$invoicePresentation = file_get_contents(
$root . '/app/Services/Cloud/CloudInvoicePresentation.php'
);
$billingCatalog = file_get_contents(
$root . '/app/Services/Cloud/CloudBillingPresentationCatalog.php'
);
$invoiceDetailTemplate = file_get_contents(
$root . '/resources/views/venix/cloud/pages/invoice-detail.tpl'
);
@ -510,9 +513,11 @@ $assert(str_contains($statusService,
"->where('user_id', \$invoice->user_id)")
&& str_contains($statusService, '$instanceId = $linkedInstance?->id;'),
'Polling must validate the linked instance owner before exposing its id.');
$assert(str_contains($invoicePresentation, "'recharge' => '余额充值'")
&& str_contains($invoicePresentation, "'provision' => '实例开通'")
&& str_contains($invoicePresentation, "'renewal' => '实例续费'")
$assert(str_contains($billingCatalog, "'recharge' => '余额充值'")
&& str_contains($billingCatalog, "'provision' => '实例开通'")
&& str_contains($billingCatalog, "'renewal' => '实例续费'")
&& str_contains($invoicePresentation,
'CloudBillingPresentationCatalog::knownPurposeLabel($purpose)')
&& str_contains($invoicePresentation, "'title' => self::invoiceTitle("),
'Invoice purpose labels are incomplete.');
$assert(!str_contains($displayMethod, "'invoice_no' =>"),

@ -24,27 +24,30 @@ $adminInstancesRuntime = $read('public/cloud/admin-instances.js')
. "\n" . $read('public/cloud/admin-instance-detail.js');
$invoiceService = $read('app/Services/Cloud/CloudInvoiceService.php');
$pageController = $read('app/Controllers/CloudPageController.php');
$presentation = $read('app/Services/Cloud/CloudInvoicePresentation.php');
$catalog = $read('app/Services/Cloud/CloudBillingPresentationCatalog.php');
$adminPresentation = $read('app/Services/Cloud/CloudAdminBillingPresentation.php');
$assert(str_contains($listTemplate, 'value="upgrade"')
&& str_contains($listTemplate, '升级账单')
&& str_contains($listRuntime, "upgrade: '实例升级'")
&& str_contains($listRuntime, "purpose === 'upgrade'"),
&& str_contains($listRuntime, 'invoice?.title')
&& str_contains($catalog, "'upgrade' => '实例升级'"),
'The user invoice list does not identify or refresh upgrade invoices.');
$assert(str_contains($detailRuntime, "if (!['provision', 'renewal'].includes(purpose)) return false;")
&& str_contains($detailRuntime, "upgrade: '实例升级'")
&& str_contains($detailRuntime, "purpose === 'upgrade'")
&& str_contains($detailRuntime, "purpose === 'upgrade' ? '目标周期流量' : '周期流量'")
&& str_contains($pageController, "? '目标周期流量' : '周期流量'")
$assert(str_contains($detailRuntime, 'invoiceCanPay(invoice)')
&& str_contains($detailRuntime, 'presentation?.fulfillment_title')
&& str_contains($presentation, "if (\$purpose === 'upgrade')")
&& str_contains($presentation, "? '目标周期流量' : '周期流量'")
&& str_contains($detailTemplate, 'id="invoice-fulfillment-title"'),
'Upgrade invoice detail must show task state without exposing payment controls.');
$assert(str_contains($invoiceService,
"if (!in_array(\$purpose, ['provision', 'renewal'], true))")
&& str_contains($invoiceService, "throw new CloudError('该账单不支持再次支付', 409);"),
'The billing service does not reject replayed payment attempts for paid operational invoices.');
$assert(str_contains($adminTemplate, "'upgrade'=>'实例升级'")
&& str_contains($adminRuntime, "['upgrade', '实例升级']")
&& str_contains($adminRuntime, "upgrade: '实例升级'")
&& str_contains($adminRuntime, "task.status === 'active'"),
$assert(str_contains($adminTemplate, '$billing_catalog.purpose')
&& str_contains($adminRuntime, 'state.catalog[definition.optionsKey]')
&& str_contains($catalog, "'upgrade' => '实例升级'")
&& str_contains($adminPresentation,
"CloudBillingPresentationCatalog::purposeLabel(\$purpose)"),
'Administrator billing cannot label or filter upgrade invoices.');
$assert(str_contains($adminInstancesRuntime, "upgrade: '实例升级'"),
'Administrator instance billing drawer exposed the raw upgrade purpose.');

@ -87,6 +87,12 @@ $cloudSchema = file_get_contents($root . '/sql/cloud.sql');
$adminBillingTemplate = $views . '/admin/billing.tpl';
$adminBillingScript = $public . '/admin-billing.js';
$adminBillingRuntime = file_get_contents($adminBillingScript);
$invoicePresentationSource = file_get_contents(
$root . '/app/Services/Cloud/CloudInvoicePresentation.php'
);
$billingPresentationCatalog = file_get_contents(
$root . '/app/Services/Cloud/CloudBillingPresentationCatalog.php'
);
$adminInstanceScript = file_get_contents($public . '/admin-instances.js')
. "\n" . file_get_contents($public . '/admin-instance-detail.js');
$adminBillingStyles = $public . '/admin-billing.css';
@ -969,8 +975,9 @@ $assert(str_contains($clientEntry, "'invoice-detail': '/cloud/invoice-detail.js'
&& !str_contains($invoiceDetailModule, '/cloud/runtime.js')
&& !str_contains($invoiceDetailModule, '/api/v1/invoices/'),
'Invoice details must hydrate SSR data through a dedicated lightweight module.');
$assert(str_contains($clientScript, "recharge: '余额充值', provision: '实例开通', renewal: '实例续费'")
&& str_contains($clientScript, '`账单 #${invoice.id} · ${formatDate(invoice.created_at)}`')
$assert(str_contains($clientScript, "String(invoice?.title || '账单')")
&& str_contains($clientScript, 'invoice?.created_display')
&& str_contains($clientScript, 'invoice?.amount_display')
&& str_contains($clientScript, "makeElement('div', 'cloud-invoice-list-amount')")
&& str_contains($clientScript,
'link.href = `/user/cloud/invoices/${encodeURIComponent(String(invoice.id))}`')
@ -993,8 +1000,10 @@ $assert(str_contains($cloudTemplate, 'id="invoices-pagination"')
&& str_contains($cloudTemplate, 'id="invoices-page-label"')
&& str_contains($clientStyles, '.invoice-pagination'),
'The invoice list is missing its accessible previous/next pagination controls.');
$assert(str_contains($invoiceLoader, '/api/v1/invoices?page=${encodeURIComponent(requestedPage)}')
&& str_contains($invoiceLoader, 'if (state.loading) return;')
$assert(str_contains($invoiceLoader, 'invoiceQueryString(requestedPage, requestedFilters)')
&& str_contains($invoiceLoader, '`/api/v1/invoices${query ? `?${query}` : \'\'}`')
&& str_contains($invoiceLoader, 'state.readController?.abort();')
&& str_contains($invoiceLoader, 'if (sequence !== state.readSequence) return;')
&& str_contains($invoiceLoader,
'state.pagination = normalizePagination(payload?.pagination, requestedPage);')
&& !str_contains($invoiceLoader, 'payment_methods'),
@ -1009,18 +1018,21 @@ $assert(str_contains($invoicesModule, "byId('invoices-previous')")
'Invoice pages must hydrate the server-rendered first page and fetch only guarded later pages.');
$assert(str_contains($cloudTemplate, 'id="invoice-payment-methods"')
&& str_contains($cloudTemplate, 'id="invoice-payment-submit"')
&& str_contains($invoiceDetailRuntime, "id: 'balance'")
&& str_contains($invoiceDetailRuntime, "name: '账户余额'")
&& str_contains($invoicePresentationSource, "'id' => 'balance'")
&& str_contains($invoicePresentationSource, "'name' => '账户余额'")
&& str_contains($invoiceDetailRuntime, "card.setAttribute('aria-pressed'")
&& str_contains($clientStyles, '.invoice-payment-method-card[aria-pressed="true"]')
&& str_contains($invoiceDetailRuntime, 'renderInvoiceSpecification(invoice)')
&& str_contains($invoiceDetailRuntime, 'renderInvoiceFulfillment(invoice)'),
&& str_contains($invoiceDetailRuntime, 'renderInvoiceSpecification(presentation)')
&& str_contains($invoiceDetailRuntime,
'renderInvoiceFulfillment(state.selectedInvoice, presentation)'),
'Invoice detail must isolate plan data and expose one card-based payment selector.');
$assert(!str_contains($invoiceDetailRuntime, "uncertain: ['正在核对结果', 'warning']")
&& !str_contains($invoiceDetailRuntime, "'needs_attention', 'uncertain'].includes(status)")
&& str_contains($invoiceDetailRuntime, 'firstText(fulfillment.task_id, invoice?.task_id)')
&& str_contains($invoiceDetailRuntime, "['succeeded', 'failed', 'expired', 'refunded', 'cancelled'].includes(status)")
&& str_contains($invoiceDetailRuntime, 'invoiceJobProgress: new Map()')
&& str_contains($invoicePresentationSource,
"\$rawFulfillment['task_id'] ?? null")
&& str_contains($invoicePresentationSource,
"'completion_notice' => self::completionNotice(")
&& str_contains($invoiceDetailRuntime, 'presentation?.polling_required === true')
&& !str_contains($invoiceDetailRuntime, 'job_id'),
'Provisioning must expose task_id and converge to an explicit terminal receipt without a reconciliation-only state.');
$assert(!str_contains($sharedSidebar, 'data-view="orders"')
@ -1032,7 +1044,8 @@ $assert(str_contains($cloudTemplate, '>创建实例</button>')
&& str_contains($clientScript, "api('/api/v1/invoices', { method: 'POST', body })")
&& str_contains($clientScript, '/api/v1/invoices/by-request/')
&& str_contains($invoiceDetailRuntime, "invoice?.purpose")
&& str_contains($invoiceDetailRuntime, 'appendProvisionInvoiceActions(invoice, detail, actions)')
&& str_contains($invoiceDetailRuntime,
'appendProvisionInvoiceActions(invoice, presentation, detail, actions)')
&& str_contains($invoiceDetailRuntime, "makeElement('a', 'row-button', '查看实例')"),
'Instance deployment must create a recoverable invoice and expose fulfillment inside billing');
$assert(!str_contains($cloudShell, '/theme/venix/js/qrcode.min.js')
@ -1058,13 +1071,14 @@ $assert(!str_contains($invoiceDetailRuntime, '/api/v1/jobs/')
&& str_contains($invoiceDetailRuntime,
'/api/v1/invoices/${encodeURIComponent(invoice.id)}/status'),
'Invoice creation progress must not load the general job payload or a cloud session.');
$assert(str_contains($invoiceDetailRuntime, 'function invoiceDeletionTimestamp(invoice)')
&& str_contains($invoiceDetailRuntime, 'invoice?.deletion_at')
$assert(str_contains($invoicePresentationSource, "\$invoice['deletion_at']")
&& str_contains($invoicePresentationSource, "'label' => '最晚支付'")
&& str_contains($invoiceDetailRuntime, 'function invoiceCanPay(invoice)')
&& substr_count($invoiceDetailRuntime, 'if (!invoiceCanPay(invoice))') >= 2
&& str_contains($invoiceDetailRuntime, 'panel.hidden = true;')
&& str_contains($invoiceDetailRuntime,
'panel.hidden = presentation?.show_payment !== true;')
&& str_contains($invoiceDetailRuntime, 'container.replaceChildren();')
&& str_contains($invoiceDetailRuntime, '已超过支付截止时间'),
&& str_contains($invoicePresentationSource, '已超过支付截止时间'),
'Invoice UI must show the deletion deadline and hide every payment path after the cutoff');
$assert(str_contains($invoiceDetailRuntime, 'status >= 400 && status < 500')
&& str_contains($invoiceDetailRuntime, 'const ambiguousHttpFailure = [408, 425, 429].includes(status)')
@ -1154,10 +1168,15 @@ $assert(str_contains($adminBillingSource, '<header class="admin-instance-drawer-
&& 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')
&& str_contains($adminBillingRuntime, 'bg-warning-subtle text-warning-emphasis')
&& str_contains($adminBillingRuntime, 'bg-danger-subtle text-danger-emphasis')
&& str_contains($adminBillingRuntime, 'bg-info-subtle text-info-emphasis'),
&& str_contains($adminBillingRuntime, 'presentation?.class')
&& str_contains($billingPresentationCatalog,
"'success' => 'bg-success-subtle text-success-emphasis'")
&& str_contains($billingPresentationCatalog,
"'warning' => 'bg-warning-subtle text-warning-emphasis'")
&& str_contains($billingPresentationCatalog,
"'danger' => 'bg-danger-subtle text-danger-emphasis'")
&& str_contains($billingPresentationCatalog,
"'info' => 'bg-info-subtle text-info-emphasis'"),
'Administrator billing status badges must retain readable semantic colors');
foreach (glob($views . '/user/*.tpl') as $template) {
$source = file_get_contents($template);

Loading…
Cancel
Save