From eff2d7ff15c8b240e4dce8934bff0015d886d981 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi Date: Fri, 29 Nov 2024 15:21:13 +0000 Subject: [PATCH] feat: add event dispatching for credit transactions --- src/Events/CreditsAdded.php | 14 ++++++++ src/Events/CreditsDeducted.php | 14 ++++++++ src/Events/CreditsTransferred.php | 16 +++++++++ src/Traits/HasCredits.php | 54 +++++++++++++++++++++++++++---- 4 files changed, 91 insertions(+), 7 deletions(-) create mode 100644 src/Events/CreditsAdded.php create mode 100644 src/Events/CreditsDeducted.php create mode 100644 src/Events/CreditsTransferred.php diff --git a/src/Events/CreditsAdded.php b/src/Events/CreditsAdded.php new file mode 100644 index 0000000..f18082d --- /dev/null +++ b/src/Events/CreditsAdded.php @@ -0,0 +1,14 @@ +getCurrentBalance(); $newBalance = $currentBalance + $amount; - return $this->creditTransactions()->create([ + $credit = $this->creditTransactions()->create([ 'amount' => $amount, 'description' => $description, 'type' => 'credit', 'metadata' => $metadata, 'running_balance' => $newBalance, ]); + + event(new CreditsAdded( + creditable: $this, + amount: $amount, + newBalance: $newBalance, + description: $description, + metadata: $metadata + )); + + return $credit; } /** @@ -54,13 +67,23 @@ public function deductCredits(float $amount, ?string $description = null, array throw new InsufficientCreditsException($amount, $currentBalance); } - return $this->creditTransactions()->create([ + $credit = $this->creditTransactions()->create([ 'amount' => $amount, 'description' => $description, 'type' => 'debit', 'metadata' => $metadata, 'running_balance' => $newBalance, ]); + + event(new CreditsDeducted( + creditable: $this, + amount: $amount, + newBalance: $newBalance, + description: $description, + metadata: $metadata + )); + + return $credit; } /** @@ -86,15 +109,32 @@ public function getCurrentBalance(): float */ public function transferCredits(self $recipient, float $amount, ?string $description = null, array $metadata = []): array { - DB::transaction(function () use ($recipient, $amount, $description, $metadata) { + $result = []; + + DB::transaction(function () use ($recipient, $amount, $description, $metadata, &$result) { $this->deductCredits($amount, $description, $metadata); $recipient->addCredits($amount, $description, $metadata); + + $senderBalance = $this->getCurrentBalance(); + $recipientBalance = $recipient->getCurrentBalance(); + + event(new CreditsTransferred( + sender: $this, + recipient: $recipient, + amount: $amount, + senderNewBalance: $senderBalance, + recipientNewBalance: $recipientBalance, + description: $description, + metadata: $metadata + )); + + $result = [ + 'sender_balance' => $senderBalance, + 'recipient_balance' => $recipientBalance, + ]; }); - return [ - 'sender_balance' => $this->getCurrentBalance(), - 'recipient_balance' => $recipient->getCurrentBalance(), - ]; + return $result; } /**