Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Finances Laravel Package

baks-dev/finances

BaksDev Finances — PHP 8.4+ модуль для Laravel/Symfony проектов: установка через Composer, установка конфигураций и ресурсов (baks:assets:install), поддержка миграций Doctrine и тестов PHPUnit (group=finances).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require baks-dev/finances
    

    Ensure your project uses PHP 8.4+ and Laravel 10+ (or a compatible Symfony-based setup).

  2. Publish Assets and Config Run the package’s installation command to set up default configurations and assets:

    php artisan baks:assets:install
    

    This typically generates:

    • Configuration files (e.g., config/finances.php)
    • Migration files (if not already present)
    • Optional asset files (e.g., Blade views, JavaScript/CSS)
  3. Run Migrations Generate and apply database migrations to create the required tables:

    php artisan doctrine:migrations:diff
    php artisan doctrine:migrations:migrate
    

    Note: If using Laravel’s native migrations, ensure the package’s migrations are merged into your existing migration files.

  4. First Use Case: Create a Financial Transaction Use the package’s models to create a basic transaction. For example:

    use BaksDev\Finances\Models\Transaction;
    
    $transaction = Transaction::create([
        'amount' => 100.00,
        'currency' => 'USD',
        'type' => 'income', // or 'expense', 'fee', etc.
        'description' => 'Monthly subscription revenue',
        'account_id' => 1, // Reference to an Account model
    ]);
    

    Verify the transaction appears in the database and can be retrieved via Eloquent:

    $transactions = Transaction::all();
    
  5. Verify with Tests Run the package’s test suite to ensure core functionality works:

    php artisan test --group=finances
    

Implementation Patterns

Core Workflows

1. Transaction Processing

  • Pattern: Use the Transaction model to handle financial movements between accounts.
  • Example Workflow:
    1. Create a Transaction:
      $transaction = Transaction::create([
          'amount' => 50.00,
          'currency' => 'EUR',
          'type' => 'expense',
          'account_id' => $sourceAccount->id,
          'related_account_id' => $destinationAccount->id,
          'metadata' => ['invoice_id' => 'INV-123'],
      ]);
      
    2. Validate Transactions: Use built-in validation rules (e.g., Transaction::validate()) or extend with custom rules:
      $validator = Validator::make($data, [
          'amount' => 'required|numeric|min:0',
          'type' => 'required|in:income,expense,fee,refund',
      ]);
      
    3. Process in Batches: For bulk operations (e.g., payouts), use Laravel’s queue system:
      Transaction::where('status', 'pending')->chunk(100, function ($transactions) {
          foreach ($transactions as $transaction) {
              // Process and update transaction status
              $transaction->update(['status' => 'completed']);
          }
      });
      

2. Account Management

  • Pattern: Manage financial accounts (e.g., bank accounts, ledgers) using the Account model.
  • Example:
    use BaksDev\Finances\Models\Account;
    
    $account = Account::create([
        'name' => 'Customer Deposits',
        'type' => 'asset', // or 'liability', 'equity', 'revenue', 'expense'
        'currency' => 'USD',
        'balance' => 0.00,
    ]);
    
  • Multi-Currency Support: If the package supports multiple currencies, use the currency field and handle conversions via a service:
    $convertedAmount = app(\BaksDev\Finances\Services\CurrencyConverter::class)
        ->convert($amount, 'USD', 'EUR');
    

3. Ledger and Reporting

  • Pattern: Generate financial reports (e.g., profit/loss, balance sheets) using the Ledger or Report models.
  • Example:
    use BaksDev\Finances\Reports\ProfitLossReport;
    
    $report = new ProfitLossReport();
    $data = $report->generate(
        startDate: now()->startOfMonth(),
        endDate: now()->endOfMonth()
    );
    
  • Custom Reports: Extend the base report classes or create new ones by implementing the ReportInterface:
    namespace App\Reports;
    
    use BaksDev\Finances\Contracts\ReportInterface;
    
    class CustomReport implements ReportInterface {
        public function generate($startDate, $endDate) {
            // Custom logic
            return $data;
        }
    }
    

4. Integration with Payment Gateways

  • Pattern: Use the package to store financial data while delegating payment processing to external gateways (e.g., Stripe, PayPal).
  • Example Workflow:
    1. Capture Payment:
      $paymentIntent = \Stripe\PaymentIntent::create([
          'amount' => $transaction->amount * 100, // in cents
          'currency' => $transaction->currency,
          'metadata' => ['transaction_id' => $transaction->id],
      ]);
      
    2. Log Transaction:
      $transaction->update([
          'status' => 'paid',
          'payment_id' => $paymentIntent->id,
          'payment_gateway' => 'stripe',
      ]);
      

Laravel-Specific Patterns

1. Service Providers and Bindings

  • The package likely registers services in its FinancesServiceProvider. Override or extend bindings in your AppServiceProvider:
    public function register()
    {
        $this->app->bind(
            \BaksDev\Finances\Contracts\TransactionProcessor::class,
            \App\Services\CustomTransactionProcessor::class
        );
    }
    

2. Artisan Commands

  • Extend or create custom commands using the package’s base commands:
    use BaksDev\Finances\Console\Commands\BaseCommand;
    
    class ReconcileAccountsCommand extends BaseCommand {
        protected $signature = 'finances:reconcile {account}';
        protected $description = 'Reconcile transactions for a specific account';
    
        public function handle()
        {
            // Custom reconciliation logic
        }
    }
    
  • Register the command in app/Console/Kernel.php:
    protected $commands = [
        \App\Console\Commands\ReconcileAccountsCommand::class,
    ];
    

3. Events and Listeners

  • Listen to package events (e.g., TransactionCreated, AccountBalanceUpdated) to trigger side effects:
    use BaksDev\Finances\Events\TransactionCreated;
    
    Event::listen(TransactionCreated::class, function ($event) {
        // Send notification, log audit trail, etc.
        Log::info('New transaction created', $event->transaction->toArray());
    });
    

4. API Resources

  • Transform package models into API responses using Laravel’s ApiResource:
    namespace App\Http\Resources;
    
    use BaksDev\Finances\Models\Transaction;
    use Illuminate\Http\Resources\Json\JsonResource;
    
    class TransactionResource extends JsonResource {
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'amount' => $this->amount,
                'currency' => $this->currency,
                'type' => $this->type,
                'metadata' => $this->metadata,
                'created_at' => $this->created_at->toIso8601String(),
            ];
        }
    }
    
  • Use in controllers:
    public function index()
    {
        return TransactionResource::collection(Transaction::all());
    }
    

5. Policy and Authorization

  • Assign policies to package models to control access:
    use BaksDev\Finances\Models\Transaction;
    use Illuminate\Auth\Access\HandlesAuthorization;
    
    class TransactionPolicy {
        use HandlesAuthorization;
    
        public function viewAny(User $user)
        {
            return $user->hasRole('accountant');
        }
    
        public function create(User $user)
        {
            return $user->hasRole(['admin', 'finance']);
        }
    }
    
  • Register the policy in AuthServiceProvider:
    protected $policies = [
        Transaction::class => TransactionPolicy::class,
    ];
    

Gotchas and Tips

Common Pitfalls

1. Migration Conflicts

  • Issue: Running the package’s migrations may conflict with existing financial tables in your database.
  • Solution:
    • Review the package’s migration files (database/migrations/) before running them.
    • Manually merge or modify migrations if tables/columns overlap.
    • Use
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky