Fix renewal billing visibility and expiry deadlines

go
codex 4 weeks ago
parent 88f38d933f
commit f3f655ba2d

@ -10,7 +10,7 @@ Virt Cloud 是 PHP 8.5 面板与宿主机 Go Agent 组成的虚拟机销售平
- Agent 以 `panel_url + agent_id + agent_secret` 主动建立 WSS 长连接。PHP 先持久化任务并立即向浏览器返回 `202 Accepted`,再通过面板本机 Go Agent Gateway 派发一次带 SHA-256、时间戳、nonce、操作者上下文和 HMAC-SHA256 签名的请求。断线、超时或重启都不会重新派发 mutation。
- 所有虚拟机使用宿主机能力支持的 Q35 UEFI,并明确关闭 Secure Boot。不要硬编码某个发行版的 OVMF 路径。
- 每个云镜像可配置仅首次安装执行的启动脚本。创建任务会快照脚本版本;脚本成功、失败或中断后都不会自动重放,租户不能读取或覆盖脚本正文。
- 用户购买套餐开通一台 VM;每次购买或续费生成独立预付费账期及流量额度。额度用尽只断网、不关机;下一已付费账期恢复网络。最终到期只断网;未支付续费账单进入三天宽限期,之后永久删除 VM 定义和面板管理的磁盘。
- 用户购买套餐开通一台 VM;每次购买或续费生成独立预付费账期及流量额度。新建实例账单的支付期限由后台按分钟配置,只影响之后生成的开通账单;续费账单的支付截止固定为其对应实例到期时间加三天,不会因账单延迟生成而顺延。额度用尽只断网、不关机;下一已付费账期恢复网络。最终到期只断网;未支付续费账单进入三天宽限期,之后永久删除 VM 定义和面板管理的磁盘。
- 用户页面及登录页保持原虚拟机面板样式,管理员页面保留 venix 主题。普通用户不获得宿主机管理、Agent 设置或退役节点管理入口。
- 任务只有执行中、成功和失败三种公开状态,终态只有 `succeeded` 或 `failed`;所有任务都有绝对截止时间。派发后超时或断线直接终态失败,并标记“效果可能已发生、不可重放原 operation ID”;任务不会停在“待核对”,也不会自动重试、退款或再次删除磁盘。实例设置可以用精确晚到回执,或 Agent 对同一 operation 的只读双标记证据,收敛 PHP 凭据/主机名账本与内部 effect fence;原任务仍保持失败,原宿主机 mutation 永不重放。不能可靠受 Go context 中止的 libvirt mutation 在独立子进程中执行,截止后由父 Agent 回收整个进程组。固定存储池配置是非破坏性的幂等例外:失败任务仍终止且不重放,但不保留跨任务资源栅栏;已定义的固定 pool 不做失败回滚,管理员可显式提交新任务核验或补全同路径固定池,绝不改绑、迁移或删除数据。

