181 lines
7.0 KiB
PHP
Executable File
181 lines
7.0 KiB
PHP
Executable File
<?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;
|
|
}
|
|
}
|