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.
966 lines
45 KiB
PHP
966 lines
45 KiB
PHP
<?php
|
|
namespace App\Services\Cloud;
|
|
|
|
use App\Models\CloudInstance;
|
|
use App\Models\CloudInvoice;
|
|
use App\Models\CloudInvoicePayment;
|
|
use App\Models\CloudMailOutbox;
|
|
use App\Models\CloudOffer;
|
|
use App\Models\CloudOrder;
|
|
use App\Models\CloudRenewal;
|
|
use App\Models\CloudJob;
|
|
use App\Models\Shop;
|
|
use App\Models\User;
|
|
use App\Services\Config;
|
|
use App\Services\Mail;
|
|
|
|
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
|
|
{
|
|
if ((string) $invoice->purpose === 'provision') {
|
|
return (int) $invoice->due_at;
|
|
}
|
|
return max((int) $invoice->due_at, (int) $invoice->created_at)
|
|
+ self::PAYMENT_GRACE_SECONDS;
|
|
}
|
|
|
|
public static function paymentDeadlinePassed(CloudInvoice $invoice, ?int $now = null): bool
|
|
{
|
|
return self::paymentDeadline($invoice) <= ($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_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->payload_cipher)
|
|
|| trim((string) $order->payload_cipher) === '') {
|
|
throw new CloudError('开通订单状态无效', 409);
|
|
}
|
|
$invoice = new CloudInvoice();
|
|
$invoice->invoice_no = self::invoiceNumber();
|
|
$invoice->purpose = 'provision';
|
|
$invoice->instance_id = null;
|
|
$invoice->order_id = $order->id;
|
|
$invoice->user_id = $order->user_id;
|
|
$invoice->plan_id = $order->plan_id;
|
|
$invoice->offer_id = $order->offer_id;
|
|
$invoice->renewal_id = null;
|
|
$invoice->renews_expires_at = null;
|
|
$invoice->due_at = $now + CloudOrderService::PAYMENT_WINDOW_SECONDS;
|
|
$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();
|
|
return $invoice;
|
|
}
|
|
|
|
/** Expire abandoned initial bills and return their finite stock safely. */
|
|
public static function expireProvision(int $limit = 200): int
|
|
{
|
|
$now = time();
|
|
$ids = CloudInvoice::where('purpose', 'provision')
|
|
->whereIn('status', ['open', 'overdue'])
|
|
->where('due_at', '<=', $now)->orderBy('id')
|
|
->limit(max(1, min(1000, $limit)))->pluck('id')->all();
|
|
$expired = 0;
|
|
foreach ($ids as $id) {
|
|
$expired += (new User())->getConnection()->transaction(function () use ($id, $now) {
|
|
$ownerId = CloudInvoice::where('id', $id)->value('user_id');
|
|
if ($ownerId === null) {
|
|
return 0;
|
|
}
|
|
// Match payment settlement's user -> invoice -> order -> plan
|
|
// lock order so expiry and a callback cannot both win.
|
|
User::where('id', (int) $ownerId)->lockForUpdate()->first();
|
|
$invoice = CloudInvoice::where('id', $id)->lockForUpdate()->first();
|
|
if ($invoice === null || (string) $invoice->purpose !== 'provision'
|
|
|| !in_array((string) $invoice->status, ['open', 'overdue'], true)
|
|
|| (int) $invoice->due_at > $now) {
|
|
return 0;
|
|
}
|
|
$order = CloudOrder::where('id', $invoice->order_id)
|
|
->lockForUpdate()->first();
|
|
if ($order !== null && (string) $order->status === 'awaiting_payment') {
|
|
CloudOrderService::releaseStock($order);
|
|
$order->status = 'expired';
|
|
$order->payload_cipher = null;
|
|
$order->updated_at = $now;
|
|
$order->save();
|
|
}
|
|
$invoice->status = 'expired';
|
|
$invoice->updated_at = $now;
|
|
$invoice->save();
|
|
return 1;
|
|
}, 3);
|
|
}
|
|
return $expired;
|
|
}
|
|
|
|
public static function issueDue(int $limit = 200): int
|
|
{
|
|
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_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;
|
|
}
|
|
$expiry = (int) $instance->expires_at;
|
|
if (CloudInvoice::where('instance_id', $instance->id)
|
|
->where('renews_expires_at', $expiry)
|
|
->where('status', '<>', 'void')->exists()) {
|
|
return false;
|
|
}
|
|
$amount = CloudMoney::decimal(CloudMoney::cents((string) $instance->renewal_price));
|
|
$invoice = new CloudInvoice();
|
|
$invoice->invoice_no = self::invoiceNumber();
|
|
$invoice->purpose = 'renewal';
|
|
$invoice->instance_id = $instance->id;
|
|
$invoice->order_id = null;
|
|
$invoice->user_id = $instance->user_id;
|
|
$invoice->plan_id = $instance->plan_id;
|
|
$invoice->renewal_id = null;
|
|
$invoice->renews_expires_at = $expiry;
|
|
$invoice->due_at = $expiry;
|
|
$invoice->amount = $amount;
|
|
$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::enqueueMail($invoice, 'renewal_due', $now);
|
|
return true;
|
|
}, 3);
|
|
}
|
|
|
|
/** 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'
|
|
|| $job === null || (string) $job->status !== '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->due_at),
|
|
'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 : [];
|
|
$cidr = is_string($spec['public_ip_cidr'] ?? null)
|
|
? trim($spec['public_ip_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();
|
|
$message = CloudMailOutbox::where(function ($query) use ($now) {
|
|
$query->where('status', 'pending')
|
|
->orWhere(function ($leased) use ($now) {
|
|
$leased->where('status', 'sending')->where('lease_until', '<=', $now);
|
|
});
|
|
})->where('available_at', '<=', $now)
|
|
->orderBy('id')->lockForUpdate()->first();
|
|
if ($message === null) {
|
|
return null;
|
|
}
|
|
$token = bin2hex(random_bytes(16));
|
|
$message->status = 'sending';
|
|
$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->attempts = (int) $message->attempts + 1;
|
|
$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 = 'pending';
|
|
$message->available_at = $now + min(21600, 60 * (1 << min(8, (int) $message->attempts - 1)));
|
|
$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 = [];
|
|
$renewalInstanceIds = [];
|
|
$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 ($purpose === 'renewal' && $invoice->instance_id !== null) {
|
|
$renewalInstanceIds[(int) $invoice->instance_id]
|
|
= (int) $invoice->instance_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 = [];
|
|
if ($renewalInstanceIds !== []) {
|
|
foreach (CloudInstance::whereIn('id', array_values($renewalInstanceIds))
|
|
->whereIn('user_id', array_values($ownerIds))
|
|
->get(['id', 'user_id', 'status']) as $instance) {
|
|
$instances[self::listKey((int) $instance->user_id, (int) $instance->id)]
|
|
= $instance;
|
|
}
|
|
}
|
|
$jobs = [];
|
|
if ($orderIds !== []) {
|
|
foreach (CloudJob::whereIn('order_id', array_values($orderIds))
|
|
->whereIn('user_id', array_values($ownerIds))
|
|
->get(['id', 'order_id', 'user_id', 'status']) as $job) {
|
|
$jobs[self::listKey((int) $job->user_id, (int) $job->order_id)] = $job;
|
|
}
|
|
}
|
|
|
|
$now = time();
|
|
$summaries = [];
|
|
foreach ($records as $invoice) {
|
|
$ownerId = (int) $invoice->user_id;
|
|
$purpose = (string) ($invoice->purpose ?: 'renewal');
|
|
$title = match ($purpose) {
|
|
'recharge' => '余额充值',
|
|
'provision' => '实例开通',
|
|
'renewal' => '实例续费',
|
|
default => '账单',
|
|
};
|
|
$order = $purpose === 'provision' && $invoice->order_id !== null
|
|
? ($orders[self::listKey($ownerId, (int) $invoice->order_id)] ?? null)
|
|
: null;
|
|
$job = $order === null
|
|
? null : ($jobs[self::listKey($ownerId, (int) $order->id)] ?? null);
|
|
$instance = $purpose === 'renewal' && $invoice->instance_id !== null
|
|
? ($instances[self::listKey($ownerId, (int) $invoice->instance_id)] ?? null)
|
|
: null;
|
|
$status = self::publicStatus($invoice, $purpose, $instance, $now);
|
|
$summaries[] = [
|
|
'id' => (string) $invoice->id,
|
|
'title' => $title,
|
|
'type_label' => $title,
|
|
'purpose' => $purpose,
|
|
'amount' => (string) $invoice->amount,
|
|
'status' => $status,
|
|
'created_at' => (int) $invoice->created_at,
|
|
'order_status' => $order?->status,
|
|
'fulfillment_status' => $job?->status ?? $order?->status,
|
|
'job_status' => $job?->status,
|
|
];
|
|
}
|
|
return $summaries;
|
|
}
|
|
|
|
private static function listKey(int $userId, int $recordId): string
|
|
{
|
|
return $userId . ':' . $recordId;
|
|
}
|
|
|
|
/** 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;
|
|
}
|
|
|
|
/**
|
|
* 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, deadline: int, payable: bool}
|
|
*/
|
|
private static function publicState(CloudInvoice $invoice, string $purpose,
|
|
$order, $instance, int $now): 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;
|
|
} else {
|
|
$payable = in_array($status, ['open', 'overdue'], true)
|
|
&& $instance !== null
|
|
&& !self::instanceDeleting($instance)
|
|
&& $deadline > $now;
|
|
}
|
|
|
|
return ['status' => $status, 'deadline' => $deadline,
|
|
'payable' => $payable];
|
|
}
|
|
|
|
/**
|
|
* 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', 'kind', 'status', 'attempts',
|
|
'updated_at', 'error_code', 'result_json']);
|
|
}
|
|
} elseif ($purpose === 'renewal' && $invoice->instance_id !== null) {
|
|
$instance = CloudInstance::where('id', $invoice->instance_id)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'user_id', 'status', 'service_status']);
|
|
}
|
|
|
|
$publicState = self::publicState($invoice, $purpose, $order, $instance, $now);
|
|
$status = $publicState['status'];
|
|
$deadline = $publicState['deadline'];
|
|
$payable = $publicState['payable'];
|
|
|
|
$decodedJobResult = $job === null || $job->result_json === null
|
|
? null : json_decode((string) $job->result_json, true);
|
|
$safeJobResult = is_array($decodedJobResult)
|
|
? CloudOperationErrorCatalog::result($decodedJobResult, false,
|
|
(string) ($job?->kind ?? 'create'), (string) ($job?->status ?? $order?->status),
|
|
true) : null;
|
|
$jobPhase = CloudOperationErrorCatalog::userPhase(
|
|
$safeJobResult['phase'] ?? null, (string) ($job?->status ?? $order?->status),
|
|
(string) ($job?->kind ?? 'create')
|
|
);
|
|
$linkedInstanceId = $purpose === 'provision'
|
|
? ($order?->instance_id ?? $invoice->instance_id)
|
|
: $invoice->instance_id;
|
|
$linkedInstance = $purpose === 'renewal' ? $instance
|
|
: ($linkedInstanceId === null ? null
|
|
: CloudInstance::where('id', $linkedInstanceId)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'user_id']));
|
|
$instanceId = $linkedInstance?->id;
|
|
// A job status originates from the engine/worker lifecycle. Keep the
|
|
// user DTO on the reviewed status vocabulary instead of reflecting a
|
|
// future host-controlled value into the browser.
|
|
$jobStatus = $job === null
|
|
? null
|
|
: (CloudOperationErrorCatalog::userStatus($job->status) ?? 'unknown');
|
|
$fulfillmentStatus = $jobStatus ?? $order?->status;
|
|
$jobError = $job === null ? null : CloudOperationErrorCatalog::userMessage(
|
|
(string) ($job->kind ?? 'create'), (string) $job->status, $job->error_code, true
|
|
);
|
|
|
|
return [
|
|
'id' => (string) $invoice->id,
|
|
'purpose' => $purpose,
|
|
'status' => $status,
|
|
'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,
|
|
'job_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $jobStatus,
|
|
'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,
|
|
'job_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $jobStatus,
|
|
'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 = match ($purpose) {
|
|
'recharge' => '余额充值',
|
|
'provision' => '实例开通',
|
|
'renewal' => '实例续费',
|
|
default => '账单',
|
|
};
|
|
$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']);
|
|
$job = $order === null ? null
|
|
: CloudJob::where('order_id', $order->id)
|
|
->where('user_id', $invoice->user_id)
|
|
->first(['id', 'order_id', 'user_id', 'kind', 'status', 'attempts',
|
|
'updated_at', 'error_code']);
|
|
// Successful workers persist both links. Keep the invoice-side link
|
|
// as a defensive fallback for an interrupted upgrade or a repaired
|
|
// order row so the unified bill can still open the created instance.
|
|
$provisionInstanceId = $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'] ?? ''));
|
|
$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'];
|
|
$deadline = $publicState['deadline'];
|
|
$payable = $publicState['payable'];
|
|
$jobError = $job === null ? null : CloudOperationErrorCatalog::userMessage(
|
|
(string) ($job->kind ?? 'create'), (string) $job->status, $job->error_code, true
|
|
);
|
|
$jobStatus = $job === null
|
|
? null
|
|
: (CloudOperationErrorCatalog::userStatus($job->status) ?? 'unknown');
|
|
return [
|
|
'id' => (string) $invoice->id,
|
|
'title' => $title,
|
|
'type_label' => $title,
|
|
'purpose' => $purpose,
|
|
'instance_id' => $instance === null ? null : (string) $instance->id,
|
|
'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,
|
|
'job_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $jobStatus,
|
|
'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,
|
|
'job_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $jobStatus,
|
|
'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,
|
|
'validity_days' => (int) $invoice->validity_days,
|
|
'service_days' => (int) $invoice->validity_days,
|
|
'traffic_quota_bytes' => (int) $invoice->traffic_quota_bytes,
|
|
'status' => $status,
|
|
'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,
|
|
];
|
|
}
|
|
|
|
public static function payBalance(CloudInvoice $invoice, array $actor, string $idempotency): CloudInvoice
|
|
{
|
|
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);
|
|
}
|
|
return $result['invoice'];
|
|
}
|
|
|
|
/**
|
|
* 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);
|
|
}
|
|
if ((int) $user->restrict_balance_purchase === 1) {
|
|
throw new CloudError('账户套餐购买服务已被管理员停用', 403);
|
|
}
|
|
$sourcePurpose = (string) ($source->purpose ?: 'renewal');
|
|
$instance = null;
|
|
if ($sourcePurpose !== 'provision') {
|
|
// Keep the established lifecycle lock order for renewals:
|
|
// user -> instance -> invoice.
|
|
$instance = CloudInstance::where('id', (int) $source->instance_id)
|
|
->lockForUpdate()->first();
|
|
}
|
|
$invoice = CloudInvoice::where('id', $source->id)->lockForUpdate()->first();
|
|
if ($invoice === null || (int) $invoice->user_id !== (int) $user->id) {
|
|
throw new CloudError('账单不存在', 404);
|
|
}
|
|
if ((string) $invoice->status === 'paid') {
|
|
return ['outcome' => 'already_paid', 'invoice' => $invoice];
|
|
}
|
|
$purpose = (string) ($invoice->purpose ?: 'renewal');
|
|
if ($purpose !== $sourcePurpose) {
|
|
throw new CloudError('账单类型已变更,请刷新后重试', 409);
|
|
}
|
|
if ($purpose === 'provision') {
|
|
$order = CloudOrder::where('id', $invoice->order_id)
|
|
->where('user_id', $user->id)->lockForUpdate()->first();
|
|
if ($order === null
|
|
|| in_array((string) $invoice->status, ['expired', 'void'], true)
|
|
|| self::paymentDeadlinePassed($invoice)
|
|
|| (string) $order->status !== 'awaiting_payment') {
|
|
if ($order !== null && (string) $order->status === 'awaiting_payment') {
|
|
CloudOrderService::releaseStock($order);
|
|
$order->status = 'expired';
|
|
$order->payload_cipher = null;
|
|
$order->updated_at = time();
|
|
$order->save();
|
|
}
|
|
if (in_array((string) $invoice->status, ['open', 'overdue'], true)) {
|
|
$invoice->status = 'expired';
|
|
$invoice->updated_at = time();
|
|
$invoice->save();
|
|
}
|
|
return ['outcome' => 'stale', 'invoice' => $invoice];
|
|
}
|
|
if ((int) $order->plan_id !== (int) $invoice->plan_id
|
|
|| (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->payload_cipher = null;
|
|
$order->updated_at = time();
|
|
$order->save();
|
|
$invoice->status = 'void';
|
|
$invoice->updated_at = time();
|
|
$invoice->save();
|
|
return ['outcome' => 'stale', 'invoice' => $invoice];
|
|
}
|
|
$price = CloudMoney::cents((string) $invoice->amount);
|
|
$balance = CloudMoney::cents((string) $user->money);
|
|
if ($balance < $price) {
|
|
throw new CloudError('账户余额不足', 409);
|
|
}
|
|
CloudOrderService::queuePaidProvision($invoice, $order);
|
|
$user->money = CloudMoney::decimal($balance - $price);
|
|
$user->save();
|
|
$invoice->status = 'paid';
|
|
$invoice->paid_via = mb_substr($paidVia, 0, 32);
|
|
$invoice->payment_reference = $reference === ''
|
|
? null : mb_substr($reference, 0, 80);
|
|
$invoice->paid_at = time();
|
|
$invoice->updated_at = time();
|
|
$invoice->save();
|
|
return ['outcome' => 'paid', 'invoice' => $invoice,
|
|
'order' => $order->fresh() ?? $order];
|
|
}
|
|
|
|
if (($instance !== null && self::instanceDeleting($instance))
|
|
|| in_array((string) $invoice->status, ['expired'], true)
|
|
|| (in_array((string) $invoice->status, ['open', 'overdue'], true)
|
|
&& 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
|
|
|| CloudMoney::cents((string) $instance->renewal_price) !== CloudMoney::cents((string) $invoice->amount)
|
|
|| (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)));
|
|
}
|
|
}
|