feat(cloud): add paid automatic backup controls

go
codex 3 weeks ago
parent c4fa9d0f56
commit 7df662415b

@ -95,7 +95,7 @@ php xcat cloudRepairInstanceMetadata --apply
后台 `/admin/object-storage` 可配置一个全局 S3 兼容对象存储应用,适用于 AWS S3、MinIO 及实现 AWS Signature Version 4 的兼容服务。该功能复用业务库已有的 `configurations` 表,不需要导入新表。Endpoint 必须是带有效证书的 HTTPS origin;MinIO 通常选择路径寻址,AWS S3 通常选择虚拟主机寻址。
Access Key ID 与 Secret Access Key 只在超级管理员提交时进入 PHP,使用 `cloud_data_key` 的独立用途密钥密封后保存,读取页面不会回显。修改任一配置或停用应用都会清除原就绪标记;必须重新执行“验证连接并启用”。连接验证只发送签名的 `HeadBucket` 请求,需要目标 Bucket 的 `s3:ListBucket` 权限,不上传、覆盖或删除对象。管理员虚拟机管理已接入完整系统盘备份和新实例恢复,目标可以是原宿主机或其他合格宿主机;运行账户还需要配置 `vm-backups/` 与 `vm-migrations/` 前缀范围内的 multipart 上传、`GetObject`、`HeadObject` 和 `DeleteObject` 权限。成功维护迁移会由普通任务 Worker 自动回收隐藏迁移传输包;版本控制 Bucket 仍须为 `vm-migrations/` 配置非当前版本过期策略。当前不包含增量链和普通备份自动保留策略,具体安全边界见 `docs/PORTABLE_VM_BACKUPS.md`。
Access Key ID 与 Secret Access Key 只在超级管理员提交时进入 PHP,使用 `cloud_data_key` 的独立用途密钥密封后保存,读取页面不会回显。修改任一配置或停用应用都会清除原就绪标记;必须重新执行“验证连接并启用”。连接验证只发送签名的 `HeadBucket` 请求,需要目标 Bucket 的 `s3:ListBucket` 权限,不上传、覆盖或删除对象。管理员虚拟机管理已接入完整系统盘备份和新实例恢复,目标可以是原宿主机或其他合格宿主机;用户自动备份使用同一对象存储,在实例设置中按每天或每周调度并保留最多两份。运行账户还需要配置 `vm-backups/` 与 `vm-migrations/` 前缀范围内的 multipart 上传、`GetObject`、`HeadObject` 和 `DeleteObject` 权限。成功维护迁移会由普通任务 Worker 自动回收隐藏迁移传输包;版本控制 Bucket 仍须为 `vm-migrations/` 配置非当前版本过期策略。当前不包含增量链和管理员手工备份的自动保留策略,具体安全边界见 `docs/PORTABLE_VM_BACKUPS.md`。
生产环境应为面板创建独立服务账户,把权限限制到配置的 Bucket 和备份前缀。数据库备份必须与原始 `cloud_data_key` 一起保管,重新生成主密钥无法恢复全局配置及各备份冻结的对象存储凭据。

@ -12,6 +12,14 @@
- 对象内容是原 qcow2 数据。传输强制 HTTPS,但当前版本不额外执行客户端加密;生产 Bucket 应启用服务端加密、版本控制、最小权限和不完整 multipart 生命周期清理。
- 系统盘内容保持不变,因此来宾系统数据、账户、SSH host key 和应用配置也保持不变。它是从备份创建新实例,不是重装一个空白操作系统。
## 用户自动备份与计费
用户在部署时购买自动备份时,首个服务周期与实例账单一并结算。运行中的实例也可以在实例设置中开启:当前服务周期按剩余秒数向上取整计费,已经提前购买但尚未包含备份的后续服务周期按每期完整价格结算。余额扣款、已支付审计账单、订阅和每个服务周期的不可变权益记录在同一事务内完成;同一个幂等请求不会重复扣款。
调度只在订阅已开启且计划执行时间落入已支付权益时运行,并在创建备份的事务内再次核对。用户可以选择每天或每周在太平洋时间 00:00 执行,保留上限为两份。关闭会立即停止新自动备份并从下一张续费账单移除备份费用,不退还当前周期费用,也不删除当前已付权益或已有备份;同一已付周期重新开启不重复收费。续费成功后会为新服务周期写入独立权益,历史部署快照不作为当前计费授权。
用户只能在源实例的设置页把自动备份恢复到原实例;全局“云备份”页面可以从已有备份创建新实例。自动备份当前仍是完整系统盘对象,不是增量链。
## 恢复为新实例
恢复目标必须满足以下条件:

@ -10,7 +10,7 @@
- 多宿主机、资源池、容量策略、reservation、具体公网 IP 账本、多 CIDR、云镜像、救援 ISO、快照、防火墙、指标与控制台入口。
- 管理员工单 Telegram 通知;普通用户仍只在网页处理工单。
- 公开产品落地页,以及后台统一维护、带草稿和发布历史的全局服务条款与隐私政策页面;法律内容不按域名拆分。
- 后台全局 S3 兼容对象存储应用配置、密钥密封和只读连接验证;管理员可把受支持实例的完整系统盘备份上传到对象存储,并在另一台 `bridge:br0` 宿主机使用全新公网 IP 创建独立免计费实例。全局备份库独立于源实例生命周期,源实例删除后仍可恢复或清理对象;增量链和自动保留策略暂未接入。
- 后台全局 S3 兼容对象存储应用配置、密钥密封和只读连接验证;管理员可把受支持实例的完整系统盘备份上传到对象存储,并在另一台 `bridge:br0` 宿主机使用全新公网 IP 创建独立免计费实例。普通用户可按服务周期购买自动备份,在实例设置中选择每天或每周执行并保留最多两份;全局备份库独立于源实例生命周期,源实例删除后仍可恢复或清理对象。增量链和管理员手工备份的自动保留策略暂未接入。
## 删除

