diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md
index c670273a..d264074e 100644
--- a/docs/DEPLOYMENT.md
+++ b/docs/DEPLOYMENT.md
@@ -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 天宽限期内续费会恢复网络,超过宽限期则永久删除实例和面板管理的系统盘。
diff --git a/docs/INTEGRATION_PLAN.md b/docs/INTEGRATION_PLAN.md
index b93cd8a2..61155fa7 100644
--- a/docs/INTEGRATION_PLAN.md
+++ b/docs/INTEGRATION_PLAN.md
@@ -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 不关机;下一已付费周期开始时以新的累计基线归零当期用量并自动恢复网卡。
diff --git a/web/README.md b/web/README.md
index c4aa6630..2e818a8f 100644
--- a/web/README.md
+++ b/web/README.md
@@ -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`。真实数据库、宿主机与支付通道仍必须在测试环境验收后再开放销售。
diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php
index 72c5d5b5..052e3aad 100644
--- a/web/app/Controllers/CloudApiController.php
+++ b/web/app/Controllers/CloudApiController.php
@@ -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);
diff --git a/web/app/Models/CloudOrder.php b/web/app/Models/CloudOrder.php
index db241943..ec3cdc79 100644
--- a/web/app/Models/CloudOrder.php
+++ b/web/app/Models/CloudOrder.php
@@ -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'];
}
diff --git a/web/app/Services/Cloud/CloudInvoicePaymentService.php b/web/app/Services/Cloud/CloudInvoicePaymentService.php
index b87f31cc..0581d430 100644
--- a/web/app/Services/Cloud/CloudInvoicePaymentService.php
+++ b/web/app/Services/Cloud/CloudInvoicePaymentService.php
@@ -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;
diff --git a/web/app/Services/Cloud/CloudInvoiceService.php b/web/app/Services/Cloud/CloudInvoiceService.php
index 33604b71..23578a80 100644
--- a/web/app/Services/Cloud/CloudInvoiceService.php
+++ b/web/app/Services/Cloud/CloudInvoiceService.php
@@ -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)
diff --git a/web/app/Services/Cloud/CloudLifecycleService.php b/web/app/Services/Cloud/CloudLifecycleService.php
index 0693b1da..7e3b89ae 100644
--- a/web/app/Services/Cloud/CloudLifecycleService.php
+++ b/web/app/Services/Cloud/CloudLifecycleService.php
@@ -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) {
diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php
index d8857aea..c8c3dd30 100644
--- a/web/app/Services/Cloud/CloudOrderService.php
+++ b/web/app/Services/Cloud/CloudOrderService.php
@@ -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];
diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php
index 720908d2..989fc139 100644
--- a/web/app/Services/Cloud/CloudWorkerService.php
+++ b/web/app/Services/Cloud/CloudWorkerService.php
@@ -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'
diff --git a/web/app/Services/Payment/PaytaroPaymentService.php b/web/app/Services/Payment/PaytaroPaymentService.php
index e95852e6..616c05e5 100644
--- a/web/app/Services/Payment/PaytaroPaymentService.php
+++ b/web/app/Services/Payment/PaytaroPaymentService.php
@@ -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;
diff --git a/web/app/Services/Payment/UsdtPaymentService.php b/web/app/Services/Payment/UsdtPaymentService.php
index 8c06bc11..8d5d9637 100644
--- a/web/app/Services/Payment/UsdtPaymentService.php
+++ b/web/app/Services/Payment/UsdtPaymentService.php
@@ -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()
diff --git a/web/app/Services/Payment/YipayPaymentService.php b/web/app/Services/Payment/YipayPaymentService.php
index 45be2a4d..3f6fa1aa 100644
--- a/web/app/Services/Payment/YipayPaymentService.php
+++ b/web/app/Services/Payment/YipayPaymentService.php
@@ -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;
diff --git a/web/app/Services/UserDataDeletionService.php b/web/app/Services/UserDataDeletionService.php
index f583b21b..a9287526 100644
--- a/web/app/Services/UserDataDeletionService.php
+++ b/web/app/Services/UserDataDeletionService.php
@@ -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 ([
diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php
index 07f072b8..23b32bc8 100644
--- a/web/config/routes_cloud.php
+++ b/web/config/routes_cloud.php
@@ -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');
diff --git a/web/public/cloud/admin.js b/web/public/cloud/admin.js
index 625d2f67..6721e5d6 100644
--- a/web/public/cloud/admin.js
+++ b/web/public/cloud/admin.js
@@ -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);
diff --git a/web/public/cloud/app.js b/web/public/cloud/app.js
index 7ac1b710..7e487be2 100644
--- a/web/public/cloud/app.js
+++ b/web/public/cloud/app.js
@@ -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();
diff --git a/web/resources/views/venix/admin/cloud/orders.tpl b/web/resources/views/venix/admin/cloud/orders.tpl
index f6bbb11a..3a3b99a2 100644
--- a/web/resources/views/venix/admin/cloud/orders.tpl
+++ b/web/resources/views/venix/admin/cloud/orders.tpl
@@ -1,2 +1,2 @@
-{assign var=admin_title value='开通订单'}{assign var=admin_active value='cloud_orders'}{include file='admin/static_header.tpl'}
- 开通套餐按设置的账期生效;到期前 7 天生成续费账单,用户可以使用账户余额或已启用的在线支付渠道结清。失败或不确定的开通任务需核查实际宿主机状态,不要重复创建或扣款。 正在加载… 用户提交部署后先生成开通账单,只有账单支付成功才会在此进入创建队列。失败或不确定的任务需核查实际宿主机状态,不要重复创建或扣款。 正在加载…余额开通订单
订单 用户 套餐 金额 状态 实例 / 任务 时间 / 错误 实例开通任务
任务 用户 套餐 金额 状态 实例 / 引擎任务 时间 / 错误
余额支付后由后台持续开通;关闭页面不会取消任务。失败会按订单状态退款,失败原因在此显示。
实例到期前 7 天自动生成账单;到期后立即停用网络,续费成功会自动恢复。到期满 3 天仍未支付,实例及系统盘将被永久删除。
部署实例时先生成开通账单,支付完成后才开始创建;实例到期前 7 天会自动生成续费账单。实例到期后立即停用网络,到期满 3 天仍未续费,实例及系统盘将被永久删除。
正在加载…