File manager - Edit - /home/autoph/public_html/projects/aha-api/app/Http/Controllers/API/chatbot/DialogflowController.php
Back
<?php namespace App\Http\Controllers\api\chatbot; use App\Http\Controllers\Controller; use Google\Auth\CredentialsLoader; use Google\Auth\ApplicationDefaultCredentials; use GuzzleHttp\Client; use Illuminate\Support\Facades\Http; use Illuminate\Http\Request; use Illuminate\Http\JsonResponse; use App\Models\ChatbotLog; use App\Jobs\SyncConversations; use App\Jobs\SyncChatbotLogsJob; use Illuminate\Support\Facades\Log; use DB; class DialogflowController extends Controller { public function index(Request $request){ // dd($request->all()); // DB::enableQueryLog(); $keyword = $request->input('keyword', ''); $perPage = $request->input('per_page',PHP_INT_MAX); $sortBy = $request->input('sortBy', ''); $sortType = $request->input('sortType', ''); $data = \App\Models\AiConversations::where(function ($query) use ($keyword) { $keyword = str_replace(" ", "%", $keyword); $query->where('user_message', 'like', '%' . $keyword . '%') ->orWhere('bot_response', 'like', '%' . $keyword . '%'); }); $data->get(); // dd(DB::getQueryLog()); $data = $data->paginate($perPage); return response()->json($data); } public function getAccessToken() { $credentialsPath = storage_path('autohub-assist-ff9a5fe0ee23.json'); // Path to service account putenv("GOOGLE_APPLICATION_CREDENTIALS={$credentialsPath}"); $client = new Client(); $scope = 'https://www.googleapis.com/auth/cloud-platform'; $creds = ApplicationDefaultCredentials::getCredentials($scope); $token = $creds->fetchAuthToken(); return $token['access_token'] ?? null; } public function HumanReadConversationHistory(Request $request) { $page = $request->input('page', 1); $perPage = $request->input('per_page', 10); $pageSize = $perPage; $offset = ($page - 1) * $perPage; $projectId = 'autohub-assist'; $accessToken = $this->getAccessToken(); if (!$accessToken) { return response()->json(['error' => 'Failed to get access token'], 500); } $url = "https://logging.googleapis.com/v2/entries:list"; $dateNow = date('Y-m-d\TH:i:s\Z'); $payload = [ 'resourceNames' => ["projects/{$projectId}"], // 'filter' => 'resource.labels.project_id="'.$projectId.'" AND timestamp >= "2025-03-16"', 'filter' => 'resource.labels.project_id="'.$projectId.'"', // 'filter' => 'resource.labels.project_id="autohub-assist" AND timestamp <= "2025-03-16T00:00:00Z"', // 'filter' => 'resource.labels.project_id="'.$projectId.'" AND timestamp <= "'.$dateNow.'"', 'orderBy' => 'timestamp desc', // 'pageSize' => $pageSize// 100 ]; // dd($payload); if ($request->has('pageToken')) { unset($payload['filter']); // Remove timestamp filter $payload['pageToken'] = $request->input('pageToken'); } // Make API request $response = Http::withHeaders([ 'Authorization' => 'Bearer ' . $accessToken, 'Content-Type' => 'application/json' ])->post($url, $payload); // ])->get($url, $payload); // ✅ Get status before decoding response $status = $response->status(); $responseData = $response->json(); // Automatically decodes JSON // Extract chat history $chatHistory = []; if (!empty($responseData['entries'])) { foreach ($responseData['entries'] as $entry) { $queryResult = $entry['jsonPayload']['queryResult'] ?? null; $timeStamp = $entry['timestamp'] ?? null; $recievedTimeStatmp = $entry['receiveTimestamp'] ?? null; $labelInfo = $entry['labels'] ?? null; if($labelInfo){ $location_id = $labelInfo['location_id'] ?? null; $sessionID = $labelInfo['session_id'] ?? null; $agentID = $labelInfo['agent_id'] ?? null; } if ($queryResult) { $userMessage = $queryResult['match']['resolvedInput'] ?? null; $botResponses = $queryResult['responseMessages'] ?? []; $botMessages = []; foreach ($botResponses as $response) { if (!empty($response['text']['text'])) { $botMessages[] = implode(" ", $response['text']['text']); } } $chatHistory[] = [ 'user' => $userMessage, 'bot' => $botMessages, // 'info' => [$sessionID,$location_id,$agentID,$timeStamp,$recievedTimeStatmp], 'session_id' => $sessionID, 'location_id' => $location_id, 'agent_id' => $agentID, 'timestamp' => $timeStamp, 'received_timestamp' => $recievedTimeStatmp ]; } } } return response()->json([ 'status' => $status, // ✅ Use stored status 'data' => $chatHistory, 'nextPageToken' => $responseData['nextPageToken'] ?? null, 'totalItems' => $responseData['totalItems'] ?? count($chatHistory), ]); } public function getConversationHistory(Request $request) { $projectId = 'autohub-assist'; $accessToken = $this->getAccessToken(); if (!$accessToken) { return response()->json(['error' => 'Failed to get access token'], 500); } $url = "https://logging.googleapis.com/v2/entries:list"; // Build request payload $payload = [ 'resourceNames' => ["projects/{$projectId}"], 'filter' => 'resource.labels.project_id="'.$projectId.'"', 'orderBy' => 'timestamp desc', 'pageSize' => 1000 ]; // Check if user provided a `pageToken` for pagination if ($request->has('pageToken')) { $payload['pageToken'] = $request->input('pageToken'); } $response = Http::withHeaders([ 'Authorization' => 'Bearer ' . $accessToken, 'Content-Type' => 'application/json' ])->post($url, $payload); $status = $response->status(); $responseData = $response->json(); return response()->json([ 'status' => $status, 'chatHistory' => $responseData['entries'] ?? [], 'nextPageToken' => $responseData['nextPageToken'] ?? null, // 👈 Return nextPageToken ]); } public static function formatLogsHistory($chatLogs): array { $formatted = []; foreach ($chatLogs as $entry) { $formatted[] = [ 'user_message' => $entry['user'] ?? 'No user message', 'bot_response' => implode("\n", $entry['bot'] ?? ['No bot response']), 'session_id' => $entry['session_id'] ?? 'N/A', 'location_id' => $entry['location_id'] ?? 'N/A', 'agent_id' => $entry['agent_id'] ?? 'N/A', 'timestamp' => $entry['timestamp'] ?? 'N/A', 'received_timestamp' => $entry['received_timestamp'] ?? 'N/A', ]; } return $formatted; } /** * Get chat logs */ public function getChatLogs(): JsonResponse { $rawLogs = ChatbotLog::latest()->limit(1000)->get(); $formattedLogs = []; foreach ($rawLogs as $log) { $chatHistory = json_decode($log->parameters, true); if ($chatHistory && count($chatHistory)> 0) { $formatted = self::formatLogsHistory($chatHistory); $formattedLogs = array_merge($formattedLogs, $formatted); } } return response()->json([ 'status' => 200, 'data' => $formattedLogs ]); } public function dispatchSyncConversations(){ Log::info('Dispatching job started: ' . now()); // $jwtToken = env('JWT_SECRET'); // Use JWT token from env $pageToken = null; // You can specify a page token if you want pagination // Dispatch the job properly with both parameters // SyncConversations::dispatch($pageToken); $job = new SyncConversations(); $job->handle(); // 🔥 Directly execute the job Log::info('Job dispatched at: ' . now()); } public function dispatchSyncChatbotLogRaw(){ Log::info('Dispatching raw logs job started: ' . now()); $job = new SyncChatbotLogsJob(); $job->handle(); Log::info('Job dispatched at: ' . now()); } }
| ver. 1.4 |
.
| PHP 8.1.32 | Generation time: 0.01 |
proxy
|
phpinfo
|
Settings