Skip to content

Commit

Permalink
Add payment method and transaction resources, localization, and seedi…
Browse files Browse the repository at this point in the history
…ng functionality
  • Loading branch information
200-0K committed Nov 18, 2024
1 parent eb36db2 commit f376bbd
Show file tree
Hide file tree
Showing 20 changed files with 609 additions and 51 deletions.
1 change: 1 addition & 0 deletions .wakatime-project
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
laratransaction
147 changes: 128 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,38 @@
# Laravel Payment Transactions Helper

[![Latest Version on Packagist](https://img.shields.io/packagist/v/err0r/laratransaction.svg?style=flat-square)](https://packagist.org/packages/err0r/laratransaction)
[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/err0r/laratransaction/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/err0r/laratransaction/actions?query=workflow%3Arun-tests+branch%3Amain)
[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/err0r/laratransaction/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/err0r/laratransaction/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain)
[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/err0r/laratransaction/run-tests.yml?branch=master&label=tests&style=flat-square)](https://github.com/err0r/laratransaction/actions?query=workflow%3Arun-tests+branch%3Amaster)
[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/err0r/laratransaction/fix-php-code-style-issues.yml?branch=master&label=code%20style&style=flat-square)](https://github.com/err0r/laratransaction/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amaster)
[![Total Downloads](https://img.shields.io/packagist/dt/err0r/laratransaction.svg?style=flat-square)](https://packagist.org/packages/err0r/laratransaction)

This is where your description should go. Limit it to a paragraph or two. Consider adding a small example.
This package provides a complete transaction management system for Laravel applications, offering powerful features:

## Support us
💳 **Payment Processing**
- Track payment transactions with multiple statuses (pending, completed, failed, cancelled)
- Support various transaction types (payment, refund)
- Handle diverse payment methods (credit card, bank transfer, cash, etc.)

[<img src="https://github-ads.s3.eu-central-1.amazonaws.com/laratransaction.jpg?t=1" width="419px" />](https://spatie.be/github-ad-click/laratransaction)
🔗 **Flexible Integration**
- Associate transactions with any model using polymorphic relationships
- Store rich transaction metadata
- Track payment gateway information and IDs

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).
🌍 **Internationalization**
- Fully localized and translatable
- Multi-currency support
- JSON-based translations

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).
🛠️ **Developer Friendly**
- Fluent builder pattern for creating transactions
- Eloquent relationships and scopes
- API Resources for JSON responses
- Extensive configuration options

🔒 **Reliable & Secure**
- UUID support for better security
- Soft deletes for data integrity
- Comprehensive audit trail
- Transaction history tracking

## Installation

Expand All @@ -23,54 +42,144 @@ You can install the package via composer:
composer require err0r/laratransaction
```

You can publish and run the migrations with:
Publish the config file with:

```bash
php artisan vendor:publish --tag="laratransaction-config"
```

Publish and run the migrations with:

```bash
php artisan vendor:publish --tag="laratransaction-migrations"
php artisan migrate
```

You can publish the config file with:
Optionally, you can publish the translations using:

```bash
php artisan vendor:publish --tag="laratransaction-config"
php artisan vendor:publish --tag="laratransaction-translations"
```

This is the contents of the published config file:
## Usage

### Adding Transactions to Your Models

Add the `HasTransaction` trait to any model that needs transaction support:

```php
return [
];
use Err0r\Laratransaction\Traits\HasTransaction;

class Order extends Model
{
use HasTransaction;
}
```

Optionally, you can publish the views using
### Creating Transactions

```bash
php artisan vendor:publish --tag="laratransaction-views"
Use the fluent `TransactionBuilder` to create transactions:

```php
use Err0r\Laratransaction\Builders\TransactionBuilder;
use Err0r\Laratransaction\Enums\TransactionStatus;
use Err0r\Laratransaction\Enums\TransactionType;
use Err0r\Laratransaction\Enums\PaymentMethod;

// Create a transaction for an order
$order = Order::find(1);

$transaction = TransactionBuilder::create()
->transactionable($order)
->status(TransactionStatus::PENDING)
->type(TransactionType::PAYMENT)
->paymentMethod(PaymentMethod::CREDIT_CARD)
->amount(100.00, 'USD')
->gateway('stripe')
->gatewayTransactionId('ch_123456')
->metadata(['order_id' => 12345])
->build();

$transaction->save();
```

## Usage
### Querying Transactions

The package provides convenient scopes for filtering transactions:

```php
$laratransaction = new Err0r\Laratransaction();
echo $laratransaction->echoPhrase('Hello, Err0r!');
// Get all pending transactions
Transaction::pending()->get();

// Get completed transactions
Transaction::completed()->get();

// Get failed transactions
Transaction::failed()->get();

// Get cancelled transactions
Transaction::cancelled()->get();
```

### Checking Transaction Status

```php
$transaction->isPending(); // Check if pending
$transaction->isCompleted(); // Check if completed
$transaction->isFailed(); // Check if failed
$transaction->isCancelled(); // Check if cancelled
```

### Updating Transaction Status

```php
use Err0r\Laratransaction\Enums\TransactionStatus;

$transaction->setStatus(TransactionStatus::COMPLETED);
$transaction->save();
```

### Accessing Related Models

```php
// Get all transactions for a model
$order->transactions;

// Get the latest transaction
$order->latestTransaction;

// Access transaction details
$transaction->status; // TransactionStatus model
$transaction->type; // TransactionType model
$transaction->paymentMethod; // PaymentMethod model
```

## Resource Classes
The package provides several resource classes to transform your models into JSON representations:
- [`TransactionResource`](src/Resources/TransactionResource.php): Transforms a transaction model.
- [`TransactionStatusResource`](src/Resources/TransactionStatusResource.php): Transforms a transaction status model.
- [`TransactionTypeResource`](src/Resources/TransactionTypeResource.php): Transforms a transaction type model.
- [`PaymentMethodResource`](src/Resources/PaymentMethodResource.php): Transforms a payment

## Testing
> TODO
```bash
composer test
```

## Changelog
> TODO
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

## Contributing
> TODO
Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

## Security Vulnerabilities
> TODO
Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
"autoload": {
"psr-4": {
"Err0r\\Laratransaction\\": "src/",
"Err0r\\Laratransaction\\Database\\Factories\\": "database/factories/"
"Err0r\\Laratransaction\\Database\\Factories\\": "database/factories/",
"Err0r\\Laratransaction\\Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
Expand Down
25 changes: 20 additions & 5 deletions config/laratransaction.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
| Tables
|--------------------------------------------------------------------------
|
| Database table configuration for the subscription system. You can customize
| table names and UUID settings for each entity. Default names are provided
| but can be overridden using environment variables.
| Database table configuration. You can customize table names and
| UUID settings for each entity. Default names are provided but
| can be overridden using environment variables.
|
*/

Expand Down Expand Up @@ -39,8 +39,8 @@
| Models
|--------------------------------------------------------------------------
|
| Model class mappings for the subscription system. These classes handle
| the business logic for transaction_statuses, transactions, subscriptions, and related
| Model class mappings. These classes handle the business logic
| for transaction_statuses, transactions, subscriptions, and related
| entities. You can extend or replace these with your own implementations.
|
*/
Expand All @@ -51,4 +51,19 @@
'transaction_type' => \Err0r\Laratransaction\Models\TransactionType::class,
'payment_method' => \Err0r\Laratransaction\Models\PaymentMethod::class,
],

/*
|--------------------------------------------------------------------------
| Localization
|--------------------------------------------------------------------------
|
| Localization configuration. You can customize the active locales
| for the system. Default locales are provided but can be overridden
| using environment variables.
|
*/

'localization' => [
'active_locales' => explode(',', env('LARATRANSACTION_ACTIVE_LOCALES', 'ar,en')),
]
];
4 changes: 3 additions & 1 deletion database/seeders/DatabaseSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ class DatabaseSeeder extends Seeder
public function run(): void
{
$this->call([
// SubscriptionStatusSeeder::class,
TransactionStatusSeeder::class,
TransactionTypeSeeder::class,
PaymentMethodSeeder::class,
]);
}
}
34 changes: 34 additions & 0 deletions database/seeders/PaymentMethodSeeder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Err0r\Laratransaction\Database\Seeders;

use \Err0r\Laratransaction\Enums\PaymentMethod as PaymentMethodEnum;
use Err0r\Laratransaction\Models\PaymentMethod;
use Illuminate\Database\Seeder;

class PaymentMethodSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$records = collect(PaymentMethodEnum::cases())->map(fn ($status) => [
'slug' => $status->value,
])->toArray();

$locales = collect(config('laratransaction.localization.active_locales'));
foreach ($records as $key => $record) {
$records[$key]['name'] = $locales->mapWithKeys(fn ($locale) => [
$locale => __('laratransaction::transaction.payment_method.' . $record['slug'], locale: $locale)
])->toArray();
}

foreach ($records as $record) {
PaymentMethod::updateOrCreate(
['slug' => $record['slug']],
$record
);
}
}
}
34 changes: 34 additions & 0 deletions database/seeders/TransactionStatusSeeder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Err0r\Laratransaction\Database\Seeders;

use \Err0r\Laratransaction\Enums\TransactionStatus as TransactionStatusEnum;
use Err0r\Laratransaction\Models\TransactionStatus;
use Illuminate\Database\Seeder;

class TransactionStatusSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$records = collect(TransactionStatusEnum::cases())->map(fn ($status) => [
'slug' => $status->value,
])->toArray();

$locales = collect(config('laratransaction.localization.active_locales'));
foreach ($records as $key => $record) {
$records[$key]['name'] = $locales->mapWithKeys(fn ($locale) => [
$locale => __('laratransaction::transaction.status.' . $record['slug'], locale: $locale)
])->toArray();
}

foreach ($records as $record) {
TransactionStatus::updateOrCreate(
['slug' => $record['slug']],
$record
);
}
}
}
34 changes: 34 additions & 0 deletions database/seeders/TransactionTypeSeeder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Err0r\Laratransaction\Database\Seeders;

use \Err0r\Laratransaction\Enums\TransactionType as TransactionTypeEnum;
use Err0r\Laratransaction\Models\TransactionType;
use Illuminate\Database\Seeder;

class TransactionTypeSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$records = collect(TransactionTypeEnum::cases())->map(fn ($status) => [
'slug' => $status->value,
])->toArray();

$locales = collect(config('laratransaction.localization.active_locales'));
foreach ($records as $key => $record) {
$records[$key]['name'] = $locales->mapWithKeys(fn ($locale) => [
$locale => __('laratransaction::transaction.type.' . $record['slug'], locale: $locale)
])->toArray();
}

foreach ($records as $record) {
TransactionType::updateOrCreate(
['slug' => $record['slug']],
$record
);
}
}
}
20 changes: 20 additions & 0 deletions resources/lang/ar/transaction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

return [
'status' => [
'pending' => 'قيد الانتظار',
'completed' => 'تمت العملية',
'failed' => 'فشلت العملية',
'cancelled' => 'تم الإلغاء',
],
'type' => [
'payment' => 'دفع',
'refund' => 'استرداد',
],
'payment_method' => [
'credit_card' => 'بطاقة ائتمان',
'bank_transfer' => 'تحويل بنكي',
'cash' => 'نقدي',
'other' => 'آخر',
],
];
Loading

0 comments on commit f376bbd

Please sign in to comment.