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

62 lines
1.7 KiB
PHP

<?php
namespace App\Services;
use App\Exceptions\WalletNotEnoughException;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class WalletService
{
/**
* 变更钱包余额
*
* @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)
{
$wallet = $user->wallet()->lockForUpdate()->first();
if (is_null($wallet)) {
throw new WalletNotEnoughException();
}
// 变更前余额
$beforeBalance = $wallet->balance;
$_changeBalance = abs($changeBalance);
if ($changeBalance > 0) {
// 收入
$user->wallet()->update([
'balance' => DB::raw("balance + {$_changeBalance}"),
'total_revenue' => DB::raw("total_revenue + {$_changeBalance}"),
]);
} else {
// 支出
if ($wallet->balance < $_changeBalance) {
throw new WalletNotEnoughException();
}
$user->wallet()->update([
'balance' => DB::raw("balance - {$_changeBalance}"),
'total_expenses' => DB::raw("total_expenses + {$_changeBalance}"),
]);
}
$user->walletLogs()->create([
'loggable_id' => $loggable?->id,
'loggable_type' => $loggable?->getMorphClass(),
'before_balance' => $beforeBalance,
'change_balance' => $changeBalance,
'action' => $action,
'remarks' => $remarks,
]);
}
}