feat(cloud): add paid automatic backup controls
parent
c4fa9d0f56
commit
7df662415b
@ -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',
|
||||
];
|
||||
}
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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'}
|
||||
|
||||
@ -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";
|
||||
Loading…
Reference in New Issue