@ -313,7 +313,8 @@ location = /agent/console {
3. 配置预先存在的 bridge 和一个或多个公网 IPv4 CIDR;显式保留宿主机管理 IP。Agent 不通过扫描推测可售地址。
4. 导入云镜像和救援 ISO。远程下载只接受可公开解析的 HTTPS 直链,Agent 会校验初始地址与全部跳转;来源的发行方可信度由管理员确认。本地上传必须是独立、未加密、无 backing/data file 的 QCOW2。
5. 为每个云镜像按需设置首次安装启动脚本。脚本最大 32 KiB UTF-8、拒绝 NUL;保存后修订递增,新创建任务快照当前版本。不要在脚本中写长期密钥。
6. 创建销售套餐和库存,再启用宿主机/Agent 调度。用户支付成功后只应创建一个 VM。
6. 在 `/admin/config` 的“云实例计费”中设置新建实例账单支付期限,单位为分钟;`60` 表示 1 小时,`1440` 表示 1 天。该值只作用于保存后新生成的开通账单,既有账单保持原截止时间。
7. 创建销售套餐和库存,再启用宿主机/Agent 调度。用户支付成功后只应创建一个 VM。
部署人员根据宿主机 domain capabilities 选择 Q35 UEFI loader/NVRAM 并写入该机 Agent 配置,Agent 用这组本地固定值生成明确关闭 Secure Boot 的 XML。首次启动脚本由 cloud-init 一次性 runner 执行;VM 创建成功不等待脚本完成,脚本失败或中断不自动重放。
@ -332,6 +333,7 @@ location = /agent/console {
- 杀死超时 helper 后确认整个进程组已回收;只有 `Wait` 成功才释放资源 admission。不能回收时,新冲突请求必须立即被执行栅栏拒绝。
- 重复、乱序和晚到完成回执不能改变终态或触发 mutation;允许类型的精确同源回执最多幂等收敛 PHP 副作用账本与 effect fence。回执在精确 ACK 前按固定低频间隔持续投递,旧 attempts/expires 不得使其永久退出 outbox。
- 并发购买不超卖 CPU/内存/磁盘/IP;同一 VM 变更串行。
- 分别把新建实例账单支付期限设为 60 和 1440 分钟,确认新账单截止时间为 1 小时和 1 天且旧账单不变;续费账单无论何时生成,其支付截止都必须等于对应实例到期时间加三天。
- RX+TX 额度用尽只断网;下一账期恢复;最终到期只断网;三天宽限结束后删除定义与面板受管磁盘。
- MariaDB、Redis、SMTP、支付回调、大文件上传和 PHP-FPM 重启。

@ -2,6 +2,6 @@
仅保留 venix 主题及通用账户、邮箱、工单、公告、充值和财务能力。
用户侧旧节点列表已经删除;管理员在 `/admin/hosts` 配置宿主机。
商城套餐现在是 CPU、内存、带宽、硬盘、账期天数和每期流量额度。部署时先生成开通账单,使用余额或已启用的在线支付渠道结清后,PHP 面板才会通过目标宿主机的私有 Go Agent 创建实例。到期前 7 天生成续费账单;支持到期断网以及流量用尽仅断网。生产必须同时运行普通 worker、账期 worker 与独立策略 worker。
商城套餐现在是 CPU、内存、带宽、硬盘、账期天数和每期流量额度。部署时先生成开通账单,支付期限可在后台按分钟配置;使用余额或已启用的在线支付渠道结清后,PHP 面板才会通过目标宿主机的私有 Go Agent 创建实例。到期前 7 天生成续费账单,其支付截止固定为对应实例到期时间加 3 天;支持到期断网以及流量用尽仅断网。生产必须同时运行普通 worker、账期 worker 与独立策略 worker。
部署与安全边界见上层 `docs/DEPLOYMENT.md` 和 `docs/INTEGRATION_PLAN.md`。真实数据库、宿主机与支付通道仍必须在测试环境验收后再开放销售。

@ -9,6 +9,7 @@ use App\Services\AdminPermission;
use App\Services\Auth;
use App\Services\CaptchaConfig;
use App\Services\Cloud\CloudIpChangeBillingService;
use App\Services\Cloud\CloudProvisioningBillingConfig;
use App\Services\LoginSessionDurationService;
use App\Services\LoginSessionRevocationService;
use App\Services\RegistrationEmailWhitelist;
@ -44,6 +45,8 @@ class ConfigController extends AdminController
ReferralConfig::ENABLED_KEY => ReferralConfig::DEFAULT_ENABLED,
CloudIpChangeBillingService::PRICE_CONFIG_KEY =>
CloudIpChangeBillingService::DEFAULT_PRICE,
CloudProvisioningBillingConfig::PAYMENT_WINDOW_MINUTES_KEY =>
(string) CloudProvisioningBillingConfig::DEFAULT_PAYMENT_WINDOW_MINUTES,
'language' => 'false',
'host_1' => '',
'host_2' => '',
@ -136,6 +139,15 @@ class ConfigController extends AdminController
$payload[CloudIpChangeBillingService::PRICE_CONFIG_KEY]
);
}
if (array_key_exists(
CloudProvisioningBillingConfig::PAYMENT_WINDOW_MINUTES_KEY,
$payload
)) {
$payload[CloudProvisioningBillingConfig::PAYMENT_WINDOW_MINUTES_KEY] =
(string) CloudProvisioningBillingConfig::validatePaymentWindowMinutes(
$payload[CloudProvisioningBillingConfig::PAYMENT_WINDOW_MINUTES_KEY]
);
}
} catch (\InvalidArgumentException $exception) {
return $response->withJson([
'ret' => 0,
@ -253,6 +265,10 @@ class ConfigController extends AdminController
$data[$key] = (string) ReferralConfig::normalizeDays($value);
} elseif ($key === ReferralConfig::ENABLED_KEY) {
$data[$key] = ReferralConfig::normalizeBoolean($value) ? 'true' : 'false';
} elseif ($key === CloudProvisioningBillingConfig::PAYMENT_WINDOW_MINUTES_KEY) {
$data[$key] = (string) CloudProvisioningBillingConfig::validatePaymentWindowMinutes(
$value
);
} else {
$data[$key] = $value;
}

@ -233,8 +233,11 @@ final class CloudApiController
throw new CloudError('账单页码无效');
}
$perPage = 10;
$purpose = CloudInvoicePageService::normalizePurpose(
$query['purpose'] ?? 'all'
);
$payload = CloudInvoicePageService::forUser(
(int) $actor['user_id'], (int) $pageValue, $perPage
(int) $actor['user_id'], (int) $pageValue, $perPage, $purpose
);
$payload['balance'] = (string) $user->money;
return $this->json($response, $payload);

@ -169,7 +169,10 @@ final class CloudPageController
$page = !is_array($requestedPage)
&& preg_match('/^[1-9][0-9]{0,8}$/D', (string) $requestedPage) === 1
? (int) $requestedPage : 1;
$payload = CloudInvoicePageService::forUser((int) $actor['user_id'], $page, 10);
$purpose = CloudInvoicePageService::normalizePurpose($query['purpose'] ?? 'all');
$payload = CloudInvoicePageService::forUser(
(int) $actor['user_id'], $page, 10, $purpose
);
$payload['balance'] = (string) $user->money;
$rows = array_map(fn (array $invoice): array => $this->invoiceListRow($invoice),
$payload['invoices']);
@ -178,6 +181,7 @@ final class CloudPageController
return $this->render($response, 'invoices', '账单信息', '', '', [
'cloud_invoice_rows' => $rows,
'cloud_invoice_filter' => $payload['purpose'],
'cloud_invoice_pagination' => $payload['pagination'],
'cloud_invoice_balance' => $this->formatUsd($payload['balance']),
'cloud_invoice_bootstrap_json' => $json === false ? '{}' : $json,
@ -275,6 +279,7 @@ final class CloudPageController
$smarty->assign('cloud_vm_id', $vmId);
$smarty->assign('cloud_invoice_id', $invoiceId);
$smarty->assign('cloud_invoice_rows', []);
$smarty->assign('cloud_invoice_filter', 'all');
$smarty->assign('cloud_invoice_pagination', [
'page' => 1, 'total' => 0, 'total_pages' => 1,
'has_previous' => false, 'has_next' => false,
@ -347,6 +352,29 @@ final class CloudPageController
$invoice['show_fulfillment'] = (string) ($invoice['purpose'] ?? '') === 'provision'
&& in_array(strtolower((string) ($invoice['status'] ?? '')), ['paid', 'refunded'], true)
&& $fulfillmentLabel !== '';
$purpose = strtolower((string) ($invoice['purpose'] ?? ''));
$status = strtolower((string) ($invoice['status'] ?? ''));
$invoice['context_display'] = '';
if ($purpose === 'renewal') {
$invoice['context_display'] = '对应实例到期 '
. $this->formatTimestamp(
$invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null,
'时间未记录'
);
if (in_array($status, ['open', 'overdue'], true)) {
$invoice['context_display'] .= ' · 最晚支付 '
. $this->formatTimestamp(
$invoice['payment_deadline_at'] ?? null,
'时间未记录'
);
}
} elseif ($purpose === 'provision') {
$invoice['context_display'] = '支付截止 '
. $this->formatTimestamp(
$invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null,
'时间未记录'
);
}
return $invoice;
}
@ -369,7 +397,7 @@ final class CloudPageController
)];
} elseif ($purpose === 'renewal') {
$facts[] = ['label' => '实例到期', 'value' => $this->formatTimestamp(
$invoice['due_at'] ?? null
$invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null
)];
if (($invoice['deletion_at'] ?? null) !== null) {
$facts[] = ['label' => '最晚支付', 'value' => $this->formatTimestamp(
@ -765,7 +793,7 @@ final class CloudPageController
'service_status_class' => $serviceClass,
'network_status_label' => $networkLabel,
'network_status_class' => $networkClass,
'period_end_display' => $this->dateTime($vm['current_period_ends_at'] ?? null),
'service_expiry_display' => $this->dateTime($vm['service_expires_at'] ?? null),
'traffic_rx_display' => $this->formatBytes($download),
'traffic_tx_display' => $this->formatBytes($upload),
'traffic_used_display' => $this->formatBytes($used),

@ -64,7 +64,8 @@ final class CloudInvoiceDetailPageService
->where('user_id', $userId)
->sharedLock()
->first(['id', 'purpose', 'instance_id', 'order_id', 'user_id',
'due_at', 'status', 'paid_at', 'paid_via', 'created_at']);
'renews_expires_at', 'due_at', 'status', 'paid_at',
'paid_via', 'created_at']);
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}

@ -11,29 +11,51 @@ use App\Models\CloudInvoice;
*/
final class CloudInvoicePageService
{
public static function forUser(int $userId, int $page = 1, int $perPage = 10): array
private const PURPOSES = ['all', 'renewal', 'provision', 'ip_change'];
public static function normalizePurpose($value): string
{
if (is_array($value) || is_object($value)) {
return 'all';
}
$purpose = strtolower(trim((string) $value));
return in_array($purpose, self::PURPOSES, true) ? $purpose : 'all';
}
public static function forUser(int $userId, int $page = 1, int $perPage = 10,
string $purpose = 'all'): array
{
$page = max(1, $page);
$perPage = max(1, min(100, $perPage));
$purpose = self::normalizePurpose($purpose);
$base = CloudInvoice::where('user_id', $userId);
if ($purpose !== 'all') {
$base->where('purpose', $purpose);
}
$total = (int) (clone $base)->count();
$totalPages = max(1, (int) ceil($total / $perPage));
$page = min($page, $totalPages);
$records = (clone $base)
// Actionable bills stay ahead of historical service dates.
->orderByRaw("CASE WHEN status IN ('open', 'overdue') THEN 0 ELSE 1 END")
$records = clone $base;
if ($purpose === 'all') {
// Keep bills requiring action prominent in the combined view.
$records->orderByRaw(
"CASE WHEN status IN ('open', 'overdue') THEN 0 ELSE 1 END"
);
}
$records = $records
->orderByDesc('created_at')
->orderByDesc('id')
->offset(($page - 1) * $perPage)
->limit($perPage)
->get([
'id', 'purpose', 'instance_id', 'order_id', 'user_id',
'due_at', 'amount', 'status', 'created_at',
'renews_expires_at', 'due_at', 'amount', 'status', 'created_at',
]);
$count = $records->count();
return [
'invoices' => CloudInvoiceService::listSummaries($records),
'purpose' => $purpose,
'pagination' => [
'page' => $page,
'per_page' => $perPage,

@ -29,9 +29,15 @@ final class CloudInvoiceService
public static function paymentDeadline(CloudInvoice $invoice): int
{
if ((string) $invoice->purpose === 'provision') {
$purpose = (string) ($invoice->purpose ?: 'renewal');
if ($purpose === 'provision') {
return (int) $invoice->due_at;
}
if ($purpose === 'renewal') {
$serviceExpiry = $invoice->renews_expires_at === null
? (int) $invoice->due_at : (int) $invoice->renews_expires_at;
return max(0, $serviceExpiry) + self::PAYMENT_GRACE_SECONDS;
}
return max((int) $invoice->due_at, (int) $invoice->created_at)
+ self::PAYMENT_GRACE_SECONDS;
}
@ -77,7 +83,8 @@ final class CloudInvoiceService
$invoice->offer_id = $order->offer_id;
$invoice->renewal_id = null;
$invoice->renews_expires_at = null;
$invoice->due_at = $now + CloudOrderService::PAYMENT_WINDOW_SECONDS;
$invoice->due_at = $now
+ CloudProvisioningBillingConfig::paymentWindowSeconds();
$invoice->amount = $order->amount;
$invoice->currency = 'USD';
$invoice->validity_days = (int) $plan->validity_days;
@ -315,6 +322,10 @@ final class CloudInvoiceService
'instance_name' => (string) $instance->name,
'amount' => (string) $invoice->amount,
'due_at' => date('Y-m-d H:i:s', (int) $invoice->due_at),
'payment_deadline_at' => date(
'Y-m-d H:i:s',
self::paymentDeadline($invoice)
),
'invoice_url' => $base . '/user/cloud/invoices/' . (int) $invoice->id,
], [], 'cloud_renewal_invoice');
} else {
@ -513,6 +524,10 @@ final class CloudInvoiceService
'purpose' => $purpose,
'amount' => (string) $invoice->amount,
'status' => $status,
'renews_expires_at' => $invoice->renews_expires_at === null
? null : max(0, (int) $invoice->renews_expires_at),
'due_at' => max(0, (int) $invoice->due_at),
'payment_deadline_at' => self::paymentDeadline($invoice),
'created_at' => (int) $invoice->created_at,
'order_status' => $order?->status,
'fulfillment_status' => $jobStatus ?? $order?->status,

@ -14,8 +14,6 @@ use App\Models\User;
final class CloudOrderService
{
/** Unpaid provisioning invoices reserve finite stock for thirty minutes. */
public const PAYMENT_WINDOW_SECONDS = 1800;
private const AUTOMATIC_NAME_SCAN_LIMIT = 256;
public static function purchase(array $input, array $actor): CloudOrder

@ -0,0 +1,61 @@
<?php
namespace App\Services\Cloud;
use App\Models\Configurations;
/** Administrator-controlled payment window for newly provisioned instances. */
final class CloudProvisioningBillingConfig
{
public const PAYMENT_WINDOW_MINUTES_KEY =
'cloud_provision_invoice_payment_window_minutes';
public const DEFAULT_PAYMENT_WINDOW_MINUTES = 30;
public const MIN_PAYMENT_WINDOW_MINUTES = 1;
public const MAX_PAYMENT_WINDOW_MINUTES = 10080;
public static function paymentWindowMinutes(): int
{
$stored = Configurations::where(
'name',
self::PAYMENT_WINDOW_MINUTES_KEY
)->value('value');
try {
return self::validatePaymentWindowMinutes(
$stored === null ? self::DEFAULT_PAYMENT_WINDOW_MINUTES : $stored
);
} catch (\InvalidArgumentException $error) {
throw new CloudError(
'新建实例账单支付期限配置无效,请联系管理员',
503
);
}
}
public static function paymentWindowSeconds(): int
{
return self::paymentWindowMinutes() * 60;
}
public static function validatePaymentWindowMinutes($value): int
{
if (is_array($value) || is_object($value)) {
throw new \InvalidArgumentException(
'新建实例账单支付期限必须是整数分钟'
);
}
$raw = trim((string) $value);
if (preg_match('/^[0-9]+$/D', $raw) !== 1) {
throw new \InvalidArgumentException(
'新建实例账单支付期限必须是整数分钟'
);
}
$minutes = (int) $raw;
if ($minutes < self::MIN_PAYMENT_WINDOW_MINUTES
|| $minutes > self::MAX_PAYMENT_WINDOW_MINUTES) {
throw new \InvalidArgumentException(
'新建实例账单支付期限必须为 1 至 10080 分钟'
);
}
return $minutes;
}
}

@ -275,6 +275,9 @@ body.vu-embedded .dashboard > .main-area > .vu-main > .vu-topbar { margin: 0; }
.cloud-invoice-list-amount { grid-area: amount; min-width: 105px; text-align: right; }
.cloud-invoice-list-amount span { display: block; margin-bottom: 5px; color: #91a0af; font-size: 10px; font-weight: 700; }
.cloud-invoice-list-amount strong { display: block; color: #1e354d; font-size: 18px; line-height: 1.25; white-space: nowrap; }
.invoice-filter-bar { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 14px; }
.invoice-filter-bar .button.active { border-color: #0f9eaa; background: #e8f8f9; color: #087b84; }
.cloud-invoice-context { margin-top: 4px; color: #60788e; }
.invoice-pagination { display: flex; align-items: center; justify-content: flex-end; gap: 12px; margin-top: 18px; }
.invoice-pagination[hidden] { display: none; }
.invoice-pagination > span { min-width: 145px; color: #75899b; font-size: 11px; font-weight: 700; text-align: center; }

@ -1280,7 +1280,9 @@ function renderInvoiceDetail(invoice, payload) {
invoicePaymentDeadlineTimestamp(invoice) ?? invoice.due_at,
)));
} else if (purpose === 'renewal') {
facts.push(invoiceFact('实例到期', formatOrderDate(invoice.due_at)));
facts.push(invoiceFact('实例到期', formatOrderDate(
invoice.renews_expires_at ?? invoice.due_at,
)));
if (invoiceDeletionTimestamp(invoice) !== null) {
facts.push(invoiceFact('最晚支付', formatServiceDate(invoiceDeletionTimestamp(invoice))));
}

@ -3,7 +3,7 @@
// endpoint, leaving only pagination and conditional refresh work to JS.
const byId = id => document.getElementById(id);
const state = {
invoices: [], page: 1,
invoices: [], page: 1, purpose: 'all',
pagination: { page: 1, per_page: 10, total: 0, total_pages: 1,
has_previous: false, has_next: false, from: 0, to: 0 },
loading: false, pollTimer: null, pollUntil: 0,
@ -77,6 +77,22 @@ function invoiceTitle(invoice) {
{ recharge: '余额充值', provision: '实例开通', renewal: '实例续费' }[invoicePurpose(invoice)], '账单');
}
function invoiceContext(invoice) {
const purpose = invoicePurpose(invoice);
const status = String(invoice?.status || '').toLowerCase();
if (purpose === 'renewal') {
let value = `对应实例到期 ${formatDate(invoice?.renews_expires_at ?? invoice?.due_at)}`;
if (['open', 'overdue'].includes(status)) {
value += ` · 最晚支付 ${formatDate(invoice?.payment_deadline_at)}`;
}
return value;
}
if (purpose === 'provision') {
return `支付截止 ${formatDate(invoice?.payment_deadline_at ?? invoice?.due_at)}`;
}
return '';
}
function invoiceStatusInfo(status) {
const values = {
open: ['待支付', 'warning'], overdue: ['已逾期', 'failed'], paid: ['已支付', 'running'],
@ -125,6 +141,8 @@ function renderInvoices() {
const detail = makeElement('div', 'cloud-order-detail cloud-invoice-list-copy');
detail.append(makeElement('strong', '', invoiceTitle(invoice)),
makeElement('p', 'muted', `账单 #${invoice.id} · ${formatDate(invoice.created_at)}`));
const context = invoiceContext(invoice);
if (context) detail.append(makeElement('p', 'muted cloud-invoice-context', context));
const actions = makeElement('div', 'cloud-order-actions cloud-invoice-list-actions');
const invoiceStatus = String(invoice.status || '').toLowerCase();
const [label, className] = invoiceStatusInfo(invoiceStatus);
@ -176,6 +194,8 @@ function updatePageUrl(page) {
const url = new URL(location.href);
if (page > 1) url.searchParams.set('page', String(page));
else url.searchParams.delete('page');
if (state.purpose !== 'all') url.searchParams.set('purpose', state.purpose);
else url.searchParams.delete('purpose');
history.replaceState(history.state, '', `${url.pathname}${url.search}${url.hash}`);
}
@ -201,10 +221,12 @@ async function loadInvoices(page = state.page, updateUrl = true, resetBudget = f
stopPolling();
renderPagination();
try {
const payload = await api(`/api/v1/invoices?page=${encodeURIComponent(requestedPage)}`);
const payload = await api(`/api/v1/invoices?page=${encodeURIComponent(requestedPage)}&purpose=${encodeURIComponent(state.purpose)}`);
state.pagination = normalizePagination(payload?.pagination, requestedPage);
state.page = state.pagination.page;
state.invoices = Array.isArray(payload?.invoices) ? payload.invoices : [];
state.purpose = ['renewal', 'provision', 'ip_change'].includes(payload?.purpose)
? payload.purpose : 'all';
if (byId('invoices-balance')) byId('invoices-balance').textContent = formatUsd(payload?.balance);
renderInvoices();
if (updateUrl) updatePageUrl(state.page);
@ -225,6 +247,8 @@ function hydrate() {
const payload = JSON.parse(source.textContent || '{}');
if (!Array.isArray(payload?.invoices)) return false;
state.invoices = payload.invoices;
state.purpose = ['renewal', 'provision', 'ip_change'].includes(payload?.purpose)
? payload.purpose : 'all';
state.pagination = normalizePagination(payload.pagination, 1);
state.page = state.pagination.page;
renderPagination();

@ -111,10 +111,11 @@ function vmServiceData(vm) {
rx !== null && tx !== null ? rx + tx : null);
const remaining = firstNumber(vm?.traffic_remaining_bytes, service.traffic_remaining_bytes, period.traffic_remaining_bytes, traffic.remaining_bytes,
quota !== null && used !== null ? Math.max(0, quota - used) : null);
const periodEndsAt = vm?.current_period_ends_at ?? vm?.current_period_end ?? service.current_period_ends_at ?? service.current_period_end ?? period.ends_at ?? period.end_at ?? null;
const serviceExpiresAt = vm?.service_expires_at ?? vm?.expires_at
?? service.service_expires_at ?? service.expires_at ?? billing.expires_at ?? null;
const status = firstText(vm?.service_status, service.status, period.status, billing.status, vm?.subscription_status);
const networkStatus = firstText(vm?.network_status, service.network_status, period.network_status, traffic.network_status);
return { quota, rx, tx, used, remaining, periodEndsAt, status, networkStatus };
return { quota, rx, tx, used, remaining, serviceExpiresAt, status, networkStatus };
}
function formatBytes(value) {
if (value === null || !Number.isFinite(value) || value < 0) return '暂未提供';
@ -141,7 +142,7 @@ function formatServiceDate(value) {
}
function serviceStatusInfo(data) {
let status = data.status.toLowerCase().replace(/[\s-]+/g, '_');
if (!status && serviceTimestamp(data.periodEndsAt) !== null) status = serviceTimestamp(data.periodEndsAt) <= Date.now() ? 'expired' : 'active';
if (!status && serviceTimestamp(data.serviceExpiresAt) !== null) status = serviceTimestamp(data.serviceExpiresAt) <= Date.now() ? 'expired' : 'active';
const labels = {
active: ['服务有效', 'active'], pending: ['待生效', 'warning'], renewing: ['续费处理中', 'warning'],
grace: ['已到期,处于删除宽限期', 'warning'], expired_grace: ['已到期,处于删除宽限期', 'warning'], grace_expired: ['已到期,处于删除宽限期', 'warning'],
@ -378,7 +379,7 @@ function renderVmService(vm) {
const networkStatusElement = byId('vm-detail-network-status');
networkStatusElement.textContent = networkStatus.label;
networkStatusElement.className = `service-pill ${networkStatus.className}`;
text('vm-detail-period-end', formatServiceDate(data.periodEndsAt));
text('vm-detail-service-expiry', formatServiceDate(data.serviceExpiresAt));
text('vm-detail-traffic-rx', formatBytes(data.rx));
text('vm-detail-traffic-tx', formatBytes(data.tx));
text('vm-detail-traffic-used', formatBytes(data.used));

@ -1,12 +1,12 @@
{extends file='layout.tpl'}
{block name='email_title'}续费账单已生成 | {$config["appName"]|escape:"html"}{/block}
{block name='preheader'}实例 {$instance_name|escape:"html"} 的续费账单已生成,请在到期前完成支付。{/block}
{block name='preheader'}实例 {$instance_name|escape:"html"} 的续费账单已生成,最晚可在 {$payment_deadline_at|escape:"html"} 前支付。{/block}
{block name='content'}
<p style="margin:0 0 10px; color:#159da9; font-size:11px; line-height:16px; font-weight:800; letter-spacing:1.8px;">SERVICE RENEWAL</p>
<h1 class="email-title" style="margin:0 0 14px; color:#15243a; font-size:28px; line-height:36px; font-weight:800; letter-spacing:-.5px;">续费账单已生成</h1>
<p class="email-copy" style="margin:0 0 23px; color:#53647a; font-size:15px; line-height:25px;">您的云服务器 <strong style="color:#34445a;">{$instance_name|escape:"html"}</strong> 即将到期。为避免网络服务中断,请在到期前完成账单支付。</p>
<p class="email-copy" style="margin:0 0 23px; color:#53647a; font-size:15px; line-height:25px;">您的云服务器 <strong style="color:#34445a;">{$instance_name|escape:"html"}</strong> 将于 {$due_at|escape:"html"} 到期。到期后网络会暂停,您仍可在 <strong style="color:#34445a;">{$payment_deadline_at|escape:"html"}</strong> 前完成续费。</p>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f2f6f9" style="width:100%; margin:0 0 22px; background-color:#f2f6f9; border-radius:12px;">
<tr>

@ -76,6 +76,11 @@
<input class="form-control" id="cloud_ip_change_price" name="cloud_ip_change_price" type="number" min="0" max="999999.99" step="0.01" inputmode="decimal" value="0.00" required>
<div class="form-text">从账户余额扣费。设置为 0.00 时关闭用户自助更换 IP;新价格只影响之后新提交的请求。</div>
</div>
<div class="col-md-6">
<label class="form-label" for="cloud_provision_invoice_payment_window_minutes">新建实例账单支付期限(分钟)</label>
<input class="form-control" id="cloud_provision_invoice_payment_window_minutes" name="cloud_provision_invoice_payment_window_minutes" type="number" min="1" max="10080" step="1" inputmode="numeric" value="30" required>
<div class="form-text">范围 1–10080 分钟。60 表示 1 小时,1440 表示 1 天;只影响保存后新生成的实例开通账单。</div>
</div>
</div>
</div>
</details>

@ -169,7 +169,7 @@
<dl class="vm-service-facts">
<div><dt>服务状态</dt><dd><span id="vm-detail-service-status" class="service-pill {$cloud_vm_view.service_status_class|default:'unknown'|escape:"html"}">{$cloud_vm_view.service_status_label|default:'暂未提供'|escape:"html"}</span></dd></div>
<div><dt>网络状态</dt><dd><span id="vm-detail-network-status" class="service-pill {$cloud_vm_view.network_status_class|default:'unknown'|escape:"html"}">{$cloud_vm_view.network_status_label|default:'暂未提供'|escape:"html"}</span></dd></div>
<div><dt>当前账期结束</dt><dd id="vm-detail-period-end">{$cloud_vm_view.period_end_display|default:'暂未提供'|escape:"html"}</dd></div>
<div><dt>实例到期时间</dt><dd id="vm-detail-service-expiry">{$cloud_vm_view.service_expiry_display|default:'暂未提供'|escape:"html"}</dd></div>
<div><dt>本期下载(RX)</dt><dd id="vm-detail-traffic-rx">{$cloud_vm_view.traffic_rx_display|default:'暂未提供'|escape:"html"}</dd></div>
<div><dt>本期上传(TX)</dt><dd id="vm-detail-traffic-tx">{$cloud_vm_view.traffic_tx_display|default:'暂未提供'|escape:"html"}</dd></div>
<div><dt>本期合计已用</dt><dd id="vm-detail-traffic-used">{$cloud_vm_view.traffic_used_display|default:'暂未提供'|escape:"html"}</dd></div>

@ -1,6 +1,12 @@
<section id="invoices-workspace">
<div class="page-heading"><div><span class="eyebrow">BILLING</span><h1>账单信息</h1><p>部署实例时先生成开通账单,支付完成后才开始创建;实例到期前 7 天会自动生成续费账单。实例到期后立即停用网络,到期满 3 天仍未续费,实例及系统盘将被永久删除。</p></div><button id="invoices-refresh" class="button button-outline" type="button">刷新</button></div>
<div class="invoice-balance-card"><span>当前账户余额</span><strong id="invoices-balance">{$cloud_invoice_balance|escape:"html"}</strong><button class="button button-outline small" type="button" data-account-drawer-open="balance" data-drawer-title="余额充值" data-drawer-description="选择充值金额和可用支付方式">余额充值</button></div>
<nav class="invoice-filter-bar" aria-label="账单类型筛选">
<a class="button button-outline small{if $cloud_invoice_filter == 'all'} active{/if}" href="/user/cloud/invoices"{if $cloud_invoice_filter == 'all'} aria-current="page"{/if}>全部账单</a>
<a class="button button-outline small{if $cloud_invoice_filter == 'renewal'} active{/if}" href="/user/cloud/invoices?purpose=renewal"{if $cloud_invoice_filter == 'renewal'} aria-current="page"{/if}>续费账单</a>
<a class="button button-outline small{if $cloud_invoice_filter == 'provision'} active{/if}" href="/user/cloud/invoices?purpose=provision"{if $cloud_invoice_filter == 'provision'} aria-current="page"{/if}>开通账单</a>
<a class="button button-outline small{if $cloud_invoice_filter == 'ip_change'} active{/if}" href="/user/cloud/invoices?purpose=ip_change"{if $cloud_invoice_filter == 'ip_change'} aria-current="page"{/if}>更换 IP</a>
</nav>
<div id="invoices-list" class="inventory-panel cloud-orders cloud-invoices" aria-live="polite">
{if empty($cloud_invoice_rows)}
<p class="muted">暂无账单。部署实例后会先生成开通账单;续费账单会在实例到期前 7 天自动生成。</p>
@ -10,6 +16,7 @@
<div class="cloud-order-detail cloud-invoice-list-copy">
<strong>{$invoice.title|escape:"html"}</strong>
<p class="muted">账单 #{$invoice.id|escape:"html"} · {$invoice.created_display|escape:"html"}</p>
{if $invoice.context_display}<p class="muted cloud-invoice-context">{$invoice.context_display|escape:"html"}</p>{/if}
</div>
<div class="cloud-order-actions cloud-invoice-list-actions">
<span class="state-pill {$invoice.status_class|escape:"html"}">{$invoice.status_label|escape:"html"}</span>

@ -116,6 +116,7 @@ namespace {
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudIpChangeBillingService;
use App\Services\Cloud\CloudProvisioningBillingConfig;
use App\Services\Cloud\CloudLifecycleService;
use App\Services\Cloud\CloudOperationCompletionService;
use App\Services\Cloud\CloudOperationRecoveryIdentity;
@ -229,6 +230,7 @@ namespace {
$capsule->setAsGlobal(); $capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', function (Blueprint $t) { $t->increments('id'); $t->string('user_name')->default(''); $t->string('email')->default(''); $t->string('money'); $t->integer('enable')->default(1); $t->integer('is_admin')->default(0); $t->integer('restrict_balance_purchase')->default(0); });
$schema->create('configurations', function (Blueprint $t) { $t->increments('id'); $t->string('name')->unique(); $t->text('value'); });
$schema->create('shop', function (Blueprint $t) { $t->increments('id'); $t->string('name'); foreach (['cpu_cores', 'memory_mib', 'bandwidth_mbps', 'disk_gib', 'validity_days', 'traffic_quota_bytes', 'status', 'sort'] as $v) { $t->integer($v)->default(0); } });
$schema->create('cloud_regions', function (Blueprint $t) { $t->increments('id'); $t->string('code'); $t->string('name'); $t->string('country_code'); $t->string('status'); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_network_lines', function (Blueprint $t) { $t->increments('id'); $t->integer('region_id'); $t->string('code'); $t->string('name'); $t->integer('is_default')->default(0); $t->string('status'); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });
@ -316,6 +318,13 @@ namespace {
$schema->create('cloud_invoice_payments', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->integer('user_id'); $t->string('provider'); $t->string('provider_order_no'); $t->string('idempotency_key'); $t->string('amount'); $t->string('status'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['provider', 'provider_order_no']); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_mail_outbox', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->string('kind'); $t->string('status'); $t->integer('attempts'); $t->integer('available_at'); $t->string('lease_token')->nullable(); $t->integer('lease_until'); $t->integer('sent_at')->nullable(); $t->string('last_error'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['invoice_id', 'kind']); });
$schema->create('cloud_ssh_keys', function (Blueprint $t) { $t->increments('id'); $t->integer('user_id'); $t->string('name'); $t->text('public_key'); $t->string('fingerprint'); $t->integer('created_at'); });
$capsule->connection('default')->table('configurations')->insert([
['name' => 'cloud_network_lines_enabled', 'value' => 'false'],
[
'name' => CloudProvisioningBillingConfig::PAYMENT_WINDOW_MINUTES_KEY,
'value' => '60',
],
]);
$capsule->connection('default')->table(
'cloud_platform_test_policy_state'
)->insert(['id' => 1, 'revision' => 0, 'updated_by' => null, 'updated_at' => 0]);
@ -428,7 +437,7 @@ namespace {
$assert(count($catalog['offers'] ?? []) === 2
&& ($catalog['offers'][0]['sellable'] ?? null) === true
&& ($catalog['offers'][1]['sellable'] ?? null) === false
&& $catalogQueryCount <= 5,
&& $catalogQueryCount <= 6,
'Catalog availability hid a sold-out offer, misclassified capacity, or queried per offer.');
foreach (['public', 'bridge:br0'] as $hostNetwork) {
$host->default_network = $hostNetwork;
@ -508,6 +517,7 @@ namespace {
&& $openingInvoice !== null
&& (string) $openingInvoice->purpose === 'provision'
&& $openingInvoice->instance_id === null
&& (int) $openingInvoice->due_at - (int) $openingInvoice->created_at === 3600
&& ($openingDisplay['purpose'] ?? null) === 'provision'
&& ($openingDisplay['title'] ?? null) === '实例开通'
&& ($openingDisplay['type_label'] ?? null) === '实例开通'
@ -525,8 +535,10 @@ namespace {
$assert(count($openingSummaries) === 25
&& $summaryQueryCount <= 3
&& array_keys($openingSummaries[0] ?? []) === [
'id', 'title', 'type_label', 'purpose', 'amount', 'status', 'created_at',
'order_status', 'fulfillment_status', 'job_status',
'id', 'title', 'type_label', 'purpose', 'amount', 'status',
'renews_expires_at', 'due_at', 'payment_deadline_at', 'created_at',
'order_status',
'fulfillment_status', 'job_status',
]
&& ($openingSummaries[0]['order_status'] ?? null) === 'awaiting_payment',
'Invoice list summaries are not compact or use per-invoice association queries.');
@ -2056,11 +2068,6 @@ namespace {
$samePoolSpare->state = 'disabled';
$samePoolSpare->updated_at = time();
$samePoolSpare->save();
$schema->create('configurations', function (Blueprint $t) {
$t->increments('id');
$t->string('name')->unique();
$t->text('value');
});
$assert(CloudIpChangeBillingService::normalizePrice('2.5') === '2.50',
'Paid IP-change price normalization lost exact cents.');
foreach (['-1', '1e2', '1000000.00'] as $invalidPrice) {

@ -156,6 +156,15 @@ namespace {
'id' => 2, 'uuid' => '22222222-2222-4222-8222-222222222222',
'user_id' => 2, 'name' => 'foreign-vm',
]);
Capsule::table('cloud_service_periods')->insert([
'id' => 1,
'instance_id' => 1,
'starts_at' => $now - 3600,
'ends_at' => $now + 3600,
'status' => 'active',
]);
Capsule::table('cloud_instances')->where('id', 1)
->update(['current_period_id' => 1]);
$owner = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false,
'can_manage' => false];
@ -222,6 +231,9 @@ namespace {
&& $ownedDetail['state_fresh'] === true
&& $ownedDetail['state_sync_status'] === 'fresh',
'Detail SSR did not use the fresh runtime observation.');
$assert($ownedDetail['service_expires_at'] === $now + 86400
&& $ownedDetail['current_period_ends_at'] === $now + 3600,
'Instance detail did not keep the latest expiry distinct from the current period.');
$assert(count($ownedDetail['disks']) === 1
&& array_keys($ownedDetail['disks'][0]) === ['capacity_gib']
&& (float) $ownedDetail['disks'][0]['capacity_gib'] === 40.0

@ -95,6 +95,11 @@ $assert(str_contains($invoiceDetailTemplate, 'id="invoice-detail-bootstrap"')
&& !str_contains($invoiceDetailTemplate, '正在读取账单信息')
&& !str_contains($invoiceDetailTemplate, '>读取中<'),
'Invoice-detail HTML must contain meaningful first-paint content, not a client-only shell.');
$assert(str_contains($pageController,
"\$invoice['renews_expires_at'] ?? \$invoice['due_at'] ?? null")
&& str_contains($invoiceDetailRuntime,
'invoice.renews_expires_at ?? invoice.due_at'),
'Renewal invoice details must render their authoritative target expiry.');
$listMethod = $section($apiController, 'public function invoices(',
'private function createProvisionInvoice(');
@ -122,13 +127,14 @@ $assert(substr_count($summaryMethod, '::whereIn(') === 3
&& str_contains($summaryMethod,
'self::publicStatus($invoice, $purpose, $instance, $now)'),
'Invoice list associations are not loaded with fixed-size batch queries.');
foreach (['id', 'title', 'type_label', 'purpose', 'amount', 'status', 'created_at',
foreach (['id', 'title', 'type_label', 'purpose', 'amount', 'status',
'renews_expires_at', 'due_at', 'payment_deadline_at', 'created_at',
'order_status', 'fulfillment_status', 'job_status'] as $field) {
$assert(str_contains($summaryMethod, "'{$field}' =>"),
'Invoice list summary is missing field: ' . $field);
}
foreach (['payment_methods', 'payment_reference', 'paid_via', 'specification',
'traffic_quota_bytes', 'payment_deadline_at'] as $detailOnlyField) {
'traffic_quota_bytes'] as $detailOnlyField) {
$assert(!str_contains($summaryMethod, "'{$detailOnlyField}' =>"),
'Invoice list summary leaked detail-only field: ' . $detailOnlyField);
}

@ -370,17 +370,18 @@ namespace {
return $bill;
};
// An invoice generated after its service expiry receives the complete
// grace period from creation, not a shortened or already-expired window.
// A late-generated invoice must retain the instance's fixed deletion
// cutoff. Creating the bill after expiry cannot extend the grace period.
$gatewayGraceInstance = $makeLifecycleInstance(
'11111111-2222-4333-8444-555555555559', 'gateway-grace', $now - 120);
$gatewayGraceInvoice = $makeLifecycleInvoice($gatewayGraceInstance, 'VC-GRACE-GATEWAY',
$now - 120, $now - 60);
$gatewayGraceDisplay = CloudInvoiceService::display($gatewayGraceInvoice);
$assert((int) ($gatewayGraceDisplay['deletion_at'] ?? 0)
=== $now - 60 + CloudInvoiceService::PAYMENT_GRACE_SECONDS
=== (int) $gatewayGraceInstance->expires_at
+ CloudInvoiceService::PAYMENT_GRACE_SECONDS
&& ($gatewayGraceDisplay['payable'] ?? false) === true,
'Invoice display did not expose the authoritative grace deadline and payable state.');
'Late invoice creation changed the authoritative deletion cutoff or payable state.');
// Replaying an existing gateway attempt exercises the same authoritative
// cutoff validation without making a network request from this test.

@ -24,17 +24,27 @@ $assert(str_contains($controller, 'CloudAccess::actor(false)')
&& str_contains($controller, "withHeader('Cache-Control', 'private, no-store')"),
'Invoice page controller must safely embed an owner-scoped first page without a cloud session.');
$assert(str_contains($service, "CloudInvoice::where('user_id', \$userId)")
&& str_contains($service, "->where('purpose', \$purpose)")
&& str_contains($service, 'normalizePurpose(')
&& str_contains($service, "if (\$purpose === 'all')")
&& str_contains($service, "status IN ('open', 'overdue')")
&& str_contains($service, 'CloudInvoiceService::listSummaries')
&& str_contains($service, "'per_page' => \$perPage")
&& str_contains($service, "->limit(\$perPage)"),
'Shared invoice pagination must remain owner scoped and bounded.');
$assert(str_contains($template, 'id="invoices-bootstrap"')
&& str_contains($template, '{foreach $cloud_invoice_rows as $invoice}')
&& str_contains($template, 'purpose=renewal')
&& str_contains($template, 'cloud-invoice-context')
&& str_contains($controller, "'对应实例到期 '")
&& !str_contains($template, '正在加载…'),
'Invoice HTML must contain the first records instead of a client-only loading placeholder.');
$assert(!str_contains($module, '/cloud/runtime.js')
&& !str_contains($module, '/api/v1/session')
&& str_contains($module, 'function hydrate()')
&& str_contains($module, 'purpose=${encodeURIComponent(state.purpose)}')
&& str_contains($module, 'function invoiceContext(')
&& str_contains($module, 'invoice?.renews_expires_at ?? invoice?.due_at')
&& str_contains($module, 'state.invoices.some(invoiceNeedsPolling)')
&& str_contains($module,
"if (['open', 'overdue'].includes(status)) return true;")

@ -0,0 +1,105 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Services\Cloud\CloudInvoicePageService;
use App\Services\Cloud\CloudInvoiceService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->string('status');
});
$schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->increments('id');
$table->string('purpose');
$table->integer('instance_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('renews_expires_at')->nullable();
$table->integer('due_at');
$table->string('amount');
$table->string('status');
$table->integer('created_at');
});
$now = time();
$expiry = $now + 3600;
Capsule::table('cloud_instances')->insert([
['id' => 1, 'user_id' => 1, 'status' => 'active'],
['id' => 2, 'user_id' => 2, 'status' => 'active'],
]);
Capsule::table('cloud_invoices')->insert([
'id' => 1,
'purpose' => 'renewal',
'instance_id' => 1,
'order_id' => null,
'user_id' => 1,
'renews_expires_at' => $expiry,
'due_at' => $expiry,
'amount' => '10.00',
'status' => 'paid',
'created_at' => $now - 100,
]);
Capsule::table('cloud_invoices')->insert([
'id' => 2,
'purpose' => 'renewal',
'instance_id' => 2,
'order_id' => null,
'user_id' => 2,
'renews_expires_at' => $expiry,
'due_at' => $expiry,
'amount' => '20.00',
'status' => 'open',
'created_at' => $now - 99,
]);
for ($number = 0; $number < 12; $number++) {
Capsule::table('cloud_invoices')->insert([
'purpose' => 'ip_change',
'instance_id' => null,
'order_id' => null,
'user_id' => 1,
'renews_expires_at' => null,
'due_at' => $now + $number,
'amount' => '1.00',
'status' => 'paid',
'created_at' => $now + $number,
]);
}
$all = CloudInvoicePageService::forUser(1, 1, 10);
$assert($all['purpose'] === 'all'
&& $all['pagination']['total'] === 13
&& count($all['invoices']) === 10
&& !in_array('1', array_column($all['invoices'], 'id'), true),
'Newest-first all-invoice pagination did not reproduce the hidden older renewal case.');
$renewals = CloudInvoicePageService::forUser(1, 1, 10, 'renewal');
$invoice = $renewals['invoices'][0] ?? [];
$assert($renewals['purpose'] === 'renewal'
&& $renewals['pagination']['total'] === 1
&& count($renewals['invoices']) === 1
&& ($invoice['id'] ?? null) === '1'
&& ($invoice['purpose'] ?? null) === 'renewal'
&& ($invoice['renews_expires_at'] ?? null) === $expiry
&& ($invoice['payment_deadline_at'] ?? null)
=== $expiry + CloudInvoiceService::PAYMENT_GRACE_SECONDS,
'The user renewal filter hid the owner invoice or returned the wrong fixed deadline.');
$assert(CloudInvoicePageService::normalizePurpose('invalid') === 'all'
&& CloudInvoicePageService::normalizePurpose(['renewal']) === 'all',
'Invoice purpose filtering accepted an unsupported or structured value.');
echo "User renewal invoice filtering, ownership and deadline checks passed.\n";

@ -185,6 +185,8 @@ namespace {
&& (string) $renewalMail->fresh()->status === 'sent'
&& (Mail::$messages[0]['template'] ?? null) === 'cloud/invoice.tpl'
&& (Mail::$messages[0]['emailType'] ?? null) === 'cloud_renewal_invoice'
&& (Mail::$messages[0]['data']['payment_deadline_at'] ?? null)
=== date('Y-m-d H:i:s', $now + 4 * 86400)
&& str_contains((string) (Mail::$messages[0]['subject'] ?? ''),
'实例续费账单已生成'),
'An open automatic renewal bill was not delivered and marked sent.');

@ -0,0 +1,82 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudInvoice;
use App\Services\Cloud\CloudInvoiceService;
use App\Services\Cloud\CloudProvisioningBillingConfig;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$System_Config = [];
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema('default')->create('configurations', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name')->unique();
$table->text('value')->nullable();
});
$assert(CloudProvisioningBillingConfig::paymentWindowMinutes() === 30,
'Missing provisioning payment-window configuration did not use 30 minutes.');
Capsule::table('configurations')->insert([
'name' => CloudProvisioningBillingConfig::PAYMENT_WINDOW_MINUTES_KEY,
'value' => '60',
]);
$assert(CloudProvisioningBillingConfig::paymentWindowSeconds() === 3600,
'One-hour provisioning payment-window configuration was not applied.');
Capsule::table('configurations')
->where('name', CloudProvisioningBillingConfig::PAYMENT_WINDOW_MINUTES_KEY)
->update(['value' => '1440']);
$assert(CloudProvisioningBillingConfig::paymentWindowSeconds() === 86400,
'One-day provisioning payment-window configuration was not applied.');
foreach (['0', '10081', '1.5', 'hour', ''] as $invalid) {
try {
CloudProvisioningBillingConfig::validatePaymentWindowMinutes($invalid);
throw new RuntimeException('Invalid provisioning payment window was accepted: ' . $invalid);
} catch (InvalidArgumentException $error) {
// Expected.
}
}
$renewal = new CloudInvoice();
$renewal->purpose = 'renewal';
$renewal->renews_expires_at = 1700000000;
$renewal->due_at = 1699999900;
$renewal->created_at = 1700003600;
$assert(CloudInvoiceService::paymentDeadline($renewal)
=== 1700000000 + CloudInvoiceService::PAYMENT_GRACE_SECONDS,
'Late renewal invoice creation extended the fixed instance deletion cutoff.');
$provision = new CloudInvoice();
$provision->purpose = 'provision';
$provision->due_at = 1700007200;
$provision->created_at = 1700000000;
$assert(CloudInvoiceService::paymentDeadline($provision) === 1700007200,
'Provision invoice ignored its configured absolute payment deadline.');
$root = dirname(__DIR__);
$invoiceService = file_get_contents($root . '/app/Services/Cloud/CloudInvoiceService.php');
$configController = file_get_contents($root . '/app/Controllers/Admin/ConfigController.php');
$configTemplate = file_get_contents($root . '/resources/views/venix/admin/config.tpl');
$assert(str_contains($invoiceService,
'CloudProvisioningBillingConfig::paymentWindowSeconds()')
&& str_contains($configController,
'CloudProvisioningBillingConfig::PAYMENT_WINDOW_MINUTES_KEY')
&& str_contains($configController,
'CloudProvisioningBillingConfig::validatePaymentWindowMinutes(')
&& str_contains($configTemplate,
'name="cloud_provision_invoice_payment_window_minutes"')
&& str_contains($configTemplate, '1440 表示 1 天'),
'Provisioning payment-window admin configuration is incomplete.');
echo "Cloud provisioning payment-window configuration checks passed.\n";

@ -77,7 +77,8 @@ $assert(str_contains($reset, '{$resetUrl|escape:"html"}')
$assert(str_contains($renewal, '#{$invoice_id|escape:"html"}')
&& str_contains($renewal, '&#36;{$amount|escape:"html"}')
&& str_contains($renewal, '{$invoice_url|escape:"html"}')
&& str_contains($renewal, '{$due_at|escape:"html"}'),
&& str_contains($renewal, '{$due_at|escape:"html"}')
&& str_contains($renewal, '{$payment_deadline_at|escape:"html"}'),
'Automatic renewal invoice email is missing public billing details.');
foreach (['instance_name', 'instance_id', 'region', 'public_ip', 'os_name',
'login_name', 'created_at', 'expires_at', 'instance_url'] as $field) {

@ -50,6 +50,7 @@ try {
'instance_name' => '<script>alert("renewal")</script>',
'amount' => '12.00',
'due_at' => '2026-10-05 18:00:00',
'payment_deadline_at' => '2026-10-08 18:00:00',
'invoice_url' => 'https://cloud.example.test/user/cloud/invoices/42?x=1&y=2',
]);
$provisioned = $render('cloud/provision-success.tpl', [
@ -130,7 +131,8 @@ try {
'Password-reset email did not render or escape its secure URL.');
$assert(str_contains($renewal, '续费账单已生成')
&& str_contains($renewal, '&lt;script&gt;')
&& str_contains($renewal, '#42'),
&& str_contains($renewal, '#42')
&& str_contains($renewal, '2026-10-08 18:00:00'),
'Renewal invoice email did not render its safe public details.');
$assert(str_contains($provisioned, '实例已开通')
&& str_contains($provisioned, '&lt;script&gt;')

@ -832,6 +832,16 @@ $assert(preg_match('/\.inventory-panel\.vm-service-panel\s*\{[^}]*min-height:\s*
&& str_contains($cloudTemplate,
'class="inventory-panel vm-service-panel"'),
'The service and traffic card must size to its content without the inventory minimum-height gap');
$assert(str_contains($detailTemplate, '>实例到期时间</dt>')
&& str_contains($detailTemplate, 'id="vm-detail-service-expiry"')
&& str_contains($detailTemplate, 'service_expiry_display')
&& !str_contains($detailTemplate, '>当前账期结束</dt>')
&& !str_contains($detailTemplate, 'id="vm-detail-period-end"')
&& str_contains($clientScript, 'const serviceExpiresAt =')
&& !str_contains($clientScript, 'const periodEndsAt =')
&& str_contains($clientScript,
"text('vm-detail-service-expiry', formatServiceDate(data.serviceExpiresAt))"),
'VM details must show only the latest instance expiry instead of the current service-period end.');
foreach (['expired_grace', 'blocked_expired', 'deleting', 'delete_failed',
'purge_pending', 'purge_stopping', 'purge_stop_failed', 'purge_deleting',
'purge_failed'] as $lifecycleStatus) {

Loading…
Cancel
Save