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...

76 lines
2.9 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\User;
use App\Services\AdminCsrf;
use App\Services\UserFeatureRestrictionService;
/**
* 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.
$detail = (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);
}
return CloudInvoiceService::display($invoice);
}, 3
);
return [
'invoice' => $detail,
'payment_methods' => ($detail['payable'] ?? false)
? CloudInvoicePaymentService::methods($user) : [],
'balance_payment_allowed' => (int) $user->enable === 1
&& !UserFeatureRestrictionService::isBalancePurchaseRestricted($user),
'balance' => (string) $user->money,
'csrf_token' => AdminCsrf::token(),
'user_id' => (string) $user->id,
'username' => (string) ($user->user_name ?: $user->email),
'admin' => $isAdmin,
];
}
/** 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',
'due_at', 'status', 'paid_at', 'paid_via', 'created_at']);
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}
return CloudInvoiceService::status($invoice);
}, 3
);
}
}