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

62 lines
1.7 KiB
PHP

<?php
namespace App\Services;
use App\Exceptions\BalanceNotEnoughException;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class BalanceService
{
/**
* 变更余额
*
* @param \App\Models\User $user
* @param int $changeBalance
* @param int $action
* @param string|null $remarks
* @param mixed $loggable
* @return void
*/
public function changeBalance(User $user, int $changeBalance, int $action, ?string $remarks = null, $loggable = null)
{
$balance = $user->balance()->lockForUpdate()->first();
if (is_null($balance)) {
throw new BalanceNotEnoughException();
}
// 变更前余额
$beforeBalance = $balance->balance;
$_changeBalance = abs($changeBalance);
if ($changeBalance > 0) {
// 收入
$user->balance()->update([
'balance' => DB::raw("balance + {$_changeBalance}"),
'total_revenue' => DB::raw("total_revenue + {$_changeBalance}"),
]);
} else {
// 支出
if ($balance->balance < $_changeBalance) {
throw new BalanceNotEnoughException();
}
$user->balance()->update([
'balance' => DB::raw("balance - {$_changeBalance}"),
'total_expenses' => DB::raw("total_expenses + {$_changeBalance}"),
]);
}
$user->balanceLogs()->create([
'loggable_id' => $loggable?->id,
'loggable_type' => $loggable?->getMorphClass(),
'before_balance' => $beforeBalance,
'change_balance' => $changeBalance,
'action' => $action,
'remarks' => $remarks,
]);
}
}