Skip to content

Commit 7d14490

Browse files
pay() method returns collection instead of void (#49)
* Update: Change log_reference_length to log_reference_params to allow passing additional parameters to the log reference generator * Update: Change log_reference_length to log_reference_params to allow passing additional parameters to the log reference generator * Return a collection of all related WalletLog for successfull call to the pay() method. * Fix missing class references * Fix missing types * Run pint * Run pint one more time * add new feature to readme * Fix styling --------- Co-authored-by: https://github.com/toneflix-forks Co-authored-by: 3m1n3nc3 <mygames.ng@gmail.com>
1 parent 04bd1eb commit 7d14490

File tree

11 files changed

+131
-25
lines changed

11 files changed

+131
-25
lines changed

README.md

Lines changed: 73 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,13 @@
1111

1212
**Demo:** https://github.com/HPWebdeveloper/demo-pay-pocket
1313

14-
**Videos:**
14+
**Videos:**
1515

16-
- [Laravel Pay Pocket Package: Virtual Wallets in Your Project](https://www.youtube.com/watch?v=KoQyURiwsA4)
16+
- [Laravel Pay Pocket Package: Virtual Wallets in Your Project](https://www.youtube.com/watch?v=KoQyURiwsA4)
1717

18-
- [Laravel Exceptions: Why and How to Use? Practical Example.](https://www.youtube.com/watch?v=-Sr18w91v8Q)
19-
20-
- [PHP Enums in Laravel: Practical Example from Package](https://www.youtube.com/watch?v=iUOb-3HQtK8)
18+
- [Laravel Exceptions: Why and How to Use? Practical Example.](https://www.youtube.com/watch?v=-Sr18w91v8Q)
2119

20+
- [PHP Enums in Laravel: Practical Example from Package](https://www.youtube.com/watch?v=iUOb-3HQtK8)
2221

2322
**Note:** This package does not handle payments from payment platforms, but instead offers the concept of virtual money, deposit, and withdrawal.
2423

@@ -33,11 +32,10 @@
3332

3433
### Support Policy
3534

36-
| Version | Laravel | PHP | Release date | End of improvements | End of support |
37-
|-------------------------------------------------|--------------|-------------|---------------|---------------------| -------------- |
38-
| 1.x | ^10.0 | 8.1, 8.2, 8.3 | Nov 30, 2023 | Mar 1, 2024 | |
39-
| 2.x | ^10.0, ^11.0 |8.2, 8.3| June 27, 2024 | January 30, 2025 | |
40-
| 3.x (atomic operations and restricted wallets) | ^11.0 |8.2, 8.3| comming soon | | |
35+
| Version | Laravel | PHP | Release date | End of improvements | End of support |
36+
| ------- | ------------ | ------------- | ------------- | ------------------- | -------------- |
37+
| 1.x | ^10.0 | 8.1, 8.2, 8.3 | Nov 30, 2023 | Mar 1, 2024 | |
38+
| 2.x | ^10.0, ^11.0 | 8.2, 8.3 | June 27, 2024 | January 30, 2025 | |
4139

4240
## Installation:
4341

@@ -178,6 +176,71 @@ $user = auth()->user();
178176
LaravelPayPocket::pay($user, 12.34);
179177
```
180178

179+
#### Payment Transaction Logs
180+
181+
The `pay()` method returns a collection of `WalletsLog` instances representing all wallet transactions that occurred during the payment. This enables you to track exactly which wallets were used and access detailed transaction information.
182+
183+
**Return Value:**
184+
185+
```php
186+
@return \Illuminate\Database\Eloquent\Collection<WalletsLog>
187+
```
188+
189+
**Basic Usage:**
190+
191+
```php
192+
$user = auth()->user();
193+
$logs = $user->pay(120.00, 'Order #1234');
194+
195+
// Access transaction details
196+
foreach ($logs as $log) {
197+
echo "Wallet: {$log->wallet_name}, Amount: {$log->value}";
198+
}
199+
```
200+
201+
**Practical Examples:**
202+
203+
```php
204+
// Get the number of wallets used in the payment
205+
$walletCount = $logs->count();
206+
207+
// Calculate total amount deducted (verification)
208+
$totalDeducted = $logs->sum('value');
209+
210+
// Get all wallet names used in the transaction
211+
$walletsUsed = $logs->pluck('wallet_name');
212+
213+
// Access specific log details
214+
$firstLog = $logs->first();
215+
echo "From: {$firstLog->from}, To: {$firstLog->to}";
216+
echo "Reference: {$firstLog->reference}";
217+
```
218+
219+
**Use Cases:**
220+
221+
- **Receipt Generation:** Display detailed payment breakdown showing amounts from each wallet
222+
- **Audit Trail:** Maintain comprehensive records of payment sources
223+
- **Transaction Verification:** Confirm the exact amount deducted from each wallet
224+
- **Analytics:** Track wallet usage patterns across payments
225+
226+
**Example: Multi-Wallet Payment**
227+
228+
```php
229+
$user = auth()->user();
230+
231+
// User has: wallet_1 = $100, wallet_2 = $50
232+
$logs = $user->pay(120.00, 'Premium subscription');
233+
234+
// Returns collection with 2 logs:
235+
// Log 1: wallet_1 deducted $100 (100.00 -> 0.00)
236+
// Log 2: wallet_2 deducted $20 (50.00 -> 30.00)
237+
238+
echo "Payment completed using {$logs->count()} wallet(s)";
239+
// Output: Payment completed using 2 wallet(s)
240+
```
241+
242+
**Note:** This feature is backward compatible. Existing code that doesn't capture the return value will continue to work without any modifications.
243+
181244
### Balance
182245

183246
- **Wallets**

config/pay-pocket.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@
1212
| This configuration allows you to customize the generation of log reference strings
1313
| within the LaravelPayPocket package.
1414
|
15-
| - [array] log_reference_params: An array of parameters to pass to the log_reference_generator_method.
16-
| - [string] log_reference_prefix: Prefix for the generated reference string.
17-
| - [class-string] log_reference_generator_class: Fully qualified name of the class containing static methods for generation.
18-
| - [string] log_reference_generator_method: Name of the static method available in the generator class.
15+
| - [array] log_reference_params: The parameters to pass to the log reference generator.
16+
| - [string] log_reference_prefix: The prefix for the generated reference string.
17+
| - [class-string] log_reference_generator_class: The fully qualified name of the class containing static methods for generation.
18+
| - [string] log_reference_generator_method: The name of the static method available in the generator class.
1919
|
2020
| By default, the following generator is set up:
2121
| Illuminate\Support\Str::random(12)

src/Facades/LaravelPayPocket.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
/**
99
* @see \HPWebdeveloper\LaravelPayPocket\Services\PocketServices
1010
*
11-
* @method static void pay(WalletOperations $user, int|float $orderValue, ?string $notes = null)
11+
* @method static \Illuminate\Support\Collection pay(WalletOperations $user, int|float $orderValue, ?string $notes = null)
1212
* @method static bool deposit(WalletOperations $user, string $type, int|float $amount, ?string $notes = null)
1313
* @method static int|float checkBalance(WalletOperations $user)
1414
* @method static int|float walletBalanceByType(WalletOperations $user, string $type)

src/Interfaces/WalletOperations.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace HPWebdeveloper\LaravelPayPocket\Interfaces;
44

55
use HPWebdeveloper\LaravelPayPocket\Exceptions\InsufficientBalanceException;
6+
use HPWebdeveloper\LaravelPayPocket\Models\WalletsLog;
67

78
interface WalletOperations
89
{
@@ -24,9 +25,11 @@ public function hasSufficientBalance(int|float $value): bool;
2425
/**
2526
* Pay the order value from the user's wallets.
2627
*
28+
* @return \Illuminate\Support\Collection<TKey,WalletsLog>
29+
*
2730
* @throws InsufficientBalanceException
2831
*/
29-
public function pay(int|float $orderValue, ?string $notes = null): void;
32+
public function pay(int|float $orderValue, ?string $notes = null): \Illuminate\Support\Collection;
3033

3134
/**
3235
* Deposit an amount to the user's wallet of a specific type.

src/Services/PocketServices.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use HPWebdeveloper\LaravelPayPocket\Exceptions\InsufficientBalanceException;
66
use HPWebdeveloper\LaravelPayPocket\Interfaces\WalletOperations;
7+
use HPWebdeveloper\LaravelPayPocket\Models\WalletsLog;
78

89
class PocketServices
910
{
@@ -18,11 +19,13 @@ public function deposit(WalletOperations $user, string $type, int|float $amount,
1819
/**
1920
* Pay the order value from the user's wallets.
2021
*
22+
* @return \Illuminate\Support\Collection<TKey,WalletsLog>
23+
*
2124
* @throws InsufficientBalanceException
2225
*/
23-
public function pay(WalletOperations $user, int|float $orderValue, ?string $notes = null): void
26+
public function pay(WalletOperations $user, int|float $orderValue, ?string $notes = null): \Illuminate\Support\Collection
2427
{
25-
$user->pay($orderValue, $notes);
28+
return $user->pay($orderValue, $notes);
2629
}
2730

2831
/**

src/Traits/BalanceOperation.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,23 @@ public function hasBalance(): bool
2020
/**
2121
* Decrement Balance and create a log entry.
2222
*/
23-
public function decrementAndCreateLog(int|float $value, ?string $notes = null): void
23+
public function decrementAndCreateLog(int|float $value, ?string $notes = null): WalletsLog
2424
{
2525
$this->createLog('dec', $value, $notes);
2626
$this->decrement('balance', $value);
27+
28+
return $this->createdLog;
2729
}
2830

2931
/**
3032
* Increment Balance and create a log entry.
3133
*/
32-
public function incrementAndCreateLog(int|float $value, ?string $notes = null): void
34+
public function incrementAndCreateLog(int|float $value, ?string $notes = null): WalletsLog
3335
{
3436
$this->createLog('inc', $value, $notes);
3537
$this->increment('balance', $value);
38+
39+
return $this->createdLog;
3640
}
3741

3842
/**

src/Traits/HandlesDeposit.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ trait HandlesDeposit
1313
/**
1414
* Deposit an amount to the user's wallet of a specific type.
1515
*
16+
*
1617
* @throws InvalidDepositException
1718
* @throws InvalidValueException
1819
* @throws InvalidWalletTypeException
@@ -26,7 +27,7 @@ public function deposit(string $type, int|float $amount, ?string $notes = null):
2627
}
2728

2829
if ($amount <= 0) {
29-
throw new InvalidValueException();
30+
throw new InvalidValueException;
3031
}
3132

3233
DB::transaction(function () use ($type, $amount, $notes) {

src/Traits/HandlesPayment.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,36 +3,42 @@
33
namespace HPWebdeveloper\LaravelPayPocket\Traits;
44

55
use HPWebdeveloper\LaravelPayPocket\Exceptions\InsufficientBalanceException;
6+
use HPWebdeveloper\LaravelPayPocket\Models\WalletsLog;
67
use Illuminate\Support\Facades\DB;
78

89
trait HandlesPayment
910
{
1011
/**
1112
* Pay the order value from the user's wallets.
1213
*
14+
*
15+
* @return \Illuminate\Support\Collection<TKey,WalletsLog>
16+
*
1317
* @throws InsufficientBalanceException
1418
*/
15-
public function pay(int|float $orderValue, ?string $notes = null): void
19+
public function pay(int|float $orderValue, ?string $notes = null): \Illuminate\Database\Eloquent\Collection
1620
{
1721
if (! $this->hasSufficientBalance($orderValue)) {
1822
throw new InsufficientBalanceException('Insufficient balance to cover the order.');
1923
}
2024

21-
DB::transaction(function () use ($orderValue, $notes) {
25+
return DB::transaction(function () use ($orderValue, $notes) {
2226
$remainingOrderValue = $orderValue;
2327

2428
/**
2529
* @var \Illuminate\Support\Collection<TKey, \HPWebdeveloper\LaravelPayPocket\Models\Wallet>
2630
*/
2731
$walletsInOrder = $this->wallets()->whereIn('type', $this->walletsInOrder())->get();
2832

33+
$logs = (new WalletsLog)->newCollection();
34+
2935
foreach ($walletsInOrder as $wallet) {
3036
if (! $wallet || ! $wallet->hasBalance()) {
3137
continue;
3238
}
3339

3440
$amountToDeduct = min($wallet->balance, $remainingOrderValue);
35-
$wallet->decrementAndCreateLog($amountToDeduct, $notes);
41+
$logs->push($wallet->decrementAndCreateLog($amountToDeduct, $notes));
3642
$remainingOrderValue -= $amountToDeduct;
3743

3844
if ($remainingOrderValue <= 0) {
@@ -43,6 +49,8 @@ public function pay(int|float $orderValue, ?string $notes = null): void
4349
if ($remainingOrderValue > 0) {
4450
throw new InsufficientBalanceException('Insufficient total wallet balance to cover the order.');
4551
}
52+
53+
return $logs;
4654
});
4755
}
4856
}

tests/OperationsWithFacadeTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,15 @@
129129

130130
expect(WalletsLog::whereNotNull('reference')->exists())->toBe(true);
131131
});
132+
133+
test('Payment returns log', function () {
134+
$user = User::factory()->create();
135+
136+
$type = 'wallet_2';
137+
138+
LaravelPayPocket::deposit($user, $type, 234.56);
139+
140+
$log = LaravelPayPocket::pay($user, 100.16);
141+
142+
expect($log->sum('value'))->toBe(100.16);
143+
});

tests/OperationsWithoutFacadeTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,3 +130,15 @@
130130

131131
expect(WalletsLog::whereNotNull('reference')->exists())->toBe(true);
132132
});
133+
134+
test('Payment returns log', function () {
135+
$user = User::factory()->create();
136+
137+
$type = 'wallet_2';
138+
139+
$user->deposit($type, 234.56);
140+
141+
$log = $user->pay(100.16);
142+
143+
expect($log->sum('value'))->toBe(100.16);
144+
});

0 commit comments

Comments
 (0)