diff --git a/app/Controllers/PolicyController.php b/app/Controllers/PolicyController.php index 1832a09..092d8c2 100644 --- a/app/Controllers/PolicyController.php +++ b/app/Controllers/PolicyController.php @@ -250,186 +250,186 @@ class PolicyController extends ResourceController } - // public function checkPolicyDoc() - // { + public function checkPolicyDoc() + { - // try - // { - // // Replace with your actual Gemini API key - // $apiKey = getenv('GEMINI_API_KEY'); - // // The model to use and the API endpoint - // $model = "gemini-pro"; - // $model = getenv('GEMINI_MODEL'); - // // $model = "gemini-1.5-pro"; - // // $model = "gemini-1.5-pro"; - // $url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}"; + try + { + // Replace with your actual Gemini API key + $apiKey = getenv('GEMINI_API_KEY'); + // The model to use and the API endpoint + $model = "gemini-pro"; + $model = getenv('GEMINI_MODEL'); + // $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'; + $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'; - // // Check if the file exists - // if (!file_exists($filePath)) { - // die("Error: File not found at {$filePath}"); - // } + // Check if the file exists + if (!file_exists($filePath)) { + die("Error: 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']; + // 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']; - // // Read the file content and encode it to Base64 - // $fileContent = file_get_contents($filePath); - // $base64Content = base64_encode($fileContent); - // // The prompt you want to send to the model - // // $prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations"; - // $prompt = "Read the following motor policy pdf document and convert into JSON format as sample specified. Give me only JSON,not any explanations.while pick up premium break up give own damage, third party ,personal accident and taxes as mentioned in JSON format.Notes:vehicle_type should be like Two Wheeler,Four Feeler,Good Vehicle,Bus, Tractor,Commercial Vehicle.rto_state_code is first two char of reg_no and rto_city_code 3rd & 4th char of reg_no and it should be two digit numeric code. Any date should be in mysql date format"; - // $prompt .= '"{\"policy\":{\"policy_number\":\"\",\"issue_date\":\"\",\"period\":{\"start\":\"\",\"end\":\"\"},\"insurer\":\"\",\"previous_policy_number\":\"\"},\"insured\":{\"name\":\"\",\"father_name\":\"\",\"address\":[\"\"],\"mobile\":\"\",\"id_proofs\":{\"aadhaar\":\"\",\"pan\":\"\"}},\"vehicle\":{\"reg_no\":\"\",\"rto_state_code\":\"\",\"rto_city_code\":\"\",\"weight\":\"\",\"fuel_type\":\"\",\"date_of_registration\":\"\",\"year_of_manufacture\":\"\",\"engine_no\":\"\",\"chassis_no\":\"\",\"make\":\"\",\"model\":\"\",\"year\":\"\",\"cubic_capacity\":\"\",\"vehicle_type\":\"\"},\"rto\":\"\",\"premium\":{\"tp\":0,\"od\":0,\"pa\":0,\"taxes\":{},\"total\":0,\"in_words\":\"\"},\"endorsements\":[{\"code\":\"\",\"desc\":\"\"}]}"'; + // Read the file content and encode it to Base64 + $fileContent = file_get_contents($filePath); + $base64Content = base64_encode($fileContent); + // The prompt you want to send to the model + // $prompt = "give me a json with emp data like name,age,dob,mobile and email. only json not any explanations"; + $prompt = "Read the following motor policy pdf document and convert into JSON format as sample specified. Give me only JSON,not any explanations.while pick up premium break up give own damage, third party ,personal accident and taxes as mentioned in JSON format.Notes:vehicle_type should be like Two Wheeler,Four Feeler,Good Vehicle,Bus, Tractor,Commercial Vehicle.rto_state_code is first two char of reg_no and rto_city_code 3rd & 4th char of reg_no and it should be two digit numeric code. Any date should be in mysql date format"; + $prompt .= '"{\"policy\":{\"policy_number\":\"\",\"issue_date\":\"\",\"period\":{\"start\":\"\",\"end\":\"\"},\"insurer\":\"\",\"previous_policy_number\":\"\"},\"insured\":{\"name\":\"\",\"father_name\":\"\",\"address\":[\"\"],\"mobile\":\"\",\"id_proofs\":{\"aadhaar\":\"\",\"pan\":\"\"}},\"vehicle\":{\"reg_no\":\"\",\"rto_state_code\":\"\",\"rto_city_code\":\"\",\"weight\":\"\",\"fuel_type\":\"\",\"date_of_registration\":\"\",\"year_of_manufacture\":\"\",\"engine_no\":\"\",\"chassis_no\":\"\",\"make\":\"\",\"model\":\"\",\"year\":\"\",\"cubic_capacity\":\"\",\"vehicle_type\":\"\"},\"rto\":\"\",\"premium\":{\"tp\":0,\"od\":0,\"pa\":0,\"taxes\":{},\"total\":0,\"in_words\":\"\"},\"endorsements\":[{\"code\":\"\",\"desc\":\"\"}]}"'; - // $payloadPart = null; + $payloadPart = null; - // // The text part of the prompt - // $text_part = [ - // "text" => $prompt - // ]; - // // 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); - // $payloadPart = [ - // "inlineData" => [ - // "mimeType" => $mimeType, - // "data" => $base64Content - // ] - // ]; + // The text part of the prompt + $text_part = [ + "text" => $prompt + ]; + // 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); + $payloadPart = [ + "inlineData" => [ + "mimeType" => $mimeType, + "data" => $base64Content + ] + ]; - // $content_parts = [ - // "parts" => [ - // $text_part, - // $payloadPart - // ] - // ]; - // } else { - // // Handle Excel/CSV using the Files API - // // echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n"; - // $fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey + $content_parts = [ + "parts" => [ + $text_part, + $payloadPart + ] + ]; + } + // else { + // // Handle Excel/CSV using the Files API + // // echo "Detected unsupported inline MIME type ({$mimeType}). Uploading via Files API...\n"; + // $fileInfo = $this->uploadFileToGemini($filePath, $apiKey); // Pass apiKey - // // print_r($fileInfo); - // // The file part, using the URI from the Files API upload - // $file_part = [ - // "fileData" => [ - // "fileUri" => $fileInfo['uri'], - // "mimeType" => $fileInfo['mimeType'] - // ] - // ]; + // // print_r($fileInfo); + // // The file part, using the URI from the Files API upload + // $file_part = [ + // "fileData" => [ + // "fileUri" => $fileInfo['uri'], + // "mimeType" => $fileInfo['mimeType'] + // ] + // ]; - // // The full content array, containing both parts - // $content_parts = [ - // "parts" => [ - // $text_part, - // $file_part - // ] - // ]; - // } + // // The full content array, containing both parts + // $content_parts = [ + // "parts" => [ + // $text_part, + // $file_part + // ] + // ]; + // } - // // The final JSON payload - // $data = [ - // "contents" => [ - // $content_parts - // ] - // ]; + // The final JSON payload + $data = [ + "contents" => [ + $content_parts + ] + ]; - // // Encode the data to a JSON string - // $json_data = json_encode($data); + // Encode the data to a JSON string + $json_data = json_encode($data); - // // Initialize cURL - // $ch = curl_init($url); + // Initialize cURL + $ch = curl_init($url); - // // Set cURL options - // curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // Set the Content-Type header - // curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); // Set the JSON payload - // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string - // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Optional: to bypass SSL verification if needed (not recommended for production) + // Set cURL options + curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); // Set the Content-Type header + curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data); // Set the JSON payload + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Optional: to bypass SSL verification if needed (not recommended for production) - // // Execute the cURL request and get the response - // $response = curl_exec($ch); + // Execute the cURL request and get the response + $response = curl_exec($ch); - // // Check for cURL errors - // if (curl_errno($ch)) { - // $curl_error = curl_error($ch); - // throw new \Exception("cURL Error: " . $curl_error); - // } - // $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + // Check for cURL errors + if (curl_errno($ch)) { + $curl_error = curl_error($ch); + throw new \Exception("cURL Error: " . $curl_error); + } + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - // // Close the cURL handle - // curl_close($ch); - // $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) . '...'); - // } + // Close the cURL handle + curl_close($ch); + $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) . '...'); + } - // // Decode the JSON response - // $responseData = json_decode($response, true, 512, JSON_THROW_ON_ERROR); - // $text_path = $responseData['candidates'][0]['content']['parts'][0]['text'] ?? null; + // Decode the JSON response + $responseData = json_decode($response, true, 512, JSON_THROW_ON_ERROR); + $text_path = $responseData['candidates'][0]['content']['parts'][0]['text'] ?? null; - // if ($text_path) { - // $generatedText = $text_path; - // log_message('info', "Successfully received generated text."); + if ($text_path) { + $generatedText = $text_path; + log_message('info', "Successfully received generated text."); - // // 9. Attempt to extract and decode the exact JSON from the generated text - // $json_string = ''; + // 9. Attempt to extract and decode the exact JSON from the generated text + $json_string = ''; - // // Preferred: Regex to find content inside a JSON markdown block: ```json\n(.*?)\n``` - // $extracted_json_match = []; - // if (preg_match('/```json\s*(.*?)\s*```/s', $generatedText, $extracted_json_match)) { - // $json_string = trim($extracted_json_match[1]); - // } else { - // // Fallback: Find the first '{' and the last '}' - // $start = strpos($generatedText, '{'); - // $end = strrpos($generatedText, '}'); - // if ($start !== false && $end !== false && $end > $start) { - // $json_string = substr($generatedText, $start, $end - $start + 1); - // } - // } + // Preferred: Regex to find content inside a JSON markdown block: ```json\n(.*?)\n``` + $extracted_json_match = []; + if (preg_match('/```json\s*(.*?)\s*```/s', $generatedText, $extracted_json_match)) { + $json_string = trim($extracted_json_match[1]); + } else { + // Fallback: Find the first '{' and the last '}' + $start = strpos($generatedText, '{'); + $end = strrpos($generatedText, '}'); + if ($start !== false && $end !== false && $end > $start) { + $json_string = substr($generatedText, $start, $end - $start + 1); + } + } - // if (empty($json_string)) { - // throw new \Exception("Could not extract a valid JSON string from the generated text."); - // } + if (empty($json_string)) { + throw new \Exception("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); + // 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;
+ log_message('info', "Extracted and decoded final JSON data successfully.");
+ echo '';
+ print_r($final_data);
+ // return $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.");
- // }
+ } 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.");
+ }
- // } catch (\Exception $e) {
- // // Log the error
- // // log_message('ERROR', "$request_id: Fatal Error: " . $e->getMessage());
+ } 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
- // }
+ // 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
+ }
- // }
+ }
diff --git a/app/Controllers/StaffAuthController.php b/app/Controllers/StaffAuthController.php
index b780d08..2aa4abf 100644
--- a/app/Controllers/StaffAuthController.php
+++ b/app/Controllers/StaffAuthController.php
@@ -172,8 +172,9 @@ class StaffAuthController extends ResourceController
}
$decodedToken = validateJWT($matches[1]);
- $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) {
@@ -187,8 +188,8 @@ class StaffAuthController extends ResourceController
->where('staff_id', $userId)
->where('DATE(login_datetime)', $lastLoginDate)
->first();
-
- if ($attendance && !$attendance['logout_datetime']) {
+
+ if ($attendance) {
$attendanceModel->update($attendance['id'], [
'logout_datetime' => date('Y-m-d H:i:s')
]);
diff --git a/app/Controllers/StaffController.php b/app/Controllers/StaffController.php
index 53255cc..36f7b63 100644
--- a/app/Controllers/StaffController.php
+++ b/app/Controllers/StaffController.php
@@ -252,7 +252,7 @@ class StaffController extends ResourceController
} else {
return $this->respond([
'status' => 'failed',
- 'code' => $response->getStatusCode(),
+ 'code' => 404,
'message' => 'Unable to fetch file from source'
], $response->getStatusCode());
}