6
0
Fork 0
jiqu-library-server/app/Services/QuotaV1Service.php

58 lines
1.5 KiB
PHP

<?php
namespace App\Services;
use App\Exceptions\BizException;
use App\Models\User;
class QuotaV1Service
{
/**
* 变老配额余额
*
* @param \App\Models\User $user
* @param float $changeBalance
* @param int $action
* @param string|null $remarks
* @param mixed $loggable
* @return void
*/
public function changeBalance(User $user, float $changeBalance, int $action, ?string $remarks = null, $loggable = null)
{
if ($changeBalance === 0) {
return;
}
$userInfo = $user->userInfo()->lockForUpdate()->first();
if ($userInfo === null) {
throw new BizException('系统错误');
}
// 变更前余额
$beforeBalance = $userInfo->quota_v1;
$_changeBalance = abs($changeBalance);
if ($changeBalance > 0) {
// 收入
$user->userInfo()->increment('quota_v1', $_changeBalance);
} else {
// 支出
if ($userInfo->quota_v1 < $_changeBalance) {
throw new BizException('老配额不足');
}
$user->userInfo()->decrement('quota_v1', $_changeBalance);
}
$user->walletLogs()->create([
'loggable_id' => $loggable?->id,
'loggable_type' => $loggable?->getMorphClass(),
'before_balance' => $beforeBalance,
'change_balance' => $changeBalance,
'action' => $action,
'remarks' => $remarks,
]);
}
}