diff --git a/src/Traits/BalanceOperation.php b/src/Traits/BalanceOperation.php index 247fb26..5e04d61 100644 --- a/src/Traits/BalanceOperation.php +++ b/src/Traits/BalanceOperation.php @@ -3,6 +3,7 @@ namespace HPWebdeveloper\LaravelPayPocket\Traits; use HPWebdeveloper\LaravelPayPocket\Models\WalletsLog; +use Illuminate\Support\Facades\DB; use InvalidArgumentException; trait BalanceOperation @@ -22,8 +23,10 @@ public function hasBalance(): bool */ public function decrementAndCreateLog(int|float $value, ?string $notes = null): void { - $this->createLog('dec', $value, $notes); - $this->decrement('balance', $value); + DB::transaction(function () use ($value, $notes) { + $this->createLog('dec', $value, $notes); + $this->decrement('balance', $value); + }); } /** @@ -31,8 +34,10 @@ public function decrementAndCreateLog(int|float $value, ?string $notes = null): */ public function incrementAndCreateLog(int|float $value, ?string $notes = null): void { - $this->createLog('inc', $value, $notes); - $this->increment('balance', $value); + DB::transaction(function () use ($value, $notes) { + $this->createLog('inc', $value, $notes); + $this->increment('balance', $value); + }); } /** @@ -44,7 +49,7 @@ protected function createLog(string $logType, int|float $value, ?string $notes = $newBalance = $logType === 'dec' ? $currentBalance - $value : $currentBalance + $value; - $this->createdLog = $this->logs()->create([ + $walletLog = (new WalletsLog())->fill([ 'wallet_name' => $this->type->value, 'from' => $currentBalance, 'to' => $newBalance, @@ -55,7 +60,9 @@ protected function createLog(string $logType, int|float $value, ?string $notes = 'reference' => $this->generateReference(), ]); - $this->createdLog->changeStatus('Done'); + $walletLog->status = 'Done'; + + $this->createdLog = $this->logs()->save($walletLog); } /**