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.
574 lines
26 KiB
PHP
574 lines
26 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\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;
|
|
|
|
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,
|
|
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
|
|
|| !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->renewal_id = null;
|
|
$invoice->renews_expires_at = null;
|
|
$invoice->due_at = $now + CloudOrderService::PAYMENT_WINDOW_SECONDS;
|
|
$invoice->amount = $order->amount;
|
|
$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
|
|
{
|
|
$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) {
|
|
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();
|
|
|
|
$mail = new CloudMailOutbox();
|
|
$mail->invoice_id = $invoice->id;
|
|
$mail->kind = 'renewal_due';
|
|
$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;
|
|
}, 3);
|
|
}
|
|
|
|
public static function deliverReminders(int $limit = 20): int
|
|
{
|
|
$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);
|
|
$ok = false;
|
|
$error = '';
|
|
$cancel = false;
|
|
if ($invoice === null || $user === null || $instance === null
|
|
|| self::instanceDeleting($instance)
|
|
|| !in_array((string) $invoice->status, ['open', 'overdue'], true)
|
|
|| self::paymentDeadlinePassed($invoice)) {
|
|
$error = '账单或收件人已不可用';
|
|
$cancel = true;
|
|
} elseif (filter_var((string) $user->email, FILTER_VALIDATE_EMAIL) === false) {
|
|
$error = '用户邮箱无效';
|
|
} else {
|
|
$base = rtrim((string) Config::get('baseUrl', ''), '/');
|
|
$ok = Mail::send((string) $user->email, '云服务器续费账单提醒',
|
|
'cloud/invoice.tpl', [
|
|
'invoice_no' => (string) $invoice->invoice_no,
|
|
'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',
|
|
], [], 'cloud_renewal_invoice');
|
|
if (!$ok) {
|
|
$error = '邮件服务未接受消息';
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
|
|
public static function display(CloudInvoice $invoice): array
|
|
{
|
|
$now = time();
|
|
$purpose = (string) ($invoice->purpose ?: 'renewal');
|
|
$instance = $invoice->instance_id === null
|
|
? null : CloudInstance::find($invoice->instance_id);
|
|
$order = $invoice->order_id === null
|
|
? null : CloudOrder::find($invoice->order_id);
|
|
$job = $order === null ? null
|
|
: CloudJob::where('order_id', $order->id)->first();
|
|
// 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 = $order?->instance_id ?? $invoice->instance_id;
|
|
$spec = $order === null ? []
|
|
: (json_decode((string) $order->spec_json, true) ?: []);
|
|
$status = (string) $invoice->status;
|
|
if ($purpose === 'renewal'
|
|
&& ($instance === null || (string) $instance->status === 'deleted')) {
|
|
if (in_array($status, ['open', 'overdue'], true)) {
|
|
$status = 'void';
|
|
}
|
|
} elseif ($status === 'open' && (int) $invoice->due_at <= $now) {
|
|
$status = 'overdue';
|
|
}
|
|
$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 [
|
|
'id' => (string) $invoice->id,
|
|
'invoice_no' => (string) $invoice->invoice_no,
|
|
'purpose' => $purpose,
|
|
'instance_id' => $purpose === 'provision'
|
|
? ($provisionInstanceId === null ? null : (string) $provisionInstanceId)
|
|
: ($invoice->instance_id === null ? null : (string) $invoice->instance_id),
|
|
'instance_name' => $purpose === 'provision'
|
|
? (string) ($spec['name'] ?? '待开通实例')
|
|
: ($instance?->name ?? '已删除实例'),
|
|
'requested_name' => $purpose === 'provision'
|
|
? (string) ($spec['name'] ?? '') : null,
|
|
'plan_name' => (string) ($spec['plan_name'] ?? ''),
|
|
'order_id' => $order === null ? null : (string) $order->id,
|
|
'order_status' => $order?->status,
|
|
'fulfillment_status' => $job?->status ?? $order?->status,
|
|
'job_id' => $job === null ? null : (string) $job->id,
|
|
'job_status' => $job?->status,
|
|
'error' => $job?->error_code,
|
|
'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' => $job?->status,
|
|
'instance_id' => $provisionInstanceId === null
|
|
? null : (string) $provisionInstanceId,
|
|
'error' => $job?->error_code,
|
|
] : null,
|
|
'amount' => (string) $invoice->amount,
|
|
'validity_days' => (int) $invoice->validity_days,
|
|
'traffic_quota_bytes' => (int) $invoice->traffic_quota_bytes,
|
|
'status' => $status,
|
|
'due_at' => (int) $invoice->due_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
|
|
|| 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)));
|
|
}
|
|
}
|