Now that we’re storing forecast data, let’s make it smarter by identifying sales trends and anomalies like unusual spikes or dips — and annotate charts using GPT-generated insights.
🧠 Step 1: Add GPT summary helper
Create app/Helpers/ForecastInsightHelper.php
:
namespace App\Helpers;
use App\Models\ForecastResult;
use OpenAI\Laravel\Facades\OpenAI;
class ForecastInsightHelper
{
public static function generateInsights(): string
{
$forecast = ForecastResult::orderBy('forecast_date')->get();
$text = $forecast->map(fn($f) =>
"{$f->forecast_date}: {$f->yhat}"
)->implode("\n");
$prompt = <<<PROMPT
You are a business analyst. Analyze this 30-day sales forecast and summarize:
- General trend (rising, falling, flat)
- Notable anomalies (spikes or drops)
- Recommendation if any
Forecast Data:
$text
Summary:
PROMPT;
$response = OpenAI::chat()->create([
'model' => 'gpt-4o',
'messages' => [['role' => 'user', 'content' => $prompt]],
'max_tokens' => 300,
]);
return $response->choices[0]->message->content ?? 'No summary generated.';
}
}
📡 Step 2: Add controller method to call GPT
In SalesController.php
:
use App\Helpers\ForecastInsightHelper;
public function generateInsights()
{
$insight = ForecastInsightHelper::generateInsights();
return back()->with('forecast_insight', $insight);
}
Route:
Route::post('/forecast/insights', [SalesController::class, 'generateInsights'])->name('forecast.insights');
📋 Step 3: Add insight button in Blade
In resources/views/sales/index.blade.php
:
<form method="POST" action="{{ route('forecast.insights') }}">
@csrf
<button class="bg-orange-500 text-white px-4 py-2 rounded">Generate AI Insight</button>
</form>
@if(session('forecast_insight'))
<div class="bg-orange-100 text-orange-900 p-3 rounded mt-4 whitespace-pre-wrap">
<strong>Forecast Insight:</strong><br>
{!! nl2br(e(session('forecast_insight'))) !!}
</div>
@endif
💡 Example Output
Forecast Insight:
Sales are gradually increasing over the 30-day period, indicating a positive trend.
Anomaly detected: spike around 15th June.
Recommendation: prepare for inventory demand surge in mid-month.
✅ Up next (Day 8): we’ll build a dashboard to compare past vs. predicted performance, and visualize deviation with confidence bands.