validate([ 'question' => 'required|string|max:500', 'period_start' => 'nullable', 'period_end' => 'nullable', ]); $user = $request->user(); $role = $user?->role ?? 'guest'; $question = $request->question; $periodStart = $request->period_start; $periodEnd = $request->period_end; $dates = $this->dateRangeService->getDateRangeForUser($user, $periodStart, $periodEnd, false); $cacheKey = 'ai_stats_' . md5("{$role}|{$periodStart}|{$periodEnd}|{$question}"); $cached = Cache::get($cacheKey); if ($cached) { return response()->json([ 'success' => true, 'from_cache' => true, 'answer' => $cached['answer'], 'structured' => $cached['structured'] ?? null, ]); } try { $result = $this->dispatcher->dispatch( question: "Период с {$dates[0]} по {$dates[1]}. Вопрос: {$question}", role: $role ); // Cache::put($cacheKey, [ // 'answer' => $result['answer'], // 'structured' => $result['structured'] ?? null, // ], now()->addMinutes(10)); return response()->json([ 'success' => true, 'from_cache' => false, 'answer' => $result['answer'], 'structured' => $result['structured'] ?? null, ]); } catch (\Exception $e) { Log::error('AI Dispatch Error: ' . $e->getMessage(), [ 'user' => $user?->id, 'question' => $question, 'period' => "$periodStart - $periodEnd", ]); return response()->json([ 'success' => false, 'message' => 'Не удалось обработать запрос. Попробуйте позже.', ], 500); } } }