From c3fbef3381f6f44cb7e3241b55bc757d574ed9c8 Mon Sep 17 00:00:00 2001 From: Gowtham M Date: Sat, 1 Nov 2025 10:52:20 +0530 Subject: [PATCH] GWM : read policy file --- app/Config/Routes.php | 3 +- app/Controllers/PolicyController.php | 123 ++++++++++++++++++++++----- app/Filters/JwtAuthFilter.php | 4 +- 3 files changed, 106 insertions(+), 24 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index f4bc202..8311fca 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -93,6 +93,7 @@ $routes->group('api', ['filter' => 'appSignature'], function ($routes) { $routes->post('policy/createPolicy', 'PolicyController::createPolicy'); $routes->post('policy/updatePolicy', 'PolicyController::updatePolicy'); $routes->get('policy/downloadPolicyFile', 'PolicyController::downloadPolicyFile'); + $routes->post('policy/uploadPolicyFile', 'PolicyController::uploadPolicyFile'); //claims $routes->get('claim/ClaimList', 'ClaimController::ClaimList'); @@ -117,7 +118,7 @@ $routes->group('api', ['filter' => 'appSignature'], function ($routes) { - + $routes->get('checkPolicyDoc', 'PolicyController::checkPolicyDoc'); diff --git a/app/Controllers/PolicyController.php b/app/Controllers/PolicyController.php index 092d8c2..0cbac6f 100644 --- a/app/Controllers/PolicyController.php +++ b/app/Controllers/PolicyController.php @@ -204,6 +204,85 @@ class PolicyController extends ResourceController } } + + public function uploadPolicyFile() + { + try { + + $data = $this->request->getPost(); + $uploadPath = WRITEPATH . 'uploads/policy/'; + + $policyPdf = $this->request->getFile('policy_pdf_file_name'); + + $pdfFileName = null; + + // PDF Upload + if ($policyPdf && $policyPdf->isValid()) { + $pdfPath = $uploadPath . 'policy_pdf/'; + if (!is_dir($pdfPath)) { + mkdir($pdfPath, 0777, true); + } + $pdfFileName = time() . '_' . $policyPdf->getRandomName(); + $policyPdf->move($pdfPath, $pdfFileName); + } + + + + if (!isset($data['id'])) { + + //fetch enquiry_id & agent_id + $quotData = $this->QuotationModel->select('partner_quotation.*,E.agent_id,E.name') + ->join('partner_enquiry E', 'E.id = partner_quotation.enquiry_id', 'left') + ->where('partner_quotation.id',$data['quotation_id']) + ->first(); + + $insertData = [ + 'enquiry_id' => $quotData['enquiry_id'], + 'quotation_id' => $data['quotation_id'], + 'insured_name' => $quotData['name'], + 'manager_id' => $data['manager_id'], + 'agent_id' => $quotData['agent_id'], + 'policy_pdf_file_name' => $pdfFileName, + 'created_by' => $data['created_by'] + ]; + + $policyId = $this->PolicyModel->insert($insertData); + + }else{ + + $updateData = [ + 'policy_pdf_file_name' => $pdfFileName, + 'updated_by' => $data['updated_by'] + ]; + + $this->PolicyModel->update($data['id'], $updateData); + $policyId = $data['id']; + + } + + $readDoc = $this->checkPolicyDoc($policyId); + + if($readDoc['status'] == 'failed'){ + + $result = ['policy_id'=>$policyId, 'file_read_data'=>[ 'value'=> [] , 'message' => $readDoc['message'] ] ]; + + }else{ + $result = ['policy_id'=>$policyId, 'file_read_data'=>[ 'value'=> $readDoc['data'] , 'message' => $readDoc['message'] ] ]; + } + + + + + return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result ], 200); + + + } catch (\Exception $e) { + return $this->respond(['status' => 'failed', 'code' => 500, 'data' => $e->getMessage()], 500); + } + } + + + // Download policy file public function downloadPolicyFile() { @@ -250,11 +329,12 @@ class PolicyController extends ResourceController } - public function checkPolicyDoc() + public function checkPolicyDoc($policyId) { try { + // Replace with your actual Gemini API key $apiKey = getenv('GEMINI_API_KEY'); // The model to use and the API endpoint @@ -263,21 +343,23 @@ class PolicyController extends ResourceController // $model = "gemini-1.5-pro"; $url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}"; - $filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\bike-0904023124P114268957.pdf'; - $filePath = 'C:\Users\Venba\AppData\Local\Programs\Python\pyenv\pdfreader\car-insurance-0904023124P114213011.pdf'; + $record = $this->PolicyModel->find($policyId); + $uploadedPath = WRITEPATH . 'uploads/policy/policy_pdf/'; + $filePath = $uploadedPath.$record['policy_pdf_file_name']; // Check if the file exists if (!file_exists($filePath)) { - die("Error: File not found at {$filePath}"); + log_message('info',"Error: File not found at {$filePath}"); + return ['status'=>"failed", 'message'=> "File not found at {$filePath}"]; } // Get the file's MIME type using the finfo extension $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimeType = finfo_file($finfo, $filePath); finfo_close($finfo); - // print_r($mimeType);die(); - // Define supported inline MIME types - $supportedInlineMimeTypes = ['application/pdf','text/csv']; + + // Define supported inline MIME types + $supportedInlineMimeTypes = ['application/pdf','text/csv']; // Read the file content and encode it to Base64 $fileContent = file_get_contents($filePath); @@ -295,7 +377,6 @@ class PolicyController extends ResourceController ]; // Conditionally handle the file upload based on MIME type if (in_array($mimeType, $supportedInlineMimeTypes)) { - // echo "Detected supported format inline MIME type ({$mimeType})"; // Handle PDF as inline data $fileContent = file_get_contents($filePath); $base64Content = base64_encode($fileContent); @@ -365,7 +446,8 @@ class PolicyController extends ResourceController // Check for cURL errors if (curl_errno($ch)) { $curl_error = curl_error($ch); - throw new \Exception("cURL Error: " . $curl_error); + log_message('info',"cURL Error: " . $curl_error); + return ['status'=>"failed", 'message'=> "cURL Error: " . $curl_error]; } $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); @@ -374,7 +456,8 @@ class PolicyController extends ResourceController $ch = null; // Mark handle as closed // Check for non-successful HTTP status codes if ($http_code < 200 || $http_code >= 300) { - throw new \Exception("API returned non-successful HTTP status code: $http_code. Response: " . substr($response, 0, 200) . '...'); + log_message('info',"API returned non-successful HTTP status code: $http_code. Response: " . substr($response, 0, 200)); + return ['status'=>"failed", 'message'=> "API returned non-successful HTTP status code: $http_code. Response: " . substr($response, 0, 200)]; } // Decode the JSON response @@ -402,31 +485,29 @@ class PolicyController extends ResourceController } if (empty($json_string)) { - throw new \Exception("Could not extract a valid JSON string from the generated text."); + log_message('info',"Could not extract a valid JSON string from the generated text."); + return ['status'=>"failed", 'message'=> "Could not extract a valid JSON string from the generated text."]; } // Decode the extracted JSON string $final_data = json_decode($json_string, true, 512, JSON_THROW_ON_ERROR); log_message('info', "Extracted and decoded final JSON data successfully."); - echo '
';
-                    print_r($final_data);
-                    // return $final_data;
+
+                    return ['status'=>"sucess", 'message'=> "Doc read sucess" , 'data'=>$final_data];
 
                 } else {
-                    // No generated text found, possibly a model safety block or API structure change
-                    throw new \Exception("Response structure invalid or no generated text candidate found.");
+                    log_message('info',"Response structure invalid or no generated text candidate found.");
+                    return ['status'=>"failed", 'message'=> "Response structure invalid or no generated text candidate found"];
                 }
 
         } catch (\Exception $e) {
-            // Log the error
-            // log_message('ERROR', "$request_id: Fatal Error: " . $e->getMessage());
-
-            // Ensure cURL handle is closed if an exception occurred after initialization but before closing
+            
             if ($ch !== null) {
                 curl_close($ch);
             }
-            return null; // Return null on failure
+
+            return ['status'=>"failed", 'message'=> "Error: " . $e];
         }
 
     }
diff --git a/app/Filters/JwtAuthFilter.php b/app/Filters/JwtAuthFilter.php
index e75c6a3..b33a502 100644
--- a/app/Filters/JwtAuthFilter.php
+++ b/app/Filters/JwtAuthFilter.php
@@ -26,8 +26,8 @@ class JwtAuthFilter implements FilterInterface
         }
 
         // ⚙️ Extract date info from token
-        $userId = $decodedToken->data->id ?? null;
-        $lastLogin = $decodedToken->data->last_login_datetime ?? null;
+        $userId = $decodedToken['data']->id ?? null;
+        $lastLogin = $decodedToken['data']->last_login_datetime ?? null;
 
         if ($userId && $lastLogin) {