First Commit

This commit is contained in:
marco
2026-09-01 10:46:29 -03:00
commit bf96b77e9c
10000 changed files with 3508600 additions and 0 deletions
@@ -0,0 +1,282 @@
<?php
namespace Modules\FluxoCaixaPro\Controllers;
use App\Controllers\BaseAdminController;
use Kernel\View;
use Symfony\Component\HttpFoundation\Request;
use Modules\FluxoCaixaPro\Models\Transaction;
use Modules\FluxoCaixaPro\Models\Category;
use Modules\FluxoCaixaPro\Models\CashFlowAnalysis;
use Modules\FluxoCaixaPro\Services\CashFlowService;
use Modules\FluxoCaixaPro\Services\CashFlowPredictionService;
use Carbon\Carbon;
/**
* Class CashFlowController
*
* Main controller for Cash Flow management and Dashboard.
*
* @package Modules\FluxoCaixaPro\Controllers
*/
class CashFlowController extends BaseAdminController
{
protected $cashFlowService;
protected $predictionService;
public function __construct(View $view, CashFlowService $cashFlowService, CashFlowPredictionService $predictionService)
{
parent::__construct($view);
$this->cashFlowService = $cashFlowService;
$this->predictionService = $predictionService;
}
/**
* checkPermission - Check if user has permission
*
* @param string $permission
* @return void
*/
protected function checkPermission(string $permission)
{
$user = $this->getCurrentUser();
if (!$user || !$user->hasPermission($permission)) {
$this->addFlash('error', 'Você não tem permissão para acessar esta área.');
$this->redirect('admin/dashboard')->send();
exit;
}
}
/**
* Display the Cash Flow Dashboard.
*/
public function index(Request $request)
{
$this->checkPermission('fluxocaixapro.view');
$startDate = $request->query->get('start_date', Carbon::now()->startOfMonth()->toDateString());
$endDate = $request->query->get('end_date', Carbon::now()->endOfMonth()->toDateString());
$statusFilter = $request->query->get('status');
$typeFilter = $request->query->get('type');
$entityFilter = $request->query->get('entity');
$summary = $this->cashFlowService->getSummary($startDate, $endDate);
$monthlyBreakdown = $this->cashFlowService->getMonthlyBreakdown();
$categoryDistribution = $this->cashFlowService->getCategoryDistribution('expense');
$projections = $this->cashFlowService->getProjections();
$latestAnalysis = CashFlowAnalysis::orderBy('created_at', 'desc')->first();
$query = Transaction::with('category');
// The global scope 'company' already handles idbus filtering
if ($startDate) {
$query->where('transaction_date', '>=', $startDate);
}
if ($endDate) {
$query->where('transaction_date', '<=', $endDate);
}
if ($statusFilter) {
$query->where('status', $statusFilter);
}
if ($typeFilter) {
$query->where('type', $typeFilter);
}
if ($entityFilter !== null && $entityFilter !== '') {
$query->where('is_personal', $entityFilter == 'personal');
}
$latestTransactions = $query->orderBy('transaction_date', 'desc')
->limit(50)
->get();
$categoriesAll = Category::where('is_active', true)->orderBy('name')->get();
return $this->renderAdminView('@fluxocaixapro/admin/index.twig', [
'title' => 'Dashboard Fluxo de Caixa Pró',
'summary' => $summary,
'monthlyBreakdown' => json_encode($monthlyBreakdown),
'categoryDistribution' => json_encode($categoryDistribution),
'projections' => json_encode($projections),
'latestAnalysis' => $latestAnalysis,
'latestTransactions' => $latestTransactions,
'categories_all' => $categoriesAll,
'startDate' => $startDate,
'endDate' => $endDate,
'filters' => [
'status' => $statusFilter,
'type' => $typeFilter,
'entity' => $entityFilter
]
]);
}
/**
* storeTransaction - Store a new transaction
*
* @return Response
*/
public function storeTransaction(Request $request)
{
$this->checkPermission('fluxocaixapro.manage');
$data = $request->request->all();
// idbus and iduser are handled by Transaction::booted() static::creating
Transaction::create([
'category_id' => $data['category_id'],
'description' => $data['description'],
'amount' => str_replace(',', '.', $data['amount']),
'type' => $data['type'],
'status' => $data['status'] ?? 'pending',
'transaction_date' => $data['transaction_date'] ?? date('Y-m-d'),
'due_date' => !empty($data['due_date']) ? $data['due_date'] : null,
'is_personal' => isset($data['is_personal']) && $data['is_personal'] == '1',
'notes' => $data['notes'] ?? null
]);
$this->addFlash('success', 'Transação registrada com sucesso!');
return $this->redirect('/admin/fluxo-caixa');
}
/**
* Update an existing transaction.
*/
public function updateTransaction(Request $request, $id)
{
$this->checkPermission('fluxocaixapro.manage');
$transaction = Transaction::findOrFail($id);
$data = $request->request->all();
$transaction->update([
'category_id' => $data['category_id'],
'description' => $data['description'],
'amount' => str_replace(',', '.', $data['amount']),
'transaction_date' => $data['transaction_date'],
'due_date' => !empty($data['due_date']) ? $data['due_date'] : null,
'payment_date' => ($data['status'] === 'paid') ? (!empty($data['payment_date']) ? $data['payment_date'] : $data['transaction_date']) : null,
'type' => $data['type'],
'status' => $data['status'] ?? 'paid',
'is_personal' => isset($data['is_personal']) && $data['is_personal'] == '1',
'notes' => $data['notes'] ?? null
]);
$this->addFlash('success', 'Transação atualizada com sucesso!');
return $this->redirect('/admin/fluxo-caixa');
}
/**
* Delete a transaction.
*/
public function deleteTransaction(Request $request, $id)
{
$this->checkPermission('fluxocaixapro.manage');
$transaction = Transaction::findOrFail($id);
$transaction->delete();
$this->addFlash('success', 'Transação excluída com sucesso!');
return $this->redirect('/admin/fluxo-caixa');
}
/**
* Mark a transaction as paid.
*/
public function markAsPaid(Request $request, $id)
{
$this->checkPermission('fluxocaixapro.manage');
$transaction = Transaction::findOrFail($id);
$transaction->update([
'status' => 'paid',
'payment_date' => Carbon::now()->toDateString()
]);
$this->addFlash('success', 'Transação marcada como paga!');
return $this->redirect('/admin/fluxo-caixa');
}
/**
* Export cash flow to Excel.
*/
public function exportToExcel(Request $request)
{
$this->checkPermission('fluxocaixapro.manage');
$transactions = Transaction::with('category')->orderBy('transaction_date', 'desc')->get();
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Fluxo de Caixa');
// Header
$headers = ['Data', 'Vencimento', 'Pagamento', 'Descrição', 'Categoria', 'Valor', 'Tipo', 'Status', 'Empresa/Pessoal'];
foreach ($headers as $col => $text) {
$sheet->setCellValue([$col + 1, 1], $text);
}
// Data
$row = 2;
foreach ($transactions as $t) {
$sheet->setCellValue([1, $row], $t->transaction_date ? $t->transaction_date->format('d/m/Y') : '');
$sheet->setCellValue([2, $row], $t->due_date ? $t->due_date->format('d/m/Y') : '');
$sheet->setCellValue([3, $row], $t->payment_date ? $t->payment_date->format('d/m/Y') : '');
$sheet->setCellValue([4, $row], $t->description);
$sheet->setCellValue([5, $row], $t->category->name ?? 'N/A');
$sheet->setCellValue([6, $row], $t->amount);
$sheet->setCellValue([7, $row], $t->type === 'income' ? 'Entrada' : 'Saída');
$sheet->setCellValue([8, $row], $t->status === 'paid' ? 'Pago' : 'Pendente');
$sheet->setCellValue([9, $row], $t->is_personal ? 'Pessoal' : 'Empresa');
$row++;
}
// Style header
$sheet->getStyle('A1:I1')->getFont()->setBold(true);
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$filename = 'fluxo_caixa_' . date('Y-m-d') . '.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$writer->save('php://output');
exit;
}
/**
* Run a new AI analysis.
*/
public function runAnalysis(Request $request)
{
$this->checkPermission('fluxocaixapro.manage');
try {
$this->predictionService->generateAnalysis();
$this->addFlash('success', 'Análise inteligente concluída com sucesso!');
} catch (\Exception $e) {
$this->addFlash('error', 'Erro ao gerar análise: ' . $e->getMessage());
}
return $this->redirect('/admin/fluxo-caixa');
}
/**
* Perform bank reconciliation.
*/
public function reconcile(Request $request)
{
$this->checkPermission('fluxocaixapro.manage');
$bankBalance = (float) $request->request->get('bank_balance', 0);
$summary = $this->cashFlowService->getSummary();
$systemBalance = $summary['net_balance'];
$difference = $bankBalance - $systemBalance;
return $this->renderAdminView('@fluxocaixapro/admin/reconciliation_result.twig', [
'title' => 'Resultado da Conciliação Bancária',
'bankBalance' => $bankBalance,
'systemBalance' => $systemBalance,
'difference' => $difference,
'summary' => $summary
]);
}
}
@@ -0,0 +1,106 @@
<?php
namespace Modules\FluxoCaixaPro\Controllers;
use App\Controllers\BaseAdminController;
use Symfony\Component\HttpFoundation\Request;
use Modules\FluxoCaixaPro\Models\Category;
/**
* Class CategoryController
*
* Manages financial categories.
*
* @package Modules\FluxoCaixaPro\Controllers
*/
class CategoryController extends BaseAdminController
{
/**
* checkPermission - Check if user has permission
*
* @param string $permission
* @return void
*/
protected function checkPermission(string $permission)
{
$user = $this->getCurrentUser();
if (!$user || !$user->hasPermission($permission)) {
$this->addFlash('error', 'Você não tem permissão para acessar esta área.');
$this->redirect('admin/dashboard')->send();
exit;
}
}
/**
* List all categories.
*/
public function index(Request $request)
{
$this->checkPermission('fluxocaixapro.view');
$categories = Category::orderBy('name')->get();
return $this->renderAdminView('@fluxocaixapro/admin/categories/index.twig', [
'title' => 'Categorias de Fluxo de Caixa',
'categories' => $categories
]);
}
/**
* Store a new category.
*/
public function store(Request $request)
{
$this->checkPermission('fluxocaixapro.manage');
$data = $request->request->all();
Category::create([
'name' => $data['name'],
'type' => $data['type'],
'color' => $data['color'] ?? '#6c757d',
'icon' => $data['icon'] ?? 'bi bi-tag',
'is_active' => true
]);
$this->addFlash('success', 'Categoria criada com sucesso!');
return $this->redirect('/admin/fluxo-caixa/categories');
}
/**
* Update an existing category.
*/
public function update(Request $request, $id)
{
$this->checkPermission('fluxocaixapro.manage');
$category = Category::findOrFail($id);
$data = $request->request->all();
$category->update([
'name' => $data['name'],
'type' => $data['type'],
'color' => $data['color'],
'icon' => $data['icon']
]);
$this->addFlash('success', 'Categoria atualizada com sucesso!');
return $this->redirect('/admin/fluxo-caixa/categories');
}
/**
* Toggle category status.
*/
public function delete(Request $request, $id)
{
$this->checkPermission('fluxocaixapro.manage');
$category = Category::findOrFail($id);
$category->is_active = !$category->is_active;
$category->save();
$status = $category->is_active ? 'ativada' : 'desativada';
$this->addFlash('success', "Categoria {$status} com sucesso!");
return $this->redirect('/admin/fluxo-caixa/categories');
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace Modules\FluxoCaixaPro\Models;
use Illuminate\Database\Eloquent\Model;
/**
* Class CashFlowAnalysis
*
* Represents an AI-generated cash flow analysis in the Fluxo de Caixa Pró module.
*
* @package Modules\FluxoCaixaPro\Models
*/
class CashFlowAnalysis extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'cash_flow_analysis';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'idbus',
'iduser',
'analysis_date',
'summary_data',
'recommendations',
'projections'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'idbus' => 'integer',
'iduser' => 'integer',
'analysis_date' => 'date',
'summary_data' => 'array',
'projections' => 'array'
];
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope('company', function ($query) {
if (isset($_SESSION['user_idbus']) && $_SESSION['user_idbus'] !== null && (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'super_admin')) {
$query->where('idbus', $_SESSION['user_idbus']);
}
});
static::creating(function ($model) {
if (isset($_SESSION['user_idbus'])) {
$model->idbus = $_SESSION['user_idbus'];
}
if (isset($_SESSION['user_id'])) {
$model->iduser = $_SESSION['user_id'];
}
});
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
/**
* SysCMS - Content Management System
*
* Copyright (c) 2026 SysCMS Team
* All rights reserved.
*
* Author: SysCMS Team
* Project: SysCMS
*/
namespace Modules\FluxoCaixaPro\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Category - Model for cash flow categories
*
* @package Modules\FluxoCaixaPro\Models
*/
class Category extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'cash_flow_categories';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'idbus',
'iduser',
'name',
'type',
'color',
'icon',
'is_active'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'idbus' => 'integer',
'iduser' => 'integer',
'is_active' => 'boolean',
'created_at' => 'datetime',
'updated_at' => 'datetime'
];
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope('company', function ($query) {
if (isset($_SESSION['user_idbus']) && $_SESSION['user_idbus'] !== null && (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'super_admin')) {
$query->where('idbus', $_SESSION['user_idbus']);
}
});
static::creating(function ($model) {
if (isset($_SESSION['user_idbus'])) {
$model->idbus = $_SESSION['user_idbus'];
}
if (isset($_SESSION['user_id'])) {
$model->iduser = $_SESSION['user_id'];
}
});
}
/**
* transactions - Get transactions for this category
*
* @return HasMany
*/
public function transactions(): HasMany
{
return $this->hasMany(Transaction::class, 'category_id');
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace Modules\FluxoCaixaPro\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Class Transaction
*
* Represents a financial transaction in the Fluxo de Caixa Pró module.
*
* @package Modules\FluxoCaixaPro\Models
*/
class Transaction extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'cash_flow_transactions';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'idbus',
'iduser',
'category_id',
'description',
'amount',
'transaction_date',
'due_date',
'payment_date',
'type',
'status',
'is_personal',
'notes',
'metadata'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'idbus' => 'integer',
'iduser' => 'integer',
'amount' => 'decimal:2',
'transaction_date' => 'date',
'due_date' => 'date',
'payment_date' => 'date',
'is_personal' => 'boolean',
'metadata' => 'array',
'created_at' => 'datetime',
'updated_at' => 'datetime'
];
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope('company', function ($query) {
if (isset($_SESSION['user_idbus']) && $_SESSION['user_idbus'] !== null && (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'super_admin')) {
$query->where('idbus', $_SESSION['user_idbus']);
}
});
static::creating(function ($model) {
if (isset($_SESSION['user_idbus'])) {
$model->idbus = $_SESSION['user_idbus'];
}
if (isset($_SESSION['user_id'])) {
$model->iduser = $_SESSION['user_id'];
}
});
}
/**
* Get the category that owns the transaction.
*
* @return BelongsTo
*/
public function category(): BelongsTo
{
return $this->belongsTo(Category::class, 'category_id');
}
}
@@ -0,0 +1,37 @@
<?php
/**
* SysCMS - Content Management System
*
* Copyright (c) 2026 SysCMS Team
* All rights reserved.
*
* Author: SysCMS Team
* Project: SysCMS
*/
namespace Modules\FluxoCaixaPro\Providers;
/**
* FluxoCaixaProServiceProvider - Service Provider for the FluxoCaixaPro module
*/
class FluxoCaixaProServiceProvider
{
/**
* register - Register module services in the container
*
* @return void
*/
public function register()
{
}
/**
* boot - Boot module resources
*
* @return void
*/
public function boot()
{
}
}
@@ -0,0 +1,180 @@
<?php
namespace Modules\FluxoCaixaPro\Services;
use Modules\FluxoCaixaPro\Models\Transaction;
use Modules\FluxoCaixaPro\Models\CashFlowAnalysis;
use Carbon\Carbon;
/**
* Class CashFlowPredictionService
*
* Handles intelligent predictions and analysis for cash flow.
*
* @package Modules\FluxoCaixaPro\Services
*/
class CashFlowPredictionService
{
/**
* Generate a new cash flow analysis based on historical data.
*
* @return CashFlowAnalysis
*/
public function generateAnalysis(): CashFlowAnalysis
{
$lastSixMonths = Carbon::now()->subMonths(6);
// Use only business transactions for core metrics
$transactions = Transaction::where('transaction_date', '>=', $lastSixMonths)
->where('is_personal', false)
->get();
$count = $transactions->count();
$monthlyAvgIncome = $count > 0 ? ($transactions->where('type', 'income')->sum('amount') / 6) : 0;
$monthlyAvgExpense = $count > 0 ? ($transactions->where('type', 'expense')->sum('amount') / 6) : 0;
$predictedBalance = $monthlyAvgIncome - $monthlyAvgExpense;
// Pending items analysis
$pendingIncome = Transaction::where('type', 'income')->where('status', 'pending')->sum('amount');
$pendingExpense = Transaction::where('type', 'expense')->where('status', 'pending')->sum('amount');
// Personal mix analysis
$personalExpense = Transaction::where('is_personal', true)
->where('transaction_date', '>=', $lastSixMonths)
->sum('amount');
$recommendations = $this->generateDetailedRecommendations([
'income' => $monthlyAvgIncome,
'expense' => $monthlyAvgExpense,
'pending_income' => $pendingIncome,
'pending_expense' => $pendingExpense,
'personal_expense' => $personalExpense,
'balance' => $predictedBalance
]);
return CashFlowAnalysis::create([
'analysis_date' => Carbon::now(),
'summary_data' => [
'period_analyzed' => $lastSixMonths->format('Y-m') . ' to ' . Carbon::now()->format('Y-m'),
'predicted_balance' => $predictedBalance,
'avg_monthly_income' => $monthlyAvgIncome,
'avg_monthly_expense' => $monthlyAvgExpense,
'growth_rate' => $this->calculateGrowthRate(),
'risk_level' => $this->calculateRiskLevel($predictedBalance, $pendingExpense, $pendingIncome),
'personal_mix_ratio' => $monthlyAvgExpense > 0 ? ($personalExpense / ($monthlyAvgExpense * 6)) : 0
],
'recommendations' => $recommendations,
'projections' => $this->getProjections()
]);
}
/**
* Generate detailed recommendations based on financial management principles.
*/
private function generateDetailedRecommendations(array $data): string
{
$rec = [];
// 1. Separation of accounts (Core management principle)
if ($data['personal_expense'] > 0) {
$rec[] = "⚠️ SEPARAÇÃO DE CONTAS: Identificamos gastos pessoais misturados aos da empresa. Recomenda-se que o empresário tenha um 'Pró-labore' fixo e nunca use o caixa da empresa para despesas pessoais.";
}
// 2. Operational Health
if ($data['balance'] < 0) {
$rec[] = "🔴 DÉFICIT OPERACIONAL: Suas despesas empresariais superam as receitas. Revise seus custos fixos e tente aumentar o volume de vendas ou reajustar preços.";
} elseif ($data['balance'] < ($data['income'] * 0.15)) {
$rec[] = "🟡 MARGEM ESTREITA: Seu saldo operacional está muito próximo de zero. Qualquer imprevisto pode gerar necessidade de capital de giro externo (empréstimos).";
}
// 3. Accounts Payable vs Receivable
if ($data['pending_expense'] > $data['pending_income']) {
$gap = $data['pending_expense'] - $data['pending_income'];
$rec[] = "📉 GAP DE CAIXA: Você tem R$ " . number_format($gap, 2, ',', '.') . " a mais em contas a pagar do que a receber nos próximos períodos. Antecipe recebíveis ou renegocie prazos com fornecedores.";
}
// 4. Working Capital Reserve
$reserveNeeded = $data['expense'] * 3; // 3 months of reserve
$rec[] = "🏦 RESERVA DE EMERGÊNCIA: Recomenda-se manter uma reserva de 3 a 6 meses de despesas. Sua meta de reserva deve ser de aproximadamente R$ " . number_format($reserveNeeded, 2, ',', '.') . ".";
if (empty($rec)) {
$rec[] = "✅ SAÚDE FINANCEIRA: Seu fluxo de caixa está equilibrado. Continue registrando todas as movimentações diariamente para manter a precisão das projeções.";
}
return implode("\n\n", $rec);
}
/**
* Calculate risk level.
*/
private function calculateRiskLevel(float $balance, float $pendingExp, float $pendingInc): string
{
if ($balance < 0 || ($pendingExp > $pendingInc * 1.5)) {
return 'High';
}
if ($balance < 500 || $pendingExp > $pendingInc) {
return 'Medium';
}
return 'Low';
}
/**
* Calculate growth rate based on last two months.
*
* @return float
*/
/**
* Calculate growth rate based on last two months.
*
* @return float
*/
private function calculateGrowthRate(): float
{
$currentMonth = Carbon::now()->startOfMonth();
$lastMonth = Carbon::now()->subMonth()->startOfMonth();
$currentIncome = Transaction::where('type', 'income')
->whereBetween('transaction_date', [$currentMonth, Carbon::now()])
->sum('amount');
$lastMonthIncome = Transaction::where('type', 'income')
->whereBetween('transaction_date', [$lastMonth, $currentMonth->subDay()])
->sum('amount');
if ($lastMonthIncome == 0) {
return 0;
}
return (($currentIncome - $lastMonthIncome) / $lastMonthIncome) * 100;
}
/**
* getProjections - Generate basic future projections for the analysis
*
* @return array
*/
private function getProjections(): array
{
$lastSixMonths = Carbon::now()->subMonths(6);
$transactions = Transaction::where('transaction_date', '>=', $lastSixMonths)
->where('is_personal', false)
->get();
$monthlyAvgIncome = $transactions->where('type', 'income')->sum('amount') / 6;
$monthlyAvgExpense = $transactions->where('type', 'expense')->sum('amount') / 6;
$projections = [];
for ($i = 1; $i <= 3; $i++) {
$month = Carbon::now()->addMonths($i)->format('Y-m');
$projections[] = [
'month' => $month,
'predicted_income' => round($monthlyAvgIncome, 2),
'predicted_expense' => round($monthlyAvgExpense, 2),
'predicted_balance' => round($monthlyAvgIncome - $monthlyAvgExpense, 2)
];
}
return $projections;
}
}
+178
View File
@@ -0,0 +1,178 @@
<?php
namespace Modules\FluxoCaixaPro\Services;
use Modules\FluxoCaixaPro\Models\Transaction;
use Modules\FluxoCaixaPro\Models\Category;
use Illuminate\Database\Capsule\Manager as DB;
use Carbon\Carbon;
/**
* Class CashFlowService
*
* Handles business logic for cash flow management.
*
* @package Modules\FluxoCaixaPro\Services
*/
class CashFlowService
{
/**
* Get summary of cash flow for a specific period.
*
* @param string|null $startDate
* @param string|null $endDate
* @return array
*/
public function getSummary(?string $startDate = null, ?string $endDate = null): array
{
$query = Transaction::query();
if ($startDate) {
$query->where('transaction_date', '>=', $startDate);
}
if ($endDate) {
$query->where('transaction_date', '<=', $endDate);
}
$transactions = $query->get();
// Total amounts (including personal)
$totalIncome = $transactions->where('type', 'income')->sum('amount');
$totalExpense = $transactions->where('type', 'expense')->sum('amount');
$netBalance = $totalIncome - $totalExpense;
// Operational amounts (Business only)
$businessTransactions = $transactions->where('is_personal', false);
$opIncome = $businessTransactions->where('type', 'income')->sum('amount');
$opExpense = $businessTransactions->where('type', 'expense')->sum('amount');
$opBalance = $opIncome - $opExpense;
// Personal amounts
$personalTransactions = $transactions->where('is_personal', true);
$personalIncome = $personalTransactions->where('type', 'income')->sum('amount');
$personalExpense = $personalTransactions->where('type', 'expense')->sum('amount');
// Accounts Payable/Receivable
$pendingIncome = Transaction::where('type', 'income')->where('status', 'pending')->sum('amount');
$pendingExpense = Transaction::where('type', 'expense')->where('status', 'pending')->sum('amount');
return [
'total_income' => $totalIncome,
'total_expense' => $totalExpense,
'net_balance' => $netBalance,
'operational_income' => $opIncome,
'operational_expense' => $opExpense,
'operational_balance' => $opBalance,
'personal_income' => $personalIncome,
'personal_expense' => $personalExpense,
'pending_income' => $pendingIncome,
'pending_expense' => $pendingExpense,
'transaction_count' => $transactions->count()
];
}
/**
* Get monthly breakdown of cash flow.
*
* @param int $months
* @return array
*/
public function getMonthlyBreakdown(int $months = 6): array
{
$startDate = Carbon::now()->subMonths($months)->startOfMonth();
$data = Transaction::where('transaction_date', '>=', $startDate)
->select(
\Illuminate\Database\Capsule\Manager::raw('DATE_FORMAT(transaction_date, "%Y-%m") as month'),
\Illuminate\Database\Capsule\Manager::raw('SUM(CASE WHEN type = "income" THEN amount ELSE 0 END) as income'),
\Illuminate\Database\Capsule\Manager::raw('SUM(CASE WHEN type = "expense" THEN amount ELSE 0 END) as expense')
)
->groupBy('month')
->orderBy('month', 'asc')
->get();
return $data->toArray();
}
/**
* Get distribution by category.
*
* @param string $type 'income' or 'expense'
* @return array
*/
public function getCategoryDistribution(string $type = 'expense'): array
{
return Transaction::where('type', $type)
->with('category')
->select('category_id', \Illuminate\Database\Capsule\Manager::raw('SUM(amount) as total'))
->groupBy('category_id')
->get()
->map(function ($item) {
return [
'category' => $item->category->name ?? 'Sem Categoria',
'total' => $item->total,
'color' => $item->category->color ?? '#6c757d'
];
})
->toArray();
}
/**
* Get long term projections with scenarios.
*
* @param int $months
* @return array
*/
public function getProjections(int $months = 12): array
{
$startDate = Carbon::now()->subMonths(12);
$history = Transaction::where('transaction_date', '>=', $startDate)
->where('is_personal', false)
->get();
if ($history->isEmpty()) {
return [];
}
$avgMonthlyIncome = $history->where('type', 'income')->sum('amount') / 12;
$avgMonthlyExpense = $history->where('type', 'expense')->sum('amount') / 12;
$projections = [];
for ($i = 1; $i <= $months; $i++) {
$month = Carbon::now()->addMonths($i)->format('Y-m');
// Realistic Scenario (Current average + slight growth)
$realisticIncome = $avgMonthlyIncome * (1 + ($i * 0.01));
$realisticExpense = $avgMonthlyExpense * (1 + ($i * 0.005));
// Optimistic Scenario (+5% income, -2% expense vs realistic)
$optimisticIncome = $realisticIncome * 1.05;
$optimisticExpense = $realisticExpense * 0.98;
// Pessimistic Scenario (-10% income, +5% expense vs realistic)
$pessimisticIncome = $realisticIncome * 0.90;
$pessimisticExpense = $realisticExpense * 1.05;
$projections[] = [
'month' => $month,
'realistic' => [
'income' => $realisticIncome,
'expense' => $realisticExpense,
'balance' => $realisticIncome - $realisticExpense
],
'optimistic' => [
'income' => $optimisticIncome,
'expense' => $optimisticExpense,
'balance' => $optimisticIncome - $optimisticExpense
],
'pessimistic' => [
'income' => $pessimisticIncome,
'expense' => $pessimisticExpense,
'balance' => $pessimisticIncome - $pessimisticExpense
]
];
}
return $projections;
}
}