You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
895 lines
36 KiB
PHP
895 lines
36 KiB
PHP
<?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\CloudServiceCompensationItem;
|
|
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 uncovered paid VM period.
|
|
*
|
|
* A paused, fully covered subscription is only a revisioned state change:
|
|
* it creates no invoice. New cover keeps wallet debit, invoice, subscription
|
|
* and immutable entitlements in one transaction. Paid retries reuse the
|
|
* payment reference; free retries are fenced by the state revision.
|
|
*/
|
|
public static function enable(
|
|
CloudInstance $instance,
|
|
User $user,
|
|
array $actor,
|
|
array $input,
|
|
?int $now = null
|
|
): array {
|
|
CloudInput::only($input, [
|
|
'expected_amount', 'expected_state_revision',
|
|
]);
|
|
self::assertActor($actor, $user);
|
|
$expected = $input['expected_amount'] ?? null;
|
|
if (!is_string($expected)) {
|
|
throw new CloudError('请确认自动备份开通金额');
|
|
}
|
|
$expectedCents = CloudMoney::cents($expected);
|
|
$expectedStateRevision = self::expectedStateRevision(
|
|
$input['expected_state_revision'] ?? null
|
|
);
|
|
$requestKey = self::requestKey($actor);
|
|
$paymentReference = 'backup-addon-'
|
|
. substr(hash('sha256', $requestKey), 0, 48);
|
|
$now ??= time();
|
|
|
|
return $instance->getConnection()->transaction(function () use (
|
|
$instance,
|
|
$user,
|
|
$expectedCents,
|
|
$expectedStateRevision,
|
|
$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
|
|
);
|
|
$currentStateRevision = self::stateRevision($subscription);
|
|
if ($expectedCents === 0
|
|
&& $quote['lines'] === []
|
|
&& (string) $quote['state'] === 'active'
|
|
&& $subscription !== null
|
|
&& $currentStateRevision === $expectedStateRevision + 1) {
|
|
return self::enableResult(
|
|
$locked,
|
|
$lockedUser,
|
|
null,
|
|
0,
|
|
$now
|
|
);
|
|
}
|
|
if ($currentStateRevision !== $expectedStateRevision) {
|
|
throw new CloudError(
|
|
'自动备份状态已变化,请刷新后重试',
|
|
409
|
|
);
|
|
}
|
|
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->state_revision = 1;
|
|
$subscription->created_at = $now;
|
|
} elseif ((int) $subscription->user_id !== (int) $lockedUser->id) {
|
|
throw new CloudError('自动备份订阅归属不一致', 409);
|
|
} else {
|
|
self::advanceStateRevision($subscription);
|
|
}
|
|
$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
|
|
);
|
|
CloudAutomaticBackupService::clearDeferredState($subscription);
|
|
$subscription->updated_at = $now;
|
|
$subscription->save();
|
|
|
|
if ($chargeCents === 0 && $quote['lines'] === []) {
|
|
CloudInvoiceService::refreshRenewalAfterBackupPolicyLocked(
|
|
$locked,
|
|
$now
|
|
);
|
|
return self::enableResult(
|
|
$locked,
|
|
$lockedUser,
|
|
null,
|
|
0,
|
|
$now
|
|
);
|
|
}
|
|
|
|
$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;
|
|
CloudAutomaticBackupService::clearDeferredState(
|
|
$subscription
|
|
);
|
|
self::advanceStateRevision($subscription);
|
|
$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' => $invoice === null
|
|
? null : (string) $invoice->id,
|
|
'charged_amount' => CloudMoney::decimal($chargedCents),
|
|
];
|
|
}
|
|
|
|
private static function expectedStateRevision(mixed $value): int
|
|
{
|
|
$revision = filter_var($value, FILTER_VALIDATE_INT, [
|
|
'options' => [
|
|
'min_range' => 0,
|
|
'max_range' => 4294967294,
|
|
],
|
|
]);
|
|
if ($revision === false) {
|
|
throw new CloudError('缺少有效的自动备份状态版本', 400);
|
|
}
|
|
return (int) $revision;
|
|
}
|
|
|
|
private static function stateRevision(
|
|
?CloudBackupSubscription $subscription
|
|
): int {
|
|
if ($subscription === null) {
|
|
return 0;
|
|
}
|
|
$revision = (int) $subscription->state_revision;
|
|
if ($revision < 1 || $revision > 4294967295) {
|
|
throw new CloudError('自动备份订阅状态版本异常', 409);
|
|
}
|
|
return $revision;
|
|
}
|
|
|
|
private static function advanceStateRevision(
|
|
CloudBackupSubscription $subscription
|
|
): int {
|
|
$revision = self::stateRevision($subscription);
|
|
if ($revision >= 4294967295) {
|
|
throw new CloudError('自动备份订阅状态版本已耗尽', 409);
|
|
}
|
|
$subscription->state_revision = $revision + 1;
|
|
return (int) $subscription->state_revision;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
if ($subscription === null) {
|
|
try {
|
|
$billingCycle = $offer->billingCycleForServiceDays(
|
|
(int) $instance->renewal_days
|
|
);
|
|
} catch (\InvalidArgumentException $exception) {
|
|
throw new CloudError(
|
|
'实例续费周期不受自动备份销售方案支持',
|
|
409
|
|
);
|
|
}
|
|
$fullPriceCents = CloudMoney::cents(
|
|
$billingCycle['backup_price']
|
|
);
|
|
} else {
|
|
$fullPriceCents = CloudMoney::cents(
|
|
(string) $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,
|
|
'state_revision' => self::stateRevision($subscription),
|
|
];
|
|
}
|
|
|
|
/** 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
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Extend an already-paid backup window with its parent service period.
|
|
* No entitlement or subscription is created or enabled by compensation;
|
|
* all paid commercial fields remain frozen.
|
|
*/
|
|
public static function extendEntitlementWindowForCompensationLocked(
|
|
int $servicePeriodId,
|
|
int $oldEnd,
|
|
int $newEnd,
|
|
int $compensationItemId,
|
|
int $now
|
|
): ?CloudBackupPeriodEntitlement {
|
|
if ($servicePeriodId < 1 || $oldEnd < 1 || $newEnd <= $oldEnd
|
|
|| $compensationItemId < 1) {
|
|
throw new CloudError('自动备份权益补偿窗口无效', 409);
|
|
}
|
|
$period = CloudServicePeriod::where('id', $servicePeriodId)
|
|
->lockForUpdate()->first();
|
|
if ($period === null
|
|
|| !in_array((int) $period->ends_at,
|
|
[$oldEnd, $newEnd], true)
|
|
|| (int) $period->starts_at >= (int) $period->ends_at) {
|
|
throw new CloudError('自动备份服务周期窗口不一致', 409);
|
|
}
|
|
$subscription = CloudBackupSubscription::where(
|
|
'instance_id', (int) $period->instance_id
|
|
)->lockForUpdate()->first();
|
|
$entitlement = CloudBackupPeriodEntitlement::where(
|
|
'service_period_id', $servicePeriodId
|
|
)->lockForUpdate()->first();
|
|
if ($entitlement === null) {
|
|
return null;
|
|
}
|
|
if ($subscription === null) {
|
|
throw new CloudError('自动备份周期权益身份不一致', 409);
|
|
}
|
|
$fullPriceCents = CloudMoney::cents(
|
|
(string) $entitlement->full_period_price
|
|
);
|
|
$paidAmountCents = CloudMoney::cents((string) $entitlement->amount);
|
|
if ((int) $subscription->id
|
|
!== (int) $entitlement->subscription_id
|
|
|| (int) $subscription->instance_id
|
|
!== (int) $period->instance_id
|
|
|| (int) $subscription->user_id !== (int) $period->user_id
|
|
|| (int) $entitlement->instance_id
|
|
!== (int) $period->instance_id
|
|
|| (int) $entitlement->user_id !== (int) $period->user_id
|
|
|| (int) $entitlement->offer_id < 1
|
|
|| (int) $entitlement->starts_at !== (int) $period->starts_at
|
|
|| strtoupper((string) $subscription->currency) !== 'USD'
|
|
|| strtoupper((string) $entitlement->currency) !== 'USD'
|
|
|| $fullPriceCents < 0
|
|
|| (int) $entitlement->price_version < 1
|
|
|| $paidAmountCents < 0
|
|
|| $paidAmountCents > $fullPriceCents
|
|
|| ((string) $entitlement->source !== 'addon'
|
|
&& $paidAmountCents !== $fullPriceCents)
|
|
|| (int) $entitlement->invoice_id < 1
|
|
|| (int) $entitlement->paid_at < 1
|
|
|| !in_array((string) $entitlement->source,
|
|
['provision', 'renewal', 'addon'], true)) {
|
|
throw new CloudError('自动备份周期权益身份不一致', 409);
|
|
}
|
|
|
|
if ((int) $entitlement->ends_at === $newEnd) {
|
|
$item = CloudServiceCompensationItem::where(
|
|
'id', $compensationItemId
|
|
)->lockForUpdate()->first();
|
|
if ($item === null || (string) $item->state !== 'applied'
|
|
|| (int) $item->service_period_id !== $servicePeriodId
|
|
|| (int) $item->backup_entitlement_id
|
|
!== (int) $entitlement->id
|
|
|| (int) $item->before_backup_ends_at !== $oldEnd
|
|
|| (int) $item->after_backup_ends_at !== $newEnd) {
|
|
throw new CloudError('自动备份权益补偿幂等记录冲突', 409);
|
|
}
|
|
return $entitlement;
|
|
}
|
|
if ((int) $period->ends_at !== $oldEnd
|
|
|| (int) $entitlement->ends_at !== $oldEnd) {
|
|
throw new CloudError('自动备份权益当前窗口不允许延长', 409);
|
|
}
|
|
$entitlement->ends_at = $newEnd;
|
|
$entitlement->updated_at = $now;
|
|
$entitlement->save();
|
|
return $entitlement;
|
|
}
|
|
|
|
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);
|
|
}
|
|
if ($source === 'renewal') {
|
|
self::resumeRenewedScheduleLocked(
|
|
$subscription, $period, $now
|
|
);
|
|
}
|
|
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();
|
|
if ($source === 'renewal') {
|
|
self::resumeRenewedScheduleLocked(
|
|
$subscription, $period, $now
|
|
);
|
|
}
|
|
return $entitlement;
|
|
}
|
|
|
|
/** Resume only a system expiry pause; a user cancellation stays closed. */
|
|
private static function resumeRenewedScheduleLocked(
|
|
CloudBackupSubscription $subscription,
|
|
CloudServicePeriod $period,
|
|
int $now
|
|
): void {
|
|
if ((bool) $subscription->enabled
|
|
|| !(bool) $subscription->renew_next_period) {
|
|
return;
|
|
}
|
|
$subscription->enabled = true;
|
|
self::advanceStateRevision($subscription);
|
|
$subscription->next_run_at =
|
|
CloudAutomaticBackupService::nextRunAt(
|
|
max($now, (int) $period->starts_at),
|
|
(string) $subscription->frequency,
|
|
(int) $subscription->weekday
|
|
);
|
|
CloudAutomaticBackupService::clearDeferredState($subscription);
|
|
$subscription->updated_at = $now;
|
|
$subscription->save();
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|