feat: improve admin billing views and detail drawer
parent
5905699742
commit
eca57ab75f
@ -1,190 +1,91 @@
|
||||
{assign var=admin_title value='账单系统'}
|
||||
{assign var=admin_active value='billing'}
|
||||
{include file='admin/static_header.tpl'}
|
||||
|
||||
{assign var=billing_view value=$billing_page.view|default:$billing_view|default:'invoices'}
|
||||
{assign var=billing_filters value=$billing_page.filters|default:[]}
|
||||
{assign var=billing_titles value=['invoices'=>'全部账单', 'orders'=>'开通任务', 'payments'=>'支付流水']}
|
||||
{assign var=billing_financial value=[''=>'全部财务状态','open'=>'待支付','overdue'=>'已逾期','paid'=>'已支付','refunded'=>'已退款','expired'=>'已失效','void'=>'已作废']}
|
||||
{assign var=billing_fulfillment value=[''=>'全部履约状态','awaiting_payment'=>'等待支付','queued'=>'已排队','pending'=>'待处理','running'=>'开通中','uncertain'=>'待人工核查','succeeded'=>'已开通','failed'=>'开通失败','expired'=>'已失效','refunded'=>'已退款','cancelled'=>'已取消']}
|
||||
{assign var=billing_payment value=[''=>'全部支付状态','creating'=>'创建中','pending'=>'待支付','paid_invoice'=>'已入账单','credited_balance'=>'已入余额','failed'=>'支付失败']}
|
||||
{assign var=billing_purpose value=[''=>'全部账单类型','provision'=>'实例开通','renewal'=>'实例续费','recharge'=>'余额充值']}
|
||||
{assign var=billing_providers value=[''=>'全部支付渠道','balance'=>'账户余额','usdt'=>'USDT-TRC20','yipay_alipay'=>'易支付 · 支付宝','yipay_wxpay'=>'易支付 · 微信','paytaro'=>'Paytaro']}
|
||||
{function name=billing_options options=[] selected=''}
|
||||
{foreach $options as $value=>$label}<option value="{$value|escape}" {if $selected == $value}selected{/if}>{$label|escape}</option>{/foreach}
|
||||
{/function}
|
||||
<main data-admin-billing>
|
||||
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column gap-3">
|
||||
<div class="flex-grow-1">
|
||||
<h1 class="fs-20 fw-semibold mb-1">账单系统</h1>
|
||||
<p class="text-muted mb-0">统一查看账单、实例开通任务与支付流水,财务和履约状态互不混用。</p>
|
||||
<p class="text-muted mb-0">集中核对账单、开通任务与支付记录,财务状态与履约状态分别展示。</p>
|
||||
</div>
|
||||
<div class="text-sm-end mt-2 mt-sm-0 admin-checkout-actions">
|
||||
<span class="admin-config-status is-loading" id="billing-notice" role="status" aria-live="polite">正在读取账单数据…</span>
|
||||
<button class="btn btn-light" id="billing-refresh" type="button">
|
||||
<i class="mdi mdi-refresh me-1" aria-hidden="true"></i>刷新
|
||||
</button>
|
||||
<div class="admin-checkout-actions">
|
||||
<span class="admin-config-status {if $billing_error|default:''}is-error{else}is-success{/if}" id="billing-notice" role="status" aria-live="polite">{if $billing_error|default:''}{$billing_error|escape}{else}已读取 {$billing_page.pagination.total|default:0|escape} 条{/if}</span>
|
||||
<button class="btn btn-light" id="billing-refresh" type="button"><i class="mdi mdi-refresh me-1" aria-hidden="true"></i>刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav class="admin-ticket-tabs mb-3" aria-label="账单视图">
|
||||
<a href="/admin/billing" data-billing-view="invoices" aria-current="page">全部账单</a>
|
||||
<a href="/admin/billing?view=orders" data-billing-view="orders">开通任务</a>
|
||||
<a href="/admin/billing?view=payments" data-billing-view="payments">支付流水</a>
|
||||
{foreach $billing_titles as $view=>$label}<a href="/admin/billing{if $view != 'invoices'}?view={$view|escape}{/if}" data-billing-view="{$view|escape}" {if $billing_view == $view}aria-current="page"{/if}>{$label|escape}</a>{/foreach}
|
||||
</nav>
|
||||
|
||||
<section class="row g-3 mb-3 admin-billing-summary" id="billing-summary" aria-label="当前视图摘要" aria-busy="true">
|
||||
<div class="col-md-6 col-xxl-3">
|
||||
<article class="card overflow-hidden admin-stat-card admin-billing-stat">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center justify-content-between gap-3">
|
||||
<div class="admin-billing-stat-copy">
|
||||
<h2 class="text-muted fs-14 fw-normal mb-1">记录总数</h2>
|
||||
<strong class="admin-stat-value admin-billing-stat-value d-block mb-0" id="billing-summary-total">—</strong>
|
||||
</div>
|
||||
<span class="admin-stat-icon text-primary"><i class="mdi mdi-file-document-multiple-outline" aria-hidden="true"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="col-md-6 col-xxl-3">
|
||||
<article class="card overflow-hidden admin-stat-card admin-billing-stat">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center justify-content-between gap-3">
|
||||
<div class="admin-billing-stat-copy">
|
||||
<h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-amount-label">总金额</h2>
|
||||
<strong class="admin-stat-value admin-billing-stat-value d-block mb-0" id="billing-summary-amount">—</strong>
|
||||
</div>
|
||||
<span class="admin-stat-icon text-success"><i class="mdi mdi-currency-usd" aria-hidden="true"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="col-md-6 col-xxl-3">
|
||||
<article class="card overflow-hidden admin-stat-card admin-billing-stat">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center justify-content-between gap-3">
|
||||
<div class="admin-billing-stat-copy">
|
||||
<h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-focus-label">待处理</h2>
|
||||
<strong class="admin-stat-value admin-billing-stat-value d-block mb-0" id="billing-summary-focus">—</strong>
|
||||
</div>
|
||||
<span class="admin-stat-icon text-warning"><i class="mdi mdi-alert-circle-outline" aria-hidden="true"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="col-md-6 col-xxl-3">
|
||||
<article class="card overflow-hidden admin-stat-card admin-billing-stat">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center justify-content-between gap-3">
|
||||
<div class="admin-billing-stat-copy">
|
||||
<h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-result-label">已完成</h2>
|
||||
<strong class="admin-stat-value admin-billing-stat-value d-block mb-0" id="billing-summary-result">—</strong>
|
||||
</div>
|
||||
<span class="admin-stat-icon text-success"><i class="mdi mdi-check-circle-outline" aria-hidden="true"></i></span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<section class="row g-3 mb-3 admin-billing-summary" id="billing-summary" aria-label="当前筛选摘要" aria-busy="false">
|
||||
{include file='admin/billing_summary.tpl'}
|
||||
</section>
|
||||
|
||||
<section class="card mb-3 admin-billing-filter" aria-labelledby="billing-filter-title">
|
||||
<div class="card-header">
|
||||
<h2 class="h5 card-title mb-1" id="billing-filter-title">筛选条件</h2>
|
||||
<span class="text-muted fs-13">缩小数据范围后再对账;清空条件可恢复默认列表。</span>
|
||||
<div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
|
||||
<div><h2 class="h5 card-title mb-1" id="billing-filter-title">筛选条件</h2><span class="text-muted fs-13">统计基于当前筛选,支付尝试金额不代表实际收入。</span></div>
|
||||
<div class="d-flex gap-2 flex-wrap" aria-label="常用筛选"><button class="btn btn-light btn-sm" type="button" data-billing-preset="uncertain">待核对</button><button class="btn btn-light btn-sm" type="button" data-billing-preset="failed">开通失败</button><button class="btn btn-light btn-sm" type="button" data-billing-preset="refunded">已退款</button></div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form id="billing-filter-form" class="row g-2 align-items-end">
|
||||
<label class="col-xl-4 col-lg-6" for="billing-query">
|
||||
<span class="form-label d-block">关键词</span>
|
||||
<input class="form-control" id="billing-query" name="q" type="search" maxlength="80"
|
||||
placeholder="账单 / 订单 / 套餐 / 用户 ID">
|
||||
<form id="billing-filter-form" class="row g-2 align-items-end" method="get" action="/admin/billing" novalidate>
|
||||
<input type="hidden" name="view" id="billing-view-input" value="{$billing_view|escape}">
|
||||
<label class="col-xl-4 col-lg-6" for="billing-query"><span class="form-label d-block">关键词</span><input class="form-control" id="billing-query" name="q" type="search" maxlength="80" value="{$billing_filters.q|default:''|escape}" placeholder="账单 / 订单 / 套餐 / 用户 ID"></label>
|
||||
<label class="col-xl-2 col-lg-3 col-6" for="billing-user-id"><span class="form-label d-block">用户 ID</span><input class="form-control" id="billing-user-id" name="user_id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20" value="{$billing_filters.user_id|default:''|escape}" placeholder="全部用户"></label>
|
||||
<label class="col-xl-3 col-lg-3 col-6" for="billing-status-primary" id="billing-status-primary-field"><span class="form-label d-block" id="billing-status-primary-label">{if $billing_view == 'invoices'}财务状态{elseif $billing_view == 'orders'}履约状态{else}支付状态{/if}</span>
|
||||
<select class="form-select" id="billing-status-primary" name="{if $billing_view == 'invoices'}financial_status{else}status{/if}">{if $billing_view == 'invoices'}{billing_options options=$billing_financial selected=$billing_filters.financial_status|default:''}{elseif $billing_view == 'orders'}{billing_options options=$billing_fulfillment selected=$billing_filters.status|default:''}{else}{billing_options options=$billing_payment selected=$billing_filters.status|default:''}{/if}</select>
|
||||
</label>
|
||||
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-user-id">
|
||||
<span class="form-label d-block">用户 ID</span>
|
||||
<input class="form-control" id="billing-user-id" name="user_id" type="text"
|
||||
inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20" placeholder="全部用户">
|
||||
<label class="col-xl-3 col-lg-4 col-6" for="billing-status-secondary" id="billing-status-secondary-field" {if $billing_view == 'payments'}hidden{/if}><span class="form-label d-block" id="billing-status-secondary-label">{if $billing_view == 'orders'}财务状态{else}履约状态{/if}</span>
|
||||
<select class="form-select" id="billing-status-secondary" name="{if $billing_view == 'orders'}financial_status{else}fulfillment_status{/if}" {if $billing_view == 'payments'}disabled{/if}>{if $billing_view == 'orders'}{billing_options options=$billing_financial selected=$billing_filters.financial_status|default:''}{else}{billing_options options=$billing_fulfillment selected=$billing_filters.fulfillment_status|default:''}{/if}</select>
|
||||
</label>
|
||||
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-status-primary" id="billing-status-primary-field">
|
||||
<span class="form-label d-block" id="billing-status-primary-label">财务状态</span>
|
||||
<select class="form-select" id="billing-status-primary"></select>
|
||||
</label>
|
||||
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-status-secondary" id="billing-status-secondary-field">
|
||||
<span class="form-label d-block" id="billing-status-secondary-label">履约状态</span>
|
||||
<select class="form-select" id="billing-status-secondary"></select>
|
||||
</label>
|
||||
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-category" id="billing-category-field">
|
||||
<span class="form-label d-block" id="billing-category-label">账单类型</span>
|
||||
<select class="form-select" id="billing-category"></select>
|
||||
</label>
|
||||
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-reference-select" id="billing-reference-field">
|
||||
<span class="form-label d-block" id="billing-reference-label">支付渠道</span>
|
||||
<select class="form-select" id="billing-reference-select"></select>
|
||||
<input class="form-control" id="billing-reference-input" type="text"
|
||||
inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20"
|
||||
placeholder="全部账单" hidden disabled>
|
||||
</label>
|
||||
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-created-from">
|
||||
<span class="form-label d-block">开始日期</span>
|
||||
<input class="form-control" id="billing-created-from" name="created_from" type="date">
|
||||
</label>
|
||||
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-created-to">
|
||||
<span class="form-label d-block">结束日期</span>
|
||||
<input class="form-control" id="billing-created-to" name="created_to" type="date">
|
||||
</label>
|
||||
<label class="col-xl-2 col-lg-3 col-md-6" for="billing-per-page">
|
||||
<span class="form-label d-block">每页条数</span>
|
||||
<select class="form-select" id="billing-per-page" name="per_page">
|
||||
<option value="30">30 条</option>
|
||||
<option value="50">50 条</option>
|
||||
<option value="100">100 条</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="col-xl-4 col-lg-6 col-12 admin-form-actions admin-billing-filter-actions mt-0">
|
||||
<button class="btn btn-primary" id="billing-apply" type="submit">应用筛选</button>
|
||||
<button class="btn btn-light" id="billing-reset" type="button">清空条件</button>
|
||||
</div>
|
||||
<details class="col-12 admin-billing-advanced" id="billing-advanced">
|
||||
<summary class="text-primary py-2">更多筛选:类型、渠道、日期和每页条数</summary>
|
||||
<div class="row g-2 align-items-end pt-2">
|
||||
<label class="col-lg-3 col-6" for="billing-category" id="billing-category-field" {if $billing_view == 'orders'}hidden{/if}><span class="form-label d-block" id="billing-category-label">{if $billing_view == 'payments'}支付渠道{else}账单类型{/if}</span><select class="form-select" id="billing-category" name="{if $billing_view == 'payments'}provider{else}purpose{/if}" {if $billing_view == 'orders'}disabled{/if}>{if $billing_view == 'payments'}{billing_options options=$billing_providers selected=$billing_filters.provider|default:''}{else}{billing_options options=$billing_purpose selected=$billing_filters.purpose|default:''}{/if}</select></label>
|
||||
<label class="col-lg-3 col-6" for="{if $billing_view == 'payments'}billing-reference-input{else}billing-reference-select{/if}" id="billing-reference-field" {if $billing_view == 'orders'}hidden{/if}><span class="form-label d-block" id="billing-reference-label">{if $billing_view == 'payments'}账单 ID{else}支付渠道{/if}</span><select class="form-select" id="billing-reference-select" name="payment_method" {if $billing_view != 'invoices'}hidden disabled{/if}>{billing_options options=$billing_providers selected=$billing_filters.payment_method|default:''}</select><input class="form-control" id="billing-reference-input" name="invoice_id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" maxlength="20" value="{$billing_filters.invoice_id|default:''|escape}" placeholder="全部账单" {if $billing_view != 'payments'}hidden disabled{/if}></label>
|
||||
<label class="col-lg-2 col-6" for="billing-created-from"><span class="form-label d-block">开始日期</span><input class="form-control" id="billing-created-from" type="date" value="{if $billing_filters.created_from|default:0}{$billing_filters.created_from|date_format:'%Y-%m-%d'|escape}{/if}"></label>
|
||||
<label class="col-lg-2 col-6" for="billing-created-to"><span class="form-label d-block">结束日期</span><input class="form-control" id="billing-created-to" type="date" value="{if $billing_filters.created_to|default:0}{$billing_filters.created_to|date_format:'%Y-%m-%d'|escape}{/if}"></label>
|
||||
<label class="col-lg-2 col-6" for="billing-per-page"><span class="form-label d-block">每页条数</span><select class="form-select" id="billing-per-page" name="per_page">{foreach [30,50,100] as $size}<option value="{$size}" {if $billing_page.pagination.per_page|default:30 == $size}selected{/if}>{$size} 条</option>{/foreach}</select></label>
|
||||
</div>
|
||||
</details>
|
||||
<div class="col-12 admin-form-actions admin-billing-filter-actions mt-2"><button class="btn btn-primary" id="billing-apply" type="submit">应用筛选</button><button class="btn btn-light" id="billing-reset" type="button">清空条件</button></div>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card" id="billing-panel" aria-labelledby="billing-view-heading">
|
||||
<div class="card-header d-flex align-items-center justify-content-between flex-wrap gap-2">
|
||||
<div>
|
||||
<h2 class="h5 card-title mb-1" id="billing-view-heading">全部账单</h2>
|
||||
<span class="text-muted fs-13" id="billing-view-description">按财务状态与履约状态核对每一笔账单。</span>
|
||||
</div>
|
||||
<span class="badge text-bg-light" id="billing-result-count" aria-live="polite">读取中</span>
|
||||
<div><h2 class="h5 card-title mb-1" id="billing-view-heading">{$billing_titles[$billing_view]|escape}</h2><span class="text-muted fs-13" id="billing-view-description">财务状态、履约状态与支付尝试分别核对。</span></div>
|
||||
<span class="badge text-bg-light" id="billing-result-count" aria-live="polite">{if $billing_page}本页 {$billing_page.items|count} 条 · 共 {$billing_page.pagination.total|escape} 条{else}数据未获取{/if}</span>
|
||||
<p class="text-muted fs-12 mb-0 w-100" id="billing-shown-filters">下列记录对应当前筛选条件。</p>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive admin-checkout-table-wrap">
|
||||
<table class="table table-hover align-middle mb-0 admin-checkout-table admin-billing-table" id="billing-table">
|
||||
<caption class="visually-hidden" id="billing-table-caption">管理员账单列表</caption>
|
||||
<thead id="billing-table-head"></thead>
|
||||
<tbody id="billing-table-body">
|
||||
<tr><td class="text-center text-muted py-4">正在加载…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<nav class="admin-user-pagination" id="billing-pagination" aria-label="账单列表分页" hidden>
|
||||
<button class="btn btn-light" id="billing-previous" type="button">
|
||||
<i class="mdi mdi-chevron-left me-1" aria-hidden="true"></i>上一页
|
||||
</button>
|
||||
<span id="billing-page-label">第 1 / 1 页</span>
|
||||
<button class="btn btn-light" id="billing-next" type="button">
|
||||
下一页<i class="mdi mdi-chevron-right ms-1" aria-hidden="true"></i>
|
||||
</button>
|
||||
<div class="table-responsive admin-checkout-table-wrap"><table class="table table-hover align-middle mb-0 admin-checkout-table admin-billing-table" id="billing-table"><caption class="visually-hidden" id="billing-table-caption">管理员账单列表</caption>
|
||||
{include file='admin/billing_rows.tpl'}
|
||||
</table></div>
|
||||
<nav class="admin-user-pagination" id="billing-pagination" aria-label="账单列表分页" {if !$billing_page || !$billing_page.pagination.total}hidden{/if}>
|
||||
<button class="btn btn-light" id="billing-previous" type="button" {if !$billing_page || !$billing_page.pagination.has_previous}disabled{/if}>上一页</button>
|
||||
<span id="billing-page-label">第 {$billing_page.pagination.page|default:1|escape} / {$billing_page.pagination.total_pages|default:1|escape} 页 · 共 {$billing_page.pagination.total|default:0|escape} 条</span>
|
||||
<button class="btn btn-light" id="billing-next" type="button" {if !$billing_page || !$billing_page.pagination.has_next}disabled{/if}>下一页</button>
|
||||
</nav>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<noscript><p class="alert alert-warning mt-3">此页需要 JavaScript 才能读取账单数据。</p></noscript>
|
||||
<noscript><p class="alert alert-info mt-3">已显示数据库账单快照。启用 JavaScript 后可查看详情、分页及日期筛选。</p></noscript>
|
||||
</main>
|
||||
|
||||
<dialog class="admin-billing-dialog" id="billing-detail-dialog" aria-labelledby="billing-detail-title">
|
||||
<div class="admin-modal-panel admin-billing-dialog-panel">
|
||||
<header class="d-flex align-items-start justify-content-between gap-3 pb-3">
|
||||
<div>
|
||||
<p class="admin-eyebrow mb-1">Invoice detail</p>
|
||||
<h2 class="h3 fw-bold text-dark mb-0" id="billing-detail-title">账单详情</h2>
|
||||
</div>
|
||||
<button class="admin-modal-close position-static flex-shrink-0" id="billing-detail-close" type="button" aria-label="关闭账单详情">
|
||||
<i class="mdi mdi-close" aria-hidden="true"></i>
|
||||
</button>
|
||||
</header>
|
||||
<p class="alert alert-info mb-3" id="billing-detail-state" role="status" aria-live="polite">正在读取账单详情…</p>
|
||||
<div class="admin-billing-dialog-body" id="billing-detail-body"></div>
|
||||
<dialog data-admin-instance-drawer data-admin-billing-drawer id="billing-detail-dialog" aria-labelledby="billing-detail-title">
|
||||
<header class="admin-instance-drawer-header"><div><p class="text-muted fs-13 mb-1">账单详情</p><h2 class="h4 fw-semibold mb-0" id="billing-detail-title">账单</h2></div><button class="admin-modal-close position-static flex-shrink-0" id="billing-detail-close" type="button" aria-label="关闭账单详情" autofocus><i class="mdi mdi-close" aria-hidden="true"></i></button></header>
|
||||
<div class="admin-instance-drawer-body"><p class="alert alert-info" id="billing-detail-state" role="status" aria-live="polite">正在读取账单详情…</p>
|
||||
<div class="admin-instance-tabs" role="tablist" aria-label="账单详情分类">{foreach ['overview'=>'账单概览','funds'=>'资金记录','fulfillment'=>'履约信息','payments'=>'支付记录'] as $tab=>$label}<button class="btn btn-light" type="button" id="billing-tab-{$tab}" data-billing-tab="{$tab}" role="tab" aria-controls="billing-panel-{$tab}" aria-selected="{if $tab == 'overview'}true{else}false{/if}" tabindex="{if $tab == 'overview'}0{else}-1{/if}">{$label}</button>{/foreach}</div>
|
||||
<div id="billing-detail-body">{foreach ['overview','funds','fulfillment','payments'] as $tab}<section id="billing-panel-{$tab}" role="tabpanel" aria-labelledby="billing-tab-{$tab}" tabindex="0" {if $tab != 'overview'}hidden{/if}></section>{/foreach}</div>
|
||||
</div>
|
||||
<footer class="admin-instance-drawer-footer"><span class="text-muted fs-12">只读核对,不会触发退款或重复执行开通。</span><div class="d-flex gap-2 flex-wrap" id="billing-detail-links"></div></footer>
|
||||
</dialog>
|
||||
|
||||
<script id="admin-billing-bootstrap" type="application/json">{$billing_bootstrap_json|default:'null' nofilter}</script>
|
||||
<script type="module" src="/cloud/admin-billing.js?v={$venix_asset_version}"></script>
|
||||
{include file='admin/static_footer.tpl'}
|
||||
|
||||
@ -0,0 +1,29 @@
|
||||
{assign var=billing_columns value=['账单','用户','项目','金额','财务状态','履约状态','支付渠道','时间','详情']}
|
||||
{if $billing_view == 'orders'}{assign var=billing_columns value=['任务','用户','套餐 / 宿主机','金额','财务状态','履约状态','实例 / 引擎任务','更新 / 异常','账单']}{/if}
|
||||
{if $billing_view == 'payments'}{assign var=billing_columns value=['支付流水','用户','支付渠道','金额','支付状态','账单财务状态','用途','时间','账单']}{/if}
|
||||
{function name=billing_badge value='' kind='financial' purpose=''}
|
||||
{assign var=labels value=$billing_financial}
|
||||
{if $kind == 'fulfillment'}{assign var=labels value=$billing_fulfillment}{elseif $kind == 'payment'}{assign var=labels value=$billing_payment}{/if}
|
||||
{assign var=tone value='light text-dark'}
|
||||
{if in_array($value,['paid','succeeded','paid_invoice','credited_balance'])}{assign var=tone value='success-subtle text-success-emphasis'}{elseif in_array($value,['failed','uncertain','overdue'])}{assign var=tone value='danger-subtle text-danger-emphasis'}{elseif in_array($value,['open','pending','queued','awaiting_payment'])}{assign var=tone value='warning-subtle text-warning-emphasis'}{elseif in_array($value,['refunded','running','creating'])}{assign var=tone value='info-subtle text-info-emphasis'}{/if}
|
||||
<span class="badge rounded-pill fs-12 px-2 py-1 bg-{$tone|escape}">{if $kind == 'fulfillment' && $purpose == 'renewal' && $value == 'succeeded'}已续费{elseif !$value}不适用{else}{$labels[$value]|default:$value|escape}{/if}</span>
|
||||
{/function}
|
||||
<thead id="billing-table-head"><tr>{foreach $billing_columns as $column}<th scope="col">{$column|escape}</th>{/foreach}</tr></thead>
|
||||
<tbody id="billing-table-body">
|
||||
{foreach $billing_page.items|default:[] as $item}
|
||||
{assign var=purpose_key value=$item.purpose|default:''}
|
||||
{assign var=provider_key value=$item.provider|default:''}
|
||||
{assign var=method_key value=$item.payment_method|default:''}
|
||||
<tr>
|
||||
<td data-label="{$billing_columns[0]|escape}"><span class="admin-checkout-user"><strong>#{$item.id|escape}</strong><span>{if $billing_view == 'invoices'}{$billing_purpose[$purpose_key]|default:$purpose_key|escape}{elseif $billing_view == 'orders'}{if $item.job_id}引擎 #{$item.job_id|escape} · {/if}尝试 {$item.attempts|escape}{else}账单 #{$item.invoice_id|escape}{/if}</span></span></td>
|
||||
<td data-label="用户"><span class="admin-checkout-user"><strong>{$item.user_name|default:$item.user_email|default:'用户'|escape}</strong><span>{if $item.user_name && $item.user_email}{$item.user_email|escape} · {/if}ID {$item.user_id|escape}</span></span></td>
|
||||
<td data-label="{$billing_columns[2]|escape}" class="admin-billing-secondary"><span class="admin-checkout-user"><strong>{if $billing_view == 'payments'}{$billing_providers[$provider_key]|default:$provider_key|escape}{else}{$item.subject_name|default:$item.plan_name|default:'套餐未记录'|escape}{/if}</strong>{if $billing_view == 'orders'}<span>宿主机 #{$item.host_id|escape}</span>{elseif $billing_view == 'invoices' && $item.plan_id}<span>套餐 #{$item.plan_id|escape}</span>{/if}</span></td>
|
||||
<td data-label="金额"><span class="admin-mono">${$item.amount|string_format:'%.2f'|escape}</span></td>
|
||||
<td data-label="{$billing_columns[4]|escape}">{if $billing_view == 'payments'}{billing_badge kind='payment' value=$item.payment_status}{else}{billing_badge value=$item.financial_status}{/if}</td>
|
||||
<td data-label="{$billing_columns[5]|escape}">{if $billing_view == 'payments'}{billing_badge value=$item.invoice_financial_status}{else}{billing_badge kind='fulfillment' value=$item.fulfillment_status purpose=$item.purpose|default:'provision'}{/if}</td>
|
||||
<td data-label="{$billing_columns[6]|escape}" class="admin-billing-secondary">{if $billing_view == 'invoices'}{if $method_key}{$billing_providers[$method_key]|default:$method_key|escape}{else}未记录{/if}{elseif $billing_view == 'orders'}<span class="admin-checkout-user"><strong>{if $item.instance_id}实例 #{$item.instance_id|escape}{else}实例 —{/if}</strong><span>{if $item.job_id}任务 #{$item.job_id|escape} · {$billing_fulfillment[$item.job_status]|default:$item.job_status|escape}{else}引擎任务 —{/if}</span></span>{else}{if $purpose_key}{$billing_purpose[$purpose_key]|default:$purpose_key|escape}{else}未分类{/if}{/if}</td>
|
||||
<td data-label="{$billing_columns[7]|escape}" class="admin-billing-secondary"><span class="admin-checkout-user"><strong>{if $billing_view == 'orders' && $item.updated_at}{$item.updated_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}{elseif $item.created_at}{$item.created_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}{else}—{/if}</strong>{if $billing_view == 'orders' && $item.error}<span>{$item.error|escape}</span>{elseif $billing_view == 'invoices' && $item.due_at}<span>到期 {$item.due_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}</span>{elseif $billing_view == 'payments' && $item.updated_at}<span>更新 {$item.updated_at|date_format:'%Y-%m-%d %H:%M:%S'|escape}</span>{/if}</span></td>
|
||||
<td data-label="{$billing_columns[8]|escape}">{assign var=detail_id value=$item.invoice_id|default:''}{if $billing_view == 'invoices'}{assign var=detail_id value=$item.id}{/if}{if $detail_id}<button class="btn btn-primary btn-sm" type="button" data-invoice-id="{$detail_id|escape}" aria-label="查看账单 {$detail_id|escape} 详情">账单详情</button>{else}—{/if}</td>
|
||||
</tr>
|
||||
{foreachelse}<tr><td colspan="9" class="text-center text-muted py-4">{if $billing_error|default:''}账单数据暂不可用,请点击刷新重试。{else}暂无匹配记录,请调整筛选条件。{/if}</td></tr>{/foreach}
|
||||
</tbody>
|
||||
@ -0,0 +1,10 @@
|
||||
{assign var=billing_summary value=$billing_page.summary|default:[]}
|
||||
{assign var=billing_counts value=$billing_summary.status_counts|default:[]}
|
||||
{assign var=billing_processing value=0}
|
||||
{if $billing_view == 'orders'}{foreach ['awaiting_payment','queued','pending','running','uncertain'] as $status}{assign var=billing_count value=$billing_counts[$status]|default:0}{assign var=billing_processing value=$billing_processing+$billing_count}{/foreach}{/if}
|
||||
{if $billing_view == 'payments'}{foreach ['creating','pending'] as $status}{assign var=billing_count value=$billing_counts[$status]|default:0}{assign var=billing_processing value=$billing_processing+$billing_count}{/foreach}{/if}
|
||||
<div class="col-6 col-xl"><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1">记录总数</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-total">{if $billing_page}{$billing_summary.total_records|escape}{else}—{/if}</strong></div></article></div>
|
||||
<div class="col-6 col-xl"><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-amount-label">{if $billing_view == 'invoices'}账单面额{elseif $billing_view == 'orders'}任务关联金额{else}支付尝试金额{/if}</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-amount">{if $billing_page}${$billing_summary.total_amount|string_format:'%.2f'|escape}{else}—{/if}</strong></div></article></div>
|
||||
<div class="col-6 col-xl"><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-focus-label">{if $billing_view == 'invoices'}待收款{elseif $billing_view == 'orders'}处理中 / 待核查{else}处理中{/if}</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-focus">{if !$billing_page}—{elseif $billing_view == 'invoices'}{$billing_summary.outstanding_count|escape} 笔 · ${$billing_summary.outstanding_amount|string_format:'%.2f'|escape}{else}{$billing_processing|escape} 笔{/if}</strong></div></article></div>
|
||||
<div class="col-6 col-xl"><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1" id="billing-summary-result-label">{if $billing_view == 'invoices'}已支付{elseif $billing_view == 'orders'}已开通 / 失败{else}入账去向{/if}</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-result">{if !$billing_page}—{elseif $billing_view == 'invoices'}{$billing_summary.paid_count|escape} 笔 · ${$billing_summary.paid_amount|string_format:'%.2f'|escape}{elseif $billing_view == 'orders'}{$billing_counts.succeeded|default:0|escape} / {$billing_counts.failed|default:0|escape}{else}账单 ${$billing_summary.paid_invoice_amount|string_format:'%.2f'|escape} · 余额 ${$billing_summary.credited_balance_amount|string_format:'%.2f'|escape}{/if}</strong></div></article></div>
|
||||
<div class="col-6 col-xl" id="billing-refund-card" {if $billing_view != 'invoices'}hidden{/if}><article class="card admin-stat-card admin-billing-stat"><div class="card-body"><h2 class="text-muted fs-14 fw-normal mb-1">已退款</h2><strong class="admin-stat-value admin-billing-stat-value" id="billing-summary-refunded">{if $billing_page && $billing_view == 'invoices'}{$billing_summary.refunded_count|escape} 笔 · ${$billing_summary.refunded_amount|string_format:'%.2f'|escape}{else}—{/if}</strong></div></article></div>
|
||||
@ -1,2 +1,2 @@
|
||||
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
|
||||
{assign var=venix_asset_version value='2026093005' scope='global'}
|
||||
{assign var=venix_asset_version value='2026093006' scope='global'}
|
||||
|
||||
@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool {
|
||||
if ((error_reporting() & $severity) && ($severity & (E_WARNING | E_USER_WARNING))) {
|
||||
throw new ErrorException($message, 0, $severity, $file, $line);
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
// Non-production records shared by the rendering test and the local browser preview.
|
||||
$now = time();
|
||||
$common = ['user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test',
|
||||
'plan_id' => '3', 'plan_name' => '标准云服务器', 'subject_name' => 'vm-production',
|
||||
'amount' => '10.00', 'payment_method' => 'balance', 'due_at' => $now + 86400,
|
||||
'paid_at' => $now - 3500, 'created_at' => $now - 3600, 'updated_at' => $now - 3400,
|
||||
'order_id' => '301', 'job_id' => '501', 'instance_id' => '101', 'renewal_id' => null];
|
||||
$invoices = [
|
||||
array_replace($common, ['id' => '201', 'purpose' => 'provision', 'financial_status' => 'paid', 'fulfillment_status' => 'succeeded']),
|
||||
array_replace($common, ['id' => '202', 'purpose' => 'provision', 'financial_status' => 'refunded', 'fulfillment_status' => 'failed', 'instance_id' => null]),
|
||||
array_replace($common, ['id' => '203', 'purpose' => 'recharge', 'financial_status' => 'paid', 'fulfillment_status' => null,
|
||||
'amount' => '100.00', 'plan_id' => null, 'plan_name' => '', 'subject_name' => '', 'order_id' => null,
|
||||
'instance_id' => null, 'job_id' => null, 'payment_method' => 'yipay_alipay']),
|
||||
array_replace($common, ['id' => '204', 'purpose' => 'renewal', 'financial_status' => 'paid', 'fulfillment_status' => 'succeeded', 'renewal_id' => '1', 'order_id' => null, 'job_id' => null]),
|
||||
array_replace($common, ['id' => '205', 'purpose' => 'provision', 'financial_status' => 'expired', 'fulfillment_status' => 'expired',
|
||||
'amount' => '100.00', 'paid_at' => null, 'payment_method' => null, 'order_id' => '305', 'job_id' => null, 'instance_id' => null]),
|
||||
];
|
||||
$orders = [[
|
||||
'id' => '301', 'user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test',
|
||||
'plan_id' => '3', 'plan_name' => '标准云服务器', 'host_id' => '7', 'amount' => '10.00',
|
||||
'financial_status' => 'paid', 'fulfillment_status' => 'uncertain', 'invoice_id' => '201',
|
||||
'job_id' => '501', 'job_status' => 'uncertain', 'instance_id' => '101', 'attempts' => 3,
|
||||
'error' => '等待引擎核对操作结果', 'refunded_at' => null, 'created_at' => $now - 3600, 'updated_at' => $now - 60,
|
||||
]];
|
||||
$paymentBase = ['user_id' => '42', 'user_name' => '演示客户', 'user_email' => 'demo@example.test',
|
||||
'provider' => 'yipay_alipay', 'purpose' => 'provision', 'created_at' => $now - 3500, 'updated_at' => $now - 3400];
|
||||
$payments = [
|
||||
array_replace($paymentBase, ['id' => '701', 'invoice_id' => '201', 'amount' => '10.00', 'payment_status' => 'paid_invoice', 'invoice_financial_status' => 'paid']),
|
||||
array_replace($paymentBase, ['id' => '702', 'invoice_id' => '205', 'amount' => '100.00', 'payment_status' => 'credited_balance', 'invoice_financial_status' => 'expired']),
|
||||
];
|
||||
$filters = ['page' => 1, 'per_page' => 30, 'q' => '', 'user_id' => null,
|
||||
'created_from' => null, 'created_to' => null];
|
||||
$viewFilters = [
|
||||
'invoices' => ['financial_status' => '', 'fulfillment_status' => '', 'payment_method' => '', 'purpose' => ''],
|
||||
'orders' => ['status' => '', 'financial_status' => ''],
|
||||
'payments' => ['status' => '', 'provider' => '', 'invoice_id' => null],
|
||||
];
|
||||
$pages = [];
|
||||
foreach (['invoices' => $invoices, 'orders' => $orders, 'payments' => $payments] as $view => $items) {
|
||||
$pages[$view] = ['view' => $view, 'items' => $items, 'filters' => $filters + $viewFilters[$view],
|
||||
'pagination' => ['page' => 1, 'per_page' => 30, 'total' => count($items), 'total_pages' => 1,
|
||||
'has_previous' => false, 'has_next' => false], 'generated_at' => $now];
|
||||
}
|
||||
$pages['invoices']['summary'] = ['total_records' => 5, 'total_amount' => '230.00',
|
||||
'outstanding_count' => 0, 'outstanding_amount' => '0.00', 'paid_count' => 3, 'paid_amount' => '120.00',
|
||||
'refunded_count' => 1, 'refunded_amount' => '10.00'];
|
||||
$pages['orders']['summary'] = ['total_records' => 1, 'total_amount' => '10.00', 'status_counts' => ['uncertain' => 1]];
|
||||
$pages['payments']['summary'] = ['total_records' => 2, 'total_amount' => '110.00',
|
||||
'paid_invoice_amount' => '10.00', 'credited_balance_amount' => '100.00',
|
||||
'status_counts' => ['paid_invoice' => 1, 'credited_balance' => 1]];
|
||||
|
||||
$details = [];
|
||||
foreach ($invoices as $row) {
|
||||
$recharge = $row['purpose'] === 'recharge';
|
||||
$refunded = $row['financial_status'] === 'refunded';
|
||||
$expired = $row['financial_status'] === 'expired';
|
||||
$detailInvoice = $row + ['validity_days' => $recharge ? 0 : 30,
|
||||
'traffic_quota_bytes' => $recharge ? 0 : 107374182400,
|
||||
'renews_expires_at' => $row['purpose'] === 'renewal' ? $now + 30 * 86400 : null,
|
||||
'payment_deadline_at' => $now + 86400,
|
||||
'specification' => $recharge ? [] : ['cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100]];
|
||||
$details[$row['id']] = ['invoice' => $detailInvoice,
|
||||
'order' => $row['order_id'] ? array_replace($orders[0], ['id' => $row['order_id'], 'invoice_id' => $row['id'],
|
||||
'fulfillment_status' => $row['fulfillment_status'], 'refunded_at' => $refunded ? $now - 3300 : null]) : null,
|
||||
'job' => $row['job_id'] ? ['id' => '501', 'kind' => 'create', 'status' => $row['fulfillment_status'],
|
||||
'attempts' => 1, 'phase' => 'complete', 'error' => $refunded ? '实例创建失败,已确认清理' : null,
|
||||
'created_at' => $now - 3500, 'updated_at' => $now - 3400] : null,
|
||||
'instance' => $row['instance_id'] ? ['id' => '101', 'name' => 'vm-production', 'status' => 'active',
|
||||
'service_status' => 'active', 'network_status' => 'active', 'expires_at' => $now + 30 * 86400] : null,
|
||||
'payment_attempts' => $expired ? [$payments[1]] : [], 'payment_attempts_truncated' => false,
|
||||
'funds' => ['title' => $refunded ? '已退回账户余额' : ($expired ? '款项保留在账户余额' : '账单已结清'),
|
||||
'description' => $refunded ? '开通失败退款记入账户余额,不是原支付渠道原路退款。'
|
||||
: ($expired ? '支付记录标记为已入余额,该次款项未结清目标账单。' : '款项已用于结清账单。'),
|
||||
'settled_amount' => $expired ? null : $row['amount'], 'refund_amount' => $refunded ? $row['amount'] : null,
|
||||
'refund_destination' => $refunded ? 'balance' : null, 'refunded_at' => $refunded ? $now - 3300 : null,
|
||||
'balance_retained_amount' => $expired ? '100.00' : '0.00', 'balance_retained_count' => $expired ? 1 : 0,
|
||||
'payment_records_truncated' => false, 'notes' => ['仅根据现有业务记录展示,不是完整钱包变动账本。']],
|
||||
'timeline' => [['kind' => 'created', 'title' => '账单创建', 'description' => '已记录账单创建时间', 'at' => $row['created_at']]],
|
||||
'links' => ['user' => '/admin/user/42/edit',
|
||||
'instance' => $row['instance_id'] ? '/admin/cloud/instances?q=11111111-1111-4111-8111-111111111111' : null,
|
||||
'payments' => '/admin/billing?view=payments&invoice_id=' . $row['id']],
|
||||
];
|
||||
if ($row['paid_at']) $details[$row['id']]['timeline'][] = ['kind' => 'paid', 'title' => '账单结清', 'description' => '账户余额支付', 'at' => $row['paid_at']];
|
||||
if ($refunded) $details[$row['id']]['timeline'][] = ['kind' => 'refunded', 'title' => '退款退回余额', 'description' => '开通失败后退回账户余额', 'at' => $now - 3300];
|
||||
}
|
||||
|
||||
$smarty = new Smarty();
|
||||
$compileDir = sys_get_temp_dir() . '/admin-billing-view-' . bin2hex(random_bytes(6));
|
||||
mkdir($compileDir);
|
||||
$smarty->setCompileDir($compileDir);
|
||||
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
|
||||
$smarty->assign('config', ['appName' => 'Venix Test']);
|
||||
$smarty->assign('cdn', '');
|
||||
$smarty->assign('user', (object) ['isLogin' => false]);
|
||||
$smarty->assign('admin_can_manage', true);
|
||||
$smarty->assign('admin_csrf_token', 'fixture-not-a-real-token');
|
||||
$render = static function (?array $payload, string $error = '', string $view = 'invoices') use ($smarty): string {
|
||||
$smarty->assign('billing_page', $payload);
|
||||
$smarty->assign('billing_view', $payload['view'] ?? $view);
|
||||
$smarty->assign('billing_error', $error);
|
||||
$smarty->assign('billing_bootstrap_json', json_encode($payload,
|
||||
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
|
||||
| JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
|
||||
return $smarty->fetch('admin/billing.tpl');
|
||||
};
|
||||
$assert = static function (bool $ok, string $message): void {
|
||||
if (!$ok) throw new RuntimeException($message);
|
||||
};
|
||||
// Test-only input used by the local preview to exercise refresh/deep-link SSR.
|
||||
foreach ($argv ?? [] as $arg) {
|
||||
if (str_starts_with($arg, '--render-page=')) {
|
||||
$payload = json_decode(base64_decode(substr($arg, 14), true), true, 512, JSON_THROW_ON_ERROR);
|
||||
echo $render($payload);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
$html = [];
|
||||
foreach ($pages as $view => $page) $html[$view] = $render($page);
|
||||
$failedHtml = $render(null, '账单数据暂不可用,请稍后重试');
|
||||
if (in_array('--fixture', $argv ?? [], true)) {
|
||||
echo json_encode(['html' => $html, 'failed_html' => $failedHtml, 'pages' => $pages, 'details' => $details],
|
||||
JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
|
||||
exit;
|
||||
}
|
||||
|
||||
$dom = new DOMDocument();
|
||||
libxml_use_internal_errors(true);
|
||||
foreach ($pages as $view => $page) {
|
||||
$dom->loadHTML('<?xml encoding="UTF-8">' . $html[$view]);
|
||||
$xpath = new DOMXPath($dom);
|
||||
$assert($xpath->query('//tbody[@id="billing-table-body"]/tr')->length === count($page['items']),
|
||||
'Server-rendered rows missing for billing view: ' . $view);
|
||||
$assert(str_contains($dom->textContent, '演示客户'), 'The first paint must contain meaningful account data.');
|
||||
$assert($xpath->query('//dialog[@id="billing-detail-dialog" and @data-admin-instance-drawer]')->length === 1,
|
||||
'Billing details must reuse the existing administrator instance drawer.');
|
||||
}
|
||||
$assert(str_contains($html['invoices'], '已续费'), 'Renewal completion must not be labelled instance provisioning.');
|
||||
$dom->loadHTML('<?xml encoding="UTF-8">' . $html['invoices']);
|
||||
$xpath = new DOMXPath($dom);
|
||||
$assert(trim($xpath->query('//*[@id="billing-summary-result"]')->item(0)->textContent) === '3 笔 · $120.00'
|
||||
&& trim($xpath->query('//*[@id="billing-summary-refunded"]')->item(0)->textContent) === '1 笔 · $10.00',
|
||||
'SSR must show paid and refunded totals separately, without subtracting refunds a second time.');
|
||||
$unsafe = $pages['invoices'];
|
||||
$unsafe['items'][0]['subject_name'] = '</script><img src=x onerror=alert(1)>';
|
||||
$unsafe['items'][0]['user_name'] = '<script>window.bad=1</script>';
|
||||
$unsafe['filters']['q'] = '" autofocus onfocus="alert(2)';
|
||||
$unsafeHtml = $render($unsafe);
|
||||
$dom->loadHTML('<?xml encoding="UTF-8">' . $unsafeHtml);
|
||||
$xpath = new DOMXPath($dom);
|
||||
$assert($xpath->query('//*[@onerror or @onfocus]')->length === 0
|
||||
&& !str_contains($unsafeHtml, '<script>window.bad=1</script>'), 'Untrusted billing fields escaped into executable markup.');
|
||||
$assert(str_contains($dom->textContent, '</script><img src=x onerror=alert(1)>'), 'Escaped names must remain visible text.');
|
||||
$bootstrap = json_decode($xpath->query('//*[@id="admin-billing-bootstrap"]')->item(0)->textContent, true, 512, JSON_THROW_ON_ERROR);
|
||||
$assert($bootstrap['items'][0]['subject_name'] === $unsafe['items'][0]['subject_name']
|
||||
&& $bootstrap['filters']['q'] === $unsafe['filters']['q'], 'Safe bootstrap encoding changed the original data.');
|
||||
foreach (['invoices' => ['financial_status', 'paid'], 'orders' => ['status', 'uncertain'],
|
||||
'payments' => ['status', 'credited_balance']] as $view => [$key, $value]) {
|
||||
$filtered = $pages[$view];
|
||||
$filtered['filters'][$key] = $value;
|
||||
$filtered['filters']['user_id'] = '42';
|
||||
$filtered['pagination'] = ['page' => 2, 'per_page' => 50, 'total' => 80, 'total_pages' => 2,
|
||||
'has_previous' => true, 'has_next' => false];
|
||||
$dom->loadHTML('<?xml encoding="UTF-8">' . $render($filtered));
|
||||
$xpath = new DOMXPath($dom);
|
||||
$assert($xpath->query('//*[@id="billing-status-primary"]/option[@selected and @value="' . $value . '"]')->length === 1
|
||||
&& $xpath->query('//*[@id="billing-per-page"]/option[@selected and @value="50"]')->length === 1
|
||||
&& $xpath->query('//*[@id="billing-user-id" and @value="42"]')->length === 1
|
||||
&& str_contains($xpath->query('//*[@id="billing-page-label"]')->item(0)->textContent, '第 2 / 2 页'),
|
||||
'SSR discarded the active filter or page: ' . $view);
|
||||
}
|
||||
$empty = $pages['invoices'];
|
||||
$empty['items'] = [];
|
||||
$empty['pagination']['total'] = 0;
|
||||
$empty['summary'] = array_fill_keys(array_keys($empty['summary']), 0);
|
||||
$emptyHtml = $render($empty);
|
||||
$assert(!str_contains($emptyHtml, 'vm-production'), 'Empty billing response retained an old record.');
|
||||
$assert(str_contains($failedHtml, '账单数据暂不可用,请稍后重试')
|
||||
&& !str_contains($failedHtml, 'vm-production'), 'Failed read was rendered as a successful old list.');
|
||||
foreach (array_keys($pages) as $view) {
|
||||
$failure = $render(null, '账单数据暂不可用,请稍后重试', $view);
|
||||
$dom->loadHTML('<?xml encoding="UTF-8">' . $failure);
|
||||
$xpath = new DOMXPath($dom);
|
||||
$assert($xpath->query('//*[@data-billing-view="' . $view . '" and @aria-current="page"]')->length === 1,
|
||||
'A failed snapshot must keep the requested view selected: ' . $view);
|
||||
$assert(trim($xpath->query('//*[@id="billing-summary-total"]')->item(0)->textContent) === '—',
|
||||
'A failed snapshot must not appear as zero financial records.');
|
||||
$assert(json_decode($xpath->query('//*[@id="admin-billing-bootstrap"]')->item(0)->textContent, true, 512, JSON_THROW_ON_ERROR) === null,
|
||||
'A failed snapshot must not bootstrap a successful list.');
|
||||
}
|
||||
echo "Administrator billing three-view SSR, shared drawer, escaping and empty/error rendering passed.\n";
|
||||
@ -0,0 +1,614 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services {
|
||||
final class AdminPermission
|
||||
{
|
||||
public static bool $superAdmin = true;
|
||||
|
||||
public static function isSuperAdmin(): bool
|
||||
{
|
||||
return self::$superAdmin;
|
||||
}
|
||||
}
|
||||
|
||||
final class Auth
|
||||
{
|
||||
public static $user = null;
|
||||
|
||||
public static function getUser()
|
||||
{
|
||||
return self::$user;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace App\Services\Cloud {
|
||||
final class CloudSessionService
|
||||
{
|
||||
public static int $calls = 0;
|
||||
|
||||
public static function current($user): string
|
||||
{
|
||||
self::$calls++;
|
||||
throw new \RuntimeException('Read-only billing requested an engine session.');
|
||||
}
|
||||
}
|
||||
|
||||
final class CloudEngineClient
|
||||
{
|
||||
public static int $calls = 0;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
self::$calls++;
|
||||
throw new \RuntimeException('Read-only billing contacted the private engine.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\AdminPermission;
|
||||
use App\Services\Auth;
|
||||
use App\Services\Cloud\CloudAdminBillingService;
|
||||
use App\Services\Cloud\CloudEngineClient;
|
||||
use App\Services\Cloud\CloudError;
|
||||
use App\Services\Cloud\CloudSessionService;
|
||||
use Illuminate\Database\Capsule\Manager as Capsule;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Slim\Http\Environment;
|
||||
use Slim\Http\Request;
|
||||
use Slim\Http\Response;
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$expectError = static function (callable $callback, int $status, string $message) use ($assert): void {
|
||||
try {
|
||||
$callback();
|
||||
} catch (CloudError $error) {
|
||||
$assert($error->httpStatus === $status,
|
||||
$message . ': unexpected HTTP status ' . $error->httpStatus);
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException($message . ': request was accepted.');
|
||||
};
|
||||
$ids = static fn (array $rows): array => array_map('intval', array_column($rows, 'id'));
|
||||
$capsule = new Capsule();
|
||||
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
||||
$capsule->setAsGlobal();
|
||||
$capsule->bootEloquent();
|
||||
$schema = $capsule->schema('default');
|
||||
$schema->create('user', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('user_name');
|
||||
$table->string('email');
|
||||
$table->boolean('is_admin')->default(false);
|
||||
$table->boolean('enable')->default(true);
|
||||
$table->string('money')->default('999.99');
|
||||
$table->string('pass')->default('must-not-expose-account-password');
|
||||
});
|
||||
$schema->create('shop', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('name');
|
||||
});
|
||||
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('uuid');
|
||||
$table->integer('user_id');
|
||||
$table->integer('plan_id')->nullable();
|
||||
$table->string('name');
|
||||
$table->string('status')->default('active');
|
||||
$table->string('service_status')->default('active');
|
||||
$table->string('network_status')->default('active');
|
||||
$table->integer('expires_at')->nullable();
|
||||
$table->text('spec_json')->default('{}');
|
||||
$table->text('credential_cipher')->default('must-not-expose-instance-credential');
|
||||
});
|
||||
$schema->create('cloud_orders', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('user_id');
|
||||
$table->integer('plan_id')->nullable();
|
||||
$table->integer('host_id')->default(7);
|
||||
$table->string('amount')->default('1.25');
|
||||
$table->string('status')->default('queued');
|
||||
$table->text('spec_json')->default('{}');
|
||||
$table->text('payload_cipher')->default('must-not-expose-order-payload');
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('refunded_at')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_jobs', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('operation_id')->default('must-not-expose-operation-id');
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('user_id');
|
||||
$table->integer('host_id')->default(7);
|
||||
$table->string('kind')->default('create');
|
||||
$table->string('status')->default('running');
|
||||
$table->integer('attempts')->default(1);
|
||||
$table->string('error_code')->nullable();
|
||||
$table->text('result_json')->nullable();
|
||||
$table->text('payload_cipher')->default('must-not-expose-job-payload');
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_invoices', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->string('invoice_no')->default('must-not-expose-invoice-number');
|
||||
$table->string('purpose')->default('provision');
|
||||
$table->integer('instance_id')->nullable();
|
||||
$table->integer('order_id')->nullable();
|
||||
$table->integer('user_id');
|
||||
$table->integer('plan_id')->nullable();
|
||||
$table->integer('renewal_id')->nullable();
|
||||
$table->integer('renews_expires_at')->nullable();
|
||||
$table->integer('due_at');
|
||||
$table->string('amount')->default('1.25');
|
||||
$table->integer('validity_days')->default(30);
|
||||
$table->integer('traffic_quota_bytes')->default(107374182400);
|
||||
$table->string('status')->default('paid');
|
||||
$table->string('paid_via')->nullable();
|
||||
$table->string('payment_reference')->default('must-not-expose-payment-reference');
|
||||
$table->integer('paid_at')->nullable();
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
$schema->create('cloud_invoice_payments', static function (Blueprint $table): void {
|
||||
$table->increments('id');
|
||||
$table->integer('invoice_id');
|
||||
$table->integer('user_id');
|
||||
$table->string('provider')->default('yipay_alipay');
|
||||
$table->string('provider_order_no')->default('must-not-expose-provider-reference');
|
||||
$table->string('idempotency_key')->default('must-not-expose-idempotency-key');
|
||||
$table->string('amount')->default('1.25');
|
||||
$table->string('status')->default('pending');
|
||||
$table->integer('created_at');
|
||||
$table->integer('updated_at');
|
||||
});
|
||||
|
||||
$now = time();
|
||||
Capsule::table('user')->insert([
|
||||
['id' => 1, 'user_name' => 'Alice Finance', 'email' => 'alice@example.test'],
|
||||
['id' => 2, 'user_name' => 'Bob Client', 'email' => 'bob@example.test'],
|
||||
['id' => 3, 'user_name' => 'Foreign Owner', 'email' => 'foreign@example.test'],
|
||||
['id' => 10, 'user_name' => 'Bulk Customer', 'email' => 'bulk@example.test'],
|
||||
]);
|
||||
Capsule::table('shop')->insert(['id' => 7, 'name' => 'Standard Cloud']);
|
||||
$spec = json_encode([
|
||||
'name' => 'production-vm', 'plan_name' => 'Historical Plan',
|
||||
'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100,
|
||||
'password' => 'must-not-expose-spec-password',
|
||||
'unreviewed_note' => 'must-not-expose-unknown-spec-field',
|
||||
]);
|
||||
$insertInstance = static function (int $id, array $overrides = []) use ($now, $spec): void {
|
||||
Capsule::table('cloud_instances')->insert(array_replace([
|
||||
'id' => $id, 'user_id' => 1, 'plan_id' => 7, 'name' => 'vm-' . $id,
|
||||
'uuid' => sprintf('11111111-1111-4111-8111-%012d', $id),
|
||||
'expires_at' => $now + 30 * 86400, 'spec_json' => $spec,
|
||||
], $overrides));
|
||||
};
|
||||
$insertOrder = static function (int $id, array $overrides = []) use ($now, $spec): void {
|
||||
Capsule::table('cloud_orders')->insert(array_replace([
|
||||
'id' => $id, 'user_id' => 1, 'plan_id' => 7, 'spec_json' => $spec,
|
||||
'created_at' => $now - 1000, 'updated_at' => $now - 100,
|
||||
], $overrides));
|
||||
};
|
||||
$insertJob = static function (int $id, array $overrides = []) use ($now): void {
|
||||
Capsule::table('cloud_jobs')->insert(array_replace([
|
||||
'id' => $id, 'user_id' => 1,
|
||||
'created_at' => $now - 900, 'updated_at' => $now - 100,
|
||||
'result_json' => json_encode([
|
||||
'phase' => 'complete', 'password' => 'must-not-expose-job-password',
|
||||
'unreviewed_note' => 'must-not-expose-unknown-job-field',
|
||||
]),
|
||||
], $overrides));
|
||||
};
|
||||
$insertInvoice = static function (int $id, array $overrides = []) use ($now): void {
|
||||
Capsule::table('cloud_invoices')->insert(array_replace([
|
||||
'id' => $id, 'user_id' => 1, 'plan_id' => 7,
|
||||
'due_at' => $now + 3600, 'created_at' => $now - 1000, 'updated_at' => $now - 100,
|
||||
], $overrides));
|
||||
};
|
||||
$insertPayment = static function (int $id, array $overrides = []) use ($now): void {
|
||||
Capsule::table('cloud_invoice_payments')->insert(array_replace([
|
||||
'id' => $id, 'invoice_id' => $id, 'user_id' => 1,
|
||||
'created_at' => $now - 800, 'updated_at' => $now - 100,
|
||||
], $overrides));
|
||||
};
|
||||
$insertInstance(501);
|
||||
$insertInstance(502, ['status' => 'deleted']);
|
||||
$insertOrder(101, ['instance_id' => 501, 'status' => 'succeeded', 'amount' => '100.00']);
|
||||
$insertOrder(102, ['status' => 'failed', 'amount' => '30.00', 'refunded_at' => $now - 200]);
|
||||
$insertOrder(103, ['status' => 'awaiting_payment', 'amount' => '40.00']);
|
||||
$insertOrder(109, ['user_id' => 3, 'status' => 'refunded', 'refunded_at' => $now - 200]);
|
||||
$insertOrder(110, ['user_id' => 3, 'status' => 'refunded', 'refunded_at' => $now - 200]);
|
||||
$insertJob(201, ['order_id' => 101, 'instance_id' => 501, 'status' => 'succeeded']);
|
||||
$insertJob(202, ['order_id' => 102, 'status' => 'failed', 'error_code' => 'provision_failed']);
|
||||
|
||||
// Financial state is independent from fulfilment and payment-attempt state.
|
||||
$insertInvoice(1, ['order_id' => 101, 'instance_id' => 501,
|
||||
'amount' => '100.00', 'status' => 'paid', 'paid_via' => 'balance', 'paid_at' => $now - 700]);
|
||||
$insertInvoice(2, ['order_id' => 102, 'amount' => '30.00', 'status' => 'refunded',
|
||||
'paid_via' => 'yipay_alipay', 'paid_at' => $now - 700]);
|
||||
$insertInvoice(3, ['order_id' => 103, 'amount' => '40.00', 'status' => 'open']);
|
||||
$insertInvoice(4, ['purpose' => 'renewal', 'instance_id' => 501,
|
||||
'amount' => '50.00', 'status' => 'open', 'due_at' => $now - 60]);
|
||||
$insertInvoice(5, ['purpose' => 'recharge', 'plan_id' => null, 'amount' => '60.00',
|
||||
'status' => 'paid', 'paid_via' => 'yipay_wxpay', 'paid_at' => $now - 700]);
|
||||
$insertInvoice(6, ['purpose' => 'renewal', 'instance_id' => 501, 'renewal_id' => 301,
|
||||
'amount' => '20.00', 'status' => 'paid', 'paid_via' => 'balance', 'paid_at' => $now - 700]);
|
||||
$insertInvoice(7, ['purpose' => 'recharge', 'plan_id' => null,
|
||||
'amount' => '10.00', 'status' => 'expired', 'due_at' => $now - 4 * 86400]);
|
||||
$insertInvoice(8, ['purpose' => 'renewal', 'instance_id' => 502,
|
||||
'amount' => '80.00', 'status' => 'open', 'due_at' => $now - 60]);
|
||||
$insertInvoice(9, ['user_id' => 2, 'order_id' => 109, 'instance_id' => 501]);
|
||||
$insertInvoice(10, ['user_id' => 2, 'order_id' => 110, 'status' => 'refunded']);
|
||||
$insertInvoice(11, ['user_id' => 404, 'purpose' => 'recharge', 'plan_id' => null, 'status' => 'open']);
|
||||
foreach ([
|
||||
1 => ['amount' => '100.00', 'status' => 'paid_invoice'],
|
||||
2 => ['amount' => '30.00', 'status' => 'paid_invoice'],
|
||||
3 => ['amount' => '40.00', 'status' => 'pending'],
|
||||
4 => ['amount' => '50.00', 'status' => 'failed'],
|
||||
5 => ['amount' => '60.00', 'status' => 'credited_balance', 'provider' => 'yipay_wxpay'],
|
||||
6 => ['amount' => '20.00', 'status' => 'paid_invoice'],
|
||||
7 => ['amount' => '10.00', 'status' => 'credited_balance'],
|
||||
8 => ['invoice_id' => 3, 'amount' => '40.00', 'status' => 'creating'],
|
||||
] as $id => $values) {
|
||||
$insertPayment($id, $values);
|
||||
}
|
||||
$insertPayment(9, ['invoice_id' => 9, 'user_id' => 3, 'status' => 'credited_balance', 'amount' => '999.00']);
|
||||
$insertInvoice(12, ['user_id' => 2, 'purpose' => 'recharge', 'plan_id' => null, 'status' => 'expired']);
|
||||
for ($id = 6000; $id < 6105; $id++) {
|
||||
$insertPayment($id, ['invoice_id' => 12, 'user_id' => 2,
|
||||
'status' => 'credited_balance', 'amount' => '1.10']);
|
||||
}
|
||||
$insertPayment(6200, ['invoice_id' => 12, 'user_id' => 3,
|
||||
'status' => 'credited_balance', 'amount' => '999.00']);
|
||||
$insertInvoice(13, ['user_id' => 2, 'purpose' => 'recharge', 'plan_id' => null,
|
||||
'status' => 'paid', 'amount' => '12.00', 'paid_at' => null]);
|
||||
$insertOrder(114, ['user_id' => 2, 'status' => 'refunded',
|
||||
'amount' => '9.00', 'refunded_at' => $now - 200]);
|
||||
$insertInvoice(14, ['user_id' => 2, 'order_id' => 114,
|
||||
'status' => 'refunded', 'amount' => '10.00', 'paid_at' => $now - 700]);
|
||||
$insertInvoice(15, ['user_id' => 2, 'purpose' => 'renewal', 'instance_id' => 999999,
|
||||
'status' => 'open', 'paid_at' => null]);
|
||||
$insertInvoice(16, ['user_id' => 2, 'purpose' => 'renewal', 'instance_id' => 999999,
|
||||
'status' => 'overdue', 'paid_at' => null]);
|
||||
|
||||
// More than one page for every view, with identical timestamps to require
|
||||
// an ID tie-breaker and a complete summary independent of the visible page.
|
||||
for ($offset = 0; $offset < 135; $offset++) {
|
||||
$created = $offset === 0 ? $now - 2 * 86400 : $now - 100;
|
||||
$insertInstance(3000 + $offset, ['user_id' => 10]);
|
||||
$insertOrder(2000 + $offset, ['user_id' => 10, 'instance_id' => 3000 + $offset,
|
||||
'status' => 'queued', 'created_at' => $created]);
|
||||
$insertJob(4000 + $offset, ['user_id' => 10, 'order_id' => 2000 + $offset,
|
||||
'instance_id' => 3000 + $offset, 'status' => 'running']);
|
||||
$insertInvoice(1000 + $offset, ['user_id' => 10, 'order_id' => 2000 + $offset,
|
||||
'instance_id' => 3000 + $offset, 'status' => 'paid', 'paid_at' => $now - 50,
|
||||
'created_at' => $created]);
|
||||
$insertPayment(5000 + $offset, ['user_id' => 10, 'invoice_id' => 1000 + $offset,
|
||||
'created_at' => $created]);
|
||||
}
|
||||
|
||||
// Exercise the real SQL implementation, including the existing invoice
|
||||
// service's deadline calculation. Only authentication/infrastructure edges
|
||||
// above are test doubles; no financial service or model is substituted.
|
||||
$before = [];
|
||||
foreach (['user', 'cloud_orders', 'cloud_jobs', 'cloud_invoices', 'cloud_invoice_payments'] as $table) {
|
||||
$before[$table] = Capsule::table($table)->orderBy('id')->get()->toJson();
|
||||
}
|
||||
$queryCounts = [];
|
||||
foreach (['invoices' => 1000, 'orders' => 2000, 'payments' => 5000] as $view => $baseId) {
|
||||
$page = CloudAdminBillingService::page(['view' => $view, 'user_id' => '10']);
|
||||
$assert($page['view'] === $view && $page['pagination']['total'] === 135
|
||||
&& count($page['items']) === 30 && $page['summary']['total_records'] === 135
|
||||
&& $page['summary']['total_amount'] === '168.75'
|
||||
&& $ids($page['items']) === range($baseId + 134, $baseId + 105),
|
||||
'Three-view page routing, full-population summary, or stable newest-first ordering failed: ' . $view);
|
||||
$seen = [];
|
||||
for ($number = 1; $number <= 2; $number++) {
|
||||
$chunk = CloudAdminBillingService::page([
|
||||
'view' => $view, 'user_id' => '10', 'page' => (string) $number, 'per_page' => '100',
|
||||
]);
|
||||
$seen = array_merge($seen, $ids($chunk['items']));
|
||||
}
|
||||
$assert($seen === range($baseId + 134, $baseId),
|
||||
'Pagination duplicated, omitted, or truncated billing records: ' . $view);
|
||||
$last = CloudAdminBillingService::page([
|
||||
'view' => $view, 'user_id' => '10', 'page' => '9999', 'per_page' => '1000',
|
||||
]);
|
||||
$assert($last['pagination']['page'] === 2 && $last['pagination']['per_page'] === 100
|
||||
&& count($last['items']) === 35, 'Pagination bounds were not enforced: ' . $view);
|
||||
$dateFiltered = CloudAdminBillingService::page([
|
||||
'view' => $view, 'user_id' => '10',
|
||||
'created_from' => (string) ($now - 100), 'created_to' => (string) ($now - 100),
|
||||
]);
|
||||
$assert($dateFiltered['pagination']['total'] === 134,
|
||||
'Date filters must include their boundary and apply to the summary: ' . $view);
|
||||
$empty = CloudAdminBillingService::page(['view' => $view, 'user_id' => '999999']);
|
||||
$assert($empty['items'] === [] && $empty['pagination']['total'] === 0
|
||||
&& $empty['pagination']['total_pages'] === 1 && $empty['summary']['total_amount'] === '0.00',
|
||||
'Empty billing results reused old data or reported invalid totals: ' . $view);
|
||||
$search = CloudAdminBillingService::page(['view' => $view, 'q' => 'bulk@example.test']);
|
||||
$assert($search['pagination']['total'] === 135, 'Account search failed: ' . $view);
|
||||
$quoted = CloudAdminBillingService::page(['view' => $view, 'q' => "' OR 1=1 --"]);
|
||||
$assert($quoted['items'] === [], 'Quoted search escaped its SQL parameter: ' . $view);
|
||||
|
||||
$counts = [];
|
||||
foreach ([30, 100] as $size) {
|
||||
$connection = Capsule::connection('default');
|
||||
$connection->flushQueryLog();
|
||||
$connection->enableQueryLog();
|
||||
CloudAdminBillingService::page(['view' => $view, 'user_id' => '10', 'per_page' => (string) $size]);
|
||||
$queries = $connection->getQueryLog();
|
||||
$connection->disableQueryLog();
|
||||
$counts[] = count($queries);
|
||||
foreach ($queries as $query) {
|
||||
$assert(preg_match('/^\s*(select|with)\b/i', $query['query']) === 1,
|
||||
'Billing list performed a write instead of a read: ' . $view);
|
||||
}
|
||||
}
|
||||
$assert($counts[0] <= 12 && $counts[1] === $counts[0],
|
||||
'Billing rows introduced N+1 queries: ' . $view . ' ' . implode('/', $counts));
|
||||
$queryCounts[$view] = $counts;
|
||||
}
|
||||
|
||||
$ledger = CloudAdminBillingService::page(['user_id' => '1']);
|
||||
$assert($ledger['view'] === 'invoices' && $ledger['summary']['total_records'] === 8
|
||||
&& $ledger['summary']['total_amount'] === '390.00'
|
||||
&& $ledger['summary']['paid_count'] === 3 && $ledger['summary']['paid_amount'] === '180.00'
|
||||
&& $ledger['summary']['refunded_count'] === 1 && $ledger['summary']['refunded_amount'] === '30.00'
|
||||
&& $ledger['summary']['outstanding_count'] === 2 && $ledger['summary']['outstanding_amount'] === '90.00',
|
||||
'Paid invoices must exclude refunds once; refunded 30 must not be subtracted again from paid 180.');
|
||||
$paymentSummary = CloudAdminBillingService::payments(['user_id' => '1'])['summary'];
|
||||
$assert($paymentSummary['total_records'] === 8 && $paymentSummary['total_amount'] === '350.00'
|
||||
&& $paymentSummary['paid_invoice_amount'] === '150.00'
|
||||
&& $paymentSummary['credited_balance_amount'] === '70.00'
|
||||
&& $paymentSummary['status_counts']['creating'] === 1
|
||||
&& $paymentSummary['status_counts']['pending'] === 1
|
||||
&& $paymentSummary['status_counts']['failed'] === 1,
|
||||
'Attempted amounts, invoice settlement records, and retained balance were incorrectly combined.');
|
||||
foreach ([
|
||||
['financial_status' => 'paid', 'expected' => [6, 5, 1]],
|
||||
['financial_status' => 'refunded', 'expected' => [2]],
|
||||
['financial_status' => 'open', 'expected' => [3]],
|
||||
['financial_status' => 'overdue', 'expected' => [4]],
|
||||
['financial_status' => 'void', 'expected' => [8]],
|
||||
['purpose' => 'recharge', 'expected' => [7, 5]],
|
||||
['purpose' => 'renewal', 'expected' => [8, 6, 4]],
|
||||
['payment_method' => 'balance', 'expected' => [6, 1]],
|
||||
['fulfillment_status' => 'failed', 'expected' => [2]],
|
||||
] as $case) {
|
||||
$expected = $case['expected'];
|
||||
unset($case['expected']);
|
||||
$filtered = CloudAdminBillingService::invoices(['user_id' => '1'] + $case);
|
||||
$assert($ids($filtered['items']) === $expected
|
||||
&& $filtered['summary']['total_records'] === count($expected),
|
||||
'Invoice filter disagreed with the displayed financial/fulfilment state: ' . json_encode($case));
|
||||
}
|
||||
$running = CloudAdminBillingService::orders(['user_id' => '10', 'status' => 'running']);
|
||||
$assert($running['summary']['total_records'] === 135
|
||||
&& $running['summary']['status_counts']['running'] === 135,
|
||||
'Order filters must use the current task state rather than the stale queued order state.');
|
||||
$queued = CloudAdminBillingService::orders(['user_id' => '10', 'status' => 'queued']);
|
||||
$assert($queued['items'] === [], 'The same order appeared in both queued and running filters.');
|
||||
$refundedOrder = CloudAdminBillingService::orders(['user_id' => '1', 'financial_status' => 'refunded']);
|
||||
$assert($ids($refundedOrder['items']) === [102], 'Order financial filtering lost its owner-scoped invoice relation.');
|
||||
$retainedPayments = CloudAdminBillingService::payments(['user_id' => '1', 'status' => 'credited_balance']);
|
||||
$assert($ids($retainedPayments['items']) === [7, 5], 'Retained-balance payment filter was confused with refunds.');
|
||||
$providerPayments = CloudAdminBillingService::payments(['user_id' => '1', 'provider' => 'yipay_wxpay']);
|
||||
$assert($ids($providerPayments['items']) === [5], 'Payment provider filtering was ignored.');
|
||||
$invoicePayments = CloudAdminBillingService::payments(['user_id' => '1', 'invoice_id' => '3']);
|
||||
$assert($ids($invoicePayments['items']) === [8, 3], 'Exact invoice payment filtering crossed another invoice.');
|
||||
|
||||
$expectError(static fn () => CloudAdminBillingService::page(['view' => ['invoices']]), 400,
|
||||
'An array cannot select a billing view');
|
||||
$expectError(static fn () => CloudAdminBillingService::page(['view' => 'invented']), 400,
|
||||
'An unknown billing view must not silently become invoices');
|
||||
foreach (['invoices', 'orders', 'payments'] as $view) {
|
||||
foreach (['page', 'per_page', 'user_id', 'q', 'created_from', 'created_to'] as $key) {
|
||||
$expectError(static fn () => CloudAdminBillingService::page(['view' => $view, $key => ['bad']]), 422,
|
||||
'Array filter must be rejected: ' . $view . '/' . $key);
|
||||
}
|
||||
$expectError(static fn () => CloudAdminBillingService::page([
|
||||
'view' => $view, 'created_from' => (string) $now, 'created_to' => (string) ($now - 1),
|
||||
]), 422, 'An inverted date interval must not be queried');
|
||||
}
|
||||
$expectError(static fn () => CloudAdminBillingService::invoice('999999'), 404,
|
||||
'A missing invoice must not fabricate details');
|
||||
|
||||
$details = [];
|
||||
foreach (range(1, 16) as $id) {
|
||||
$details[$id] = CloudAdminBillingService::invoice((string) $id);
|
||||
}
|
||||
$assert($details[1]['funds']['settled_amount'] === '100.00'
|
||||
&& $details[1]['funds']['refund_amount'] === null
|
||||
&& $details[1]['invoice']['payment_deadline_at'] === $now + 3600
|
||||
&& $details[1]['invoice']['specification']['cpu_cores'] === 2,
|
||||
'Settled provisioning detail lost its specification, deadline, or financial meaning.');
|
||||
$assert($details[2]['funds']['settled_amount'] === '30.00'
|
||||
&& $details[2]['funds']['refund_amount'] === '30.00'
|
||||
&& $details[2]['funds']['refund_destination'] === 'balance'
|
||||
&& $details[2]['funds']['refunded_at'] === $now - 200
|
||||
&& $details[2]['job']['status'] === 'failed',
|
||||
'A confirmed failed-provision refund must identify the original settlement and balance return independently.');
|
||||
$assert($details[3]['funds']['settled_amount'] === null
|
||||
&& $details[3]['funds']['refund_amount'] === null
|
||||
&& $details[3]['funds']['refund_destination'] === null,
|
||||
'An unpaid order was described as a paid or refunded order.');
|
||||
$assert($details[4]['invoice']['financial_status'] === 'overdue'
|
||||
&& $details[4]['invoice']['fulfillment_status'] === 'awaiting_payment'
|
||||
&& $details[4]['invoice']['payment_deadline_at'] === $now - 60 + 3 * 86400
|
||||
&& $details[6]['invoice']['fulfillment_status'] === 'succeeded',
|
||||
'Renewal detail lost its grace deadline or mixed renewal completion with payment state.');
|
||||
$assert($details[5]['invoice']['purpose'] === 'recharge'
|
||||
&& $details[5]['job'] === null && $details[5]['instance'] === null
|
||||
&& $details[5]['invoice']['fulfillment_status'] === null,
|
||||
'Recharge detail fabricated a virtual machine or provisioning task.');
|
||||
$assert($details[7]['funds']['settled_amount'] === null
|
||||
&& $details[7]['funds']['refund_amount'] === null
|
||||
&& $details[7]['funds']['balance_retained_amount'] === '10.00'
|
||||
&& $details[7]['funds']['balance_retained_count'] === 1,
|
||||
'An expired unpaid invoice with retained payment funds was incorrectly called a refund.');
|
||||
$assert($details[8]['invoice']['financial_status'] === 'void'
|
||||
&& $details[8]['links']['instance'] === null,
|
||||
'An orphan renewal still offered payment or a deleted-instance link.');
|
||||
$assert($details[9]['order'] === null && $details[9]['job'] === null
|
||||
&& $details[9]['instance'] === null && $details[9]['payment_attempts'] === []
|
||||
&& $details[9]['links']['instance'] === null
|
||||
&& $details[9]['funds']['balance_retained_amount'] === '0.00',
|
||||
'Invoice detail crossed ownership through orders, instances or gateway attempts.');
|
||||
$assert($details[10]['funds']['refund_amount'] === null
|
||||
&& $details[10]['funds']['refund_destination'] === null
|
||||
&& $details[10]['funds']['refunded_at'] === null,
|
||||
'A foreign order\'s refund timestamp falsely confirmed another user\'s refund.');
|
||||
$assert($details[11]['links']['user'] === null, 'A missing account received a fabricated administrative link.');
|
||||
$assert(count($details[12]['payment_attempts']) === 100
|
||||
&& $details[12]['payment_attempts_truncated'] === true
|
||||
&& $ids($details[12]['payment_attempts']) === range(6104, 6005)
|
||||
&& $details[12]['funds']['balance_retained_count'] === 105
|
||||
&& $details[12]['funds']['balance_retained_amount'] === '115.50'
|
||||
&& $details[12]['funds']['payment_records_truncated'] === true,
|
||||
'Retained balance must aggregate every same-owner payment, not just the latest 100 display rows.');
|
||||
$assert($details[14]['funds']['refund_amount'] === '9.00'
|
||||
&& str_contains(implode(' ', $details[14]['funds']['notes']), '不同'),
|
||||
'Refund explanation replaced the recorded order amount with a conflicting invoice face value.');
|
||||
|
||||
$eventsOf = static fn (array $detail, string $kind): array => array_values(array_filter(
|
||||
$detail['timeline'], static fn (array $event): bool => $event['kind'] === $kind
|
||||
));
|
||||
$assert($eventsOf($details[2], 'invoice_refunded')[0]['at'] === $now - 200
|
||||
&& $eventsOf($details[10], 'invoice_refunded')[0]['at'] === null
|
||||
&& $eventsOf($details[13], 'invoice_paid')[0]['at'] === null,
|
||||
'Timeline invented missing financial event timestamps from generic updated_at values.');
|
||||
$assert($eventsOf($details[3], 'invoice_paid') === []
|
||||
&& $eventsOf($details[3], 'invoice_refunded') === []
|
||||
&& $eventsOf($details[7], 'invoice_refunded') === []
|
||||
&& $eventsOf($details[7], 'invoice_closed')[0]['at'] === null,
|
||||
'Unpaid/expired timeline fabricated settlement or refund events.');
|
||||
foreach ([8, 15, 16] as $id) {
|
||||
$void = $details[$id];
|
||||
$assert($void['invoice']['financial_status'] === 'void'
|
||||
&& $void['funds']['title'] === '账单已作废'
|
||||
&& $void['funds']['settled_amount'] === null
|
||||
&& $void['funds']['refund_amount'] === null
|
||||
&& $void['funds']['refund_destination'] === null
|
||||
&& $eventsOf($void, 'invoice_paid') === []
|
||||
&& $eventsOf($void, 'invoice_refunded') === []
|
||||
&& count($eventsOf($void, 'invoice_closed')) === 1
|
||||
&& $eventsOf($void, 'invoice_closed')[0]['at'] === null,
|
||||
'Deleted/missing renewal targets must show the same derived void state in funds and timeline without inventing financial events.');
|
||||
}
|
||||
foreach ($eventsOf($details[7], 'payment_updated') as $event) {
|
||||
$assert($event['at'] === $now - 100 && str_contains($event['description'], '更新时间')
|
||||
&& str_contains($event['description'], '不代表'),
|
||||
'A payment record update was presented as the gateway receipt time.');
|
||||
}
|
||||
foreach ($details as $detail) {
|
||||
$dated = array_values(array_filter(array_column($detail['timeline'], 'at'),
|
||||
static fn ($at): bool => $at !== null));
|
||||
$sorted = $dated;
|
||||
sort($sorted);
|
||||
$assert($dated === $sorted, 'Timeline did not preserve chronological order.');
|
||||
}
|
||||
$assert($details[1]['links']['user'] === '/admin/user/1/edit'
|
||||
&& $details[1]['links']['instance'] === '/admin/cloud/instances?q=11111111-1111-4111-8111-000000000501'
|
||||
&& $details[1]['links']['payments'] === '/admin/billing?view=payments&invoice_id=1',
|
||||
'Validated account, exact-instance, or payment deep links were lost.');
|
||||
|
||||
AdminPermission::$superAdmin = false;
|
||||
$masked = CloudAdminBillingService::invoice('1');
|
||||
$assert($masked['invoice']['user_email'] !== 'alice@example.test'
|
||||
&& $masked['invoice']['user_name'] !== 'Alice Finance'
|
||||
&& $masked['links']['user'] === null && $masked['links']['instance'] !== null,
|
||||
'Read-only admins gained unmasked account data or a restricted account-edit link.');
|
||||
foreach (['invoices', 'orders', 'payments'] as $view) {
|
||||
$hidden = CloudAdminBillingService::page(['view' => $view, 'q' => 'alice@example.test']);
|
||||
$assert($hidden['items'] === [], 'Masked account search disclosed a hidden identity: ' . $view);
|
||||
}
|
||||
AdminPermission::$superAdmin = true;
|
||||
$serialized = json_encode([$details, $ledger, $masked], JSON_THROW_ON_ERROR);
|
||||
$assert(!str_contains($serialized, 'must-not-expose')
|
||||
&& !str_contains($serialized, 'credential_cipher')
|
||||
&& !str_contains($serialized, 'provider_order_no')
|
||||
&& !str_contains($serialized, 'idempotency_key')
|
||||
&& !str_contains($serialized, 'payment_reference')
|
||||
&& !str_contains($serialized, 'unreviewed_note'),
|
||||
'Billing detail leaked unreviewed provider, credential or metadata fields.');
|
||||
|
||||
$login = static function (bool $admin, bool $super = false): void {
|
||||
$user = new User();
|
||||
$user->id = 1;
|
||||
$user->enable = 1;
|
||||
$user->is_admin = $admin;
|
||||
$user->isLogin = true;
|
||||
Auth::$user = $user;
|
||||
AdminPermission::$superAdmin = $super;
|
||||
};
|
||||
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
|
||||
require dirname(__DIR__) . '/config/routes_cloud.php';
|
||||
$requestApi = static function (string $path, array $query = []) use ($app): array {
|
||||
$request = Request::createFromEnvironment(Environment::mock([
|
||||
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => $path,
|
||||
]))->withQueryParams($query);
|
||||
$response = $app->process($request, new Response());
|
||||
return [$response, json_decode((string) $response->getBody(), true)];
|
||||
};
|
||||
$login(true, true);
|
||||
foreach (['invoices', 'orders', 'payments'] as $view) {
|
||||
[$response, $payload] = $requestApi('/api/v1/admin/billing/' . $view, ['user_id' => '10']);
|
||||
$assert($response->getStatusCode() === 200 && $payload['pagination']['total'] === 135
|
||||
&& $response->getHeaderLine('Cache-Control') === 'private, no-store',
|
||||
'Registered billing route lost its private database response: ' . $view);
|
||||
}
|
||||
[$response, $payload] = $requestApi('/api/v1/admin/billing/invoices/2');
|
||||
$assert($response->getStatusCode() === 200 && $payload['funds']['refund_destination'] === 'balance',
|
||||
'The invoice API did not expose the verified read-only funds explanation.');
|
||||
$login(true);
|
||||
[$response, $payload] = $requestApi('/api/v1/admin/billing/invoices/1');
|
||||
$assert($response->getStatusCode() === 200 && $payload['links']['user'] === null,
|
||||
'Read-only admins lost billing detail access or gained account-edit permission.');
|
||||
$login(false);
|
||||
foreach (['invoices', 'orders', 'payments', 'invoices/1'] as $suffix) {
|
||||
[$response] = $requestApi('/api/v1/admin/billing/' . $suffix);
|
||||
$assert($response->getStatusCode() === 403, 'Customer access to an admin billing route was not denied.');
|
||||
}
|
||||
Auth::$user = null;
|
||||
[$response] = $requestApi('/api/v1/admin/billing/invoices');
|
||||
$assert($response->getStatusCode() === 401, 'Anonymous access bypassed billing authentication.');
|
||||
|
||||
// Authentication rejection must return before the inherited constructor's
|
||||
// Redis/theme work or view rendering is needed. This invokes the real page
|
||||
// controller and CloudAccess, with no substitute business or view service.
|
||||
$pageController = (new \ReflectionClass(\App\Controllers\Admin\CloudPageController::class))
|
||||
->newInstanceWithoutConstructor();
|
||||
$pageRequest = Request::createFromEnvironment(Environment::mock([
|
||||
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/admin/billing',
|
||||
]));
|
||||
foreach (['disabled' => 401, 'anonymous' => 401, 'customer' => 403] as $identity => $status) {
|
||||
$login($identity !== 'customer', true);
|
||||
if ($identity === 'disabled') Auth::$user->enable = 0;
|
||||
if ($identity === 'anonymous') Auth::$user = null;
|
||||
$response = $pageController->billing($pageRequest, new Response(), []);
|
||||
$assert($response->getStatusCode() === $status
|
||||
&& $response->getHeaderLine('Cache-Control') === 'private, no-store'
|
||||
&& (string) $response->getBody() === '',
|
||||
'Page authentication failure became a 500 or rendered the admin shell: ' . $identity);
|
||||
}
|
||||
foreach ($before as $table => $snapshot) {
|
||||
$assert(Capsule::table($table)->orderBy('id')->get()->toJson() === $snapshot,
|
||||
'Read-only billing mutated financial/account records: ' . $table);
|
||||
}
|
||||
$assert(CloudEngineClient::$calls === 0 && CloudSessionService::$calls === 0,
|
||||
'Database-only billing reads created an engine session or contacted the engine.');
|
||||
echo 'Administrator billing SQL pagination/filtering, financial separation, funds/timeline/links, ownership and API access passed. Queries for 30/100 rows: '
|
||||
. json_encode($queryCounts) . ".\n";
|
||||
}
|
||||
Loading…
Reference in New Issue