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,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;
}
}