feat: provision instances through unified invoices

dev
admin 2 months ago
parent 4bb98a3de8
commit 2ef392ffa9

@ -164,8 +164,8 @@ location = /engine-console {
1. 管理员添加宿主机:现有 SSH/root/私钥口令、核验指纹,设置区域、网桥、目录、地址池/网关/DNS/网卡前缀,测试连接。
2. 导入云镜像与救援模板;无已有模板不能开通云镜像 VM。云镜像 SHA-256 可留空;留空时仍会在下载后计算并保存实际摘要,填写时则会严格比对。预存其他系统图标不代表已实现其云模板导入;其他系统可用合适 ISO 安装,云镜像适配后续扩展。
3. 套餐设置规格、每期价格、账期天数、每期流量额度、库存和已启用宿主机。实例到期前 7 天生成续费账单;用户可用余额支付,也可由启用的易支付、Paytaro 或 USDT 渠道直接生成支付订单。在线支付回调会自动结清对应账单;重复到账或超过 3 天宽限期的晚到款只保留在账户余额中,不能恢复已经进入删除流程的实例。
4. 测试用户注册/充值/购买/账单支付,验证提醒邮件、到期仅断网、宽限期内续费恢复网络,以及到期满 3 天后永久删除实例和系统盘;同时验收任务、VM 控制台、SSH、重装、救援、手动删除与图表。
3. 套餐设置规格、每期价格、账期天数、每期流量额度、库存和已启用宿主机。用户提交部署后先生成 30 分钟有效的开通账单,支付成功才创建实例;实例到期前 7 天再生成续费账单。两种账单均可用余额支付,也可由启用的易支付、Paytaro 或 USDT 渠道生成支付订单。在线支付回调会自动结清对应账单;失效账单的晚到款只保留在账户余额中,不会创建实例或恢复已进入删除流程的实例。
4. 测试用户注册/充值/生成开通账单/账单支付,确认未支付时没有引擎任务,支付后只创建一个实例;再验证提醒邮件、到期仅断网、宽限期内续费恢复网络,以及到期满 3 天后永久删除实例和系统盘;同时验收任务、VM 控制台、SSH、重装、救援、手动删除与图表。
5. 日志库 `engine_vm_metric_samples` 应在所有用户退出后继续新增,`engine_vm_traffic_totals` 应持续累加 RX/TX 字节;稳定 MAC 用于跨 QEMU/tap 重启衔接计数,首批数据需等待采样间隔。
6. 用测试小额度验收:下载与上传合计达额度后 VM 仍运行但所有网卡断开;下一已付费周期开始后当期用量归零且网卡自动恢复。无下一周期时,实例到期后 VM 保持原电源状态但网络立即停用;3 天宽限期内续费会恢复网络,超过宽限期则永久删除实例和面板管理的系统盘。

@ -38,10 +38,10 @@ PHP 不直接解密 Python 记录或执行任意 virsh 命令。主库与日志
## 购买状态机
1. 用户选择启用套餐、已有系统来源、公钥/强 root 密码,提交幂等键。
2. PHP 事务锁定用户钱包与套餐,校验余额、库存、宿主机与实例配额,保存不可由浏览器改写的规格快照,扣款并保存加密任务。
3. 独立 `cloudWorker` 获取租约,携带唯一 `operation_id` 请求引擎。只有经过签名的开通上下文可以创建 VM,用户不能免费创建。
4. 成功关联实例和凭据;确认创建失败且无残留时只退款、恢复库存一次。
5. 超时、引擎中断或残留无法确认时保持待核对,只查询原操作,不重复创建或盲目退款。
2. PHP 事务校验库存、宿主机与实例配额,保存不可由浏览器改写的规格快照和加密创建载荷,预留有限库存并生成开通账单;此时不扣钱、不创建引擎任务。
3. 余额或在线支付结清账单后,同一事务才扣减钱包并创建唯一队列任务。未支付开通账单 30 分钟后失效,释放库存并清除其加密凭据载荷;晚到的在线付款只保留为账户余额。
4. 独立 `cloudWorker` 获取租约,携带唯一 `operation_id` 请求引擎。只有已支付且经过签名的开通上下文可以创建 VM。
5. 成功关联实例和凭据;确认创建失败且无残留时只退款、恢复库存一次。超时、引擎中断或残留无法确认时保持待核对,只查询原操作,不重复创建或盲目退款。
金额通过精确小数与整数最小单位换算处理,不用浮点完成扣款比较。套餐带宽转换成 libvirt 网卡双向 KiB/s 限制。到期前 7 天幂等生成一张续费账单和可重试邮件任务;账单可由余额结清,也可绑定现有在线支付订单。网关回调先入账余额并在同一事务结清账单,净余额为零;账单已结清或失效时晚到款保留为余额,不能重复续期或丢失。每次结清账单都生成一个独立预付费周期,提前支付只排在已购周期末尾,不会提前刷新当期流量。每期额度为下载 RX + 上传 TX;用尽只持久断开网卡,VM 不关机;下一已付费周期开始时以新的累计基线归零当期用量并自动恢复网卡。

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

@ -71,10 +71,9 @@ final class CloudApiController
{
$actor = $this->actor($request);
if ($request->getMethod() === 'POST') {
$order = CloudOrderService::purchase(CloudInput::object($request), $actor);
$display = CloudOrderService::display($order);
return $this->json($response, ['order' => $display, 'job_id' => $display['job_id'],
'status_url' => '/api/v1/jobs/' . $display['job_id']], 202);
// Compatibility alias for a browser loaded before the unified
// billing release. It now creates only an unpaid invoice.
return $this->createProvisionInvoice($request, $response, $actor);
}
$query = CloudOrder::query();
if (!$actor['is_admin']) {
@ -115,18 +114,61 @@ final class CloudApiController
return $this->json($response, ['order' => CloudOrderService::display($order)]);
}
public function invoiceRequest($request, $response, $args)
{
$actor = $this->actor($request);
$key = (string) ($args['key'] ?? '');
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
throw new CloudError('账单请求标识无效');
}
$order = CloudOrder::where('user_id', $actor['user_id'])
->where('idempotency_key', $key)->first();
$invoice = $order === null ? null
: CloudInvoice::where('order_id', $order->id)->first();
if ($invoice === null || (string) ($invoice->purpose ?: 'renewal') !== 'provision') {
throw new CloudError('账单请求尚未建立', 404);
}
return $this->json($response,
['invoice' => CloudInvoiceService::display($invoice)]);
}
public function invoices($request, $response)
{
$actor = $this->actor($request);
if ($request->getMethod() === 'POST') {
return $this->createProvisionInvoice($request, $response, $actor);
}
$user = Auth::getUser();
$invoices = CloudInvoice::where('user_id', $actor['user_id'])
->orderByDesc('due_at')->orderByDesc('id')->limit(200)->get()
// The unified page must never hide a newly-created opening bill
// behind older invoices whose service due dates are farther in
// the future. Keep all actionable bills first, then newest audit
// history; pagination can extend the historical tail later.
->orderByRaw("CASE WHEN status IN ('open', 'overdue') THEN 0 ELSE 1 END")
->orderByDesc('created_at')->orderByDesc('id')->limit(200)->get()
->map(fn ($invoice) => CloudInvoiceService::display($invoice))->all();
return $this->json($response, ['invoices' => $invoices,
'payment_methods' => CloudInvoicePaymentService::methods($user),
'balance' => (string) $user->money]);
}
private function createProvisionInvoice($request, $response, array $actor)
{
$order = CloudOrderService::purchase(CloudInput::object($request), $actor);
$invoice = CloudInvoice::where('order_id', $order->id)->first();
if ($invoice === null) {
// An idempotency key from a pre-invoice deployment can still
// resolve to its historical order after an upgrade. Do not turn
// that expected compatibility case into an opaque HTTP 500.
if ((string) $order->status !== 'awaiting_payment') {
throw new CloudError('该请求已由旧版开通流程处理,请刷新实例列表或联系管理员核对', 409);
}
throw new \RuntimeException('开通账单创建失败');
}
return $this->json($response,
['invoice' => CloudInvoiceService::display($invoice)], 201);
}
public function invoice($request, $response, $args)
{
$actor = $this->actor($request);

@ -5,5 +5,5 @@ final class CloudOrder extends Model
protected $connection = 'default';
protected $table = 'cloud_orders';
protected $casts = ['amount' => 'decimal:2'];
protected $hidden = ['request_hash'];
protected $hidden = ['request_hash', 'payload_cipher'];
}

@ -4,6 +4,7 @@ namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\CloudInvoicePayment;
use App\Models\CloudInstance;
use App\Models\CloudOrder;
use App\Models\PaytaroOrder;
use App\Models\UsdtPaymentOrder;
use App\Models\User;
@ -19,6 +20,28 @@ use App\Services\UserFeatureRestrictionService;
final class CloudInvoicePaymentService
{
/**
* Recheck the account at the final, row-locked provider-order boundary.
*
* The controller performs the same validation for a useful early error,
* but an administrator can change account restrictions before the payment
* provider's transaction begins. Each provider calls this method after it
* locks the user row so a disabled account cannot still receive a real
* external payment order through that race window.
*/
public static function assertInvoicePaymentAllowed(User $user): void
{
if ((int) $user->enable !== 1) {
throw new CloudError('账户不存在或不可用', 403);
}
if (UserFeatureRestrictionService::isBalancePurchaseRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::PURCHASE_MESSAGE, 403);
}
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::RECHARGE_MESSAGE, 403);
}
}
public static function methods(User $user): array
{
if (UserFeatureRestrictionService::isRechargeRestricted($user)
@ -51,6 +74,33 @@ final class CloudInvoicePaymentService
}
$validated = (new CloudInstance())->getConnection()->transaction(
function () use ($invoice, $user) {
$lockedUser = User::where('id', $user->id)->lockForUpdate()->first();
if ($lockedUser === null || (int) $lockedUser->enable !== 1) {
return ['error' => '账户不存在或不可用', 'status' => 403];
}
if (UserFeatureRestrictionService::isBalancePurchaseRestricted($lockedUser)) {
return ['error' => UserFeatureRestrictionService::PURCHASE_MESSAGE,
'status' => 403];
}
if (UserFeatureRestrictionService::isRechargeRestricted($lockedUser)) {
return ['error' => UserFeatureRestrictionService::RECHARGE_MESSAGE,
'status' => 403];
}
if ((string) ($invoice->purpose ?: 'renewal') === 'provision') {
$current = CloudInvoice::where('id', $invoice->id)
->where('user_id', $user->id)->lockForUpdate()->first();
if ($current === null) {
return ['error' => '账单不存在', 'status' => 404];
}
$order = CloudOrder::where('id', $current->order_id)
->where('user_id', $user->id)->lockForUpdate()->first();
if (!in_array((string) $current->status, ['open', 'overdue'], true)
|| self::provisionUnavailable($current, $order)) {
return ['error' => '账单已失效,请重新提交开通请求',
'status' => 409];
}
return ['invoice' => $current];
}
// Lock in the same instance -> invoice order as lifecycle. If
// the three-day cutoff wins, no new provider order is opened;
// if payment validation wins, final settlement still rechecks
@ -168,6 +218,17 @@ final class CloudInvoicePaymentService
return self::display($payment);
}
private static function provisionUnavailable(CloudInvoice $invoice,
?CloudOrder $order): bool
{
return $order === null
|| (string) $order->status !== 'awaiting_payment'
|| CloudInvoiceService::paymentDeadlinePassed($invoice)
|| (int) $order->plan_id !== (int) $invoice->plan_id
|| CloudMoney::cents((string) $order->amount)
!== CloudMoney::cents((string) $invoice->amount);
}
private static function recoverCreatingAttempt(
CloudInvoicePayment $payment
): CloudInvoicePayment {
@ -219,12 +280,29 @@ final class CloudInvoicePaymentService
// Re-lock the billing state here so lifecycle cannot cross the grace
// cutoff between the controller's early validation and creation of a
// real provider order.
$instanceId = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->value('instance_id');
if ($instanceId === null) {
$source = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->first();
if ($source === null) {
throw new CloudError('账单不存在', 404);
}
$instance = CloudInstance::where('id', (int) $instanceId)
if ((string) ($source->purpose ?: 'renewal') === 'provision') {
$invoice = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->lockForUpdate()->first();
$order = $invoice === null ? null : CloudOrder::where('id', $invoice->order_id)
->where('user_id', $userId)->lockForUpdate()->first();
if ($invoice === null || !in_array((string) $invoice->status,
['open', 'overdue'], true)) {
throw new CloudError('账单已结清或不可支付', 409);
}
if (self::provisionUnavailable($invoice, $order)) {
throw new CloudError('账单已失效,请重新提交开通请求', 409);
}
self::saveAttempt($invoiceId, $provider, $orderNo, $idempotency,
$amount, $userId, $now);
return;
}
$instance = CloudInstance::where('id', (int) $source->instance_id)
->where('user_id', $userId)->lockForUpdate()->first();
$invoice = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)->lockForUpdate()->first();
@ -244,6 +322,14 @@ final class CloudInvoicePaymentService
!== (int) $invoice->traffic_quota_bytes) {
throw new CloudError('账单已失效,请刷新账单列表', 409);
}
self::saveAttempt($invoiceId, $provider, $orderNo, $idempotency,
$amount, $userId, $now);
}
private static function saveAttempt(int $invoiceId, string $provider,
string $orderNo, string $idempotency, string $amount, int $userId,
int $now): void
{
$payment = new CloudInvoicePayment();
$payment->invoice_id = $invoiceId;
$payment->user_id = $userId;

@ -5,7 +5,10 @@ use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudInvoicePayment;
use App\Models\CloudMailOutbox;
use App\Models\CloudOrder;
use App\Models\CloudRenewal;
use App\Models\CloudJob;
use App\Models\Shop;
use App\Models\User;
use App\Services\Config;
use App\Services\Mail;
@ -17,6 +20,9 @@ final class CloudInvoiceService
public static function paymentDeadline(CloudInvoice $invoice): int
{
if ((string) $invoice->purpose === 'provision') {
return (int) $invoice->due_at;
}
return max((int) $invoice->due_at, (int) $invoice->created_at)
+ self::PAYMENT_GRACE_SECONDS;
}
@ -35,6 +41,84 @@ final class CloudInvoiceService
'purge_failed'], true);
}
/** Create the initial bill for a validated, encrypted provisioning order. */
public static function issueProvision(CloudOrder $order, Shop $plan,
int $now): CloudInvoice
{
$existing = CloudInvoice::where('order_id', $order->id)->first();
if ($existing !== null) {
return $existing;
}
if ((string) $order->status !== 'awaiting_payment'
|| (int) $order->plan_id !== (int) $plan->id
|| !is_string($order->payload_cipher)
|| trim((string) $order->payload_cipher) === '') {
throw new CloudError('开通订单状态无效', 409);
}
$invoice = new CloudInvoice();
$invoice->invoice_no = self::invoiceNumber();
$invoice->purpose = 'provision';
$invoice->instance_id = null;
$invoice->order_id = $order->id;
$invoice->user_id = $order->user_id;
$invoice->plan_id = $order->plan_id;
$invoice->renewal_id = null;
$invoice->renews_expires_at = null;
$invoice->due_at = $now + CloudOrderService::PAYMENT_WINDOW_SECONDS;
$invoice->amount = $order->amount;
$invoice->validity_days = (int) $plan->validity_days;
$invoice->traffic_quota_bytes = max(0, (int) $plan->traffic_quota_bytes);
$invoice->status = 'open';
$invoice->paid_via = null;
$invoice->payment_reference = null;
$invoice->paid_at = null;
$invoice->created_at = $invoice->updated_at = $now;
$invoice->save();
return $invoice;
}
/** Expire abandoned initial bills and return their finite stock safely. */
public static function expireProvision(int $limit = 200): int
{
$now = time();
$ids = CloudInvoice::where('purpose', 'provision')
->whereIn('status', ['open', 'overdue'])
->where('due_at', '<=', $now)->orderBy('id')
->limit(max(1, min(1000, $limit)))->pluck('id')->all();
$expired = 0;
foreach ($ids as $id) {
$expired += (new User())->getConnection()->transaction(function () use ($id, $now) {
$ownerId = CloudInvoice::where('id', $id)->value('user_id');
if ($ownerId === null) {
return 0;
}
// Match payment settlement's user -> invoice -> order -> plan
// lock order so expiry and a callback cannot both win.
User::where('id', (int) $ownerId)->lockForUpdate()->first();
$invoice = CloudInvoice::where('id', $id)->lockForUpdate()->first();
if ($invoice === null || (string) $invoice->purpose !== 'provision'
|| !in_array((string) $invoice->status, ['open', 'overdue'], true)
|| (int) $invoice->due_at > $now) {
return 0;
}
$order = CloudOrder::where('id', $invoice->order_id)
->lockForUpdate()->first();
if ($order !== null && (string) $order->status === 'awaiting_payment') {
CloudOrderService::releaseStock($order);
$order->status = 'expired';
$order->payload_cipher = null;
$order->updated_at = $now;
$order->save();
}
$invoice->status = 'expired';
$invoice->updated_at = $now;
$invoice->save();
return 1;
}, 3);
}
return $expired;
}
public static function issueDue(int $limit = 200): int
{
$now = time();
@ -89,7 +173,9 @@ final class CloudInvoiceService
$amount = CloudMoney::decimal(CloudMoney::cents((string) $instance->renewal_price));
$invoice = new CloudInvoice();
$invoice->invoice_no = self::invoiceNumber();
$invoice->purpose = 'renewal';
$invoice->instance_id = $instance->id;
$invoice->order_id = null;
$invoice->user_id = $instance->user_id;
$invoice->plan_id = $instance->plan_id;
$invoice->renewal_id = null;
@ -223,31 +309,75 @@ final class CloudInvoiceService
public static function display(CloudInvoice $invoice): array
{
$now = time();
$instance = CloudInstance::find($invoice->instance_id);
$purpose = (string) ($invoice->purpose ?: 'renewal');
$instance = $invoice->instance_id === null
? null : CloudInstance::find($invoice->instance_id);
$order = $invoice->order_id === null
? null : CloudOrder::find($invoice->order_id);
$job = $order === null ? null
: CloudJob::where('order_id', $order->id)->first();
// Successful workers persist both links. Keep the invoice-side link
// as a defensive fallback for an interrupted upgrade or a repaired
// order row so the unified bill can still open the created instance.
$provisionInstanceId = $order?->instance_id ?? $invoice->instance_id;
$spec = $order === null ? []
: (json_decode((string) $order->spec_json, true) ?: []);
$status = (string) $invoice->status;
if ($instance === null || (string) $instance->status === 'deleted') {
if ($purpose === 'renewal'
&& ($instance === null || (string) $instance->status === 'deleted')) {
if (in_array($status, ['open', 'overdue'], true)) {
$status = 'void';
}
} elseif ($status === 'open' && (int) $invoice->due_at <= $now) {
$status = 'overdue';
}
$deletionAt = self::paymentDeadline($invoice);
$payable = in_array($status, ['open', 'overdue'], true)
&& $instance !== null
&& !self::instanceDeleting($instance)
&& $deletionAt > $now;
$deadline = self::paymentDeadline($invoice);
if ($purpose === 'provision') {
$payable = in_array($status, ['open', 'overdue'], true)
&& $order !== null
&& (string) $order->status === 'awaiting_payment'
&& $deadline > $now;
} else {
$payable = in_array($status, ['open', 'overdue'], true)
&& $instance !== null
&& !self::instanceDeleting($instance)
&& $deadline > $now;
}
return [
'id' => (string) $invoice->id,
'invoice_no' => (string) $invoice->invoice_no,
'instance_id' => (string) $invoice->instance_id,
'instance_name' => $instance?->name ?? '已删除实例',
'purpose' => $purpose,
'instance_id' => $purpose === 'provision'
? ($provisionInstanceId === null ? null : (string) $provisionInstanceId)
: ($invoice->instance_id === null ? null : (string) $invoice->instance_id),
'instance_name' => $purpose === 'provision'
? (string) ($spec['name'] ?? '待开通实例')
: ($instance?->name ?? '已删除实例'),
'requested_name' => $purpose === 'provision'
? (string) ($spec['name'] ?? '') : null,
'plan_name' => (string) ($spec['plan_name'] ?? ''),
'order_id' => $order === null ? null : (string) $order->id,
'order_status' => $order?->status,
'fulfillment_status' => $job?->status ?? $order?->status,
'job_id' => $job === null ? null : (string) $job->id,
'job_status' => $job?->status,
'error' => $job?->error_code,
'fulfillment' => $purpose === 'provision' ? [
'order_id' => $order === null ? null : (string) $order->id,
'order_status' => $order?->status,
'job_id' => $job === null ? null : (string) $job->id,
'job_status' => $job?->status,
'instance_id' => $provisionInstanceId === null
? null : (string) $provisionInstanceId,
'error' => $job?->error_code,
] : null,
'amount' => (string) $invoice->amount,
'validity_days' => (int) $invoice->validity_days,
'traffic_quota_bytes' => (int) $invoice->traffic_quota_bytes,
'status' => $status,
'due_at' => (int) $invoice->due_at,
'deletion_at' => $deletionAt,
'payment_deadline_at' => $deadline,
'deletion_at' => $purpose === 'renewal' ? $deadline : null,
'payable' => $payable,
'paid_at' => $invoice->paid_at === null ? null : (int) $invoice->paid_at,
'paid_via' => $invoice->paid_via,
@ -316,11 +446,20 @@ final class CloudInvoiceService
$source, $actor, $idempotency, $paidVia, $reference
) {
$user = User::where('id', (int) $actor['user_id'])->lockForUpdate()->first();
if ($user === null) {
throw new CloudError('账户不存在', 404);
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不存在或不可用', 403);
}
if ((int) $user->restrict_balance_purchase === 1) {
throw new CloudError('账户套餐购买服务已被管理员停用', 403);
}
$sourcePurpose = (string) ($source->purpose ?: 'renewal');
$instance = null;
if ($sourcePurpose !== 'provision') {
// Keep the established lifecycle lock order for renewals:
// user -> instance -> invoice.
$instance = CloudInstance::where('id', (int) $source->instance_id)
->lockForUpdate()->first();
}
$instanceId = (int) $source->instance_id;
$instance = CloudInstance::where('id', $instanceId)->lockForUpdate()->first();
$invoice = CloudInvoice::where('id', $source->id)->lockForUpdate()->first();
if ($invoice === null || (int) $invoice->user_id !== (int) $user->id) {
throw new CloudError('账单不存在', 404);
@ -328,6 +467,63 @@ final class CloudInvoiceService
if ((string) $invoice->status === 'paid') {
return ['outcome' => 'already_paid', 'invoice' => $invoice];
}
$purpose = (string) ($invoice->purpose ?: 'renewal');
if ($purpose !== $sourcePurpose) {
throw new CloudError('账单类型已变更,请刷新后重试', 409);
}
if ($purpose === 'provision') {
$order = CloudOrder::where('id', $invoice->order_id)
->where('user_id', $user->id)->lockForUpdate()->first();
if ($order === null
|| in_array((string) $invoice->status, ['expired', 'void'], true)
|| self::paymentDeadlinePassed($invoice)
|| (string) $order->status !== 'awaiting_payment') {
if ($order !== null && (string) $order->status === 'awaiting_payment') {
CloudOrderService::releaseStock($order);
$order->status = 'expired';
$order->payload_cipher = null;
$order->updated_at = time();
$order->save();
}
if (in_array((string) $invoice->status, ['open', 'overdue'], true)) {
$invoice->status = 'expired';
$invoice->updated_at = time();
$invoice->save();
}
return ['outcome' => 'stale', 'invoice' => $invoice];
}
if ((int) $order->plan_id !== (int) $invoice->plan_id
|| CloudMoney::cents((string) $order->amount)
!== CloudMoney::cents((string) $invoice->amount)) {
CloudOrderService::releaseStock($order);
$order->status = 'expired';
$order->payload_cipher = null;
$order->updated_at = time();
$order->save();
$invoice->status = 'void';
$invoice->updated_at = time();
$invoice->save();
return ['outcome' => 'stale', 'invoice' => $invoice];
}
$price = CloudMoney::cents((string) $invoice->amount);
$balance = CloudMoney::cents((string) $user->money);
if ($balance < $price) {
throw new CloudError('账户余额不足', 409);
}
CloudOrderService::queuePaidProvision($invoice, $order);
$user->money = CloudMoney::decimal($balance - $price);
$user->save();
$invoice->status = 'paid';
$invoice->paid_via = mb_substr($paidVia, 0, 32);
$invoice->payment_reference = $reference === ''
? null : mb_substr($reference, 0, 80);
$invoice->paid_at = time();
$invoice->updated_at = time();
$invoice->save();
return ['outcome' => 'paid', 'invoice' => $invoice,
'order' => $order->fresh() ?? $order];
}
if (($instance !== null && self::instanceDeleting($instance))
|| in_array((string) $invoice->status, ['expired'], true)
|| (in_array((string) $invoice->status, ['open', 'overdue'], true)

@ -11,6 +11,14 @@ final class CloudLifecycleService
public function tick(int $limit = 200): int
{
$batchSize = max(1, min(1000, $limit));
try {
CloudInvoiceService::expireProvision($batchSize);
} catch (\Throwable $error) {
// Releasing an abandoned provisioning reservation is database-only
// and must not stop instance expiry or traffic enforcement.
error_log('cloud provisioning invoice expiry unavailable: '
. get_class($error));
}
try {
CloudInvoiceService::issueDue($batchSize);
} catch (\Throwable $error) {

@ -2,6 +2,7 @@
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudInvoice;
use App\Models\CloudInstance;
use App\Models\CloudJob;
use App\Models\CloudOrder;
@ -10,6 +11,9 @@ use App\Models\User;
final class CloudOrderService
{
/** Unpaid provisioning invoices reserve finite stock for thirty minutes. */
public const PAYMENT_WINDOW_SECONDS = 1800;
public static function purchase(array $input, array $actor): CloudOrder
{
CloudInput::only($input, ['plan_id', 'source', 'template_id', 'iso_path', 'guest_ssh_key_id',
@ -54,7 +58,8 @@ final class CloudOrderService
}
$maximum = max(1, (int) \App\Services\Config::get('cloud_max_instances_per_user', 20));
$active = CloudInstance::where('user_id', $user->id)->where('status', '<>', 'deleted')->count();
$reserved = CloudOrder::where('user_id', $user->id)->whereIn('status', ['queued', 'running', 'uncertain'])->count();
$reserved = CloudOrder::where('user_id', $user->id)->whereIn('status',
['awaiting_payment', 'queued', 'running', 'uncertain'])->count();
if ($active + $reserved >= $maximum) {
throw new CloudError('已达到账户虚拟机数量上限', 409);
}
@ -67,10 +72,6 @@ final class CloudOrderService
throw new CloudError('套餐对应宿主机暂不可用', 409);
}
$price = CloudMoney::cents($plan->price);
$balance = CloudMoney::cents((string) $user->money);
if ($balance < $price) {
throw new CloudError('账户余额不足', 409);
}
$payload = ['source' => $source, 'name' => $name, 'vcpu' => (int) $plan->cpu_cores,
'memory_mib' => (int) $plan->memory_mib, 'disk_gib' => (int) $plan->disk_gib,
'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'network' => $host->default_network];
@ -97,38 +98,101 @@ final class CloudOrderService
$order->idempotency_key = $idempotency;
$order->request_hash = $requestHash;
$order->amount = CloudMoney::decimal($price);
$order->status = 'queued';
$order->status = 'awaiting_payment';
$order->spec_json = json_encode($safeSpec, JSON_THROW_ON_ERROR);
$order->payload_cipher = CloudSecrets::encrypt(['method' => 'POST',
'resource' => 'vms', 'body' => $payload, 'credential' => $credential]);
$order->created_at = $order->updated_at = time();
$order->save();
$job = new CloudJob();
$job->operation_id = bin2hex(random_bytes(16));
$job->order_id = $order->id;
$job->user_id = $user->id;
$job->host_id = $host->id;
$job->kind = 'create';
$job->status = 'queued';
$job->payload_cipher = CloudSecrets::encrypt(['method' => 'POST', 'resource' => 'vms',
'body' => $payload, 'credential' => $credential]);
$job->available_at = $job->created_at = $job->updated_at = time();
$job->save();
$user->money = CloudMoney::decimal($balance - $price);
$user->save();
if ((int) $plan->stock > 0) {
$plan->stock--;
$plan->save();
$order->stock_reserved_at = time();
}
$order->save();
CloudInvoiceService::issueProvision($order, $plan, time());
return $order;
}, 3);
}
/**
* Transfer a paid provisioning invoice into the worker queue.
*
* The caller owns the surrounding wallet transaction and has locked the
* user, invoice and order rows in that order. The unique job order key is
* the final database guard against duplicate payment callbacks.
*/
public static function queuePaidProvision(CloudInvoice $invoice,
CloudOrder $order): CloudOrder
{
if ((string) $invoice->purpose !== 'provision'
|| (int) $invoice->order_id !== (int) $order->id
|| (int) $invoice->user_id !== (int) $order->user_id
|| (int) $invoice->plan_id !== (int) $order->plan_id
|| CloudMoney::cents((string) $invoice->amount)
!== CloudMoney::cents((string) $order->amount)) {
throw new CloudError('开通账单与订单快照不匹配', 409);
}
if (in_array((string) $order->status,
['queued', 'running', 'uncertain', 'succeeded'], true)) {
if (!CloudJob::where('order_id', $order->id)->exists()) {
throw new CloudError('开通订单缺少任务记录,请联系管理员', 409);
}
return $order;
}
if ((string) $order->status !== 'awaiting_payment'
|| !is_string($order->payload_cipher)
|| trim((string) $order->payload_cipher) === '') {
throw new CloudError('开通订单已失效或不可支付', 409);
}
$payload = CloudSecrets::decrypt((string) $order->payload_cipher);
if (($payload['method'] ?? null) !== 'POST'
|| ($payload['resource'] ?? null) !== 'vms'
|| !is_array($payload['body'] ?? null)) {
throw new CloudError('开通订单的加密请求无效', 409);
}
$job = new CloudJob();
$job->operation_id = bin2hex(random_bytes(16));
$job->order_id = $order->id;
$job->user_id = $order->user_id;
$job->host_id = $order->host_id;
$job->kind = 'create';
$job->status = 'queued';
$job->payload_cipher = $order->payload_cipher;
$job->available_at = $job->created_at = $job->updated_at = time();
$job->save();
// The worker now owns the sole recoverable credential copy.
$order->payload_cipher = null;
$order->status = 'queued';
$order->updated_at = time();
$order->save();
return $order;
}
/** Release a finite plan reservation exactly once. */
public static function releaseStock(CloudOrder $order): void
{
if ($order->stock_reserved_at === null || $order->stock_released_at !== null) {
return;
}
$plan = Shop::where('id', $order->plan_id)->lockForUpdate()->first();
if ($plan !== null && (int) $plan->stock >= 0) {
$plan->stock = (int) $plan->stock + 1;
$plan->save();
}
$order->stock_released_at = time();
$order->updated_at = time();
$order->save();
}
public static function display(CloudOrder $order): array
{
$job = CloudJob::where('order_id', $order->id)->first();
$invoice = CloudInvoice::where('order_id', $order->id)->first();
return ['id' => (string) $order->id, 'user_id' => (int) $order->user_id, 'status' => $order->status, 'amount' => (string) $order->amount,
'plan_id' => (int) $order->plan_id, 'host_id' => (int) $order->host_id,
'instance_id' => $order->instance_id === null ? null : (string) $order->instance_id,
'created_at' => (int) $order->created_at, 'updated_at' => (int) ($job?->updated_at ?? $order->updated_at),
'invoice_id' => $invoice === null ? null : (string) $invoice->id,
'job_id' => $job === null ? '' : (string) $job->id,
'job_status' => $job?->status, 'attempts' => (int) ($job?->attempts ?? 0),
'error' => $job?->error_code];

@ -2,6 +2,7 @@
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudServicePeriod;
@ -370,7 +371,12 @@ final class CloudWorkerService
$instance->traffic_synced_at = 0;
$instance->spec_json = $order->spec_json;
$instance->credential_cipher = isset($payload['credential']) ? CloudSecrets::encrypt($payload['credential']) : null;
$instance->created_at = $order->created_at;
// The paid service begins when provisioning actually succeeds,
// not while an opening invoice is waiting for payment. A
// reconciled/replayed success must retain the original value.
if (!$instance->exists) {
$instance->created_at = $now;
}
$instance->updated_at = time();
$instance->save();
if ($billingSnapshot) {
@ -396,6 +402,14 @@ final class CloudWorkerService
$instance->save();
}
$job->instance_id = $order->instance_id = $instance->id;
$provisionInvoice = CloudInvoice::where('order_id', $order->id)
->lockForUpdate()->first();
if ($provisionInvoice !== null
&& (string) $provisionInvoice->purpose === 'provision') {
$provisionInvoice->instance_id = $instance->id;
$provisionInvoice->updated_at = time();
$provisionInvoice->save();
}
$safe = $safe ?? [];
$safe['id'] = (string) $instance->id;
$safe['uuid'] = $uuid;
@ -405,10 +419,21 @@ final class CloudWorkerService
}
$user->money = CloudMoney::decimal(CloudMoney::cents((string) $user->money) + CloudMoney::cents($order->amount));
$user->save();
$plan = Shop::where('id', $order->plan_id)->lockForUpdate()->first();
if ($plan !== null && (int) $plan->stock >= 0) {
$plan->stock++;
$plan->save();
$invoice = CloudInvoice::where('order_id', $order->id)
->lockForUpdate()->first();
if ($invoice !== null && (string) $invoice->purpose === 'provision') {
CloudOrderService::releaseStock($order);
$invoice->status = 'refunded';
$invoice->updated_at = time();
$invoice->save();
} else {
// Compatibility for an in-flight order created before
// provisioning invoices existed.
$plan = Shop::where('id', $order->plan_id)->lockForUpdate()->first();
if ($plan !== null && (int) $plan->stock >= 0) {
$plan->stock++;
$plan->save();
}
}
$order->refunded_at = time();
} elseif ($status === 'failed' && $job->kind === 'expiry_delete'

@ -29,9 +29,13 @@ class PaytaroPaymentService
$connection->transaction(function () use (
$user, $amount, $orderNo, $now, $businessContext
) {
if (User::where('id', (int) $user->id)->lockForUpdate()->first() === null) {
$lockedUser = User::where('id', (int) $user->id)->lockForUpdate()->first();
if ($lockedUser === null) {
throw new \RuntimeException('支付账户不存在');
}
if ($businessContext !== []) {
CloudInvoicePaymentService::assertInvoicePaymentAllowed($lockedUser);
}
$paylist = new Paylist();
$paylist->userid = (int) $user->id;
$paylist->total = $amount;

@ -65,9 +65,13 @@ class UsdtPaymentService
$connection->transaction(function () use (
$businessOrderNo, $userId, $amount, $settings, $businessContext, $now, &$result
) {
if (User::where('id', (int) $userId)->lockForUpdate()->first() === null) {
$lockedUser = User::where('id', (int) $userId)->lockForUpdate()->first();
if ($lockedUser === null) {
throw new \RuntimeException('支付账户不存在');
}
if ($businessContext !== []) {
CloudInvoicePaymentService::assertInvoicePaymentAllowed($lockedUser);
}
$existing = UsdtPaymentOrder::where('business_type', 'recharge')
->where('business_order_no', $businessOrderNo)
->lockForUpdate()

@ -32,9 +32,13 @@ class YipayPaymentService
$connection->transaction(function () use (
$user, $amount, $method, $orderNo, $now, $businessContext
) {
if (User::where('id', (int) $user->id)->lockForUpdate()->first() === null) {
$lockedUser = User::where('id', (int) $user->id)->lockForUpdate()->first();
if ($lockedUser === null) {
throw new \RuntimeException('支付账户不存在');
}
if ($businessContext !== []) {
CloudInvoicePaymentService::assertInvoicePaymentAllowed($lockedUser);
}
$paylist = new Paylist();
$paylist->userid = (int) $user->id;
$paylist->total = $amount;

@ -53,7 +53,8 @@ class UserDataDeletionService
}
if ($connection->getSchemaBuilder()->hasTable('cloud_orders')
&& $connection->table('cloud_orders')->whereIn('user_id', $ids)
->whereIn('status', ['pending', 'queued', 'running', 'provisioning', 'uncertain'])->exists()) {
->whereIn('status', ['awaiting_payment', 'pending', 'queued',
'running', 'provisioning', 'uncertain'])->exists()) {
throw new \RuntimeException('用户仍有开通中的订单,请先处理订单后再删除账户');
}
foreach ([

@ -8,7 +8,9 @@ $app->group('/api/v1', function () {
$this->get('/orders/by-request/{key:[A-Za-z0-9_.-]+}',
'App\Controllers\CloudApiController:orderRequest');
$this->get('/orders/{id:[0-9]+}', 'App\Controllers\CloudApiController:order');
$this->get('/invoices', 'App\Controllers\CloudApiController:invoices');
$this->map(['GET', 'POST'], '/invoices', 'App\Controllers\CloudApiController:invoices');
$this->get('/invoices/by-request/{key:[A-Za-z0-9_.-]+}',
'App\Controllers\CloudApiController:invoiceRequest');
$this->get('/invoices/{id:[0-9]+}', 'App\Controllers\CloudApiController:invoice');
$this->post('/invoices/{id:[0-9]+}/pay-balance', 'App\Controllers\CloudApiController:payInvoice');
$this->post('/invoices/{id:[0-9]+}/payments', 'App\Controllers\CloudApiController:createInvoicePayment');

@ -17,7 +17,7 @@ async function api(path, options = {}) {
function formList(value) { return String(value || '').split(/[\s,]+/).filter(Boolean); }
function profile(host) { return { ...host, ...(host.profile || host.config || {}) }; }
function orderStatus(value) {
return ({ queued: '等待开通', running: '开通中', succeeded: '已开通', failed: '已失败', uncertain: '待核对' })[value] || value || '—';
return ({ awaiting_payment: '等待账单支付', expired: '账单已失效', queued: '等待创建', running: '创建中', succeeded: '已开通', failed: '已失败', uncertain: '待核对' })[value] || value || '—';
}
function unixTime(value) {
const seconds = Number(value);

@ -1,11 +1,13 @@
// PHP owns authentication, authorisation, ownership and purchasing. No engine
// address, token, host credential or unrestricted create API exists in this UI.
const byId = (id) => document.getElementById(id);
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, invoices: [], invoicePaymentMethods: [], invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, orderPoll: null, mutationBusy: false, orderIdempotency: '', orderFingerprint: '', rescueActive: false, rescueStaged: false };
const ORDER_STORAGE_PREFIX = 'virt-cloud:pending-order:';
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, invoices: [], invoicePaymentMethods: [], invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false };
// Keep the historical storage key so an interrupted deployment made just
// before an online update can still reconcile to the same opening invoice.
const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:';
const INVOICE_PAYMENT_STORAGE_PREFIX = 'virt-cloud:invoice-payment:';
const text = (id, value) => { byId(id).textContent = value ?? '—'; };
const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.orders) ? payload.orders : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : [];
const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : [];
function showError(id, message) { text(id, message); byId(id).hidden = !message; }
let toastTimer;
function toast(message, kind = '') { const element = byId('toast'); element.textContent = message; element.className = `toast ${kind}`; element.hidden = false; clearTimeout(toastTimer); toastTimer = setTimeout(() => { element.hidden = true; }, 5000); }
@ -146,8 +148,8 @@ function setVmDetailTab(tab, focus = false) {
function showView(view) {
clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); state.view = view;
if (view !== 'invoices' && state.invoicePollTimers.size) stopInvoicePoll();
byId('vm-workspace').hidden = ['keys', 'orders', 'invoices'].includes(view);
byId('ssh-keys-workspace').hidden = view !== 'keys'; byId('orders-workspace').hidden = view !== 'orders'; byId('invoices-workspace').hidden = view !== 'invoices';
byId('vm-workspace').hidden = ['keys', 'invoices'].includes(view);
byId('ssh-keys-workspace').hidden = view !== 'keys'; byId('invoices-workspace').hidden = view !== 'invoices';
const sections = { list: 'vm-list-view', detail: 'vm-detail-view', create: 'create-view', reinstall: 'reinstall-view', rescue: 'rescue-view' };
for (const [name, id] of Object.entries(sections)) byId(id).hidden = view !== name;
const navigationView = ['detail', 'reinstall', 'rescue'].includes(view) ? 'list' : view;
@ -157,13 +159,13 @@ function showView(view) {
if (active) button.setAttribute('aria-current', 'page');
else button.removeAttribute('aria-current');
});
text('breadcrumb-current', ({ list: '实例管理', detail: '虚拟机详情', create: '部署实例', reinstall: '重装系统', rescue: '紧急救援', keys: 'SSH 公钥', orders: '开通订单', invoices: '续费账单' })[view]);
const hash = ({ list: '', create: 'plans', keys: 'keys', orders: 'orders', invoices: 'invoices' })[view] ?? (selectedVm() ? `vm=${encodeURIComponent(selectedVm().api_id)}` : '');
text('breadcrumb-current', ({ list: '实例管理', detail: '虚拟机详情', create: '部署实例', reinstall: '重装系统', rescue: '紧急救援', keys: 'SSH 公钥', invoices: '账单信息' })[view]);
const hash = ({ list: '', create: 'plans', keys: 'keys', invoices: 'invoices' })[view] ?? (selectedVm() ? `vm=${encodeURIComponent(selectedVm().api_id)}` : '');
history.replaceState(null, '', `${location.pathname}${location.search}${hash ? '#' + hash : ''}`);
window.scrollTo({ top: 0, behavior: 'auto' });
if (view === 'detail') setVmDetailTab(state.detailTab);
}
async function routeHash(hash = location.hash) { const target = hash.replace(/^#/, ''); try { if (target === 'plans') await openCreate(); else if (target === 'keys') { showView('keys'); await loadKeys(); } else if (target === 'orders') { showView('orders'); await loadOrders(); } else if (target === 'invoices') { showView('invoices'); await loadInvoices(); } else if (target.startsWith('vm=')) { const id = decodeURIComponent(target.slice(3)); const vm = state.vms.find(item => item.api_id === id); if (vm) openVmDetail(vm.uuid); else showView('list'); } else showView('list'); } catch (error) { showError('cloud-page-error', error.message); } }
async function routeHash(hash = location.hash) { const target = hash.replace(/^#/, ''); try { if (target === 'plans') await openCreate(); else if (target === 'keys') { showView('keys'); await loadKeys(); } else if (target === 'orders' || target === 'invoices') { showView('invoices'); await loadInvoices(); } else if (target.startsWith('vm=')) { const id = decodeURIComponent(target.slice(3)); const vm = state.vms.find(item => item.api_id === id); if (vm) openVmDetail(vm.uuid); else showView('list'); } else showView('list'); } catch (error) { showError('cloud-page-error', error.message); } }
async function loadVms() {
if (state.loadingVMs) return;
state.loadingVMs = true;
@ -271,28 +273,28 @@ async function loadPlanResources() {
try { const resources = await api(`/api/v1/resources?plan_id=${encodeURIComponent(planId)}`, { signal: state.resourceController.signal }); if (epoch !== state.formEpoch) return; state.resources = resources; state.templates = items(resources.templates || resources.cloud_templates); renderTemplateCatalog('vm-template'); const isos = items(resources.isos || resources.iso_images); const select = byId('vm-iso'); select.replaceChildren(makeElement('option', '', isos.length ? '选择安装镜像' : '没有可用 ISO')); select.firstElementChild.value = ''; for (const iso of isos) { const path = typeof iso === 'string' ? iso : iso.path || iso.name; if (!path) continue; const option = makeElement('option', '', typeof iso === 'string' ? iso.split('/').pop() : iso.name || iso.path.split('/').pop()); option.value = path; select.append(option); } byId('create-submit').disabled = false; }
catch (error) { if (epoch === state.formEpoch && error.name !== 'AbortError') showError('create-error', error.message); }
}
function orderStorageKey() { return `${ORDER_STORAGE_PREFIX}${state.userId || 'unknown'}`; }
async function purchaseFingerprint(body) {
if (!globalThis.crypto?.subtle) throw new Error('当前浏览器不支持安全订单核对,请更新浏览器。');
function provisionInvoiceStorageKey() { return `${PROVISION_INVOICE_STORAGE_PREFIX}${state.userId || 'unknown'}`; }
async function provisionInvoiceFingerprint(body) {
if (!globalThis.crypto?.subtle) throw new Error('当前浏览器不支持安全账单核对,请更新浏览器。');
const canonical = {}; for (const key of Object.keys(body).sort()) canonical[key] = body[key];
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(canonical)));
return Array.from(new Uint8Array(digest), value => value.toString(16).padStart(2, '0')).join('');
}
async function pendingOrderKey(fingerprint) {
if (state.orderIdempotency && state.orderFingerprint === fingerprint) return state.orderIdempotency;
async function pendingProvisionInvoiceKey(fingerprint) {
if (state.provisionIdempotency && state.provisionFingerprint === fingerprint) return state.provisionIdempotency;
let saved = null;
try { saved = JSON.parse(sessionStorage.getItem(orderStorageKey()) || 'null'); } catch {}
try { saved = JSON.parse(sessionStorage.getItem(provisionInvoiceStorageKey()) || 'null'); } catch {}
let key = saved && saved.fingerprint === fingerprint ? String(saved.key || '') : '';
if (!/^[A-Za-z0-9_.-]{16,128}$/.test(key)) key = crypto.randomUUID();
state.orderIdempotency = key;
state.orderFingerprint = fingerprint;
try { sessionStorage.setItem(orderStorageKey(), JSON.stringify({ key, fingerprint })); } catch {}
state.provisionIdempotency = key;
state.provisionFingerprint = fingerprint;
try { sessionStorage.setItem(provisionInvoiceStorageKey(), JSON.stringify({ key, fingerprint })); } catch {}
return key;
}
function clearPendingOrderKey() {
state.orderIdempotency = '';
state.orderFingerprint = '';
try { sessionStorage.removeItem(orderStorageKey()); } catch {}
function clearPendingProvisionInvoiceKey() {
state.provisionIdempotency = '';
state.provisionFingerprint = '';
try { sessionStorage.removeItem(provisionInvoiceStorageKey()); } catch {}
}
function invoicePaymentStorageKey(invoiceId, methodId) {
return `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:${methodId}`;
@ -319,8 +321,8 @@ function clearInvoicePaymentKeys(invoiceId) {
keys.forEach(key => sessionStorage.removeItem(key));
} catch {}
}
async function existingPendingOrder(key) {
try { return await api(`/api/v1/orders/by-request/${encodeURIComponent(key)}`); }
async function existingProvisionInvoice(key) {
try { return await api(`/api/v1/invoices/by-request/${encodeURIComponent(key)}`); }
catch (error) { if (error.status === 404) return null; throw error; }
}
async function buy(event) {
@ -330,74 +332,75 @@ async function buy(event) {
if (cloud && !byId('vm-template').value) return showError('create-error', '请选择系统镜像版本。');
if (!byId('vm-plan').value || !state.resources) return showError('create-error', '请先选择可用套餐。');
const selectedPlan = state.plans.find(plan => String(plan.id) === byId('vm-plan').value);
const purchaseSummary = selectedPlan ? `每期 ¥${selectedPlan.price},${planBillingLabel(selectedPlan)}` : '所选套餐';
if (!confirm(`确认从账户余额支付并开通虚拟机?${purchaseSummary}。到期前 7 天会自动生成续费账单。`)) return;
const purchaseSummary = selectedPlan ? `¥${selectedPlan.price},${planBillingLabel(selectedPlan)}` : '所选套餐';
if (!confirm(`确认为该实例生成开通账单?账单金额 ${purchaseSummary}。支付完成后才会开始创建实例。`)) return;
state.mutationBusy = true; byId('create-submit').disabled = true; showError('create-error', '');
const body = { plan_id: Number(byId('vm-plan').value), name: byId('vm-name').value.trim(), source: sourceMode() };
if (cloud) { body.template_id = byId('vm-template').value; if (state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; if (password) body.root_password = password; } else body.iso_path = byId('vm-iso').value;
try {
const fingerprint = await purchaseFingerprint(body);
const orderIdempotency = await pendingOrderKey(fingerprint);
body.idempotency_key = orderIdempotency;
const recovered = await existingPendingOrder(orderIdempotency);
if (!recovered) await api('/api/v1/orders', { method: 'POST', body });
clearPendingOrderKey(); byId('vm-root-password').value = '';
toast(recovered ? '已找回之前提交的订单,没有重复扣款。' : '订单已提交,后台持续开通中。', 'success');
showView('orders'); await loadOrders();
const fingerprint = await provisionInvoiceFingerprint(body);
const invoiceIdempotency = await pendingProvisionInvoiceKey(fingerprint);
body.idempotency_key = invoiceIdempotency;
const recovered = await existingProvisionInvoice(invoiceIdempotency);
if (!recovered) await api('/api/v1/invoices', { method: 'POST', body });
clearPendingProvisionInvoiceKey(); byId('vm-root-password').value = '';
toast(recovered ? '已找回之前生成的开通账单,没有重复创建。' : '开通账单已生成,请完成支付。', 'success');
showView('invoices'); await loadInvoices();
}
catch (error) {
// A timeout or 409 can mean the first request committed but its response
// was lost. Reconcile by the same durable key before reporting failure.
try {
const orderIdempotency = state.orderIdempotency;
const recovered = orderIdempotency ? await existingPendingOrder(orderIdempotency) : null;
const invoiceIdempotency = state.provisionIdempotency;
const recovered = invoiceIdempotency ? await existingProvisionInvoice(invoiceIdempotency) : null;
if (recovered) {
clearPendingOrderKey(); byId('vm-root-password').value = '';
toast('已核对到订单,没有重复扣款。', 'success'); showView('orders'); await loadOrders(); return;
clearPendingProvisionInvoiceKey(); byId('vm-root-password').value = '';
toast('已核对到开通账单,没有重复创建。', 'success'); showView('invoices'); await loadInvoices(); return;
}
} catch {}
showError('create-error', `${error.message} 可再次点击提交安全核对同一订单。`);
showError('create-error', `${error.message} 可再次点击提交安全核对同一张账单。`);
}
finally { delete body.root_password; state.mutationBusy = false; byId('create-submit').disabled = !state.resources; }
}
function formatOrderDate(value) { const date = new Date(typeof value === 'number' ? value * 1000 : value); return Number.isFinite(date.getTime()) ? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录'; }
async function loadOrders() {
try {
const orders = items(await api('/api/v1/orders'));
const container = byId('orders-list');
container.replaceChildren();
if (!orders.length) return container.append(makeElement('p', 'muted', '暂无订单。'));
const labels = { queued: '等待开通', pending: '等待开通', provisioning: '开通中', running: '开通中', completed: '已开通', succeeded: '已开通', active: '已开通', failed: '失败', refunded: '已退款', needs_attention: '需要管理员核查', uncertain: '需要管理员核查' };
for (const order of orders) {
const row = makeElement('div', 'cloud-order');
const detail = makeElement('div', 'cloud-order-detail');
detail.append(makeElement('strong', '', order.name || order.plan_name || `订单 #${order.id} · 套餐 #${order.plan_id ?? '—'}`), makeElement('p', 'muted', `¥${order.price ?? order.amount ?? '—'} · ${formatOrderDate(order.created_at)}`));
if (order.error || order.message || order.phase) detail.append(makeElement('p', 'cloud-order-message', order.error || order.message || order.phase));
const completed = ['completed', 'succeeded', 'active'].includes(order.status);
const failed = ['failed', 'refunded'].includes(order.status);
const stateClass = completed ? 'running' : failed ? 'failed' : 'other';
const actions = makeElement('div', 'cloud-order-actions');
actions.append(makeElement('span', `state-pill ${stateClass}`, labels[order.status] || order.status));
if (order.job_id) actions.append(actionButton('查看任务进度', async () => {
let progress = detail.querySelector('.cloud-order-progress');
if (!progress) { progress = makeElement('p', 'cloud-order-progress muted'); detail.append(progress); }
try { const job = await api(`/api/v1/jobs/${encodeURIComponent(order.job_id)}`); progress.className = `cloud-order-progress ${job.error ? 'form-error' : 'muted'}`; progress.textContent = job.error || job.phase || `任务状态:${job.status}`; }
catch (error) { toast(error.message, 'error'); }
}));
if (order.vm_id || order.instance_id || order.vm_uuid) actions.append(actionButton('查看虚拟机', async () => {
await loadVms();
const vm = state.vms.find(item => item.api_id === String(order.vm_id || order.instance_id) || item.uuid === order.vm_uuid);
if (vm) openVmDetail(vm.uuid); else toast('虚拟机尚未出现在列表,请稍后刷新。');
}));
row.append(detail, actions);
container.append(row);
}
} catch (error) { showError('cloud-page-error', error.message); }
function invoicePurpose(invoice) {
const value = firstText(invoice?.purpose, invoice?.kind, invoice?.invoice_type, invoice?.type).toLowerCase();
return ['provision', 'provisioning', 'initial', 'create'].includes(value) ? 'provision' : 'renewal';
}
function provisionInvoiceData(invoice) {
const fulfillment = invoice?.fulfillment && typeof invoice.fulfillment === 'object' ? invoice.fulfillment : {};
return {
orderId: firstText(fulfillment.order_id, invoice?.order_id),
status: firstText(fulfillment.status, fulfillment.fulfillment_status, invoice?.fulfillment_status,
fulfillment.order_status, invoice?.order_status, fulfillment.job_status, invoice?.job_status).toLowerCase(),
jobId: firstText(fulfillment.job_id, invoice?.job_id),
jobStatus: firstText(fulfillment.job_status, invoice?.job_status).toLowerCase(),
instanceId: firstText(fulfillment.instance_id, invoice?.instance_id),
instanceUuid: firstText(fulfillment.instance_uuid, fulfillment.vm_uuid, invoice?.instance_uuid, invoice?.vm_uuid),
phase: firstText(fulfillment.phase, invoice?.phase),
error: firstText(fulfillment.error, invoice?.error),
};
}
function provisionStatusInfo(invoice) {
const data = provisionInvoiceData(invoice);
const status = data.status || data.jobStatus;
const values = {
awaiting_payment: ['等待支付', 'warning'], payment_pending: ['等待支付', 'warning'], draft: ['等待支付', 'warning'],
queued: ['等待创建', 'warning'], pending: ['等待创建', 'warning'], provisioning: ['创建中', 'warning'], running: ['创建中', 'warning'],
completed: ['已开通', 'running'], succeeded: ['已开通', 'running'], active: ['已开通', 'running'],
failed: ['创建失败', 'failed'], refunded: ['开通失败,已退款', 'failed'],
needs_attention: ['需要管理员核查', 'failed'], uncertain: ['需要管理员核查', 'failed'],
};
return { data, status, display: values[status] || [status || '等待支付', 'warning'] };
}
function provisionFinished(invoice) {
const { status } = provisionStatusInfo(invoice);
return ['completed', 'succeeded', 'active', 'failed', 'refunded', 'needs_attention', 'uncertain'].includes(status);
}
function invoiceStatusInfo(status) {
const values = {
open: ['待支付', 'warning'], overdue: ['已逾期', 'failed'],
paid: ['已支付', 'running'], void: ['已失效', 'other'], expired: ['宽限期已结束', 'failed'],
paid: ['已支付', 'running'], refunded: ['已退款', 'other'], void: ['已失效', 'other'], expired: ['已失效', 'failed'],
deleting: ['实例删除中', 'failed'], delete_failed: ['自动删除失败', 'failed'],
purge_pending: ['等待永久删除', 'failed'], purge_stopping: ['删除前正在关机', 'failed'],
purge_deleting: ['实例删除中', 'failed'], purge_stop_failed: ['删除前关机失败', 'failed'], purge_failed: ['自动删除失败', 'failed'],
@ -407,12 +410,16 @@ function invoiceStatusInfo(status) {
function invoiceDeletionTimestamp(invoice) {
return serviceTimestamp(invoice?.deletion_at ?? invoice?.delete_at ?? invoice?.grace_ends_at ?? null);
}
function invoicePaymentDeadlineTimestamp(invoice) {
return serviceTimestamp(invoice?.payment_deadline_at ?? invoice?.payable_until ?? invoice?.payment_due_at ?? null);
}
function invoiceCanPay(invoice) {
if (!['open', 'overdue'].includes(String(invoice?.status || '').toLowerCase())) return false;
if (invoice?.payable === false) return false;
if (invoice?.payable === true) return true;
const deletionAt = invoiceDeletionTimestamp(invoice);
return deletionAt === null || Date.now() < deletionAt;
const deadline = invoicePurpose(invoice) === 'provision'
? invoicePaymentDeadlineTimestamp(invoice) : invoiceDeletionTimestamp(invoice);
return deadline === null || Date.now() < deadline;
}
function validPaymentUrl(value) {
try {
@ -454,14 +461,32 @@ function scheduleInvoicePoll(invoiceId) {
if (state.view !== 'invoices') return stopInvoicePoll(key);
try {
const result = await api(`/api/v1/invoices/${encodeURIComponent(key)}`);
if (result.invoice?.status === 'paid') {
stopInvoicePoll(key); toast('账单支付成功,服务期限已延长。', 'success'); await loadInvoices(); await loadVms(); return;
const invoice = result.invoice || {};
const status = String(invoice.status || '').toLowerCase();
if (status === 'paid') {
await loadInvoices(); await loadVms();
if (invoicePurpose(invoice) !== 'provision') {
stopInvoicePoll(key); toast('账单支付成功,服务期限已延长。', 'success'); return;
}
if (provisionFinished(invoice)) {
const { status: provisionStatus } = provisionStatusInfo(invoice);
stopInvoicePoll(key);
if (['completed', 'succeeded', 'active'].includes(provisionStatus)) toast('实例已创建完成。', 'success');
else if (provisionStatus === 'refunded') toast('实例创建失败,款项已退回账户余额。', 'error');
else toast('实例开通未完成,请在账单中查看任务状态。', 'error');
return;
}
}
if (['void'].includes(result.invoice?.status)) {
if (['void', 'expired'].includes(status)) {
stopInvoicePoll(key); toast('账单已失效,到账金额会保留在账户余额中。', 'error'); await loadInvoices(); return;
}
if (!invoiceCanPay(result.invoice)) {
stopInvoicePoll(key); toast('续费宽限期已经结束,到账金额会保留在账户余额中。', 'error'); await loadInvoices(); return;
if (status === 'refunded') {
stopInvoicePoll(key); toast('实例创建失败,款项已退回账户余额。', 'error'); await loadInvoices(); return;
}
if (!invoiceCanPay(invoice) && status !== 'paid') {
const message = invoicePurpose(invoice) === 'provision'
? '开通账单已超过支付截止时间。' : '续费宽限期已经结束,到账金额会保留在账户余额中。';
stopInvoicePoll(key); toast(message, 'error'); await loadInvoices(); return;
}
} catch {}
if (Date.now() - started < 10 * 60 * 1000) {
@ -507,15 +532,21 @@ function renderOnlinePayment(container, payment) {
scheduleInvoicePoll(payment.invoice_id);
}
async function payInvoiceBalance(invoice, row) {
if (!invoiceCanPay(invoice)) return toast('续费宽限期已经结束,账单不可支付。', 'error');
if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision'
? '开通账单已失效,不能支付。' : '续费宽限期已经结束,账单不可支付。', 'error');
if (state.mutationBusy || !confirm(`确认使用账户余额支付账单 ${invoice.invoice_no},金额 ¥${invoice.amount}?`)) return;
state.mutationBusy = true;
row.querySelectorAll('button').forEach(button => { button.disabled = true; });
try {
await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, {
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, {
method: 'POST', body: { idempotency_key: crypto.randomUUID() },
});
toast('账单已支付,服务期限已延长。', 'success'); await loadInvoices(); await loadVms();
const paid = result.invoice || invoice;
if (invoicePurpose(paid) === 'provision') {
toast('账单已支付,实例已进入创建队列。', 'success'); await loadInvoices(); await loadVms(); scheduleInvoicePoll(paid.id || invoice.id);
} else {
toast('账单已支付,服务期限已延长。', 'success'); await loadInvoices(); await loadVms();
}
} catch (error) { toast(error.message, 'error'); }
finally {
state.mutationBusy = false;
@ -523,7 +554,8 @@ async function payInvoiceBalance(invoice, row) {
}
}
async function createInvoicePayment(invoice, method, row) {
if (!invoiceCanPay(invoice)) return toast('续费宽限期已经结束,不能再生成支付订单。', 'error');
if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision'
? '开通账单已失效,不能再生成支付订单。' : '续费宽限期已经结束,不能再生成支付订单。', 'error');
if (state.mutationBusy || !confirm(`确认通过“${method.name}”生成 ¥${invoice.amount} 的支付订单?`)) return;
state.mutationBusy = true;
row.querySelectorAll('button').forEach(button => { button.disabled = true; });
@ -547,54 +579,99 @@ async function createInvoicePayment(invoice, method, row) {
}
finally { state.mutationBusy = false; row.querySelectorAll('button').forEach(button => { button.disabled = false; }); }
}
function appendProvisionInvoiceActions(invoice, detail, actions) {
const { data, status, display } = provisionStatusInfo(invoice);
if (status) actions.append(makeElement('span', `state-pill ${display[1]}`, display[0]));
if (data.jobId) actions.append(actionButton('查看创建进度', async () => {
let progress = detail.querySelector('.cloud-order-progress');
if (!progress) { progress = makeElement('p', 'cloud-order-progress muted'); detail.append(progress); }
try {
const job = await api(`/api/v1/jobs/${encodeURIComponent(data.jobId)}`);
progress.className = `cloud-order-progress ${job.error ? 'form-error' : 'muted'}`;
progress.textContent = job.error || job.phase || `任务状态:${job.status}`;
if (['completed', 'succeeded', 'failed', 'cancelled', 'needs_attention', 'uncertain'].includes(String(job.status || '').toLowerCase())) {
await loadInvoices(); await loadVms();
}
} catch (error) { toast(error.message, 'error'); }
}));
if (data.instanceId || data.instanceUuid) actions.append(actionButton('查看实例', async () => {
await loadVms();
const vm = state.vms.find(item => item.api_id === data.instanceId || item.uuid === data.instanceUuid);
if (vm) openVmDetail(vm.uuid); else toast('实例尚未出现在列表,请稍后刷新。');
}));
}
function renderInvoices() {
const container = byId('invoices-list'); container.replaceChildren();
if (!state.invoices.length) return container.append(makeElement('p', 'muted', '暂无续费账单。账单会在实例到期前 7 天自动生成。'));
if (!state.invoices.length) return container.append(makeElement('p', 'muted', '暂无账单。部署实例后会先生成开通账单;续费账单会在实例到期前 7 天自动生成。'));
for (const invoice of state.invoices) {
const row = makeElement('article', 'cloud-order cloud-invoice');
const detail = makeElement('div', 'cloud-order-detail');
const purpose = invoicePurpose(invoice);
const provision = purpose === 'provision';
const invoiceStatus = String(invoice.status || '').toLowerCase();
const deletionAt = invoiceDeletionTimestamp(invoice);
const paymentDeadline = invoicePaymentDeadlineTimestamp(invoice);
const payable = invoiceCanPay(invoice);
detail.append(makeElement('strong', '', `${invoice.instance_name || '实例'} · ¥${invoice.amount}`),
makeElement('p', 'muted', `账单 ${invoice.invoice_no} · 到期时间 ${formatOrderDate(invoice.due_at)}`),
makeElement('p', 'cloud-order-message', `支付后增加 ${invoice.validity_days} 天服务期 · 新账期流量 ${formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))}`));
if (['open', 'overdue'].includes(invoice.status) && deletionAt !== null) {
const subject = provision
? invoice.requested_name || invoice.instance_name || '待创建实例'
: invoice.instance_name || '实例';
const dueText = provision
? `支付截止 ${formatServiceDate(paymentDeadline ?? invoice.due_at)}`
: `实例到期 ${formatOrderDate(invoice.due_at)}`;
detail.append(makeElement('strong', '', `${subject} · ¥${invoice.amount}`),
makeElement('p', 'muted', `${provision ? '开通账单' : '续费账单'} ${invoice.invoice_no} · ${dueText}`),
makeElement('p', 'cloud-order-message', provision
? `${invoice.plan_name || '云服务器套餐'} · 支付后创建 ${invoice.validity_days} 天服务期 · 每期流量 ${formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))}`
: `支付后增加 ${invoice.validity_days} 天服务期 · 新账期流量 ${formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))}`));
if (provision) {
const task = provisionInvoiceData(invoice);
if (task.phase || task.error) {
const progress = makeElement('p', `cloud-order-progress ${task.error ? 'form-error' : 'muted'}`, task.error || task.phase);
detail.append(progress);
} else if (invoiceStatus === 'paid' && !provisionFinished(invoice)) {
detail.append(makeElement('p', 'cloud-order-message', '账单已支付,实例正在等待后台创建;关闭页面不会取消任务。'));
} else if (['void', 'expired'].includes(invoiceStatus)) {
detail.append(makeElement('p', 'cloud-order-message', '开通账单已失效,不会创建实例。'));
}
} else if (['open', 'overdue'].includes(invoiceStatus) && deletionAt !== null) {
detail.append(makeElement('p', 'cloud-order-message', payable
? `实例到期后会立即停用网络;若在 ${formatServiceDate(deletionAt)} 前仍未支付,实例及系统盘将被永久删除。续费成功后网络会自动恢复。`
: '三天续费宽限期已经结束,账单不可支付;实例及系统盘已进入永久删除流程。'));
} else if (['delete_failed', 'purge_stop_failed', 'purge_failed'].includes(invoice.status)) {
} else if (['delete_failed', 'purge_stop_failed', 'purge_failed'].includes(invoiceStatus)) {
detail.append(makeElement('p', 'cloud-order-message', '三天续费宽限期已经结束,账单不可支付;自动清理尚未完成,请联系管理员处理。'));
} else if (['expired', 'deleting', 'purge_pending', 'purge_stopping', 'purge_deleting'].includes(invoice.status)) {
} else if (['expired', 'deleting', 'purge_pending', 'purge_stopping', 'purge_deleting'].includes(invoiceStatus)) {
detail.append(makeElement('p', 'cloud-order-message', '三天续费宽限期已经结束,账单不可支付;实例及系统盘已进入永久删除流程。'));
}
const actions = makeElement('div', 'cloud-order-actions');
const [label, className] = invoiceStatusInfo(invoice.status);
const [label, className] = invoiceStatusInfo(invoiceStatus);
actions.append(makeElement('span', `state-pill ${className}`, label));
if (payable) {
actions.append(actionButton('余额支付', () => payInvoiceBalance(invoice, row)));
for (const method of state.invoicePaymentMethods) actions.append(actionButton(method.name, () => createInvoicePayment(invoice, method, row)));
} else if (['open', 'overdue'].includes(invoice.status)) {
} else if (['open', 'overdue'].includes(invoiceStatus)) {
stopInvoicePoll(invoice.id);
clearInvoicePaymentKeys(invoice.id);
actions.append(makeElement('span', 'muted', '已超过支付截止时间'));
} else if (invoice.status === 'paid') {
stopInvoicePoll(invoice.id);
} else if (invoiceStatus === 'paid') {
clearInvoicePaymentKeys(invoice.id);
if (!provision) stopInvoicePoll(invoice.id);
actions.append(makeElement('span', 'muted', invoice.paid_at ? `支付于 ${formatOrderDate(invoice.paid_at)}` : '已结清'));
} else if (invoice.status === 'void') {
stopInvoicePoll(invoice.id);
clearInvoicePaymentKeys(invoice.id);
} else if (['expired', 'deleting', 'delete_failed', 'purge_pending', 'purge_stopping', 'purge_stop_failed', 'purge_deleting', 'purge_failed'].includes(invoice.status)) {
} else if (['refunded', 'void', 'expired', 'deleting', 'delete_failed', 'purge_pending', 'purge_stopping', 'purge_stop_failed', 'purge_deleting', 'purge_failed'].includes(invoiceStatus)) {
stopInvoicePoll(invoice.id);
clearInvoicePaymentKeys(invoice.id);
}
if (provision && ['paid', 'refunded'].includes(invoiceStatus)) appendProvisionInvoiceActions(invoice, detail, actions);
if (provision && invoiceStatus === 'paid' && !provisionFinished(invoice)
&& !state.invoicePollTimers.has(String(invoice.id))) scheduleInvoicePoll(invoice.id);
row.append(detail, actions); container.append(row);
}
}
async function loadInvoices() {
try {
const payload = await api('/api/v1/invoices');
state.invoices = Array.isArray(payload.invoices) ? payload.invoices : [];
state.invoices = (Array.isArray(payload.invoices) ? payload.invoices : []).slice()
.sort((left, right) => Number(right.created_at || 0) - Number(left.created_at || 0)
|| Number(right.id || 0) - Number(left.id || 0));
state.invoicePaymentMethods = Array.isArray(payload.payment_methods) ? payload.payment_methods : [];
text('invoices-balance', `¥${payload.balance ?? '—'}`); renderInvoices(); showError('cloud-page-error', '');
} catch (error) { showError('cloud-page-error', error.message); }
@ -1358,7 +1435,7 @@ function renderTemplateCatalog(inputId) {
}
container.replaceChildren(...cards);
}
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', async event => { event.preventDefault(); const view = button.dataset.view; button.closest('details')?.removeAttribute('open'); try { if (view === 'create') await openCreate(); else { showView(view); if (view === 'keys') await loadKeys(); if (view === 'orders') await loadOrders(); if (view === 'invoices') await loadInvoices(); } } catch (error) { showError('cloud-page-error', error.message); } }));
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', async event => { event.preventDefault(); const view = button.dataset.view; button.closest('details')?.removeAttribute('open'); try { if (view === 'create') await openCreate(); else { showView(view); if (view === 'keys') await loadKeys(); if (view === 'invoices') await loadInvoices(); } } catch (error) { showError('cloud-page-error', error.message); } }));
byId('refresh-button').addEventListener('click', loadVms);
byId('vm-detail-refresh-button').addEventListener('click', async () => {
await loadVms();
@ -1367,7 +1444,7 @@ byId('vm-detail-refresh-button').addEventListener('click', async () => {
byId('create-button').addEventListener('click', openCreate); byId('create-back').addEventListener('click', () => showView('list')); byId('vm-detail-back-button').addEventListener('click', () => { state.selectedVmId = null; showView('list'); }); byId('ssh-keys-back-button').addEventListener('click', () => showView('list'));
for (const id of ['reinstall-back', 'reinstall-cancel', 'rescue-back']) byId(id).addEventListener('click', () => { if (!state.mutationBusy) { const vm = selectedVm(); if (vm) openVmDetail(vm.uuid); else showView('list'); } });
byId('search-input').addEventListener('input', () => renderVMs()); byId('state-filter').addEventListener('change', () => renderVMs()); byId('vm-plan').addEventListener('change', () => { void loadPlanResources(); }); byId('create-form').querySelectorAll('[name="source"]').forEach(radio => radio.addEventListener('change', updateSource));
byId('create-form').addEventListener('submit', buy); byId('reinstall-form').addEventListener('submit', reinstall); byId('rescue-form').addEventListener('submit', event => { event.preventDefault(); void rescueAction('load'); }); byId('rescue-force-start').addEventListener('click', () => rescueAction('force-start')); byId('rescue-exit').addEventListener('click', () => rescueAction('exit')); byId('orders-refresh').addEventListener('click', loadOrders); byId('invoices-refresh').addEventListener('click', loadInvoices);
byId('create-form').addEventListener('submit', buy); byId('reinstall-form').addEventListener('submit', reinstall); byId('rescue-form').addEventListener('submit', event => { event.preventDefault(); void rescueAction('load'); }); byId('rescue-force-start').addEventListener('click', () => rescueAction('force-start')); byId('rescue-exit').addEventListener('click', () => rescueAction('exit')); byId('invoices-refresh').addEventListener('click', loadInvoices);
for (const id of ['vm-open-ssh-keys', 'reinstall-open-ssh-keys']) byId(id).addEventListener('click', async () => { showView('keys'); try { await loadKeys(); } catch (error) { toast(error.message, 'error'); } });
byId('ssh-key-form').addEventListener('submit', async event => { event.preventDefault(); const button = byId('ssh-key-save-button'); button.disabled = true; showError('ssh-key-form-error', ''); try { await api('/api/v1/ssh-keys', { method: 'POST', body: { name: byId('ssh-key-name').value.trim(), public_key: byId('ssh-key-public-key').value.trim() } }); byId('ssh-key-form').reset(); await loadKeys(); toast('公钥已保存。', 'success'); } catch (error) { showError('ssh-key-form-error', error.message); } finally { button.disabled = false; } });
byId('ssh-key-file').addEventListener('change', async event => { const file = event.target.files?.[0]; if (!file) return; if (file.size > 16384) return showError('ssh-key-form-error', '公钥文件超过 16 KiB 限制。'); const content = await file.text(); if (/PRIVATE KEY/.test(content)) return showError('ssh-key-form-error', '不能导入私钥,只能导入 .pub 公钥。'); byId('ssh-key-public-key').value = content.trim(); });
@ -1394,6 +1471,6 @@ byId('vm-metrics-range').addEventListener('change', () => { state.metricsRange =
});
byId('console-modal').querySelector('[data-close-modal]').addEventListener('click', closeConsole); byId('console-cad').addEventListener('click', () => state.rfb?.sendCtrlAltDel()); byId('console-fullscreen').addEventListener('click', () => { byId('console-stage').requestFullscreen?.().catch(error => toast(error.message, 'error')); }); byId('console-password-form').addEventListener('submit', event => { event.preventDefault(); state.rfb?.sendCredentials({ password: byId('console-password').value }); byId('console-password').value = ''; byId('console-password-form').hidden = true; }); window.addEventListener('keydown', event => { if (event.key === 'Escape') closeConsole(); });
document.addEventListener('visibilitychange', () => { if (document.hidden) { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); stopInvoicePoll(); } else { void loadVms(); if (state.view === 'detail') setVmDetailTab(state.detailTab); if (state.view === 'invoices') void loadInvoices(); } }); window.addEventListener('pagehide', () => { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); stopInvoicePoll(); closeConsole(); state.resourceController?.abort(); }); byId('logout-button').addEventListener('click', () => { clearCredential(); closeConsole(); location.assign('/user/logout'); });
async function initialize() { const initialHash = location.hash; try { const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return; } state.csrfToken = session.csrf_token || ''; if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); state.userId = String(session.user_id || ''); if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。'); state.username = session.username || session.user_name || session.email || session.user?.email || '用户'; state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1; text('current-username', state.username); for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) { const link = byId(id); if (link) link.hidden = !state.admin; } showView('list'); updateSource(); await loadVms(); await routeHash(initialHash); setInterval(() => { if (!document.hidden) { void loadVms(); if (trafficDailyViewVisible()) void loadVmTrafficDaily(); if (state.view === 'orders') void loadOrders(); if (state.view === 'invoices' && state.invoicePollTimers.size === 0) void loadInvoices(); } }, 15000); } catch (error) { showError('cloud-page-error', error.message); } }
async function initialize() { const initialHash = location.hash; try { const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return; } state.csrfToken = session.csrf_token || ''; if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); state.userId = String(session.user_id || ''); if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。'); state.username = session.username || session.user_name || session.email || session.user?.email || '用户'; state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1; text('current-username', state.username); for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) { const link = byId(id); if (link) link.hidden = !state.admin; } showView('list'); updateSource(); await loadVms(); await routeHash(initialHash); setInterval(() => { if (!document.hidden) { void loadVms(); if (trafficDailyViewVisible()) void loadVmTrafficDaily(); if (state.view === 'invoices' && state.invoicePollTimers.size === 0) void loadInvoices(); } }, 15000); } catch (error) { showError('cloud-page-error', error.message); } }
window.addEventListener('hashchange', () => { if (state.csrfToken) void routeHash(); });
void initialize();

@ -1,2 +1,2 @@
{assign var=admin_title value='开通订单'}{assign var=admin_active value='cloud_orders'}{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css"><section class="cloud-admin" data-cloud-admin="orders"><h4>余额开通订单</h4><p class="text-muted">开通套餐按设置的账期生效;到期前 7 天生成续费账单,用户可以使用账户余额或已启用的在线支付渠道结清。失败或不确定的开通任务需核查实际宿主机状态,不要重复创建或扣款。</p><p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p><button id="admin-records-refresh" class="btn btn-outline-primary mb-3" type="button">刷新</button><div class="card"><div class="card-body table-responsive"><table class="table"><thead><tr><th>订单</th><th>用户</th><th>套餐</th><th>金额</th><th>状态</th><th>实例 / 任务</th><th>时间 / 错误</th></tr></thead><tbody id="admin-records"></tbody></table></div></div></section><script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>{include file='admin/static_footer.tpl'}
{assign var=admin_title value='开通任务'}{assign var=admin_active value='cloud-orders'}{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css"><section class="cloud-admin" data-cloud-admin="orders"><h4>实例开通任务</h4><p class="text-muted">用户提交部署后先生成开通账单,只有账单支付成功才会在此进入创建队列。失败或不确定的任务需核查实际宿主机状态,不要重复创建或扣款。</p><p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p><button id="admin-records-refresh" class="btn btn-outline-primary mb-3" type="button">刷新</button><div class="card"><div class="card-body table-responsive"><table class="table"><thead><tr><th>任务</th><th>用户</th><th>套餐</th><th>金额</th><th>状态</th><th>实例 / 引擎任务</th><th>时间 / 错误</th></tr></thead><tbody id="admin-records"></tbody></table></div></div></section><script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>{include file='admin/static_footer.tpl'}

@ -1,5 +1,5 @@
{assign var=admin_title value='新增商品'}{assign var=admin_active value='shop'}{include file='admin/static_header.tpl'}
<div class="py-3"><h4>新增云服务器套餐</h4><p class="text-muted">绑定宿主机并设置账期、每期流量额度后,用户可用余额购买开通;到期前会生成支持余额或在线支付的续费账单。</p><a class="btn btn-light" href="/admin/shop">返回商品列表</a></div>
<div class="py-3"><h4>新增云服务器套餐</h4><p class="text-muted">绑定宿主机并设置账期、每期流量额度后,用户部署时会先生成支持余额或在线支付的开通账单;支付成功后才创建实例,到期前再自动生成续费账单。</p><a class="btn btn-light" href="/admin/shop">返回商品列表</a></div>
<form class="card" id="shopForm" data-method="POST" data-url="/admin/shop"><div class="card-body"><div class="row g-3"><div class="col-12"><label class="form-label" for="name">商品名称</label><input class="form-control" id="name" name="name" type="text" maxlength="128" value="" required></div>
<div class="col-md-6"><label class="form-label" for="cpu_cores">CPU 核数</label><input class="form-control" id="cpu_cores" name="cpu_cores" type="number" min="1" max="64" step="1" value="2" required></div>
<div class="col-md-6"><label class="form-label" for="host_id">开通宿主机</label><select class="form-select" id="host_id" name="host_id" data-selected=""><option value="">未绑定(禁止购买)</option></select></div>

@ -161,7 +161,7 @@
<li><a class="{if $admin_active|default:'' == 'cloud-templates'}active{/if}" href="/admin/cloud/templates"><i class="mdi mdi-disc"></i><span>云镜像模版</span></a></li>
<li><a class="{if $admin_active|default:'' == 'cloud-rescue'}active{/if}" href="/admin/cloud/rescue"><i class="mdi mdi-lifebuoy"></i><span>救援模版</span></a></li>
<li><a class="{if $admin_active|default:'' == 'cloud-instances'}active{/if}" href="/admin/cloud/instances"><i class="mdi mdi-server"></i><span>虚拟机管理</span></a></li>
<li><a class="{if $admin_active|default:'' == 'cloud-orders'}active{/if}" href="/admin/cloud/orders"><i class="mdi mdi-receipt-text-outline"></i><span>开通订单</span></a></li>
<li><a class="{if $admin_active|default:'' == 'cloud-orders'}active{/if}" href="/admin/cloud/orders"><i class="mdi mdi-progress-wrench"></i><span>开通任务</span></a></li>
{if $admin_can_manage|default:false}<li><a class="{if $admin_active|default:'' == 'update'}active{/if}" href="/admin/update"><i class="mdi mdi-update"></i><span>在线更新</span></a></li>{/if}

@ -80,7 +80,7 @@
</section>
<section id="create-view" class="workspace-form-page" aria-labelledby="create-title" hidden>
<button id="create-back" class="button button-ghost workspace-form-back" type="button">← 返回虚拟机列表</button>
<div class="page-heading workspace-form-heading"><div><span class="eyebrow">NEW VIRTUAL MACHINE</span><h1 id="create-title" tabindex="-1">部署实例</h1><p>选择 ISO 安装,或从云镜像模板直接创建系统。</p></div></div>
<div class="page-heading workspace-form-heading"><div><span class="eyebrow">NEW VIRTUAL MACHINE</span><h1 id="create-title" tabindex="-1">部署实例</h1><p>选择系统和套餐,提交后先生成开通账单;支付完成后才会创建实例。</p></div></div>
<form id="create-form" class="inventory-panel workspace-form-card">
<div class="workspace-form-body">
<fieldset class="create-source-picker"><legend>系统来源</legend><label><input type="radio" name="source" value="iso" /><span><strong>ISO 安装</strong><small>通过 VNC 安装系统</small></span></label><label><input type="radio" name="source" value="cloud" checked /><span><strong>公网云镜像</strong><small>自动配置公网 IP 后直接开机</small></span></label></fieldset>
@ -96,8 +96,8 @@
<div class="field full" id="vm-root-password-field"><label for="vm-root-password">初始 root 密码(可选)</label><input id="vm-root-password" name="root_password" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" aria-describedby="vm-root-password-hint" placeholder="可自行设置,留空时自动生成强密码" disabled /><small id="vm-root-password-hint" aria-live="polite">留空时自动生成强密码,即使选择了 SSH 公钥;自行设置需至少 12 个字符,包含大写字母、小写字母、数字和符号。</small></div>
</div>
</div>
</div><div id="create-iso-tip" class="form-tip"><span aria-hidden="true">ⓘ</span><p>创建后会自动开机,可通过 VNC 安装系统。安装程序首次重启时虚拟机会先停机;之后在面板点“开机”,将从硬盘启动且不再挂载 ISO。</p></div><div id="create-cloud-tip" class="form-tip" hidden><span aria-hidden="true">ⓘ</span><p>云镜像首次启动由 cloud-init 写入静态 IP、DNS 和 root 登录凭据,无需 VNC 安装。可同时使用已保存的 SSH 公钥和 root 密码;密码留空时,即使选择了公钥也会自动生成强密码。初始密码可在虚拟机详情页查看。</p></div><p id="create-error" class="form-error" role="alert" hidden></p></div>
<div class="workspace-form-actions"><button id="create-submit" class="button button-primary" type="submit">部署实例</button></div>
</div><div id="create-iso-tip" class="form-tip"><span aria-hidden="true">ⓘ</span><p>账单支付并完成创建后,实例会自动开机,可通过 VNC 安装系统。安装程序首次重启时虚拟机会先停机;之后在面板点“开机”,将从硬盘启动且不再挂载 ISO。</p></div><div id="create-cloud-tip" class="form-tip" hidden><span aria-hidden="true">ⓘ</span><p>账单支付后才会创建实例。云镜像首次启动由 cloud-init 写入静态 IP、DNS 和 root 登录凭据,无需 VNC 安装。可同时使用已保存的 SSH 公钥和 root 密码;密码留空时,即使选择了公钥也会自动生成强密码。初始密码可在虚拟机详情页查看。</p></div><p id="create-error" class="form-error" role="alert" hidden></p></div>
<div class="workspace-form-actions"><button id="create-submit" class="button button-primary" type="submit">生成开通账单</button></div>
</form>
</section>
<section id="reinstall-view" class="workspace-form-page" aria-labelledby="reinstall-title" hidden>
@ -161,9 +161,8 @@
</div>
</div>
<section id="orders-workspace" hidden><div class="page-heading"><div><span class="eyebrow">PROVISIONING ORDERS</span><h1>开通订单</h1><p>余额支付后由后台持续开通;关闭页面不会取消任务。失败会按订单状态退款,失败原因在此显示。</p></div><button id="orders-refresh" class="button button-outline" type="button">刷新</button></div><div id="orders-list" class="inventory-panel cloud-orders" aria-live="polite"></div></section>
<section id="invoices-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">RENEWAL INVOICES</span><h1>续费账单</h1><p>实例到期前 7 天自动生成账单;到期后立即停用网络,续费成功会自动恢复。到期满 3 天仍未支付,实例及系统盘将被永久删除。</p></div><button id="invoices-refresh" class="button button-outline" type="button">刷新</button></div>
<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">¥—</strong><a class="button button-outline small" href="/user/code">余额充值</a></div>
<div id="invoices-list" class="inventory-panel cloud-orders cloud-invoices" aria-live="polite"><p class="muted">正在加载…</p></div>
</section>

@ -1 +1 @@
{assign var=venix_asset_version value='2026092712' scope='global'}
{assign var=venix_asset_version value='2026092713' scope='global'}

@ -22,11 +22,8 @@
<a class="sidebar-link" href="/user/cloud#keys"{if $panel_cloud_mode} data-view="keys"{/if}>
<i class="mdi mdi-key-outline nav-icon" aria-hidden="true"></i><span>SSH 公钥</span>
</a>
<a class="sidebar-link" href="/user/cloud#orders"{if $panel_cloud_mode} data-view="orders"{/if}>
<i class="mdi mdi-clipboard-text-outline nav-icon" aria-hidden="true"></i><span>开通订单</span>
</a>
<a class="sidebar-link" href="/user/cloud#invoices"{if $panel_cloud_mode} data-view="invoices"{/if}>
<i class="mdi mdi-file-document-outline nav-icon" aria-hidden="true"></i><span>续费账单</span>
<i class="mdi mdi-file-document-outline nav-icon" aria-hidden="true"></i><span>账单信息</span>
</a>
<div class="sidebar-section-label">账户与支持</div>

@ -51,8 +51,11 @@ CREATE TABLE IF NOT EXISTS cloud_orders (
amount DECIMAL(12,2) NOT NULL,
status VARCHAR(32) NOT NULL DEFAULT 'queued',
spec_json LONGTEXT NOT NULL,
payload_cipher LONGTEXT DEFAULT NULL,
instance_id BIGINT UNSIGNED DEFAULT NULL,
refunded_at BIGINT DEFAULT NULL,
stock_reserved_at BIGINT UNSIGNED DEFAULT NULL,
stock_released_at BIGINT UNSIGNED DEFAULT NULL,
created_at BIGINT NOT NULL,
updated_at BIGINT NOT NULL,
UNIQUE KEY uniq_cloud_order_request (user_id, idempotency_key),
@ -101,11 +104,13 @@ CREATE TABLE IF NOT EXISTS cloud_renewals (
CREATE TABLE IF NOT EXISTS cloud_invoices (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
invoice_no VARCHAR(40) NOT NULL,
instance_id BIGINT UNSIGNED NOT NULL,
purpose VARCHAR(16) NOT NULL DEFAULT 'renewal',
instance_id BIGINT UNSIGNED DEFAULT NULL,
order_id BIGINT UNSIGNED DEFAULT NULL,
user_id BIGINT UNSIGNED NOT NULL,
plan_id BIGINT UNSIGNED DEFAULT NULL,
renewal_id BIGINT UNSIGNED DEFAULT NULL,
renews_expires_at BIGINT UNSIGNED NOT NULL,
renews_expires_at BIGINT UNSIGNED DEFAULT NULL,
due_at BIGINT UNSIGNED NOT NULL,
amount DECIMAL(12,2) NOT NULL,
validity_days INT UNSIGNED NOT NULL,
@ -117,6 +122,7 @@ CREATE TABLE IF NOT EXISTS cloud_invoices (
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY uniq_cloud_invoice_no (invoice_no),
UNIQUE KEY uniq_cloud_invoice_order (order_id),
KEY cloud_invoice_period (instance_id, renews_expires_at, status),
UNIQUE KEY uniq_cloud_invoice_renewal (renewal_id),
KEY cloud_invoice_owner (user_id, status, due_at),
@ -128,6 +134,16 @@ CREATE TABLE IF NOT EXISTS cloud_invoices (
ALTER TABLE cloud_invoices DROP INDEX IF EXISTS uniq_cloud_invoice_period;
ALTER TABLE cloud_invoices ADD INDEX IF NOT EXISTS
cloud_invoice_period (instance_id, renews_expires_at, status);
-- Upgrade an existing installation so unpaid provisioning requests can live
-- behind an invoice without fabricating an instance or expiry timestamp.
ALTER TABLE cloud_orders ADD COLUMN IF NOT EXISTS payload_cipher LONGTEXT NULL AFTER spec_json;
ALTER TABLE cloud_orders ADD COLUMN IF NOT EXISTS stock_reserved_at BIGINT UNSIGNED NULL AFTER refunded_at;
ALTER TABLE cloud_orders ADD COLUMN IF NOT EXISTS stock_released_at BIGINT UNSIGNED NULL AFTER stock_reserved_at;
ALTER TABLE cloud_invoices ADD COLUMN IF NOT EXISTS purpose VARCHAR(16) NOT NULL DEFAULT 'renewal' AFTER invoice_no;
ALTER TABLE cloud_invoices MODIFY instance_id BIGINT UNSIGNED NULL;
ALTER TABLE cloud_invoices ADD COLUMN IF NOT EXISTS order_id BIGINT UNSIGNED NULL AFTER instance_id;
ALTER TABLE cloud_invoices MODIFY renews_expires_at BIGINT UNSIGNED NULL;
ALTER TABLE cloud_invoices ADD UNIQUE INDEX IF NOT EXISTS uniq_cloud_invoice_order (order_id);
CREATE TABLE IF NOT EXISTS cloud_invoice_payments (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
invoice_id BIGINT UNSIGNED NOT NULL,

@ -23,8 +23,12 @@ namespace {
use App\Models\Shop;
use App\Models\CloudHost;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudInvoicePayment;
use App\Models\CloudOrder;
use App\Models\CloudJob;
use App\Services\Cloud\CloudInvoiceService;
use App\Services\Cloud\CloudInvoicePaymentService;
use App\Services\Cloud\CloudOrderService;
use App\Services\Cloud\CloudWorkerService;
use App\Services\Cloud\CloudEngineClient;
@ -32,6 +36,7 @@ namespace {
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudInstanceDiscovery;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudMoney;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
@ -47,12 +52,14 @@ namespace {
$schema->create('user', function (Blueprint $t) { $t->increments('id'); $t->string('money'); $t->integer('enable')->default(1); $t->integer('is_admin')->default(0); $t->integer('restrict_balance_purchase')->default(0); });
$schema->create('shop', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->string('name'); $t->string('price'); foreach (['cpu_cores', 'memory_mib', 'bandwidth_mbps', 'disk_gib', 'validity_days', 'traffic_quota_bytes', 'status', 'stock', 'sort'] as $v) { $t->integer($v)->default(0); } });
$schema->create('cloud_hosts', function (Blueprint $t) { $t->increments('id'); $t->string('name'); $t->string('region')->default(''); $t->integer('enabled'); $t->string('default_network'); });
$schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'host_id'] as $v) { $t->integer($v); } $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('status'); $t->text('spec_json'); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'host_id'] as $v) { $t->integer($v); } $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('status'); $t->text('spec_json'); $t->text('payload_cipher')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); });
$schema->create('cloud_jobs', function (Blueprint $t) { $t->increments('id'); $t->string('operation_id')->unique(); foreach (['order_id', 'instance_id'] as $v) { $t->integer($v)->nullable(); } foreach (['user_id', 'host_id'] as $v) { $t->integer($v); } $t->string('kind'); $t->string('status'); $t->text('payload_cipher'); $t->integer('attempts')->default(0); $t->integer('dispatched_at')->nullable(); $t->string('lease_token')->nullable(); $t->integer('lease_until')->default(0); $t->integer('available_at'); $t->string('error_code')->nullable(); $t->text('result_json')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); });
$schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); foreach (['host_id', 'user_id'] as $v) { $t->integer($v); } foreach (['order_id', 'plan_id', 'current_period_id', 'expires_at', 'suspended_at', 'network_suspended_at'] as $v) { $t->integer($v)->nullable(); } foreach (['renewal_days', 'renewal_traffic_bytes', 'traffic_quota_bytes', 'traffic_download_bytes', 'traffic_upload_bytes', 'lifetime_download_bytes', 'lifetime_upload_bytes', 'traffic_synced_at'] as $v) { $t->integer($v)->default(0); } $t->string('renewal_price')->nullable(); $t->string('uuid'); $t->string('name'); $t->string('status'); $t->string('service_status')->default('exempt'); $t->string('network_status')->default('active'); $t->text('spec_json'); $t->text('credential_cipher')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique(['host_id', 'uuid']); });
$schema->create('cloud_service_periods', function (Blueprint $t) { $t->increments('id'); foreach (['instance_id', 'user_id'] as $v) { $t->integer($v); } foreach (['plan_id', 'order_id', 'renewal_id', 'download_base_bytes', 'upload_base_bytes', 'activated_at'] as $v) { $t->integer($v)->nullable(); } foreach (['starts_at', 'ends_at', 'traffic_quota_bytes', 'download_used_bytes', 'upload_used_bytes', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } $t->string('status'); $t->unique('order_id'); $t->unique('renewal_id'); });
$schema->create('cloud_invoices', function (Blueprint $t) { $t->increments('id'); $t->string('invoice_no')->unique(); $t->string('purpose')->default('renewal'); $t->integer('instance_id')->nullable(); $t->integer('order_id')->nullable()->unique(); $t->integer('user_id'); $t->integer('plan_id')->nullable(); $t->integer('renewal_id')->nullable(); $t->integer('renews_expires_at')->nullable(); $t->integer('due_at'); $t->string('amount'); $t->integer('validity_days'); $t->integer('traffic_quota_bytes'); $t->string('status'); $t->string('paid_via')->nullable(); $t->string('payment_reference')->nullable(); $t->integer('paid_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$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_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'); });
$user = new User(); $user->id = 1; $user->money = '100.00'; $user->enable = 1; $user->is_admin = false; $user->save(); $user->isLogin = true;
$user = new User(); $user->id = 1; $user->money = '0.00'; $user->enable = 1; $user->is_admin = false; $user->save(); $user->isLogin = true;
\App\Services\Auth::$user = $user;
$host = new CloudHost(); $host->name = 'host'; $host->enabled = true; $host->default_network = 'bridge:br0'; $host->save();
$plan = new Shop(); $plan->host_id = $host->id; $plan->name = 'plan'; $plan->price = '9.99'; $plan->cpu_cores = 2; $plan->memory_mib = 2048; $plan->bandwidth_mbps = 100; $plan->disk_gib = 20; $plan->validity_days = 30; $plan->traffic_quota_bytes = 1024 * 1024 * 1024; $plan->status = 1; $plan->stock = 10; $plan->save();
@ -69,16 +76,68 @@ namespace {
$input = ['plan_id' => 1, 'source' => 'cloud', 'name' => 'vm-one', 'template_id' => 'alma10-1234abcd-0123456789abcdef', 'idempotency_key' => 'test-request-key-0001'];
$first = CloudOrderService::purchase($input, $actor);
$same = CloudOrderService::purchase($input, $actor);
$assert($first->id === $same->id && User::find(1)->money === '90.01' && CloudJob::count() === 1 && Shop::find(1)->stock === 9, 'Idempotent purchase charged twice or stock incorrect.');
$openingInvoice = CloudInvoice::where('order_id', $first->id)->first();
$openingDisplay = $openingInvoice === null ? []
: CloudInvoiceService::display($openingInvoice);
$assert($first->id === $same->id
&& (string) $first->status === 'awaiting_payment'
&& $openingInvoice !== null
&& (string) $openingInvoice->purpose === 'provision'
&& $openingInvoice->instance_id === null
&& ($openingDisplay['purpose'] ?? null) === 'provision'
&& ($openingDisplay['order_status'] ?? null) === 'awaiting_payment'
&& User::find(1)->money === '0.00'
&& CloudJob::count() === 0
&& Shop::find(1)->stock === 9,
'Idempotent deployment request charged money, queued work, lost its opening invoice, or reserved stock twice.');
try { CloudOrderService::purchase($input + ['vcpu' => 64], $actor); throw new RuntimeException('Resource bypass accepted.'); } catch (CloudError $e) {}
try { CloudOrderService::purchase(array_replace($input, ['name' => 'changed']), $actor); throw new RuntimeException('Idempotency conflict accepted.'); } catch (CloudError $e) { $assert($e->httpStatus === 409, 'Wrong idempotency response.'); }
try {
CloudInvoiceService::payBalance($openingInvoice,
array_replace($actor, ['user_id' => 2]), 'provision-cross-tenant-0001');
throw new RuntimeException('Another tenant paid an opening invoice.');
} catch (CloudError $e) {
$assert($e->httpStatus === 403, 'Opening invoice ownership failure leaked another status.');
}
$assert(User::find(1)->money === '0.00'
&& CloudOrder::find($first->id)->status === 'awaiting_payment'
&& CloudJob::count() === 0,
'Cross-tenant opening-invoice access changed financial or queue state.');
try {
CloudInvoiceService::payBalance(
$openingInvoice, $actor, 'provision-insufficient-balance-0001');
throw new RuntimeException('Opening invoice was paid without sufficient balance.');
} catch (CloudError $e) {
$assert($e->httpStatus === 409, 'Insufficient opening-invoice balance returned the wrong status.');
}
$assert(CloudOrder::find($first->id)->status === 'awaiting_payment'
&& CloudInvoice::find($openingInvoice->id)->status === 'open'
&& CloudJob::count() === 0,
'Failed opening-invoice payment changed invoice, order, or queue state.');
$user = User::find(1); $user->money = '100.00'; $user->save();
$paidOpening = CloudInvoiceService::payBalance(
$openingInvoice, $actor, 'provision-balance-test-0001');
$paidOpeningAgain = CloudInvoiceService::payBalance(
$paidOpening->fresh(), $actor, 'provision-balance-test-0001');
$assert((string) $paidOpeningAgain->status === 'paid'
&& User::find(1)->money === '90.01'
&& CloudOrder::find($first->id)->status === 'queued'
&& CloudJob::where('order_id', $first->id)->count() === 1
&& CloudOrder::find($first->id)->payload_cipher === null,
'Opening invoice payment was not an atomic, exactly-once transition into the provisioning queue.');
$history = [];
$mock = new MockHandler([new Response(200, [], json_encode(['status' => 'succeeded', 'uuid' => '11111111-1111-4111-8111-111111111111', 'generated_password' => 'must-not-persist']))]);
$stack = HandlerStack::create($mock); $stack->push(Middleware::history($history));
$worker = new CloudWorkerService(new CloudEngineClient(new Client(['handler' => $stack])));
$worker->tick();
$openingDisplay = CloudInvoiceService::display($openingInvoice->fresh());
$assert(CloudOrder::find($first->id)->status === 'succeeded' && CloudInstance::count() === 1
&& \App\Models\CloudServicePeriod::count() === 1, 'Successful provision did not create its first service period.');
&& \App\Models\CloudServicePeriod::count() === 1
&& CloudInvoice::find($openingInvoice->id)->instance_id !== null
&& ($openingDisplay['order_status'] ?? null) === 'succeeded'
&& ($openingDisplay['instance_id'] ?? null) !== null
&& ($openingDisplay['job_status'] ?? null) === 'succeeded',
'Successful provision did not create its first service period or update the opening bill.');
$posted = json_decode((string) $history[0]['request']->getBody(), true);
$signedActor = json_decode(base64_decode(strtr($history[0]['request']->getHeaderLine('X-Cloud-Actor'), '-_', '+/')), true);
$assert($posted['vcpu'] === 2 && $posted['bandwidth_mbps'] === 100 && $posted['network'] === 'bridge:br0'
@ -91,6 +150,36 @@ namespace {
&& !array_key_exists('root_password', $terminalPayload['body'] ?? []),
'Terminal provisioning job retained a recoverable root password.');
$instance = CloudInstance::first();
// One active instance plus one unpaid reservation must exhaust a limit of
// two. Expiry releases finite stock and the encrypted credential exactly
// once without ever entering the worker queue or touching the wallet.
\App\Services\Config::$values['cloud_max_instances_per_user'] = 2;
$abandoned = CloudOrderService::purchase(array_replace($input, [
'name' => 'vm-abandoned', 'idempotency_key' => 'test-request-key-abandoned',
]), $actor);
try {
CloudOrderService::purchase(array_replace($input, [
'name' => 'vm-over-limit', 'idempotency_key' => 'test-request-key-over-limit',
]), $actor);
throw new RuntimeException('Unpaid provisioning reservation bypassed the instance limit.');
} catch (CloudError $e) {
$assert($e->httpStatus === 409, 'Reserved instance limit returned the wrong status.');
}
$abandonedInvoice = CloudInvoice::where('order_id', $abandoned->id)->first();
$abandonedInvoice->due_at = time() - 1;
$abandonedInvoice->save();
$assert(CloudInvoiceService::expireProvision() === 1
&& CloudInvoiceService::expireProvision() === 0
&& CloudOrder::find($abandoned->id)->status === 'expired'
&& CloudOrder::find($abandoned->id)->payload_cipher === null
&& CloudOrder::find($abandoned->id)->stock_released_at !== null
&& CloudJob::where('order_id', $abandoned->id)->count() === 0
&& User::find(1)->money === '90.01'
&& Shop::find(1)->stock === 9,
'Expired opening invoice queued work, changed money, retained credentials, or released stock more than once.');
\App\Services\Config::$values['cloud_max_instances_per_user'] = 20;
$assert(CloudAccess::instance((string) $instance->id, $actor)->id === $instance->id, 'Owner denied own VM.');
$other = array_replace($actor, ['user_id' => 2]);
try { CloudAccess::instance((string) $instance->id, $other); throw new RuntimeException('Tenant isolation failed.'); } catch (CloudError $e) { $assert($e->httpStatus === 404, 'Nonowner information leaked.'); }
@ -100,21 +189,42 @@ namespace {
try { CloudJobService::enqueue($instance, array_replace($admin, ['can_manage' => true]), 'action', 'POST', '/actions', ['action' => 'reboot']); throw new RuntimeException('Scoped can_manage bypassed cross-owner queue authorization.'); } catch (CloudError $e) {}
try { CloudAccess::manage($actor + ['can_provision' => true]); throw new RuntimeException('Provision actor globally privileged.'); } catch (CloudError $e) {}
$failed = CloudOrderService::purchase(array_replace($input, ['name' => 'vm-two', 'idempotency_key' => 'test-request-key-0002']), $actor);
$assert(User::find(1)->money === '90.01'
&& CloudJob::where('order_id', $failed->id)->count() === 0,
'A second unpaid deployment charged or entered the worker queue.');
CloudInvoiceService::payBalance(CloudInvoice::where('order_id', $failed->id)->first(),
$actor, 'provision-balance-test-0002');
$failedJob = CloudJob::where('order_id', $failed->id)->first();
$mock->append(new Response(422, [], json_encode(['operation_id' => $failedJob->operation_id,
'status' => 'failed', 'safe_to_refund' => true, 'error' => '虚拟机参数校验失败'])));
$worker->tick(); $worker->tick();
$failedDisplay = CloudOrderService::display(CloudOrder::find($failed->id));
$failedInvoiceDisplay = CloudInvoiceService::display(
CloudInvoice::where('order_id', $failed->id)->first());
$assert(User::find(1)->money === '90.01' && CloudOrder::find($failed->id)->refunded_at !== null && Shop::find(1)->stock === 9,
'Structured non-2xx operation failure was not refunded exactly once.');
$assert($failedDisplay['job_status'] === 'failed' && $failedDisplay['attempts'] >= 1
&& str_contains($failedDisplay['error'], '虚拟机参数校验失败'),
'Safe job diagnostics are missing from the order display.');
&& str_contains($failedDisplay['error'], '虚拟机参数校验失败')
&& ($failedInvoiceDisplay['status'] ?? null) === 'refunded'
&& ($failedInvoiceDisplay['order_status'] ?? null) === 'failed'
&& str_contains((string) ($failedInvoiceDisplay['error'] ?? ''), '虚拟机参数校验失败'),
'Safe job diagnostics are missing from the unified invoice display.');
$uncertain = CloudOrderService::purchase(array_replace($input, ['name' => 'vm-three', 'idempotency_key' => 'test-request-key-0003']), $actor);
$assert(User::find(1)->money === '90.01'
&& CloudJob::where('order_id', $uncertain->id)->count() === 0,
'An unpaid ambiguous-case deployment charged or entered the worker queue.');
CloudInvoiceService::payBalance(CloudInvoice::where('order_id', $uncertain->id)->first(),
$actor, 'provision-balance-test-0003');
$mock->append(new ConnectException('simulated timeout', new Request('POST', 'http://127.0.0.1:8000')));
$worker->tick();
$uncertainJob = CloudJob::where('order_id', $uncertain->id)->first();
$assert($uncertainJob->status === 'uncertain' && CloudOrder::find($uncertain->id)->refunded_at === null && User::find(1)->money === '80.02', 'Timeout incorrectly refunded.');
$uncertainInvoiceDisplay = CloudInvoiceService::display(
CloudInvoice::where('order_id', $uncertain->id)->first());
$assert($uncertainJob->status === 'uncertain'
&& CloudOrder::find($uncertain->id)->refunded_at === null
&& User::find(1)->money === '80.02'
&& ($uncertainInvoiceDisplay['order_status'] ?? null) === 'uncertain',
'Timeout incorrectly refunded or disappeared from unified billing.');
$uncertainJob->available_at = 0; $uncertainJob->save();
$mock->append(new Response(404, [], '{}')); $worker->tick();
$last = end($history)['request'];
@ -125,7 +235,7 @@ namespace {
$assert(CloudInstance::count() === 2 && CloudOrder::find($uncertain->id)->status === 'succeeded' && User::find(1)->money === '80.02', 'Reconciliation did not recover exactly once.');
\App\Services\Config::$values['cloud_max_instances_per_user'] = 2;
try { CloudOrderService::purchase(array_replace($input, ['name' => 'vm-four', 'idempotency_key' => 'test-request-key-0004']), $actor); throw new RuntimeException('Quota bypass.'); } catch (CloudError $e) { $assert($e->httpStatus === 409, 'Quota response incorrect.'); }
$assert(User::find(1)->money === '80.02' && CloudOrder::count() === 3, 'Rejected order altered finance.');
$assert(User::find(1)->money === '80.02' && CloudOrder::count() === 4, 'Rejected order altered finance.');
$actionJob = CloudJobService::enqueue($instance, $actor, 'action', 'POST', '/actions', ['action' => 'reboot']);
$mock->append(new Response(200, [], '{"status":"succeeded","uuid":"11111111-1111-4111-8111-111111111111","state":"running"}')); $worker->tick();
$last = end($history)['request']; $signedActor = json_decode(base64_decode(strtr($last->getHeaderLine('X-Cloud-Actor'), '-_', '+/')), true);
@ -559,5 +669,40 @@ namespace {
$assert($repeat['imported'] === 0 && $repeat['existing'] === 1
&& CloudInstance::where('uuid', $manualUuid)->count() === 1,
'Repeated VM discovery duplicated or rewrote the imported instance.');
// Provider callbacks credit the wallet before the invoice bridge runs.
// That credit must be consumed once, queue one create job, and remain
// idempotent when the payment provider retries its callback.
\App\Services\Config::$values['cloud_max_instances_per_user'] = 20;
$providerOrder = CloudOrderService::purchase(array_replace($input, [
'name' => 'vm-provider-payment',
'idempotency_key' => 'test-request-key-provider-payment',
]), $actor);
$providerInvoice = CloudInvoice::where('order_id', $providerOrder->id)->first();
$providerPayment = new CloudInvoicePayment();
$providerPayment->invoice_id = $providerInvoice->id;
$providerPayment->user_id = 1;
$providerPayment->provider = 'paytaro';
$providerPayment->provider_order_no = 'PT-PROVISION-0001';
$providerPayment->idempotency_key = 'provision-provider-payment-0001';
$providerPayment->amount = '9.99';
$providerPayment->status = 'pending';
$providerPayment->created_at = $providerPayment->updated_at = time();
$providerPayment->save();
$balanceBeforeProviderCredit = CloudMoney::cents((string) User::find(1)->money);
$user = User::find(1);
$user->money = CloudMoney::decimal($balanceBeforeProviderCredit + 999);
$user->save();
$providerOutcome = CloudInvoicePaymentService::settleForProvider(
'paytaro', 'PT-PROVISION-0001');
$providerOutcomeAgain = CloudInvoicePaymentService::settleForProvider(
'paytaro', 'PT-PROVISION-0001');
$assert($providerOutcome === 'paid_invoice'
&& $providerOutcomeAgain === 'paid_invoice'
&& CloudMoney::cents((string) User::find(1)->money) === $balanceBeforeProviderCredit
&& CloudInvoice::find($providerInvoice->id)->status === 'paid'
&& CloudOrder::find($providerOrder->id)->status === 'queued'
&& CloudJob::where('order_id', $providerOrder->id)->count() === 1,
'Provider callback did not settle an opening invoice exactly once.');
echo "Cloud SQLite purchase, provisioning, refund, ambiguity, quota and tenant checks passed (crypto double only).\n";
}

@ -98,9 +98,11 @@ namespace {
$table->string('status'); $table->integer('updated_at')->default(0);
});
$schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->increments('id'); $table->string('invoice_no')->unique(); $table->integer('instance_id');
$table->integer('user_id'); $table->integer('plan_id')->nullable(); $table->integer('renewal_id')->nullable();
$table->integer('renews_expires_at'); $table->integer('due_at'); $table->string('amount');
$table->increments('id'); $table->string('invoice_no')->unique();
$table->string('purpose')->default('renewal'); $table->integer('instance_id')->nullable();
$table->integer('order_id')->nullable()->unique(); $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');
$table->integer('validity_days'); $table->integer('traffic_quota_bytes'); $table->string('status');
$table->string('paid_via')->nullable(); $table->string('payment_reference')->nullable();
$table->integer('paid_at')->nullable(); $table->integer('created_at'); $table->integer('updated_at');
@ -142,8 +144,12 @@ namespace {
$assert(CloudInvoiceService::issueDue() === 1 && CloudInvoiceService::issueDue() === 0,
'T-7 invoice generation was not idempotent.');
$invoice = CloudInvoice::first();
$assert($invoice !== null && CloudMailOutbox::count() === 1 && (string) $invoice->amount === '12.50',
'Invoice snapshot or reminder outbox is missing.');
$renewalDisplay = $invoice === null ? [] : CloudInvoiceService::display($invoice);
$assert($invoice !== null && (string) $invoice->purpose === 'renewal'
&& ($renewalDisplay['purpose'] ?? null) === 'renewal'
&& ($renewalDisplay['order_id'] ?? null) === null
&& CloudMailOutbox::count() === 1 && (string) $invoice->amount === '12.50',
'Renewal invoice type, snapshot or reminder outbox is missing.');
$actor = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false,
'can_manage' => false, 'session_id' => ''];
$paid = CloudInvoiceService::payBalance($invoice, $actor, 'invoice-balance-test-0001');

@ -40,8 +40,16 @@ namespace {
$assert(strpos($body, '409') !== false && strpos($body, 'save(') === false && strpos($body, 'transaction(') === false,
'Purchase must not debit or create an order before virtualization integration.');
$controller = file_get_contents(dirname(__DIR__) . '/app/Controllers/CloudApiController.php');
$routes = file_get_contents(dirname(__DIR__) . '/config/routes_cloud.php');
$cloudSchema = file_get_contents(dirname(__DIR__) . '/sql/cloud.sql');
$client = file_get_contents(dirname(__DIR__) . '/public/cloud/app.js');
$invoiceService = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudInvoiceService.php');
$invoicePaymentService = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudInvoicePaymentService.php');
$paymentProviders = implode("\n", [
file_get_contents(dirname(__DIR__) . '/app/Services/Payment/YipayPaymentService.php'),
file_get_contents(dirname(__DIR__) . '/app/Services/Payment/PaytaroPaymentService.php'),
file_get_contents(dirname(__DIR__) . '/app/Services/Payment/UsdtPaymentService.php'),
]);
$assert(str_contains($controller, '\'can_operate\' => $canOperate')
&& str_contains($controller, '\'can_delete\' => $canDelete')
&& str_contains($controller, '$canOperate = $canDelete && $instance->serviceAvailable()')
@ -73,5 +81,22 @@ namespace {
&& str_contains($client, 'if (payable)')
&& str_contains($client, '已超过支付截止时间'),
'Expired invoice rows must not render a balance or provider payment action.');
$assert(str_contains($routes, "['GET', 'POST'], '/invoices'")
&& str_contains($routes, "'/invoices/by-request/{key:[A-Za-z0-9_.-]+}'")
&& str_contains($controller, 'private function createProvisionInvoice')
&& str_contains($controller, "CloudOrder::where('user_id', \$actor['user_id'])")
&& str_contains($controller, "CloudInvoice::where('order_id', \$order->id)"),
'Opening invoices must use the unified invoice API and owner-scoped lost-response recovery.');
$assert(str_contains($invoicePaymentService, 'assertInvoicePaymentAllowed')
&& substr_count($paymentProviders,
'CloudInvoicePaymentService::assertInvoicePaymentAllowed($lockedUser)') === 3,
'Every online provider must recheck account restrictions inside its final row-locked order transaction.');
$assert(str_contains($cloudSchema, "purpose VARCHAR(16) NOT NULL DEFAULT 'renewal'")
&& str_contains($cloudSchema, 'order_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($cloudSchema, 'UNIQUE KEY uniq_cloud_invoice_order (order_id)')
&& str_contains($cloudSchema, 'payload_cipher LONGTEXT DEFAULT NULL')
&& str_contains($cloudSchema, 'ALTER TABLE cloud_invoices MODIFY instance_id BIGINT UNSIGNED NULL')
&& str_contains($cloudSchema, 'ALTER TABLE cloud_invoices MODIFY renews_expires_at BIGINT UNSIGNED NULL'),
'Fresh and upgraded schemas must support unpaid provisioning invoices without a fake instance.');
echo 'Cloud plan definition checks passed.' . PHP_EOL;
}

@ -154,4 +154,22 @@ try {
}
$assert(User::find(4) !== null, 'Unresolved-payment deletion was not rolled back.');
Capsule::table('user')->insert([
'id' => 5, 'email' => 'provision-invoice@example.com',
'is_admin' => 0, 'ref_by' => 0,
]);
Capsule::table('cloud_orders')->insert([
'id' => 502, 'user_id' => 5, 'status' => 'awaiting_payment',
]);
try {
(new UserDataDeletionService())->deleteUsers([5], false);
throw new RuntimeException('Account with an unpaid provisioning invoice was deleted.');
} catch (RuntimeException $error) {
$assert(str_contains($error->getMessage(), '开通中的订单'),
'Unpaid-provisioning deletion returned the wrong error.');
}
$assert(User::find(5) !== null
&& Capsule::table('cloud_orders')->where('id', 502)->exists(),
'Unpaid-provisioning deletion was not rolled back.');
echo 'Manual account deletion SQLite checks passed.' . PHP_EOL;

@ -190,6 +190,9 @@ $schema->create('configurations', function (Blueprint $table) {
$schema->create('user', function (Blueprint $table) {
$table->increments('id');
$table->decimal('money', 12, 2)->default(0);
$table->integer('enable')->default(1);
$table->integer('restrict_balance_purchase')->default(0);
$table->integer('restrict_recharge')->default(0);
$table->integer('ref_by')->default(0);
$table->dateTime('reg_date');
$table->decimal('aff_rate', 8, 2)->default(0);
@ -245,9 +248,22 @@ $schema->create('paytaro_callback_events', function (Blueprint $table) {
$table->integer('received_at');
$table->integer('processed_at');
});
$schema->create('cloud_orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('plan_id');
$table->decimal('amount', 12, 2);
$table->string('status');
});
$schema->create('cloud_invoices', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('purpose')->default('renewal');
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('due_at')->default(0);
$table->decimal('amount', 12, 2)->default(0);
$table->string('status')->default('open');
});
$schema->create('cloud_invoice_payments', function (Blueprint $table) {
$table->bigIncrements('id');
@ -287,6 +303,20 @@ Capsule::table('user')->insert([
['id' => 1, 'money' => 0, 'ref_by' => 2, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 0, 'aff_money' => 0],
['id' => 2, 'money' => 0, 'ref_by' => 0, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 10, 'aff_money' => 0],
]);
Capsule::table('cloud_orders')->insert([
['id' => 1998, 'user_id' => 1, 'plan_id' => 1,
'amount' => '42.00', 'status' => 'awaiting_payment'],
['id' => 1997, 'user_id' => 1, 'plan_id' => 1,
'amount' => '43.00', 'status' => 'awaiting_payment'],
]);
Capsule::table('cloud_invoices')->insert([
['id' => 998, 'purpose' => 'provision', 'order_id' => 1998,
'user_id' => 1, 'plan_id' => 1, 'due_at' => time() + 1800,
'amount' => '42.00', 'status' => 'open'],
['id' => 997, 'purpose' => 'provision', 'order_id' => 1997,
'user_id' => 1, 'plan_id' => 1, 'due_at' => time() + 1800,
'amount' => '43.00', 'status' => 'open'],
]);
$invoiceCreateGateway = new class {
public function createOrder(array $payload)
{

@ -58,6 +58,9 @@ $schema->create('user', function (Blueprint $table) {
$table->string('email')->default('');
$table->integer('is_admin')->default(0);
$table->decimal('money', 12, 2)->default(0);
$table->integer('enable')->default(1);
$table->integer('restrict_balance_purchase')->default(0);
$table->integer('restrict_recharge')->default(0);
$table->integer('ref_by')->default(0);
$table->dateTime('reg_date');
$table->decimal('aff_rate', 8, 2)->default(0);
@ -147,9 +150,22 @@ $schema->create('usdt_chain_transactions', function (Blueprint $table) {
$table->bigInteger('processed_at')->default(0);
$table->string('error_message')->default('');
});
$schema->create('cloud_orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('plan_id');
$table->decimal('amount', 12, 2);
$table->string('status');
});
$schema->create('cloud_invoices', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('purpose')->default('renewal');
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('due_at')->default(0);
$table->decimal('amount', 12, 2)->default(0);
$table->string('status')->default('open');
});
$schema->create('cloud_invoice_payments', function (Blueprint $table) {
$table->bigIncrements('id');
@ -181,6 +197,15 @@ Capsule::table('user')->insert([
['id' => 1, 'email' => 'buyer@example.com', 'money' => 0, 'ref_by' => 2, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 0, 'aff_money' => 0],
['id' => 2, 'email' => 'referrer@example.com', 'money' => 0, 'ref_by' => 0, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 10, 'aff_money' => 0],
]);
Capsule::table('cloud_orders')->insert([
'id' => 1999, 'user_id' => 1, 'plan_id' => 1,
'amount' => '50.00', 'status' => 'awaiting_payment',
]);
Capsule::table('cloud_invoices')->insert([
'id' => 999, 'purpose' => 'provision', 'order_id' => 1999,
'user_id' => 1, 'plan_id' => 1, 'due_at' => time() + 1800,
'amount' => '50.00', 'status' => 'open',
]);
$user = User::where('id', 1)->first();
if (method_exists(UsdtPaymentService::class, 'createPaidRegistrationOrder')) {
@ -260,6 +285,9 @@ if ($invoiceAttempt === null
|| (string) $invoiceOrder->business_order_no !== (string) $invoiceOrder->order_no) {
failUsdtTest('Native USDT invoice order did not preserve recharge scanning semantics.');
}
// The scanner bridge must retain a provider credit if its linked business
// invoice disappeared after the payment order was created.
Capsule::table('cloud_invoices')->where('id', 999)->delete();
Capsule::table('cloud_invoice_payments')->where('id', $invoiceAttempt->id)
->update(['status' => 'pending', 'updated_at' => time()]);
$invoiceTransfer = [

@ -66,7 +66,7 @@ $assert(str_contains($adminScript, 'function unixTime(value)')
'Order diagnostics must format timestamps and localize task status');
$assert(str_contains($clientScript, "makeElement('div', 'cloud-order-actions')")
&& str_contains($clientStyles, '.cloud-orders { min-height: 0;'),
'Provisioning orders must use grouped actions without inheriting the inventory minimum height');
'Billing records must use grouped actions without inheriting the inventory minimum height');
$assert(str_contains($cloudTemplate, 'data-detail-tab="operations"')
&& str_contains($cloudTemplate, 'data-detail-tab="performance"')
&& str_contains($cloudTemplate, 'data-detail-tab="traffic"'),
@ -87,9 +87,22 @@ foreach (['expired_grace', 'blocked_expired', 'deleting', 'delete_failed',
}
$assert(str_contains($sharedSidebar, 'data-view="invoices"')
&& str_contains($cloudTemplate, 'id="invoices-workspace"')
&& str_contains($sharedSidebar, '>账单信息</span>')
&& str_contains($clientScript, '/pay-balance')
&& str_contains($clientScript, '/payments'),
'Renewal invoices must support balance and online payment paths');
'Unified invoices must support balance and online payment paths');
$assert(!str_contains($sharedSidebar, 'data-view="orders"')
&& !str_contains($cloudTemplate, 'id="orders-workspace"')
&& !str_contains($clientScript, 'function loadOrders()')
&& str_contains($clientScript, "target === 'orders' || target === 'invoices'"),
'The retired user provisioning-order page must redirect old hashes into billing');
$assert(str_contains($cloudTemplate, '>生成开通账单</button>')
&& str_contains($clientScript, "api('/api/v1/invoices', { method: 'POST', body })")
&& str_contains($clientScript, '/api/v1/invoices/by-request/')
&& str_contains($clientScript, "invoice?.purpose")
&& str_contains($clientScript, 'appendProvisionInvoiceActions(invoice, detail, actions)')
&& str_contains($clientScript, "actionButton('查看实例'"),
'Instance deployment must create a recoverable invoice and expose fulfillment inside billing');
$assert(str_contains($cloudTemplate, '/theme/venix/js/qrcode.min.js')
&& str_contains($clientScript, "'weixin:', 'alipays:', 'alipayqr:'")
&& str_contains($clientScript, 'appendPaymentQr(box'),

@ -66,6 +66,9 @@ $schema->create('configurations', function (Blueprint $table) {
$schema->create('user', function (Blueprint $table) {
$table->increments('id');
$table->decimal('money', 12, 2)->default(0);
$table->integer('enable')->default(1);
$table->integer('restrict_balance_purchase')->default(0);
$table->integer('restrict_recharge')->default(0);
$table->integer('ref_by')->default(0);
$table->dateTime('reg_date');
$table->decimal('aff_rate', 8, 2)->default(0);
@ -136,9 +139,22 @@ $schema->create('yipay_refunds', function (Blueprint $table) {
$table->integer('completed_at');
$table->integer('updated_at');
});
$schema->create('cloud_orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('plan_id');
$table->decimal('amount', 12, 2);
$table->string('status');
});
$schema->create('cloud_invoices', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('purpose')->default('renewal');
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('due_at')->default(0);
$table->decimal('amount', 12, 2)->default(0);
$table->string('status')->default('open');
});
$schema->create('cloud_invoice_payments', function (Blueprint $table) {
$table->bigIncrements('id');
@ -168,6 +184,20 @@ Capsule::table('user')->insert([
['id' => 1, 'money' => 0, 'ref_by' => 2, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 0, 'aff_money' => 0],
['id' => 2, 'money' => 0, 'ref_by' => 0, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 10, 'aff_money' => 0],
]);
Capsule::table('cloud_orders')->insert([
['id' => 1998, 'user_id' => 1, 'plan_id' => 1,
'amount' => '42.00', 'status' => 'awaiting_payment'],
['id' => 1997, 'user_id' => 1, 'plan_id' => 1,
'amount' => '43.00', 'status' => 'awaiting_payment'],
]);
Capsule::table('cloud_invoices')->insert([
['id' => 998, 'purpose' => 'provision', 'order_id' => 1998,
'user_id' => 1, 'plan_id' => 1, 'due_at' => time() + 1800,
'amount' => '42.00', 'status' => 'open'],
['id' => 997, 'purpose' => 'provision', 'order_id' => 1997,
'user_id' => 1, 'plan_id' => 1, 'due_at' => time() + 1800,
'amount' => '43.00', 'status' => 'open'],
]);
$invoiceCreateGateway = new class {
public function createOrder(array $payload)
{

Loading…
Cancel
Save