@ -8,7 +8,7 @@ use App\Services\Config;
/** Initializes only the clean-break PHP business and Agent log schemas. */
final class CloudSetup
{
private const SCHEMA_VERSION = 'go-agent-wss-v7-automatic-backups';
private const SCHEMA_VERSION = 'go-agent-wss-v8-backup-entitlements';
private const MAIN_TABLES = [
'cloud_regions', 'cloud_network_lines', 'cloud_resource_pools',
'cloud_hosts', 'cloud_host_agents',
@ -23,7 +23,8 @@ final class CloudSetup
'cloud_instance_firewall_versions', 'cloud_instance_firewall_rules',
'cloud_platform_test_policy_state',
'cloud_platform_test_policy_rules', 'cloud_instance_snapshots',
'cloud_backup_subscriptions', 'cloud_instance_backups',
'cloud_backup_subscriptions', 'cloud_backup_period_entitlements',
'cloud_instance_backups',
'cloud_backup_restores', 'cloud_backup_recoveries',
'cloud_instance_migrations', 'cloud_migration_bundle_artifacts',
'cloud_instance_runtime', 'cloud_orders', 'cloud_order_items',
@ -73,6 +74,12 @@ final class CloudSetup
'timezone', 'price', 'currency', 'price_version', 'next_run_at',
'last_scheduled_at', 'last_backup_id', 'created_at', 'updated_at',
],
'cloud_backup_period_entitlements' => [
'id', 'subscription_id', 'instance_id', 'service_period_id',
'user_id', 'offer_id', 'invoice_id', 'starts_at', 'ends_at',
'amount', 'full_period_price', 'currency', 'price_version',
'source', 'paid_at', 'created_at', 'updated_at',
],
'cloud_instance_backups' => [
'id', 'backup_key', 'source_instance_id', 'source_host_id',
'user_id', 'source_uuid', 'name', 'purpose', 'source',
@ -153,6 +160,10 @@ final class CloudSetup
'chk_cloud_backup_subscription_weekday',
'chk_cloud_backup_subscription_retention',
],
'cloud_backup_period_entitlements' => [
'chk_cloud_backup_entitlement_source',
'chk_cloud_backup_entitlement_window',
],
'cloud_invoice_payments' => [
'chk_cloud_invoice_payment_status',
],
@ -188,6 +199,13 @@ final class CloudSetup
'cloud_backup_subscription_due',
'cloud_backup_subscription_owner',
],
'cloud_backup_period_entitlements' => [
'PRIMARY', 'cloud_backup_entitlement_period',
'cloud_backup_entitlement_subscription',
'cloud_backup_entitlement_instance',
'cloud_backup_entitlement_owner',
'cloud_backup_entitlement_invoice',
],
'cloud_instance_backups' => [
'PRIMARY', 'cloud_instance_backup_key',
'cloud_instance_backup_object', 'cloud_instance_backup_schedule',

@ -13,6 +13,7 @@ use App\Services\Auth;
use App\Services\AdminCsrf;
use App\Services\Config;
use App\Services\Cloud\CloudAccess;
use App\Services\Cloud\CloudAutomaticBackupBillingService;
use App\Services\Cloud\CloudAutomaticBackupService;
use App\Services\Cloud\CloudBackupService;
use App\Services\Cloud\CloudDeploymentPageService;
@ -1054,9 +1055,76 @@ final class CloudApiController
$instance, $actor, CloudInput::object($request)
)
: CloudAutomaticBackupService::settings($instance, $actor);
$value['billing'] = $this->automaticBackupBilling(
CloudAutomaticBackupBillingService::quote(
$instance,
$this->user($request)
)
);
return $this->json($response, $value);
}
/** Buy the missing paid periods and enable future automatic-backup renewal. */
public function enableAutomaticBackup($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$quote = CloudAutomaticBackupBillingService::enable(
$instance,
$this->user($request),
$actor,
CloudInput::object($request)
);
$value = CloudAutomaticBackupService::settings($instance, $actor);
$value['billing'] = $this->automaticBackupBilling($quote);
$value['invoice_id'] = $quote['invoice_id'] ?? null;
$value['charged_amount'] = $quote['charged_amount'] ?? '0.00';
return $this->json($response, $value);
}
/** Pause scheduling and remove automatic backup from the next renewal. */
public function disableAutomaticBackup($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$quote = CloudAutomaticBackupBillingService::disable(
$instance,
$this->user($request),
$actor
);
$value = CloudAutomaticBackupService::settings($instance, $actor);
$value['billing'] = $this->automaticBackupBilling($quote);
return $this->json($response, $value);
}
private function automaticBackupBilling(array $quote): array
{
$entitlement = is_array($quote['entitlement'] ?? null)
? $quote['entitlement'] : [];
return [
'state' => (string) ($quote['state'] ?? 'inactive'),
'subscription_enabled' =>
($quote['schedule_enabled'] ?? false) === true,
'renew_next_period' =>
($quote['renew_next_period'] ?? false) === true,
'entitlement_active' =>
($entitlement['active'] ?? false) === true,
'entitlement_paid_until' => $entitlement['paid_until'] ?? null,
'activation_amount' => (string) ($quote['activation_amount'] ?? ''),
'full_period_price' =>
(string) ($quote['full_period_amount'] ?? ''),
'currency' => (string) ($quote['currency'] ?? 'USD'),
'current_period_ends_at' => $quote['period_ends_at'] ?? null,
'future_period_count' =>
max(0, (int) ($quote['future_period_count'] ?? 0)),
'balance_sufficient' =>
($quote['balance_sufficient'] ?? false) === true,
'can_enable' => ($quote['can_enable'] ?? false) === true,
'can_disable' => ($quote['can_disable'] ?? false) === true,
'price_version' => max(0, (int) ($quote['price_version'] ?? 0)),
];
}
/** Queue a destructive in-place system-disk recovery. */
public function restoreAutomaticBackup($request, $response, $args)
{

@ -35,6 +35,7 @@ final class CloudApi
|| preg_match('#^/api/v1/vms/[0-9]+/(?:upgrade-options|upgrade)$#D', $path) === 1
|| preg_match('#^/api/v1/vms/[0-9]+/firewall$#D', $path) === 1
|| preg_match('#^/api/v1/vms/[0-9]+/snapshots(?:/[0-9a-f]{32}(?:/restore)?)?$#D', $path) === 1
|| preg_match('#^/api/v1/vms/[0-9]+/automatic-backup(?:/(?:enable|disable))?$#D', $path) === 1
|| preg_match('#^/api/v1/vms/[0-9]+/metrics$#D', $path) === 1
|| preg_match('#^/api/v1/vms/[0-9]+/display-name$#D', $path) === 1
|| $path === '/api/v1/announcements'

@ -0,0 +1,28 @@
<?php
namespace App\Models;
/** Immutable proof that automatic backup was paid for one service period. */
final class CloudBackupPeriodEntitlement extends Model
{
protected $connection = 'default';
protected $table = 'cloud_backup_period_entitlements';
protected $casts = [
'id' => 'int',
'subscription_id' => 'int',
'service_period_id' => 'int',
'instance_id' => 'int',
'user_id' => 'int',
'offer_id' => 'int',
'invoice_id' => 'int',
'starts_at' => 'int',
'ends_at' => 'int',
'full_period_price' => 'decimal:2',
'amount' => 'decimal:2',
'price_version' => 'int',
'paid_at' => 'int',
'created_at' => 'int',
'updated_at' => 'int',
];
}

@ -25,7 +25,7 @@ final class CloudAdminBillingService
private const MAX_PER_PAGE = 100;
private const DETAIL_PAYMENT_LIMIT = 100;
private const PURPOSES = [
'provision', 'renewal', 'upgrade', 'ip_change', 'recharge',
'provision', 'renewal', 'upgrade', 'ip_change', 'backup_addon', 'recharge',
];
private const FINANCIAL_STATUSES = [
'open', 'overdue', 'paid', 'refunded', 'expired', 'void',

@ -0,0 +1,665 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudBackupPeriodEntitlement;
use App\Models\CloudBackupSubscription;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudInvoiceItem;
use App\Models\CloudOffer;
use App\Models\CloudServicePeriod;
use App\Models\User;
/** Period-aligned wallet billing for the optional automatic-backup service. */
final class CloudAutomaticBackupBillingService
{
public const PURPOSE = 'backup_addon';
/** Quote every paid VM period that still lacks automatic-backup cover. */
public static function quote(
CloudInstance $instance,
User $user,
?int $now = null
): array {
$now ??= time();
$offer = CloudOffer::where('id', (int) $instance->offer_id)
->where('currency', 'USD')->first();
$periods = CloudServicePeriod::where(
'instance_id', (int) $instance->id
)->whereIn('status', ['active', 'exhausted', 'scheduled'])
->where('ends_at', '>', $now)
->orderBy('starts_at')->orderBy('id')->get();
$periodIds = $periods->pluck('id')->map(
static fn ($id): int => (int) $id
)->all();
$subscription = CloudBackupSubscription::where(
'instance_id', (int) $instance->id
)->first();
$entitlements = $periodIds === [] ? collect()
: CloudBackupPeriodEntitlement::whereIn(
'service_period_id', $periodIds
)->get();
return self::buildQuote(
$instance,
$user,
$offer,
$periods,
$subscription,
$entitlements,
$now
);
}
/**
* Enable automatic backup and buy cover for every already-paid VM period.
*
* Wallet debit, audit invoice, subscription state and immutable period
* entitlements share one transaction. The payment reference derived from
* the request key makes browser retries return the first outcome.
*/
public static function enable(
CloudInstance $instance,
User $user,
array $actor,
array $input,
?int $now = null
): array {
CloudInput::only($input, ['expected_amount']);
self::assertActor($actor, $user);
$expected = $input['expected_amount'] ?? null;
if (!is_string($expected)) {
throw new CloudError('请确认自动备份开通金额');
}
$expectedCents = CloudMoney::cents($expected);
$requestKey = self::requestKey($actor);
$paymentReference = 'backup-addon-'
. substr(hash('sha256', $requestKey), 0, 48);
$now ??= time();
return $instance->getConnection()->transaction(function () use (
$instance,
$user,
$expectedCents,
$paymentReference,
$now
): array {
$lockedUser = User::where('id', (int) $user->id)
->lockForUpdate()->first();
$locked = CloudInstance::where('id', (int) $instance->id)
->lockForUpdate()->first();
if ($lockedUser === null || $locked === null) {
throw new CloudError('账户或虚拟机不存在', 404);
}
self::assertOwner($locked, $lockedUser);
$existing = CloudInvoice::where('purpose', self::PURPOSE)
->where('instance_id', (int) $locked->id)
->where('user_id', (int) $lockedUser->id)
->where('payment_reference', $paymentReference)
->lockForUpdate()->first();
if ($existing !== null) {
if ((string) $existing->status !== 'paid'
|| strtoupper((string) $existing->currency) !== 'USD') {
throw new CloudError('自动备份开通账单状态异常', 409);
}
if (CloudMoney::cents((string) $existing->amount)
!== $expectedCents) {
throw new CloudError(
'同一请求标识不能用于不同的自动备份金额',
409
);
}
return self::enableResult(
$locked,
$lockedUser,
$existing,
CloudMoney::cents((string) $existing->amount),
$now
);
}
// Lock the commercial rows before quoting so concurrent enable,
// renewal and plan changes cannot charge different snapshots.
$periods = CloudServicePeriod::where(
'instance_id', (int) $locked->id
)->whereIn('status', ['active', 'exhausted', 'scheduled'])
->where('ends_at', '>', $now)->orderBy('starts_at')
->orderBy('id')->lockForUpdate()->get();
$offer = CloudOffer::where('id', (int) $locked->offer_id)
->where('currency', 'USD')->lockForUpdate()->first();
$subscription = CloudBackupSubscription::where(
'instance_id', (int) $locked->id
)->lockForUpdate()->first();
$periodIds = $periods->pluck('id')->map(
static fn ($id): int => (int) $id
)->all();
$entitlements = $periodIds === [] ? collect()
: CloudBackupPeriodEntitlement::whereIn(
'service_period_id', $periodIds
)->lockForUpdate()->get();
$quote = self::buildQuote(
$locked,
$lockedUser,
$offer,
$periods,
$subscription,
$entitlements,
$now
);
if ((string) $quote['state'] === 'active') {
throw new CloudError('自动备份已经开启,请勿重复提交', 409);
}
$chargeCents = CloudMoney::cents($quote['activation_amount']);
if ((int) $offer->status !== 1 && $quote['lines'] !== []) {
throw new CloudError('实例的自动备份销售方案当前不可用', 409);
}
if ($chargeCents !== $expectedCents) {
throw new CloudError('自动备份价格已变化,请刷新后重试', 409);
}
$balanceCents = CloudMoney::cents((string) $lockedUser->money);
if ($balanceCents < $chargeCents) {
throw new CloudError('账户余额不足', 409);
}
if ($subscription === null) {
$subscription = new CloudBackupSubscription();
$subscription->instance_id = (int) $locked->id;
$subscription->user_id = (int) $lockedUser->id;
$subscription->frequency = 'daily';
$subscription->weekday = 0;
$subscription->retention_count =
CloudAutomaticBackupService::MAX_RETENTION;
$subscription->timezone =
CloudAutomaticBackupService::TIMEZONE;
$subscription->last_scheduled_at = null;
$subscription->last_backup_id = null;
$subscription->created_at = $now;
} elseif ((int) $subscription->user_id !== (int) $lockedUser->id) {
throw new CloudError('自动备份订阅归属不一致', 409);
}
$subscription->offer_id = (int) $offer->id;
$subscription->enabled = true;
$subscription->renew_next_period = true;
$subscription->price = (string) $quote['full_period_amount'];
$subscription->currency = 'USD';
$subscription->price_version = (int) $quote['price_version'];
$subscription->next_run_at =
CloudAutomaticBackupService::nextRunAt(
$now,
(string) $subscription->frequency,
(int) $subscription->weekday
);
$subscription->updated_at = $now;
$subscription->save();
$invoice = new CloudInvoice();
$invoice->invoice_no = 'VC' . gmdate('YmdHis', $now)
. strtoupper(bin2hex(random_bytes(8)));
$invoice->purpose = self::PURPOSE;
$invoice->instance_id = (int) $locked->id;
$invoice->order_id = null;
$invoice->user_id = (int) $lockedUser->id;
$invoice->plan_id = $locked->plan_id;
$invoice->offer_id = (int) $offer->id;
$invoice->renewal_id = null;
$invoice->renews_expires_at = null;
$invoice->due_at = $now;
$invoice->amount = CloudMoney::decimal($chargeCents);
$invoice->currency = 'USD';
$invoice->validity_days = 0;
$invoice->traffic_quota_bytes = 0;
$invoice->status = 'paid';
$invoice->paid_via = 'balance';
$invoice->payment_reference = $paymentReference;
$invoice->paid_at = $now;
$invoice->created_at = $invoice->updated_at = $now;
$invoice->save();
$item = new CloudInvoiceItem();
$item->invoice_id = (int) $invoice->id;
$item->order_item_id = null;
$item->code = 'automatic_backup_activation';
$item->label = '自动备份服务开通';
$item->amount = CloudMoney::decimal($chargeCents);
$item->currency = 'USD';
$item->snapshot_json = json_encode([
'version' => 1,
'full_period_amount' => $quote['full_period_amount'],
'price_version' => (int) $quote['price_version'],
'periods' => $quote['lines'],
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
| JSON_THROW_ON_ERROR);
$item->created_at = $now;
$item->save();
foreach ($quote['lines'] as $line) {
$entitlement = new CloudBackupPeriodEntitlement();
$entitlement->subscription_id = (int) $subscription->id;
$entitlement->service_period_id =
(int) $line['service_period_id'];
$entitlement->instance_id = (int) $locked->id;
$entitlement->user_id = (int) $lockedUser->id;
$entitlement->offer_id = (int) $offer->id;
$entitlement->invoice_id = (int) $invoice->id;
$entitlement->source = 'addon';
$entitlement->starts_at = (int) $line['starts_at'];
$entitlement->ends_at = (int) $line['ends_at'];
$entitlement->full_period_price =
(string) $quote['full_period_amount'];
$entitlement->amount = (string) $line['amount'];
$entitlement->currency = 'USD';
$entitlement->price_version =
(int) $subscription->price_version;
$entitlement->paid_at = $now;
$entitlement->created_at = $entitlement->updated_at = $now;
$entitlement->save();
}
$lockedUser->money = CloudMoney::decimal(
$balanceCents - $chargeCents
);
$lockedUser->save();
CloudInvoiceService::refreshRenewalAfterBackupPolicyLocked(
$locked,
$now
);
return self::enableResult(
$locked,
$lockedUser,
$invoice,
$chargeCents,
$now
);
}, 3);
}
/** Pause scheduling and remove the service from future renewal quotes. */
public static function disable(
CloudInstance $instance,
User $user,
array $actor,
?int $now = null
): array {
self::assertActor($actor, $user);
$now ??= time();
return $instance->getConnection()->transaction(function () use (
$instance,
$user,
$now
): array {
$lockedUser = User::where('id', (int) $user->id)
->lockForUpdate()->first();
$locked = CloudInstance::where('id', (int) $instance->id)
->lockForUpdate()->first();
if ($lockedUser === null || $locked === null) {
throw new CloudError('账户或虚拟机不存在', 404);
}
self::assertOwner($locked, $lockedUser);
$subscription = CloudBackupSubscription::where(
'instance_id', (int) $locked->id
)->lockForUpdate()->first();
if ($subscription === null
|| (int) $subscription->user_id !== (int) $lockedUser->id) {
throw new CloudError('该实例尚未开通自动备份', 409);
}
if ((bool) $subscription->enabled
|| (bool) $subscription->renew_next_period) {
$subscription->enabled = false;
$subscription->renew_next_period = false;
$subscription->updated_at = $now;
$subscription->save();
CloudInvoiceService::refreshRenewalAfterBackupPolicyLocked(
$locked,
$now
);
}
return self::quote($locked, $lockedUser, $now);
}, 3);
}
private static function enableResult(
CloudInstance $instance,
User $user,
CloudInvoice $invoice,
int $chargedCents,
int $now
): array {
$quote = self::quote($instance, $user, $now);
return $quote + [
'invoice_id' => (string) $invoice->id,
'charged_amount' => CloudMoney::decimal($chargedCents),
];
}
private static function requestKey(array $actor): string
{
$key = $actor['request_idempotency_key'] ?? null;
if (!is_string($key)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $key) !== 1) {
throw new CloudError('缺少有效的幂等请求标识', 400);
}
return $key;
}
private static function assertActor(array $actor, User $user): void
{
if ((int) ($actor['user_id'] ?? 0) !== (int) $user->id) {
throw new CloudError('只能管理自己的自动备份', 403);
}
}
/** Build a quote from rows that may already be locked by the caller. */
private static function buildQuote(
CloudInstance $instance,
User $user,
?CloudOffer $offer,
$periods,
?CloudBackupSubscription $subscription,
$entitlements,
int $now
): array {
self::assertOwner($instance, $user);
if ((int) $user->enable !== 1) {
throw new CloudError('账户不可用', 403);
}
if ((string) $instance->status !== 'active'
|| (string) $instance->service_status !== 'active'
|| $instance->expires_at === null
|| (int) $instance->expires_at <= $now
|| CloudInvoiceService::instanceDeleting($instance)) {
throw new CloudError('实例当前不能开通自动备份', 409);
}
if ($offer === null
|| strtoupper((string) $offer->currency) !== 'USD') {
throw new CloudError('实例的自动备份销售方案当前不可用', 409);
}
if ($periods->isEmpty()) {
throw new CloudError('实例缺少可计费的服务周期', 409);
}
if ($subscription !== null
&& ((int) $subscription->instance_id !== (int) $instance->id
|| (int) $subscription->user_id !== (int) $user->id
|| (int) $subscription->offer_id !== (int) $offer->id
|| strtoupper((string) $subscription->currency) !== 'USD')) {
throw new CloudError('自动备份订阅账本不一致', 409);
}
$periodById = [];
foreach ($periods as $period) {
$periodById[(int) $period->id] = $period;
}
foreach ($entitlements as $entitlement) {
$period = $periodById[(int) $entitlement->service_period_id]
?? null;
if ($subscription === null || $period === null
|| (int) $entitlement->subscription_id
!== (int) $subscription->id
|| (int) $entitlement->instance_id !== (int) $instance->id
|| (int) $entitlement->user_id !== (int) $user->id
|| (int) $entitlement->starts_at !== (int) $period->starts_at
|| (int) $entitlement->ends_at !== (int) $period->ends_at
|| strtoupper((string) $entitlement->currency) !== 'USD') {
throw new CloudError('自动备份周期权益账本不一致', 409);
}
}
$fullPriceCents = CloudMoney::cents((string) ($subscription === null
? $offer->backup_price : $subscription->price));
$priceVersion = $subscription === null
? (int) $offer->price_version
: (int) $subscription->price_version;
$covered = $entitlements->mapWithKeys(
static fn ($row): array => [(int) $row->service_period_id => true]
)->all();
$activationCents = 0;
$futureCount = 0;
$lines = [];
foreach ($periods as $period) {
$periodId = (int) $period->id;
$startsAt = (int) $period->starts_at;
$endsAt = (int) $period->ends_at;
if ($startsAt >= $endsAt || isset($covered[$periodId])) {
continue;
}
$amountCents = $fullPriceCents;
$kind = 'future_period';
if ($startsAt <= $now && $now < $endsAt) {
$kind = 'current_period';
$amountCents = self::proratedCents(
$fullPriceCents,
$endsAt - $now,
$endsAt - $startsAt
);
} else {
$futureCount++;
}
$activationCents += $amountCents;
$lines[] = [
'service_period_id' => (string) $periodId,
'kind' => $kind,
'starts_at' => $startsAt,
'ends_at' => $endsAt,
'amount' => CloudMoney::decimal($amountCents),
];
}
$activeEntitlement = $entitlements->first(
static fn ($row): bool => (int) $row->starts_at <= $now
&& (int) $row->ends_at > $now
);
$paidUntil = $entitlements->max('ends_at');
$balanceCents = CloudMoney::cents((string) $user->money);
$scheduleEnabled = $subscription !== null
&& (bool) $subscription->enabled;
$isActive = $scheduleEnabled && $activeEntitlement !== null;
return [
'state' => $isActive ? 'active'
: ($activeEntitlement === null ? 'inactive' : 'paused'),
'schedule_enabled' => $scheduleEnabled,
'renew_next_period' => $subscription !== null
&& (bool) $subscription->renew_next_period,
'entitlement' => [
'active' => $activeEntitlement !== null,
'paid_until' => $paidUntil === null ? null : (int) $paidUntil,
],
'activation_amount' => CloudMoney::decimal($activationCents),
'full_period_amount' => CloudMoney::decimal($fullPriceCents),
'currency' => 'USD',
'period_ends_at' => (int) $periods->first()->ends_at,
'future_period_count' => $futureCount,
'lines' => $lines,
'balance' => CloudMoney::decimal($balanceCents),
'balance_sufficient' => $balanceCents >= $activationCents,
'can_enable' => !$isActive
&& $balanceCents >= $activationCents
&& ((int) $offer->status === 1 || $lines === []),
'can_disable' => $scheduleEnabled,
'price_version' => $priceVersion,
];
}
/** Record the automatic-backup item bought with initial provisioning. */
public static function grantProvisionEntitlementLocked(
CloudInstance $instance,
CloudServicePeriod $period,
CloudInvoice $invoice,
?CloudBackupSubscription $subscription,
int $now
): ?CloudBackupPeriodEntitlement {
$item = self::backupItem($invoice);
if ($item === null && $subscription === null) {
return null;
}
if ($item === null || $subscription === null
|| (string) $invoice->purpose !== 'provision'
|| (string) $invoice->status !== 'paid'
|| $invoice->paid_at === null
|| $invoice->order_id === null
|| (int) $period->order_id !== (int) $invoice->order_id) {
throw new CloudError('实例开通的自动备份权益账本不一致', 409);
}
return self::grantEntitlementLocked(
$instance,
$period,
$invoice,
$item,
$subscription,
'provision',
$now
);
}
/** Record the automatic-backup item settled with one renewal period. */
public static function grantRenewalEntitlementLocked(
CloudInstance $instance,
CloudServicePeriod $period,
CloudInvoice $invoice,
int $now
): ?CloudBackupPeriodEntitlement {
$item = self::backupItem($invoice);
if ($item === null) {
return null;
}
$subscription = CloudBackupSubscription::where(
'instance_id', (int) $instance->id
)->lockForUpdate()->first();
if ($subscription === null
|| (string) $invoice->purpose !== 'renewal'
|| !in_array((string) $invoice->status,
['open', 'overdue', 'paid'], true)
|| $invoice->instance_id === null
|| (int) $invoice->instance_id !== (int) $instance->id
|| $period->renewal_id === null) {
throw new CloudError('实例续费的自动备份权益账本不一致', 409);
}
$snapshot = json_decode((string) $item->snapshot_json, true);
if (!is_array($snapshot)
|| (int) ($snapshot['subscription_id'] ?? 0)
!== (int) $subscription->id) {
throw new CloudError('自动备份续费明细缺少订阅快照', 409);
}
return self::grantEntitlementLocked(
$instance,
$period,
$invoice,
$item,
$subscription,
'renewal',
$now
);
}
private static function backupItem(
CloudInvoice $invoice
): ?CloudInvoiceItem {
$items = CloudInvoiceItem::where('invoice_id', (int) $invoice->id)
->where('code', 'automatic_backup')->lockForUpdate()->get();
if ($items->count() > 1) {
throw new CloudError('自动备份账单费用明细重复', 409);
}
return $items->first();
}
private static function grantEntitlementLocked(
CloudInstance $instance,
CloudServicePeriod $period,
CloudInvoice $invoice,
CloudInvoiceItem $item,
CloudBackupSubscription $subscription,
string $source,
int $now
): CloudBackupPeriodEntitlement {
$amountCents = CloudMoney::cents((string) $item->amount);
$fullPriceCents = CloudMoney::cents((string) $subscription->price);
if ((int) $period->instance_id !== (int) $instance->id
|| (int) $period->user_id !== (int) $instance->user_id
|| (int) $invoice->user_id !== (int) $instance->user_id
|| (int) $subscription->instance_id !== (int) $instance->id
|| (int) $subscription->user_id !== (int) $instance->user_id
|| (int) $subscription->offer_id !== (int) $instance->offer_id
|| strtoupper((string) $invoice->currency) !== 'USD'
|| strtoupper((string) $item->currency) !== 'USD'
|| strtoupper((string) $subscription->currency) !== 'USD'
|| $amountCents !== $fullPriceCents
|| (int) $period->starts_at >= (int) $period->ends_at) {
throw new CloudError('自动备份周期权益关联不一致', 409);
}
$existing = CloudBackupPeriodEntitlement::where(
'service_period_id', (int) $period->id
)->lockForUpdate()->first();
if ($existing !== null) {
if ((int) $existing->subscription_id !== (int) $subscription->id
|| (int) $existing->instance_id !== (int) $instance->id
|| (int) $existing->user_id !== (int) $instance->user_id
|| (int) $existing->offer_id !== (int) $subscription->offer_id
|| (int) $existing->invoice_id !== (int) $invoice->id
|| (int) $existing->starts_at !== (int) $period->starts_at
|| (int) $existing->ends_at !== (int) $period->ends_at
|| CloudMoney::cents((string) $existing->amount)
!== $amountCents
|| CloudMoney::cents(
(string) $existing->full_period_price
) !== $fullPriceCents
|| strtoupper((string) $existing->currency) !== 'USD'
|| (int) $existing->price_version
!== (int) $subscription->price_version
|| (string) $existing->source !== $source) {
throw new CloudError('自动备份周期权益重复记录不一致', 409);
}
return $existing;
}
$entitlement = new CloudBackupPeriodEntitlement();
$entitlement->subscription_id = (int) $subscription->id;
$entitlement->instance_id = (int) $instance->id;
$entitlement->service_period_id = (int) $period->id;
$entitlement->user_id = (int) $instance->user_id;
$entitlement->offer_id = (int) $subscription->offer_id;
$entitlement->invoice_id = (int) $invoice->id;
$entitlement->starts_at = (int) $period->starts_at;
$entitlement->ends_at = (int) $period->ends_at;
$entitlement->amount = CloudMoney::decimal($amountCents);
$entitlement->full_period_price =
CloudMoney::decimal($fullPriceCents);
$entitlement->currency = 'USD';
$entitlement->price_version = (int) $subscription->price_version;
$entitlement->source = $source;
$entitlement->paid_at = $invoice->paid_at === null
? $now : (int) $invoice->paid_at;
$entitlement->created_at = $entitlement->updated_at = $now;
$entitlement->save();
return $entitlement;
}
private static function proratedCents(
int $fullPriceCents,
int $remainingSeconds,
int $periodSeconds
): int {
if ($fullPriceCents === 0) {
return 0;
}
if ($fullPriceCents < 0 || $remainingSeconds < 1
|| $periodSeconds < 1 || $remainingSeconds > $periodSeconds) {
throw new CloudError('自动备份计费周期无效', 409);
}
$whole = intdiv($fullPriceCents, $periodSeconds)
* $remainingSeconds;
$remainder = $fullPriceCents % $periodSeconds;
$partial = intdiv(
($remainder * $remainingSeconds) + $periodSeconds - 1,
$periodSeconds
);
return max(1, $whole + $partial);
}
private static function assertOwner(
CloudInstance $instance,
User $user
): void {
if ((int) $instance->user_id !== (int) $user->id) {
throw new CloudError('只能管理自己持有实例的自动备份', 403);
}
}
}

@ -3,6 +3,7 @@
namespace App\Services\Cloud;
use App\Models\CloudBackupSubscription;
use App\Models\CloudBackupPeriodEntitlement;
use App\Models\CloudInstance;
use App\Models\CloudInstanceBackup;
use App\Models\CloudJob;
@ -87,15 +88,16 @@ final class CloudAutomaticBackupService
public static function settings(CloudInstance $instance, array $actor): array
{
self::assertOwner($instance, $actor);
$entitled = self::entitled($instance);
$subscription = CloudBackupSubscription::where(
'instance_id', (int) $instance->id
)->first();
if (!$entitled && $subscription !== null) {
throw new CloudError('自动备份订阅与实例计费快照不一致', 409);
}
$entitled = self::entitled($instance, $subscription, time());
if ($entitled && $subscription === null) {
throw new CloudError('自动备份订阅尚未激活,请联系管理员', 409);
throw new CloudError('自动备份权益缺少订阅账本,请联系管理员', 409);
}
if ($subscription !== null
&& (int) $subscription->user_id !== (int) $instance->user_id) {
throw new CloudError('自动备份订阅归属不一致', 409);
}
return [
'instance_id' => (string) $instance->id,
@ -114,23 +116,18 @@ final class CloudAutomaticBackupService
CloudInstance $instance,
CloudOffer $offer
): void {
$spec = self::spec($instance);
if (($spec['automatic_backup'] ?? null) !== true) {
return;
}
$subscription = CloudBackupSubscription::where(
'instance_id', (int) $instance->id
)->lockForUpdate()->first();
if ($subscription === null
|| (int) $offer->id !== (int) $instance->offer_id
if ($subscription === null) {
return;
}
if ((int) $offer->id !== (int) $instance->offer_id
|| (int) $subscription->user_id !== (int) $instance->user_id
|| strtoupper((string) $offer->currency) !== 'USD') {
throw new CloudError('升级后的自动备份价格账本不一致', 409);
}
$price = self::moneySnapshot($offer->backup_price);
if (!hash_equals($price, (string) ($spec['backup_price'] ?? ''))) {
throw new CloudError('升级后的自动备份价格快照不一致', 409);
}
$subscription->offer_id = (int) $offer->id;
$subscription->price = $price;
$subscription->price_version = (int) $offer->price_version;
@ -142,9 +139,6 @@ final class CloudAutomaticBackupService
array $input): array
{
self::assertOwner($instance, $actor);
if (!self::entitled($instance)) {
throw new CloudError('该实例未购买自动备份', 409);
}
CloudInput::only($input, [
'frequency', 'weekday', 'retention_count',
]);
@ -173,9 +167,10 @@ final class CloudAutomaticBackupService
}
}
$now = time();
$subscription = $instance->getConnection()->transaction(
function () use (
$instance, $frequency, $weekday, $retention
$instance, $frequency, $weekday, $retention, $now
): CloudBackupSubscription {
$locked = CloudBackupSubscription::where(
'instance_id', (int) $instance->id
@ -184,6 +179,16 @@ final class CloudAutomaticBackupService
|| (int) $locked->user_id !== (int) $instance->user_id) {
throw new CloudError('自动备份订阅尚未激活,请联系管理员', 409);
}
if (!(bool) $locked->enabled
|| !CloudBackupPeriodEntitlement::where(
'subscription_id', (int) $locked->id
)->where('instance_id', (int) $instance->id)
->where('user_id', (int) $instance->user_id)
->where('starts_at', '<=', $now)
->where('ends_at', '>', $now)
->lockForUpdate()->exists()) {
throw new CloudError('该实例当前没有已启用的自动备份权益', 409);
}
$changedSchedule = (string) $locked->frequency !== $frequency
|| (int) $locked->weekday !== (int) $weekday;
$locked->frequency = $frequency;
@ -192,10 +197,10 @@ final class CloudAutomaticBackupService
$locked->timezone = self::TIMEZONE;
if ($changedSchedule) {
$locked->next_run_at = self::nextRunAt(
time(), $frequency, (int) $weekday
$now, $frequency, (int) $weekday
);
}
$locked->updated_at = time();
$locked->updated_at = $now;
$locked->save();
return $locked;
}, 3
@ -427,6 +432,14 @@ final class CloudAutomaticBackupService
throw new CloudError('实例当前不可创建自动备份', 409);
}
$scheduledFor = (int) $subscription->next_run_at;
if (!CloudBackupPeriodEntitlement::where(
'subscription_id', (int) $subscription->id
)->where('instance_id', (int) $instance->id)
->where('user_id', (int) $instance->user_id)
->where('starts_at', '<=', $scheduledFor)
->where('ends_at', '>', $scheduledFor)->exists()) {
throw new CloudError('自动备份执行时间不在已付权益周期内', 409);
}
$actor = [
'user_id' => (int) $instance->user_id,
'is_admin' => false,
@ -510,9 +523,21 @@ final class CloudAutomaticBackupService
];
}
private static function entitled(CloudInstance $instance): bool
private static function entitled(
CloudInstance $instance,
?CloudBackupSubscription $subscription,
int $at
): bool
{
return (self::spec($instance)['automatic_backup'] ?? null) === true;
if ($subscription === null) {
return false;
}
return CloudBackupPeriodEntitlement::where(
'subscription_id', (int) $subscription->id
)->where('instance_id', (int) $instance->id)
->where('user_id', (int) $instance->user_id)
->where('starts_at', '<=', $at)
->where('ends_at', '>', $at)->exists();
}
private static function spec(CloudInstance $instance): array

@ -4,6 +4,7 @@ namespace App\Services\Cloud;
use App\Models\CloudBackupRestore;
use App\Models\CloudBackupRecovery;
use App\Models\CloudBackupPeriodEntitlement;
use App\Models\CloudBackupSubscription;
use App\Models\CloudHost;
use App\Models\CloudInstance;
@ -562,20 +563,29 @@ final class CloudBackupService
$automaticSubscription = CloudBackupSubscription::where(
'id', (int) $automatic['subscription_id']
)->lockForUpdate()->first();
$spec = self::decodeSpec((string) $locked->spec_json);
$scheduledFor = (int) $automatic['scheduled_for'];
$entitled = $automaticSubscription !== null
&& CloudBackupPeriodEntitlement::where(
'subscription_id',
(int) $automaticSubscription->id
)->where('instance_id', (int) $locked->id)
->where('user_id', (int) $locked->user_id)
->where('starts_at', '<=', $scheduledFor)
->where('ends_at', '>', $scheduledFor)
->lockForUpdate()->exists();
if ($automaticSubscription === null
|| !(bool) $automaticSubscription->enabled
|| (int) $automaticSubscription->instance_id
!== (int) $locked->id
|| (int) $automaticSubscription->user_id
!== (int) $locked->user_id
|| ($spec['automatic_backup'] ?? null) !== true) {
|| !$entitled) {
throw new CloudError('自动备份订阅与实例账本不一致', 409);
}
$existing = CloudInstanceBackup::where(
'subscription_id', (int) $automaticSubscription->id
)->where('scheduled_for',
(int) $automatic['scheduled_for'])->first();
$scheduledFor)->first();
if ($existing !== null) {
$job = CloudJob::where('kind', 'backup_create')
->where('backup_id', (int) $existing->id)
@ -585,7 +595,7 @@ final class CloudBackupService
}
CloudAutomaticBackupService::advanceAfterScheduled(
$automaticSubscription,
(int) $automatic['scheduled_for'],
$scheduledFor,
(int) $existing->id
);
return [

@ -15,6 +15,7 @@ final class CloudInvoicePageService
private const PURPOSES = [
'all', 'renewal', 'provision', 'upgrade', 'ip_change',
'backup_addon',
];
public static function normalizePurpose($value): string

@ -253,14 +253,41 @@ final class CloudInvoiceService
public static function refreshRenewalAfterUpgradeLocked(
CloudInstance $instance,
int $now
): ?CloudInvoice {
return self::refreshRenewalSnapshotLocked(
$instance,
$now,
'实例升级恢复时',
true
);
}
/** Rebuild an unpaid renewal after the automatic-backup renewal choice changes. */
public static function refreshRenewalAfterBackupPolicyLocked(
CloudInstance $instance,
int $now
): ?CloudInvoice {
return self::refreshRenewalSnapshotLocked(
$instance,
$now,
'自动备份切换时',
false
);
}
private static function refreshRenewalSnapshotLocked(
CloudInstance $instance,
int $now,
string $context,
bool $recoveryConflict
): ?CloudInvoice {
if ($instance->expires_at === null
|| $instance->renewal_price === null
|| (int) $instance->renewal_days < 1
|| self::instanceDeleting($instance)) {
throw new CloudRecoveryInstanceStateConflict(
'实例升级后的续费快照不可用',
409
self::renewalRefreshConflict(
$context . '续费快照不可用',
$recoveryConflict
);
}
$expiry = (int) $instance->expires_at;
@ -276,25 +303,25 @@ final class CloudInvoiceService
if ($invoices->contains(static fn ($candidate): bool =>
$candidate->renewal_id !== null
|| (string) $candidate->status === 'paid')) {
throw new CloudRecoveryInstanceStateConflict(
'实例升级恢复时发现已结算续费账单',
409
self::renewalRefreshConflict(
$context . '发现已结算续费账单',
$recoveryConflict
);
}
if (CloudInvoicePayment::whereIn('invoice_id', $ids)
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
->lockForUpdate()->exists()) {
throw new CloudRecoveryInstanceStateConflict(
'实例升级恢复时续费支付仍在处理中',
409
self::renewalRefreshConflict(
$context . '续费支付仍在处理中',
$recoveryConflict
);
}
foreach ($ids as $invoiceId) {
if (CloudJobService::blockingQueryForInvoice($invoiceId)
->exists()) {
throw new CloudRecoveryInstanceStateConflict(
'实例升级恢复时续费支付结果仍待核对',
409
self::renewalRefreshConflict(
$context . '续费支付结果仍待核对',
$recoveryConflict
);
}
}
@ -325,9 +352,9 @@ final class CloudInvoiceService
foreach ($invoices as $candidate) {
if (!in_array((string) $candidate->status,
['open', 'overdue', 'expired'], true)) {
throw new CloudRecoveryInstanceStateConflict(
'实例升级恢复时续费账单状态异常',
409
self::renewalRefreshConflict(
$context . '续费账单状态异常',
$recoveryConflict
);
}
$candidate->status = 'void';
@ -344,6 +371,16 @@ final class CloudInvoiceService
);
}
private static function renewalRefreshConflict(
string $message,
bool $recoveryConflict
): void {
if ($recoveryConflict) {
throw new CloudRecoveryInstanceStateConflict($message, 409);
}
throw new CloudError($message, 409);
}
private static function createRenewalInvoiceLocked(
CloudInstance $instance,
int $dueAt,
@ -391,12 +428,10 @@ final class CloudInvoiceService
if ($instanceCents < 0) {
throw new CloudError('实例缺少基础续费价格快照', 409);
}
$spec = json_decode((string) $instance->spec_json, true);
if (!is_array($spec) || array_is_list($spec)) {
throw new CloudError('实例计费快照损坏', 409);
}
$entitled = ($spec['automatic_backup'] ?? null) === true;
if (!$entitled) {
$subscription = CloudBackupSubscription::where(
'instance_id', (int) $instance->id
)->lockForUpdate()->first();
if ($subscription === null || !(bool) $subscription->renew_next_period) {
return [
'instance_cents' => $instanceCents,
'backup_cents' => 0,
@ -404,18 +439,9 @@ final class CloudInvoiceService
'backup_subscription_id' => null,
];
}
$subscription = CloudBackupSubscription::where(
'instance_id', (int) $instance->id
)->lockForUpdate()->first();
if ($subscription === null) {
throw new CloudError('实例自动备份订阅账本缺失', 409);
}
if ($subscription !== null
&& ((int) $subscription->user_id !== (int) $instance->user_id
if ((int) $subscription->user_id !== (int) $instance->user_id
|| (int) $subscription->offer_id !== (int) $instance->offer_id
|| strtoupper((string) $subscription->currency) !== 'USD'
|| !(bool) $subscription->enabled
|| !(bool) $subscription->renew_next_period)) {
|| strtoupper((string) $subscription->currency) !== 'USD') {
throw new CloudError('实例自动备份订阅账本不一致', 409);
}
$backupCents = CloudMoney::cents((string) $subscription->price);
@ -759,7 +785,8 @@ final class CloudInvoiceService
$purpose = (string) ($invoice->purpose ?: 'renewal');
if ($purpose === 'provision' && $invoice->order_id !== null) {
$orderIds[(int) $invoice->order_id] = (int) $invoice->order_id;
} elseif (in_array($purpose, ['renewal', 'upgrade'], true)
} elseif (in_array($purpose,
['renewal', 'upgrade', 'backup_addon'], true)
&& $invoice->instance_id !== null) {
$linkedInstanceIds[(int) $invoice->instance_id]
= (int) $invoice->instance_id;
@ -834,6 +861,7 @@ final class CloudInvoiceService
'renewal' => '实例续费',
'upgrade' => '实例升级',
'ip_change' => '更换公网 IP',
'backup_addon' => '自动备份开通',
default => '账单',
};
$order = $purpose === 'provision' && $invoice->order_id !== null
@ -844,13 +872,17 @@ final class CloudInvoiceService
: ($purpose === 'upgrade'
? ($jobsByInvoice[self::listKey($ownerId, (int) $invoice->id)] ?? null)
: null);
$instance = in_array($purpose, ['renewal', 'upgrade'], true)
$instance = in_array(
$purpose,
['renewal', 'upgrade', 'backup_addon'],
true
)
&& $invoice->instance_id !== null
? ($instances[self::listKey($ownerId, (int) $invoice->instance_id)] ?? null)
: null;
$historicalInstanceId = in_array(
$purpose,
['renewal', 'upgrade'],
['renewal', 'upgrade', 'backup_addon'],
true
) && $invoice->instance_id !== null
? (int) $invoice->instance_id : null;
@ -1000,7 +1032,8 @@ final class CloudInvoiceService
'outcome', 'attempts', 'updated_at', 'error_code',
'result_json', 'effect_resolution']);
}
} elseif (in_array($purpose, ['renewal', 'upgrade'], true)
} elseif (in_array($purpose,
['renewal', 'upgrade', 'backup_addon'], true)
&& $invoice->instance_id !== null) {
$instance = CloudInstance::where('id', $invoice->instance_id)
->where('user_id', $invoice->user_id)
@ -1036,7 +1069,11 @@ final class CloudInvoiceService
$linkedInstanceId = $purpose === 'provision'
? ($order?->instance_id ?? $invoice->instance_id)
: $invoice->instance_id;
$linkedInstance = in_array($purpose, ['renewal', 'upgrade'], true) ? $instance
$linkedInstance = in_array(
$purpose,
['renewal', 'upgrade', 'backup_addon'],
true
) ? $instance
: ($linkedInstanceId === null ? null
: CloudInstance::where('id', $linkedInstanceId)
->where('user_id', $invoice->user_id)
@ -1045,7 +1082,8 @@ final class CloudInvoiceService
&& CloudInstance::where('id', $linkedInstanceId)->exists();
$instanceId = $linkedInstance?->id;
if ($instanceId === null
&& in_array($purpose, ['renewal', 'upgrade'], true)
&& in_array($purpose,
['renewal', 'upgrade', 'backup_addon'], true)
&& !$linkedInstanceExists) {
$instanceId = $linkedInstanceId;
}
@ -1101,6 +1139,7 @@ final class CloudInvoiceService
'renewal' => '实例续费',
'upgrade' => '实例升级',
'ip_change' => '更换公网 IP',
'backup_addon' => '自动备份开通',
default => '账单',
};
$order = $purpose !== 'provision' || $invoice->order_id === null
@ -1119,7 +1158,8 @@ final class CloudInvoiceService
&& CloudInstance::where('id', $linkedInstanceId)->exists();
$safeLinkedInstanceId = $instance?->id;
if ($safeLinkedInstanceId === null
&& in_array($purpose, ['renewal', 'upgrade'], true)
&& in_array($purpose,
['renewal', 'upgrade', 'backup_addon'], true)
&& !$linkedInstanceExists) {
$safeLinkedInstanceId = $linkedInstanceId;
}

@ -163,6 +163,13 @@ final class CloudRenewalService
$renewal->period_id = $period->id;
$renewal->save();
CloudAutomaticBackupBillingService::grantRenewalEntitlementLocked(
$locked,
$period,
$invoice,
$now
);
$user->money = CloudMoney::decimal($balance - $price);
$user->save();
$locked->expires_at = $newExpiry;

@ -2731,7 +2731,15 @@ final class CloudWorkerService
$period->save();
$instance->current_period_id = $period->id;
$instance->save();
CloudAutomaticBackupService::activatePurchased($instance);
$backupSubscription =
CloudAutomaticBackupService::activatePurchased($instance);
CloudAutomaticBackupBillingService::grantProvisionEntitlementLocked(
$instance,
$period,
$provisionInvoice,
$backupSubscription,
$now
);
$job->instance_id = $order->instance_id = $instance->id;
$provisionInvoice->instance_id = $instance->id;
$provisionInvoice->updated_at = time();
@ -2903,8 +2911,9 @@ final class CloudWorkerService
$instance->sealed_credential = null;
CloudBackupSubscription::where(
'instance_id', (int) $instance->id
)->where('enabled', 1)->update([
)->update([
'enabled' => 0,
'renew_next_period' => 0,
'updated_at' => time(),
]);
CloudPlacementService::releaseDeletedInstance(

@ -20,6 +20,7 @@ class UserDataDeletionService
// remove. cloud_jobs may contain encrypted provisioning credentials.
['cloud_jobs', 'user_id'], ['cloud_instance_snapshots', 'user_id'],
['cloud_instance_firewalls', 'user_id'],
['cloud_backup_period_entitlements', 'user_id'],
['cloud_service_periods', 'user_id'],
['cloud_renewals', 'user_id'], ['cloud_invoice_payments', 'user_id'],
['cloud_invoices', 'user_id'], ['cloud_orders', 'user_id'],

@ -55,6 +55,10 @@ $app->group('/api/v1', function () {
'App\Controllers\CloudApiController:deleteSnapshot');
$this->map(['GET', 'PUT'], '/vms/{id:[0-9]+}/automatic-backup',
'App\Controllers\CloudApiController:automaticBackup');
$this->post('/vms/{id:[0-9]+}/automatic-backup/enable',
'App\Controllers\CloudApiController:enableAutomaticBackup');
$this->post('/vms/{id:[0-9]+}/automatic-backup/disable',
'App\Controllers\CloudApiController:disableAutomaticBackup');
$this->post('/vms/{id:[0-9]+}/automatic-backup/{backup_id:[0-9]+}/restore',
'App\Controllers\CloudApiController:restoreAutomaticBackup');
$this->patch('/vms/{id:[0-9]+}/display-name', 'App\Controllers\CloudApiController:displayName');

@ -17,7 +17,8 @@ const PAYMENT_OPTIONS = [
];
const PURPOSE_OPTIONS = [
['', '全部账单类型'], ['provision', '实例开通'], ['renewal', '实例续费'],
['upgrade', '实例升级'], ['ip_change', '更换公网 IP'], ['recharge', '余额充值'],
['upgrade', '实例升级'], ['ip_change', '更换公网 IP'],
['backup_addon', '自动备份开通'], ['recharge', '余额充值'],
];
const PROVIDER_OPTIONS = [
['', '全部支付渠道'], ['balance', '账户余额'], ['usdt', 'USDT-TRC20'],
@ -113,7 +114,8 @@ function formatBytes(value) {
function purposeLabel(value) {
return ({ provision: '实例开通', renewal: '实例续费', upgrade: '实例升级',
ip_change: '更换公网 IP', recharge: '余额充值' })[String(value || '').toLowerCase()]
ip_change: '更换公网 IP', backup_addon: '自动备份开通',
recharge: '余额充值' })[String(value || '').toLowerCase()]
|| firstText(value, '未分类');
}

@ -1408,6 +1408,52 @@ function automaticBackupSubscription(payload = automaticBackupPayload) {
? payload.subscription : payload || {};
}
function automaticBackupBilling(payload = automaticBackupPayload) {
return payload?.billing && typeof payload.billing === 'object'
? payload.billing : payload || {};
}
function automaticBackupEnabled(payload = automaticBackupPayload) {
const billing = automaticBackupBilling(payload);
const subscription = automaticBackupSubscription(payload);
return billing?.subscription_enabled === true || subscription?.enabled === true;
}
function automaticBackupAmount(value) {
const amount = typeof value === 'string' ? value.trim() : String(value ?? '').trim();
return /^(?:0|[1-9][0-9]{0,9})\.[0-9]{2}$/.test(amount) ? amount : '';
}
function automaticBackupMoney(value, currency = 'USD') {
const amount = automaticBackupAmount(value);
if (!amount) return '—';
const code = /^[A-Z]{3}$/.test(String(currency || '').toUpperCase())
? String(currency).toUpperCase() : 'USD';
return `${code === 'USD' ? '$' : ''}${amount} ${code}`;
}
function automaticBackupEnableStorageKey(vmId) {
return `virt-cloud:pending-automatic-backup-enable:${state.userId || 'unknown'}:${vmId}`;
}
function pendingAutomaticBackupEnableKey(vmId, fingerprint) {
let saved = null;
try {
saved = JSON.parse(sessionStorage.getItem(automaticBackupEnableStorageKey(vmId)) || 'null');
} catch {}
const key = saved?.fingerprint === fingerprint
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
? String(saved.key) : firewallIdempotencyKey();
try {
sessionStorage.setItem(automaticBackupEnableStorageKey(vmId), JSON.stringify({ fingerprint, key }));
} catch {}
return key;
}
function clearPendingAutomaticBackupEnableKey(vmId) {
try { sessionStorage.removeItem(automaticBackupEnableStorageKey(vmId)); } catch {}
}
function automaticBackupSchedule(payload = automaticBackupPayload) {
const subscription = automaticBackupSubscription(payload);
const schedule = payload?.schedule && typeof payload.schedule === 'object'
@ -1421,14 +1467,56 @@ function automaticBackupSchedule(payload = automaticBackupPayload) {
}
function automaticBackupPurchased(payload = automaticBackupPayload) {
const billing = automaticBackupBilling(payload);
const subscription = automaticBackupSubscription(payload);
return payload?.entitled === true || payload?.purchased === true || payload?.subscribed === true
return billing?.entitlement_active === true
|| payload?.entitled === true || payload?.purchased === true || payload?.subscribed === true
|| subscription?.purchased === true || subscription?.active === true
|| ['active', 'pending', 'cancel_at_period_end'].includes(
String(subscription?.status || payload?.subscription_status || '').toLowerCase()
);
}
function renderAutomaticBackupService(vmId, payload = automaticBackupPayload) {
const billing = automaticBackupBilling(payload);
const stateTarget = byId('vm-automatic-backup-service-state');
const note = byId('vm-automatic-backup-service-note');
const enable = byId('vm-automatic-backup-enable');
const disable = byId('vm-automatic-backup-disable');
if (!stateTarget || !note || !enable || !disable) return;
const currency = String(billing?.currency || 'USD').toUpperCase();
const activationAmount = automaticBackupAmount(billing?.activation_amount);
const fullPrice = automaticBackupAmount(billing?.full_period_price);
const entitlementActive = billing?.entitlement_active === true;
const enabled = automaticBackupEnabled(payload);
const entitlementEnd = billing?.entitlement_paid_until;
byId('vm-automatic-backup-activation-price').textContent = automaticBackupMoney(activationAmount, currency);
byId('vm-automatic-backup-renewal-price').textContent = automaticBackupMoney(fullPrice, currency);
byId('vm-automatic-backup-entitlement-end').textContent = entitlementEnd
? snapshotTime(entitlementEnd) : '尚未购买';
if (enabled && entitlementActive) {
stateTarget.textContent = '已开启';
stateTarget.className = 'state-pill running';
note.textContent = '自动备份正在按计划执行。关闭后会立即停止生成新备份并取消下期续费,本期已支付费用不退款。';
} else if (entitlementActive) {
stateTarget.textContent = '本期已付 · 已关闭';
stateTarget.className = 'state-pill warning';
note.textContent = `本期权益仍保留到 ${snapshotTime(entitlementEnd)};重新开启不会重复收取已付周期费用。`;
} else {
stateTarget.textContent = '未开启';
stateTarget.className = 'state-pill other';
note.textContent = activationAmount
? `现在开启将从余额扣除 ${automaticBackupMoney(activationAmount, currency)},以后每个续费周期为 ${automaticBackupMoney(fullPrice, currency)}。`
: String(billing?.message || payload?.message || '当前暂不能开启自动备份。');
}
if (automaticBackupSaving) note.textContent = '正在更新自动备份服务,请勿重复提交。';
const canOperate = selectedVm()?.can_operate === true && !instanceOperationBusy();
enable.disabled = automaticBackupSaving || enabled || !canOperate || billing?.can_enable !== true;
disable.disabled = automaticBackupSaving || !enabled || !canOperate || billing?.can_disable !== true;
enable.textContent = automaticBackupSaving && !enabled ? '正在开启…' : '开启自动备份';
disable.textContent = automaticBackupSaving && enabled ? '正在关闭…' : '关闭自动备份';
}
function automaticBackupItems(payload = automaticBackupPayload) {
const values = Array.isArray(payload?.backups) ? payload.backups
: Array.isArray(payload?.items) ? payload.items : [];
@ -1528,9 +1616,10 @@ function renderAutomaticBackup(vmId, payload = automaticBackupPayload) {
if (!form) return;
const schedule = automaticBackupSchedule(payload);
const purchased = automaticBackupPurchased(payload);
const enabled = automaticBackupEnabled(payload);
const canConfigure = payload?.can_configure !== false
&& automaticBackupSubscription(payload)?.can_configure !== false;
const allowed = purchased && canConfigure
const allowed = purchased && enabled && canConfigure
&& selectedVm()?.can_operate === true && !instanceOperationBusy()
&& !automaticBackupSaving && !automaticBackupRestoring;
form.elements.frequency.value = schedule.frequency;
@ -1538,15 +1627,18 @@ function renderAutomaticBackup(vmId, payload = automaticBackupPayload) {
form.elements.retention_count.value = String(schedule.retention);
byId('vm-automatic-backup-weekday-field').hidden = schedule.frequency !== 'weekly';
for (const control of form.querySelectorAll('select, button')) control.disabled = !allowed;
renderAutomaticBackupService(vmId, payload);
renderAutomaticBackupList(vmId, automaticBackupItems(payload), allowed);
if (!purchased) {
automaticBackupStatus('当前实例没有有效的自动备份服务,请在部署新实例时选择自动备份。', 'warning');
automaticBackupStatus('当前实例没有有效的自动备份权益,可在上方查看本周期启用费用。', 'warning');
} else if (automaticBackupSaving) {
automaticBackupStatus('正在保存自动备份计划,请勿重复提交。');
automaticBackupStatus('正在更新自动备份服务,请勿重复提交。');
} else if (automaticBackupRestoring) {
automaticBackupStatus('正在恢复当前实例,请勿重复提交其他实例操作。', 'warning');
} else if (!canConfigure) {
automaticBackupStatus(String(payload?.message || '当前自动备份服务暂不能修改。'), 'warning');
} else if (!enabled) {
automaticBackupStatus('自动备份已关闭;已付权益保留,但不会继续生成新备份。', 'warning');
} else {
automaticBackupStatus('自动备份服务已启用,可修改下次执行计划。', 'success');
}
@ -1651,13 +1743,91 @@ async function restoreAutomaticBackup(vmId, backup) {
function bindAutomaticBackup(vmId) {
const form = byId('vm-automatic-backup-form');
if (!form) return;
byId('vm-automatic-backup-enable')?.addEventListener('click', async () => {
const billing = automaticBackupBilling();
if (automaticBackupSaving || automaticBackupRestoring || instanceOperationBusy()
|| billing?.can_enable !== true || automaticBackupEnabled()) return;
const expectedAmount = automaticBackupAmount(billing?.activation_amount);
if (!expectedAmount) {
automaticBackupError('自动备份启用报价无效,请刷新后重试。');
return;
}
const currency = String(billing?.currency || 'USD').toUpperCase();
const freeForPaidPeriod = expectedAmount === '0.00';
const confirmed = await requestUserConfirmation({
title: '确认开启自动备份',
message: freeForPaidPeriod
? '当前周期的备份权益已经支付,本次重新开启不会重复扣费。后续续费账单将继续包含自动备份费用。'
: `系统将从余额扣除 ${automaticBackupMoney(expectedAmount, currency)},用于当前及已预付服务周期的自动备份权益。`,
confirmText: freeForPaidPeriod ? '确认重新开启' : '确认扣费并开启',
tone: freeForPaidPeriod ? 'default' : 'danger',
});
if (!confirmed) return;
const fingerprint = [expectedAmount, String(billing?.price_version || ''),
String(billing?.current_period_ends_at || billing?.entitlement_paid_until || '')].join('|');
const idempotencyKey = pendingAutomaticBackupEnableKey(vmId, fingerprint);
automaticBackupSaving = true;
automaticBackupError();
renderAutomaticBackup(vmId, automaticBackupPayload);
try {
await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup/enable`, {
method: 'POST',
headers: { 'Idempotency-Key': idempotencyKey },
body: { expected_amount: expectedAmount },
});
clearPendingAutomaticBackupEnableKey(vmId);
await loadAutomaticBackup(vmId, true);
toast(freeForPaidPeriod ? '自动备份已重新开启。' : '自动备份已开启并完成扣费。', 'success');
} catch (error) {
const uncertain = firewallTransportUncertain(error);
if (!uncertain) clearPendingAutomaticBackupEnableKey(vmId);
automaticBackupError(error?.message || '自动备份开启失败,请稍后重试。');
if (uncertain) {
automaticBackupStatus('请求结果暂时无法确认;已保留同一请求标识。请勿重复发起其他操作。', 'warning');
} else {
await loadAutomaticBackup(vmId, true).catch(() => null);
}
} finally {
automaticBackupSaving = false;
if (automaticBackupPayload) renderAutomaticBackup(vmId, automaticBackupPayload);
}
});
byId('vm-automatic-backup-disable')?.addEventListener('click', async () => {
const billing = automaticBackupBilling();
if (automaticBackupSaving || automaticBackupRestoring || instanceOperationBusy()
|| billing?.can_disable !== true || !automaticBackupEnabled()) return;
const confirmed = await requestUserConfirmation({
title: '确认关闭自动备份',
message: '关闭后会立即停止生成新自动备份,并从下一张续费账单中移除备份费用。当前周期已支付费用不退款,已有备份和本期权益不会立即删除。',
confirmText: '确认关闭',
tone: 'danger',
});
if (!confirmed) return;
automaticBackupSaving = true;
automaticBackupError();
renderAutomaticBackup(vmId, automaticBackupPayload);
try {
await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup/disable`, {
method: 'POST', body: {},
});
await loadAutomaticBackup(vmId, true);
toast('自动备份已关闭,下期不再自动续费。', 'success');
} catch (error) {
automaticBackupError(error?.message || '自动备份关闭失败,请稍后重试。');
await loadAutomaticBackup(vmId, true).catch(() => null);
} finally {
automaticBackupSaving = false;
if (automaticBackupPayload) renderAutomaticBackup(vmId, automaticBackupPayload);
}
});
form.elements.frequency.addEventListener('change', () => {
byId('vm-automatic-backup-weekday-field').hidden = form.elements.frequency.value !== 'weekly';
});
form.addEventListener('submit', async event => {
event.preventDefault();
if (automaticBackupSaving || automaticBackupRestoring
|| !automaticBackupPurchased() || instanceOperationBusy()) return;
|| !automaticBackupPurchased() || !automaticBackupEnabled()
|| instanceOperationBusy()) return;
const frequency = form.elements.frequency.value === 'weekly' ? 'weekly' : 'daily';
const weekday = Math.min(6, Math.max(0, Number(form.elements.weekday.value) || 0));
const retention = Number(form.elements.retention_count.value) === 1 ? 1 : 2;

@ -281,6 +281,8 @@ function invoicePurpose(invoice) {
if (['provision', 'provisioning', 'initial', 'create'].includes(value)) return 'provision';
if (['renewal', 'renew', 'subscription'].includes(value)) return 'renewal';
if (value === 'upgrade') return 'upgrade';
if (value === 'ip_change') return 'ip_change';
if (value === 'backup_addon') return 'backup_addon';
return '';
}
@ -291,6 +293,8 @@ function invoiceTitle(invoice) {
provision: '实例开通',
renewal: '实例续费',
upgrade: '实例升级',
ip_change: '更换公网 IP',
backup_addon: '自动备份开通',
}[purpose], '账单');
}
@ -436,14 +440,32 @@ function renderInvoiceSpecification(invoice) {
const container = byId('invoice-specification');
if (!panel || !container) return;
const purpose = invoicePurpose(invoice);
if (!['provision', 'renewal', 'upgrade'].includes(purpose)) {
if (!['provision', 'renewal', 'upgrade', 'backup_addon'].includes(purpose)) {
panel.hidden = true;
container.replaceChildren();
return;
}
const spec = invoiceSpecification(invoice);
const subject = firstText(invoice.requested_name, invoice.instance_name,
purpose === 'provision' ? '待创建实例' : '实例');
if (purpose === 'backup_addon') {
const facts = [
invoiceFact('实例', subject),
invoiceFact('服务内容', '自动备份服务开通'),
];
if (firstText(invoice?.instance_id)) {
const item = makeElement('div', 'invoice-detail-fact');
const value = makeElement('dd');
const link = makeElement('a', 'row-button', '查看实例');
link.href = `/user/cloud/instances/${encodeURIComponent(String(invoice.instance_id))}`;
value.append(link);
item.append(makeElement('dt', '', '关联实例'), value);
facts.push(item);
}
container.replaceChildren(...facts);
panel.hidden = false;
return;
}
const spec = invoiceSpecification(invoice);
const facts = [
invoiceFact('实例', subject),
invoiceFact('套餐', firstText(invoice.plan_name, '云服务器套餐')),

@ -11,7 +11,7 @@ const state = {
function normalizePurposeFilter(value) {
const purpose = String(value || '').toLowerCase();
return ['renewal', 'provision', 'upgrade', 'ip_change'].includes(purpose)
return ['renewal', 'provision', 'upgrade', 'ip_change', 'backup_addon'].includes(purpose)
? purpose : 'all';
}
@ -81,13 +81,16 @@ function invoicePurpose(invoice) {
if (['provision', 'provisioning', 'initial', 'create'].includes(value)) return 'provision';
if (['renewal', 'renew', 'subscription'].includes(value)) return 'renewal';
if (value === 'upgrade') return 'upgrade';
if (value === 'ip_change') return 'ip_change';
if (value === 'backup_addon') return 'backup_addon';
return '';
}
function invoiceTitle(invoice) {
return firstText(invoice?.type_label, invoice?.title,
{ recharge: '余额充值', provision: '实例开通', renewal: '实例续费',
upgrade: '实例升级' }[invoicePurpose(invoice)], '账单');
upgrade: '实例升级', ip_change: '更换公网 IP',
backup_addon: '自动备份开通' }[invoicePurpose(invoice)], '账单');
}
function invoiceContext(invoice) {
@ -107,6 +110,10 @@ function invoiceContext(invoice) {
return `目标实例 ${firstText(invoice?.instance_name,
invoice?.instance_id ? `#${invoice.instance_id}` : '', '实例')}`;
}
if (purpose === 'backup_addon') {
return `目标实例 ${firstText(invoice?.instance_name,
invoice?.instance_id ? `#${invoice.instance_id}` : '', '实例')}`;
}
return '';
}

@ -292,3 +292,4 @@ body.vu-body .ssh-key-picker-manage:hover {
.vm-ip-change-facts{display:grid;grid-template-columns:1fr;gap:1px;margin:0 0 24px;padding:1px;background:#e5ecef}.vm-ip-change-facts>div{min-width:0;padding:14px 16px;background:#fff}.vm-ip-change-facts dt{margin-bottom:5px;color:#8796a4;font-size:10px}.vm-ip-change-facts dd{margin:0;color:#294257;font:700 12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}@media screen and (max-width:510px){.vm-ip-change-facts>div{padding:11px 13px}}
.vm-upgrade-section{max-width:880px}.vm-upgrade-current-card{margin:0 0 25px;padding:18px;border:1px solid #e1e9ed;border-radius:10px;background:#fbfcfd}.vm-upgrade-current-card h4,.vm-upgrade-picker-heading h4{margin:0;color:#314a5f;font-size:13px}.vm-upgrade-spec-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1px;margin:14px 0 0;padding:1px;background:#e3eaee}.vm-upgrade-spec-grid>div{min-width:0;padding:11px 13px;background:#fff}.vm-upgrade-spec-grid dt{margin-bottom:4px;color:#8797a5;font-size:9px}.vm-upgrade-spec-grid dd{margin:0;color:#294257;font-size:11px;font-weight:800;overflow-wrap:anywhere}.vm-upgrade-picker-heading{display:flex;align-items:baseline;justify-content:space-between;gap:15px;margin-bottom:11px}.vm-upgrade-picker-heading span{color:#8a99a7;font-size:10px}.vm-upgrade-offers{display:grid;gap:10px;margin:0 0 22px}.vm-upgrade-offer{position:relative;display:grid;width:100%;gap:14px;padding:16px 18px;border:1px solid #dce7ec;border-radius:10px;background:#fff;color:#50677a;text-align:left;cursor:pointer}.vm-upgrade-offer:hover:not(:disabled){border-color:#8ecdd2;background:#f8fcfc}.vm-upgrade-offer:focus-visible{outline:3px solid rgba(18,166,176,.22);outline-offset:2px}.vm-upgrade-offer[aria-checked=true]{border-color:#2eabb4;background:#eef9fa;box-shadow:inset 0 0 0 1px #2eabb4}.vm-upgrade-offer[aria-checked=true]::after{content:"✓";position:absolute;top:10px;right:10px;display:grid;place-items:center;width:21px;height:21px;border-radius:50%;background:#18a6b0;color:#fff;font-size:12px;font-weight:900}.vm-upgrade-offer:disabled{cursor:not-allowed;opacity:.66}.vm-upgrade-offer-heading{display:flex;align-items:center;justify-content:space-between;gap:35px;padding-right:21px}.vm-upgrade-offer-name{min-width:0;color:#293f53;font-size:13px;overflow-wrap:anywhere}.vm-upgrade-offer-price{flex:none;color:#0d929d;font-size:13px}.vm-upgrade-offer-facts{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:10px}.vm-upgrade-offer-fact{display:grid;min-width:0;gap:3px}.vm-upgrade-offer-fact small{color:#8a99a7;font-size:9px}.vm-upgrade-offer-fact b{color:#445d70;font-size:10px;overflow-wrap:anywhere}.vm-upgrade-empty{margin:0;padding:24px;border:1px dashed #d7e1e6;border-radius:10px;color:#8494a2;font-size:11px;text-align:center}@media screen and (max-width:510px){.vm-upgrade-current-card{padding:14px}.vm-upgrade-spec-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.vm-upgrade-picker-heading{align-items:flex-start;flex-direction:column;gap:4px}.vm-upgrade-offer{gap:13px;padding:15px}.vm-upgrade-offer-heading{align-items:flex-start;flex-direction:column;gap:5px;padding-right:27px}.vm-upgrade-offer-facts{grid-template-columns:repeat(2,minmax(0,1fr));gap:11px 8px}.vm-upgrade-offer-fact:last-child{grid-column:1/-1}.vm-upgrade-offer-price{font-size:12px}}
.vm-automatic-backup-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-automatic-backup-field-label{color:#40566a;font-size:12px;font-weight:800}.vm-automatic-backup-fixed-time{display:flex;align-items:center;height:44px;padding:0 13px;border:1px solid #dbe5ea;border-radius:8px;background:#f7f9fa;color:#40566a;font-size:12px}.vm-automatic-backup-list-heading{display:flex;align-items:center;justify-content:space-between;gap:15px;margin:32px 0 12px;padding-top:24px;border-top:1px solid #e6ecef}.vm-automatic-backup-list-heading h4{margin:0 0 4px;color:#354c60;font-size:14px}.vm-automatic-backup-list-heading small{color:#8797a5;font-size:10px}.vm-automatic-backup-list{display:grid;gap:10px}.vm-automatic-backup-card{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:13px 18px;padding:15px;border:1px solid #dfe8ed;border-radius:9px;background:#fbfdfd}.vm-automatic-backup-card-main{display:grid;gap:5px;min-width:0}.vm-automatic-backup-card-main strong{color:#31495d;font-size:12px;overflow-wrap:anywhere}.vm-automatic-backup-card-main small{color:#8192a1;font-size:10px;line-height:1.55}.vm-automatic-backup-card-status{align-self:start}.vm-automatic-backup-card-actions{grid-column:1/-1;display:flex;justify-content:flex-end}.vm-automatic-backup-empty{display:grid;gap:5px;padding:25px 17px;border:1px dashed #cedce2;border-radius:9px;color:#8797a5;text-align:center}.vm-automatic-backup-empty strong{color:#506779;font-size:12px}.vm-automatic-backup-empty span{font-size:10px}@media screen and (max-width:740px){.vm-automatic-backup-grid{grid-template-columns:1fr}}@media screen and (max-width:510px){.vm-automatic-backup-list-heading{align-items:flex-start;flex-direction:column}.vm-automatic-backup-list-heading .button{width:100%}.vm-automatic-backup-card{grid-template-columns:1fr}.vm-automatic-backup-card-status,.vm-automatic-backup-card-actions{grid-column:1}.vm-automatic-backup-card-actions .button{width:100%}}
.vm-automatic-backup-service{display:grid;gap:15px;margin:0 0 24px;padding:18px;border:1px solid #dce7ec;border-radius:11px;background:#fbfdfd}.vm-automatic-backup-service-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:18px}.vm-automatic-backup-service-heading h4{margin:4px 0 0;color:#30495d;font-size:14px}.vm-automatic-backup-service-prices{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1px;padding:1px;background:#e2eaed}.vm-automatic-backup-service-prices>div{display:grid;min-width:0;gap:5px;padding:14px;background:#fff}.vm-automatic-backup-service-prices span{color:#7c8e9e;font-size:10px}.vm-automatic-backup-service-prices strong{color:#263f54;font-size:14px;overflow-wrap:anywhere}.vm-automatic-backup-service-prices small{color:#8999a6;font-size:9px;line-height:1.55}.vm-automatic-backup-service-note{margin:0;color:#64798b;font-size:10px;line-height:1.7}.vm-automatic-backup-service-actions{display:flex;justify-content:flex-end;gap:10px}.vm-automatic-backup-service-actions .button{min-width:138px}@media screen and (max-width:740px){.vm-automatic-backup-service-prices{grid-template-columns:1fr}.vm-automatic-backup-service-actions{flex-direction:column}.vm-automatic-backup-service-actions .button{width:100%}}

@ -159,6 +159,16 @@
<div class="vm-settings-notice"><strong>固定执行时间</strong><span>自动任务统一在太平洋时间 00:00 执行;系统使用 America/Los_Angeles 时区并自动处理夏令时。</span></div>
<div class="vm-settings-notice warning"><strong>恢复会覆盖当前系统盘</strong><span>恢复当前实例必须在这里操作。恢复期间实例会停止,系统盘将回到所选备份的内容;账单、服务周期和公网 IP 不会回滚。</span></div>
<p id="vm-automatic-backup-status" class="vm-settings-status" role="status" aria-live="polite">打开本栏目后加载。</p>
<section id="vm-automatic-backup-service" class="vm-automatic-backup-service" aria-labelledby="vm-automatic-backup-service-title">
<div class="vm-automatic-backup-service-heading"><div><span class="eyebrow">BACKUP SERVICE</span><h4 id="vm-automatic-backup-service-title">备份服务</h4></div><span id="vm-automatic-backup-service-state" class="state-pill other">正在读取</span></div>
<div class="vm-automatic-backup-service-prices">
<div><span>现在启用需支付</span><strong id="vm-automatic-backup-activation-price">—</strong><small>当前周期按剩余时间计费;已付过的周期不会重复收费。</small></div>
<div><span>下个服务周期</span><strong id="vm-automatic-backup-renewal-price">—</strong><small>保持开启时,续费账单会包含完整周期备份费用。</small></div>
<div><span>当前已付权益至</span><strong id="vm-automatic-backup-entitlement-end">—</strong><small>关闭不会退款,已支付的本期权益会保留到这里。</small></div>
</div>
<p id="vm-automatic-backup-service-note" class="vm-automatic-backup-service-note">正在读取自动备份计费状态。</p>
<div class="vm-automatic-backup-service-actions"><button id="vm-automatic-backup-enable" class="button button-primary" type="button" disabled>开启自动备份</button><button id="vm-automatic-backup-disable" class="button button-outline" type="button" disabled>关闭自动备份</button></div>
</section>
<form id="vm-automatic-backup-form" class="vm-settings-form" novalidate>
<div class="vm-automatic-backup-grid">
<div class="vm-settings-field"><label for="vm-automatic-backup-frequency">备份频率</label><select id="vm-automatic-backup-frequency" name="frequency" disabled><option value="daily" selected>每天</option><option value="weekly">每周</option></select></div>

@ -10,6 +10,7 @@
<option value="provision"{if $cloud_invoice_filter == 'provision'} selected{/if}>开通账单</option>
<option value="upgrade"{if $cloud_invoice_filter == 'upgrade'} selected{/if}>升级账单</option>
<option value="ip_change"{if $cloud_invoice_filter == 'ip_change'} selected{/if}>更换 IP</option>
<option value="backup_addon"{if $cloud_invoice_filter == 'backup_addon'} selected{/if}>自动备份开通</option>
</select>
</label>
<noscript><button class="button button-outline small" type="submit">筛选</button></noscript>

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026102602' scope='global'}
{assign var=venix_asset_version value='2026102603' scope='global'}

@ -546,6 +546,37 @@ CREATE TABLE cloud_backup_subscriptions (
CONSTRAINT chk_cloud_backup_subscription_weekday CHECK (weekday <= 6),
CONSTRAINT chk_cloud_backup_subscription_retention CHECK (retention_count IN (1,2))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Immutable proof that one service period includes paid automatic backup.
-- Scheduling can be paused independently; the entitlement itself is never
-- deleted or rewritten merely because the user disables future backups.
CREATE TABLE cloud_backup_period_entitlements (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
subscription_id BIGINT UNSIGNED NOT NULL,
instance_id BIGINT UNSIGNED NOT NULL,
service_period_id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
offer_id BIGINT UNSIGNED NOT NULL,
invoice_id BIGINT UNSIGNED NOT NULL,
starts_at BIGINT UNSIGNED NOT NULL,
ends_at BIGINT UNSIGNED NOT NULL,
amount DECIMAL(12,2) NOT NULL,
full_period_price DECIMAL(12,2) NOT NULL,
currency CHAR(3) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'USD',
price_version INT UNSIGNED NOT NULL,
source VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
paid_at BIGINT UNSIGNED NOT NULL,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY cloud_backup_entitlement_period (service_period_id),
KEY cloud_backup_entitlement_subscription (subscription_id, starts_at, ends_at),
KEY cloud_backup_entitlement_instance (instance_id, starts_at, ends_at),
KEY cloud_backup_entitlement_owner (user_id, id),
KEY cloud_backup_entitlement_invoice (invoice_id, id),
CONSTRAINT chk_cloud_backup_entitlement_source CHECK (
source IN ('provision','renewal','addon')
),
CONSTRAINT chk_cloud_backup_entitlement_window CHECK (starts_at < ends_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Portable, object-storage-backed VM system-disk backups. The immutable
-- source/spec and sealed storage target snapshots keep old backups restorable
-- after the global object-storage configuration changes. Object URLs and

@ -0,0 +1,547 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudInstance;
use App\Models\User;
use App\Services\Cloud\CloudAutomaticBackupBillingService;
use App\Services\Cloud\CloudError;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('enable');
$table->string('money');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('offer_id');
$table->integer('current_period_id')->nullable();
$table->string('name');
$table->string('status');
$table->string('service_status');
$table->integer('expires_at')->nullable();
$table->string('renewal_price')->nullable();
$table->integer('renewal_days');
$table->integer('renewal_traffic_bytes')->default(0);
$table->text('spec_json');
$table->integer('updated_at');
});
$schema->create('cloud_offers', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('plan_id');
$table->integer('resource_pool_id');
$table->string('code');
$table->string('name');
$table->string('price');
$table->string('backup_price');
$table->string('currency');
$table->integer('price_version');
$table->integer('revision');
$table->integer('status');
$table->integer('stock');
$table->integer('sort');
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id');
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('renewal_id')->nullable();
$table->integer('starts_at');
$table->integer('ends_at');
$table->string('status');
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_backup_subscriptions', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id')->unique();
$table->integer('user_id');
$table->integer('offer_id');
$table->boolean('enabled');
$table->boolean('renew_next_period');
$table->string('frequency');
$table->integer('weekday');
$table->integer('retention_count');
$table->string('timezone');
$table->string('price');
$table->string('currency');
$table->integer('price_version');
$table->integer('next_run_at');
$table->integer('last_scheduled_at')->nullable();
$table->integer('last_backup_id')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_backup_period_entitlements', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('subscription_id');
$table->integer('service_period_id')->unique();
$table->integer('instance_id');
$table->integer('user_id');
$table->integer('offer_id');
$table->integer('invoice_id');
$table->string('source');
$table->integer('starts_at');
$table->integer('ends_at');
$table->string('full_period_price');
$table->string('amount');
$table->string('currency');
$table->integer('price_version');
$table->integer('paid_at');
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->increments('id');
$table->string('invoice_no')->unique();
$table->string('purpose');
$table->integer('instance_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('offer_id')->nullable();
$table->integer('renewal_id')->nullable();
$table->integer('renews_expires_at')->nullable();
$table->integer('due_at');
$table->string('amount');
$table->string('currency');
$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');
});
$schema->create('cloud_invoice_items', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('invoice_id');
$table->integer('order_item_id')->nullable();
$table->string('code');
$table->string('label');
$table->string('amount');
$table->string('currency');
$table->text('snapshot_json');
$table->integer('created_at');
$table->unique(['invoice_id', 'code']);
});
$schema->create('cloud_invoice_payments', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('invoice_id');
$table->integer('user_id');
$table->string('status');
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('invoice_id')->nullable();
$table->string('kind');
$table->string('phase');
$table->string('outcome')->nullable();
$table->string('effect_resolution')->default('not_applicable');
$table->boolean('safe_to_resubmit')->nullable();
});
$now = 2_000_000_000;
$startsAt = $now - (15 * 86400);
$endsAt = $now + (15 * 86400);
$user = new User();
$user->id = 7;
$user->enable = 1;
$user->money = '50.00';
$user->save();
$capsule->table('cloud_offers')->insert([
'id' => 9,
'plan_id' => 4,
'resource_pool_id' => 2,
'code' => 'half-period-offer',
'name' => 'Half period offer',
'price' => '20.00',
'backup_price' => '10.00',
'currency' => 'USD',
'price_version' => 3,
'revision' => 1,
'status' => 1,
'stock' => -1,
'sort' => 0,
'created_at' => $startsAt,
'updated_at' => $startsAt,
]);
$instance = new CloudInstance();
$instance->id = 11;
$instance->user_id = 7;
$instance->offer_id = 9;
$instance->name = 'billing-test-vm';
$instance->status = 'active';
$instance->service_status = 'active';
$instance->expires_at = $endsAt;
$instance->renewal_price = '20.00';
$instance->renewal_days = 30;
$instance->renewal_traffic_bytes = 0;
$instance->spec_json = '{}';
$instance->updated_at = $startsAt;
$instance->save();
$periodId = $capsule->table('cloud_service_periods')->insertGetId([
'instance_id' => 11,
'user_id' => 7,
'plan_id' => 4,
'order_id' => 1,
'renewal_id' => null,
'starts_at' => $startsAt,
'ends_at' => $endsAt,
'status' => 'active',
'created_at' => $startsAt,
'updated_at' => $startsAt,
]);
$instance->current_period_id = $periodId;
$instance->save();
$quote = CloudAutomaticBackupBillingService::quote($instance, $user, $now);
$assert($quote['activation_amount'] === '5.00',
'Half-period automatic backup quote must be exactly $5.00.');
$assert($quote['full_period_amount'] === '10.00'
&& $quote['period_ends_at'] === $endsAt
&& $quote['future_period_count'] === 0
&& $quote['can_enable'] === true,
'Automatic backup quote did not expose the verified billing period.');
$actor = [
'user_id' => 7,
'request_idempotency_key' => 'backup-enable-test-0001',
];
$enabled = CloudAutomaticBackupBillingService::enable(
$instance,
$user,
$actor,
['expected_amount' => '5.00'],
$now
);
$user->refresh();
$assert($enabled['state'] === 'active'
&& $enabled['charged_amount'] === '5.00'
&& (string) $user->money === '45.00',
'Paid activation did not atomically debit the quoted wallet amount.');
$assert($capsule->table('cloud_invoices')->where('purpose', 'backup_addon')
->where('status', 'paid')->count() === 1
&& $capsule->table('cloud_backup_period_entitlements')->count() === 1
&& $capsule->table('cloud_backup_subscriptions')
->where('enabled', 1)->where('renew_next_period', 1)->count() === 1,
'Paid activation did not create its invoice, entitlement and subscription.');
$replayed = CloudAutomaticBackupBillingService::enable(
$instance,
$user,
$actor,
['expected_amount' => '5.00'],
$now
);
$user->refresh();
$assert($replayed['invoice_id'] === $enabled['invoice_id']
&& (string) $user->money === '45.00'
&& $capsule->table('cloud_invoices')->count() === 1
&& $capsule->table('cloud_backup_period_entitlements')->count() === 1,
'Repeated activation was not idempotent.');
$changedReplayRejected = false;
try {
CloudAutomaticBackupBillingService::enable(
$instance,
$user,
$actor,
['expected_amount' => '4.99'],
$now
);
} catch (CloudError $error) {
$changedReplayRejected = $error->httpStatus === 409;
}
$nextRunBeforeDuplicate = (int) $capsule->table(
'cloud_backup_subscriptions'
)->where('instance_id', 11)->value('next_run_at');
$activeDuplicateRejected = false;
try {
CloudAutomaticBackupBillingService::enable(
$instance,
$user,
[
'user_id' => 7,
'request_idempotency_key' => 'backup-enable-active-0001',
],
['expected_amount' => '0.00'],
$now
);
} catch (CloudError $error) {
$activeDuplicateRejected = $error->httpStatus === 409;
}
$assert($changedReplayRejected && $activeDuplicateRejected
&& $capsule->table('cloud_invoices')->count() === 1
&& (int) $capsule->table('cloud_backup_subscriptions')
->where('instance_id', 11)->value('next_run_at')
=== $nextRunBeforeDuplicate,
'Changed or duplicate activation request altered the paid schedule.');
$renewalInvoiceId = $capsule->table('cloud_invoices')->insertGetId([
'invoice_no' => 'RENEW-BACKUP-TOGGLE-1',
'purpose' => 'renewal', 'instance_id' => 11, 'order_id' => null,
'user_id' => 7, 'plan_id' => null, 'offer_id' => 9,
'renewal_id' => null, 'renews_expires_at' => $endsAt,
'due_at' => $endsAt, 'amount' => '30.00', 'currency' => 'USD',
'validity_days' => 30, 'traffic_quota_bytes' => 0,
'status' => 'open', 'paid_via' => null, 'payment_reference' => null,
'paid_at' => null, 'created_at' => $now, 'updated_at' => $now,
]);
$capsule->table('cloud_invoice_items')->insert([
[
'invoice_id' => $renewalInvoiceId, 'order_item_id' => null,
'code' => 'instance', 'label' => '实例套餐续费',
'amount' => '20.00', 'currency' => 'USD',
'snapshot_json' => '{}', 'created_at' => $now,
],
[
'invoice_id' => $renewalInvoiceId, 'order_item_id' => null,
'code' => 'automatic_backup', 'label' => '自动备份续费',
'amount' => '10.00', 'currency' => 'USD',
'snapshot_json' => json_encode([
'subscription_id' => (int) $capsule->table(
'cloud_backup_subscriptions'
)->where('instance_id', 11)->value('id'),
], JSON_THROW_ON_ERROR),
'created_at' => $now,
],
]);
$paymentId = $capsule->table('cloud_invoice_payments')->insertGetId([
'invoice_id' => $renewalInvoiceId, 'user_id' => 7,
'status' => 'pending',
]);
$pendingBlocked = false;
try {
CloudAutomaticBackupBillingService::disable(
$instance,
$user,
['user_id' => 7],
$now
);
} catch (CloudError $error) {
$pendingBlocked = $error->httpStatus === 409;
}
$assert($pendingBlocked
&& $capsule->table('cloud_backup_subscriptions')
->where('instance_id', 11)->where('enabled', 1)
->where('renew_next_period', 1)->count() === 1
&& $capsule->table('cloud_invoices')
->where('id', $renewalInvoiceId)->value('status') === 'open',
'Pending renewal payment did not roll back the backup-policy change.');
$capsule->table('cloud_invoice_payments')->where('id', $paymentId)->delete();
$disabled = CloudAutomaticBackupBillingService::disable(
$instance,
$user,
['user_id' => 7],
$now
);
$user->refresh();
$assert($disabled['state'] === 'paused'
&& $disabled['activation_amount'] === '0.00'
&& $disabled['can_enable'] === true
&& $disabled['can_disable'] === false
&& (string) $user->money === '45.00',
'Disabling did not preserve the already-paid period without refunding it.');
$assert($capsule->table('cloud_backup_subscriptions')
->where('enabled', 0)->where('renew_next_period', 0)->count() === 1
&& $capsule->table('cloud_backup_period_entitlements')->count() === 1,
'Disabling mutated the paid entitlement or retained future renewal.');
$assert($capsule->table('cloud_invoices')->where('id', $renewalInvoiceId)
->value('status') === 'void',
'Disabling did not void the stale unpaid backup renewal invoice.');
$reenabled = CloudAutomaticBackupBillingService::enable(
$instance,
$user,
[
'user_id' => 7,
'request_idempotency_key' => 'backup-enable-test-0002',
],
['expected_amount' => '0.00'],
$now
);
$user->refresh();
$assert($reenabled['state'] === 'active'
&& $reenabled['charged_amount'] === '0.00'
&& (string) $user->money === '45.00'
&& $capsule->table('cloud_backup_period_entitlements')->count() === 1,
'Re-enabling an already-paid period charged again or duplicated cover.');
$prepaidUser = new User();
$prepaidUser->id = 8;
$prepaidUser->enable = 1;
$prepaidUser->money = '20.00';
$prepaidUser->save();
$prepaid = new CloudInstance();
$prepaid->id = 12;
$prepaid->user_id = 8;
$prepaid->offer_id = 9;
$prepaid->name = 'prepaid-period-vm';
$prepaid->status = 'active';
$prepaid->service_status = 'active';
$prepaid->expires_at = $endsAt + (30 * 86400);
$prepaid->renewal_price = '20.00';
$prepaid->renewal_days = 30;
$prepaid->renewal_traffic_bytes = 0;
$prepaid->spec_json = '{}';
$prepaid->updated_at = $startsAt;
$prepaid->save();
$prepaidCurrent = $capsule->table('cloud_service_periods')->insertGetId([
'instance_id' => 12, 'user_id' => 8, 'plan_id' => 4,
'order_id' => 2, 'renewal_id' => null, 'starts_at' => $startsAt,
'ends_at' => $endsAt, 'status' => 'exhausted',
'created_at' => $startsAt, 'updated_at' => $startsAt,
]);
$capsule->table('cloud_service_periods')->insert([
'instance_id' => 12, 'user_id' => 8, 'plan_id' => 4,
'order_id' => null, 'renewal_id' => 2, 'starts_at' => $endsAt,
'ends_at' => $endsAt + (30 * 86400), 'status' => 'scheduled',
'created_at' => $startsAt, 'updated_at' => $startsAt,
]);
$prepaid->current_period_id = $prepaidCurrent;
$prepaid->save();
$prepaidQuote = CloudAutomaticBackupBillingService::quote(
$prepaid,
$prepaidUser,
$now
);
$assert($prepaidQuote['activation_amount'] === '15.00'
&& $prepaidQuote['future_period_count'] === 1,
'Activation did not add the full fee for a prepaid future period.');
CloudAutomaticBackupBillingService::enable(
$prepaid,
$prepaidUser,
[
'user_id' => 8,
'request_idempotency_key' => 'backup-enable-prepaid-0001',
],
['expected_amount' => '15.00'],
$now
);
$prepaidUser->refresh();
$assert((string) $prepaidUser->money === '5.00'
&& $capsule->table('cloud_backup_period_entitlements')
->where('instance_id', 12)->count() === 2,
'Prepaid periods were not covered atomically by one activation.');
$capsule->table('cloud_offers')->insert([
'id' => 10,
'plan_id' => 5,
'resource_pool_id' => 2,
'code' => 'upgraded-offer',
'name' => 'Upgraded offer',
'price' => '30.00',
'backup_price' => '12.00',
'currency' => 'USD',
'price_version' => 4,
'revision' => 1,
'status' => 1,
'stock' => -1,
'sort' => 0,
'created_at' => $now,
'updated_at' => $now,
]);
$capsule->table('cloud_instances')->where('id', 12)->update([
'offer_id' => 10,
]);
$capsule->table('cloud_backup_subscriptions')->where('instance_id', 12)
->update([
'offer_id' => 10,
'price' => '12.00',
'price_version' => 4,
'updated_at' => $now,
]);
$prepaid->refresh();
$postUpgradeQuote = CloudAutomaticBackupBillingService::quote(
$prepaid,
$prepaidUser,
$now
);
$assert($postUpgradeQuote['state'] === 'active'
&& $postUpgradeQuote['activation_amount'] === '0.00'
&& $postUpgradeQuote['full_period_amount'] === '12.00'
&& $capsule->table('cloud_backup_period_entitlements')
->where('instance_id', 12)->where('offer_id', 9)->count() === 2,
'A plan upgrade invalidated immutable paid backup entitlements.');
$poorUser = new User();
$poorUser->id = 9;
$poorUser->enable = 1;
$poorUser->money = '4.99';
$poorUser->save();
$poor = new CloudInstance();
$poor->id = 13;
$poor->user_id = 9;
$poor->offer_id = 9;
$poor->name = 'insufficient-balance-vm';
$poor->status = 'active';
$poor->service_status = 'active';
$poor->expires_at = $endsAt;
$poor->renewal_price = '20.00';
$poor->renewal_days = 30;
$poor->renewal_traffic_bytes = 0;
$poor->spec_json = '{}';
$poor->updated_at = $startsAt;
$poor->save();
$poorPeriod = $capsule->table('cloud_service_periods')->insertGetId([
'instance_id' => 13, 'user_id' => 9, 'plan_id' => 4,
'order_id' => 3, 'renewal_id' => null, 'starts_at' => $startsAt,
'ends_at' => $endsAt, 'status' => 'active',
'created_at' => $startsAt, 'updated_at' => $startsAt,
]);
$poor->current_period_id = $poorPeriod;
$poor->save();
$rejected = false;
try {
CloudAutomaticBackupBillingService::enable(
$poor,
$poorUser,
[
'user_id' => 9,
'request_idempotency_key' => 'backup-enable-poor-00001',
],
['expected_amount' => '5.00'],
$now
);
} catch (CloudError $error) {
$rejected = $error->getMessage() === '账户余额不足';
}
$poorUser->refresh();
$assert($rejected && (string) $poorUser->money === '4.99'
&& $capsule->table('cloud_backup_subscriptions')
->where('instance_id', 13)->count() === 0
&& $capsule->table('cloud_backup_period_entitlements')
->where('instance_id', 13)->count() === 0
&& $capsule->table('cloud_invoices')
->where('instance_id', 13)->count() === 0,
'Insufficient balance left partial automatic-backup billing state.');
echo "Automatic backup mid-period billing tests passed.\n";

@ -0,0 +1,217 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudBackupSubscription;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudInvoiceItem;
use App\Models\CloudServicePeriod;
use App\Services\Cloud\CloudAutomaticBackupBillingService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->addConnection([
'driver' => 'sqlite', 'database' => ':memory:',
], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('offer_id');
});
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id');
$table->integer('user_id');
$table->integer('order_id')->nullable();
$table->integer('renewal_id')->nullable();
$table->integer('starts_at');
$table->integer('ends_at');
});
$schema->create('cloud_backup_subscriptions', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id')->unique();
$table->integer('user_id');
$table->integer('offer_id');
$table->string('price');
$table->string('currency');
$table->integer('price_version');
});
$schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->increments('id');
$table->string('purpose');
$table->integer('instance_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->string('status');
$table->string('currency');
$table->integer('paid_at')->nullable();
});
$schema->create('cloud_invoice_items', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('invoice_id');
$table->integer('order_item_id')->nullable();
$table->string('code');
$table->string('label');
$table->string('amount');
$table->string('currency');
$table->text('snapshot_json');
$table->integer('created_at');
});
$schema->create('cloud_backup_period_entitlements', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('subscription_id');
$table->integer('instance_id');
$table->integer('service_period_id')->unique();
$table->integer('user_id');
$table->integer('offer_id');
$table->integer('invoice_id');
$table->integer('starts_at');
$table->integer('ends_at');
$table->string('amount');
$table->string('full_period_price');
$table->string('currency');
$table->integer('price_version');
$table->string('source');
$table->integer('paid_at');
$table->integer('created_at');
$table->integer('updated_at');
});
$now = 2_000_000_000;
$instance = new CloudInstance();
$instance->id = 10;
$instance->user_id = 7;
$instance->offer_id = 3;
$instance->save();
$subscription = new CloudBackupSubscription();
$subscription->instance_id = 10;
$subscription->user_id = 7;
$subscription->offer_id = 3;
$subscription->price = '2.50';
$subscription->currency = 'USD';
$subscription->price_version = 4;
$subscription->save();
$provision = new CloudInvoice();
$provision->purpose = 'provision';
$provision->instance_id = 10;
$provision->order_id = 70;
$provision->user_id = 7;
$provision->status = 'paid';
$provision->currency = 'USD';
$provision->paid_at = $now - 60;
$provision->save();
$provisionItem = new CloudInvoiceItem();
$provisionItem->invoice_id = (int) $provision->id;
$provisionItem->order_item_id = 1;
$provisionItem->code = 'automatic_backup';
$provisionItem->label = '自动备份';
$provisionItem->amount = '2.50';
$provisionItem->currency = 'USD';
$provisionItem->snapshot_json = '{}';
$provisionItem->created_at = $now - 60;
$provisionItem->save();
$firstPeriod = new CloudServicePeriod();
$firstPeriod->instance_id = 10;
$firstPeriod->user_id = 7;
$firstPeriod->order_id = 70;
$firstPeriod->starts_at = $now;
$firstPeriod->ends_at = $now + 30 * 86400;
$firstPeriod->save();
$first = CloudAutomaticBackupBillingService::grantProvisionEntitlementLocked(
$instance,
$firstPeriod,
$provision,
$subscription,
$now
);
$same = CloudAutomaticBackupBillingService::grantProvisionEntitlementLocked(
$instance,
$firstPeriod,
$provision,
$subscription,
$now + 10
);
$assert($first !== null && $same !== null
&& (int) $first->id === (int) $same->id
&& (string) $first->source === 'provision'
&& (string) $first->amount === '2.50'
&& (string) $first->full_period_price === '2.50'
&& $capsule->table('cloud_backup_period_entitlements')->count() === 1,
'Provision finalization did not grant exactly one immutable period entitlement.');
$renewal = new CloudInvoice();
$renewal->purpose = 'renewal';
$renewal->instance_id = 10;
$renewal->order_id = null;
$renewal->user_id = 7;
$renewal->status = 'open';
$renewal->currency = 'USD';
$renewal->paid_at = null;
$renewal->save();
$renewalItem = new CloudInvoiceItem();
$renewalItem->invoice_id = (int) $renewal->id;
$renewalItem->order_item_id = null;
$renewalItem->code = 'automatic_backup';
$renewalItem->label = '自动备份续费';
$renewalItem->amount = '2.50';
$renewalItem->currency = 'USD';
$renewalItem->snapshot_json = json_encode([
'subscription_id' => (int) $subscription->id,
], JSON_THROW_ON_ERROR);
$renewalItem->created_at = $now;
$renewalItem->save();
$nextPeriod = new CloudServicePeriod();
$nextPeriod->instance_id = 10;
$nextPeriod->user_id = 7;
$nextPeriod->renewal_id = 80;
$nextPeriod->starts_at = $firstPeriod->ends_at;
$nextPeriod->ends_at = $firstPeriod->ends_at + 30 * 86400;
$nextPeriod->save();
$second = CloudAutomaticBackupBillingService::grantRenewalEntitlementLocked(
$instance,
$nextPeriod,
$renewal,
$now
);
$assert($second !== null
&& (string) $second->source === 'renewal'
&& (int) $second->service_period_id === (int) $nextPeriod->id
&& $capsule->table('cloud_backup_period_entitlements')->count() === 2,
'Paid renewal did not grant its independent backup entitlement.');
$baseOnly = new CloudInvoice();
$baseOnly->purpose = 'renewal';
$baseOnly->instance_id = 10;
$baseOnly->user_id = 7;
$baseOnly->status = 'open';
$baseOnly->currency = 'USD';
$baseOnly->save();
$withoutBackup = CloudAutomaticBackupBillingService::grantRenewalEntitlementLocked(
$instance,
$nextPeriod,
$baseOnly,
$now
);
$assert($withoutBackup === null
&& $capsule->table('cloud_backup_period_entitlements')->count() === 2,
'A base-only renewal created automatic-backup cover.');
echo "Automatic backup entitlement grant tests passed.\n";

@ -0,0 +1,41 @@
<?php
$root = dirname(__DIR__);
$assert = static function (bool $condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$read = static fn (string $path): string => (string) file_get_contents(
$root . '/' . $path
);
$pageService = $read('app/Services/Cloud/CloudInvoicePageService.php');
$invoiceService = $read('app/Services/Cloud/CloudInvoiceService.php');
$adminService = $read('app/Services/Cloud/CloudAdminBillingService.php');
$listTemplate = $read('resources/views/venix/cloud/pages/invoices.tpl');
$listRuntime = $read('public/cloud/invoices.js');
$detailRuntime = $read('public/cloud/invoice-detail-runtime.js');
$adminRuntime = $read('public/cloud/admin-billing.js');
$assert(str_contains($pageService, "'backup_addon'")
&& substr_count($invoiceService,
"'backup_addon' => '自动备份开通'") >= 2,
'Automatic-backup bills are not recognized by user invoice services.');
$assert(str_contains($listTemplate, 'value="backup_addon"')
&& str_contains($listRuntime, "value === 'backup_addon'")
&& str_contains($listRuntime, "backup_addon: '自动备份开通'")
&& str_contains($detailRuntime, "value === 'backup_addon'")
&& str_contains($detailRuntime, "backup_addon: '自动备份开通'")
&& str_contains($detailRuntime, "purpose === 'backup_addon'")
&& str_contains($detailRuntime, '/user/cloud/instances/'),
'User invoice UI hides the add-on type or its linked instance.');
$assert(str_contains($adminService,
"'provision', 'renewal', 'upgrade', 'ip_change', 'backup_addon', 'recharge'")
&& str_contains($adminRuntime,
"['backup_addon', '自动备份开通']")
&& str_contains($adminRuntime,
"backup_addon: '自动备份开通'"),
'Administrator billing filters or labels omit automatic-backup add-ons.');
echo "Automatic-backup invoice presentation contract passed.\n";

@ -31,10 +31,45 @@ $assert($local->format('w H:i') === '1 00:00',
'Weekly schedule did not use the selected Pacific weekday at midnight.');
$routes = file_get_contents(dirname(__DIR__) . '/config/routes_cloud.php');
$controller = file_get_contents(
dirname(__DIR__) . '/app/Controllers/CloudApiController.php'
);
$middleware = file_get_contents(dirname(__DIR__) . '/app/Middleware/CloudApi.php');
$automaticService = file_get_contents(
dirname(__DIR__) . '/app/Services/Cloud/CloudAutomaticBackupService.php'
);
$backupService = file_get_contents(
dirname(__DIR__) . '/app/Services/Cloud/CloudBackupService.php'
);
$assert(str_contains($routes, "'/backups'")
&& str_contains($routes, "'/vms/{id:[0-9]+}/automatic-backup'")
&& str_contains($routes,
"'/vms/{id:[0-9]+}/automatic-backup/enable'")
&& str_contains($routes,
"'/vms/{id:[0-9]+}/automatic-backup/disable'")
&& str_contains($routes,
"'/vms/{id:[0-9]+}/automatic-backup/{backup_id:[0-9]+}/restore'"),
'Owner backup routes are incomplete.');
$assert(str_contains($controller, 'CloudAutomaticBackupBillingService::enable(')
&& str_contains($controller, 'CloudAutomaticBackupBillingService::disable(')
&& str_contains($controller, '$value[\'billing\'] =')
&& str_contains($controller, "'entitlement_paid_until' =>"),
'Owner backup API does not expose the paid toggle and billing state.');
$assert(str_contains($middleware,
"#^/api/v1/vms/[0-9]+/automatic-backup(?:/(?:enable|disable))?$#D")
&& !str_contains($middleware,
'automatic-backup(?:/|$)'),
'Database-only backup routes are missing or incorrectly include restore.');
$assert(str_contains($automaticService,
'CloudBackupPeriodEntitlement::where(')
&& str_contains($automaticService,
'->where(\'starts_at\', \'<=\', $scheduledFor)')
&& str_contains($backupService,
'CloudBackupPeriodEntitlement::where(')
&& str_contains($backupService,
'->where(\'ends_at\', \'>\', $scheduledFor)')
&& !str_contains($backupService,
'($spec[\'automatic_backup\'] ?? null) !== true'),
'Automatic backup scheduling is not guarded by paid-period entitlement on both sides of the transaction.');
echo "Automatic backup Pacific schedule and route contract passed.\n";

@ -53,6 +53,16 @@ $schema->create('cloud_backup_subscriptions',
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_backup_period_entitlements',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('subscription_id');
$table->integer('service_period_id')->unique();
$table->integer('instance_id');
$table->integer('user_id');
$table->integer('starts_at');
$table->integer('ends_at');
});
$schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->increments('id');
$table->string('purpose');
@ -115,6 +125,25 @@ $assert($subscription !== null
&& (string) $subscription->price === '2.50',
'Paid provisioning did not freeze the default backup subscription.');
// The commercial spec is historical after provisioning. Current access is
// proven by the immutable paid service-period entitlement.
$instance->spec_json = json_encode([
'automatic_backup' => false,
'instance_price' => '10.00',
'backup_price' => '2.50',
'price_version' => 4,
'currency' => 'USD',
], JSON_THROW_ON_ERROR);
$instance->save();
$capsule->table('cloud_backup_period_entitlements')->insert([
'subscription_id' => (int) $subscription->id,
'service_period_id' => 31,
'instance_id' => (int) $instance->id,
'user_id' => (int) $instance->user_id,
'starts_at' => time() - 3600,
'ends_at' => time() + 86400,
]);
$updated = CloudAutomaticBackupService::update($instance, [
'user_id' => 9,
], [
@ -185,15 +214,19 @@ $capsule->table('cloud_invoice_items')->insert([
]);
$assert(CloudInvoiceService::renewalInvoiceMatches($instance, $invoice),
'Renewal invoice did not accept the exact two-item backup quote.');
$subscription->enabled = false;
$subscription->save();
$pausedRenewal = CloudInvoiceService::renewalQuoteLocked($instance);
$assert($pausedRenewal['total_cents'] === 1250
&& $pausedRenewal['backup_cents'] === 250,
'Pausing this-period scheduling incorrectly removed a retained next-period renewal.');
$subscription->renew_next_period = false;
$subscription->save();
$failedClosed = false;
try {
CloudInvoiceService::renewalQuoteLocked($instance);
} catch (CloudError $error) {
$failedClosed = true;
}
$assert($failedClosed,
'An entitled instance accepted a disabled backup renewal ledger.');
$withoutBackup = CloudInvoiceService::renewalQuoteLocked($instance);
$assert($withoutBackup['instance_cents'] === 1000
&& $withoutBackup['backup_cents'] === 0
&& $withoutBackup['total_cents'] === 1000
&& $withoutBackup['backup_subscription_id'] === null,
'Disabled next-period renewal still charged for automatic backup.');
echo "Automatic backup subscription activation and update tests passed.\n";

@ -146,6 +146,26 @@ namespace {
$table->unique('order_id');
$table->unique('renewal_id');
});
$schema->create('cloud_backup_subscriptions', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id')->unique();
$table->integer('user_id');
$table->integer('offer_id');
$table->boolean('enabled');
$table->boolean('renew_next_period');
$table->string('frequency')->default('daily');
$table->integer('weekday')->default(0);
$table->integer('retention_count')->default(2);
$table->string('timezone')->default('America/Los_Angeles');
$table->string('price');
$table->string('currency');
$table->integer('price_version')->default(1);
$table->integer('next_run_at')->default(0);
$table->integer('last_scheduled_at')->nullable();
$table->integer('last_backup_id')->nullable();
$table->integer('created_at')->default(0);
$table->integer('updated_at')->default(0);
});
$schema->create('cloud_renewals', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id');

@ -324,6 +324,7 @@ namespace {
$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('offer_id')->nullable(); $t->integer('renewal_id')->nullable(); $t->integer('renews_expires_at')->nullable(); $t->integer('due_at'); $t->string('amount'); $t->string('currency')->default('USD'); $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_items', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->integer('order_item_id')->nullable(); $t->string('code'); $t->string('label'); $t->string('amount'); $t->string('currency')->default('USD'); $t->text('snapshot_json'); $t->integer('created_at'); $t->unique(['invoice_id', 'code']); });
$schema->create('cloud_backup_subscriptions', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id')->unique(); $t->integer('user_id'); $t->integer('offer_id'); $t->boolean('enabled')->default(true); $t->boolean('renew_next_period')->default(true); $t->string('frequency')->default('daily'); $t->integer('weekday')->default(0); $t->integer('retention_count')->default(2); $t->string('timezone')->default('America/Los_Angeles'); $t->string('price'); $t->string('currency')->default('USD'); $t->integer('price_version'); $t->integer('next_run_at'); $t->integer('last_scheduled_at')->nullable(); $t->integer('last_backup_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_backup_period_entitlements', function (Blueprint $t) { $t->increments('id'); $t->integer('subscription_id'); $t->integer('instance_id'); $t->integer('service_period_id')->unique(); $t->integer('user_id'); $t->integer('offer_id'); $t->integer('invoice_id'); $t->integer('starts_at'); $t->integer('ends_at'); $t->string('amount'); $t->string('full_period_price'); $t->string('currency')->default('USD'); $t->integer('price_version'); $t->string('source'); $t->integer('paid_at'); $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_mail_outbox', function (Blueprint $t) { $t->increments('id'); $t->integer('invoice_id'); $t->string('kind'); $t->string('status'); $t->integer('attempts'); $t->integer('available_at'); $t->string('lease_token')->nullable(); $t->integer('lease_until'); $t->integer('sent_at')->nullable(); $t->string('last_error'); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['invoice_id', 'kind']); });
$schema->create('cloud_ssh_keys', function (Blueprint $t) { $t->increments('id'); $t->integer('user_id'); $t->string('name'); $t->text('public_key'); $t->string('fingerprint'); $t->integer('created_at'); });
@ -1874,6 +1875,9 @@ namespace {
&& (int) Capsule::table('cloud_backup_subscriptions')
->where('instance_id', (int) $purgeForceRequired->id)
->value('enabled') === 0
&& (int) Capsule::table('cloud_backup_subscriptions')
->where('instance_id', (int) $purgeForceRequired->id)
->value('renew_next_period') === 0
&& $purgeForcedRequest['method'] === 'POST'
&& str_ends_with($purgeForcedRequest['request_target'], '/force-delete')
&& ($purgeForcedBody['prior_operation_id'] ?? null)

@ -22,7 +22,7 @@ $assert(stripos($schema, 'compatibility import') === false
$assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema),
'cloud.sql retained an engine-prefixed identifier.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v7-automatic-backups'")
"SCHEMA_VERSION = 'go-agent-wss-v8-backup-entitlements'")
&& !str_contains($setup, "SCHEMA_VERSION = 'go-v1'"),
'Outbound Agent schema must reject the incompatible earlier Go database.');
@ -30,7 +30,8 @@ foreach (['cloud_host_agents', 'cloud_templates', 'cloud_hosts', 'cloud_instance
'cloud_orders', 'cloud_invoices', 'cloud_jobs',
'cloud_agent_completion_events', 'cloud_console_tickets',
'cloud_rescue_template_imports', 'cloud_instance_backups',
'cloud_backup_subscriptions', 'cloud_backup_restores',
'cloud_backup_subscriptions', 'cloud_backup_period_entitlements',
'cloud_backup_restores',
'cloud_backup_recoveries', 'cloud_order_items', 'cloud_invoice_items',
'cloud_instance_migrations', 'cloud_migration_bundle_artifacts'] as $table) {
$assert(str_contains($schema, 'CREATE TABLE ' . $table . ' ('),
@ -75,7 +76,7 @@ $assert(str_contains($schema,
&& str_contains($schema,
'KEY cloud_job_backup_recovery (backup_recovery_id, id)')
&& str_contains($setup,
"'cloud_backup_subscriptions', 'cloud_instance_backups'")
"'cloud_backup_subscriptions', 'cloud_backup_period_entitlements'")
&& str_contains($setup,
"'cloud_backup_restores', 'cloud_backup_recoveries'")
&& str_contains($setup,
@ -83,6 +84,33 @@ $assert(str_contains($schema,
&& str_contains($setup,
"'cloud_job_backup_recovery'"),
'Fresh schema is missing portable-backup catalog or restore reservation constraints.');
$assert(str_contains($schema,
'CREATE TABLE cloud_backup_period_entitlements (')
&& str_contains($schema,
'service_period_id BIGINT UNSIGNED NOT NULL')
&& str_contains($schema,
'full_period_price DECIMAL(12,2) NOT NULL')
&& str_contains($schema,
"source VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL")
&& str_contains($schema,
'UNIQUE KEY cloud_backup_entitlement_period (service_period_id)')
&& str_contains($schema,
'KEY cloud_backup_entitlement_subscription (subscription_id, starts_at, ends_at)')
&& str_contains($schema,
'KEY cloud_backup_entitlement_instance (instance_id, starts_at, ends_at)')
&& str_contains($schema,
'CONSTRAINT chk_cloud_backup_entitlement_source CHECK (')
&& str_contains($schema,
'CONSTRAINT chk_cloud_backup_entitlement_window CHECK (starts_at < ends_at)')
&& str_contains($setup,
"'cloud_backup_period_entitlements' => [")
&& str_contains($setup,
"'cloud_backup_entitlement_period',")
&& str_contains($setup,
"'chk_cloud_backup_entitlement_source',")
&& str_contains($setup,
"'chk_cloud_backup_entitlement_window',"),
'Fresh schema is missing immutable paid automatic-backup period entitlements.');
$assert(str_contains($schema, 'CREATE TABLE cloud_instance_migrations (')
&& str_contains($schema, 'purpose VARCHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT \'portable\'')
&& str_contains($schema, 'CREATE TABLE cloud_migration_bundle_artifacts (')

@ -91,6 +91,16 @@ namespace {
$table->integer('previous_expires_at'); $table->integer('new_expires_at'); $table->integer('created_at');
$table->unique(['user_id', 'idempotency_key']);
});
$schema->create('cloud_backup_subscriptions', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id')->unique();
$table->integer('user_id');
$table->integer('offer_id');
$table->boolean('enabled');
$table->boolean('renew_next_period');
$table->string('price');
$table->string('currency');
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id')->nullable()->unique();

@ -124,6 +124,20 @@ Capsule::table('cloud_jobs')->insert([
'outcome' => null,
'effect_resolution' => 'not_applicable',
]);
Capsule::table('cloud_invoices')->insert([
'id' => 50,
'purpose' => 'backup_addon',
'instance_id' => 1,
'order_id' => null,
'user_id' => 1,
'renews_expires_at' => null,
'due_at' => $now,
'amount' => '2.50',
'status' => 'paid',
'paid_via' => 'balance',
'paid_at' => $now,
'created_at' => $now + 200,
]);
for ($number = 0; $number < 12; $number++) {
Capsule::table('cloud_invoices')->insert([
'purpose' => 'ip_change',
@ -140,9 +154,9 @@ for ($number = 0; $number < 12; $number++) {
$all = CloudInvoicePageService::forUser(1);
$assert($all['purpose'] === 'all'
&& $all['pagination']['total'] === 14
&& $all['pagination']['total'] === 15
&& $all['pagination']['per_page'] === 100
&& count($all['invoices']) === 14
&& count($all['invoices']) === 15
&& in_array('1', array_column($all['invoices'], 'id'), true),
'The default all-invoice view did not include every owner bill within the bounded page.');
@ -183,6 +197,29 @@ $assert(($upgradeStatus['payable'] ?? null) === false
&& $upgradeDetail['payment_deadline_at'] === null,
'Upgrade invoice detail or polling lost its target, task link, or non-payable state.');
$backupAddons = CloudInvoicePageService::forUser(
1,
1,
10,
'backup_addon'
);
$backupAddon = $backupAddons['invoices'][0] ?? [];
$backupInvoice = CloudInvoice::find(50);
$backupStatus = CloudInvoiceService::status($backupInvoice);
$backupDetail = CloudInvoiceService::display($backupInvoice);
$assert($backupAddons['purpose'] === 'backup_addon'
&& $backupAddons['pagination']['total'] === 1
&& ($backupAddon['title'] ?? null) === '自动备份开通'
&& ($backupAddon['instance_id'] ?? null) === '1'
&& ($backupAddon['instance_name'] ?? null) === 'customer-api'
&& ($backupStatus['payable'] ?? null) === false
&& ($backupStatus['instance_id'] ?? null) === '1'
&& ($backupDetail['title'] ?? null) === '自动备份开通'
&& ($backupDetail['instance_id'] ?? null) === '1'
&& ($backupDetail['instance_name'] ?? null) === 'customer-api'
&& ($backupDetail['payable'] ?? null) === false,
'Automatic-backup add-on bills were hidden, payable, or detached from their instance.');
Capsule::table('cloud_jobs')->where('id', 3)->update([
'phase' => 'terminal',
'outcome' => 'failed',
@ -209,6 +246,7 @@ $assert(($deletedList['invoices'][0]['instance_id'] ?? null) === '1'
&& ($deletedDetail['instance_name'] ?? null) === '已删除实例',
'Upgrade audit lost its referenced instance ID after the instance row disappeared.');
$assert(CloudInvoicePageService::normalizePurpose('upgrade') === 'upgrade'
&& CloudInvoicePageService::normalizePurpose('backup_addon') === 'backup_addon'
&& CloudInvoicePageService::normalizePurpose('invalid') === 'all'
&& CloudInvoicePageService::normalizePurpose(['renewal']) === 'all',
'Invoice purpose filtering accepted an unsupported or structured value.');

@ -197,6 +197,27 @@ namespace {
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_backup_subscriptions',
static function (Blueprint $table): void {
$table->increments('id');
$table->integer('instance_id')->unique();
$table->integer('user_id');
$table->integer('offer_id');
$table->boolean('enabled');
$table->boolean('renew_next_period');
$table->string('frequency')->default('daily');
$table->integer('weekday')->default(0);
$table->integer('retention_count')->default(2);
$table->string('timezone')->default('America/Los_Angeles');
$table->string('price');
$table->string('currency')->default('USD');
$table->integer('price_version');
$table->integer('next_run_at')->default(0);
$table->integer('last_scheduled_at')->nullable();
$table->integer('last_backup_id')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('host_id');
@ -748,6 +769,16 @@ namespace {
// Applied upgrades change the current/renewal snapshots without extending
// time or resetting usage, release source stock and void stale renewal.
$applied = $fixture(2, true);
$connection->table('cloud_backup_subscriptions')->insert([
'instance_id' => $applied['instanceId'], 'user_id' => 1,
'offer_id' => $applied['sourceOfferId'], 'enabled' => 0,
'renew_next_period' => 1, 'frequency' => 'daily', 'weekday' => 0,
'retention_count' => 2, 'timezone' => 'America/Los_Angeles',
'price' => '2.00', 'currency' => 'USD', 'price_version' => 1,
'next_run_at' => $now + 86400, 'last_scheduled_at' => null,
'last_backup_id' => null, 'created_at' => $now,
'updated_at' => $now,
]);
$instance = CloudInstance::find($applied['instanceId']);
$options = CloudPlanUpgradeService::options($instance, User::find(1));
$option = $optionFor($options, $applied['targetOfferId']);
@ -810,6 +841,14 @@ namespace {
$applied['renewalInvoiceId']
)->status === 'void',
'Applied upgrade did not release source stock or void stale renewal.');
$upgradedBackup = $connection->table('cloud_backup_subscriptions')
->where('instance_id', $applied['instanceId'])->first();
$assert((int) $upgradedBackup->offer_id === $applied['targetOfferId']
&& (string) $upgradedBackup->price === '3.00'
&& (int) $upgradedBackup->price_version === 3
&& (int) $upgradedBackup->enabled === 0
&& (int) $upgradedBackup->renew_next_period === 1,
'Upgrade did not move a mid-cycle backup subscription to the target offer price.');
$mutated = json_decode((string) $upgraded->spec_json, true,
32, JSON_THROW_ON_ERROR);
$mutated['plan_name'] = 'Later mutable plan';

@ -40,6 +40,12 @@ $assert(str_contains($runtime, 'const backupAvailable = Boolean(offer);')
'Deployment pricing and idempotency must include the backup purchase and optional backup source.');
$assert(str_contains($detail, 'data-instance-setting-tab="automatic_backup"')
&& str_contains($detail, 'id="vm-automatic-backup-service"')
&& str_contains($detail, 'id="vm-automatic-backup-activation-price"')
&& str_contains($detail, 'id="vm-automatic-backup-renewal-price"')
&& str_contains($detail, 'id="vm-automatic-backup-entitlement-end"')
&& str_contains($detail, 'id="vm-automatic-backup-enable"')
&& str_contains($detail, 'id="vm-automatic-backup-disable"')
&& str_contains($detail, 'id="vm-automatic-backup-frequency"')
&& str_contains($detail, '<option value="daily" selected>每天</option>')
&& str_contains($detail, '<option value="weekly">每周</option>')
@ -50,6 +56,12 @@ $assert(str_contains($detail, 'data-instance-setting-tab="automatic_backup"')
'Instance settings must own daily/weekly scheduling, Pacific midnight and the two-backup retention limit.');
$assert(str_contains($detailScript,
"`/api/v1/vms/\${encodeURIComponent(vmId)}/automatic-backup`")
&& str_contains($detailScript,
"`/api/v1/vms/\${encodeURIComponent(vmId)}/automatic-backup/enable`")
&& str_contains($detailScript,
"`/api/v1/vms/\${encodeURIComponent(vmId)}/automatic-backup/disable`")
&& str_contains($detailScript, "body: { expected_amount: expectedAmount }")
&& str_contains($detailScript, "headers: { 'Idempotency-Key': idempotencyKey }")
&& str_contains($detailScript, "method: 'PUT', body: { frequency, weekday, retention_count: retention }")
&& str_contains($detailScript,
"`/api/v1/vms/\${encodeURIComponent(vmId)}/automatic-backup/\${encodeURIComponent(id)}/restore`")
@ -72,6 +84,8 @@ $assert(str_contains($sidebar, 'href="/user/cloud/backups"')
'The global backup library must create new instances or link to instance settings, never restore the source directly.');
$assert(str_contains($styles, '.cloud-backups-list')
&& str_contains($styles, '.vm-automatic-backup-grid')
&& str_contains($styles, '.vm-automatic-backup-service')
&& str_contains($styles, '.vm-automatic-backup-service-actions')
&& str_contains($styles, '@media screen and (max-width:510px)')
&& str_contains($styles, '.cloud-backup-actions .button{flex:1 1 100%;width:100%}'),
'Backup library and settings must retain mobile layouts.');

@ -73,7 +73,7 @@ $assert(str_contains($auth, "Config::get('tos_reg') === 'true'")
'Legal consent is only client-side and can be bypassed.');
$assets = $read('web/resources/views/venix/layout_assets.tpl');
$assert(str_contains($assets, "value='2026102602'")
$assert(str_contains($assets, "value='2026102603'")
&& str_contains($admin, '?v={$venix_asset_version}')
&& str_contains($read('web/resources/views/venix/home/layout_header.tpl'), '?v={$venix_asset_version}'),
'Shared browser asset version was not coupled to the new assets.');

@ -82,6 +82,9 @@ foreach (['cloud_service_periods', 'cloud_renewals'] as $tableName) {
$table->increments('id'); $table->integer('user_id');
});
}
$schema->create('cloud_backup_period_entitlements', static function (Blueprint $table) {
$table->increments('id'); $table->integer('user_id');
});
$schema->create('cloud_invoices', static function (Blueprint $table) {
$table->increments('id'); $table->integer('user_id');
});
@ -158,6 +161,9 @@ foreach (['cloud_service_periods', 'cloud_renewals'] as $tableName) {
['user_id' => 1], ['user_id' => 3],
]);
}
Capsule::table('cloud_backup_period_entitlements')->insert([
['user_id' => 1], ['user_id' => 3],
]);
Capsule::table('cloud_invoices')->insert([
['id' => 103, 'user_id' => 1], ['id' => 303, 'user_id' => 3],
]);
@ -186,7 +192,8 @@ foreach (['yipay_orders', 'yipay_callback_events', 'yipay_refunds'] as $tableNam
}
foreach (['cloud_instances', 'cloud_orders', 'cloud_instance_snapshots',
'cloud_instance_firewalls', 'cloud_service_periods', 'cloud_renewals',
'cloud_invoices', 'cloud_invoice_payments'] as $tableName) {
'cloud_backup_period_entitlements', 'cloud_invoices',
'cloud_invoice_payments'] as $tableName) {
$assert(Capsule::table($tableName)->pluck('user_id')->all() === [3],
'Cloud account history deletion was not isolated: ' . $tableName);
}

@ -80,7 +80,7 @@ $assert(preg_match('/\.landing-site-header\s*\{[^}]*position:\s*fixed;/s', $css)
&& str_contains($accountCss, 'padding-top: 88px;')
&& str_contains($accountCss, 'padding-top: 76px;'),
'Persistent desktop or mobile public-navigation styling is incomplete.');
$assert(str_contains($read('web/resources/views/venix/layout_assets.tpl'), "value='2026102602'"),
$assert(str_contains($read('web/resources/views/venix/layout_assets.tpl'), "value='2026102603'"),
'The shared browser asset version was not advanced with the navigation styles.');
echo "Public page locale and shared-layout contract tests passed.\n";

@ -69,7 +69,7 @@ foreach ($templates as $template) {
}
$assets = $read('web/resources/views/venix/layout_assets.tpl');
$assert(str_contains($assets, "value='2026102602'"),
$assert(str_contains($assets, "value='2026102603'"),
'The shared asset version was not updated for the canonical logo.');
echo "Shared site-brand contract passed across public, auth, user, cloud and admin layouts.\n";

Loading…
Cancel
Save