补齐座驾购买金币流水

This commit is contained in:
pllx
2026-04-30 10:02:59 +08:00
parent 363c45a140
commit b60f3615c1
5 changed files with 58 additions and 10 deletions
+28 -5
View File
@@ -8,6 +8,7 @@
namespace App\Services;
use App\Enums\CurrencySource;
use App\Models\Ride;
use App\Models\User;
use App\Models\UserRidePurchase;
@@ -22,6 +23,13 @@ use Illuminate\Support\Facades\DB;
*/
class RideService
{
/**
* 构造座驾服务依赖。
*/
public function __construct(
private readonly UserCurrencyService $currencyService,
) {}
/**
* 获取全部上架座驾商品。
*
@@ -116,7 +124,7 @@ class RideService
*
* @return array{ok:bool, message:string, current_ride?:array<string, mixed>}
*/
public function buy(User $user, Ride $item): array
public function buy(User $user, Ride $item, ?int $roomId = null): array
{
if (! $item->is_active) {
return ['ok' => false, 'message' => '该座驾暂未上架。'];
@@ -131,7 +139,7 @@ class RideService
return ['ok' => false, 'message' => "金币不足,购买【{$item->name}】需要 {$item->price} 金币,当前仅有 {$user->jjb} 金币。"];
}
DB::transaction(function () use ($user, $item, $days): void {
$purchased = DB::transaction(function () use ($user, $item, $days, $roomId): bool {
$now = Carbon::now();
// 先清理已过期的 active 座驾,避免旧状态影响替换判断。
@@ -149,8 +157,17 @@ class RideService
->orderByDesc('expires_at')
->first();
// 座驾购买必须先扣金币,后续续期或替换都在同一个事务内完成。
$user->decrement('jjb', $item->price);
$balanceAfter = $this->currencyService->deductGoldIfEnough(
$user,
(int) $item->price,
CurrencySource::RIDE_BUY,
"购买聊天室座驾:{$item->name}",
$roomId,
);
if ($balanceAfter === null) {
return false;
}
if ($activeRide && (int) $activeRide->ride_id === (int) $item->id) {
$baseTime = $activeRide->expires_at && $activeRide->expires_at->greaterThan($now)
@@ -167,7 +184,7 @@ class RideService
'expires_at' => $baseTime->copy()->addDays($days),
]);
return;
return true;
}
if ($activeRide) {
@@ -182,8 +199,14 @@ class RideService
'price_paid' => $item->price,
'expires_at' => $now->copy()->addDays($days),
]);
return true;
});
if (! $purchased) {
return ['ok' => false, 'message' => "金币不足,购买【{$item->name}】需要 {$item->price} 金币,当前仅有 {$user->fresh()->jjb} 金币。"];
}
return [
'ok' => true,
'message' => "购买成功!{$item->icon} {$item->name} 已激活({$days}天有效)。",