73 lines
2.0 KiB
PHP
73 lines
2.0 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)
|
|
{
|
|
if ($changeBalance === 0) {
|
|
return;
|
|
}
|
|
|
|
$wallet = $user->wallet()->lockForUpdate()->first();
|
|
|
|
if ($wallet === null) {
|
|
if ($changeBalance < 0) {
|
|
throw new WalletNotEnoughException();
|
|
}
|
|
|
|
// 创建可提表
|
|
$user->wallet()->create();
|
|
// 锁定可提表
|
|
$wallet = $user->wallet()->lockForUpdate()->first();
|
|
}
|
|
|
|
// 变更前余额
|
|
$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,
|
|
]);
|
|
}
|
|
}
|