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.
1822 lines
79 KiB
PHP
1822 lines
79 KiB
PHP
<?php
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudInstance;
|
|
use App\Models\CloudBackupSubscription;
|
|
use App\Models\CloudInvoice;
|
|
use App\Models\CloudInvoiceItem;
|
|
use App\Models\CloudInvoicePayment;
|
|
use App\Models\CloudMailOutbox;
|
|
use App\Models\CloudOffer;
|
|
use App\Models\CloudOrder;
|
|
use App\Models\CloudOrderItem;
|
|
use App\Models\CloudRenewal;
|
|
use App\Models\CloudServicePeriod;
|
|
use App\Models\CloudJob;
|
|
use App\Models\Shop;
|
|
use App\Models\User;
|
|
use App\Services\Config;
|
|
use App\Services\Mail;
|
|
|
|
final class CloudInvoiceService
|
|
{
|
|
public const REMINDER_SECONDS = 7 * 86400;
|
|
public const PAYMENT_GRACE_SECONDS = 3 * 86400;
|
|
|
|
private static array $observedErrors = [];
|
|
|
|
/** Last invocation only; fixed observation codes never alter financial outcomes. */
|
|
public static function observationErrors(string $operation): array
|
|
{
|
|
return array_keys(self::$observedErrors[$operation] ?? []);
|
|
}
|
|
|
|
public static function paymentDeadline(CloudInvoice $invoice): ?int
|
|
{
|
|
$purpose = (string) ($invoice->purpose ?: 'renewal');
|
|
if ($purpose === 'provision') {
|
|
return (int) $invoice->due_at;
|
|
}
|
|
if ($purpose === 'renewal') {
|
|
$serviceExpiry = $invoice->renews_expires_at === null
|
|
? (int) $invoice->due_at : (int) $invoice->renews_expires_at;
|
|
// due_at is normally the service expiry. A delayed operation
|
|
// recovery may move it forward to grant the user the full grace
|
|
// period that was unavailable while the instance was fenced.
|
|
return max(0, $serviceExpiry, (int) $invoice->due_at)
|
|
+ self::PAYMENT_GRACE_SECONDS;
|
|
}
|
|
// Already-settled operational invoices are audit records and do not
|
|
// have a second payment window.
|
|
return null;
|
|
}
|
|
|
|
public static function paymentDeadlinePassed(CloudInvoice $invoice, ?int $now = null): bool
|
|
{
|
|
$deadline = self::paymentDeadline($invoice);
|
|
return $deadline !== null && $deadline <= ($now ?? time());
|
|
}
|
|
|
|
public static function instanceDeleting(CloudInstance $instance): bool
|
|
{
|
|
return in_array((string) $instance->status,
|
|
['deleting', 'delete_failed', 'deleted'], true)
|
|
|| in_array((string) $instance->service_status,
|
|
['purge_stopping', 'purge_stop_failed',
|
|
'purge_force_required', 'purge_deleting', 'purge_failed'],
|
|
true);
|
|
}
|
|
|
|
/** Create the initial bill for a validated, encrypted provisioning order. */
|
|
public static function issueProvision(CloudOrder $order, Shop $plan,
|
|
CloudOffer $offer, int $now): CloudInvoice
|
|
{
|
|
$existing = CloudInvoice::where('order_id', $order->id)->first();
|
|
if ($existing !== null) {
|
|
return $existing;
|
|
}
|
|
if ((string) $order->status !== 'awaiting_payment'
|
|
|| (int) $order->plan_id !== (int) $plan->id
|
|
|| (int) $order->offer_id !== (int) $offer->id
|
|
|| (int) $offer->plan_id !== (int) $plan->id
|
|
|| !is_string($order->sealed_payload)
|
|
|| trim((string) $order->sealed_payload) === '') {
|
|
throw new CloudError('开通订单状态无效', 409);
|
|
}
|
|
$orderItems = CloudOrderItem::where('order_id', (int) $order->id)
|
|
->orderBy('id')->get();
|
|
$itemTotal = 0;
|
|
$codes = [];
|
|
foreach ($orderItems as $orderItem) {
|
|
$code = (string) $orderItem->code;
|
|
if (!in_array($code, ['instance', 'automatic_backup'], true)
|
|
|| isset($codes[$code])
|
|
|| strtoupper((string) $orderItem->currency) !== 'USD') {
|
|
throw new CloudError('开通订单费用明细无效', 409);
|
|
}
|
|
$codes[$code] = true;
|
|
$itemTotal += CloudMoney::cents((string) $orderItem->amount);
|
|
}
|
|
if (!isset($codes['instance'])
|
|
|| $itemTotal !== CloudMoney::cents((string) $order->amount)) {
|
|
throw new CloudError('开通订单费用明细合计不一致', 409);
|
|
}
|
|
$invoice = new CloudInvoice();
|
|
$invoice->invoice_no = self::invoiceNumber();
|
|
$invoice->purpose = 'provision';
|
|
$invoice->instance_id = null;
|
|
$invoice->order_id = $order->id;
|
|
$invoice->user_id = $order->user_id;
|
|
$invoice->plan_id = $order->plan_id;
|
|
$invoice->offer_id = $order->offer_id;
|
|
$invoice->renewal_id = null;
|
|
$invoice->renews_expires_at = null;
|
|
$invoice->due_at = $now
|
|
+ CloudProvisioningBillingConfig::paymentWindowSeconds();
|
|
$invoice->amount = $order->amount;
|
|
$invoice->currency = 'USD';
|
|
$invoice->validity_days = (int) $plan->validity_days;
|
|
$invoice->traffic_quota_bytes = max(0, (int) $plan->traffic_quota_bytes);
|
|
$invoice->status = 'open';
|
|
$invoice->paid_via = null;
|
|
$invoice->payment_reference = null;
|
|
$invoice->paid_at = null;
|
|
$invoice->created_at = $invoice->updated_at = $now;
|
|
$invoice->save();
|
|
foreach ($orderItems as $orderItem) {
|
|
$item = new CloudInvoiceItem();
|
|
$item->invoice_id = (int) $invoice->id;
|
|
$item->order_item_id = (int) $orderItem->id;
|
|
$item->code = (string) $orderItem->code;
|
|
$item->label = (string) $orderItem->label;
|
|
$item->amount = (string) $orderItem->amount;
|
|
$item->currency = (string) $orderItem->currency;
|
|
$item->snapshot_json = (string) $orderItem->snapshot_json;
|
|
$item->created_at = $now;
|
|
$item->save();
|
|
}
|
|
return $invoice;
|
|
}
|
|
|
|
/** Expire abandoned initial bills and return their finite stock safely. */
|
|
public static function expireProvision(int $limit = 200): int
|
|
{
|
|
$now = time();
|
|
$ids = CloudInvoice::where('purpose', 'provision')
|
|
->whereIn('status', ['open', 'overdue'])
|
|
->where('due_at', '<=', $now)->orderBy('id')
|
|
->limit(max(1, min(1000, $limit)))->pluck('id')->all();
|
|
$expired = 0;
|
|
foreach ($ids as $id) {
|
|
$expired += (new User())->getConnection()->transaction(function () use ($id, $now) {
|
|
$ownerId = CloudInvoice::where('id', $id)->value('user_id');
|
|
if ($ownerId === null) {
|
|
return 0;
|
|
}
|
|
// Match payment settlement's user -> invoice -> order -> plan
|
|
// lock order so expiry and a callback cannot both win.
|
|
User::where('id', (int) $ownerId)->lockForUpdate()->first();
|
|
$invoice = CloudInvoice::where('id', $id)->lockForUpdate()->first();
|
|
if ($invoice === null || (string) $invoice->purpose !== 'provision'
|
|
|| !in_array((string) $invoice->status, ['open', 'overdue'], true)
|
|
|| (int) $invoice->due_at > $now) {
|
|
return 0;
|
|
}
|
|
$order = CloudOrder::where('id', $invoice->order_id)
|
|
->lockForUpdate()->first();
|
|
if ($order !== null && (string) $order->status === 'awaiting_payment') {
|
|
CloudOrderService::releaseStock($order);
|
|
$order->status = 'expired';
|
|
$order->sealed_payload = null;
|
|
$order->updated_at = $now;
|
|
$order->save();
|
|
}
|
|
$invoice->status = 'expired';
|
|
$invoice->updated_at = $now;
|
|
$invoice->save();
|
|
return 1;
|
|
}, 3);
|
|
}
|
|
return $expired;
|
|
}
|
|
|
|
public static function issueDue(int $limit = 200): int
|
|
{
|
|
self::$observedErrors['issue_due'] = [];
|
|
$now = time();
|
|
$ids = CloudInstance::where('status', '<>', 'deleted')
|
|
->whereNotIn('status', ['deleting', 'delete_failed'])
|
|
->where('service_status', '<>', 'exempt')
|
|
->whereNotIn('service_status', ['purge_stopping', 'purge_stop_failed',
|
|
'purge_force_required', 'purge_deleting', 'purge_failed'])
|
|
->whereNotNull('expires_at')
|
|
->whereNotNull('renewal_price')
|
|
->where('renewal_days', '>', 0)
|
|
->where('expires_at', '<=', $now + self::REMINDER_SECONDS)
|
|
->whereNotExists(function ($query) {
|
|
$query->selectRaw('1')->from('cloud_invoices')
|
|
->whereColumn('cloud_invoices.instance_id', 'cloud_instances.id')
|
|
->whereColumn('cloud_invoices.renews_expires_at', 'cloud_instances.expires_at')
|
|
->where('cloud_invoices.status', '<>', 'void');
|
|
})
|
|
->orderBy('expires_at')->orderBy('id')
|
|
->limit(max(1, min(1000, $limit)))
|
|
->pluck('id')->all();
|
|
$created = 0;
|
|
foreach ($ids as $id) {
|
|
try {
|
|
$created += self::issueOne((int) $id, $now) ? 1 : 0;
|
|
} catch (\Throwable $error) {
|
|
self::$observedErrors['issue_due']['invoice_generation_failed'] = true;
|
|
error_log('cloud invoice generation failed for instance ' . (int) $id
|
|
. ': ' . get_class($error));
|
|
}
|
|
}
|
|
return $created;
|
|
}
|
|
|
|
private static function issueOne(int $instanceId, int $now): bool
|
|
{
|
|
return (new CloudInstance())->getConnection()->transaction(function () use ($instanceId, $now) {
|
|
$instance = CloudInstance::where('id', $instanceId)->lockForUpdate()->first();
|
|
if ($instance === null || (string) $instance->status === 'deleted'
|
|
|| self::instanceDeleting($instance)
|
|
|| (string) $instance->service_status === 'exempt'
|
|
|| $instance->expires_at === null || $instance->renewal_price === null
|
|
|| (int) $instance->renewal_days < 1
|
|
|| (int) $instance->expires_at > $now + self::REMINDER_SECONDS) {
|
|
return false;
|
|
}
|
|
if (CloudJobService::blockingQueryForInstance((int) $instance->id)
|
|
->where('kind', 'instance_upgrade')->exists()) {
|
|
return false;
|
|
}
|
|
$expiry = (int) $instance->expires_at;
|
|
if (CloudInvoice::where('instance_id', $instance->id)
|
|
->where('renews_expires_at', $expiry)
|
|
->where('status', '<>', 'void')->exists()) {
|
|
return false;
|
|
}
|
|
self::createRenewalInvoiceLocked($instance, $expiry, $now);
|
|
return true;
|
|
}, 3);
|
|
}
|
|
|
|
/**
|
|
* Reconcile the next renewal bill after an upgrade fence is resolved.
|
|
*
|
|
* The service expiry remains immutable. If the final套餐 changed, or the
|
|
* upgrade fence crossed the original expiry, the old unpaid bill is
|
|
* closed and a fresh immutable bill is issued from the final instance
|
|
* snapshot. due_at then acts only as the start of the restored grace
|
|
* window.
|
|
*/
|
|
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
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Move one still-unsettled renewal target after an audited service-time
|
|
* compensation. Callers already hold the owner and instance rows. The
|
|
* old bill is closed rather than rewritten so its original commercial
|
|
* target remains an immutable audit fact.
|
|
*
|
|
* @return array{source_invoice_id:?int,replacement_invoice:?CloudInvoice}
|
|
*/
|
|
public static function reconcileRenewalAfterCompensationLocked(
|
|
CloudInstance $instance,
|
|
int $oldExpiry,
|
|
int $newExpiry,
|
|
int $now
|
|
): array {
|
|
if ((int) $instance->id < 1 || (int) $instance->user_id < 1
|
|
|| $oldExpiry < 1 || $newExpiry <= $oldExpiry
|
|
|| (int) $instance->expires_at !== $newExpiry) {
|
|
throw new CloudError('实例补偿后的续费目标无效', 409);
|
|
}
|
|
|
|
$oldInvoices = CloudInvoice::where(
|
|
'instance_id', (int) $instance->id
|
|
)->where('purpose', 'renewal')
|
|
->where('renews_expires_at', $oldExpiry)
|
|
->where('status', '<>', 'void')
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
if ($oldInvoices->count() > 1) {
|
|
throw new CloudError('实例旧到期时间存在重复续费账单', 409);
|
|
}
|
|
$source = $oldInvoices->first();
|
|
if ($source !== null) {
|
|
if ((int) $source->user_id !== (int) $instance->user_id
|
|
|| $source->renewal_id !== null
|
|
|| $source->paid_at !== null
|
|
|| (string) $source->status === 'paid') {
|
|
throw new CloudError('实例旧续费账单已经结算', 409);
|
|
}
|
|
if (!in_array((string) $source->status, [
|
|
'open', 'overdue', 'expired',
|
|
], true)) {
|
|
throw new CloudError('实例旧续费账单状态异常', 409);
|
|
}
|
|
$payments = CloudInvoicePayment::where(
|
|
'invoice_id', (int) $source->id
|
|
)->orderBy('id')->lockForUpdate()->get();
|
|
if ($payments->contains(static fn ($payment): bool => !in_array(
|
|
(string) $payment->status,
|
|
['failed', 'expired', 'not_created'],
|
|
true
|
|
))) {
|
|
throw new CloudError('实例旧续费账单已有支付或仍待核对', 409);
|
|
}
|
|
$blockingJobs = CloudJobService::blockingQueryForInvoice(
|
|
(int) $source->id
|
|
)->orderBy('id')->lockForUpdate()->get(['id']);
|
|
if (!$blockingJobs->isEmpty()) {
|
|
throw new CloudError('实例旧续费支付结果仍待核对', 409);
|
|
}
|
|
}
|
|
|
|
$newInvoices = CloudInvoice::where(
|
|
'instance_id', (int) $instance->id
|
|
)->where('purpose', 'renewal')
|
|
->where('renews_expires_at', $newExpiry)
|
|
->where('status', '<>', 'void')
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
if ($newInvoices->count() > 1) {
|
|
throw new CloudError('实例新到期时间存在重复续费账单', 409);
|
|
}
|
|
$replacement = $newInvoices->first();
|
|
if ($replacement !== null) {
|
|
if (!in_array((string) $replacement->status,
|
|
['open', 'overdue'], true)
|
|
|| $replacement->renewal_id !== null
|
|
|| $replacement->paid_at !== null
|
|
|| (int) $replacement->user_id !== (int) $instance->user_id
|
|
|| (int) $replacement->plan_id !== (int) $instance->plan_id
|
|
|| (int) $replacement->validity_days
|
|
!== (int) $instance->renewal_days
|
|
|| (int) $replacement->traffic_quota_bytes
|
|
!== max(0, (int) $instance->renewal_traffic_bytes)
|
|
|| !self::renewalInvoiceMatches($instance, $replacement)) {
|
|
throw new CloudError('实例新续费账单快照不一致', 409);
|
|
}
|
|
}
|
|
|
|
if ($source !== null) {
|
|
if (!self::fenceRenewalMailForCompensationLocked(
|
|
$source,
|
|
$now
|
|
)) {
|
|
throw new CloudError(
|
|
'实例旧续费账单提醒邮件仍在投递',
|
|
409
|
|
);
|
|
}
|
|
$source->status = 'void';
|
|
$source->updated_at = $now;
|
|
$source->save();
|
|
}
|
|
if ($replacement === null
|
|
&& $newExpiry <= $now + self::REMINDER_SECONDS) {
|
|
$replacement = self::createRenewalInvoiceLocked(
|
|
$instance,
|
|
$newExpiry,
|
|
$now
|
|
);
|
|
}
|
|
return [
|
|
'source_invoice_id' => $source === null
|
|
? null : (int) $source->id,
|
|
'replacement_invoice' => $replacement,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Fence an obsolete renewal reminder before replacing its invoice.
|
|
*
|
|
* The caller already holds the source invoice inside the compensation
|
|
* transaction. A sender claims the outbox row before contacting SMTP, so
|
|
* locking that row gives the transaction a strict ordering: admission may
|
|
* first lock without mutating, then reconciliation cancels pending mail
|
|
* before the invoice is voided. An already-sending message makes
|
|
* compensation wait without holding a transaction across the SMTP call.
|
|
*
|
|
* @return bool false only while the reminder is actively sending
|
|
*/
|
|
public static function fenceRenewalMailForCompensationLocked(
|
|
CloudInvoice $invoice,
|
|
int $now,
|
|
bool $cancelPending = true
|
|
): bool {
|
|
if ((int) $invoice->id < 1
|
|
|| (string) $invoice->purpose !== 'renewal') {
|
|
throw new CloudError('实例旧续费账单邮件目标无效', 409);
|
|
}
|
|
$messages = CloudMailOutbox::where(
|
|
'invoice_id',
|
|
(int) $invoice->id
|
|
)->where('kind', 'renewal_due')->orderBy('id')
|
|
->lockForUpdate()->get();
|
|
if ($messages->count() > 1) {
|
|
throw new CloudError('实例旧续费账单存在重复邮件任务', 409);
|
|
}
|
|
$message = $messages->first();
|
|
if ($message === null) {
|
|
return true;
|
|
}
|
|
$status = (string) $message->status;
|
|
if ($status === 'sending') {
|
|
return false;
|
|
}
|
|
if ($status === 'pending') {
|
|
if (!$cancelPending) {
|
|
return true;
|
|
}
|
|
$message->status = 'cancelled';
|
|
$message->available_at = 0;
|
|
$message->lease_token = null;
|
|
$message->lease_until = 0;
|
|
$message->sent_at = null;
|
|
$message->last_error = '续费目标已因实例服务时间补偿变更';
|
|
$message->updated_at = $now;
|
|
$message->save();
|
|
return true;
|
|
}
|
|
if (in_array($status, ['sent', 'failed', 'cancelled'], true)) {
|
|
return true;
|
|
}
|
|
throw new CloudError('实例旧续费账单邮件状态异常', 409);
|
|
}
|
|
|
|
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)) {
|
|
self::renewalRefreshConflict(
|
|
$context . '续费快照不可用',
|
|
$recoveryConflict
|
|
);
|
|
}
|
|
$expiry = (int) $instance->expires_at;
|
|
$invoices = CloudInvoice::where('instance_id', (int) $instance->id)
|
|
->where('purpose', 'renewal')
|
|
->where('renews_expires_at', $expiry)
|
|
->where('status', '<>', 'void')
|
|
->orderBy('id')->lockForUpdate()->get();
|
|
$ids = $invoices->pluck('id')->map(
|
|
static fn ($id): int => (int) $id
|
|
)->values()->all();
|
|
if ($ids !== []) {
|
|
if ($invoices->contains(static fn ($candidate): bool =>
|
|
$candidate->renewal_id !== null
|
|
|| (string) $candidate->status === 'paid')) {
|
|
self::renewalRefreshConflict(
|
|
$context . '发现已结算续费账单',
|
|
$recoveryConflict
|
|
);
|
|
}
|
|
if (CloudInvoicePayment::whereIn('invoice_id', $ids)
|
|
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
|
|
->lockForUpdate()->exists()) {
|
|
self::renewalRefreshConflict(
|
|
$context . '续费支付仍在处理中',
|
|
$recoveryConflict
|
|
);
|
|
}
|
|
foreach ($ids as $invoiceId) {
|
|
if (CloudJobService::blockingQueryForInvoice($invoiceId)
|
|
->exists()) {
|
|
self::renewalRefreshConflict(
|
|
$context . '续费支付结果仍待核对',
|
|
$recoveryConflict
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
$quote = self::renewalQuoteLocked($instance);
|
|
$amount = CloudMoney::decimal($quote['total_cents']);
|
|
$matchesFinalSnapshot = static function ($candidate) use (
|
|
$instance,
|
|
$amount
|
|
): bool {
|
|
return in_array((string) $candidate->status,
|
|
['open', 'overdue'], true)
|
|
&& (int) $candidate->plan_id === (int) $instance->plan_id
|
|
&& CloudMoney::cents((string) $candidate->amount)
|
|
=== CloudMoney::cents($amount)
|
|
&& self::renewalInvoiceMatches($instance, $candidate)
|
|
&& (int) $candidate->validity_days
|
|
=== (int) $instance->renewal_days
|
|
&& (int) $candidate->traffic_quota_bytes
|
|
=== max(0, (int) $instance->renewal_traffic_bytes);
|
|
};
|
|
$matching = $invoices->first($matchesFinalSnapshot);
|
|
if ($matching !== null && $expiry > $now) {
|
|
return $matching;
|
|
}
|
|
|
|
foreach ($invoices as $candidate) {
|
|
if (!in_array((string) $candidate->status,
|
|
['open', 'overdue', 'expired'], true)) {
|
|
self::renewalRefreshConflict(
|
|
$context . '续费账单状态异常',
|
|
$recoveryConflict
|
|
);
|
|
}
|
|
$candidate->status = 'void';
|
|
$candidate->updated_at = $now;
|
|
$candidate->save();
|
|
}
|
|
if ($expiry > $now + self::REMINDER_SECONDS) {
|
|
return null;
|
|
}
|
|
return self::createRenewalInvoiceLocked(
|
|
$instance,
|
|
max($expiry, $now),
|
|
$now
|
|
);
|
|
}
|
|
|
|
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,
|
|
int $now
|
|
): CloudInvoice {
|
|
$quote = self::renewalQuoteLocked($instance);
|
|
$invoice = new CloudInvoice();
|
|
$invoice->invoice_no = self::invoiceNumber();
|
|
$invoice->purpose = 'renewal';
|
|
$invoice->instance_id = $instance->id;
|
|
$invoice->order_id = null;
|
|
$invoice->user_id = $instance->user_id;
|
|
$invoice->plan_id = $instance->plan_id;
|
|
$invoice->renewal_id = null;
|
|
$invoice->renews_expires_at = (int) $instance->expires_at;
|
|
$invoice->due_at = $dueAt;
|
|
$invoice->amount = CloudMoney::decimal($quote['total_cents']);
|
|
$invoice->currency = 'USD';
|
|
$invoice->validity_days = (int) $instance->renewal_days;
|
|
$invoice->traffic_quota_bytes =
|
|
max(0, (int) $instance->renewal_traffic_bytes);
|
|
$invoice->status = 'open';
|
|
$invoice->paid_via = null;
|
|
$invoice->payment_reference = null;
|
|
$invoice->paid_at = null;
|
|
$invoice->created_at = $invoice->updated_at = $now;
|
|
$invoice->save();
|
|
self::createRenewalItems($invoice, $instance, $quote, $now);
|
|
self::enqueueMail($invoice, 'renewal_due', $now);
|
|
return $invoice;
|
|
}
|
|
|
|
/**
|
|
* Compose one renewal from the immutable instance base price and its paid
|
|
* automatic-backup subscription. Callers already hold the instance row.
|
|
*
|
|
* @return array{instance_cents:int,backup_cents:int,total_cents:int,
|
|
* backup_subscription_id:?int}
|
|
*/
|
|
public static function renewalQuoteLocked(
|
|
CloudInstance $instance
|
|
): array {
|
|
$instanceCents = $instance->renewal_price === null
|
|
? -1 : CloudMoney::cents((string) $instance->renewal_price);
|
|
if ($instanceCents < 0) {
|
|
throw new CloudError('实例缺少基础续费价格快照', 409);
|
|
}
|
|
$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,
|
|
'total_cents' => $instanceCents,
|
|
'backup_subscription_id' => null,
|
|
];
|
|
}
|
|
if ((int) $subscription->user_id !== (int) $instance->user_id
|
|
|| (int) $subscription->offer_id !== (int) $instance->offer_id
|
|
|| strtoupper((string) $subscription->currency) !== 'USD') {
|
|
throw new CloudError('实例自动备份订阅账本不一致', 409);
|
|
}
|
|
$backupCents = CloudMoney::cents((string) $subscription->price);
|
|
return [
|
|
'instance_cents' => $instanceCents,
|
|
'backup_cents' => $backupCents,
|
|
'total_cents' => $instanceCents + $backupCents,
|
|
'backup_subscription_id' => (int) $subscription->id,
|
|
];
|
|
}
|
|
|
|
public static function renewalInvoiceMatches(
|
|
CloudInstance $instance,
|
|
CloudInvoice $invoice
|
|
): bool {
|
|
try {
|
|
$quote = self::renewalQuoteLocked($instance);
|
|
} catch (\Throwable $error) {
|
|
return false;
|
|
}
|
|
if ((string) $invoice->purpose !== 'renewal'
|
|
|| CloudMoney::cents((string) $invoice->amount)
|
|
!== $quote['total_cents']) {
|
|
return false;
|
|
}
|
|
$items = CloudInvoiceItem::where(
|
|
'invoice_id', (int) $invoice->id
|
|
)->orderBy('id')->get();
|
|
$amounts = [];
|
|
foreach ($items as $item) {
|
|
$code = (string) $item->code;
|
|
if (isset($amounts[$code])
|
|
|| !in_array($code,
|
|
['instance', 'automatic_backup'], true)
|
|
|| strtoupper((string) $item->currency) !== 'USD') {
|
|
return false;
|
|
}
|
|
$amounts[$code] = CloudMoney::cents(
|
|
(string) $item->amount
|
|
);
|
|
}
|
|
return ($amounts['instance'] ?? -1) === $quote['instance_cents']
|
|
&& ($amounts['automatic_backup'] ?? 0)
|
|
=== $quote['backup_cents']
|
|
&& (($quote['backup_subscription_id'] === null)
|
|
=== !array_key_exists('automatic_backup', $amounts));
|
|
}
|
|
|
|
private static function createRenewalItems(
|
|
CloudInvoice $invoice,
|
|
CloudInstance $instance,
|
|
array $quote,
|
|
int $now
|
|
): void {
|
|
$rows = [[
|
|
'code' => 'instance',
|
|
'label' => '实例套餐续费',
|
|
'amount' => $quote['instance_cents'],
|
|
'snapshot' => [
|
|
'instance_id' => (int) $instance->id,
|
|
'plan_id' => (int) $instance->plan_id,
|
|
'validity_days' => (int) $instance->renewal_days,
|
|
],
|
|
]];
|
|
if ($quote['backup_subscription_id'] !== null) {
|
|
$rows[] = [
|
|
'code' => 'automatic_backup',
|
|
'label' => '自动备份续费',
|
|
'amount' => $quote['backup_cents'],
|
|
'snapshot' => [
|
|
'subscription_id' =>
|
|
$quote['backup_subscription_id'],
|
|
'validity_days' => (int) $instance->renewal_days,
|
|
],
|
|
];
|
|
}
|
|
$total = 0;
|
|
foreach ($rows as $row) {
|
|
$item = new CloudInvoiceItem();
|
|
$item->invoice_id = (int) $invoice->id;
|
|
$item->order_item_id = null;
|
|
$item->code = $row['code'];
|
|
$item->label = $row['label'];
|
|
$item->amount = CloudMoney::decimal($row['amount']);
|
|
$item->currency = 'USD';
|
|
$item->snapshot_json = json_encode(
|
|
$row['snapshot'],
|
|
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
);
|
|
$item->created_at = $now;
|
|
$item->save();
|
|
$total += $row['amount'];
|
|
}
|
|
if ($total !== $quote['total_cents']) {
|
|
throw new \RuntimeException('续费账单费用明细合计不一致');
|
|
}
|
|
}
|
|
|
|
/** Queue one idempotent notification after a paid instance is available. */
|
|
public static function queueProvisionSucceeded(CloudInvoice $invoice,
|
|
int $now): bool
|
|
{
|
|
if ((string) $invoice->purpose !== 'provision'
|
|
|| (string) $invoice->status !== 'paid'
|
|
|| $invoice->instance_id === null) {
|
|
return false;
|
|
}
|
|
return self::enqueueMail($invoice, 'provision_succeeded', $now);
|
|
}
|
|
|
|
private static function enqueueMail(CloudInvoice $invoice, string $kind,
|
|
int $now): bool
|
|
{
|
|
if (!in_array($kind, ['renewal_due', 'provision_succeeded'], true)) {
|
|
throw new \InvalidArgumentException('Unsupported cloud mail kind');
|
|
}
|
|
if (CloudMailOutbox::where('invoice_id', $invoice->id)
|
|
->where('kind', $kind)->exists()) {
|
|
return false;
|
|
}
|
|
// Do not use mass assignment here. Models intentionally keep
|
|
// Illuminate's guarded defaults, and both callers already hold the
|
|
// authoritative invoice/instance transaction locks. The database
|
|
// unique key on (invoice_id, kind) is the final concurrency guard.
|
|
$mail = new CloudMailOutbox();
|
|
$mail->invoice_id = $invoice->id;
|
|
$mail->kind = $kind;
|
|
$mail->status = 'pending';
|
|
$mail->attempts = 0;
|
|
$mail->available_at = $now;
|
|
$mail->lease_token = null;
|
|
$mail->lease_until = 0;
|
|
$mail->sent_at = null;
|
|
$mail->last_error = '';
|
|
$mail->created_at = $mail->updated_at = $now;
|
|
$mail->save();
|
|
return true;
|
|
}
|
|
|
|
public static function deliverReminders(int $limit = 20): int
|
|
{
|
|
self::$observedErrors['notifications'] = [];
|
|
$sent = 0;
|
|
for ($index = 0; $index < max(1, min(100, $limit)); $index++) {
|
|
$claimed = self::claimMail();
|
|
if ($claimed === null) {
|
|
break;
|
|
}
|
|
[$message, $token] = $claimed;
|
|
$invoice = CloudInvoice::find($message->invoice_id);
|
|
$user = $invoice === null ? null : User::find($invoice->user_id);
|
|
$instance = $invoice === null ? null : CloudInstance::find($invoice->instance_id);
|
|
$kind = (string) $message->kind;
|
|
$order = $kind !== 'provision_succeeded' || $invoice === null
|
|
|| $invoice->order_id === null ? null
|
|
: CloudOrder::where('id', $invoice->order_id)
|
|
->where('user_id', $invoice->user_id)
|
|
->where('instance_id', $invoice->instance_id)->first();
|
|
$job = $order === null ? null
|
|
: CloudJob::where('order_id', $order->id)
|
|
->where('user_id', $invoice->user_id)
|
|
->where('instance_id', $invoice->instance_id)->first();
|
|
$ok = false;
|
|
$error = '';
|
|
$cancel = false;
|
|
if ($invoice === null || $user === null || $instance === null
|
|
|| (int) $instance->user_id !== (int) $invoice->user_id
|
|
|| self::instanceDeleting($instance)) {
|
|
$error = '账单或收件人已不可用';
|
|
$cancel = true;
|
|
} elseif ($kind === 'renewal_due'
|
|
&& ((string) $invoice->purpose !== 'renewal'
|
|
|| !in_array((string) $invoice->status, ['open', 'overdue'], true)
|
|
|| self::paymentDeadlinePassed($invoice))) {
|
|
$error = '续费账单已不可用';
|
|
$cancel = true;
|
|
} elseif ($kind === 'provision_succeeded'
|
|
&& ((string) $invoice->purpose !== 'provision'
|
|
|| (string) $invoice->status !== 'paid'
|
|
|| (string) $instance->status !== 'active'
|
|
|| $order === null || (string) $order->status !== 'succeeded'
|
|
|| self::taskStatus($job) !== 'succeeded')) {
|
|
$error = '实例开通通知已不可用';
|
|
$cancel = true;
|
|
} elseif (!in_array($kind,
|
|
['renewal_due', 'provision_succeeded'], true)) {
|
|
$error = '邮件通知类型无效';
|
|
$cancel = true;
|
|
} elseif (filter_var((string) $user->email, FILTER_VALIDATE_EMAIL) === false) {
|
|
$error = '用户邮箱无效';
|
|
} else {
|
|
$base = rtrim((string) Config::get('baseUrl', ''), '/');
|
|
$appName = trim((string) Config::get('appName', ''));
|
|
if ($kind === 'renewal_due') {
|
|
$ok = Mail::send((string) $user->email,
|
|
($appName !== '' ? $appName . ' - ' : '') . '实例续费账单已生成',
|
|
'cloud/invoice.tpl', [
|
|
'invoice_id' => (string) $invoice->id,
|
|
'instance_name' => (string) $instance->name,
|
|
'amount' => (string) $invoice->amount,
|
|
'due_at' => date(
|
|
'Y-m-d H:i:s',
|
|
(int) ($invoice->renews_expires_at
|
|
?? $invoice->due_at)
|
|
),
|
|
'payment_deadline_at' => date(
|
|
'Y-m-d H:i:s',
|
|
self::paymentDeadline($invoice)
|
|
),
|
|
'invoice_url' => $base . '/user/cloud/invoices/' . (int) $invoice->id,
|
|
], [], 'cloud_renewal_invoice');
|
|
} else {
|
|
$spec = json_decode((string) $instance->spec_json, true);
|
|
$spec = is_array($spec) && !array_is_list($spec) ? $spec : [];
|
|
try {
|
|
$cidr = CloudPublicNetworkSnapshot::fromArray(
|
|
$spec['public_network'] ?? null
|
|
)->address(4);
|
|
} catch (\InvalidArgumentException) {
|
|
$cidr = '';
|
|
}
|
|
$ip = explode('/', $cidr, 2)[0];
|
|
if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
|
|
$ip = '—';
|
|
}
|
|
$region = trim((string) ($spec['region'] ?? ''));
|
|
$osName = trim((string) ($spec['os_name']
|
|
?? $spec['template_id'] ?? ''));
|
|
$loginName = trim((string) ($spec['login_name'] ?? ''));
|
|
$ok = Mail::send((string) $user->email,
|
|
($appName !== '' ? $appName . ' - ' : '') . '实例开通成功',
|
|
'cloud/provision-success.tpl', [
|
|
'instance_name' => (string) $instance->name,
|
|
'instance_id' => (string) $instance->id,
|
|
'region' => $region !== '' ? $region : '—',
|
|
'public_ip' => $ip,
|
|
'os_name' => $osName !== '' ? $osName : '云镜像系统',
|
|
'login_name' => preg_match(
|
|
'/^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/D', $loginName
|
|
) === 1 ? $loginName : 'root',
|
|
'created_at' => date('Y-m-d H:i:s',
|
|
(int) $instance->created_at),
|
|
'expires_at' => $instance->expires_at === null
|
|
? '未设置' : date('Y-m-d H:i:s',
|
|
(int) $instance->expires_at),
|
|
'instance_url' => $base . '/user/cloud/instances/'
|
|
. (int) $instance->id,
|
|
], [], 'cloud_provision_success');
|
|
}
|
|
if (!$ok) {
|
|
$error = '邮件服务未接受消息';
|
|
}
|
|
}
|
|
if (!$ok && !$cancel) {
|
|
self::$observedErrors['notifications']['notification_failed'] = true;
|
|
}
|
|
self::finishMail((int) $message->id, $token, $ok, $error, $cancel);
|
|
$sent += $ok ? 1 : 0;
|
|
}
|
|
return $sent;
|
|
}
|
|
|
|
private static function claimMail(): ?array
|
|
{
|
|
return (new CloudMailOutbox())->getConnection()->transaction(function () {
|
|
$now = time();
|
|
// A crashed sender may already have handed the message to SMTP.
|
|
// Close that attempt as failed instead of risking a duplicate mail.
|
|
CloudMailOutbox::where('status', 'sending')
|
|
->where('lease_until', '<=', $now)->update([
|
|
'status' => 'failed',
|
|
'lease_token' => null,
|
|
'lease_until' => 0,
|
|
'available_at' => 0,
|
|
'last_error' => '发送进程中断,结果未知,未自动重试',
|
|
'updated_at' => $now,
|
|
]);
|
|
$message = CloudMailOutbox::where('status', 'pending')
|
|
->where('attempts', 0)->where('available_at', '<=', $now)
|
|
->orderBy('id')->lockForUpdate()->first();
|
|
if ($message === null) {
|
|
return null;
|
|
}
|
|
$token = bin2hex(random_bytes(16));
|
|
$message->status = 'sending';
|
|
$message->attempts = 1;
|
|
$message->lease_token = $token;
|
|
$message->lease_until = $now + 300;
|
|
$message->updated_at = $now;
|
|
$message->save();
|
|
return [$message, $token];
|
|
}, 3);
|
|
}
|
|
|
|
private static function finishMail(int $id, string $token, bool $ok, string $error,
|
|
bool $cancel = false): void
|
|
{
|
|
(new CloudMailOutbox())->getConnection()->transaction(function () use (
|
|
$id, $token, $ok, $error, $cancel
|
|
) {
|
|
$message = CloudMailOutbox::where('id', $id)->where('lease_token', $token)
|
|
->lockForUpdate()->first();
|
|
if ($message === null) {
|
|
return;
|
|
}
|
|
$now = time();
|
|
$message->lease_token = null;
|
|
$message->lease_until = 0;
|
|
$message->updated_at = $now;
|
|
if ($ok) {
|
|
$message->status = 'sent';
|
|
$message->sent_at = $now;
|
|
$message->last_error = '';
|
|
} elseif ($cancel) {
|
|
$message->status = 'cancelled';
|
|
$message->last_error = mb_substr($error, 0, 500);
|
|
} else {
|
|
$message->status = 'failed';
|
|
$message->available_at = 0;
|
|
$message->last_error = mb_substr($error, 0, 500);
|
|
}
|
|
$message->save();
|
|
}, 3);
|
|
}
|
|
|
|
/**
|
|
* Build the compact rows used by the paginated invoice list without
|
|
* loading the order, instance and job once for every invoice.
|
|
*
|
|
* @param iterable<CloudInvoice> $invoices
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
public static function listSummaries(iterable $invoices): array
|
|
{
|
|
$records = [];
|
|
$orderIds = [];
|
|
$linkedInstanceIds = [];
|
|
$renewalInstanceIds = [];
|
|
$operationalInvoiceIds = [];
|
|
$ownerIds = [];
|
|
foreach ($invoices as $invoice) {
|
|
if (!$invoice instanceof CloudInvoice) {
|
|
continue;
|
|
}
|
|
$records[] = $invoice;
|
|
$ownerIds[(int) $invoice->user_id] = (int) $invoice->user_id;
|
|
$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', 'ip_change', 'backup_addon'], true)
|
|
&& $invoice->instance_id !== null) {
|
|
$linkedInstanceIds[(int) $invoice->instance_id]
|
|
= (int) $invoice->instance_id;
|
|
if ($purpose === 'renewal') {
|
|
$renewalInstanceIds[(int) $invoice->instance_id]
|
|
= (int) $invoice->instance_id;
|
|
}
|
|
if (in_array($purpose, ['upgrade', 'ip_change'], true)) {
|
|
$operationalInvoiceIds[(int) $invoice->id]
|
|
= (int) $invoice->id;
|
|
}
|
|
}
|
|
}
|
|
if ($records === []) {
|
|
return [];
|
|
}
|
|
|
|
$orders = [];
|
|
if ($orderIds !== []) {
|
|
foreach (CloudOrder::whereIn('id', array_values($orderIds))
|
|
->whereIn('user_id', array_values($ownerIds))
|
|
->get(['id', 'user_id', 'status']) as $order) {
|
|
$orders[self::listKey((int) $order->user_id, (int) $order->id)] = $order;
|
|
}
|
|
}
|
|
$instances = [];
|
|
$existingInstanceIds = [];
|
|
if ($linkedInstanceIds !== []) {
|
|
foreach (CloudInstance::whereIn('id', array_values($linkedInstanceIds))
|
|
->get(['id', 'user_id', 'name', 'status', 'service_status'])
|
|
as $instance) {
|
|
$existingInstanceIds[(int) $instance->id] = true;
|
|
$instances[self::listKey((int) $instance->user_id, (int) $instance->id)]
|
|
= $instance;
|
|
}
|
|
}
|
|
$jobsByOrder = [];
|
|
$jobsByInvoice = [];
|
|
if ($orderIds !== [] || $operationalInvoiceIds !== []) {
|
|
foreach (CloudJob::whereIn('user_id', array_values($ownerIds))
|
|
->where(function ($query) use (
|
|
$orderIds,
|
|
$operationalInvoiceIds
|
|
): void {
|
|
if ($orderIds !== []) {
|
|
$query->whereIn('order_id', array_values($orderIds));
|
|
}
|
|
if ($operationalInvoiceIds !== []) {
|
|
$method = $orderIds === [] ? 'whereIn' : 'orWhereIn';
|
|
$query->{$method}(
|
|
'invoice_id',
|
|
array_values($operationalInvoiceIds)
|
|
);
|
|
}
|
|
})
|
|
->where(function ($query): void {
|
|
$query->whereNotNull('order_id')
|
|
->orWhereIn('kind', ['instance_upgrade', 'network_change']);
|
|
})
|
|
->orderBy('id')
|
|
->get(['id', 'order_id', 'invoice_id', 'user_id', 'instance_id', 'kind',
|
|
'phase', 'outcome', 'effect_resolution']) as $job) {
|
|
if ($job->order_id !== null) {
|
|
$jobsByOrder[self::listKey(
|
|
(int) $job->user_id, (int) $job->order_id
|
|
)] = $job;
|
|
}
|
|
if ($job->invoice_id !== null
|
|
&& in_array((string) $job->kind,
|
|
['instance_upgrade', 'network_change'], true)) {
|
|
$jobsByInvoice[self::listKey(
|
|
(int) $job->user_id, (int) $job->invoice_id
|
|
)] = $job;
|
|
}
|
|
}
|
|
}
|
|
$blockedUpgradeInstanceIds = [];
|
|
if ($renewalInstanceIds !== []) {
|
|
foreach (CloudJobService::blockingQueryForInstances(
|
|
array_values($renewalInstanceIds)
|
|
)->where('kind', 'instance_upgrade')->pluck('instance_id') as $instanceId) {
|
|
$blockedUpgradeInstanceIds[(int) $instanceId] = true;
|
|
}
|
|
}
|
|
|
|
$now = time();
|
|
$summaries = [];
|
|
foreach ($records as $invoice) {
|
|
$ownerId = (int) $invoice->user_id;
|
|
$purpose = (string) ($invoice->purpose ?: 'renewal');
|
|
$title = CloudBillingPresentationCatalog::knownPurposeLabel($purpose);
|
|
if ($title === '') {
|
|
$title = '账单';
|
|
}
|
|
$order = $purpose === 'provision' && $invoice->order_id !== null
|
|
? ($orders[self::listKey($ownerId, (int) $invoice->order_id)] ?? null)
|
|
: null;
|
|
$job = $order !== null
|
|
? ($jobsByOrder[self::listKey($ownerId, (int) $order->id)] ?? null)
|
|
: (in_array($purpose, ['upgrade', 'ip_change'], true)
|
|
? ($jobsByInvoice[self::listKey($ownerId, (int) $invoice->id)] ?? null)
|
|
: null);
|
|
$instance = in_array(
|
|
$purpose,
|
|
['renewal', 'upgrade', 'ip_change', 'backup_addon'],
|
|
true
|
|
)
|
|
&& $invoice->instance_id !== null
|
|
? ($instances[self::listKey($ownerId, (int) $invoice->instance_id)] ?? null)
|
|
: null;
|
|
$historicalInstanceId = in_array(
|
|
$purpose,
|
|
['renewal', 'upgrade', 'ip_change', 'backup_addon'],
|
|
true
|
|
) && $invoice->instance_id !== null
|
|
? (int) $invoice->instance_id : null;
|
|
$safeInstanceId = $instance?->id;
|
|
if ($safeInstanceId === null
|
|
&& $historicalInstanceId !== null
|
|
&& !isset($existingInstanceIds[$historicalInstanceId])) {
|
|
$safeInstanceId = $historicalInstanceId;
|
|
}
|
|
$publicState = self::publicState(
|
|
$invoice,
|
|
$purpose,
|
|
$order,
|
|
$instance,
|
|
$now,
|
|
$instance !== null
|
|
&& isset($blockedUpgradeInstanceIds[(int) $instance->id])
|
|
);
|
|
$jobStatus = self::taskStatus($job);
|
|
$summaries[] = [
|
|
'id' => (string) $invoice->id,
|
|
'title' => $title,
|
|
'type_label' => $title,
|
|
'purpose' => $purpose,
|
|
'amount' => (string) $invoice->amount,
|
|
'currency' => strtoupper((string) ($invoice->currency ?: 'USD')),
|
|
'status' => $publicState['status'],
|
|
'display_status' => $publicState['display_status'],
|
|
'available_action' => $publicState['available_action'],
|
|
'payable' => $publicState['payable'],
|
|
'renews_expires_at' => $invoice->renews_expires_at === null
|
|
? null : max(0, (int) $invoice->renews_expires_at),
|
|
'due_at' => max(0, (int) $invoice->due_at),
|
|
'payment_deadline_at' => $publicState['deadline'],
|
|
'created_at' => (int) $invoice->created_at,
|
|
'order_status' => $order?->status,
|
|
'fulfillment_status' => $jobStatus ?? $order?->status,
|
|
'task_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $jobStatus,
|
|
'instance_id' => $safeInstanceId === null
|
|
? null : (string) $safeInstanceId,
|
|
'instance_name' => $instance?->name,
|
|
];
|
|
}
|
|
return $summaries;
|
|
}
|
|
|
|
private static function listKey(int $userId, int $recordId): string
|
|
{
|
|
return $userId . ':' . $recordId;
|
|
}
|
|
|
|
/** Public jobs expose only active or a terminal receipt outcome. */
|
|
private static function taskStatus($job): ?string
|
|
{
|
|
if ($job === null) {
|
|
return null;
|
|
}
|
|
if ((string) $job->phase !== 'terminal') {
|
|
return 'active';
|
|
}
|
|
if ((string) ($job->kind ?? '') === 'create'
|
|
&& (string) $job->outcome === 'failed'
|
|
&& (string) ($job->effect_resolution ?? '') === 'applied'
|
|
&& (int) ($job->instance_id ?? 0) > 0) {
|
|
// Preserve the immutable failed task receipt while presenting the
|
|
// specialised exact-receipt create finalizer as fulfilled to
|
|
// invoices and notification consumers.
|
|
return 'succeeded';
|
|
}
|
|
$outcome = (string) $job->outcome;
|
|
if ((string) ($job->kind ?? '') === 'instance_upgrade'
|
|
&& $outcome === 'failed') {
|
|
return match ((string) ($job->effect_resolution ?? '')) {
|
|
'applied' => 'succeeded',
|
|
'unknown' => 'active',
|
|
default => 'failed',
|
|
};
|
|
}
|
|
if ((string) ($job->kind ?? '') === 'network_change'
|
|
&& $outcome === 'failed') {
|
|
return match ((string) ($job->effect_resolution ?? '')) {
|
|
'applied' => 'succeeded',
|
|
'unknown' => 'review',
|
|
default => 'failed',
|
|
};
|
|
}
|
|
return in_array($outcome, ['succeeded', 'failed'], true)
|
|
? $outcome : 'failed';
|
|
}
|
|
|
|
/** Derive the user-visible status shared by list, detail and polling. */
|
|
private static function publicStatus(CloudInvoice $invoice, string $purpose,
|
|
$instance, int $now): string
|
|
{
|
|
$status = (string) $invoice->status;
|
|
if ($purpose === 'renewal'
|
|
&& ($instance === null || (string) $instance->status === 'deleted')) {
|
|
if (in_array($status, ['open', 'overdue'], true)) {
|
|
return 'void';
|
|
}
|
|
} elseif ($status === 'open' && (int) $invoice->due_at <= $now) {
|
|
return 'overdue';
|
|
}
|
|
return $status;
|
|
}
|
|
|
|
/** Keep storage status stable while presenting the renewal grace phase. */
|
|
private static function displayStatus(string $purpose, string $status,
|
|
bool $payable, ?int $deadline, int $now): string
|
|
{
|
|
if ($purpose !== 'renewal' || $status !== 'overdue') {
|
|
return $status;
|
|
}
|
|
if ($payable) {
|
|
return 'renewal_grace';
|
|
}
|
|
return $deadline !== null && $deadline <= $now
|
|
? 'expired' : $status;
|
|
}
|
|
|
|
/**
|
|
* Derive the public invoice state once for both full detail responses and
|
|
* lightweight polling responses. The callers deliberately load different
|
|
* columns, but payment eligibility must never drift between them.
|
|
*
|
|
* @return array{status: string, display_status: string, deadline: ?int,
|
|
* payable: bool, available_action: ?string}
|
|
*/
|
|
private static function publicState(CloudInvoice $invoice, string $purpose,
|
|
$order, $instance, int $now, ?bool $upgradeBlocked = null): array
|
|
{
|
|
$status = self::publicStatus($invoice, $purpose, $instance, $now);
|
|
|
|
$deadline = self::paymentDeadline($invoice);
|
|
if ($purpose === 'provision') {
|
|
$payable = in_array($status, ['open', 'overdue'], true)
|
|
&& $order !== null
|
|
&& (string) $order->status === 'awaiting_payment'
|
|
&& $deadline > $now;
|
|
} elseif ($purpose === 'renewal') {
|
|
$upgradeBlocked ??= $instance !== null
|
|
&& CloudJobService::blockingQueryForInstance(
|
|
(int) $instance->id
|
|
)->where('kind', 'instance_upgrade')->exists();
|
|
$payable = in_array($status, ['open', 'overdue'], true)
|
|
&& $instance !== null
|
|
&& !self::instanceDeleting($instance)
|
|
&& !$upgradeBlocked
|
|
&& $deadline > $now;
|
|
} else {
|
|
// Upgrade and operational invoices are settled atomically when
|
|
// their task is created. They are audit records, not payable bills.
|
|
$payable = false;
|
|
}
|
|
|
|
return [
|
|
'status' => $status,
|
|
'display_status' => self::displayStatus(
|
|
$purpose,
|
|
$status,
|
|
$payable,
|
|
$deadline,
|
|
$now
|
|
),
|
|
'deadline' => $deadline,
|
|
'payable' => $payable,
|
|
'available_action' => $payable ? 'pay' : null,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Return only the mutable fields needed while a browser waits for an
|
|
* invoice payment or a provisioning job. This deliberately avoids plan
|
|
* snapshots, payment-method discovery and the other detail-only work in
|
|
* display().
|
|
*/
|
|
public static function status(CloudInvoice $invoice): array
|
|
{
|
|
$now = time();
|
|
$purpose = (string) ($invoice->purpose ?: 'renewal');
|
|
$order = null;
|
|
$instance = null;
|
|
$job = null;
|
|
|
|
if ($purpose === 'provision' && $invoice->order_id !== null) {
|
|
$order = CloudOrder::where('id', $invoice->order_id)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'user_id', 'status', 'instance_id']);
|
|
if ($order !== null) {
|
|
$job = CloudJob::where('order_id', $order->id)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'order_id', 'user_id', 'instance_id',
|
|
'kind', 'phase',
|
|
'outcome', 'attempts', 'updated_at', 'error_code',
|
|
'result_json', 'effect_resolution']);
|
|
}
|
|
} elseif (in_array($purpose,
|
|
['renewal', 'upgrade', 'ip_change', 'backup_addon'], true)
|
|
&& $invoice->instance_id !== null) {
|
|
$instance = CloudInstance::where('id', $invoice->instance_id)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'user_id', 'status', 'service_status']);
|
|
if ($purpose === 'upgrade') {
|
|
$job = CloudJob::where('invoice_id', $invoice->id)
|
|
->where('user_id', $invoice->user_id)
|
|
->where('kind', 'instance_upgrade')
|
|
->first(['id', 'invoice_id', 'user_id', 'instance_id',
|
|
'kind', 'phase', 'outcome', 'attempts', 'updated_at',
|
|
'error_code', 'result_json', 'effect_resolution']);
|
|
} elseif ($purpose === 'ip_change') {
|
|
$job = CloudJob::where('invoice_id', $invoice->id)
|
|
->where('user_id', $invoice->user_id)
|
|
->where('kind', 'network_change')
|
|
->orderByDesc('id')
|
|
->first(['id', 'invoice_id', 'user_id', 'instance_id',
|
|
'kind', 'phase', 'outcome', 'attempts', 'updated_at',
|
|
'error_code', 'result_json', 'effect_resolution']);
|
|
}
|
|
}
|
|
|
|
$publicState = self::publicState($invoice, $purpose, $order, $instance, $now);
|
|
$status = $publicState['status'];
|
|
$displayStatus = $publicState['display_status'];
|
|
$deadline = $publicState['deadline'];
|
|
$payable = $publicState['payable'];
|
|
|
|
$decodedJobResult = $job === null || $job->result_json === null
|
|
? null : json_decode((string) $job->result_json, true);
|
|
$jobStatus = self::taskStatus($job);
|
|
$safeJobResult = is_array($decodedJobResult)
|
|
? CloudOperationErrorCatalog::result($decodedJobResult, false,
|
|
(string) ($job?->kind ?? 'create'),
|
|
(string) ($jobStatus ?? $order?->status),
|
|
true) : null;
|
|
$jobPhase = CloudOperationErrorCatalog::userPhase(
|
|
$safeJobResult['phase'] ?? null,
|
|
(string) ($jobStatus ?? $order?->status),
|
|
(string) ($job?->kind ?? 'create')
|
|
);
|
|
$linkedInstanceId = $purpose === 'provision'
|
|
? ($order?->instance_id ?? $invoice->instance_id)
|
|
: $invoice->instance_id;
|
|
$linkedInstance = in_array(
|
|
$purpose,
|
|
['renewal', 'upgrade', 'ip_change', 'backup_addon'],
|
|
true
|
|
) ? $instance
|
|
: ($linkedInstanceId === null ? null
|
|
: CloudInstance::where('id', $linkedInstanceId)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'user_id']));
|
|
$linkedInstanceExists = $linkedInstanceId !== null
|
|
&& CloudInstance::where('id', $linkedInstanceId)->exists();
|
|
$instanceId = $linkedInstance?->id;
|
|
if ($instanceId === null
|
|
&& in_array($purpose,
|
|
['renewal', 'upgrade', 'ip_change', 'backup_addon'], true)
|
|
&& !$linkedInstanceExists) {
|
|
$instanceId = $linkedInstanceId;
|
|
}
|
|
$fulfillmentStatus = $jobStatus ?? $order?->status;
|
|
$jobError = $job === null ? null : CloudOperationErrorCatalog::userMessage(
|
|
(string) ($job->kind ?? 'create'), (string) $jobStatus,
|
|
$job->error_code, true
|
|
);
|
|
|
|
return [
|
|
'id' => (string) $invoice->id,
|
|
'purpose' => $purpose,
|
|
'status' => $status,
|
|
'display_status' => $displayStatus,
|
|
'available_action' => $publicState['available_action'],
|
|
'payable' => $payable,
|
|
'paid_at' => $invoice->paid_at === null ? null : (int) $invoice->paid_at,
|
|
'paid_via' => $invoice->paid_via,
|
|
'payment_deadline_at' => $deadline,
|
|
'deletion_at' => $purpose === 'renewal' ? $deadline : null,
|
|
'instance_id' => $instanceId === null ? null : (string) $instanceId,
|
|
'order_status' => $order?->status,
|
|
'fulfillment_status' => $fulfillmentStatus,
|
|
'task_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $jobStatus,
|
|
'job_completed' => $job === null ? null
|
|
: $jobStatus !== 'active',
|
|
'job_attempts' => $job === null ? 0 : max(0, (int) $job->attempts),
|
|
'job_updated_at' => $job === null ? null : max(0, (int) $job->updated_at),
|
|
'phase' => $jobPhase,
|
|
'error' => $jobError,
|
|
'fulfillment' => $purpose === 'provision' ? [
|
|
'order_id' => $order === null ? null : (string) $order->id,
|
|
'order_status' => $order?->status,
|
|
'task_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $jobStatus,
|
|
'completed' => $job === null ? null
|
|
: $jobStatus !== 'active',
|
|
'attempts' => $job === null ? 0 : max(0, (int) $job->attempts),
|
|
'updated_at' => $job === null ? null : max(0, (int) $job->updated_at),
|
|
'instance_id' => $instanceId === null ? null : (string) $instanceId,
|
|
'phase' => $jobPhase,
|
|
'error' => $jobError,
|
|
] : null,
|
|
];
|
|
}
|
|
|
|
public static function display(CloudInvoice $invoice): array
|
|
{
|
|
$now = time();
|
|
$purpose = (string) ($invoice->purpose ?: 'renewal');
|
|
$title = CloudBillingPresentationCatalog::knownPurposeLabel($purpose);
|
|
if ($title === '') {
|
|
$title = '账单';
|
|
}
|
|
$order = $purpose !== 'provision' || $invoice->order_id === null
|
|
? null : CloudOrder::where('id', $invoice->order_id)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'user_id', 'instance_id', 'status', 'spec_json']);
|
|
$linkedInstanceId = $purpose === 'provision'
|
|
? ($order?->instance_id ?? $invoice->instance_id)
|
|
: $invoice->instance_id;
|
|
$instance = $linkedInstanceId === null
|
|
? null : CloudInstance::where('id', $linkedInstanceId)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'user_id', 'name', 'status', 'service_status',
|
|
'spec_json']);
|
|
$linkedInstanceExists = $linkedInstanceId !== null
|
|
&& CloudInstance::where('id', $linkedInstanceId)->exists();
|
|
$safeLinkedInstanceId = $instance?->id;
|
|
if ($safeLinkedInstanceId === null
|
|
&& in_array($purpose,
|
|
['renewal', 'upgrade', 'ip_change', 'backup_addon'], true)
|
|
&& !$linkedInstanceExists) {
|
|
$safeLinkedInstanceId = $linkedInstanceId;
|
|
}
|
|
$job = $order === null ? null
|
|
: CloudJob::where('order_id', $order->id)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'order_id', 'user_id', 'instance_id', 'kind',
|
|
'phase', 'outcome', 'attempts', 'updated_at',
|
|
'error_code', 'effect_resolution']);
|
|
if ($purpose === 'upgrade') {
|
|
$job = CloudJob::where('invoice_id', $invoice->id)
|
|
->where('user_id', $invoice->user_id)
|
|
->where('kind', 'instance_upgrade')
|
|
->first(['id', 'invoice_id', 'user_id', 'instance_id', 'kind',
|
|
'phase', 'outcome', 'attempts', 'updated_at',
|
|
'error_code', 'effect_resolution', 'sealed_payload']);
|
|
} elseif ($purpose === 'ip_change') {
|
|
$job = CloudJob::where('invoice_id', $invoice->id)
|
|
->where('user_id', $invoice->user_id)
|
|
->where('kind', 'network_change')
|
|
->orderByDesc('id')
|
|
->first(['id', 'invoice_id', 'user_id', 'instance_id', 'kind',
|
|
'phase', 'outcome', 'attempts', 'updated_at',
|
|
'error_code', 'effect_resolution']);
|
|
}
|
|
// Successful workers persist both links. Keep the invoice-side link
|
|
// as a defensive fallback if transaction recovery repaired one side
|
|
// so the unified bill can still open the created instance.
|
|
$provisionInstanceId = $instance?->id;
|
|
$decodedOrderSpec = $order === null
|
|
? null : json_decode((string) $order->spec_json, true);
|
|
$decodedInstanceSpec = $instance === null
|
|
? null : json_decode((string) $instance->spec_json, true);
|
|
$orderSpec = is_array($decodedOrderSpec) ? $decodedOrderSpec : [];
|
|
$instanceSpec = is_array($decodedInstanceSpec) ? $decodedInstanceSpec : [];
|
|
$spec = $orderSpec !== [] ? $orderSpec : $instanceSpec;
|
|
$planName = trim((string) ($orderSpec['plan_name']
|
|
?? $instanceSpec['plan_name'] ?? ''));
|
|
if ($purpose === 'upgrade') {
|
|
$target = CloudPlanUpgradeService::invoiceTargetSnapshot(
|
|
$invoice,
|
|
$job
|
|
);
|
|
$spec = $target === null ? [] : (array) $target['resources'];
|
|
$planName = $target === null
|
|
? ($invoice->plan_id === null
|
|
? '升级目标套餐' : '套餐 #' . (int) $invoice->plan_id)
|
|
: trim((string) $target['plan_name']);
|
|
}
|
|
$cpuCores = (int) ($spec['cpu_cores'] ?? $spec['vcpu'] ?? 0);
|
|
$memoryMiB = (int) ($spec['memory_mib'] ?? 0);
|
|
$diskGiB = (int) ($spec['disk_gib'] ?? 0);
|
|
$bandwidthMbps = (int) ($spec['bandwidth_mbps'] ?? 0);
|
|
$cpuCores = $cpuCores > 0 ? $cpuCores : null;
|
|
$memoryMiB = $memoryMiB > 0 ? $memoryMiB : null;
|
|
$diskGiB = $diskGiB > 0 ? $diskGiB : null;
|
|
$bandwidthMbps = $bandwidthMbps > 0 ? $bandwidthMbps : null;
|
|
$publicState = self::publicState($invoice, $purpose, $order, $instance, $now);
|
|
$status = $publicState['status'];
|
|
$displayStatus = $publicState['display_status'];
|
|
$deadline = $publicState['deadline'];
|
|
$payable = $publicState['payable'];
|
|
$jobStatus = self::taskStatus($job);
|
|
$jobError = $job === null ? null : CloudOperationErrorCatalog::userMessage(
|
|
(string) ($job->kind ?? 'create'), (string) $jobStatus,
|
|
$job->error_code, true
|
|
);
|
|
$items = CloudInvoiceItem::where('invoice_id', (int) $invoice->id)
|
|
->orderBy('id')->get([
|
|
'id', 'code', 'label', 'amount', 'currency',
|
|
])->map(static fn (CloudInvoiceItem $item): array => [
|
|
'id' => (string) $item->id,
|
|
'code' => (string) $item->code,
|
|
'label' => (string) $item->label,
|
|
'amount' => (string) $item->amount,
|
|
'currency' => (string) $item->currency,
|
|
])->all();
|
|
$renewalResult = self::renewalResult($invoice, $purpose);
|
|
return [
|
|
'id' => (string) $invoice->id,
|
|
'title' => $title,
|
|
'type_label' => $title,
|
|
'purpose' => $purpose,
|
|
'instance_id' => $safeLinkedInstanceId === null
|
|
? null : (string) $safeLinkedInstanceId,
|
|
'instance_name' => $purpose === 'provision'
|
|
? (string) ($spec['name'] ?? '待开通实例')
|
|
: ($instance?->name ?? '已删除实例'),
|
|
'requested_name' => $purpose === 'provision'
|
|
? (string) ($spec['name'] ?? '') : null,
|
|
'plan_name' => $planName,
|
|
'cpu_cores' => $cpuCores,
|
|
'memory_mib' => $memoryMiB,
|
|
'disk_gib' => $diskGiB,
|
|
'bandwidth_mbps' => $bandwidthMbps,
|
|
'specification' => [
|
|
'cpu_cores' => $cpuCores,
|
|
'memory_mib' => $memoryMiB,
|
|
'disk_gib' => $diskGiB,
|
|
'bandwidth_mbps' => $bandwidthMbps,
|
|
],
|
|
'order_id' => $order === null ? null : (string) $order->id,
|
|
'order_status' => $order?->status,
|
|
'fulfillment_status' => $jobStatus ?? $order?->status,
|
|
'task_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $jobStatus,
|
|
'job_completed' => $job === null ? null
|
|
: $jobStatus !== 'active',
|
|
'job_attempts' => $job === null ? 0 : max(0, (int) $job->attempts),
|
|
'job_updated_at' => $job === null ? null : max(0, (int) $job->updated_at),
|
|
'error' => $jobError,
|
|
'fulfillment' => $purpose === 'provision' ? [
|
|
'order_id' => $order === null ? null : (string) $order->id,
|
|
'order_status' => $order?->status,
|
|
'task_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $jobStatus,
|
|
'completed' => $job === null ? null
|
|
: (string) $job->phase === 'terminal',
|
|
'attempts' => $job === null ? 0 : max(0, (int) $job->attempts),
|
|
'updated_at' => $job === null ? null : max(0, (int) $job->updated_at),
|
|
'instance_id' => $provisionInstanceId === null
|
|
? null : (string) $provisionInstanceId,
|
|
'error' => $jobError,
|
|
] : null,
|
|
'amount' => (string) $invoice->amount,
|
|
'currency' => strtoupper((string) ($invoice->currency ?: 'USD')),
|
|
'items' => $items,
|
|
'renewal_result' => $renewalResult,
|
|
'validity_days' => (int) $invoice->validity_days,
|
|
'service_days' => (int) $invoice->validity_days,
|
|
'traffic_quota_bytes' => (int) $invoice->traffic_quota_bytes,
|
|
'status' => $status,
|
|
'display_status' => $displayStatus,
|
|
'available_action' => $publicState['available_action'],
|
|
'due_at' => (int) $invoice->due_at,
|
|
'renews_expires_at' => $invoice->renews_expires_at === null
|
|
? null : (int) $invoice->renews_expires_at,
|
|
'payment_deadline_at' => $deadline,
|
|
'deletion_at' => $purpose === 'renewal' ? $deadline : null,
|
|
'payable' => $payable,
|
|
'paid_at' => $invoice->paid_at === null ? null : (int) $invoice->paid_at,
|
|
'paid_via' => $invoice->paid_via,
|
|
'created_at' => (int) $invoice->created_at,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Return only the immutable rows created by this paid renewal. Never use
|
|
* the instance's current expiry: later renewals may already have moved it.
|
|
*/
|
|
private static function renewalResult(
|
|
CloudInvoice $invoice,
|
|
string $purpose
|
|
): ?array {
|
|
if ($purpose !== 'renewal'
|
|
|| (string) $invoice->status !== 'paid'
|
|
|| $invoice->renewal_id === null
|
|
|| $invoice->instance_id === null) {
|
|
return null;
|
|
}
|
|
$renewal = CloudRenewal::where('id', (int) $invoice->renewal_id)
|
|
->where('user_id', (int) $invoice->user_id)
|
|
->where('instance_id', (int) $invoice->instance_id)
|
|
->first([
|
|
'id', 'instance_id', 'user_id', 'period_id',
|
|
'validity_days', 'previous_expires_at', 'new_expires_at',
|
|
]);
|
|
if ($renewal === null) {
|
|
return null;
|
|
}
|
|
$period = $renewal->period_id === null ? null
|
|
: CloudServicePeriod::where('id', (int) $renewal->period_id)
|
|
->where('renewal_id', (int) $renewal->id)
|
|
->where('user_id', (int) $invoice->user_id)
|
|
->where('instance_id', (int) $invoice->instance_id)
|
|
->first(['id', 'starts_at', 'ends_at']);
|
|
return [
|
|
'previous_expires_at' => max(
|
|
0,
|
|
(int) $renewal->previous_expires_at
|
|
),
|
|
'new_expires_at' => max(0, (int) $renewal->new_expires_at),
|
|
'period_starts_at' => $period === null
|
|
? null : max(0, (int) $period->starts_at),
|
|
'period_ends_at' => $period === null
|
|
? null : max(0, (int) $period->ends_at),
|
|
'validity_days' => max(0, (int) $renewal->validity_days),
|
|
];
|
|
}
|
|
|
|
public static function payBalance(CloudInvoice $invoice, array $actor, string $idempotency): CloudInvoice
|
|
{
|
|
return self::payBalanceResult($invoice, $actor, $idempotency)['invoice'];
|
|
}
|
|
|
|
/**
|
|
* Return the durable provisioning task separately from synchronous
|
|
* renewal settlement so the HTTP layer can emit the exact 202 contract.
|
|
*
|
|
* @return array{invoice: CloudInvoice, job: ?CloudJob}
|
|
*/
|
|
public static function payBalanceResult(CloudInvoice $invoice,
|
|
array $actor, string $idempotency): array
|
|
{
|
|
if ((int) $invoice->user_id !== (int) $actor['user_id']) {
|
|
throw new CloudError('只能支付自己的账单', 403);
|
|
}
|
|
$result = self::settle($invoice, $actor, $idempotency, 'balance', '');
|
|
if ($result['outcome'] === 'stale') {
|
|
throw new CloudError('账单已失效,请刷新账单列表', 409);
|
|
}
|
|
$paid = $result['invoice'];
|
|
$job = null;
|
|
if ((string) ($paid->purpose ?: 'renewal') === 'provision') {
|
|
$job = CloudJob::where('order_id', (int) $paid->order_id)
|
|
->where('user_id', (int) $paid->user_id)
|
|
->whereNull('parent_job_id')->first();
|
|
if ($job === null) {
|
|
throw new \RuntimeException('已支付开通账单缺少持久任务');
|
|
}
|
|
}
|
|
return ['invoice' => $paid, 'job' => $job];
|
|
}
|
|
|
|
/**
|
|
* Settle an invoice after a provider callback has already credited the
|
|
* exact payment to the wallet in the same outer database transaction.
|
|
* Expected business conflicts keep that money in the wallet.
|
|
*/
|
|
public static function settleCreditedPayment(CloudInvoicePayment $payment): string
|
|
{
|
|
$invoice = CloudInvoice::where('id', $payment->invoice_id)->first();
|
|
$amountMatches = false;
|
|
if ($invoice !== null) {
|
|
try {
|
|
$amountMatches = CloudMoney::cents((string) $payment->amount)
|
|
=== CloudMoney::cents((string) $invoice->amount);
|
|
} catch (\Throwable $error) {
|
|
$amountMatches = false;
|
|
}
|
|
}
|
|
if ($invoice === null || (int) $invoice->user_id !== (int) $payment->user_id
|
|
|| !$amountMatches) {
|
|
$payment->status = 'credited_balance';
|
|
$payment->updated_at = time();
|
|
$payment->save();
|
|
return 'credited_balance';
|
|
}
|
|
$actor = ['user_id' => (int) $payment->user_id, 'is_admin' => false,
|
|
'is_super_admin' => false, 'can_manage' => false, 'session_id' => ''];
|
|
try {
|
|
$result = self::settle($invoice, $actor,
|
|
'invoice-payment-' . (int) $payment->id,
|
|
(string) $payment->provider, (string) $payment->provider_order_no);
|
|
$payment->status = $result['outcome'] === 'paid' ? 'paid_invoice' : 'credited_balance';
|
|
} catch (CloudError $error) {
|
|
$payment->status = 'credited_balance';
|
|
}
|
|
$payment->updated_at = time();
|
|
$payment->save();
|
|
return (string) $payment->status;
|
|
}
|
|
|
|
private static function settle(CloudInvoice $source, array $actor, string $idempotency,
|
|
string $paidVia, string $reference): array
|
|
{
|
|
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
|
|
throw new CloudError('支付请求标识无效');
|
|
}
|
|
return (new User())->getConnection()->transaction(function () use (
|
|
$source, $actor, $idempotency, $paidVia, $reference
|
|
) {
|
|
$user = User::where('id', (int) $actor['user_id'])->lockForUpdate()->first();
|
|
if ($user === null || (int) $user->enable !== 1) {
|
|
throw new CloudError('账户不存在或不可用', 403);
|
|
}
|
|
$sourcePurpose = (string) ($source->purpose ?: 'renewal');
|
|
if (!in_array($sourcePurpose, ['provision', 'renewal'], true)) {
|
|
throw new CloudError('该账单不支持再次支付', 409);
|
|
}
|
|
$instance = null;
|
|
if ($sourcePurpose !== 'provision') {
|
|
// Keep the established lifecycle lock order for renewals:
|
|
// user -> instance -> invoice.
|
|
$instance = CloudInstance::where('id', (int) $source->instance_id)
|
|
->lockForUpdate()->first();
|
|
}
|
|
$invoice = CloudInvoice::where('id', $source->id)->lockForUpdate()->first();
|
|
if ($invoice === null || (int) $invoice->user_id !== (int) $user->id) {
|
|
throw new CloudError('账单不存在', 404);
|
|
}
|
|
$purpose = (string) ($invoice->purpose ?: 'renewal');
|
|
if ($purpose !== $sourcePurpose) {
|
|
throw new CloudError('账单类型已变更,请刷新后重试', 409);
|
|
}
|
|
if (!in_array($purpose, ['provision', 'renewal'], true)) {
|
|
throw new CloudError('该账单不支持再次支付', 409);
|
|
}
|
|
if ((string) $invoice->status === 'paid') {
|
|
return ['outcome' => 'already_paid', 'invoice' => $invoice];
|
|
}
|
|
if ($purpose === 'provision') {
|
|
$order = CloudOrder::where('id', $invoice->order_id)
|
|
->where('user_id', $user->id)->lockForUpdate()->first();
|
|
if ($order === null
|
|
|| in_array((string) $invoice->status, ['expired', 'void'], true)
|
|
|| self::paymentDeadlinePassed($invoice)
|
|
|| (string) $order->status !== 'awaiting_payment') {
|
|
if ($order !== null && (string) $order->status === 'awaiting_payment') {
|
|
CloudOrderService::releaseStock($order);
|
|
$order->status = 'expired';
|
|
$order->sealed_payload = null;
|
|
$order->updated_at = time();
|
|
$order->save();
|
|
}
|
|
if (in_array((string) $invoice->status, ['open', 'overdue'], true)) {
|
|
$invoice->status = 'expired';
|
|
$invoice->updated_at = time();
|
|
$invoice->save();
|
|
}
|
|
return ['outcome' => 'stale', 'invoice' => $invoice];
|
|
}
|
|
if ((int) $order->plan_id !== (int) $invoice->plan_id
|
|
|| (int) $order->offer_id !== (int) $invoice->offer_id
|
|
|| strtoupper((string) $order->currency) !== 'USD'
|
|
|| strtoupper((string) $invoice->currency) !== 'USD'
|
|
|| CloudMoney::cents((string) $order->amount)
|
|
!== CloudMoney::cents((string) $invoice->amount)) {
|
|
CloudOrderService::releaseStock($order);
|
|
$order->status = 'expired';
|
|
$order->sealed_payload = null;
|
|
$order->updated_at = time();
|
|
$order->save();
|
|
$invoice->status = 'void';
|
|
$invoice->updated_at = time();
|
|
$invoice->save();
|
|
return ['outcome' => 'stale', 'invoice' => $invoice];
|
|
}
|
|
$price = CloudMoney::cents((string) $invoice->amount);
|
|
$balance = CloudMoney::cents((string) $user->money);
|
|
if ($balance < $price) {
|
|
throw new CloudError('账户余额不足', 409);
|
|
}
|
|
CloudOrderService::queuePaidProvision($invoice, $order);
|
|
$user->money = CloudMoney::decimal($balance - $price);
|
|
$user->save();
|
|
$invoice->status = 'paid';
|
|
$invoice->paid_via = mb_substr($paidVia, 0, 32);
|
|
$invoice->payment_reference = $reference === ''
|
|
? null : mb_substr($reference, 0, 80);
|
|
$invoice->paid_at = time();
|
|
$invoice->updated_at = time();
|
|
$invoice->save();
|
|
return ['outcome' => 'paid', 'invoice' => $invoice,
|
|
'order' => $order->fresh() ?? $order];
|
|
}
|
|
|
|
if ($instance !== null
|
|
&& CloudJobService::blockingQueryForInstance((int) $instance->id)
|
|
->where('kind', 'instance_upgrade')->exists()) {
|
|
throw new CloudError('实例正在升级或等待核对,续费账单暂不可支付', 409);
|
|
}
|
|
if (($instance !== null && self::instanceDeleting($instance))
|
|
|| in_array((string) $invoice->status, ['expired'], true)
|
|
|| (in_array((string) $invoice->status, ['open', 'overdue'], true)
|
|
&& self::paymentDeadlinePassed($invoice))) {
|
|
if (in_array((string) $invoice->status, ['open', 'overdue'], true)) {
|
|
$invoice->status = 'expired';
|
|
$invoice->updated_at = time();
|
|
$invoice->save();
|
|
}
|
|
return ['outcome' => 'stale', 'invoice' => $invoice];
|
|
}
|
|
if ($instance === null || (string) $instance->status === 'deleted'
|
|
|| !in_array((string) $invoice->status, ['open', 'overdue'], true)
|
|
|| (int) $instance->user_id !== (int) $user->id
|
|
|| $instance->expires_at === null
|
|
|| (int) $instance->expires_at !== (int) $invoice->renews_expires_at
|
|
|| !self::renewalInvoiceMatches($instance, $invoice)
|
|
|| (int) $instance->renewal_days !== (int) $invoice->validity_days
|
|
|| (int) $instance->renewal_traffic_bytes !== (int) $invoice->traffic_quota_bytes) {
|
|
$invoice->status = 'void';
|
|
$invoice->updated_at = time();
|
|
$invoice->save();
|
|
return ['outcome' => 'stale', 'invoice' => $invoice];
|
|
}
|
|
|
|
// Scope the renewal key to this bill. A client key reused in a
|
|
// later billing period must never resolve to an older renewal.
|
|
$renewal = CloudRenewalService::renew($instance, [
|
|
'idempotency_key' => 'invoice-' . (int) $invoice->id . '-'
|
|
. hash('sha256', $idempotency),
|
|
], $actor);
|
|
$invoice->status = 'paid';
|
|
$invoice->renewal_id = $renewal->id;
|
|
$invoice->paid_via = mb_substr($paidVia, 0, 32);
|
|
$invoice->payment_reference = $reference === '' ? null : mb_substr($reference, 0, 80);
|
|
$invoice->paid_at = time();
|
|
$invoice->updated_at = time();
|
|
$invoice->save();
|
|
return ['outcome' => 'paid', 'invoice' => $invoice, 'renewal' => $renewal];
|
|
}, 3);
|
|
}
|
|
|
|
private static function invoiceNumber(): string
|
|
{
|
|
return 'VC' . gmdate('YmdHis') . strtoupper(bin2hex(random_bytes(8)));
|
|
}
|
|
}
|