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.
virt/web/app/Services/Cloud/CloudInvoiceDetailPageServi...

165 lines
6.6 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\CloudInvoicePayment;
use App\Models\User;
use App\Services\AdminCsrf;
/**
* Owner-scoped invoice detail payload shared by the HTML first paint and API.
*
* Keeping the public payload in one place prevents server-rendered content and
* later JavaScript refreshes from applying different payable/status rules.
*/
final class CloudInvoiceDetailPageService
{
public static function forUser(int $invoiceId, int $userId, User $user,
bool $isAdmin = false): array
{
if ($invoiceId <= 0 || $userId <= 0 || (int) $user->id !== $userId) {
throw new CloudError('账单不存在', 404);
}
// The invoice and its order/job/instance snapshot must agree. Holding
// a shared lock prevents a concurrent payment transaction from
// returning an old invoice status with newly-updated associations.
$snapshot = (new CloudInvoice())->getConnection()->transaction(
function () use ($invoiceId, $userId) {
$invoice = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)
->sharedLock()
->first();
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}
$detail = CloudInvoiceService::display($invoice);
return [
'invoice' => $detail,
'active_payment' => in_array(
(string) ($detail['status'] ?? ''),
['open', 'overdue'],
true
)
? self::activePaymentLocked($invoiceId, $userId)
: null,
];
}, 3
);
$detail = $snapshot['invoice'];
$activePayment = $snapshot['active_payment'];
$canStartPayment = ($detail['payable'] ?? false) === true;
if ($activePayment !== null) {
$activePayment['can_submit'] = $canStartPayment;
}
$payload = [
'invoice' => $detail,
'active_payment' => $activePayment,
'payment_methods' => $canStartPayment
? CloudInvoicePaymentService::methods($user) : [],
'balance_payment_allowed' => $canStartPayment
&& (int) $user->enable === 1,
'balance' => (string) $user->money,
'csrf_token' => AdminCsrf::token(),
'user_id' => (string) $user->id,
'username' => (string) ($user->user_name ?: $user->email),
'admin' => $isAdmin,
];
$payload['presentation'] = CloudInvoicePresentation::detail($payload);
return $payload;
}
/**
* Rehydrate only an already-durable payment attempt. This read path never
* contacts a provider and never creates or retries a provider order.
*/
private static function activePaymentLocked(int $invoiceId,
int $userId): ?array
{
$payment = CloudInvoicePayment::where('invoice_id', $invoiceId)
->where('user_id', $userId)
->whereIn('status', ['creating', 'pending', 'creation_unknown'])
->orderByDesc('updated_at')->orderByDesc('id')
->sharedLock()
->first();
$jobQuery = CloudJobService::blockingQueryForInvoice($invoiceId)
->where('user_id', $userId);
if ($payment !== null) {
$jobQuery->where('request_idempotency_key',
(string) $payment->idempotency_key);
}
$job = $jobQuery->orderByDesc('id')->sharedLock()
->first(['id', 'user_id', 'invoice_id', 'kind', 'phase',
'outcome', 'effect_resolution', 'safe_to_resubmit']);
if ($job === null && $payment === null) {
return null;
}
$review = ($payment !== null
&& (string) $payment->status === 'creation_unknown')
|| ($job !== null
&& (string) $job->phase === 'terminal'
&& (string) $job->outcome === 'failed'
&& (string) $job->effect_resolution === 'unknown');
$status = $review ? 'review'
: ($payment !== null && (string) $payment->status === 'pending'
? 'pending' : 'creating');
$safePayment = null;
if ($status === 'pending' && $payment !== null) {
try {
$safePayment = CloudInvoicePaymentService::display($payment);
} catch (CloudError) {
// A missing provider ledger is itself uncertain evidence.
// Keep the invoice fenced and expose no stale payment link.
$status = 'review';
}
}
return [
'status' => $status,
'task_id' => $job === null ? null : (string) $job->id,
'payment' => $safePayment,
'can_submit' => true,
];
}
/** Return one owner-scoped, transactionally consistent polling snapshot. */
public static function statusForUser(int $invoiceId, int $userId): array
{
if ($invoiceId <= 0 || $userId <= 0) {
throw new CloudError('账单不存在', 404);
}
return (new CloudInvoice())->getConnection()->transaction(
function () use ($invoiceId, $userId) {
$invoice = CloudInvoice::where('id', $invoiceId)
->where('user_id', $userId)
->sharedLock()
->first(['id', 'purpose', 'instance_id', 'order_id', 'user_id',
'renews_expires_at', 'due_at', 'status', 'paid_at',
'paid_via', 'created_at']);
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}
$status = CloudInvoiceService::status($invoice);
$activePayment = in_array(
(string) ($status['status'] ?? ''),
['open', 'overdue'],
true
) ? self::activePaymentLocked($invoiceId, $userId) : null;
if ($activePayment !== null) {
$activePayment['can_submit'] =
($status['payable'] ?? false) === true;
}
$payload = [
'invoice' => $status,
'active_payment' => $activePayment,
];
$payload['presentation_patch'] =
CloudInvoicePresentation::statusPatch($payload);
return $payload;
}, 3
);
}
}