diff --git a/.env.sample b/.env.sample index 50244384..5c3f1bf8 100755 --- a/.env.sample +++ b/.env.sample @@ -131,5 +131,10 @@ HEALTH_INDIA_PASSWORD = HEALTH_INDIA_PRIMARY_KEY_CONSTANT = +#For sending mail for leads RFQ/QCR +LEAD_INSURER_FROM_MAIL_ID = +LEAD_CLIENT_FROM_MAIL_ID = + # BDS Daily Report Emails Configuration bds.dailyReportEmails = + diff --git a/app/Config/Acl.php b/app/Config/Acl.php index b4d85eac..45ca160a 100644 --- a/app/Config/Acl.php +++ b/app/Config/Acl.php @@ -15,6 +15,13 @@ class Acl '#^/loginPos#' => ['public' => true], '#^/getVerifyPosMobileNo#' => ['public' => true], '#^/getVerifiedPosUserData#' => ['public' => true], + '#^/chat#' => ['public' => true], + '#^/widget#' => ['public' => true], + '#^/chatbottest#' => ['public' => true], + '#^/chatbot#' => ['public' => true], + '#^/getSSORedirectUrl#' => ['public' => true], + '#^/getEmployeePolicy#' => ['public' => true], + '#^/downloadFileTableFile#' => ['public' => true], '#^/swagger#' => ['roles' => [ADMIN_ROLE_ID]], '#^/getEmployeeActiveOrInactivePolicy#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]], '#^/bulkEcardDownloadAsZip#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID]], @@ -54,6 +61,34 @@ class Acl 'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], 'teams' => [] ], + '#^/hrFileDownload#' => [ + 'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [] + ], + '#^/sendPushNotification#' => [ + 'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [] + ], + '#^/sendEmail#' => [ + 'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [] + ], + '#^/getPolicyLevelEmployeeSummaryData#' => [ + 'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [] + ], + '#^/cdTransactionData#' => [ + 'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [] + ], + '#^/claimsSearch#' => [ + 'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/getBackToEnrolledDetails#' => [ + 'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [] + ], // ===================== USER MANAGEMENT ===================== '#^/user#' => [ @@ -88,6 +123,18 @@ class Acl 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], 'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID] ], + '#^/dmsSearch#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID] + ], + '#^/downloadGdriveFile#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID] + ], + '#^/driveListFiles#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID] + ], '#^/bds_upload#' => [ 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], 'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID] @@ -108,12 +155,60 @@ class Acl 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], 'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID] ], + '#^/importRules#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID] + ], // ===================== CLAIMS / TICKETS ===================== '#^/ticket#' => [ 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], 'teams' => [CLAIMS_TEAM_ID] ], + '#^/ticketSave#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/ticketList#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/ticketConversationSave#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/ticketConversationList#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/ticketType#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/ticketHistoryList#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/ticketAutoFetchDetails#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/initiateClaim#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/departments#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/get_ticket_data#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], + '#^/claimView#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], + 'teams' => [CLAIMS_TEAM_ID] + ], '#^/claim_mis#' => [ 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID], 'teams' => [CLAIMS_TEAM_ID] @@ -138,6 +233,22 @@ class Acl 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID], 'teams' => [] ], + '#^/add_advertise_image#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID], + 'teams' => [] + ], + '#^/remove_advertise_image#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID], + 'teams' => [] + ], + '#^/getAdvertiseImage#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID], + 'teams' => [] + ], + '#^/showAdvertiseImage#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID], + 'teams' => [] + ], '#^/frontend_content#' => [ 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID], 'teams' => [] @@ -146,6 +257,10 @@ class Acl 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID], 'teams' => [] ], + '#^/getFEContent#' => [ + 'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID], + 'teams' => [] + ], // ===================== LOGS ===================== '#^/logs#' => [ @@ -167,9 +282,25 @@ class Acl // ===================== WEBHOOKS / 3RD PARTY ===================== '#^/dispatchWebhookData#' => ['public' => true], '#^/retrieveWebhookData#' => ['public' => true], - // '#^/ICICI#' => ['public' => true], - // '#^/Vidal#' => ['public' => true], - // '#^/MediAssist#' => ['public' => true], + '#^/ecardRequest#' => ['public' => true], + '#^/getTPAID#' => ['public' => true], + '#^/fileDownload#' => ['public' => true], + '#^/generateAuthToken#' => ['public' => true], + '#^/createEnrollmentBatch#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID], 'teams' => [ENROLLMENT_TEAM_ID]], + '#^/getEnrollmentBatchStatus#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID], 'teams' => [ENROLLMENT_TEAM_ID]], + '#^/fetchUHIDDetails#' => ['roles' => [ADMIN_ROLE_ID, HEAD_ROLE_ID], 'teams' => [ENROLLMENT_TEAM_ID]], + '#^/FhplGetBenefDetails#' => ['roles' => [ADMIN_ROLE_ID]], + '#^/EcardRequest#' => ['public' => true], + '#^/HospitalNetwork#' => ['public' => true], + '#^/VidalGetBenefDetails#' => ['public' => true], + '#^/ClaimDetail#' => ['public' => true], + '#^/SubmitClaim#' => ['roles' => [ADMIN_ROLE_ID,HEAD_ROLE_ID,ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID]], + '#^/IntimateClaim#' => ['roles' => [ADMIN_ROLE_ID,HEAD_ROLE_ID,ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID]], + '#^/IRSubmission#' => ['roles' => [ADMIN_ROLE_ID,HEAD_ROLE_ID,ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID]], + '#^/ClaimStatusUpdate#' => ['roles' => [ADMIN_ROLE_ID,HEAD_ROLE_ID,ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID]], + '#^/syncTpaClaimToNhance#' => ['roles' => [ADMIN_ROLE_ID,HEAD_ROLE_ID,ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID]], + '#^/HealthIndiaGetBenefDetails#' => ['roles' => [ADMIN_ROLE_ID,HEAD_ROLE_ID,ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID]], + '#^/testTracelog#' => ['roles' => [ADMIN_ROLE_ID]], // ===================== CLI ===================== '#^/cli/#' => ['public' => true], diff --git a/app/Config/RfqConfig.php b/app/Config/RfqConfig.php new file mode 100644 index 00000000..ca536901 --- /dev/null +++ b/app/Config/RfqConfig.php @@ -0,0 +1,51 @@ + [ + 'vitvelz@gmail.com', + 'velz1990@gmail.com', + 'venkateshraman786@gmail.com', + ], + 'viewers' => [], + ]; + + /** + * Default protections for RFQ sheets. + * Copied from GoogleSheetController::$config. + */ + public array $protections = [ + [ + 'range' => 'RFQ Page!B12:C12', + 'users' => [ + 'velz1990@gmail.com', + 'vitvelz@gmail.com', + 'firebase-adminsdk-mcdfe@nhance-ee8d1.iam.gserviceaccount.com', + ], + 'groups' => [], + ], + [ + 'range' => 'Claims Page!A1', + 'users' => [ + 'velz1990@gmail.com', + 'venkateshraman786@gmail.com', + 'firebase-adminsdk-mcdfe@nhance-ee8d1.iam.gserviceaccount.com', + ], + 'groups' => [], + ], + ]; +} diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 17126e97..cf17885b 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -512,6 +512,8 @@ $routes->group("leads", ["filter" => "authMVC"], function ($routes) { $routes->match(['get', 'post'],"list", "LeadsController::viewLeadsList"); $routes->post("create", "LeadsController::createLead"); $routes->get("list/(:any)", "LeadsController::getLeadDataForEdit/$1"); + $routes->get("createRfqSheet", "LeadsController::createRfqSheet"); + $routes->get("mailTemplate", "LeadsController::getLeadMailTemplate"); $routes->get("sendMail", "LeadsController::sendMailWithAttachement"); $routes->post("sendMail", "LeadsController::sendMailWithAttachement"); $routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1"); @@ -525,6 +527,10 @@ $routes->group("rfq", ["filter" => "authMVC"], function ($routes) { $routes->post("createQCR", "LeadsController::createQCR"); $routes->get("list/(:any)", "LeadsController::viewRFQ/$1"); $routes->get("nonEB","LeadsController::rfqNonEB"); + // Non-EB dedicated RFQ/QCR endpoints (do not alter existing ones) + $routes->get("nonEB/rfq/(:any)","LeadsController::viewNonEbRFQFromList/$1"); + $routes->get("nonEB/qcr/(:any)","LeadsController::viewNonEbQCRFromList/$1"); + $routes->get("placementData/(:num)", "LeadsController::getPlacementData/$1"); }); diff --git a/app/Controllers/ApiServiceController.php b/app/Controllers/ApiServiceController.php index 16a650a0..bb977a11 100644 --- a/app/Controllers/ApiServiceController.php +++ b/app/Controllers/ApiServiceController.php @@ -82,6 +82,8 @@ class ApiServiceController extends BaseController { try{ + + if(empty($params) && $this->response){ $payload = $this->request->getJSON(true); @@ -105,6 +107,9 @@ class ApiServiceController extends BaseController } + + log_message('error', 'Ecard Request started | client_policy_id: '.$client_policy_id.' | policyNo: '.$policy_no.' | emp_code: '.$emp_code.' | type: '.$type); + // $employee_policy = $this->employeePolicyModel // ->select('employees.*, employee_polices.tpa_id , employee_polices.rand_string , employee_polices.uhid as uhid , client_policy.tpa_id as tpa_primary_id ') // ->join('employees', 'employee_polices.employee_id = employees.id', 'left') @@ -126,11 +131,15 @@ class ApiServiceController extends BaseController ->whereIn('employees.emp_status', ['active', 'expired']) ->findAll(); + log_message('error', 'Ecard Request - Employee data fetched | count: '.count($employee_policy).' | type: '.$type); if(count($employee_policy) > 0) { if($employee_policy[0]['tpa_id'] != null) { + + log_message('error', 'Ecard Request - tpa_id found | tpa_id: '.$employee_policy[0]['tpa_id'].' | type: '.$type); + if($employee_policy[0]['tpa_primary_id'] == $this->medi_assist_primary_key)//Medi assist { @@ -176,11 +185,11 @@ class ApiServiceController extends BaseController $data['message'] = "E-card not generated"; } - } else { - $data['eCardDownload'] = null; - $data['message'] = "E-card not generated"; - log_message('error', 'TPA number is null'); - } + } else { + $data['eCardDownload'] = null; + $data['message'] = "E-card not generated"; + log_message('error', 'TPA number is null'); + } }else{ $data['eCardDownload'] = null; $data['message'] = "E-card not generated"; diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index 76e2b811..fbff649a 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -163,17 +163,21 @@ class EmployeeController extends AdminController public function getClientWithPolicies() { - //echo $this->request->isAJAX();die(); - $result = $this->clientModel->clientsWithPolicies(); + try { + //echo $this->request->isAJAX();die(); + $result = $this->clientModel->clientsWithPolicies(); - // dd($result); + // dd($result); - // print_r($result);die(); - if (!count($result)) { - return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200); - } else { - - return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $result], 200); + // print_r($result);die(); + if (!count($result)) { + return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200); + } else { + + return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $result], 200); + } + } catch (\Throwable $th) { + return $this->respond(['dataStatus' => false, 'code' => 500, 'message' => $th->getMessage()], 500); } } @@ -3564,7 +3568,7 @@ class EmployeeController extends AdminController public function initiateWellnessOnboard($client_policy_id) { $r = Jobs::addJob(['job_name' => 'initiateWellnessOnboardJob','payload' => ['client_policy_id' => $client_policy_id]]); - //$this->initiateWellnessOnboardJob(['client_policy_id' => $client_policy_id]); + // $this->initiateWellnessOnboardJob(['client_policy_id' => $client_policy_id]); return $this->respond(['status' => true, 'code' => 200, 'message' => 'Process started'], 200); } @@ -4667,14 +4671,17 @@ class EmployeeController extends AdminController $statusCode = $response->getStatusCode(); $rawBody = $response->getBody(); $result = json_decode($rawBody, true); + // print_rr($result); - // 4. Handle based on HTTP Status Code - if ($statusCode >= 200 && $statusCode < 300) { + // 4. Handle based on HTTP Status Code - BUG FIX: Changed = to == for proper comparison + if ($statusCode == 200) { $this->myLogger->logme('error', "VISIT_OFFBOARD API Success (Code $statusCode): Policy deleted."); - return [ - 'status' => true, - 'data' => $result + $return_data = [ + 'memberIds' => $params['memberIds'] ?? [], + 'api_result' => $result ]; + $this->updateVisitoffboardStatus($return_data); + return $return_data; } // Log API-level errors (4xx or 5xx) @@ -4697,6 +4704,73 @@ class EmployeeController extends AdminController } } + + /** + * Updates the wellness onboard status in the database for deleted members. + * + * Marks employee policy records as deleted in the wellness system after + * a successful API response from the wellness onboard service. + * + * @param array $data Contains 'memberIds' array and 'api_result' from API response + * @return bool Returns true if update was successful or no action needed, false on error + */ + public function updateVisitoffboardStatus(array $data): bool + { + try { + // Validate input data structure + if (empty($data) || !is_array($data)) { + $this->myLogger->logme('error', 'VISIT_OFFBOARD_STATUS_UPDATE: Invalid data parameter'); + return false; + } + + // Check if API result exists + if (empty($data['api_result'])) { + $this->myLogger->logme('error', 'VISIT_OFFBOARD_STATUS_UPDATE: No API result found in data'); + return false; + } + + $apiResult = $data['api_result']; + + // Verify API success status - BUG FIX: Proper key access and validation + if (($apiResult['message'] ?? null) !== 'success') { + $this->myLogger->logme('error', 'VISIT_OFFBOARD_STATUS_UPDATE: API response not successful - ' . json_encode($apiResult)); + return false; + } + + // Extract member IDs safely - BUG FIX: Corrected key from memberids to memberIds + $memberIds = $data['memberIds'] ?? []; + + if (empty($memberIds) || !is_array($memberIds)) { + $this->myLogger->logme('warn', 'VISIT_OFFBOARD_STATUS_UPDATE: No valid memberIds provided for update'); + return true; // Not an error if no members to update + } + + if(!empty($apiResult['missingMemberIds']) && is_array($apiResult['missingMemberIds'])) + { + $this->myLogger->logme('error', 'VISIT_OFFBOARD_STATUS_UPDATE: missing member IDs found - ' . json_encode($apiResult['missingMemberIds'])); + } + // Update wellness_onboard status for deleted members - Append '_DEL' to existing value + $updateResult = $this->employeePolicyModel + ->whereIn('id', $memberIds) + ->set('wellness_onboard', "CONCAT(wellness_onboard, '_DEL')", false) + ->update(); + + if ($updateResult !== false) { + $this->myLogger->logme('error', 'VISIT_OFFBOARD_STATUS_UPDATE: Updated ' . $updateResult . ' employee policy records with wellness_onboard_DEL status'); + return true; + } else { + $this->myLogger->logme('error', 'VISIT_OFFBOARD_STATUS_UPDATE: Database update operation failed'); + return false; + } + + + + } catch (\Exception $e) { + $this->myLogger->logme('error', 'VISIT_OFFBOARD_STATUS_UPDATE: Exception occurred - ' . $e->getMessage() . ' - File: ' . $e->getFile() . ' - Line: ' . $e->getLine()); + return false; + } + } + public function insufficientCdBalanceHrMailSend() { $post_data = $this->request->getJson(true); diff --git a/app/Controllers/ICICILombardController.php b/app/Controllers/ICICILombardController.php index 4d98bc96..717f8a05 100644 --- a/app/Controllers/ICICILombardController.php +++ b/app/Controllers/ICICILombardController.php @@ -121,10 +121,10 @@ class ICICILombardController extends AdminController $body = [ "PolicyNumber" => "4016/PPN/A/O/53185987/00/000", "CDBGAccountNumber" => "CD-MUM-0026", - "CorrelationId" => "550e8400-e29b-41d4-a716-446655440022", + "CorrelationId" => "550e8400-e29b-41d4-a716-446655440023", "MemberDetails" => [ [ - "MemberEmpId" => "EMPID3625565", + "MemberEmpId" => "EMPID3625566", "DOJ" => "21-MAR-2019", "InsuredName" => "sanjeev", "DOB" => "7-JUL-1993", @@ -136,7 +136,7 @@ class ICICILombardController extends AdminController "FlagStatus" => "A" ], [ - "MemberEmpId" => "EMPID3625565", + "MemberEmpId" => "EMPID3625566", "DOJ" => "21-MAR-2019", "InsuredName" => "bhavya", "DOB" => "8-AUG-1970", @@ -195,6 +195,7 @@ class ICICILombardController extends AdminController //fetch token $tokenResponse = $this->generateAuthToken('esbgpauhid'); + // dd($tokenResponse); if (!$tokenResponse || empty($tokenResponse['data']['access_token'])) { return $this->response->setJSON([ 'status' => false, @@ -213,13 +214,15 @@ class ICICILombardController extends AdminController ]; $body = [ - "PolicyNumber" => "4016/PPN/A/O/53185987/00/000", + "PolicyNumber" => "4016/PPN/A/O/53185987/00/001", "IMID" => "201580517901", "CorrelationId" => "550e8400-e29b-41d4-a716-446655440022" ]; $response = call_third_party_api($url, 'POST', $headers, $body, true); + // dd($response); + return $this->response->setJSON($response); } diff --git a/app/Controllers/JobWorker.php b/app/Controllers/JobWorker.php index 9aba4443..5840ac3f 100755 --- a/app/Controllers/JobWorker.php +++ b/app/Controllers/JobWorker.php @@ -238,6 +238,10 @@ class JobWorker extends AdminController 'getEmployeeEcardFromTmpFolderAndZipToS3' => [ 'type' => 'CC', // Handler Category 'handler' => 'App\Controllers\EmployeeController', + ], + 'visitOffBoard' => [ + 'type' => 'CC', // Handler Category + 'handler' => 'App\Controllers\EmployeeController', ] ]; diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 2d3988ac..fd736c2a 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -1,19 +1,18 @@ myLogger = \Config\Services::mylogger(); - $this->clientModel = new ClientModel(); - $this->userModel = new UserModel(); - $this->clientBranchModel = new ClientBranchModel(); - $this->clientPolicyModel = new ClientPolicyModel(); - $this->levelContactModel = new LevelContactModel(); - $this->leadsModel = new LeadsModel(); - $this->policyTypeModel = new PolicyTypeModel(); - $this->kycEntityTypeModel = new KYCEntityTypeModel(); - $this->policyTransactionStatusModel = new PolicyTransactionStatusModel(); - $this->insurerBranchModel = new InsurerBranchModel(); - $this->tpaBranchModel = new TPABranchModel(); - $this->RFQModel = new RFQModel(); - $this->insurerModel = new InsurerModel(); - $this->occupancyModel = new OccupancyMasterModel(); - $this->leadFilesModel = new LeadFilesModel(); + $this->clientModel = new ClientModel(); + $this->userModel = new UserModel(); + $this->clientBranchModel = new ClientBranchModel(); + $this->clientPolicyModel = new ClientPolicyModel(); + $this->levelContactModel = new LevelContactModel(); + $this->leadsModel = new LeadsModel(); + $this->policyTypeModel = new PolicyTypeModel(); + $this->kycEntityTypeModel = new KYCEntityTypeModel(); + $this->policyTransactionStatusModel = new PolicyTransactionStatusModel(); + $this->insurerBranchModel = new InsurerBranchModel(); + $this->tpaBranchModel = new TPABranchModel(); + $this->RFQModel = new RFQModel(); + $this->insurerModel = new InsurerModel(); + $this->occupancyModel = new OccupancyMasterModel(); + $this->leadFilesModel = new LeadFilesModel(); $this->leadInstallmentPaymentDetails = new LeadInstallmentPaymentDetails(); $this->gmailSentHistoryModel = new GmailSentHistoryModel(); $this->leadModel = new SalesActualLeadModel(); $this->contactModel = new SalesContactPersonModel(); - $this->issuer = [1 => 'JIBS', 2 => 'Nhance']; - $this->clientType = [1 => 'Group', 2 => 'Individual']; - $this->leadType = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over']; - $data = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); + + $this->issuer = [1 => 'JIBS', 2 => 'Nhance']; + $this->clientType = [1 => 'Group', 2 => 'Individual']; + $this->leadType = [1 => 'Fresh', 2 => 'Renewal', 3 => 'Roll Over']; + $data = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); $this->buisnessType = array_column($data, 'name', 'id'); // $this->buisnessType = [1 => 'Public Sector', 2 => 'Private Sector',3=> 'Trust',4 => 'Proprietorship',5 => 'Partnership',6 => 'Private',7 => 'Individual']; $this->leadsStatus = [ - 'queued' => 'In-Queued', - 'rfq_created' => 'RFQ Created', - 'rfq_sent' => 'RFQ Sent', - 'qcr_created' => 'QCR Created', - 'qcr_sent' => 'QCR Sent', - 'lost' => 'Lost', - 'co_insurer_pending' => 'Co-Insurer Pending', - 'won' => 'Won', - 'completed_with_corrections' => 'Completed with Corrections', + 'queued' => 'In-Queued', + 'rfq_created' => 'RFQ Created', + 'rfq_sent' => 'RFQ Sent', + 'qcr_created' => 'QCR Created', + 'qcr_sent' => 'QCR Sent', + 'lost' => 'Lost', + 'co_insurer_pending' => 'Co-Insurer Pending', + 'won' => 'Won', + 'completed_with_corrections' => 'Completed with Corrections', 'completed_without_corrections' => 'Completed without Corrections', ]; $this->claim_type_for_gpa = [ - 'nil' => 'Nil', - 'accident_death' => 'Accident Death', - 'permanent_total_disablement' => 'Permanent Total Disablement', - 'permanent_partial_disablement' => 'Permanent Partial Disablement', - 'temporary_total_disablement_benefit' => 'Temporary Total Disablement benefit' + 'nil' => 'Nil', + 'accident_death' => 'Accident Death', + 'permanent_total_disablement' => 'Permanent Total Disablement', + 'permanent_partial_disablement' => 'Permanent Partial Disablement', + 'temporary_total_disablement_benefit' => 'Temporary Total Disablement benefit', ]; $this->cause_of_death = [ - 'natural_death' => 'Natural Death', - 'suicide' => 'Suicide', - 'accident' => 'Accident', + 'natural_death' => 'Natural Death', + 'suicide' => 'Suicide', + 'accident' => 'Accident', 'cardiac_arrest' => 'Cardiac Arrest', - 'septic_shock' => 'Septic shock', - 'heart_attack' => 'Heart Attack', + 'septic_shock' => 'Septic shock', + 'heart_attack' => 'Heart Attack', ]; $this->member_data_excel_columns = [ - 'sno' => [ - 'col_idx' => 0, - 'col_cell_name' => 'A', - 'col_name' => 'Sl no', - 'is_mandatory' => false, - 'data_type' => 'str', - 'format' => null, - 'allowed_values' => null + 'sno' => [ + 'col_idx' => 0, + 'col_cell_name' => 'A', + 'col_name' => 'Sl no', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, ], - 'emp_code' => [ - 'col_idx' => 1, - 'col_cell_name' => 'B', - 'col_name' => 'Emp Code', - 'is_mandatory' => true, - 'data_type' => 'str', - 'format' => null, - 'allowed_values' => null + 'emp_code' => [ + 'col_idx' => 1, + 'col_cell_name' => 'B', + 'col_name' => 'Emp Code', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, ], - 'name' => [ - 'col_idx' => 2, - 'col_cell_name' => 'C', - 'col_name' => 'Name', - 'is_mandatory' => true, - 'data_type' => 'str', - 'format' => null, - 'allowed_values' => null + 'name' => [ + 'col_idx' => 2, + 'col_cell_name' => 'C', + 'col_name' => 'Name', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, ], 'relationship' => [ - 'col_idx' => 3, - 'col_cell_name' => 'D', - 'col_name' => 'Relationship', - 'is_mandatory' => true, - 'data_type' => 'str', - 'format' => null, + 'col_idx' => 3, + 'col_cell_name' => 'D', + 'col_name' => 'Relationship', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, 'allowed_values' => [ 'Self', 'Spouse', 'Son', 'Daughter', 'Father', 'Mother', 'Father-in-law', 'Mother-in-law', 'self', 'spouse', 'son', 'daughter', 'father', 'mother', - 'father-in-law', 'mother-in-law' + 'father-in-law', 'mother-in-law', ], - 'custom' => 'check_relationship_for_member_data', - 'params' => ['row', 'relationship', 'columns_to_check'] + 'custom' => 'check_relationship_for_member_data', + 'params' => ['row', 'relationship', 'columns_to_check'], ], - 'gender' => [ - 'col_idx' => 4, - 'col_cell_name' => 'E', - 'col_name' => 'Gender', - 'is_mandatory' => true, - 'data_type' => 'str', - 'format' => null, - 'allowed_values' => ['M', 'F'] + 'gender' => [ + 'col_idx' => 4, + 'col_cell_name' => 'E', + 'col_name' => 'Gender', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => ['M', 'F'], ], - 'dob' => [ - 'col_idx' => 5, - 'col_cell_name' => 'F', - 'col_name' => 'DOB', - 'is_mandatory' => true, - 'data_type' => 'str', - 'format' => 'd-M-Y', + 'dob' => [ + 'col_idx' => 5, + 'col_cell_name' => 'F', + 'col_name' => 'DOB', + 'is_mandatory' => true, + 'data_type' => 'str', + 'format' => 'd-M-Y', 'allowed_values' => null, 'age_validation' => true, // 'custom' => 'check_dob_diff', // 'params' => ['row', 'relationship', 'default_age_ratio', 'policy_details'] ], - 'age' => [ - 'col_idx' => 6, - 'col_cell_name' => 'G', - 'col_name' => 'Age', - 'is_mandatory' => true, - 'data_type' => 'int', - 'format' => null, - 'allowed_values' => null - ], - 'email' => [ - 'col_idx' => 7, - 'col_cell_name' => 'H', - 'col_name' => 'Email', - 'is_mandatory' => false, - 'data_type' => 'str', - 'format' => null, - 'allowed_values' => null - ], - 'mobile' => [ - 'col_idx' => 8, - 'col_cell_name' => 'I', - 'col_name' => 'Mobile', - 'is_mandatory' => false, - 'data_type' => 'str', - 'format' => null, - 'allowed_values' => null - ], - 'si' => [ - 'col_idx' => 9, - 'col_cell_name' => 'J', - 'col_name' => 'SI', - 'is_mandatory' => false, - 'data_type' => 'int', - 'format' => null, + 'age' => [ + 'col_idx' => 6, + 'col_cell_name' => 'G', + 'col_name' => 'Age', + 'is_mandatory' => true, + 'data_type' => 'int', + 'format' => null, 'allowed_values' => null, - ] + ], + 'email' => [ + 'col_idx' => 7, + 'col_cell_name' => 'H', + 'col_name' => 'Email', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + ], + 'mobile' => [ + 'col_idx' => 8, + 'col_cell_name' => 'I', + 'col_name' => 'Mobile', + 'is_mandatory' => false, + 'data_type' => 'str', + 'format' => null, + 'allowed_values' => null, + ], + 'si' => [ + 'col_idx' => 9, + 'col_cell_name' => 'J', + 'col_name' => 'SI', + 'is_mandatory' => false, + 'data_type' => 'int', + 'format' => null, + 'allowed_values' => null, + ], ]; $this->general_relationships = [ - 'self' => [ - 'name' => 'Self', - 'gender' => 'M', + 'self' => [ + 'name' => 'Self', + 'gender' => 'M', 'age_min' => 18, - 'age_max' => null + 'age_max' => null, ], - 'spouse' => [ - 'name' => 'Spouse', - 'gender' => 'F', + 'spouse' => [ + 'name' => 'Spouse', + 'gender' => 'F', 'age_min' => 18, - 'age_max' => null + 'age_max' => null, ], - 'son' => [ - 'name' => 'Son', - 'gender' => 'M', + 'son' => [ + 'name' => 'Son', + 'gender' => 'M', 'age_min' => null, - 'age_max' => 25 + 'age_max' => 25, ], - 'daughter' => [ - 'name' => 'Daughter', - 'gender' => 'F', + 'daughter' => [ + 'name' => 'Daughter', + 'gender' => 'F', 'age_min' => null, - 'age_max' => 25 + 'age_max' => 25, ], - 'father' => [ - 'name' => 'Father', - 'gender' => 'M', + 'father' => [ + 'name' => 'Father', + 'gender' => 'M', 'age_min' => 18, - 'age_max' => null + 'age_max' => null, ], - 'mother' => [ - 'name' => 'Mother', - 'gender' => 'F', + 'mother' => [ + 'name' => 'Mother', + 'gender' => 'F', 'age_min' => 18, - 'age_max' => null + 'age_max' => null, ], 'father-in-law' => [ - 'name' => 'Father in Law', - 'gender' => 'M', + 'name' => 'Father in Law', + 'gender' => 'M', 'age_min' => 18, - 'age_max' => null + 'age_max' => null, ], 'mother-in-law' => [ - 'name' => 'Mother in Law', - 'gender' => 'F', + 'name' => 'Mother in Law', + 'gender' => 'F', 'age_min' => 18, - 'age_max' => null - ] + 'age_max' => null, + ], ]; - + } public function viewLeadsList() { - $data['tab_name'] = 'Opportunities'; + $data['tab_name'] = 'Opportunities'; $data['page_name'] = 'Opportunities'; // Set basic data - $data['issuer'] = $this->issuer; + $data['issuer'] = $this->issuer; $data['client_type'] = $this->clientType; - $data['lead_type'] = $this->leadType; + $data['lead_type'] = $this->leadType; $data['lead_status'] = $this->leadsStatus; // Fetch policy types and entity data $data['policy_type'] = $this->policyTypeModel->where('is_active', 1)->findAll(); - $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); + $data['entity'] = $this->kycEntityTypeModel->where('is_active', 1)->findAll(); - // dd($lastFiveYears); + // Data needed for mail modals on Opportunities list (reuse RFQ behaviour) + $data['userList'] = $this->userModel->getUserListForRFQ(); + $data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ(); + // Attachments for mails are lead-specific and will be handled at RFQ level; + // keep placeholder here so modal templates render without notices. + $data['attachment_html'] = ''; + + // dd($lastFiveYears); if ($this->request->is('get')) { // Fetch leads data $data['lead_data_list'] = $this->leadsModel->getLeadDataForLising(); @@ -331,13 +328,13 @@ class LeadsController extends BaseController $isFromDashboard = $this->request->getPost("is_dashboard"); - if (isset($isFromDashboard) && !empty($isFromDashboard) && $isFromDashboard == 1) { + if (isset($isFromDashboard) && ! empty($isFromDashboard) && $isFromDashboard == 1) { $ids = $this->request->getPost('ids'); $ids = array_filter(explode(',', $ids)); - if (!empty($ids)) { + if (! empty($ids)) { $idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers - $where = "leads.id IN ($idsStr)"; + $where = "leads.id IN ($idsStr)"; } else { $where = '1 = 0'; // No valid IDs, return empty result } @@ -350,11 +347,10 @@ class LeadsController extends BaseController $where = []; foreach ($search_data as $search_objects => $key) { if ($key != null && $key != '' && $key != 0 && $search_objects != 'is_dashboard') { - if($search_objects == 'status') - { - $where[('leads.'.$search_objects)] = $key; - }else{ - $where[$search_objects] = $key; + if ($search_objects == 'status') { + $where[('leads.' . $search_objects)] = $key; + } else { + $where[$search_objects] = $key; } } } @@ -369,98 +365,98 @@ class LeadsController extends BaseController public function createLead() { - $id = $this->request->getPost('id'); + $id = $this->request->getPost('id'); $actual_lead_id = $this->request->getPost('actual_lead_id'); - $actual_lead_id = !empty($actual_lead_id) ? $actual_lead_id : null; - $postData = $this->request->getPost(); - $data = $this->prepareLeadData(); - $rules = [ + $actual_lead_id = ! empty($actual_lead_id) ? $actual_lead_id : null; + $postData = $this->request->getPost(); + $data = $this->prepareLeadData(); + $rules = [ - 'lead_type' => [ + 'lead_type' => [ 'rules' => 'integer', - 'errors' => ['required' => 'Opportunity Type is required'] + 'errors' => ['required' => 'Opportunity Type is required'], ], - 'issuer' => [ + 'issuer' => [ 'rules' => 'required', - 'errors' => ['required' => 'Issuer is required'] + 'errors' => ['required' => 'Issuer is required'], ], - 'entity_type_id' => [ + 'entity_type_id' => [ 'rules' => 'required', - 'errors' => ['required' => 'Entity Type is required'] + 'errors' => ['required' => 'Entity Type is required'], ], - 'client_name' => [ + 'client_name' => [ 'rules' => 'required|regex_match[/^[a-zA-Z0-9_ -]+$/]', 'errors' => [ 'required' => 'Client Name is required', - 'regex_match' => 'Client Name only letters, numbers, space, hyphens and underscores are allowed' - ] + 'regex_match' => 'Client Name only letters, numbers, space, hyphens and underscores are allowed', + ], ], - 'client_short_name' => [ + 'client_short_name' => [ 'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]', - 'errors' => ['required' => 'Client Short Name is required','regex_match' => 'Client Short Name only letters, numbers, hyphens and underscores are allowed'] + 'errors' => ['required' => 'Client Short Name is required', 'regex_match' => 'Client Short Name only letters, numbers, hyphens and underscores are allowed'], ], - 'gst' => [ + 'gst' => [ 'rules' => 'required|regex_match[/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/]', 'errors' => [ 'required' => 'GST Number is required.', - 'regex_match' => 'Invalid GST format. Example: 22AAAAA0000A1Z5' - ] + 'regex_match' => 'Invalid GST format. Example: 22AAAAA0000A1Z5', + ], ], - 'branch_name' => [ + 'branch_name' => [ 'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]|min_length[3]', 'errors' => [ 'required' => 'Branch Name is required.', 'regex_match' => 'Branch Name can only contain letters, numbers, spaces, hyphens and underscores..', - 'min_length' => 'Branch Name must be at least 3 characters long.' - ] + 'min_length' => 'Branch Name must be at least 3 characters long.', + ], ], - 'branch_code' => [ + 'branch_code' => [ 'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]', 'errors' => [ 'required' => 'Branch Code is required.', - 'regex_match' => 'Branch Code can only contain letters, numbers, hyphens and underscores..' - ] + 'regex_match' => 'Branch Code can only contain letters, numbers, hyphens and underscores..', + ], ], - 'contact_person_name' => [ + 'contact_person_name' => [ 'rules' => 'required|regex_match[/^[a-zA-Z0-9_ -]+$/]', 'errors' => [ 'required' => 'Contact Person Name is required', - 'regex_match' => 'Contact person name only letters, numbers and spaces, hyphens and underscores..' - ] + 'regex_match' => 'Contact person name only letters, numbers and spaces, hyphens and underscores..', + ], ], 'contact_person_mobile' => [ 'rules' => 'required', 'rules' => 'required|exact_length[10]|regex_match[/^[0-9]+$/]', 'errors' => [ - 'required' => 'Contact Person Mobile is required' , - 'regex_match' => 'Contact Person Mobile Only numbers', - 'exact_length'=> 'Contact Person Mobile must be exactly 10 digits long.' - ] + 'required' => 'Contact Person Mobile is required', + 'regex_match' => 'Contact Person Mobile Only numbers', + 'exact_length' => 'Contact Person Mobile must be exactly 10 digits long.', + ], ], - 'contact_person_email' => [ + 'contact_person_email' => [ 'rules' => 'required|regex_match[/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/]', 'errors' => [ 'required' => 'Contact Person Email address is required.', - 'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).' - ] + 'regex_match' => 'Please enter a valid email format (e.g., name@domain.com).', + ], // 'rules' => 'required|valid_email|regex_match[/^[a-zA-Z0-9_-]+$/]', - // 'regex_match' => 'Contact Person Email Only letters, numbers and characters _ - @ . are allowed' - + // 'regex_match' => 'Contact Person Email Only letters, numbers and characters _ - @ . are allowed' + ], - 'salse_person_id' => [ + 'salse_person_id' => [ 'rules' => 'required', - 'errors' => ['required' => 'Sales Person is required'] + 'errors' => ['required' => 'Sales Person is required'], ], - 'status' => [ + 'status' => [ 'rules' => 'required', - 'errors' => ['required' => 'Status is required'] + 'errors' => ['required' => 'Status is required'], ], - 'next_reminder_date' => [ + 'next_reminder_date' => [ 'label' => 'Next Reminder Date', 'rules' => 'permit_empty|valid_date[d/m/Y]', 'errors' => [ - 'valid_date' => 'The {field} must be in the format DD/MM/YYYY.' - ] + 'valid_date' => 'The {field} must be in the format DD/MM/YYYY.', + ], ], ]; @@ -471,75 +467,75 @@ class LeadsController extends BaseController 'label' => 'Document Name', 'rules' => 'permit_empty|regex_match[/^[a-zA-Z0-9_\- ]+$/]', 'errors' => [ - 'regex_match' => 'Document Name in {field} can only contain letters, numbers, hyphens, and underscores.' - ] + 'regex_match' => 'Document Name in {field} can only contain letters, numbers, hyphens, and underscores.', + ], ]; } } // print_r($rules); die; - if ((int)$this->request->getPost('lead_form_type') === 2) { + if ((int) $this->request->getPost('lead_form_type') === 2) { $rules['client_type'] = [ 'rules' => 'required', - 'errors' => ['required' => 'Client Type is required'] + 'errors' => ['required' => 'Client Type is required'], ]; $rules['policy_type_id'] = [ 'rules' => 'required', - 'errors' => ['required' => 'Policy Type is required'] + 'errors' => ['required' => 'Policy Type is required'], ]; $rules['policy_start_date'] = [ 'rules' => 'required', - 'errors' => ['required' => 'Date of Commencement is required'] + 'errors' => ['required' => 'Date of Commencement is required'], ]; $rules['policy_end_date'] = [ 'rules' => 'required', - 'errors' => ['required' => 'Date of Expiry is required'] + 'errors' => ['required' => 'Date of Expiry is required'], ]; - if ((int)$this->request->getPost('claim_history') === 1) { - $rules['first_year.*'] = [ - 'rules' => 'required|regex_match[/^\d{4}-\d{4}$/]', - 'errors' => ['required' => 'Claim Year is required for all entries.','regex_match' => 'Year must be in format YYYY-YYYY.'] - ]; - $rules['first_policy_type_.*'] = [ - 'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]', - 'errors' => ['required' => 'Policy Type is required in Claim History.', - 'regex_match' => 'Policy Type only letters, numbers, space, hyphens and underscores are allowed' - ] - ]; - $rules['first_date_of_loss_.*'] = [ - 'rules' => 'required|regex_match[/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/]', - 'errors' => ['required' => 'Date of Loss is required.', - 'regex_match' => 'Date of Loss must be inValid format.'] - ]; - $rules['first_cause_of_loss.*'] = [ - 'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]', - 'errors' => [ - 'required' => 'Cause of Loss is required.', - 'regex_match' => 'Cause of Loss only letters, numbers, space, hyphens and underscores are allowed' - ] - ]; - $rules['first_claim_amount.*'] = [ - 'rules' => 'required|numeric', - 'errors' => [ - 'required' => 'Claim Amount is required.', - 'numeric' => 'Claim Amount must be a number.' - ] - ]; - $rules['first_settled_amount.*'] = [ - 'rules' => 'required|numeric', - 'errors' => ['required' => 'Settled Amount is required.', - 'numeric' => 'Settled Amount must be a number.'] - ]; - $rules['first_claim_status.*'] = [ - 'rules' => 'required|alpha_space', - 'errors' => [ - 'required' => 'Claim Status is required.', - 'alpha_space' => 'Claim Status should only contain letters and spaces.' - ] - ]; - } + if ((int) $this->request->getPost('claim_history') === 1) { + $rules['first_year.*'] = [ + 'rules' => 'required|regex_match[/^\d{4}-\d{4}$/]', + 'errors' => ['required' => 'Claim Year is required for all entries.', 'regex_match' => 'Year must be in format YYYY-YYYY.'], + ]; + $rules['first_policy_type_.*'] = [ + 'rules' => 'required|regex_match[/^[a-zA-Z0-9_-]+$/]', + 'errors' => ['required' => 'Policy Type is required in Claim History.', + 'regex_match' => 'Policy Type only letters, numbers, space, hyphens and underscores are allowed', + ], + ]; + $rules['first_date_of_loss_.*'] = [ + 'rules' => 'required|regex_match[/^[0-9]{2}-[0-9]{2}-[0-9]{4}$/]', + 'errors' => ['required' => 'Date of Loss is required.', + 'regex_match' => 'Date of Loss must be inValid format.'], + ]; + $rules['first_cause_of_loss.*'] = [ + 'rules' => 'required|regex_match[/^[a-zA-Z0-9\s_-]+$/]', + 'errors' => [ + 'required' => 'Cause of Loss is required.', + 'regex_match' => 'Cause of Loss only letters, numbers, space, hyphens and underscores are allowed', + ], + ]; + $rules['first_claim_amount.*'] = [ + 'rules' => 'required|numeric', + 'errors' => [ + 'required' => 'Claim Amount is required.', + 'numeric' => 'Claim Amount must be a number.', + ], + ]; + $rules['first_settled_amount.*'] = [ + 'rules' => 'required|numeric', + 'errors' => ['required' => 'Settled Amount is required.', + 'numeric' => 'Settled Amount must be a number.'], + ]; + $rules['first_claim_status.*'] = [ + 'rules' => 'required|alpha_space', + 'errors' => [ + 'required' => 'Claim Status is required.', + 'alpha_space' => 'Claim Status should only contain letters and spaces.', + ], + ]; + } } @@ -548,11 +544,11 @@ class LeadsController extends BaseController // foreach ($allFiles as $inputName => $files) { // // If it's a single file, wrap it in an array to use the same logic // $fileArray = is_array($files) ? $files : [$files]; - + // foreach ($fileArray as $index => $file) { // if ($file->isValid() && !$file->hasMoved()) { // $extension = strtolower($file->getExtension()); - + // // Logic: index 0 is Excel only, others are mixed // if ($index === 0) { // $allowed = ['xls', 'xlsx']; @@ -574,7 +570,6 @@ class LeadsController extends BaseController // } // } // } - $isValid = $this->validate($rules); @@ -582,47 +577,44 @@ class LeadsController extends BaseController $end_dates = $this->request->getPost('policy_end_date'); if ($start_dates && $end_dates) { - + $starts = is_array($start_dates) ? $start_dates : [$start_dates]; - $ends = is_array($end_dates) ? $end_dates : [$end_dates]; + $ends = is_array($end_dates) ? $end_dates : [$end_dates]; foreach ($starts as $index => $s_date) { $e_date = $ends[$index] ?? null; if ($s_date && $e_date) { - + $f_start = change_date_format($s_date, 'd/m/Y', 'Y-m-d'); $f_end = change_date_format($e_date, 'd/m/Y', 'Y-m-d'); if ($f_start && $f_end && ($f_end < $f_start)) { $isValid = false; - + // Determine the error key name // If it's an array, we use index (e.g., policy_end_date.0) $errorKey = is_array($start_dates) ? "policy_end_date.$index" : "policy_end_date"; - + $this->validator->setError($errorKey, 'Date of Expiry cannot be before Date of Commencement.'); } } } } - - if (!$isValid) { + if (! $isValid) { return $this->response->setStatusCode(400)->setJSON([ - 'status' => false, + 'status' => false, 'message' => 'Input validation failed', - 'code' => 400, - 'errors' => $this->validator->getErrors() + 'code' => 400, + 'errors' => $this->validator->getErrors(), ]); } - // print_r($data); die; - - if (!$id) { + if (! $id) { return $this->insertNewLead($data); } else { return $this->updateOldLead($id, $data); @@ -631,25 +623,23 @@ class LeadsController extends BaseController private function prepareLeadData() { - - $request_data = $this->request->getPost(); - print_r($request_data);die; - $data = sanitizeInputArrayAdvanced($request_data); - + + $request_data = $this->request->getPost(); + $data = sanitizeInputArrayAdvanced($request_data); $data['client_type'] = 1; - $data['pan'] = ""; + $data['pan'] = ""; if ($data['lead_type'] != 1) { - $client_data = $this->clientModel->where('id', $data['client_id'])->where('is_active', 1)->first(); - $data['client_name'] = $client_data['client_name']; + $client_data = $this->clientModel->where('id', $data['client_id'])->where('is_active', 1)->first(); + $data['client_name'] = $client_data['client_name']; $data['client_short_name'] = $client_data['short_name']; - $data['entity_type_id'] = $client_data['entity_type_id']; - $data['client_type'] = $client_data['client_type']; + $data['entity_type_id'] = $client_data['entity_type_id']; + $data['client_type'] = $client_data['client_type']; } else { - if(!empty($data['client_id'])){ + if (! empty($data['client_id'])) { $data['is_client_created'] = $data['client_id']; - }else{ - $data['client_id'] = 0; + } else { + $data['client_id'] = 0; $data['client_branch_id'] = 0; $data['source_policy_id'] = 0; } @@ -673,14 +663,14 @@ class LeadsController extends BaseController private function prepareSingleLeadData($data) { // print_r($data); die; - $index_plus_one = 1; - $form_file_name = "file_name_" . $index_plus_one; - $form_docs_name = "docs_name_" . $index_plus_one; + $index_plus_one = 1; + $form_file_name = "file_name_" . $index_plus_one; + $form_docs_name = "docs_name_" . $index_plus_one; $leads_file_primary_key = $data['leads_file_id'] ?? []; $multi_file_data = []; if (isset($data[$form_docs_name])) { - $files = $this->request->getFileMultiple($form_file_name); + $files = $this->request->getFileMultiple($form_file_name); $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key); } @@ -689,10 +679,10 @@ class LeadsController extends BaseController list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer']); } else { $insurer_branch_id = 0; - $insurer_id = 0; + $insurer_id = 0; } - $data['insurer_id'] = $insurer_id; + $data['insurer_id'] = $insurer_id; $data['insurer_branch_id'] = $insurer_branch_id; // Separate the insurer and insurer branch, handle missing or invalid data @@ -700,21 +690,20 @@ class LeadsController extends BaseController list($tpa_branch_id, $tpa_id) = explode('-', $data['tpa']); } else { $tpa_branch_id = 0; - $tpa_id = 0; + $tpa_id = 0; } - $data['tpa_id'] = $tpa_id; + $data['tpa_id'] = $tpa_id; $data['tpa_branch_id'] = $tpa_branch_id; - - if (!empty($data['policy_start_date'])) { - $data['policy_start_date'] = change_date_format($data['policy_start_date']); + if (! empty($data['policy_start_date'])) { + $data['policy_start_date'] = change_date_format($data['policy_start_date']); } else { $data['policy_start_date'] = null; } - if (!empty($data['policy_end_date'])) { - $data['policy_end_date'] = change_date_format($data['policy_end_date']); + if (! empty($data['policy_end_date'])) { + $data['policy_end_date'] = change_date_format($data['policy_end_date']); } else { $data['policy_end_date'] = null; } @@ -735,26 +724,26 @@ class LeadsController extends BaseController foreach ($data['policy_type_id'] as $index => $value) { - $index_plus_one = $index + 1; - $form_file_name = "file_name_" . $index_plus_one; - $form_docs_name = "docs_name_" . $index_plus_one; + $index_plus_one = $index + 1; + $form_file_name = "file_name_" . $index_plus_one; + $form_docs_name = "docs_name_" . $index_plus_one; $leads_file_primary_key = $data['leads_file_id'] ?? []; - $files = $this->request->getFileMultiple($form_file_name); - $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key); + $files = $this->request->getFileMultiple($form_file_name); + $multi_file_data = $this->uploadMultiFiles($files, $data[$form_docs_name], $leads_file_primary_key); // Separate the insurer and insurer branch, handle missing or invalid data if (isset($data['insurer'][$index]) && strpos($data['insurer'][$index], '-') !== false) { list($insurer_branch_id, $insurer_id) = explode('-', $data['insurer'][$index]); } else { $insurer_branch_id = 0; - $insurer_id = 0; + $insurer_id = 0; } // Separate the insurer and insurer branch, handle missing or invalid data if (isset($data['tpa'][$index]) && strpos($data['tpa'][$index], '-') !== false) { list($tpa_branch_id, $tpa_id) = explode('-', $data['tpa'][$index]); } else { $tpa_branch_id = 0; - $tpa_id = 0; + $tpa_id = 0; } // Separate the insurer and insurer branch, handle missing or invalid data @@ -762,7 +751,7 @@ class LeadsController extends BaseController list($proposed_insurer_branch_id, $proposed_insurer_id) = explode('-', $data['proposed_insurer'][$index]); } else { $proposed_insurer_branch_id = 0; - $proposed_insurer_id = 0; + $proposed_insurer_id = 0; } // Separate the TPA and TPA branch, handle missing or invalid data @@ -770,23 +759,23 @@ class LeadsController extends BaseController list($proposed_tpa_branch_id, $proposed_tpa_id) = explode('-', $data['proposed_tpa'][$index]); } else { $proposed_tpa_branch_id = 0; - $proposed_tpa_id = 0; + $proposed_tpa_id = 0; } - if (!empty($data['policy_start_date'][$index])) { - $policy_start_date = change_date_format($data['policy_start_date'][$index], 'd/m/Y', 'Y-m-d'); + if (! empty($data['policy_start_date'][$index])) { + $policy_start_date = change_date_format($data['policy_start_date'][$index], 'd/m/Y', 'Y-m-d'); } else { $policy_start_date = null; } - if (!empty($data['policy_end_date'][$index])) { - $policy_end_date = change_date_format($data['policy_end_date'][$index], 'd/m/Y', 'Y-m-d'); + if (! empty($data['policy_end_date'][$index])) { + $policy_end_date = change_date_format($data['policy_end_date'][$index], 'd/m/Y', 'Y-m-d'); } else { $policy_end_date = null; } - if (!empty($data['incurred_claim_date'][$index])) { - $incurred_claims_date = change_date_format($data['incurred_claim_date'][$index], 'd/m/Y', 'Y-m-d'); + if (! empty($data['incurred_claim_date'][$index])) { + $incurred_claims_date = change_date_format($data['incurred_claim_date'][$index], 'd/m/Y', 'Y-m-d'); } else { $incurred_claims_date = null; } @@ -797,14 +786,14 @@ class LeadsController extends BaseController // $premium_date = null; // } - if (!empty($data['source_policy_start_date']) && $data['lead_type'] == 2) { - $data['source_policy_start_date'] = change_date_format($data['source_policy_start_date'], 'd/m/Y', 'Y-m-d'); + if (! empty($data['source_policy_start_date']) && $data['lead_type'] == 2) { + $data['source_policy_start_date'] = change_date_format($data['source_policy_start_date'], 'd/m/Y', 'Y-m-d'); } else { $data['source_policy_start_date'] = null; } - if (!empty($data['source_policy_end_date']) && $data['lead_type'] == 2) { - $data['source_policy_end_date'] = change_date_format($data['source_policy_end_date'], 'd/m/Y', 'Y-m-d'); + if (! empty($data['source_policy_end_date']) && $data['lead_type'] == 2) { + $data['source_policy_end_date'] = change_date_format($data['source_policy_end_date'], 'd/m/Y', 'Y-m-d'); } else { $data['source_policy_end_date'] = null; } @@ -814,7 +803,7 @@ class LeadsController extends BaseController $reminderDate = trim($data['next_reminder_date'] ?? ''); if ($reminderDate !== '' && $reminderDate != null && $reminderDate != 0) { - $convertedDate = change_date_format($reminderDate); + $convertedDate = change_date_format($reminderDate); $data['next_reminder_date'] = $convertedDate ?: null; } else { $data['next_reminder_date'] = null; @@ -854,63 +843,62 @@ class LeadsController extends BaseController 'source_policy_id' => $data['source_policy_id'] ?? 0, 'policy_type_id' => $value, 'salse_person_id' => $data['salse_person_id'] ?? 0, + 'insurer_id' => $insurer_id ?? 0, + 'insurer_branch_id' => $insurer_branch_id ?? 0, + 'tpa_id' => $tpa_id ?? 0, + 'tpa_branch_id' => $tpa_branch_id ?? 0, + 'policy_start_date' => $policy_start_date, + 'policy_end_date' => $policy_end_date, + 'no_of_lives' => $data['no_of_lives'][$index] ?? null, + 'incurred_claims' => $data['incurred_claims'][$index] ?? 0, + 'location' => $data['location'][$index] ?? null, + 'proposed_insurer_id' => $proposed_insurer_id ?? 0, + 'proposed_insurer_branch_id' => $proposed_insurer_branch_id ?? 0, + 'proposed_tpa_id' => $proposed_tpa_id ?? 0, + 'proposed_tpa_branch_id' => $proposed_tpa_branch_id ?? 0, - 'insurer_id' => $insurer_id ?? 0, - 'insurer_branch_id' => $insurer_branch_id ?? 0, - 'tpa_id' => $tpa_id ?? 0, - 'tpa_branch_id' => $tpa_branch_id ?? 0, - 'policy_start_date' => $policy_start_date, - 'policy_end_date' => $policy_end_date, - 'no_of_lives' => $data['no_of_lives'][$index] ?? null, - 'incurred_claims' => $data['incurred_claims'][$index] ?? 0, - 'location' => $data['location'][$index] ?? null, - 'proposed_insurer_id' => $proposed_insurer_id ?? 0, - 'proposed_insurer_branch_id' => $proposed_insurer_branch_id ?? 0, - 'proposed_tpa_id' => $proposed_tpa_id ?? 0, - 'proposed_tpa_branch_id' => $proposed_tpa_branch_id ?? 0, + 'renewal_emp_count' => $data['renewal_emp_count'][$index] ?? 0, + 'renewal_dept_count' => $data['renewal_dept_count'][$index] ?? 0, + 'renewal_no_of_lives' => $data['renewal_no_of_lives'][$index] ?? 0, + 'incept_emp_count' => $data['incept_emp_count'][$index] ?? 0, + 'incept_dept_count' => $data['incept_dept_count'][$index] ?? 0, + 'incept_no_of_lives' => $data['incept_no_of_lives'][$index] ?? 0, + 'exp_emp_count' => $data['exp_emp_count'][$index] ?? 0, + 'exp_dept_count' => $data['exp_dept_count'][$index] ?? 0, + 'exp_no_of_lives' => $data['exp_no_of_lives'][$index] ?? 0, - 'renewal_emp_count' => $data['renewal_emp_count'][$index] ?? 0, - 'renewal_dept_count' => $data['renewal_dept_count'][$index] ?? 0, - 'renewal_no_of_lives' => $data['renewal_no_of_lives'][$index] ?? 0, - 'incept_emp_count' => $data['incept_emp_count'][$index] ?? 0, - 'incept_dept_count' => $data['incept_dept_count'][$index] ?? 0, - 'incept_no_of_lives' => $data['incept_no_of_lives'][$index] ?? 0, - 'exp_emp_count' => $data['exp_emp_count'][$index] ?? 0, - 'exp_dept_count' => $data['exp_dept_count'][$index] ?? 0, - 'exp_no_of_lives' => $data['exp_no_of_lives'][$index] ?? 0, + 'incurred_claims_date' => $incurred_claims_date, + 'paid_claims' => $data['paid_claims'][$index] ?? 0, + 'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0, + 'policy_run_days' => $data['policy_run_days'][$index] ?? 0, + 'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0, + 'premium_date' => $data['premium_date'][$index] ?? 0, + 'earned_premium' => $data['earned_premium'][$index] ?? 0, + 'annualised_claims' => $data['annualised_claims'][$index] ?? 0, + 'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0, + 'earned_claims_ratio' => $data['earned_claims_ratio'][$index] ?? 0, + 'total_si_at_incept' => $data['total_si_at_incept'][$index] ?? 0, + 'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0, - 'incurred_claims_date' => $incurred_claims_date, - 'paid_claims' => $data['paid_claims'][$index] ?? 0, - 'outstanding_claims' => $data['outstanding_claims'][$index] ?? 0, - 'policy_run_days' => $data['policy_run_days'][$index] ?? 0, - 'premium_at_inception' => $data['premium_at_inception'][$index] ?? 0, - 'premium_date' => $data['premium_date'][$index] ?? 0, - 'earned_premium' => $data['earned_premium'][$index] ?? 0, - 'annualised_claims' => $data['annualised_claims'][$index] ?? 0, - 'incurred_claims_ratio' => $data['incurred_claims_ratio'][$index] ?? 0, - 'earned_claims_ratio' => $data['earned_claims_ratio'][$index] ?? 0, - 'total_si_at_incept' => $data['total_si_at_incept'][$index] ?? 0, - 'total_si_at_renewal' => $data['total_si_at_renewal'][$index] ?? 0, - - 'total_lives_at_incept' => $data['total_lives_at_incept'][$index] ?? 0, - 'premium_at_incept' => $data['premium_at_incept'][$index] ?? 0, - 'fin_years_claims' => $last_3_years_claims, + 'total_lives_at_incept' => $data['total_lives_at_incept'][$index] ?? 0, + 'premium_at_incept' => $data['premium_at_incept'][$index] ?? 0, + 'fin_years_claims' => $last_3_years_claims, // 'file_name' => $file_name, - 'multi_file_data' => $multi_file_data ?? null, + 'multi_file_data' => $multi_file_data ?? null, - 'status' => $data['status'] ?? null, - 'notes' => $data['notes'] ?? null, + 'status' => $data['status'] ?? null, + 'notes' => $data['notes'] ?? null, - 'lead_form_type' => $data['lead_form_type'] ?? 1, - 'custom_fields' => $data['custom_fields'] ?? null, + 'lead_form_type' => $data['lead_form_type'] ?? 1, + 'custom_fields' => $data['custom_fields'] ?? null, - 'source_policy_start_date' => $data['source_policy_start_date'] ?? null, - 'source_policy_end_date' => $data['source_policy_end_date'] ?? null, - 'claim_history' => $data['claim_history'] ?? 0, + 'source_policy_start_date' => $data['source_policy_start_date'] ?? null, + 'source_policy_end_date' => $data['source_policy_end_date'] ?? null, + 'claim_history' => $data['claim_history'] ?? 0, - 'next_reminder_date' => $data['next_reminder_date'] ?? null, - 'is_insurer_auto_mail' => $data['is_insurer_auto_mail'] ?? 0 + 'next_reminder_date' => $data['next_reminder_date'] ?? null, + 'is_insurer_auto_mail' => $data['is_insurer_auto_mail'] ?? 0, ]; } // print_r($processedData);die(); @@ -932,7 +920,7 @@ class LeadsController extends BaseController if ($value['lead_form_type'] == 1) { //for this push the job to the calculateMembersDemography() function - $job_details = new Jobs(); + $job_details = new Jobs(); // $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [ // 'lead_id' => $insert, // ]]); @@ -969,26 +957,25 @@ class LeadsController extends BaseController ->where('leads.is_active', 1) ->first(); - $data['lead_edit_data'] = $this->leadsModel + $data['lead_edit_data'] = $this->leadsModel ->where('leads.id', $id) ->where('leads.is_active', 1) ->first(); - - if (!empty($data['policy_start_date'])) { - $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y'); + if (! empty($data['policy_start_date'])) { + $data['policy_start_date'] = change_date_format($data['policy_start_date'], 'Y-m-d', 'd/m/Y'); } else { $data['policy_start_date'] = null; } - if (!empty($data['policy_end_date'])) { - $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y'); + if (! empty($data['policy_end_date'])) { + $data['policy_end_date'] = change_date_format($data['policy_end_date'], 'Y-m-d', 'd/m/Y'); } else { $data['policy_end_date'] = null; } - if (!empty($data['incurred_claims_date'])) { - $data['incurred_claims_date'] = change_date_format($data['incurred_claims_date'], 'Y-m-d', 'd/m/Y'); + if (! empty($data['incurred_claims_date'])) { + $data['incurred_claims_date'] = change_date_format($data['incurred_claims_date'], 'Y-m-d', 'd/m/Y'); } else { $data['incurred_claims_date'] = null; } @@ -1000,17 +987,17 @@ class LeadsController extends BaseController // } $data['multi_file_data'] = $this->leadFilesModel - ->where('lead_id', $id) - ->where('type !=', 2) - ->where('is_active', 1) - ->first() ?? null; + ->where('lead_id', $id) + ->where('type !=', 2) + ->where('is_active', 1) + ->first() ?? null; $data['lastFiveYears'] = $this->getLastFiveFinancialYears(); - $data['gpaClaimType'] = $this->claim_type_for_gpa; - $data['causeOfDeath'] = $this->cause_of_death; + $data['gpaClaimType'] = $this->claim_type_for_gpa; + $data['causeOfDeath'] = $this->cause_of_death; - if (!empty($data['fin_years_claims'])) { - $decoded = json_decode($data['fin_years_claims'], true); + if (! empty($data['fin_years_claims'])) { + $decoded = json_decode($data['fin_years_claims'], true); $data['lead_edit_data']['fin_years_claims_array'] = isset($decoded['finyear']) ? $decoded['finyear'] : []; } else { $data['lead_edit_data']['fin_years_claims_array'] = []; @@ -1031,24 +1018,24 @@ class LeadsController extends BaseController { $statusData = [ 'policy_tran_id' => $primaryKey, - 'status' => $status, - 'status_type' => $statusType, - 'created_by' => get_session_userid(), + 'status' => $status, + 'status_type' => $statusType, + 'created_by' => get_session_userid(), ]; $this->policyTransactionStatusModel->insert($statusData); } public function uploadMultiFiles($files, $docs_names, $primaryKey) - { + { $uploadFilePath = WRITEPATH . 'uploads/lead_files/'; $multi_file_data = []; foreach ($files as $index => $value) { - $file_name = file_Upload_for_lead($value, $uploadFilePath, UPLOAD_EXT_LEAD_FILES); + $file_name = file_Upload_for_lead($value, $uploadFilePath, UPLOAD_EXT_LEAD_FILES); $multi_file_data[] = [ 'file_name' => $file_name, 'docs_name' => $docs_names[$index], - 'id' => $primaryKey[$index] ?? "", + 'id' => $primaryKey[$index] ?? "", ]; } @@ -1059,27 +1046,27 @@ class LeadsController extends BaseController { log_message('info', 'insertMultiFilesData() called with lead_id: ' . $lead_id); - if (!empty($data)) { + if (! empty($data)) { log_message('info', 'Data is not empty. Total items: ' . count($data)); foreach ($data as $key => $value) { log_message('info', "Processing item at index {$key}: " . json_encode($value)); - if (!empty($value['id'])) { + if (! empty($value['id'])) { log_message('info', "Record with ID {$value['id']} exists. Preparing to update."); $lead_file_data = [ - 'lead_id' => $lead_id, + 'lead_id' => $lead_id, 'docs_name' => $value['docs_name'], ]; - if (!empty($value['file_name'])) { + if (! empty($value['file_name'])) { $lead_file_data['file_name'] = $value['file_name']; log_message('info', "file_name found: {$value['file_name']}"); - if (!empty($lead_form_type) && $lead_form_type == 1 && $key == 0) { + if (! empty($lead_form_type) && $lead_form_type == 1 && $key == 0) { //for this push the job to the calculateMembersDemography() function - $job_details = new Jobs(); + $job_details = new Jobs(); // $r = Jobs::addJob(['job_name' => 'memberDataListExcelFileFormatValidation', 'payload' => [ // 'lead_id' => $lead_id, // ]]); @@ -1095,9 +1082,9 @@ class LeadsController extends BaseController } else { log_message('info', "No ID found. Preparing to insert new record."); - if (!empty($value['file_name'])) { + if (! empty($value['file_name'])) { $lead_file_data = [ - 'lead_id' => $lead_id, + 'lead_id' => $lead_id, 'docs_name' => $value['docs_name'], 'file_name' => $value['file_name'], ]; @@ -1109,7 +1096,7 @@ class LeadsController extends BaseController } } - if ($key == 0 && !empty($value['file_name'])) { + if ($key == 0 && ! empty($value['file_name'])) { log_message('info', "Setting first file_name '{$value['file_name']}' to leadsModel for lead_id: {$lead_id}"); $this->leadsModel->where('id', $lead_id)->set('file_name', $value['file_name'])->update(); } @@ -1125,7 +1112,7 @@ class LeadsController extends BaseController public function removeMultiFile() { $id = $this->request->getGet('lead_file_id'); - if (!empty($id)) { + if (! empty($id)) { $this->leadFilesModel->where('id', $id)->set(['is_active' => 0])->update(); return $this->respond(['status' => true, 'message' => 'File removed successfully'], 200); } else { @@ -1163,10 +1150,10 @@ class LeadsController extends BaseController // $data['lead_id'] = $id; // $lead_data = $this->leadsModel // ->select(' - // leads.*, - // policy_type.question_json, + // leads.*, + // policy_type.question_json, // policy_type.policy_type, - // policy_type.long_name, + // policy_type.long_name, // user_profiles.email as created_person_email // ') // ->join('policy_type', 'leads.policy_type_id = policy_type.id') @@ -1193,7 +1180,6 @@ class LeadsController extends BaseController // $data['tpa_list'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); // $data['account_manager'] = $this->userModel->where('is_active', 1)->where('role', 3)->findAll(); - // $mail_content = ' //

Dear Sir,

//

Greetings From Nhance India!

@@ -1298,10 +1284,10 @@ class LeadsController extends BaseController // 3. Optimize lead data query with specific field selection $lead_data = $this->leadsModel ->select(' - leads.*, + leads.*, lead_files.status as demography_file_status, - policy_type.question_json, - policy_type.policy_type, + policy_type.question_json, + policy_type.policy_type, policy_type.long_name, user_profiles.email as created_person_email ') @@ -1312,7 +1298,7 @@ class LeadsController extends BaseController ->where('leads.is_active', 1) ->first(); - if (!$lead_data) { + if (! $lead_data) { // Handle case where lead doesn't exist throw new \Exception('Opportunity not found'); } @@ -1336,38 +1322,38 @@ class LeadsController extends BaseController } // 5. Cache decoded JSON to avoid multiple decodes - $question_json_decoded = !empty($lead_data['question_json']) + $question_json_decoded = ! empty($lead_data['question_json']) ? json_decode($lead_data['question_json'], true) : null; $data['question_json'] = $lead_data['question_json']; - $data['tab_name'] = $type == 2 ? 'QCR' : 'RFQ'; - $data['page_name'] = $type == 2 ? 'QCR' : 'RFQ'; - $data['lead_data'] = $lead_data; + $data['tab_name'] = $type == 2 ? 'QCR' : 'RFQ'; + $data['page_name'] = $type == 2 ? 'QCR' : 'RFQ'; + $data['lead_data'] = $lead_data; // 6. Parallel/batch data fetching for independent queries - $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); - $data['userList'] = $this->userModel->getUserListForRFQ(); + $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); + $data['userList'] = $this->userModel->getUserListForRFQ(); $data['exclusiveUserList'] = $this->userModel->getexclusiveUserListForRFQ(); - $data['tpa_list'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); - $data['account_manager'] = $this->userModel + $data['tpa_list'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); + $data['account_manager'] = $this->userModel ->where('is_active', 1) ->where('role', 3) ->findAll(); // 7. Define mail templates as constants or config - $mail_content = $this->getMailTemplate(); + $mail_content = $this->getMailTemplate(); $placement_mail_content = $this->getMailTemplate('placement'); - $subject = $this->getSubjectTemplate($lead_data); + $subject = $this->getSubjectTemplate($lead_data); // 8. Pre-calculate sum assured only for GPA $data['totalSumAssured'] = ($lead_data['policy_type_id'] == 1) ? $this->handleMemberDataGPATotalSumInsurerFromExcel(['lead_id' => $id]) : []; // 9. Transform mail content once - $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); - $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); + $data['mail_content'] = $this->transformMailContent($lead_data, $mail_content, $data['page_name']); + $data['subject'] = $this->transformMailContent($lead_data, $subject, $data['page_name']); $data['placement_mail_content'] = $this->transformMailContent($lead_data, $placement_mail_content, 'Placement'); - $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement'); + $data['placement_subject'] = $this->transformMailContent($lead_data, $subject, 'Placement'); // 10. Combine related queries $data['multi_file_data'] = $this->leadFilesModel @@ -1382,7 +1368,7 @@ class LeadsController extends BaseController ->findAll(); // 11. Generate views efficiently - $data['lead_data']['installment_data'] = !empty($installment_data['installments']) + $data['lead_data']['installment_data'] = ! empty($installment_data['installments']) ? view('rfq/installment_fields', $installment_data) : null; @@ -1406,22 +1392,22 @@ class LeadsController extends BaseController // Use cached decoded JSON if ($question_json_decoded) { - $data['policies'] = $question_json_decoded['policies'] ?? []; + $data['policies'] = $question_json_decoded['policies'] ?? []; $data["child_table_data"] = $question_json_decoded['child_table_data'] ?? []; } - $data['product'] = $lead_data['policy_type']; + $data['product'] = $lead_data['policy_type']; $data['buisness_type'] = $this->buisnessType; - $data['client_type'] = $this->clientType; + $data['client_type'] = $this->clientType; $this->loadLayout('view_rfq_non_eb', $data); } } // 13. Extract mail template to separate method for reusability - private function getMailTemplate( $template_type = "" ) - { - if($template_type == 'placement'){ + private function getMailTemplate($template_type = "") + { + if ($template_type == 'placement') { return '

Dear Sir,

Greetings From Nhance India!

@@ -1430,15 +1416,15 @@ class LeadsController extends BaseController

In case of any query, please feel free to contact us.

Thank You!


Best regards,

- +
{{LOGGED_USER_NAME}}
Mobile: {{LOGGED_USER_MOBILE}}
- + Nhance Logo '; - }else{ + } else { return '

Dear Sir,

Greetings From Nhance India!

@@ -1447,12 +1433,12 @@ class LeadsController extends BaseController

In case of any query, please feel free to contact us.

Thank You!


Best regards,

- +
{{LOGGED_USER_NAME}}
Mobile: {{LOGGED_USER_MOBILE}}
- + Nhance Logo '; } @@ -1471,7 +1457,7 @@ class LeadsController extends BaseController $data = $this->request->getPost(); - $lead_id = $data['lead_id']; + $lead_id = $data['lead_id']; $json_data = $data['registration_json']; $existingJson = $this->RFQModel->where('is_active', 1)->where("lead_id", $lead_id)->first()['registration_json'] ?? null; @@ -1484,10 +1470,9 @@ class LeadsController extends BaseController ->set('is_active', 0) ->update(); - $insertData['lead_id'] = $lead_id; + $insertData['lead_id'] = $lead_id; $insertData['registration_json'] = json_encode($json_data); - $this->RFQModel->insert($insertData); return $this->respond(['status' => true, "message" => "Policy Inforamtion saved"]); @@ -1499,26 +1484,26 @@ class LeadsController extends BaseController public function createRFQ() { - $data = $this->request->getPost(); + $data = $this->request->getPost(); $lead_id = $data['lead_id'] ?? null; - if (!$lead_id) { + if (! $lead_id) { return $this->respond(['status' => false, 'message' => 'Opportunity ID is required'], 400); } $rfq_created = $this->RFQModel->where('lead_id', $lead_id)->where('is_active', 1)->countAllResults(); $qcr_created = false; - $inputJson = json_decode($data['json'], true); - if (isset($inputJson['premium_data']) && !empty($inputJson['premium_data'])) { - $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson); + $inputJson = json_decode($data['json'], true); + if (isset($inputJson['premium_data']) && ! empty($inputJson['premium_data'])) { + $sortedJson = $this->reorderProposalsByInsurerTotal($inputJson); $data['json'] = json_encode($sortedJson); - $qcr_created = true; + $qcr_created = true; } $quote_received_insurer = []; if (($data['submit_type'] ?? "") === 'QCR') { - $inputJson = json_decode($data['json'], true); + $inputJson = json_decode($data['json'], true); $proposal_data = $inputJson['proposal_data'] ?? array_pop($inputJson); if (isset($proposal_data['over_all_column_data'])) { @@ -1527,11 +1512,11 @@ class LeadsController extends BaseController $this->myLogger->logme("error", "insurer id : " . json_encode($proposel_count)); foreach ($proposel_count as $key => $value) { - if (!empty($value['insurers'])) { + if (! empty($value['insurers'])) { $qcr_created = true; foreach ($value['insurers'] as $insurer => $id) { - if (!empty($id['id'])) { + if (! empty($id['id'])) { $quote_received_insurer[] = $id['id']; } } @@ -1544,13 +1529,13 @@ class LeadsController extends BaseController $data['type'] = 1; //update the quote received insurer data to the lead - if(count($quote_received_insurer) != 0){ + if (count($quote_received_insurer) != 0) { $this->leadsModel->update($lead_id, ['quote_received_insurer' => json_encode($quote_received_insurer ?? [])]); $this->myLogger->logme("error", "quote_received_insurer data updated in the lead: " . json_encode($quote_received_insurer)); } // Deactivate existing RFQs for this lead and type - if (!isset($data['rfq_primaryKey']) && empty($data['rfq_primaryKey'])) { + if (! isset($data['rfq_primaryKey']) && empty($data['rfq_primaryKey'])) { $this->RFQModel ->where('lead_id', $lead_id) ->where('type', 1) @@ -1568,16 +1553,16 @@ class LeadsController extends BaseController ->orderBy('id', 'DESC') ->first(); - if (!empty($latest['registration_json'])) { + if (! empty($latest['registration_json'])) { $data['registration_json'] = $latest['registration_json']; } } // print_r($data); die; // $data['json'] = ""; - if (isset($data['rfq_primaryKey']) && !empty($data['rfq_primaryKey'])) { + if (isset($data['rfq_primaryKey']) && ! empty($data['rfq_primaryKey'])) { $this->RFQModel->update($data['rfq_primaryKey'], $data); - $insertId = $data['rfq_primaryKey']; + $insertId = $data['rfq_primaryKey']; $affectedRows = db_connect()->affectedRows(); } else { // Insert new RFQ @@ -1600,28 +1585,28 @@ class LeadsController extends BaseController $message = ($data['submit_type'] ?? '') == 'QCR' ? 'QCR saved successfully' : 'RFQ saved successfully'; return $this->respond([ - 'status' => true, - 'id' => $insertId, - 'message' => $message, - 'data' => $data, + 'status' => true, + 'id' => $insertId, + 'message' => $message, + 'data' => $data, 'affectedRows' => $affectedRows ?? null, ], 200); } $message = ($data['submit_type'] ?? '') == 'QCR' ? 'Failed to save QCR' : 'Failed to save RFQ'; return $this->respond([ - 'status' => false, - 'id' => null, + 'status' => false, + 'id' => null, 'message' => $message, - 'data' => $data + 'data' => $data, ], 200); } public function createQCR() { - $data = $this->request->getPost(); - $lead_id = $data['lead_id']; + $data = $this->request->getPost(); + $lead_id = $data['lead_id']; $data['type'] = 2; $this->RFQModel @@ -1640,15 +1625,16 @@ class LeadsController extends BaseController return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create QCR", 'data' => $data], 200); } - public function reorderProposalsByInsurerTotal(array $data): array { - if (!isset($data['premium_data']['data'])) return $data; + if (! isset($data['premium_data']['data'])) { + return $data; + } - $original = $data['premium_data']['data']; - $proposals = []; - $others = []; + $original = $data['premium_data']['data']; + $proposals = []; + $others = []; $emptyKeyData = []; foreach ($original as $key => $value) { @@ -1685,7 +1671,7 @@ class LeadsController extends BaseController // Add Quote Asked back at the top $proposal = array_merge(['Quote Asked' => $quoteAsked], $proposal); } - + // Sort proposals by their insurer's total uasort($proposals, function ($a, $b) { $totalA = 0; @@ -1710,29 +1696,29 @@ class LeadsController extends BaseController // Merge back the sorted proposals into the full structure $data['premium_data']['data'] = array_merge($others, $proposals, $emptyKeyData); - $data = $this->reorderProposalDataByPremiumOrder($data); + $data = $this->reorderProposalDataByPremiumOrder($data); return $data; } private function reorderProposalDataByPremiumOrder(array $data): array { - if (!isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) { + if (! isset($data['premium_data']['data'], $data['proposal_data']['over_all_column_data'])) { return $data; } - $porposalData = $data['premium_data']['data']; - $premiumProposals = array_keys($data['premium_data']['data']); + $porposalData = $data['premium_data']['data']; + $premiumProposals = array_keys($data['premium_data']['data']); $filteredProposals = []; //Reorder the Insurer based on the Premium data insurer foreach ($porposalData as $key => $value) { - if(in_array($key, ['Particulars', ""])){ + if (in_array($key, ['Particulars', ""])) { continue; } // Ensure the premium data is an array and not empty - if (!is_array($value) || empty($value)) { + if (! is_array($value) || empty($value)) { continue; } @@ -1749,7 +1735,7 @@ class LeadsController extends BaseController // }); // Step 2: Reorder proposal insurers based on premium order - usort($data['proposal_data']['over_all_column_data'][$key]['insurers'], function($a, $b) use ($premiumOrder) { + usort($data['proposal_data']['over_all_column_data'][$key]['insurers'], function ($a, $b) use ($premiumOrder) { $posA = array_search($a['display_name'] ?? '', $premiumOrder); $posB = array_search($b['display_name'] ?? '', $premiumOrder); @@ -1772,21 +1758,21 @@ class LeadsController extends BaseController // dd($premiumProposals, $filteredProposals); $data['proposal_data']['over_all_column_data'] = $filteredProposals; - $data = $this->reorderProposalInHeaderAndData($data); + $data = $this->reorderProposalInHeaderAndData($data); return $data; } private function reorderProposalInHeaderAndData(array $data): array { - $tableData = $data['table_data']; + $tableData = $data['table_data']; $sortedProposalOrder = $data['proposal_data']['over_all_column_data']; - $headers = $tableData['headers'] ?? []; - $dataRows = $tableData['data'] ?? []; + $headers = $tableData['headers'] ?? []; + $dataRows = $tableData['data'] ?? []; // Step 1: Separate static and proposal headers - $staticHeaders = []; + $staticHeaders = []; $proposalHeaders = []; - $actionHeader = []; + $actionHeader = []; foreach ($headers as $header) { if (in_array($header['parentHeader'], array_keys($sortedProposalOrder))) { $proposalHeaders[$header['parentHeader']] = $header; @@ -1803,10 +1789,10 @@ class LeadsController extends BaseController foreach ($sortedProposalOrder as $proposalKey => $proposalData) { // Skip if insurers or subHeaders are missing if ( - !isset($proposalData['insurers']) || - !is_array($proposalData['insurers']) || - !isset($proposalHeaders[$proposalKey]['subHeaders']) || - !is_array($proposalHeaders[$proposalKey]['subHeaders']) + ! isset($proposalData['insurers']) || + ! is_array($proposalData['insurers']) || + ! isset($proposalHeaders[$proposalKey]['subHeaders']) || + ! is_array($proposalHeaders[$proposalKey]['subHeaders']) ) { continue; } @@ -1816,7 +1802,7 @@ class LeadsController extends BaseController // Add insurers in the sorted order foreach ($proposalData['insurers'] as $insurer) { - if(in_array($insurer['display_name'], $proposalHeaders[$proposalKey]['subHeaders'])){ + if (in_array($insurer['display_name'], $proposalHeaders[$proposalKey]['subHeaders'])) { $newSubHeaders[] = $insurer['display_name']; } } @@ -1838,7 +1824,7 @@ class LeadsController extends BaseController // print_rr($reorderedHeaders); die; $proposel_count = 1; foreach ($reorderedHeaders as $key => &$value) { - if(!in_array($value['parentHeader'], ["Existing Renewal", "Existing Rollover"])){ + if (! in_array($value['parentHeader'], ["Existing Renewal", "Existing Rollover"])) { $value['parentHeader'] = 'Proposal ' . $proposel_count; $proposel_count++; } @@ -1847,12 +1833,12 @@ class LeadsController extends BaseController //merge the all headers $reorderedHeaders = array_merge($staticHeaders, $reorderedHeaders, $actionHeader); - + // Step 3: Reorder each row's `data` by matching parentth foreach ($dataRows as $dataRowIndex => &$row) { - $staticData = []; + $staticData = []; $proposalData = []; - $actionData = []; + $actionData = []; foreach ($row['data'] as $entry) { if (in_array($entry['parentth'], array_keys($sortedProposalOrder))) { @@ -1875,18 +1861,18 @@ class LeadsController extends BaseController } } - $dubParTh = ""; + $dubParTh = ""; $increament = 0; foreach ($reorderedProposalData as $key => &$value) { if ($dubParTh == $value['parentth']) { - if(!in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])){ + if (! in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])) { $value['parentth'] = 'Proposal ' . ($increament); } } else { $dubParTh = $value['parentth']; - if(!in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])){ - $increament = $increament + 1; + if (! in_array($value['parentth'], ["Existing Renewal", "Existing Rollover"])) { + $increament = $increament + 1; $value['parentth'] = 'Proposal ' . ($increament); } } @@ -1896,19 +1882,18 @@ class LeadsController extends BaseController //Reorder the Row Data based on the Insurer $reorderedProposalData = $this->reorderProposalRowData($reorderedProposalData, $proposalHeaders); - // print_rr($reorderedProposalData); die; $row['data'] = array_merge($staticData, $reorderedProposalData, $actionData); } $data['table_data']['headers'] = $reorderedHeaders; - $data['table_data']['data'] = $dataRows; + $data['table_data']['data'] = $dataRows; - $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']); - $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']); - $data['proposal_data']['over_all_column_data'] = !empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data']; - $data['premium_data']['data'] = !empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data']; + $renumberedArray = $this->renumberProposalKeys($data['proposal_data']['over_all_column_data']); + $updatedDataSet = $this->renumberProposalKeys($data['premium_data']['data']); + $data['proposal_data']['over_all_column_data'] = ! empty($renumberedArray) ? $renumberedArray : $data['proposal_data']['over_all_column_data']; + $data['premium_data']['data'] = ! empty($updatedDataSet) ? $updatedDataSet : $data['premium_data']['data']; return $data; } @@ -1920,7 +1905,7 @@ class LeadsController extends BaseController // Group rows by parentth $groupedRows = []; foreach ($proposalRowData as $row) { - if (!isset($row['parentth'])) { + if (! isset($row['parentth'])) { continue; // skip invalid rows } $groupedRows[$row['parentth']][] = $row; @@ -1929,15 +1914,15 @@ class LeadsController extends BaseController // Reorder each group's rows based on header subHeaders foreach ($proposalHeaderData as $proposalKey => $headerInfo) { if ( - !isset($groupedRows[$proposalKey]) || - !isset($headerInfo['subHeaders']) || - !is_array($headerInfo['subHeaders']) + ! isset($groupedRows[$proposalKey]) || + ! isset($headerInfo['subHeaders']) || + ! is_array($headerInfo['subHeaders']) ) { continue; } $order = $headerInfo['subHeaders']; - $rows = $groupedRows[$proposalKey]; + $rows = $groupedRows[$proposalKey]; // Sort whole rows according to subth position in $order usort($rows, function ($a, $b) use ($order) { @@ -1953,12 +1938,12 @@ class LeadsController extends BaseController private function renumberProposalKeys(array $input): array { - $result = []; + $result = []; $counter = 1; foreach ($input as $key => $value) { if (strpos($key, 'Proposal') === 0) { - $newKey = 'Proposal ' . $counter++; + $newKey = 'Proposal ' . $counter++; $result[$newKey] = $value; } else { $result[$key] = $value; @@ -1972,7 +1957,7 @@ class LeadsController extends BaseController { $id = $this->request->getGet('id'); // print_r($id); die; - if (!empty($id)) { + if (! empty($id)) { $this->leadInstallmentPaymentDetails->whereIn('id', $id)->set(['is_active' => 0])->update(); } else { return $this->respond(['status' => false, 'message' => 'Could not be removed.'], 200); @@ -1980,9 +1965,9 @@ class LeadsController extends BaseController if ($this->request->getGet('lead_id')) { $lead_id = $this->request->getGet('lead_id'); - $data = [ + $data = [ 'no_of_installment' => 0, - 'is_installment' => 0 + 'is_installment' => 0, ]; $this->leadsModel->where('id', $lead_id)->set($data)->update(); } @@ -1992,7 +1977,6 @@ class LeadsController extends BaseController //-----RFQ and QCR EXPORT------------------------------------------------------------------------------------------------ - //export main route function public function exportQCRandRFQ($lead_id, $type, $lead_form_type) { @@ -2023,7 +2007,7 @@ class LeadsController extends BaseController if ($lead_file_path) { $filePaths = [ ['file_path' => $temp_file_path, 'sheets' => []], - ['file_path' => $lead_file_path, 'sheets' => []] + ['file_path' => $lead_file_path, 'sheets' => []], ]; // $outputPath = dirname($temp_file_path) . '/' . 'merged_' . $temp_file_name; $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $temp_file_path); @@ -2057,15 +2041,15 @@ class LeadsController extends BaseController public function constructExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null) { helper('excel_util_helper'); - $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); + $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); $is_placement = false; - $length = 0; + $length = 0; // dd($rfq_data, $lead_id, $type, $propsal_and_insurer); // print_r($propsal_and_insurer); die; // print_r($is_placement); die; - $data = json_decode($rfq_data['json'], true); + $data = json_decode($rfq_data['json'], true); $sheetName = 'Worksheet'; if ($type == 2) { $sheetName = 'QCR'; @@ -2073,51 +2057,51 @@ class LeadsController extends BaseController $data = $this->convertJsonForQCR($data, $type); if ($propsal_and_insurer !== null) { list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); - $data = $this->transformProposelData($data, $proposal_key, $insurer_key); - $is_placement = true; - $sheetName = 'Placement'; + $data = $this->transformProposelData($data, $proposal_key, $insurer_key); + $is_placement = true; + $sheetName = 'Placement'; } } else if ($type == 1) { $sheetName = 'RFQ'; - $data = $this->convertJsonForQCR($data, $type); + $data = $this->convertJsonForQCR($data, $type); } // dd($data); if ($rfq_data['lead_type'] == 1) { if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) { $lead_data = [ - 'Insured' => $rfq_data['client_name'], - 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", + 'Insured' => $rfq_data['client_name'], + 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", - 'No of Employees' => $rfq_data['incept_emp_count'], - 'No of Dependents' => $rfq_data['incept_dept_count'], - 'Total Lives' => $rfq_data['incept_no_of_lives'], + 'No of Employees' => $rfq_data['incept_emp_count'], + 'No of Dependents' => $rfq_data['incept_dept_count'], + 'Total Lives' => $rfq_data['incept_no_of_lives'], - 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Period of Insurance ' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", // 'Insurer' => $rfq_data['insurer_name'] ?? " - ", // 'TPA' => $rfq_data['tpa_name'] ?? " - ", // 'Policy Run Days' => $rfq_data['policy_run_days'], ]; } else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) { $lead_data = [ - 'Insured' => $rfq_data['client_name'], + 'Insured' => $rfq_data['client_name'], 'No of Employees at Inception' => $rfq_data['incept_emp_count'], // 'Total Sum Insured at Inception ' => $rfq_data['total_si_at_incept'], - 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Policy Period' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", // 'Insurer' => $rfq_data['insurer_name'] ?? " - ", // 'TPA' => $rfq_data['tpa_name'] ?? " - ", - 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", + 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", ]; } - + } else { if (in_array($rfq_data['policy_type_id'], [2, 3, 4, 5])) { - if($is_placement == true){ + if ($is_placement == true) { $lead_data = [ - 'Insured' => $rfq_data['client_name'], - 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", + 'Insured' => $rfq_data['client_name'], + 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", // 'No of Employees at Inception' => $rfq_data['incept_emp_count'], // 'No of Dependents at Inception' => $rfq_data['incept_dept_count'], @@ -2127,13 +2111,13 @@ class LeadsController extends BaseController // 'No of Dependents at Expiry' => $rfq_data['exp_dept_count'], // 'Total Lives at Expiry ' => $rfq_data['exp_no_of_lives'], - 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], + 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'], - 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'], + 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'], - 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", - 'Insurer' => $rfq_data['insurer_name'] ?? " - ", - 'TPA' => $rfq_data['tpa_name'] ?? " - ", + 'Period of Insurance ' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Insurer' => $rfq_data['insurer_name'] ?? " - ", + 'TPA' => $rfq_data['tpa_name'] ?? " - ", // 'Policy Run Days' => $rfq_data['policy_run_days'], // 'Inception Premium' => formatIndianCurrency($rfq_data['premium_at_inception']), @@ -2144,52 +2128,52 @@ class LeadsController extends BaseController // 'Incurred Claims Ratio' => $rfq_data['incurred_claims_ratio'] . " %", // 'Earned Claims Ratio' => $rfq_data['earned_claims_ratio'] . " %", ]; - }else{ + } else { $lead_data = [ - 'Insured' => $rfq_data['client_name'], - 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", + 'Insured' => $rfq_data['client_name'], + 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", - 'No of Employees at Inception' => $is_placement ? '-' : $rfq_data['incept_emp_count'], - 'No of Dependents at Inception' => $is_placement ? '-' : $rfq_data['incept_dept_count'], - 'Total Lives at Inception ' => $is_placement ? '-' : $rfq_data['incept_no_of_lives'], + 'No of Employees at Inception' => $is_placement ? '-' : $rfq_data['incept_emp_count'], + 'No of Dependents at Inception' => $is_placement ? '-' : $rfq_data['incept_dept_count'], + 'Total Lives at Inception ' => $is_placement ? '-' : $rfq_data['incept_no_of_lives'], - 'No of Employees at Expiry' => $is_placement ? '-' : $rfq_data['exp_emp_count'], - 'No of Dependents at Expiry' => $is_placement ? '-' : $rfq_data['exp_dept_count'], - 'Total Lives at Expiry ' => $is_placement ? '-' : $rfq_data['exp_no_of_lives'], + 'No of Employees at Expiry' => $is_placement ? '-' : $rfq_data['exp_emp_count'], + 'No of Dependents at Expiry' => $is_placement ? '-' : $rfq_data['exp_dept_count'], + 'Total Lives at Expiry ' => $is_placement ? '-' : $rfq_data['exp_no_of_lives'], - 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], - 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'], - 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'], + 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], + 'No of Dependents at Renewal' => $rfq_data['renewal_dept_count'], + 'Total Lives at Renewal ' => $rfq_data['renewal_no_of_lives'], - 'Period of Insurance ' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) + 'Period of Insurance ' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", - 'Insurer' => $rfq_data['insurer_name'] ?? " - ", - 'TPA' => $rfq_data['tpa_name'] ?? " - ", + 'Insurer' => $rfq_data['insurer_name'] ?? " - ", + 'TPA' => $rfq_data['tpa_name'] ?? " - ", - 'Policy Run Days' => $is_placement ? '-' : $rfq_data['policy_run_days'], - 'Inception Premium' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_at_inception']), - 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_date']), - 'Earned Premium' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['earned_premium'])), + 'Policy Run Days' => $is_placement ? '-' : $rfq_data['policy_run_days'], + 'Inception Premium' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_at_inception']), + 'Premium as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['premium_date']), + 'Earned Premium' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['earned_premium'])), 'Incurred Claims as on (' . date('d-m-Y', strtotime($rfq_data['incurred_claims_date'])) . ')' => $is_placement ? '-' : formatIndianCurrency($rfq_data['incurred_claims']), - 'Annualised Claims' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['annualised_claims'])), - 'Incurred Claims Ratio' => $is_placement ? '-' : $rfq_data['incurred_claims_ratio'] . " %", - 'Earned Claims Ratio' => $is_placement ? '-' : $rfq_data['earned_claims_ratio'] . " %", + 'Annualised Claims' => $is_placement ? '-' : formatIndianCurrency(intval($rfq_data['annualised_claims'])), + 'Incurred Claims Ratio' => $is_placement ? '-' : $rfq_data['incurred_claims_ratio'] . " %", + 'Earned Claims Ratio' => $is_placement ? '-' : $rfq_data['earned_claims_ratio'] . " %", ]; } } else if (in_array($rfq_data['policy_type_id'], [1, 6, 7])) { $lead_data = [ - 'Insured' => $rfq_data['client_name'], - 'No of Employees at Inception' => $rfq_data['incept_emp_count'], - 'Total Sum Insured at Inception' => $rfq_data['total_si_at_incept'], - 'Premium at inception' => $rfq_data['premium_at_incept'], - 'Policy Period' => !empty($rfq_data['policy_start_date']) && !empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", - 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", - 'Existing Insurer' => $rfq_data['insurer_name'], - 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], - 'Total Sum Insured at Renewal' => $rfq_data['total_si_at_renewal'], + 'Insured' => $rfq_data['client_name'], + 'No of Employees at Inception' => $rfq_data['incept_emp_count'], + 'Total Sum Insured at Inception' => $rfq_data['total_si_at_incept'], + 'Premium at inception' => $rfq_data['premium_at_incept'], + 'Policy Period' => ! empty($rfq_data['policy_start_date']) && ! empty($rfq_data['policy_end_date']) ? date('d-m-Y', strtotime($rfq_data['policy_start_date'])) . ' to ' . date('d-m-Y', strtotime($rfq_data['policy_end_date'])) : "To be decided", + 'Policy Type' => $this->leadType[$rfq_data['lead_type']] ?? "", + 'Existing Insurer' => $rfq_data['insurer_name'], + 'No of Employees at Renewal' => $rfq_data['renewal_emp_count'], + 'Total Sum Insured at Renewal' => $rfq_data['total_si_at_renewal'], 'Claims Experience for last 3 years' => "Mentioned in Claims sheet", // 'Insurer' => $rfq_data['insurer_name'] ?? " - ", // 'TPA' => $rfq_data['tpa_name'] ?? " - ", @@ -2199,12 +2183,10 @@ class LeadsController extends BaseController } // print_r($lead_data); die; - $spreadsheet = new Spreadsheet(); - $sheet = $spreadsheet->getActiveSheet(); + $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle($sheetName); - // Start with lead_data at the top $rowNumber = 1; @@ -2212,13 +2194,13 @@ class LeadsController extends BaseController // $sheet->mergeCells($mergeRange1); $sheet->setCellValue("A{$rowNumber}", "Nhance India Insurance Broking Pvt Ltd"); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ - 'font' => [ + 'font' => [ 'bold' => true, - 'size' => 23 + 'size' => 23, ], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); @@ -2279,22 +2261,22 @@ class LeadsController extends BaseController $sheet->setCellValue("A{$rowNumber}", "Details of Coverage"); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ - 'font' => [ + 'font' => [ 'bold' => true, ], - 'fill' => [ - 'fillType' => Fill::FILL_SOLID, + 'fill' => [ + 'fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'ADD8E6'], ], 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); - if($type == 2){ + if ($type == 2) { $subheader_count = array_sum( array_map( fn($header) => count(array_filter( @@ -2304,7 +2286,7 @@ class LeadsController extends BaseController $data['table_data']['headers'] ) ); - }else{ + } else { $subheader_count = array_sum(array_map(fn($header) => count($header['subHeaders']), $data['table_data']['headers'])); } @@ -2313,7 +2295,7 @@ class LeadsController extends BaseController } $headerCount = count($data['table_data']['headers']); - $lastColumn = Coordinate::stringFromColumnIndex($subheader_count); + $lastColumn = Coordinate::stringFromColumnIndex($subheader_count); // dd( $headerCount, $lastColumn); // Merge cells from A to the last column @@ -2323,14 +2305,14 @@ class LeadsController extends BaseController 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); $sheet->mergeCells($mergeRange); $rowNumber_for_remove_quote_asked = $rowNumber; - $rowNumber = $rowNumber + 1; + $rowNumber = $rowNumber + 1; if ($type == 2) { $subHeaderRow = $rowNumber + 1; @@ -2339,13 +2321,13 @@ class LeadsController extends BaseController $subHeaderRow = $rowNumber + 1; } - $columnLetter = 'A'; + $columnLetter = 'A'; $header_actual_count = 0; - $headerIndex = 0; + $headerIndex = 0; foreach ($headers as $header) { // Kint::dump($header); - if($is_placement == true){ + if ($is_placement == true) { //for placement proposal only $nxt_ro = $rowNumber + 1; $sheet->mergeCells("C{$rowNumber}:C{$nxt_ro}"); @@ -2354,13 +2336,13 @@ class LeadsController extends BaseController if (in_array($header['parentHeader'], ['Item Key', 'Action'])) { continue; } - - if (!in_array($header['parentHeader'], ['Item Key', 'Action', 'Sno', 'Particulars'])) { + + if (! in_array($header['parentHeader'], ['Item Key', 'Action', 'Sno', 'Particulars'])) { $header_actual_count++; - //Quote asked not showed in the QCR excel so some proposel has only one Quote Asked, So that case avoid the proposel name + //Quote asked not showed in the QCR excel so some proposel has only one Quote Asked, So that case avoid the proposel name $subHeaderCount = count($header['subHeaders'] ?? []) ?? 0; - if($subHeaderCount <= 1 && $type == 2 && $is_placement == false){ + if ($subHeaderCount <= 1 && $type == 2 && $is_placement == false) { // print_rr($header); continue; } @@ -2384,33 +2366,33 @@ class LeadsController extends BaseController } $startColumn = $columnLetter; // Start of the current header range - if($type == 2){ - $subHeaderCount = count(array_filter($header['subHeaders'], function($subHeader) { + if ($type == 2) { + $subHeaderCount = count(array_filter($header['subHeaders'], function ($subHeader) { return $subHeader !== "Quote Asked"; })); - }else{ + } else { $subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header } // Set parent header value - if ($is_placement == true && !in_array($header['parentHeader'], ['Particulars', 'S.No.'])) { + if ($is_placement == true && ! in_array($header['parentHeader'], ['Particulars', 'S.No.'])) { $sheet->setCellValue("{$startColumn}{$rowNumber}", "Terms"); } else { - if(in_array($header['parentHeader'], ["Existing Renewal", "Existing Rollover"])){ + if (in_array($header['parentHeader'], ["Existing Renewal", "Existing Rollover"])) { $sheet->setCellValue("{$startColumn}{$rowNumber}", "Existing Terms"); - }else if(in_array($header['parentHeader'], ["Particulars", "S.No."])){ + } else if (in_array($header['parentHeader'], ["Particulars", "S.No."])) { $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']); - }else{ + } else { $headerIndex = $headerIndex + 1; $sheet->setCellValue("{$startColumn}{$rowNumber}", "Proposal Terms " . $headerIndex); } } - + $sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); @@ -2425,7 +2407,7 @@ class LeadsController extends BaseController // Add subheaders foreach ($header['subHeaders'] as $subHeader) { - if($type == 2 && in_array($subHeader, ['Quote Asked'])){ + if ($type == 2 && in_array($subHeader, ['Quote Asked'])) { continue; } @@ -2441,23 +2423,23 @@ class LeadsController extends BaseController if ($is_placement == false) { $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); } $columnLetter++; // Move to the next column for subheaders - // Kint::dump($subHeader); + // Kint::dump($subHeader); $length++; } } - - if($header_actual_count == 1 && $type == 1){ + + if ($header_actual_count == 1 && $type == 1) { $sheet->getColumnDimension('B')->setWidth(80); - }else{ + } else { $sheet->getColumnDimension('B')->setWidth(35); } @@ -2468,13 +2450,13 @@ class LeadsController extends BaseController 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); - // Increase row height for headers and subheaders - $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height + // Increase row height for headers and subheaders + $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height $sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height if ($is_placement == true) { @@ -2484,8 +2466,8 @@ class LeadsController extends BaseController } // dd($rowNumber); - $column_data = $data['table_data']['data']; - $serial_no = 1; + $column_data = $data['table_data']['data']; + $serial_no = 1; $maxColumnWidths = []; // Add table data rows @@ -2496,7 +2478,7 @@ class LeadsController extends BaseController continue; } - if($type == 2 && in_array($cellData['subth'], ['Quote Asked'])){ + if ($type == 2 && in_array($cellData['subth'], ['Quote Asked'])) { continue; } @@ -2513,26 +2495,26 @@ class LeadsController extends BaseController } $prevColumn2 = $this->getPreviousColumn($columnLetter); - $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn2}" . ($rowNumber - 1); + $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn2}" . ($rowNumber - 1); $sheet->getStyle($dataRange)->applyFromArray([ 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); - //premium data + //premium data if ($type == 2) { - if($is_placement == true){$columnLetterForPremium = "B";}else{$columnLetterForPremium = "B";} + if ($is_placement == true) {$columnLetterForPremium = "B";} else { $columnLetterForPremium = "B";} $rowNumber += 2; // Add premium data // dd($data); // $labelArray = ["Premium", "GST (%)", "GST Amount (₹)", "Total"]; - $labelArray = ["Premium", "GST Amount (₹)", "Total"]; + $labelArray = ["Premium", "GST Amount (₹)", "Total"]; $premiumData = $data['premium_data']['data']; // dd($premiumData); // $premium = [$labelArray[0]]; @@ -2541,24 +2523,24 @@ class LeadsController extends BaseController // $total = [$labelArray[2]]; // if($is_placement == true){ - $premium[] = $labelArray[0]; - $gstAmt[] = $labelArray[1]; - $total[] = $labelArray[2]; + $premium[] = $labelArray[0]; + $gstAmt[] = $labelArray[1]; + $total[] = $labelArray[2]; // } foreach ($premiumData as $proposal => $insurers) { if ($proposal != 'Particulars') { foreach ($insurers as $insurer => $values) { - if($insurer == 'Quote Asked'){ + if ($insurer == 'Quote Asked') { // $premium[] = count($insurers ?? []) > 1 ? $labelArray[0] : ""; // $gst[] = ""; // $gstAmt[] = count($insurers ?? []) > 1 ? $labelArray[1] : ""; // $total[] = count($insurers ?? []) > 1 ? $labelArray[2] : ""; - }else{ + } else { $premium[] = formatIndianCurrency($values[$labelArray[0]]); // $gst[] = $values[$labelArray[1]]; $gstAmt[] = formatIndianCurrency($values[$labelArray[1]]); - $total[] = formatIndianCurrency($values[$labelArray[2]]); + $total[] = formatIndianCurrency($values[$labelArray[2]]); } } } @@ -2571,7 +2553,7 @@ class LeadsController extends BaseController foreach ($rowData as $key => $value) { $sheet->setCellValue("{$columnLetter}{$rowNumber}", $value); if (in_array($value, $labelArray)) { - $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray(['font' => ['bold' => true,],]); + $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray(['font' => ['bold' => true]]); } $columnLetter++; } @@ -2591,7 +2573,7 @@ class LeadsController extends BaseController 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); @@ -2609,7 +2591,7 @@ class LeadsController extends BaseController } $company_name = $this->getPreviousColumn($columnLetter_img); - $mergeRange1 = "A1:{$company_name}1"; + $mergeRange1 = "A1:{$company_name}1"; $sheet->mergeCells($mergeRange1); $rowCount = count($lead_data); @@ -2620,7 +2602,7 @@ class LeadsController extends BaseController 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); @@ -2630,13 +2612,13 @@ class LeadsController extends BaseController $sheet->getRowDimension(1)->setRowHeight(50); // Adjust as needed $drawing = new Drawing(); - $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path + $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path $drawing->setPath($path); $drawing->setCoordinates("{$columnLetter_img}1"); // Set position in column B - $drawing->setHeight(35); // Adjust image + $drawing->setHeight(35); // Adjust image $offsetX = 35; $drawing->setOffsetX($offsetX); // Adjust horizontal offset - $drawing->setOffsetY(10); // Adjust vertical offset + $drawing->setOffsetY(10); // Adjust vertical offset $drawing->setWorksheet($sheet); //end @@ -2658,53 +2640,53 @@ class LeadsController extends BaseController if ($matches) { $startColumn = $matches[1]; // A - $startRow = $matches[2]; // 1 - $endColumn = $matches[3]; // G - $endRow = $matches[4]; // 75 + $startRow = $matches[2]; // 1 + $endColumn = $matches[3]; // G + $endRow = $matches[4]; // 75 // Convert column letter to index, reduce by 1, and convert back $endColumnIndex = Coordinate::columnIndexFromString($endColumn) - 1; - $newEndColumn = Coordinate::stringFromColumnIndex($endColumnIndex); + $newEndColumn = Coordinate::stringFromColumnIndex($endColumnIndex); // Generate the new range (e.g., "A1:F75" instead of "A1:G75") $newDataRange = "{$startColumn}{$startRow}:{$newEndColumn}{$endRow}"; // $sheet->getStyle($newDataRange)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN); } - $lastRow = count($lead_data) + 1; + $lastRow = count($lead_data) + 1; $leadRange = "A1:{$columnLetter_img}{$lastRow}"; $sheet->getStyle($leadRange)->applyFromArray([ 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); // Set filename - $string = ($type == 2) ? ($is_placement == true ? 'Placement' : 'QCR') : 'RFQ'; + $string = ($type == 2) ? ($is_placement == true ? 'Placement' : 'QCR') : 'RFQ'; $current_year = date('Y'); - $next_year = $current_year + 1; - $policy_year = "$current_year-$next_year"; + $next_year = $current_year + 1; + $policy_year = "$current_year-$next_year"; - if (!empty($rfq_data['policy_end_date'])) { + if (! empty($rfq_data['policy_end_date'])) { - $policy_expiry = strtotime($rfq_data['policy_end_date']); + $policy_expiry = strtotime($rfq_data['policy_end_date']); $formatted_policy = date("d-m-Y", $policy_expiry); - $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '(Due On ' . $formatted_policy . ')' . '.xlsx'; + $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '(Due On ' . $formatted_policy . ')' . '.xlsx'; } else { - $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '_' . '.xlsx'; + $filename = "{$rfq_data['client_name']}_{$rfq_data['policy_type']}_{$string}_" . $policy_year . '_' . '.xlsx'; } //claim history new sheet; - if (!empty($rfq_data['fin_years_claims'])) { + if (! empty($rfq_data['fin_years_claims'])) { $claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? []; - if (!empty($claim_details['finyear'])) { + if (! empty($claim_details['finyear'])) { // Get headers dynamically $headers = array_map(function ($key) { @@ -2717,9 +2699,9 @@ class LeadsController extends BaseController $sheet = $spreadsheet->getActiveSheet(); // Set headers - $sheet->fromArray($headers, NULL, 'A1'); + $sheet->fromArray($headers, null, 'A1'); - // Apply background color and bold style to headers + // Apply background color and bold style to headers $headerCellRange = 'A1:' . chr(64 + count($headers)) . '1'; // e.g., A1:G1 $sheet->getStyle($headerCellRange)->getFont()->setBold(true); @@ -2733,8 +2715,8 @@ class LeadsController extends BaseController foreach ($claim_details['finyear'] as $record) { $col = 'A'; foreach ($record as $array_key => $value) { - $label = ucwords(str_replace('_', ' ', ($value ?? ""))); - if(in_array($array_key, ['sum_insured', 'claim_amount', 'settled'])){ + $label = ucwords(str_replace('_', ' ', ($value ?? ""))); + if (in_array($array_key, ['sum_insured', 'claim_amount', 'settled'])) { $label = formatIndianCurrency(intval($label)); } $sheet->setCellValue($col . $row, $label); @@ -2761,24 +2743,24 @@ class LeadsController extends BaseController // $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); $maxColLetter = chr(64 + count($headers)); - $dataRange = "A1:{$maxColLetter}" . ($row - 1); + $dataRange = "A1:{$maxColLetter}" . ($row - 1); $sheet->getStyle($dataRange)->getAlignment() ->setWrapText(true) ->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER) ->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); - // Optional: Make row height auto (helps when wrap text is on) - for ($i = 2; $i < $row; $i++) { - $sheet->getRowDimension($i)->setRowHeight(-1); - } + // Optional: Make row height auto (helps when wrap text is on) + for ($i = 2; $i < $row; $i++) { + $sheet->getRowDimension($i)->setRowHeight(-1); + } - } - } + } + } // Save to temporary location $uploadFilePath = WRITEPATH . 'tmp/' . $filename; - $writer = new Xlsx($spreadsheet); + $writer = new Xlsx($spreadsheet); $writer->save($uploadFilePath); return [ @@ -2800,21 +2782,21 @@ class LeadsController extends BaseController public function calculateMembersDemography($params, $returnType = null) { - $lead_id = $params['lead_id']; - $lead_data = $this->leadsModel->find((int)$lead_id); + $lead_id = $params['lead_id']; + $lead_data = $this->leadsModel->find((int) $lead_id); $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name']; - if (!$lead_data) { + if (! $lead_data) { return ['status' => 'failed', 'message' => 'Opportunity data not found']; } - try{ + try { if ($lead_data['file_name']) { // $file_name_with_path = WRITEPATH . "/uploads/lead_files/NonPrintableCharacters.xlsx"; //check physical file - if (!file_exists($file_name_with_path)) { - //file not found update status and reason + if (! file_exists($file_name_with_path)) { + //file not found update status and reason $message = "Lead Physcial file not found"; // echo $message; $this->myLogger->logme('error', ($message . ' for file ' . $file_name_with_path)); @@ -2824,28 +2806,27 @@ class LeadsController extends BaseController $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); //get members data - $members_sheet = $spreadsheet->getSheet(0); + $members_sheet = $spreadsheet->getSheet(0); $highestRowAndColumn = $members_sheet->getHighestRowAndColumn(); // dd($highestRowAndColumn); $uncleaned_members = $members_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); - $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members); + $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members); //get age band data - $age_band_sheet = $spreadsheet->getSheet(1); + $age_band_sheet = $spreadsheet->getSheet(1); $highestRowAndColumn = $age_band_sheet->getHighestRowAndColumn(); - $age_band_data = $age_band_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); + $age_band_data = $age_band_sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); - - //check age or dob column + //check age or dob column $members_heading = $members[0]; - $available_col = null; - $col_index = null; + $available_col = null; + $col_index = null; if (in_array('age', array_map('strtolower', $members_heading))) { $available_col = 'age'; - $col_index = array_search('age', array_map('strtolower', $members_heading)); + $col_index = array_search('age', array_map('strtolower', $members_heading)); } elseif (in_array('dob', array_map('strtolower', $members_heading))) { $available_col = 'dob'; - $col_index = array_search('dob', array_map('strtolower', $members_heading)); + $col_index = array_search('dob', array_map('strtolower', $members_heading)); } if ($available_col == null) { @@ -2861,12 +2842,11 @@ class LeadsController extends BaseController } //for this to view the demography in the RFQ and QCR page to using internal - if($returnType == "internal"){ + if ($returnType == "internal") { return ['data' => $classifiers]; // print_rr($classifiers); die; } - try { $result = $this->generateClassifierSpreadsheet($classifiers, WRITEPATH . 'uploads/lead_files/'); if ($result['success']) { @@ -2876,9 +2856,9 @@ class LeadsController extends BaseController echo "Filename: " . $result['filename'] . "\n"; $filePaths = [ ['file_path' => WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name'], 'sheets' => [0, 1]], - ['file_path' => WRITEPATH . '/uploads/lead_files/' . $result['filename'], 'sheets' => []], + ['file_path' => WRITEPATH . '/uploads/lead_files/' . $result['filename'], 'sheets' => []], ]; - $outputPath = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name']; + $outputPath = WRITEPATH . 'uploads/lead_files/' . $lead_data['file_name']; $result_merge = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); if ($result_merge) { // Call the delete function after the file is successfully created @@ -2899,8 +2879,8 @@ class LeadsController extends BaseController $this->myLogger->logme('error', (' no file found ' . $file_name_with_path)); return ['status' => 'failed', 'message' => 'no file found']; } - - }catch(Exception $e){ + + } catch (Exception $e) { $this->myLogger->logme("error", "Exception: " . $e->getMessage() . " --- Line: " . $e->getLine() . " --- Trace: " . $e->getTraceAsString()); return ['status' => 'fail', 'error' => "File not found / Wrong file"]; } @@ -2910,10 +2890,10 @@ class LeadsController extends BaseController { $first_loop = 0; // $col_index_si = array_search('si enhancement', array_map('strtolower', $members_heading)); - $col_index_si = array_search('si', array_map('strtolower', $members_heading)); + $col_index_si = array_search('si', array_map('strtolower', $members_heading)); $col_index_relationship = array_search('relationship', array_map('strtolower', $members_heading)); - $relations = []; - $si_amt = ['general']; // Initialize with 'general' as per first loop condition + $relations = []; + $si_amt = ['general']; // Initialize with 'general' as per first loop condition // First pass - collect unique relations and SI amounts foreach ($members as $member) { @@ -2925,11 +2905,11 @@ class LeadsController extends BaseController continue; } - if (!in_array($member[$col_index_relationship], $relations) && $member[$col_index_relationship] != null) { + if (! in_array($member[$col_index_relationship], $relations) && $member[$col_index_relationship] != null) { $relations[] = $member[$col_index_relationship]; } - if (!in_array($member[$col_index_si], $si_amt) && $member[$col_index_si] != null) { + if (! in_array($member[$col_index_si], $si_amt) && $member[$col_index_si] != null) { $si_amt[] = $member[$col_index_si]; } } @@ -2968,14 +2948,15 @@ class LeadsController extends BaseController // Get age $age = $this->getAge($available_col, $member, $col_index); - - $relation = $member[$col_index_relationship]; + $relation = $member[$col_index_relationship]; $member_si = $member[$col_index_si]; // Find the correct age band (only once per member) $found_band = false; foreach ($age_band_data as $age_bands) { - if ($found_band) break; + if ($found_band) { + break; + } foreach ($age_bands as $age_band) { //get Min and Max Age @@ -3018,21 +2999,21 @@ class LeadsController extends BaseController public function generateClassifierSpreadsheet($classifiers, $outputDir = 'exports') { - if (!file_exists($outputDir)) { - if (!mkdir($outputDir, 0755, true)) { + if (! file_exists($outputDir)) { + if (! mkdir($outputDir, 0755, true)) { throw new Exception("Failed to create directory: $outputDir"); } } // Check if directory is writable - if (!is_writable($outputDir)) { + if (! is_writable($outputDir)) { throw new Exception("Directory is not writable: $outputDir"); } // Generate unique filename $timestamp = date('Y-m-d_His'); - $filename = "member_classification_{$timestamp}.xlsx"; - $filepath = $outputDir . DIRECTORY_SEPARATOR . $filename; + $filename = "member_classification_{$timestamp}.xlsx"; + $filepath = $outputDir . DIRECTORY_SEPARATOR . $filename; // Check if file already exists (shouldn't happen with timestamp, but just in case) if (file_exists($filepath)) { @@ -3045,12 +3026,12 @@ class LeadsController extends BaseController } $spreadsheet = new Spreadsheet(); - $sheet = $spreadsheet->getActiveSheet(); + $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle('Demography_Data'); // Get all age bands $age_bands = array_keys(reset($classifiers['general'])); - array_pop($age_bands); // Remove 'Grand Total' + array_pop($age_bands); // Remove 'Grand Total' $age_bands[] = 'Grand Total'; // Add it back at the end $currentRow = 5; // Start from row 5 to match the example @@ -3062,7 +3043,7 @@ class LeadsController extends BaseController // Style section header $sheet->getStyle('B' . $currentRow)->applyFromArray([ - 'font' => ['bold' => true, 'size' => 14], + 'font' => ['bold' => true, 'size' => 14], 'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER], ]); @@ -3077,14 +3058,14 @@ class LeadsController extends BaseController } // Style headers - $lastCol = chr(ord('B') + count($age_bands)); + $lastCol = chr(ord('B') + count($age_bands)); $headerRange = 'B' . $currentRow . ':' . $lastCol . $currentRow; $sheet->getStyle($headerRange)->applyFromArray([ - 'font' => ['bold' => true], - 'borders' => [ + 'font' => ['bold' => true], + 'borders' => [ 'allBorders' => [ 'borderStyle' => Border::BORDER_THIN, - 'color' => ['rgb' => '000000'], + 'color' => ['rgb' => '000000'], ], ], 'alignment' => [ @@ -3108,10 +3089,10 @@ class LeadsController extends BaseController // Style data row $dataRange = 'B' . $currentRow . ':' . $lastCol . $currentRow; $sheet->getStyle($dataRange)->applyFromArray([ - 'borders' => [ + 'borders' => [ 'allBorders' => [ 'borderStyle' => Border::BORDER_THIN, - 'color' => ['rgb' => '000000'], + 'color' => ['rgb' => '000000'], ], ], 'alignment' => [ @@ -3134,15 +3115,15 @@ class LeadsController extends BaseController // Style Grand Total row $totalRange = 'B' . $currentRow . ':' . $lastCol . $currentRow; $sheet->getStyle($totalRange)->applyFromArray([ - 'font' => ['bold' => true], - 'borders' => [ + 'font' => ['bold' => true], + 'borders' => [ 'allBorders' => [ 'borderStyle' => Border::BORDER_THIN, - 'color' => ['rgb' => '000000'], + 'color' => ['rgb' => '000000'], ], ], - 'fill' => [ - 'fillType' => Fill::FILL_SOLID, + 'fill' => [ + 'fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'F2F2F2'], ], 'alignment' => [ @@ -3170,23 +3151,23 @@ class LeadsController extends BaseController $writer->save($filepath); // Verify file was created successfully - if (!file_exists($filepath)) { + if (! file_exists($filepath)) { throw new Exception("Failed to create file: $filepath"); } // Return the file info after creation $response = [ - 'success' => true, + 'success' => true, 'filepath' => $filepath, 'filename' => $filename, - 'fullpath' => realpath($filepath) + 'fullpath' => realpath($filepath), ]; return $response; } catch (Exception $e) { return [ 'success' => false, - 'error' => $e->getMessage() + 'error' => $e->getMessage(), ]; } } @@ -3199,18 +3180,18 @@ class LeadsController extends BaseController unlink($filePath); // Delete the file return [ 'success' => true, - 'message' => "File deleted successfully" + 'message' => "File deleted successfully", ]; } else { return [ 'success' => false, - 'message' => "File does not exist" + 'message' => "File does not exist", ]; } } catch (Exception $e) { return [ 'success' => false, - 'error' => $e->getMessage() + 'error' => $e->getMessage(), ]; } } @@ -3224,7 +3205,7 @@ class LeadsController extends BaseController if ($dob == 'DOB') { return; } - $dobDate = \DateTime::createFromFormat('d-M-Y', $dob); + $dobDate = \DateTime::createFromFormat('d-M-Y', $dob); $currentDate = new \DateTime(); if ($dobDate == false) { $this->myLogger->logme('error', $dob . 'is not valid'); @@ -3240,18 +3221,17 @@ class LeadsController extends BaseController $age_band = trim($age_band); // Parse age range if (strpos($age_band, '-') === false) { - $min_age = (int)filter_var($age_band, FILTER_SANITIZE_NUMBER_INT); + $min_age = (int) filter_var($age_band, FILTER_SANITIZE_NUMBER_INT); $max_age = PHP_INT_MAX; } else { - $parts = explode("-", $age_band); - $min_age = (int)$parts[0]; - $max_age = (int)$parts[1]; + $parts = explode("-", $age_band); + $min_age = (int) $parts[0]; + $max_age = (int) $parts[1]; } - return array($min_age, $max_age); + return [$min_age, $max_age]; } - //this funciton for send mail to insurer and client with either RFQ/QCR public function sendMailWithAttachement() { @@ -3262,33 +3242,33 @@ class LeadsController extends BaseController // print_r($params); die; - $lead_id = (int)$params['lead_id']; - $file_type = $params['file_type']; //rfq or qcr - $recipient_type = $params['recipient_type']; //insurer or client or internal or placement - $recipient_mail = $params['recipient_mail']; // - only primary key of contacts - $recipient_mail = json_decode($params['recipient_mail'], true); // - only primary key of contacts + $lead_id = (int) $params['lead_id']; + $file_type = $params['file_type']; //rfq or qcr + $recipient_type = $params['recipient_type']; //insurer or client or internal or placement + $recipient_mail = $params['recipient_mail']; // - only primary key of contacts + $recipient_mail = json_decode($params['recipient_mail'], true); // - only primary key of contacts $propsal_and_insurer = isset($params['proposal_insurer']) ? $params['proposal_insurer'] : null; - $mail_content = $params['mail_content']; - $mail_subject = $params['subject']; + $mail_content = $params['mail_content']; + $mail_subject = $params['subject']; $attachment_file_ids = $params['selected_attachment_files']; $from_mail = getenv('email.fromEmail'); if (in_array($recipient_type, ['placement', 'insurer', 'internal'])) { - $from_mail = "im@nhanceindia.in"; + $from_mail = getenv('LEAD_INSURER_FROM_MAIL_ID'); } else if (in_array($recipient_type, ['client'])) { - $from_mail = "bs@nhanceindia.in"; + $from_mail = getenv('LEAD_CLIENT_FROM_MAIL_ID'); } - $type = ""; + $type = ""; $insurer_ids = null; if (in_array($recipient_type, ['placement'])) { $type = "placement"; } else if (in_array($recipient_type, ['insurer'])) { - $type = "insurer"; + $type = "insurer"; $insurer_ids = json_decode($params['insurer_ids'] ?? "", true) ?? []; - }else if (in_array($recipient_type, ['internal'])) { + } else if (in_array($recipient_type, ['internal'])) { $type = "internal"; - }else if (in_array($recipient_type, ['client'])) { + } else if (in_array($recipient_type, ['client'])) { $type = "client"; } @@ -3296,32 +3276,32 @@ class LeadsController extends BaseController if ($recipient_type === 'placement') { - $lead_data = $this->leadsModel->find((int)$lead_id); + $lead_data = $this->leadsModel->find((int) $lead_id); $data = []; - if (!empty($params['policy_start_date'])) { + if (! empty($params['policy_start_date'])) { $converted_start = change_date_format($params['policy_start_date']); // converts to Y-m-d if ($converted_start !== $lead_data['policy_start_date']) { $data['policy_start_date'] = $converted_start; } } - if (!empty($params['policy_end_date'])) { + if (! empty($params['policy_end_date'])) { $converted_end = change_date_format($params['policy_end_date']); // converts to Y-m-d if ($converted_end !== $lead_data['policy_end_date']) { $data['policy_end_date'] = $converted_end; } } - if (!empty($data)) { + if (! empty($data)) { $this->leadsModel->update($lead_id, $data); } } $result_data = []; // dd($recipient_mail); - if ($recipient_type == 'insurer' && (!is_array($recipient_mail) || count($recipient_mail) == 0)) { + if ($recipient_type == 'insurer' && (! is_array($recipient_mail) || count($recipient_mail) == 0)) { return $this->respond(['status' => 'failed', 'code' => 400, 'data' => '', 'messgae' => 'Recipient mail not found ! '], 200); } // dd(); @@ -3336,16 +3316,15 @@ class LeadsController extends BaseController // log_message('error', 'Lead Data' . json_encode($lead_data)); // print_r($lead_data ); die; - $cc_mails = []; + $cc_mails = []; $bcc_mails = []; //get CC Mails if ($recipient_type == 'internal' || $recipient_type == 'insurer' || $recipient_type == 'client') { - $cc_data = isset($params['cc']) ? $params['cc'] : ""; + $cc_data = isset($params['cc']) ? $params['cc'] : ""; $param_cc_mail = json_decode($cc_data, true); - if (isset($param_cc_mail) && is_array($param_cc_mail) && count($param_cc_mail) > 0) { // Fetch user data where ID is in the param_cc_mail array $userData = $this->userModel @@ -3370,13 +3349,20 @@ class LeadsController extends BaseController // return $this->respond(['status' => 'failed','code' => 400,'data' => '','message' => 'CC mail not found!'], 200); } } else if ($recipient_type == 'placement') { - $cc_mails = isset($params['cc']) ? json_decode($params['cc'], true) : ""; + + if(isset($params['cc']) && !empty($params['cc'])) { + if(is_array($params['cc'])) { + $cc_mails = $params['cc']; + } else { + $cc_mails = json_decode($params['cc'], true); + } + } } //get BCC Mails if ($recipient_type == 'insurer' || $recipient_type == 'client') { - $bcc_data = isset($params['bcc']) ? $params['bcc'] : ""; + $bcc_data = isset($params['bcc']) ? $params['bcc'] : ""; $param_bcc_mail = json_decode($bcc_data, true); if (isset($param_bcc_mail) && is_array($param_bcc_mail) && count($param_bcc_mail) > 0) { @@ -3414,7 +3400,8 @@ class LeadsController extends BaseController //get file path to attach if ($lead_data["lead_form_type"] == 2) { - $file_info = $this->constructNonEbExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer); + // For Non-EB, download RFQ/QCR file from Google Sheet (if configured) + $file_info = $this->downloadFileFromGoogleSheet($lead_data); } else { $file_info = $this->constructExcelToSaveTemp($lead_id, ($file_type == 'rfq' ? 1 : 2), $propsal_and_insurer); } @@ -3428,10 +3415,10 @@ class LeadsController extends BaseController if ($lead_file_path) { $filePaths = [ ['file_path' => $temp_file_path, 'sheets' => []], - ['file_path' => $lead_file_path, 'sheets' => []] + ['file_path' => $lead_file_path, 'sheets' => []], ]; - $outputPath = dirname($temp_file_path) . '/' . $temp_file_name; - $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); + $outputPath = dirname($temp_file_path) . '/' . $temp_file_name; + $result = ExcelMergeHelper::mergeExcelFiles($filePaths, $outputPath); // print_rr($result); } } else { @@ -3449,21 +3436,24 @@ class LeadsController extends BaseController $file_name = basename($result); // Attacments part - $attachments = [['fileName' => $file_name, 'filePath' => $file_path]]; + $attachments = [['fileName' => $file_name, 'filePath' => $file_path]]; $other_attachments = $this->handleMultiFileAttachments($attachment_file_ids, $lead_id); - $attachments = array_merge($attachments, $other_attachments); + $attachments = array_merge($attachments, $other_attachments); // print_r($attachments); die; //get recipient address if ($recipient_type == 'insurer' || $recipient_type == 'placement') { - + + if(!is_array($recipient_mail)) { + $recipient_mail = [$recipient_mail]; + } $recipient_data = $this->levelContactModel ->where(['contact_type' => 'insurer', 'is_active' => 1]) ->whereIn('id', $recipient_mail) ->findAll(); } else if ($recipient_type == 'client') { - $mailIDS = explode(',', $params['contact_mail']); + $mailIDS = explode(',', $params['contact_mail']); $recipient_data = []; foreach ($mailIDS as $mail) { $recipient_data[] = ['name' => $lead_data['contact_person_name'], 'email' => $mail]; @@ -3478,12 +3468,12 @@ class LeadsController extends BaseController $original_message = '

Request for Quotation (RFQ)

Dear {{RECIPIENT_NAME}},

We are reaching out to request a quotation for the following insurance coverage. Please review the details below and provide your quote at your earliest convenience.

RFQ Details

Client name{{CLIENT_NAME}}
Coverage Type{{POLICY_LONG_NAME}}
Policy Start Date{{POLICY_START_DATE}}
Policy Duration{{DURATION}}
Please note: Additional terms and details are included in the attachment for your reference.

Please feel free to reach out if you require any further information to prepare the quote. We look forward to receiving your proposal.

Best regards,

Nhance India Pvt Ltd

© Nhance India Pvt Ltd. All rights reserved.

'; //for mail content - if (!empty($mail_content)) { + if (! empty($mail_content)) { $original_message = $mail_content; } //for mail subject - if (!empty($mail_subject)) { + if (! empty($mail_subject)) { $subject = $mail_subject; } @@ -3492,10 +3482,10 @@ class LeadsController extends BaseController if ($recipient_data) { foreach ($recipient_data as $position => $recipient) { - if ($recipient_type == 'insurer'){ + if ($recipient_type == 'insurer') { $common['common'] = $insurer_ids[$position] ?? null; } - + $message = $original_message; $message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'] != "" ? $recipient['name'] : " ", $message); $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'] != "" ? $lead_data['client_name'] : "", $message); @@ -3504,7 +3494,7 @@ class LeadsController extends BaseController $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'] ?? "", $lead_data['policy_start_date'] ?? "")->days, $message) ?? '--'; // print_rr($message);calculate_days_bw_dates - $string = implode(", ", $cc_mails); + $string = implode(", ", $cc_mails); $bcc_string = implode(", ", $bcc_mails); $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $recipient['email'], 'cc' => $string, 'subject' => $subject, 'message' => $message, 'attachments' => $attachments, 'reply_to' => $reply_to, 'bcc' => $bcc_string, 'common' => $common]); @@ -3513,10 +3503,10 @@ class LeadsController extends BaseController } } - if($recipient_type == 'placement' && isset($params['acm_email']) && !empty($params['acm_email'])){ + if ($recipient_type == 'placement' && isset($params['acm_email']) && ! empty($params['acm_email'])) { $common['mail_type'] = "internal acm"; - $acm_mail_content = ' + $acm_mail_content = '

Dear Sir,

The placement for the {{POLICY_TYPE}} policy pertaining to {{CLIENT_NAME}} has been successfully won.

Please proceed with the next steps accordingly.

@@ -3526,7 +3516,7 @@ class LeadsController extends BaseController Nhance Logo '; $acm_mail_content = $this->transformMailContent($lead_data, $acm_mail_content, $data['page_name'] = 'QCR'); - $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $params['acm_email'], 'subject' => $subject, 'message' => $acm_mail_content, 'attachments' => $attachments, 'common' => $common]); + $res = MailHelper::send_email(['from_mail' => $from_mail, 'mail' => $params['acm_email'], 'subject' => $subject, 'message' => $acm_mail_content, 'attachments' => $attachments, 'common' => $common]); } $is_placement = false; @@ -3534,48 +3524,60 @@ class LeadsController extends BaseController $is_placement = true; - list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); + if(isset($propsal_and_insurer)) { + + if (! empty($propsal_and_insurer[0])) { + $parts = explode('-', $propsal_and_insurer[0], 2); + $proposal_key = $parts[0] ?? null; + $insurer_key = $parts[1] ?? null; + } else { + $proposal_key = null; + $insurer_key = null; + } + + } + $lead_update_data = [ - 'proposel_name' => $proposal_key, - 'insurer_name' => $insurer_key, - 'insurer' => $params['insurer_and_branch'], + 'proposel_name' => $proposal_key ?? null , + 'insurer_name' => $insurer_key ?? null, + 'insurer' => $params['insurer_and_branch'] ?? null, ]; $data = [ - 'proposel_data' => json_encode($lead_update_data), - 'status' => 'won', - 'placement_date' => !empty($params['placement_date']) ? change_date_format($params['placement_date']) : null, - 'payment_date' => !empty($params['payment_date']) ? change_date_format($params['payment_date']) : null, - 'utr_no' => $params['utr_no'] ?? null, - 'is_cd' => $params['is_cd'] ?? null, - 'premium_amount' => $params['premium_amount'] ?? null, - 'total_amount' => $params['total_amount'] ?? null, - 'cd_amount' => $params['cd_amount'] ?? null, + 'proposel_data' => json_encode($lead_update_data), + 'status' => 'won', + 'placement_date' => ! empty($params['placement_date']) ? change_date_format($params['placement_date']) : null, + 'payment_date' => ! empty($params['payment_date']) ? change_date_format($params['payment_date']) : null, + 'utr_no' => $params['utr_no'] ?? null, + 'is_cd' => $params['is_cd'] ?? null, + 'premium_amount' => $params['premium_amount'] ?? null, + 'total_amount' => $params['total_amount'] ?? null, + 'cd_amount' => $params['cd_amount'] ?? null, 'no_of_installment' => $params['no_of_installment'] ?? null, - 'is_installment' => $params['is_installment'] ?? null, - 'acm_id' => $params['acm_pk'] ?? null, + 'is_installment' => $params['is_installment'] ?? null, + 'acm_id' => $params['acm_pk'] ?? null, 'agreed_percentage' => $params['agreed_percentage'] ?? null, ]; - if(isset($params['tpa_id']) && !empty($params['tpa_id'])){ + if (isset($params['tpa_id']) && ! empty($params['tpa_id'])) { list($tpaBranchId, $tpaId) = explode('-', $params['tpa_id']); - $data['tpa_branch_id'] = $tpaBranchId; - $data['tpa_id'] = $tpaId; + $data['tpa_branch_id'] = $tpaBranchId; + $data['tpa_id'] = $tpaId; } $this->leadsModel->where('id', $lead_id)->set($data)->update(); - if (isset($params['installments']) && !empty($params['installments'])) { + if (isset($params['installments']) && ! empty($params['installments'])) { $installment_data = json_decode($params['installments'], true); - if (!empty($installment_data)) { + if (! empty($installment_data)) { foreach ($installment_data as $key => $value) { // print_r($value);die - $value['payment_date'] = !empty($value['payment_date']) && strtotime($value['payment_date']) + $value['payment_date'] = ! empty($value['payment_date']) && strtotime($value['payment_date']) ? date('Y/m/d', strtotime($value['payment_date'])) : null; - if (isset($value['id']) && !empty($value['id'])) { + if (isset($value['id']) && ! empty($value['id'])) { $this->leadInstallmentPaymentDetails->where('id', $value['id'])->set($value)->update(); } else { $this->leadInstallmentPaymentDetails->insert($value); @@ -3603,7 +3605,7 @@ class LeadsController extends BaseController ->update(); } - //delete attachment file + //delete attachment file unlink($file_path); return $this->respond(['status' => 'success', 'code' => 200, 'data' => $result_data, 'is_placement' => $is_placement], 200); } @@ -3631,7 +3633,7 @@ class LeadsController extends BaseController $data = $this->levelContactModel->getContactForRFQ($insurerId, $insurerBranchId); - if (!empty($data)) { + if (! empty($data)) { return $this->respond(['status' => true, 'data' => $data], 200); } else { return $this->respond(['status' => false, 'data' => $data, 'message' => 'No contacts were found for the selected insurer.'], 200); @@ -3649,12 +3651,12 @@ class LeadsController extends BaseController $defaultHeaders = [ [ 'parentHeader' => 'Sno', - 'subHeaders' => ['-'] + 'subHeaders' => ['-'], ], [ 'parentHeader' => 'Particulars', - 'subHeaders' => ['-'] - ] + 'subHeaders' => ['-'], + ], ]; // Add default headers to the result @@ -3668,10 +3670,10 @@ class LeadsController extends BaseController if ($subHeader === $insurer) { $headerData[] = [ 'parentHeader' => $header['parentHeader'], - 'subHeaders' => [ - // 'Quote Asked', // Default value - $subHeader // Matched insurer key - ] + 'subHeaders' => [ + // 'Quote Asked', // Default value + $subHeader, // Matched insurer key + ], ]; break; } @@ -3683,14 +3685,14 @@ class LeadsController extends BaseController foreach ($data['table_data']['data'] as $entry) { - $sno = $entry['SNO']; - $items = $entry['items']; + $sno = $entry['SNO']; + $items = $entry['items']; $dataEntry = $entry['data']; $result = [ - "SNO" => $sno, + "SNO" => $sno, "items" => $items, - "data" => [] + "data" => [], ]; foreach ($dataEntry as $item) { @@ -3698,14 +3700,14 @@ class LeadsController extends BaseController // Include Sno and Particulars by default if (in_array($item['parentth'], ['Sno', 'Particulars'])) { $result['data'][] = [ - "parentth" => $item['parentth'], - "subth" => $item['subth'], - "value" => $item['value'], - "input_value" => $item['input_value'] + "parentth" => $item['parentth'], + "subth" => $item['subth'], + "value" => $item['value'], + "input_value" => $item['input_value'], ]; } - // Include Proposal with Quote Asked by default + // Include Proposal with Quote Asked by default /* For proposel do not remove it */ // if ($item['parentth'] === $proposel && $item['subth'] === "Quote Asked") { // $result['data'][] = [ @@ -3719,10 +3721,10 @@ class LeadsController extends BaseController // Example of including matching specific proposals and insurers if ($item['parentth'] === $proposel && $item['subth'] === $insurer) { $result['data'][] = [ - "parentth" => $item['parentth'], - "subth" => $item['subth'], - "value" => $item['value'], - "input_value" => $item['input_value'] + "parentth" => $item['parentth'], + "subth" => $item['subth'], + "value" => $item['value'], + "input_value" => $item['input_value'], ]; } } @@ -3741,8 +3743,8 @@ class LeadsController extends BaseController } $data['table_data']['headers'] = $headerData; - $data['table_data']['data'] = $columnData; - $data['premium_data']['data'] = $premiumData; + $data['table_data']['data'] = $columnData; + $data['premium_data']['data'] = $premiumData; return $data; } @@ -3796,7 +3798,6 @@ class LeadsController extends BaseController } } - foreach ($first_json['table_data']['data'] as &$item) { $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) { return $entry['subth'] !== $insurer['display_name']; @@ -3824,8 +3825,8 @@ class LeadsController extends BaseController } // Reindex arrays to maintain proper structure - $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']); - $first_json['table_data']['data'] = array_values($first_json['table_data']['data']); + $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']); + $first_json['table_data']['data'] = array_values($first_json['table_data']['data']); $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) { $proposal['insurers'] = array_values($proposal['insurers']); return $proposal; @@ -3856,7 +3857,6 @@ class LeadsController extends BaseController // Ensure to unset the reference after the loop unset($row); - // Remove insurers from Proposal Data key for RFQ foreach ($first_json['proposal_data']['over_all_column_data'] as $key => &$proposal) { if (isset($proposal['insurers'])) { @@ -3877,13 +3877,12 @@ class LeadsController extends BaseController //----- Featch Lead data and insert Client ------------------------------------------------------------------------------------------- - public function featchLeadDataAndInsertClient($lead_id) { try { $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first(); - if (!$data) { + if (! $data) { $this->myLogger->logme('featchLeadDataAndInsertClient', "Lead not found or inactive", ['lead_id' => $lead_id]); return $this->respond(['status' => false, 'message' => 'Failed to create Client', 'data' => null], 200); } @@ -3893,10 +3892,10 @@ class LeadsController extends BaseController if ($result) { $policy_data = $this->clientPolicyModel->where('client_id', $result)->where('is_active', 1)->first(); return $this->respond([ - 'status' => true, - 'message' => 'New Client created successfully', - 'client_id' => $result, - 'data' => $data, + 'status' => true, + 'message' => 'New Client created successfully', + 'client_id' => $result, + 'data' => $data, 'client_policy_id' => $policy_data['id'] ?? null, ], 200); } @@ -3913,7 +3912,7 @@ class LeadsController extends BaseController { try { $client_data = $this->prepareClientData($data); - $client_id = $this->clientModel->insert($client_data); + $client_id = $this->clientModel->insert($client_data); if ($client_id) { $this->createClientBranchAndContactWithLeadData($data, $client_id); @@ -3931,7 +3930,7 @@ class LeadsController extends BaseController { try { $branch_data = $this->prepareClientBranchData($data, $client_id); - $branch_id = $this->clientBranchModel->insert($branch_data); + $branch_id = $this->clientBranchModel->insert($branch_data); if ($branch_id) { $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update(); @@ -3951,7 +3950,7 @@ class LeadsController extends BaseController { try { $client_policy_data = $this->prepareClientPolicyData($data, $client_id, $branch_id); - $client_policy_id = $this->clientPolicyModel->insert($client_policy_data); + $client_policy_id = $this->clientPolicyModel->insert($client_policy_data); if ($client_policy_id) { $this->leadsModel->where('id', $data['id'])->set('is_client_created', $client_id)->update(); @@ -4042,7 +4041,7 @@ class LeadsController extends BaseController $placementJson = $this->getPlacementJson($data); if ($placementJson) { $client_policy_data['placement_json'] = $placementJson; - $client_policy_data['policy_terms'] = $this->convertNonEbQCRJsonToPolicyTerms(json_decode($placementJson, true)); + $client_policy_data['policy_terms'] = $this->convertNonEbQCRJsonToPolicyTerms(json_decode($placementJson, true)); } } // print_r($client_policy_data); die; @@ -4054,13 +4053,13 @@ class LeadsController extends BaseController { try { $proposel_data = json_decode($data['proposel_data'], true); - $QCRData = $this->RFQModel->where('is_active', 1)->where('lead_id', $data['id'])->first(); + $QCRData = $this->RFQModel->where('is_active', 1)->where('lead_id', $data['id'])->first(); - if (!$QCRData) { + if (! $QCRData) { throw new \Exception('RFQ Data not found'); } - $JSON = json_decode($QCRData['json'], true); + $JSON = json_decode($QCRData['json'], true); $converted_json = $this->transformProposelData($JSON, $proposel_data['proposel_name'], $proposel_data['insurer_name']); // log_message('error', 'Converted JSON: ' . json_encode($converted_json)); @@ -4075,7 +4074,7 @@ class LeadsController extends BaseController { $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first(); - if (!$data) { + if (! $data) { return $this->respond(['status' => false, 'message' => 'Failed to create policy', 'data' => null], 200); } @@ -4101,26 +4100,26 @@ class LeadsController extends BaseController // Initialize age_ratio based on policy type $age_ratio = $policy_type == 2 ? [ - 'self' => ['min' => '18', 'max' => '60'], + 'self' => ['min' => '18', 'max' => '60'], 'spouse' => ['min' => 0, 'max' => 0], - 'child' => ['min' => 0, 'max' => '25'], + 'child' => ['min' => 0, 'max' => '25'], 'elders' => ['min' => 0, 'max' => 0], ] : [ - 'self' => ['min' => '18', 'max' => '60'] + 'self' => ['min' => '18', 'max' => '60'], ]; foreach ($data['table_data']['data'] as $dataRow) { $item = $dataRow['items'] ?? ''; foreach ($dataRow['data'] as $cellData) { - $parentth = $cellData['parentth'] ?? ''; - $subth = $cellData['subth'] ?? ''; + $parentth = $cellData['parentth'] ?? ''; + $subth = $cellData['subth'] ?? ''; $input_value = $cellData['input_value'] != "" ? $cellData['input_value'] : ($cellData['value'] ?? ''); - $value = $cellData['value'] ?? ''; + $value = $cellData['value'] ?? ''; - if( $item == "family_composition" && $subth == $insurer_name && $policy_type == 2){ + if ($item == "family_composition" && $subth == $insurer_name && $policy_type == 2) { $age_ratio_array = json_decode($input_value, true)['age_ratio'] ?? null; - if(!empty($age_ratio_array)){ + if (! empty($age_ratio_array)) { $age_ratio = $age_ratio_array; } } @@ -4132,7 +4131,7 @@ class LeadsController extends BaseController switch (true) { - // CASE 1: Handle special conditions + // CASE 1: Handle special conditions case str_starts_with($item, 'special_condition') && $parentth === $proposel_name && $subth === $insurer_name: // log_message("error","INPUT".json_encode($input_value)); $parts = explode('-', $input_value); @@ -4146,8 +4145,8 @@ class LeadsController extends BaseController // CASE 2: Handle sum insured case in_array($item, ['sum_insured', 'sumInsured2']): - $si_amt = explode(',', $value); - $terms_array[$item] = $si_amt[0] ?? ''; + $si_amt = explode(',', $value); + $terms_array[$item] = $si_amt[0] ?? ''; $terms_array['multiple_sum_insured'] = array_slice($si_amt, 1); // Add age_ratio after Sum insured @@ -4183,7 +4182,7 @@ class LeadsController extends BaseController public function convertNonEbQCRJsonToPolicyTerms($allTableData) { - if (!empty($allTableData)) { + if (! empty($allTableData)) { array_pop($allTableData); // Remove the last item from the array $terms_array = []; @@ -4199,8 +4198,8 @@ class LeadsController extends BaseController foreach ($dataRow['data'] as $cellData) { $parentth = $cellData['parentth'] ?? ''; - $subth = $cellData['subth'] ?? ''; - $value = $cellData['display_content'] ?? ''; + $subth = $cellData['subth'] ?? ''; + $value = $cellData['display_content'] ?? ''; // Skip unwanted keys if (in_array($parentth, ['SNO', 'Particulars', 'Action']) || $subth === 'Sum Insured' || $subth === 'Fidelity Limit') { @@ -4213,13 +4212,13 @@ class LeadsController extends BaseController } // Set the value directly, overwriting with latest encountered - if (!empty($item) && !empty($value)) { + if (! empty($item) && ! empty($value)) { $finalItem = $item; if (strpos($tableGroup['tableId'], 'summary') !== false) { $policy_type = explode('_', $tableGroup['tableId'])[0] ?? ''; - $finalItem = $policy_type . ' - ' . $item; + $finalItem = $policy_type . ' - ' . $item; } $terms_array[$finalItem] = $value; } @@ -4242,11 +4241,11 @@ class LeadsController extends BaseController ->where('lead_id', $data['id']) ->first(); - if (!$QCRData || empty($QCRData['json'])) { + if (! $QCRData || empty($QCRData['json'])) { return null; } - $jsonArray = json_decode($QCRData['json'], true); + $jsonArray = json_decode($QCRData['json'], true); $proposalData = array_pop($jsonArray); // Get last item and remove it from the array if (empty($jsonArray)) { @@ -4263,14 +4262,14 @@ class LeadsController extends BaseController ); }, $jsonArray); - if (!empty($proposalData)) { + if (! empty($proposalData)) { foreach ($proposalData['proposal_data']['over_all_column_data'] as $key => &$proposal) { // Keep only the required proposal if ($key !== $proposel_data['proposel_name']) { unset($proposalData['proposal_data']['over_all_column_data'][$key]); } else { // Within the matched proposal, filter insurers - if (!empty($proposal['insurers'])) { + if (! empty($proposal['insurers'])) { $proposal['insurers'] = array_values(array_filter($proposal['insurers'], function ($insurer) use ($proposel_data) { return $insurer['display_name'] === $proposel_data['insurer_name']; })); @@ -4280,7 +4279,6 @@ class LeadsController extends BaseController unset($proposal); // Good practice after foreach by reference } - $placement_json_data[] = $proposalData; return json_encode($placement_json_data); @@ -4288,21 +4286,20 @@ class LeadsController extends BaseController //------------------------------------------------------------------------------------------------ - public function transformMailContent($lead_data, $mail_content, $page_name) { $current_year = date('Y'); - $next_year = $current_year + 1; - $policy_year = "$current_year-$next_year"; - $page_name = $page_name == "QCR" ? "Quote Comparison Report" : $page_name; - $log_path = base_url() . '/public/assets/images/Nhance-Logo-Final.png'; + $next_year = $current_year + 1; + $policy_year = "$current_year-$next_year"; + $page_name = $page_name == "QCR" ? "Quote Comparison Report" : $page_name; + $log_path = base_url() . '/public/assets/images/Nhance-Logo-Final.png'; // $log_path ='https://venbait.in/nhance/dev/public/assets/images/Nhance-Logo-Final.png'; // dd($log_path); $policy_expiry = strtotime($lead_data['policy_end_date']); $formatted_policy = date("d-m-Y", $policy_expiry); - $logged_user_id = get_session_userid(); + $logged_user_id = get_session_userid(); $logged_user_data = $this->userModel->where("id", $logged_user_id)->where("is_active", 1)->first(); @@ -4317,7 +4314,6 @@ class LeadsController extends BaseController $message = str_replace("{{POLICY_YEAR}}", $policy_year, $message); $message = str_replace("{{POLICY_END_DATE}}", " (Due On " . $formatted_policy . ")", $message); - $message = str_replace("{{LOGGED_USER_NAME}}", ucfirst($logged_user_data['first_name'] ?? "") . " " . ucfirst($logged_user_data['last_name'] ?? ""), $message); $message = str_replace("{{LOGGED_USER_EMAIL}}", $logged_user_data['email'] ?? "", $message); $message = str_replace("{{LOGGED_USER_MOBILE}}", $logged_user_data['mobile'] ?? "", $message); @@ -4329,6 +4325,125 @@ class LeadsController extends BaseController } } + /** + * Return subject and mail content for a lead and a given template type. + * + * GET params: + * - lead_id (int, required) + * - template_type (string, one of: rfq, qcr, placement; default: rfq) + * + * Response: + * { + * status: 'success'|'error', + * code: 200|4xx|5xx, + * subject: string, + * mail_content: string, + * message: string + * } + */ + public function getLeadMailTemplate() + { + try { + $leadId = (int) $this->request->getGet('lead_id'); + $templateType = strtolower((string) $this->request->getGet('template_type')); + + if ($leadId <= 0) { + return $this->respond( + ['status' => 'error', 'code' => 400, 'message' => 'Invalid lead id'], + 400 + ); + } + + if (! in_array($templateType, ['rfq', 'qcr', 'placement'], true)) { + // Default to RFQ if not provided or invalid + $templateType = 'rfq'; + } + + // Fetch master lead data similar to sendMailWithAttachement / viewRFQ + $lead_data = $this->leadsModel + ->select(' + leads.*, + policy_type.long_name, + policy_type.policy_type, + user_profiles.email as created_person_email + ') + ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + ->join('user_profiles', 'leads.created_by = user_profiles.id', 'left') + ->where('leads.id', $leadId) + ->where('leads.is_active', 1) + ->first(); + + if (! $lead_data) { + $this->myLogger->logme('error', "MAIL TEMPLATE: lead not found | lead_id={$leadId}"); + return $this->respond( + ['status' => 'error', 'code' => 404, 'message' => 'Lead not found'], + 404 + ); + } + + // Determine page name and mail template type + if ($templateType === 'qcr') { + $pageName = 'QCR'; + $mailTemplateId = ''; + } elseif ($templateType === 'placement') { + $pageName = 'Placement'; + $mailTemplateId = 'placement'; + } else { + // rfq + $pageName = 'RFQ'; + $mailTemplateId = ''; + } + + $rawMailTemplate = $this->getMailTemplate($mailTemplateId); + $rawSubjectTemplate = $this->getSubjectTemplate($lead_data); + + $mail_content = $this->transformMailContent($lead_data, $rawMailTemplate, $pageName); + $subject = $this->transformMailContent($lead_data, $rawSubjectTemplate, $pageName); + + + //attachement files + $attachments = $this->leadFilesModel + ->where('lead_id', $leadId) + ->where('type !=', 2) + ->where('is_active', 1) + ->findAll(); + + $attachment_html = view('rfq/attachment_files', ['multi_file_data' => $attachments]); + + return $this->respond( + [ + 'status' => 'success', + 'code' => 200, + 'subject' => $subject, + 'mail_content' => $mail_content, + 'message' => 'Mail template generated successfully', + 'attachment_html' => $attachment_html, + ], + 200 + ); + } catch (\Throwable $e) { + $errorDetails = [ + 'message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + ]; + + $this->myLogger->logme( + 'error', + 'MAIL TEMPLATE: exception occurred | ' . json_encode($errorDetails) + ); + + return $this->respond( + [ + 'status' => 'error', + 'code' => 500, + 'message' => 'Failed to generate mail template', + ], + 500 + ); + } + } + public function getLastFiveFinancialYears(): array { $year = (int) date('Y'); @@ -4341,14 +4456,117 @@ class LeadsController extends BaseController $financialYears = []; for ($i = 0; $i < 6; $i++) { - $startYear = $currentFYStart - $i; - $endYear = $startYear + 1; + $startYear = $currentFYStart - $i; + $endYear = $startYear + 1; $financialYears[] = "{$startYear}-{$endYear}"; } return $financialYears; } + /** + * Fetch basic placement-related lead data for Non-EB placement modal (AJAX). + * + * Route: GET /rfq/placementData/{lead_id} + */ + public function getPlacementData($id) + { + try { + $leadId = (int) $id; + + if ($leadId <= 0) { + return $this->respond( + ['status' => 'error', 'code' => 400, 'message' => 'Invalid lead id'], + 400 + ); + } + + $lead = $this->leadsModel + ->where('id', $leadId) + ->where('is_active', 1) + ->first(); + + if (! $lead) { + $this->myLogger->logme('error', "PLACEMENT DATA: lead not found | lead_id={$leadId}"); + return $this->respond( + ['status' => 'error', 'code' => 404, 'message' => 'Lead not found'], + 404 + ); + } + + $data = [ + 'id' => (int) $lead['id'], + 'policy_start_date' => ! empty($lead['policy_start_date']) ? date('d-m-Y', strtotime($lead['policy_start_date'])) : null, + 'policy_end_date' => ! empty($lead['policy_end_date']) ? date('d-m-Y', strtotime($lead['policy_end_date'])) : null, + 'placement_date' => ! empty($lead['placement_date']) ? date('d-m-Y', strtotime($lead['placement_date'])) : null, + 'payment_date' => ! empty($lead['payment_date']) ? date('d-m-Y', strtotime($lead['payment_date'])) : null, + 'utr_no' => $lead['utr_no'] ?? null, + 'premium_amount' => $lead['premium_amount'] ?? null, + 'cd_amount' => $lead['cd_amount'] ?? null, + 'total_amount' => $lead['total_amount'] ?? null, + 'is_cd' => isset($lead['is_cd']) ? (int) $lead['is_cd'] : 1, + 'is_installment' => isset($lead['is_installment']) ? (int) $lead['is_installment'] : 0, + 'no_of_installment' => $lead['no_of_installment'] ?? 1, + 'status' => $lead['status'] ?? null, + ]; + + // Fetch insurer level contacts based on lead's insurer/branch + $insurerId = $lead['insurer_id'] ?? null; + $insurerBranchId = $lead['insurer_branch_id'] ?? null; + // echo $insurerId;die(); + $insurerContacts = []; + if (! empty($insurerId)) { + // getContactForRFQ($insurerId, $branchId) returns insurer-level contacts + $contacts = $this->levelContactModel->getContactForRFQ($insurerId, $insurerBranchId); + // print_rr($contacts);die(); + if (! empty($contacts) && is_array($contacts)) { + foreach ($contacts as $contact) { + $insurerContacts[] = [ + 'id' => (int) ($contact['id'] ?? 0), + 'display' => trim( + ($contact['insurer_name'] ?? '') . ' - ' . + ($contact['branch_code'] ?? '') . ' - ' . + ($contact['contact_person_name'] ?? '') . ' - ' . + ($contact['contact_person_email'] ?? '') + ), + 'email' => $contact['contact_person_email'] ?? '', + ]; + } + } + } + + $data['insurer_contacts'] = $insurerContacts; + + return $this->respond( + [ + 'status' => 'success', + 'code' => 200, + 'data' => $data, + ], + 200 + ); + } catch (\Throwable $e) { + $errorDetails = [ + 'message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + ]; + + $this->myLogger->logme( + 'error', + 'PLACEMENT DATA: exception occurred | ' . json_encode($errorDetails) + ); + + return $this->respond( + [ + 'status' => 'error', + 'code' => 500, + 'message' => 'Failed to fetch placement data', + ], + 500 + ); + } + } // ------------ RFQ NON EB FUNCTIONS----------------------------------------------------------------------------------------- @@ -4358,27 +4576,47 @@ class LeadsController extends BaseController $this->loadLayout('view_rfq_non_eb'); } + /** + * Dedicated endpoint to view RFQ for Non-EB opportunities from the Opportunities List. + * Internally reuses the existing viewRFQ flow without modifying its logic. + */ + public function viewNonEbRFQFromList($id) + { + echo 'NONEB_RFQ'; + } + + /** + * Dedicated endpoint to view QCR for Non-EB opportunities from the Opportunities List. + * Internally reuses the existing viewRFQ flow without modifying its logic. + */ + public function viewNonEbQCRFromList($id) + { + echo 'NONEB_QCR'; + } + // get lead data for edit both EB and NON-EB - public function getLeadNonEB($type, $actual_lead_id = null ,$id = null) + public function getLeadNonEB($type, $actual_lead_id = null, $id = null) { // Convert '0' to null so it doesn't break your existing DB checks $actual_lead_id = ($actual_lead_id == 0 || $actual_lead_id == '0') ? null : $actual_lead_id; // Set basic data $data = [ - 'issuer' => $this->issuer, - 'client_type' => $this->clientType, - 'lead_type' => $this->leadType, - 'lead_status' => $this->leadsStatus, - 'policy_type' => $this->policyTypeModel->where('is_active', 1)->findAll(), - 'entity' => $this->kycEntityTypeModel->where('is_active', 1)->findAll(), - 'insurer' => $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(), - 'tpa' => $this->tpaBranchModel->getTpaBranchesWithTpaNames(), - 'lastFiveYears' => $this->getLastFiveFinancialYears(), - 'gpaClaimType' => $this->claim_type_for_gpa, - 'causeOfDeath' => $this->cause_of_death, + 'issuer' => $this->issuer, + 'client_type' => $this->clientType, + 'lead_type' => $this->leadType, + 'lead_status' => $this->leadsStatus, + 'policy_type' => $this->policyTypeModel->where('is_active', 1)->findAll(), + 'entity' => $this->kycEntityTypeModel->where('is_active', 1)->findAll(), + 'insurer' => $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(), + 'tpa' => $this->tpaBranchModel->getTpaBranchesWithTpaNames(), + 'lastFiveYears' => $this->getLastFiveFinancialYears(), + 'gpaClaimType' => $this->claim_type_for_gpa, + 'causeOfDeath' => $this->cause_of_death, 'selected_lead_type' => $type, 'actual_lead_id' => $actual_lead_id, ]; + $data['tab_name'] = 'Opportunities'; + $data['page_name'] = 'Opportunities'; if ($actual_lead_id > 0) { @@ -4411,36 +4649,34 @@ class LeadsController extends BaseController ->where('user_profiles.is_active', 1) ->findAll(); - - - if (!empty($id)) { + if (! empty($id)) { $data['lead_edit_data'] = $this->leadsModel->where('id', $id)->first() ?? []; $data['lead_edit_data']['multi_file_data'] = $this->leadFilesModel - ->where('lead_id', $id) - ->where('type !=', 2) - ->where('is_active', 1) - ->findAll() ?? null; + ->where('lead_id', $id) + ->where('type !=', 2) + ->where('is_active', 1) + ->findAll() ?? null; $data['lead_edit_data']['lead_file_count'] = count($data['lead_edit_data']['multi_file_data']); // Decode and merge custom fields if present - $custom_fields_data = !empty($data['lead_edit_data']['custom_fields']) + $custom_fields_data = ! empty($data['lead_edit_data']['custom_fields']) ? json_decode($data['lead_edit_data']['custom_fields'], true) : []; - if (!empty($custom_fields_data) && is_array($custom_fields_data)) { + if (! empty($custom_fields_data) && is_array($custom_fields_data)) { $data['lead_edit_data'] = array_merge($data['lead_edit_data'], $custom_fields_data); } - if (!empty($data['lead_edit_data'])) { + if (! empty($data['lead_edit_data'])) { foreach (['policy_start_date', 'policy_end_date', 'source_policy_start_date', 'source_policy_end_date', 'incurred_claims_date', 'next_reminder_date'] as $dateField) { - $data['lead_edit_data'][$dateField] = !empty($data['lead_edit_data'][$dateField]) + $data['lead_edit_data'][$dateField] = ! empty($data['lead_edit_data'][$dateField]) ? change_date_format($data['lead_edit_data'][$dateField], 'Y-m-d', 'd/m/Y') : null; } - $data['lead_edit_data']['fin_years_claims_array'] = !empty($data['lead_edit_data']['fin_years_claims']) + $data['lead_edit_data']['fin_years_claims_array'] = ! empty($data['lead_edit_data']['fin_years_claims']) ? json_decode($data['lead_edit_data']['fin_years_claims'], true)['finyear'] ?? [] : []; @@ -4449,7 +4685,7 @@ class LeadsController extends BaseController $data ) ?? ""; - $html = view('rfq/multi_files', $data); + $html = view('rfq/multi_files', $data); $data['lead_edit_data']['multi_file_html'] = trim($html) !== '' ? $html : null; } @@ -4464,26 +4700,26 @@ class LeadsController extends BaseController return $this->loadLayout('leads_form_handler', $data); } - public function getLeadEmailHistory($id){ - if(!empty($id)){ - $result = $this->gmailSentHistoryModel - ->where('pk', $id) - ->where('module',"leads") - ->orderBy('created_at', 'desc') - ->findAll(); - if(!empty($result)){ - $result = !empty($result) ? $result : []; - return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); - }else{ - return $this->response->setJSON((['status' => 'error', 'message' => 'No History found']))->setStatusCode(400); - } - }else{ - return $this->response->setJSON((['status' => 'error', 'message' => 'ID not found']))->setStatusCode(404); + public function getLeadEmailHistory($id) + { + if (! empty($id)) { + $result = $this->gmailSentHistoryModel + ->where('pk', $id) + ->where('module', "leads") + ->orderBy('created_at', 'desc') + ->findAll(); + if (! empty($result)) { + $result = ! empty($result) ? $result : []; + return $this->response->setJSON((['status' => 'success', 'data' => $result]))->setStatusCode(200); + } else { + return $this->response->setJSON((['status' => 'error', 'message' => 'No History found']))->setStatusCode(400); } - + } else { + return $this->response->setJSON((['status' => 'error', 'message' => 'ID not found']))->setStatusCode(404); + } // Select * from gmail_sent_history where pk != "" and module = "leads"; - // echo $id; + // echo $id; } public function getPolicyTypeFields() @@ -4493,26 +4729,361 @@ class LeadsController extends BaseController $html = $this->generateViewPageHtml($policy_type_id) ?? ""; - if (!empty($html)) { + if (! empty($html)) { return $this->respond(['status' => true, 'code' => 200, 'message' => 'Policy Type FIELDS are found', 'data' => $html], 200); } else { return $this->respond(['status' => false, 'code' => 400, 'message' => 'Fields not found for this policy type'], 200); } } + /** + * AJAX endpoint to create or fetch RFQ Google Sheet for a lead. + * + * Flow: + * - Get lead_id from query param. + * - Fetch lead joined with policy_type (to read both misc columns). + * - If leads.misc has non-empty rfq_sheet_id, return that. + * - Else, read policy_type.misc.rfq_template_sheet_id and copy that template. + * - Apply protections (using RfqConfig if available). + * - Store new rfq_sheet_id back into leads.misc. + */ + public function createRfqSheet() + { + try { + $leadId = (int) $this->request->getGet('lead_id'); + + if ($leadId <= 0) { + return $this->respond( + ['status' => 'error', 'code' => 400, 'message' => 'Invalid lead id'], + 400 + ); + } + + $this->myLogger->logme('error', "RFQ Sheet: starting for lead_id={$leadId}"); + + // Fetch lead + policy type (including misc JSON from both) + $lead = $this->leadsModel + ->select(' + leads.*, + policy_type.policy_type, + policy_type.long_name, + policy_type.misc as policy_misc + ') + ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') + ->where('leads.id', $leadId) + ->where('leads.is_active', 1) + ->first(); + + if (! $lead) { + $this->myLogger->logme('error', "RFQ Sheet: lead not found | lead_id={$leadId}"); + return $this->respond( + ['status' => 'error', 'code' => 404, 'message' => 'Lead not found'], + 404 + ); + } + + // Decode leads.misc + $leadMisc = []; + if (! empty($lead['misc'])) { + $decoded = json_decode($lead['misc'], true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + $leadMisc = $decoded; + } else { + $this->myLogger->logme('error', "RFQ Sheet: invalid JSON in leads.misc | lead_id={$leadId}, misc={$lead['misc']}"); + } + } + + // If RFQ sheet already exists, just return it + if (! empty($leadMisc['rfq_sheet_id'])) { + $sheetId = (string) $leadMisc['rfq_sheet_id']; + $sheetLib = new GoogleSheetLib(); + $sheetUrl = $sheetLib->sheetUrl($sheetId); + + $this->myLogger->logme('error', "RFQ Sheet: existing sheet found | lead_id={$leadId}, sheet_id={$sheetId}"); + + return $this->respond( + [ + 'status' => 'success', + 'code' => 200, + 'sheet_id' => $sheetId, + 'sheet_url' => $sheetUrl, + 'message' => 'RFQ sheet already exists', + ], + 200 + ); + } + + // Decode policy_type.misc and get template id + $policyMisc = []; + if (! empty($lead['policy_misc'])) { + $decodedPolicy = json_decode($lead['policy_misc'], true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decodedPolicy)) { + $policyMisc = $decodedPolicy; + } else { + $this->myLogger->logme('error', "RFQ Sheet: invalid JSON in policy_type.misc | lead_id={$leadId}, policy_misc={$lead['policy_misc']}"); + } + } + + $templateId = $policyMisc['rfq_template_sheet_id'] ?? null; + if (empty($templateId)) { + $this->myLogger->logme( + 'error', + "RFQ Sheet: rfq_template_sheet_id missing | lead_id={$leadId}, policy_misc=" . ($lead['policy_misc'] ?? 'NULL') + ); + + return $this->respond( + [ + 'status' => 'error', + 'code' => 400, + 'message' => 'RFQ template not found for this policy type', + ], + 400 + ); + } + + // Prepare Google Sheet lib and config + $sheetLib = new GoogleSheetLib(); + + // Try to use RfqConfig if available for folder/protections + $parentFolderId = null; + $protections = []; + + try { + /** @var \Config\RfqConfig $rfqConfig */ + $rfqConfig = config('RfqConfig'); + if ($rfqConfig) { + $parentFolderId = $rfqConfig->rfqParentFolderId ?? null; + $protections = $rfqConfig->protections ?? []; + } + } catch (\Throwable $e) { + // Config is optional; just log and continue with defaults + $this->myLogger->logme('error', 'RFQ Sheet: error loading RfqConfig | ' . $e->getMessage()); + } + + // Fallback to same parent folder as GoogleSheetController if config not set + if (! $parentFolderId) { + return $this->respond( + [ + 'status' => 'error', + 'code' => 400, + 'message' => 'Google config not correct, contact administrator', + ], + 400); + } + + // Filename logic same as exportQCRandRFQ (lines 2660-2673) + $string = 'RFQ'; + $current_year = date('Y'); + $next_year = $current_year + 1; + $policy_year = "{$current_year}-{$next_year}"; + + $clientName = trim($lead['client_name'] ?? $lead['client_short_name'] ?? ''); + $policyType = trim($lead['policy_type'] ?? ''); + + if (! empty($lead['policy_end_date'])) { + $policy_expiry = strtotime($lead['policy_end_date']); + $formatted_policy = date('d-m-Y', $policy_expiry); + $sheetName = "{$clientName}_{$policyType}_{$string}_{$policy_year}(Due On {$formatted_policy}).xlsx"; + } else { + $sheetName = "{$clientName}_{$policyType}_{$string}_{$policy_year}_" . '.xlsx'; + } + + // Copy template in Drive + $newSheetId = $sheetLib->copyTemplate($templateId, $sheetName, $parentFolderId); + $this->myLogger->logme('error', "RFQ Sheet: template copied | lead_id={$leadId}, template_id={$templateId}, new_sheet_id={$newSheetId}"); + + // Apply permissions: get sales users from DB (team_id 5) and add as editors + $salesTeam = $this->userModel + ->select('user_profiles.email') + ->join('user_teams', 'user_profiles.id = user_teams.user_id') + ->where('user_teams.team_id', 5) + ->where('user_teams.is_active', 1) + ->where('user_profiles.is_active', 1) + ->findAll(); + $editorEmails = array_values(array_filter(array_unique(array_column($salesTeam, 'email')))); + if (! empty($editorEmails)) { + try { + $sheetLib->applyPermissions($newSheetId, [ + 'editors' => $editorEmails, + 'viewers' => [], + ]); + $this->myLogger->logme('error', "RFQ Sheet: permissions applied (sales team) | sheet_id={$newSheetId}, count=" . count($editorEmails)); + } catch (\Throwable $e) { + $this->myLogger->logme( + 'error', + "RFQ Sheet: failed to apply permissions | sheet_id={$newSheetId}, error=" . $e->getMessage() + ); + } + } + + // Apply protections if configured + if (! empty($protections)) { + try { + $sheetLib->applyProtections($newSheetId, $protections); + $this->myLogger->logme('error', "RFQ Sheet: protections applied | sheet_id={$newSheetId}"); + } catch (\Throwable $e) { + $this->myLogger->logme( + 'error', + "RFQ Sheet: failed to apply protections | sheet_id={$newSheetId}, error=" . $e->getMessage() + ); + } + } + + // Update leads.misc with new rfq_sheet_id + $leadMisc['rfq_sheet_id'] = $newSheetId; + $this->leadsModel->update($leadId, [ + 'misc' => json_encode($leadMisc), + 'status' => 'rfq_created', + ]); + + $sheetUrl = $sheetLib->sheetUrl($newSheetId); + + $this->myLogger->logme( + 'error', + "RFQ Sheet: created and stored | lead_id={$leadId}, sheet_id={$newSheetId}" + ); + + return $this->respond( + [ + 'status' => 'success', + 'code' => 200, + 'sheet_id' => $newSheetId, + 'sheet_url' => $sheetUrl, + 'message' => 'RFQ sheet created successfully', + ], + 200 + ); + } catch (\Throwable $e) { + $errorDetails = [ + 'message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + ]; + + $this->myLogger->logme( + 'error', + 'RFQ Sheet: exception occurred | ' . json_encode($errorDetails) + ); + + return $this->respond( + [ + 'status' => 'error', + 'code' => 500, + 'message' => 'Failed to create RFQ sheet', + ], + 500 + ); + } + } + + /** + * Download RFQ/QCR Excel file from Google Sheet for Non-EB leads. + * + * Expects $lead_data to contain misc JSON with rfq_sheet_id or qcr_sheet_id. + * Returns an array compatible with constructNonEbExcelToSaveTemp: + * [ + * 'filePath' => string, + * 'fileName' => string, + * ] + */ + protected function downloadFileFromGoogleSheet(array $lead_data): array + { + try { + $leadId = (int) ($lead_data['id'] ?? 0); + + // Decode misc JSON + $misc = []; + if (! empty($lead_data['misc'])) { + $decoded = json_decode($lead_data['misc'], true); + if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { + $misc = $decoded; + } else { + $this->myLogger->logme('error', "GSHEET DOWNLOAD: invalid JSON in leads.misc | lead_id={$leadId}, misc={$lead_data['misc']}"); + } + } + + // Prefer RFQ sheet id, fallback to QCR if needed + $sheetId = $misc['rfq_sheet_id'] ?? ($misc['qcr_sheet_id'] ?? null); + + if (empty($sheetId)) { + $this->myLogger->logme('error', "GSHEET DOWNLOAD: sheet id missing in misc | lead_id={$leadId}"); + // Fallback: behave like old flow and construct Non-EB Excel locally + // $file_info = $this->constructNonEbExcelToSaveTemp($leadId, 1, null); + // return [ + // 'filePath' => $file_info['filePath'], + // 'fileName' => $file_info['fileName'], + // ]; + } + + $this->myLogger->logme('error', "GSHEET DOWNLOAD: starting download | lead_id={$leadId}, sheet_id={$sheetId}"); + + $sheetLib = new GoogleSheetLib(); + $binary = $sheetLib->downloadExcel($sheetId); + + if (! $binary) { + $this->myLogger->logme('error', "GSHEET DOWNLOAD: empty content from Google | lead_id={$leadId}, sheet_id={$sheetId}"); + throw new \RuntimeException('Empty content from Google Sheet'); + } + + $filename = "lead_{$leadId}_" . date('Ymd_His') . '.xlsx'; + $uploadDir = WRITEPATH . 'tmp/'; + $uploadFilePath = $uploadDir . $filename; + + if (! is_dir($uploadDir)) { + if (! mkdir($uploadDir, 0777, true) && ! is_dir($uploadDir)) { + $this->myLogger->logme('error', "GSHEET DOWNLOAD: failed to create tmp dir | path={$uploadDir}"); + throw new \RuntimeException('Failed to create temporary directory for Excel download'); + } + } + + $bytes = file_put_contents($uploadFilePath, $binary); + if ($bytes === false) { + $this->myLogger->logme('error', "GSHEET DOWNLOAD: failed to write file | path={$uploadFilePath}"); + throw new \RuntimeException('Failed to write downloaded Excel file'); + } + + $this->myLogger->logme('error', "GSHEET DOWNLOAD: saved file | lead_id={$leadId}, path={$uploadFilePath}"); + + return [ + 'filePath' => $uploadFilePath, + 'fileName' => $filename, + ]; + } catch (\Throwable $e) { + $errorDetails = [ + 'message' => $e->getMessage(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + ]; + + $this->myLogger->logme( + 'error', + 'GSHEET DOWNLOAD: exception occurred | ' . json_encode($errorDetails) + ); + + // Final fallback to existing Non-EB Excel generator to avoid breaking mail flow + // $leadId = (int) ($lead_data['id'] ?? 0); + // $file_info = $this->constructNonEbExcelToSaveTemp($leadId, 1, null); + + // return [ + // 'filePath' => $file_info['filePath'], + // 'fileName' => $file_info['fileName'], + // ]; + } + } + public function generateViewPageHtml($policy_type_id, $data = []) { $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames(); - $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); + $data['tpa'] = $this->tpaBranchModel->getTpaBranchesWithTpaNames(); $viewMap = [ - 1 => 'rfq/gpa', - 6 => 'rfq/gpa', - 7 => 'rfq/gpa', - 2 => 'rfq/gmc', - 3 => 'rfq/gmc', - 4 => 'rfq/gmc', - 5 => 'rfq/gmc', + 1 => 'rfq/gpa', + 6 => 'rfq/gpa', + 7 => 'rfq/gpa', + 2 => 'rfq/gmc', + 3 => 'rfq/gmc', + 4 => 'rfq/gmc', + 5 => 'rfq/gmc', 17 => 'rfq/burglary', 22 => 'rfq/car', 23 => 'rfq/cpm', @@ -4529,7 +5100,7 @@ class LeadsController extends BaseController 45 => 'rfq/marine', 46 => 'rfq/marine', 47 => 'rfq/marine', - 50 => 'rfq/office' + 50 => 'rfq/office', ]; return isset($viewMap[$policy_type_id]) ? view($viewMap[$policy_type_id], $data) : ""; @@ -4539,13 +5110,13 @@ class LeadsController extends BaseController public function constructNonEbExcelToSaveTemp($lead_id, $type, $propsal_and_insurer = null) { - $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); + $rfq_data = $this->RFQModel->getRFQTableDataWithLeadIDAndType($lead_id, $type); $claim_history = $rfq_data['claim_history']; // dd($claim_history); - $lead_data = json_decode($rfq_data['custom_fields'], true) ?? []; + $lead_data = json_decode($rfq_data['custom_fields'], true) ?? []; $lead_data['claim_history'] = $claim_history; // dd($lead_data); - if (!is_array($lead_data)) { + if (! is_array($lead_data)) { $lead_data = []; } @@ -4562,30 +5133,29 @@ class LeadsController extends BaseController $lead_data = array_merge(['Insured' => $rfq_data['client_name']], $lead_data); $policy_registration_data = []; - if (isset($rfq_data['registration_json']) && !empty($rfq_data['registration_json'])) { + if (isset($rfq_data['registration_json']) && ! empty($rfq_data['registration_json'])) { $policy_registration_data = json_decode($rfq_data['registration_json'], true); } - - $jsonData = json_decode($rfq_data['json'], true); + $jsonData = json_decode($rfq_data['json'], true); $proposalData = end($jsonData); array_pop($jsonData); $length = 0; // dd($jsonData[0]['table_data']['headers']); - foreach ($jsonData as $key => $data) { + foreach ($jsonData as $key => $data) { if ($type == 2) { - $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); + $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); // Kint::dump($data, 'Second'); if ($propsal_and_insurer !== null) { list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); - $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key); + $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key); } unset($data['proposalData']); } else if ($type == 1) { - $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); + $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); unset($data['proposalData']); } } @@ -4616,45 +5186,40 @@ class LeadsController extends BaseController } $spreadsheet = new Spreadsheet(); - $sheet = $spreadsheet->getActiveSheet(); + $sheet = $spreadsheet->getActiveSheet(); $sheet->setTitle($sheetName); - - // Start with lead_data at the top $rowNumber = 1; - $title = "Nhance India Insurance Broking Pvt Ltd"; + $title = "Nhance India Insurance Broking Pvt Ltd"; $mergeRange1 = "A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"; $sheet->mergeCells($mergeRange1); $sheet->setCellValue("A{$rowNumber}", $title); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ - 'font' => [ + 'font' => [ 'bold' => true, - 'size' => 20 + 'size' => 20, ], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); // Calculate title width $maxWidthA = mb_strlen($title); - // dd($columnLetterForImage); - // Set column width to fit the image properly + // dd($columnLetterForImage); + // Set column width to fit the image properly $sheet->getColumnDimension($columnLetterForImage)->setWidth(40); // Adjust as needed - $sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed - + $sheet->getRowDimension($rowNumber)->setRowHeight(40); // Adjust as needed $drawing = new Drawing(); - $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path + $path = ROOTPATH . "public/assets/images/Nhance-Logo-Final.png"; // Use FCPATH for server path $drawing->setPath($path); $drawing->setCoordinates("{$columnLetterForImage}{$rowNumber}"); // Set position in column C - $drawing->setHeight(35); // Adjust image height - - + $drawing->setHeight(35); // Adjust image height // Apply center alignment to the cell $sheet->getStyle("{$columnLetterForImage}{$rowNumber}")->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); @@ -4673,15 +5238,15 @@ class LeadsController extends BaseController // } // Kint::dump($key); // Kint::dump($value); - $formattedKey = ucwords(str_replace('_', ' ', $key)); - $formattedKey = $formattedKey == "Risk Location" ? "Risk Details" : $formattedKey; - $formattedKey = $formattedKey == "Address" ? "Communication Address" : $formattedKey; + $formattedKey = ucwords(str_replace('_', ' ', $key)); + $formattedKey = $formattedKey == "Risk Location" ? "Risk Details" : $formattedKey; + $formattedKey = $formattedKey == "Address" ? "Communication Address" : $formattedKey; $formattedValue = ucwords(str_replace("_", " ", $value)); if ($key == "claim_history") { - $formattedValue = $value == "1" ? "Yes" : "No"; - $formattedKey = "Claim Experience"; + $formattedValue = $value == "1" ? "Yes" : "No"; + $formattedKey = "Claim Experience"; } // Kint::dump($formattedValue); @@ -4696,10 +5261,10 @@ class LeadsController extends BaseController // Apply styles for alignment and bold text in A:B $sheet->getStyle($mergeRangeKey)->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); @@ -4710,7 +5275,7 @@ class LeadsController extends BaseController // ]); // } - // Track max width needed for columns + // Track max width needed for columns $maxWidthA = max($maxWidthA, mb_strlen($formattedKey)); // Consider title and keys $maxWidthB = max($maxWidthB, mb_strlen((string) $value)); // if (!empty($policy_registration_data)) { @@ -4721,7 +5286,6 @@ class LeadsController extends BaseController $rowNumber++; } // die(); - // Set column width based on max content length (adjusted for padding) $sheet->getColumnDimension('A')->setWidth($maxWidthA * 1.2); @@ -4730,9 +5294,9 @@ class LeadsController extends BaseController // $rowNumber += 1; //Policy Registration - if (!empty($policy_registration_data)) { + if (! empty($policy_registration_data)) { foreach ($policy_registration_data as $key => $value) { - // kint::dump($value); + // kint::dump($value); $startRow = $rowNumber; // Track where the block starts // Title Row @@ -4742,13 +5306,13 @@ class LeadsController extends BaseController // Title Style $sheet->getStyle($titleMergeRangeKey)->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], - 'fill' => [ - 'fillType' => Fill::FILL_SOLID, + 'fill' => [ + 'fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'ADD8E6'], ], ]); @@ -4762,10 +5326,10 @@ class LeadsController extends BaseController $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $value['policyType']); $sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); @@ -4776,10 +5340,10 @@ class LeadsController extends BaseController $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", ucfirst($key) . " Policy"); $sheet->getStyle("A{$rowNumber}:C{$rowNumber}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); @@ -4787,17 +5351,17 @@ class LeadsController extends BaseController } // Type of Business & Nature of Business - if (isset($value['productSelection']) && !empty($value['productSelection'])) { + if (isset($value['productSelection']) && ! empty($value['productSelection'])) { // Type of Business $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"); $sheet->setCellValue("A{$rowNumber}", "Type of Business"); $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $this->buisnessType[$value['productSelection']['type_of_buisness']] ?? ''); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); @@ -4809,33 +5373,33 @@ class LeadsController extends BaseController $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", $value['productSelection']['buisness_nature'] ?? ''); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); $rowNumber++; } - if (isset($value['policyDetails']) && !empty($value['policyDetails'])) { + if (isset($value['policyDetails']) && ! empty($value['policyDetails'])) { // Type of Business $sheet->mergeCells("A{$rowNumber}:{$columnLetterForTitle}{$rowNumber}"); $sheet->setCellValue("A{$rowNumber}", "Terrorism"); $sheet->setCellValue("{$columnLetterForImage}{$rowNumber}", ucfirst($value['policyDetails']['terrorism'] ?? 'No')); $sheet->getStyle("A{$rowNumber}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); $rowNumber++; } - if (!empty($value['locations'])) { + if (! empty($value['locations'])) { foreach ($value['locations'] as $index => $location) { // Merge title cell @@ -4852,10 +5416,10 @@ class LeadsController extends BaseController // Style the title cell $sheet->getStyle("A{$rowNumber}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); @@ -4863,7 +5427,6 @@ class LeadsController extends BaseController } } - $endRow = $rowNumber; // Block ends at previous row // Apply border to the whole block @@ -4871,7 +5434,7 @@ class LeadsController extends BaseController 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => '000000'], + 'color' => ['argb' => '000000'], ], ], ]); @@ -4889,17 +5452,17 @@ class LeadsController extends BaseController if ($type == 2) { - $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); + $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); // Kint::dump($data, 'Second'); if ($propsal_and_insurer !== null) { list($proposal_key, $insurer_key) = explode('-', $propsal_and_insurer, 2); - $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key); + $data = $this->transformNonEbProposelData($data, $proposal_key, $insurer_key, $key); } unset($data['proposalData']); } else if ($type == 1) { - $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); + $data = $this->convertNonEbJsonForQCR($data, $type, $proposalData, $key); unset($data['proposalData']); } @@ -4922,7 +5485,6 @@ class LeadsController extends BaseController $sheet->getColumnDimension($columnLetter)->setWidth(60); $sheet->getColumnDimension('C')->setWidth(35); - if ($header['parentHeader'] == 'Policy') { // $header['parentHeader'] = 'S.No.'; $sheet->getColumnDimension('A')->setWidth(10); @@ -4937,20 +5499,19 @@ class LeadsController extends BaseController $sheet->getColumnDimension('D')->setWidth(35); } - - $startColumn = $columnLetter; // Start of the current header range + $startColumn = $columnLetter; // Start of the current header range $subHeaderCount = count($header['subHeaders']); // Number of subheaders for this parent header - // Kint::dump($subHeaderCount); - // Set parent header value + // Kint::dump($subHeaderCount); + // Set parent header value $sheet->setCellValue("{$startColumn}{$rowNumber}", $header['parentHeader']); $sheet->getStyle("{$startColumn}{$rowNumber}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], - 'fill' => [ - 'fillType' => Fill::FILL_SOLID, + 'fill' => [ + 'fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => 'ADD8E6'], ], ]); @@ -4975,10 +5536,10 @@ class LeadsController extends BaseController } $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); $columnLetter++; // Move to the next column for subheaders @@ -4989,10 +5550,10 @@ class LeadsController extends BaseController $sheet->setCellValue("B{$subHeaderRow}", "Sum Insured"); $sheet->mergeCells("B{$subHeaderRow}:C{$subHeaderRow}"); $sheet->getStyle("B{$subHeaderRow}:C{$subHeaderRow}")->applyFromArray([ - 'font' => ['bold' => true], + 'font' => ['bold' => true], 'alignment' => [ 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER, - 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, + 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER, ], ]); @@ -5003,13 +5564,13 @@ class LeadsController extends BaseController 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); - // Increase row height for headers and subheaders - $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height + // Increase row height for headers and subheaders + $sheet->getRowDimension($rowNumber)->setRowHeight(25); // Header row height $sheet->getRowDimension($subHeaderRow)->setRowHeight(20); // Subheader row height // $rowNumber = $subHeaderRow + 2; @@ -5017,15 +5578,15 @@ class LeadsController extends BaseController $column_data = $data['table_data']['data']; // dd($column_data); - $serial_no = 1; + $serial_no = 1; $maxColumnWidths = []; - $RowSpanEnable = false; + $RowSpanEnable = false; // Add table data rows foreach ($column_data as $dataRow) { $columnLetter = 'A'; - $hasPolicy = in_array('Policy', array_column($dataRow['data'], 'parentth')); + $hasPolicy = in_array('Policy', array_column($dataRow['data'], 'parentth')); // Kint::dump($hasPolicy); foreach ($dataRow['data'] as $cellData) { @@ -5037,15 +5598,15 @@ class LeadsController extends BaseController if ($cellData['parentth'] == 'SNO') { $sheet->setCellValue("{$columnLetter}{$rowNumber}", $serial_no); } else if ($cellData['parentth'] == 'Policy') { - $mergeStart = $rowNumber; // Start row for merging - $mergeEnd = $rowNumber + ($cellData['rowspan'] - 1); // End row for merging + $mergeStart = $rowNumber; // Start row for merging + $mergeEnd = $rowNumber + ($cellData['rowspan'] - 1); // End row for merging $sheet->setCellValue("{$columnLetter}{$mergeStart}", $dataRow['SNO']); $sheet->mergeCells("{$columnLetter}{$mergeStart}:{$columnLetter}{$mergeEnd}"); $sheet->getStyle("{$columnLetter}{$mergeStart}:{$columnLetter}{$mergeEnd}") ->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); } else { - if (!$hasPolicy && $key == 0) { + if (! $hasPolicy && $key == 0) { $RowSpanEnable = true; $columnLetter++; $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['display_content']); @@ -5054,7 +5615,7 @@ class LeadsController extends BaseController } } - if (!($key === 0 && !$hasPolicy)) { + if (! ($key === 0 && ! $hasPolicy)) { $columnLetter++; } } @@ -5068,12 +5629,12 @@ class LeadsController extends BaseController // dd($columnLetter); $prevColumn5 = $this->getPreviousColumn($columnLetter); - $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn5}" . ($rowNumber - 1); + $dataRange = "A" . ($subHeaderRow + 1) . ":" . "{$prevColumn5}" . ($rowNumber - 1); $sheet->getStyle($dataRange)->applyFromArray([ 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); @@ -5101,36 +5662,36 @@ class LeadsController extends BaseController if ($matches) { $startColumn = $matches[1]; // A - $startRow = $matches[2]; // 1 - $endColumn = $matches[3]; // G - $endRow = $matches[4]; // 75 + $startRow = $matches[2]; // 1 + $endColumn = $matches[3]; // G + $endRow = $matches[4]; // 75 // Convert column letter to index, reduce by 1, and convert back $endColumnIndex = Coordinate::columnIndexFromString($endColumn) - 1; - $newEndColumn = Coordinate::stringFromColumnIndex($endColumnIndex); + $newEndColumn = Coordinate::stringFromColumnIndex($endColumnIndex); // Generate the new range (e.g., "A1:F75" instead of "A1:G75") $newDataRange = "{$startColumn}{$startRow}:{$newEndColumn}{$endRow}"; // $sheet->getStyle($newDataRange)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN); } - $lastRow = count($lead_data) + 1; + $lastRow = count($lead_data) + 1; $leadRange = "A1:{$columnLetterForImage}{$lastRow}"; $sheet->getStyle($leadRange)->applyFromArray([ 'borders' => [ 'allBorders' => [ 'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN, - 'color' => ['argb' => 'FF000000'], // Black color + 'color' => ['argb' => 'FF000000'], // Black color ], ], ]); } - $columnWidth = $sheet->getColumnDimension("C")->getWidth(); // e.g., 20 - $cellPixelWidth = $columnWidth * 7; // Approximate conversion (1 unit ≈ 7 pixels) - $imagePixelWidth = 250; // Approximate width of your image (in pixels) - + $columnWidth = $sheet->getColumnDimension("C")->getWidth(); // e.g., 20 + $cellPixelWidth = $columnWidth * 7; // Approximate conversion (1 unit ≈ 7 pixels) + $imagePixelWidth = 250; // Approximate width of your image (in pixels) + $offsetX = max(0, ($cellPixelWidth - $imagePixelWidth) / 2); $offsetX = $offsetX + 97; if ($length >= 4) { @@ -5138,22 +5699,22 @@ class LeadsController extends BaseController } else if ($length == 3) { $offsetX = 140; } - - // dd($offsetX, $cellPixelWidth, $imagePixelWidth); + + // dd($offsetX, $cellPixelWidth, $imagePixelWidth); $drawing->setOffsetX($offsetX); // Dynamically center - $drawing->setOffsetY(10); // Dynamically center + $drawing->setOffsetY(10); // Dynamically center $drawing->setWorksheet($sheet); - - $sheet->getStyle('C1')->getAlignment() - ->setHorizontal(Alignment::HORIZONTAL_CENTER) - ->setVertical(Alignment::VERTICAL_CENTER); - if (!empty($rfq_data['fin_years_claims']) && $claim_history == 1) { + $sheet->getStyle('C1')->getAlignment() + ->setHorizontal(Alignment::HORIZONTAL_CENTER) + ->setVertical(Alignment::VERTICAL_CENTER); + + if (! empty($rfq_data['fin_years_claims']) && $claim_history == 1) { $claim_details = json_decode($rfq_data['fin_years_claims'], true) ?? []; - if (!empty($claim_details['finyear'])) { + if (! empty($claim_details['finyear'])) { // Get headers dynamically $headers = array_map(function ($key) { @@ -5166,9 +5727,9 @@ class LeadsController extends BaseController $sheet = $spreadsheet->getActiveSheet(); // Set headers - $sheet->fromArray($headers, NULL, 'A1'); + $sheet->fromArray($headers, null, 'A1'); - // Apply background color and bold style to headers + // Apply background color and bold style to headers $headerCellRange = 'A1:' . chr(64 + count($headers)) . '1'; // e.g., A1:G1 $sheet->getStyle($headerCellRange)->getFont()->setBold(true); @@ -5198,7 +5759,7 @@ class LeadsController extends BaseController $sheet->getColumnDimension($colLetter)->setAutoSize(true); } - // Enable wrap text for all cells + // Enable wrap text for all cells $maxColLetter = chr(64 + count($headers)); // Last column letter $sheet->getStyle("A2:{$maxColLetter}{$row}")->getAlignment()->setWrapText(true); @@ -5215,12 +5776,12 @@ class LeadsController extends BaseController // dd($rowNumber); // Set filename - $string = ($type == 2) ? 'QCR' : 'RFQ'; + $string = ($type == 2) ? 'QCR' : 'RFQ'; $filename = "{$string}_{$rfq_data['client_short_name']}_{$rfq_data['policy_type']}_" . date('YmdHis') . '.xlsx'; // Save to temporary location $uploadFilePath = WRITEPATH . 'tmp/' . $filename; - $writer = new Xlsx($spreadsheet); + $writer = new Xlsx($spreadsheet); $writer->save($uploadFilePath); return [ @@ -5240,7 +5801,7 @@ class LeadsController extends BaseController // Column-wise Check: Remove headers and relevant data if qcr == 0 foreach ($first_json['proposal_data']['over_all_column_data'] as $proposalKey => $proposalData) { - if ((isset($proposalData['qcr']) && isset($proposalData['stc'])) && ($proposalData['qcr'] == 0 || $proposalData['qcr'] === false) || ($proposalData['stc'] == 0 || $proposalData['stc'] === false)) { + if ((isset($proposalData['qcr']) && isset($proposalData['stc'])) && ($proposalData['qcr'] == 0 || $proposalData['qcr'] === false) || ($proposalData['stc'] == 0 || $proposalData['stc'] === false)) { // Remove matching parentHeader in headers foreach ($first_json['table_data']['headers'] as $index => $header) { @@ -5281,7 +5842,6 @@ class LeadsController extends BaseController } } - foreach ($first_json['table_data']['data'] as &$item) { $item['data'] = array_values(array_filter($item['data'], function ($entry) use ($insurer) { return $entry['subth'] !== $insurer['display_name']; @@ -5327,7 +5887,7 @@ class LeadsController extends BaseController $finalRows = []; - if (!empty($groupedRows)) { + if (! empty($groupedRows)) { // Loop through each row_id group and check for Policy status foreach ($groupedRows as $rowId => $rows) { @@ -5347,23 +5907,22 @@ class LeadsController extends BaseController } // Step 3: If parent Policy is "Checked", retain the entire group - if (!$hasPolicy || $isChecked) { + if (! $hasPolicy || $isChecked) { foreach ($rows as $r) { $finalRows[] = $r; } } } - if (!empty($finalRows)) { + if (! empty($finalRows)) { // Update the original data $first_json['table_data']['data'] = array_values($finalRows); } } - // Reindex arrays to maintain proper structure - $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']); - $first_json['table_data']['data'] = array_values($first_json['table_data']['data']); + $first_json['table_data']['headers'] = array_values($first_json['table_data']['headers']); + $first_json['table_data']['data'] = array_values($first_json['table_data']['data']); $first_json['proposal_data']['over_all_column_data'] = array_map(function ($proposal) { $proposal['insurers'] = array_values($proposal['insurers']); return $proposal; @@ -5399,10 +5958,9 @@ class LeadsController extends BaseController // Ensure to unset the reference after the loop unset($row); - $finalRows = []; - if (!empty($groupedRows)) { + if (! empty($groupedRows)) { // Loop through each row_id group and check for Policy status foreach ($groupedRows as $rowId => $rows) { @@ -5422,14 +5980,14 @@ class LeadsController extends BaseController } // Step 3: If parent Policy is "Checked", retain the entire group - if (!$hasPolicy || $isChecked) { + if (! $hasPolicy || $isChecked) { foreach ($rows as $r) { $finalRows[] = $r; } } } - if (!empty($finalRows)) { + if (! empty($finalRows)) { // Update the original data $first_json['table_data']['data'] = array_values($finalRows); } @@ -5461,11 +6019,11 @@ class LeadsController extends BaseController // Add the first two default headers only once $headerData[] = [ 'parentHeader' => $data['table_data']['headers'][0]['parentHeader'], - 'subHeaders' => ['-'] + 'subHeaders' => ['-'], ]; $headerData[] = [ 'parentHeader' => $data['table_data']['headers'][1]['parentHeader'], - 'subHeaders' => ['-'] + 'subHeaders' => ['-'], ]; $second_table_name = $data['table_data']['headers'][1]['parentHeader'] ?? ""; @@ -5477,7 +6035,7 @@ class LeadsController extends BaseController if ($subHeader === $insurer) { $headerData[] = [ 'parentHeader' => $header['parentHeader'], - 'subHeaders' => ['Sum Insured', $subHeader] + 'subHeaders' => ['Sum Insured', $subHeader], ]; break 2; // Exit both loops after match is found } @@ -5488,17 +6046,17 @@ class LeadsController extends BaseController // Update the original data's headers $data['table_data']['headers'] = $headerData; - if (!empty($actionColumn)) { + if (! empty($actionColumn)) { $data['table_data']['headers'][] = [ 'parentHeader' => "Action", - 'subHeaders' => ['-'] + 'subHeaders' => ['-'], ]; } foreach ($data['table_data']['data'] as &$entry) { - $sno = $entry['SNO']; - $items = $entry['items']; + $sno = $entry['SNO']; + $items = $entry['items']; $row_id = $entry['row_id']; $filteredData = []; @@ -5520,7 +6078,7 @@ class LeadsController extends BaseController $filteredData[] = $item; } - if (!empty($actionColumn)) { + if (! empty($actionColumn)) { if ($item['parentth'] === "Action") { $filteredData[] = $item; } @@ -5528,10 +6086,10 @@ class LeadsController extends BaseController } // Update the entry with filtered data - $entry['SNO'] = $sno; - $entry['items'] = $items; + $entry['SNO'] = $sno; + $entry['items'] = $items; $entry['row_id'] = $row_id; - $entry['data'] = $filteredData; + $entry['data'] = $filteredData; } unset($entry); @@ -5552,7 +6110,7 @@ class LeadsController extends BaseController $attachments = []; - if (!empty($json_string)) { + if (! empty($json_string)) { log_message('error', 'json_string is not empty'); $fileIds = json_decode($json_string, true); @@ -5580,12 +6138,12 @@ class LeadsController extends BaseController if (file_exists($fullPath)) { log_message('error', 'File exists at path: ' . $fullPath); - if (!empty($lead_file['file_name'])) { + if (! empty($lead_file['file_name'])) { log_message('error', 'File name is not empty: ' . $lead_file['file_name']); $attachments[] = [ 'fileName' => $lead_file['file_name'], - 'filePath' => $fullPath + 'filePath' => $fullPath, ]; } else { log_message('error', 'File name is empty for ID: ' . $id); @@ -5607,20 +6165,20 @@ class LeadsController extends BaseController public function handleMemberDataGPATotalSumInsurerFromExcel($params) { - $lead_id = $params['lead_id']; - $lead_data = $this->leadsModel->find((int)$lead_id); + $lead_id = $params['lead_id']; + $lead_data = $this->leadsModel->find((int) $lead_id); // dd($lead_data); $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name']; // dd($file_name_with_path); - if (!$lead_data) { + if (! $lead_data) { return ['status' => 'failed', 'message' => 'Opportunity data not found']; } if ($lead_data['file_name']) { //check physical file - if (!file_exists($file_name_with_path)) { + if (! file_exists($file_name_with_path)) { $message = "Lead Physcial file not found"; $this->myLogger->logme('error', ($message . ' for file ' . $file_name_with_path)); @@ -5630,7 +6188,7 @@ class LeadsController extends BaseController $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); //get members data - $members_sheet = $spreadsheet->getSheet(0); + $members_sheet = $spreadsheet->getSheet(0); $highestRowAndColumn = $members_sheet->getHighestRowAndColumn(); // dd($highestRowAndColumn); @@ -5640,19 +6198,18 @@ class LeadsController extends BaseController $members = ExcelSanitizeHelper::sanitizeArrayData($uncleaned_members); // dd($members); - // Check column headings $members_heading = $members[0]; - $available_col = []; + $available_col = []; $lower_headers = array_map('strtolower', $members_heading); foreach ($lower_headers as $index => $header) { if (preg_match('/^(sa\s*-\s*option|proposed\s+sum\s+insured)\s+\d+$/i', $header)) { $column_name = $members_heading[$index]; - $sum = 0; + $sum = 0; for ($i = 1; $i < count($members); $i++) { - $cell_raw = $members[$i][$index] ?? ''; + $cell_raw = $members[$i][$index] ?? ''; $cell_clean = preg_replace('/[^0-9.\-]/', '', $cell_raw); // remove non-numeric chars if ($cell_clean !== '' && is_numeric($cell_clean)) { @@ -5664,7 +6221,6 @@ class LeadsController extends BaseController } } - // dd($available_col); return $available_col; } @@ -5673,7 +6229,7 @@ class LeadsController extends BaseController } public function generateDemographyDataTable($param = []) - { + { if ($this->request !== null) { $param['lead_id'] = $this->request->getGet('lead_id'); @@ -5714,8 +6270,8 @@ class LeadsController extends BaseController $html .= ""; $html .= "{$relation}"; foreach ($allColumns as $col) { - $value = isset($ages[$col]) ? $ages[$col] : "-"; - $html .= "{$value}"; + $value = isset($ages[$col]) ? $ages[$col] : "-"; + $html .= "{$value}"; } $html .= ""; } @@ -5725,9 +6281,9 @@ class LeadsController extends BaseController } if ($this->request !== null) { - if(!empty($html)){ + if (! empty($html)) { return $this->respond(['status' => true, 'data' => $html], 200); - }else{ + } else { return $this->respond(['status' => false, 'data' => $html], 200); } } @@ -5740,7 +6296,7 @@ class LeadsController extends BaseController { $lead_data = $this->leadsModel ->select( - 'leads.*, + 'leads.*, user_profiles.email as created_person_email, policy_type.policy_type, policy_type.long_name @@ -5762,8 +6318,8 @@ class LeadsController extends BaseController } - $from_mail = "im@nhanceindia.in"; - $subject = "Reminder for RFQ"; + $from_mail = getenv(LEAD_INSURER_FROM_MAIL_ID); + $subject = "Reminder for RFQ"; $content_string = '

Dear Sir,

Greetings from Nhance India!

@@ -5791,7 +6347,6 @@ class LeadsController extends BaseController $mail_content = $this->transformMailContent($lead, $content_string, "RFQ"); $mail_subject = $this->transformMailContent($lead, $subject, "RFQ"); - $this->myLogger->logme("info", "Processing lead_id={$leadId} for reminder mails"); // get sales person + created_by emails @@ -5802,7 +6357,7 @@ class LeadsController extends BaseController ->findAll(); $email_list = array_column($sales_person_emails, 'email'); - if (!empty($reply_to)) { + if (! empty($reply_to)) { $email_list[] = $reply_to; } $email_list = array_filter(array_unique($email_list)); @@ -5818,7 +6373,7 @@ class LeadsController extends BaseController ->first(); // dd(db_connect()->getLastQuery(), $createdAtRow); - if (!$createdAtRow) { + if (! $createdAtRow) { $this->myLogger->logme("warning", "No sent history found for lead_id={$leadId}, skipping..."); continue; } @@ -5840,14 +6395,14 @@ class LeadsController extends BaseController // Filter only pending insurers $quote_received_insurer = json_decode($lead['quote_received_insurer'] ?? "[]", true); - $reminder_mail_data = []; + $reminder_mail_data = []; if (empty($quote_received_insurer)) { $reminder_mail_data = $mail_datas; } else { foreach ($mail_datas as $mail_value) { $insurer_id = $mail_value['common'] ?? ""; - if (!in_array($insurer_id, $quote_received_insurer)) { + if (! in_array($insurer_id, $quote_received_insurer)) { $reminder_mail_data[] = $mail_value; } } @@ -5864,7 +6419,7 @@ class LeadsController extends BaseController $common = ['module' => "leads", 'pk' => $leadId, 'mail_type' => "remainder", 'common' => null]; foreach ($reminder_mail_data as $content) { - $insurerId = $content['common'] ?? null; + $insurerId = $content['common'] ?? null; $common['common'] = $insurerId; try { @@ -5879,20 +6434,19 @@ class LeadsController extends BaseController 'message' => $mail_content ?? "", 'reply_to' => $reply_to, 'bcc' => json_decode($content["bcc"] ?? "", true) ?? "", - 'common' => $common + 'common' => $common, ]); $this->myLogger->logme("info", "Reminder mail sent to the insurer | lead_id={$leadId}, insurer_id={$insurerId}, response=" . json_encode($res)); $reminder_sended_lead[] = [ 'lead_id' => $leadId, 'insurer_id' => $insurerId, - 'response' => $res + 'response' => $res, ]; - } else{ + } else { $this->myLogger->logme("info", "Reminder mail disable for this lead_id={$leadId}"); } - } catch (\Throwable $e) { $errorDetails = [ 'error_message' => $e->getMessage(), @@ -5904,22 +6458,21 @@ class LeadsController extends BaseController $reminder_sended_lead[] = [ 'lead_id' => $leadId, 'insurer_id' => $insurerId, - 'response' => ['status' => false, 'error' => $errorDetails] + 'response' => ['status' => false, 'error' => $errorDetails], ]; } // send reminder to sales person / creator only $internal_mail_response = MailHelper::send_email([ - 'mail' => $from_mail, - 'cc' => $email_string, - 'subject' => $mail_subject ?? "", - 'message' => $mail_content ?? "", - 'common' => $common + 'mail' => $from_mail, + 'cc' => $email_string, + 'subject' => $mail_subject ?? "", + 'message' => $mail_content ?? "", + 'common' => $common, ]); $this->myLogger->logme("info", "Reminder mail sent to sales persons | lead_id={$leadId}, recipients={$email_string}, response=" . json_encode($internal_mail_response)); - } } @@ -5933,18 +6486,18 @@ class LeadsController extends BaseController $this->myLogger->logme('error', "uploadMultiFileFromRfq START"); $this->myLogger->logme('error', "Files received: " . json_encode($this->request->getPost() ?? [])); - $lead_id = $this->request->getPost('lead_id'); - $lead_form_type = $this->request->getPost('lead_form_type'); + $lead_id = $this->request->getPost('lead_id'); + $lead_form_type = $this->request->getPost('lead_form_type'); $leads_file_primary_key = $this->request->getPost('leads_file_id') ?? []; - $docs_name = $this->request->getPost('docs_name') ?? []; - $files = $this->request->getFileMultiple('file_name'); + $docs_name = $this->request->getPost('docs_name') ?? []; + $files = $this->request->getFileMultiple('file_name'); if (empty($files) || empty($docs_name)) { $this->myLogger->logme('error', "No files or document names provided"); return $this->respond([ - 'status' => false, - 'code' => 400, - 'message' => 'No files or document names provided' + 'status' => false, + 'code' => 400, + 'message' => 'No files or document names provided', ], 400); } @@ -5953,12 +6506,12 @@ class LeadsController extends BaseController $this->myLogger->logme('error', "uploadMultiFiles result: " . json_encode($multi_file_data ?? [])); - if (!empty($multi_file_data)) { + if (! empty($multi_file_data)) { $this->insertMultiFilesData($multi_file_data, $lead_id, $lead_form_type); $this->myLogger->logme('error', "Files inserted successfully into DB"); // update lead file name if change - if(isset($multi_file_data[0]['file_name']) && !empty($multi_file_data[0]['file_name'])){ + if (isset($multi_file_data[0]['file_name']) && ! empty($multi_file_data[0]['file_name'])) { $this->leadsModel->where('id', $lead_id)->set('file_name', $multi_file_data[0]['file_name'])->update(); } @@ -5966,7 +6519,6 @@ class LeadsController extends BaseController $this->myLogger->logme('error', "uploadMultiFiles returned empty"); } - // Get the updated lead file data $lead_file_data = $this->leadFilesModel ->where('is_active', 1) @@ -5976,17 +6528,17 @@ class LeadsController extends BaseController $this->myLogger->logme('error', "Fetched " . count($lead_file_data) . " lead file records"); - $document_data = $this->renderFileFields($lead_file_data); - $attch_data['multi_file_data'] = $lead_file_data; - $attachment_html = view('rfq/attachment_files', $attch_data) ?? ""; + $document_data = $this->renderFileFields($lead_file_data); + $attch_data['multi_file_data'] = $lead_file_data; + $attachment_html = view('rfq/attachment_files', $attch_data) ?? ""; $this->myLogger->logme('error', "uploadMultiFileFromRfq END"); return $this->respond([ - 'status' => true, - 'code' => 200, - 'message' => "File uploaded Successfully", - 'document_data' => $document_data, + 'status' => true, + 'code' => 200, + 'message' => "File uploaded Successfully", + 'document_data' => $document_data, 'attachment_html' => $attachment_html, ], 200); @@ -6003,32 +6555,32 @@ class LeadsController extends BaseController $this->myLogger->logme('error', "Exception in uploadMultiFileFromRfq: " . json_encode($errorDetails)); return $this->respond([ - 'status' => false, - 'code' => 500, - 'message' => "File upload failed: " . $e->getMessage(), - 'errorDetails' => $errorDetails, + 'status' => false, + 'code' => 500, + 'message' => "File upload failed: " . $e->getMessage(), + 'errorDetails' => $errorDetails, ], 500); } } public function renderFileFields($multi_file_data = []) - { + { $uploadFilePath = WRITEPATH . 'uploads/lead_files/'; - $html = ''; + $html = ''; // If data exists (edit mode) - if (!empty($multi_file_data)) { + if (! empty($multi_file_data)) { foreach ($multi_file_data as $index => $value) { - $sample_dwn_link = ' [ Download ]'; - $isFirstField = ($index === 0); - $placeholder = $isFirstField ? 'First file must be Demography.' : ''; - $first_file_name = $isFirstField ? 'Member List' : ''; + $sample_dwn_link = ' [ Download ]'; + $isFirstField = ($index === 0); + $placeholder = $isFirstField ? 'First file must be Demography.' : ''; + $first_file_name = $isFirstField ? 'Member List' : ''; $member_data_link = $isFirstField ? $sample_dwn_link : ''; - $read_only = $isFirstField ? 'readonly' : ''; - $accept = $isFirstField ? '.xls,.xlsx' : '.xls,.xlsx,.pdf,.jpg,.jpeg,.png'; - $displayIndex = $index + 1; + $read_only = $isFirstField ? 'readonly' : ''; + $accept = $isFirstField ? '.xls,.xlsx' : '.xls,.xlsx,.pdf,.jpg,.jpeg,.png'; + $displayIndex = $index + 1; $html .= '
@@ -6036,20 +6588,20 @@ class LeadsController extends BaseController
- +
-
@@ -6067,7 +6619,7 @@ class LeadsController extends BaseController
-
@@ -6076,7 +6628,7 @@ class LeadsController extends BaseController File Upload
No file chosen -
@@ -6094,7 +6646,7 @@ class LeadsController extends BaseController { $filePath = WRITEPATH . 'uploads/lead_files/' . $fileName; - if (!file_exists($filePath)) { + if (! file_exists($filePath)) { $data['message'] = 'The Physical File Not Found'; echo view('errors/404', $data); } @@ -6118,35 +6670,35 @@ class LeadsController extends BaseController $this->myLogger->logme('error', 'Start memberDataListExcelFileFormatValidation'); $this->myLogger->logme('error', "Received params: " . json_encode($params)); - $lead_id = $params['lead_id']; + $lead_id = $params['lead_id']; $age_validation_check = $params['age_validation'] ?? null; - $lead_data = $this->leadsModel->where('id', $lead_id)->first(); + $lead_data = $this->leadsModel->where('id', $lead_id)->first(); // dd($lead_data); $return = []; - if (!isset($lead_data)) { + if (! isset($lead_data)) { $this->myLogger->logme('error', "Lead not found for lead_id: {$lead_id}"); - $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'failed', 'error_data' => json_encode(['error_summary' => array_count_values([12]),'error_data' => 'file not found in DB'])])->update(); - return array('status' => false, 'msg' => 'file not found in DB'); + $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'failed', 'error_data' => json_encode(['error_summary' => array_count_values([12]), 'error_data' => 'file not found in DB'])])->update(); + return ['status' => false, 'msg' => 'file not found in DB']; } //get the lead files data $lead_file_data = $this->leadFilesModel->where('is_active', 1)->where('type', 2)->first(); //check the lead file table has the error data entry if not than create new entry - if(empty($lead_file_data)){ - $data['type'] = 2; - $data['file_name'] = $lead_data['file_name']; - $data['docs_name'] = "Member List"; - $data['lead_id'] = $lead_id; + if (empty($lead_file_data)) { + $data['type'] = 2; + $data['file_name'] = $lead_data['file_name']; + $data['docs_name'] = "Member List"; + $data['lead_id'] = $lead_id; $lead_file_last_insert_id = $this->leadFilesModel->insert($data); $this->myLogger->logme('error', "New lead file entry created for store the error data, insert_id : '{$lead_file_last_insert_id}'"); } $family_composition = []; - if($age_validation_check && !empty($lead_data['proposel_data'])){ + if ($age_validation_check && ! empty($lead_data['proposel_data'])) { $family_composition = $this->getAgeRatioFromRfqJson($lead_id, $lead_data['proposel_data']); - $this->myLogger->logme('info', 'Family composition :',json_encode($family_composition)); + $this->myLogger->logme('info', 'Family composition :', json_encode($family_composition)); } // dd($family_composition); @@ -6155,34 +6707,34 @@ class LeadsController extends BaseController $this->myLogger->logme('error', "File path: {$file_name_with_path}"); //check physical file - if (!file_exists($file_name_with_path)) { - //file not found update status and reason + if (! file_exists($file_name_with_path)) { + //file not found update status and reason $message = "Physcial file not found"; $this->myLogger->logme('error', ($message . ' for lead id ' . $lead_id)); $this->leadFilesModel ->where('lead_id', $lead_id) ->where('type', 2) - ->set(['status' => 'failed','error_data' => json_encode(['error_summary' => array_count_values([5]),'error_data' => $message])]) + ->set(['status' => 'failed', 'error_data' => json_encode(['error_summary' => array_count_values([5]), 'error_data' => $message])]) ->update(); - return array('error_summary' => [5], 'error_data' => $message); + return ['error_summary' => [5], 'error_data' => $message]; } $this->myLogger->logme('info', 'File exists, starting validation process'); //start validation process $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); - $sheet = $spreadsheet->getActiveSheet(); + $sheet = $spreadsheet->getActiveSheet(); $highestRowAndColumn = $sheet->getHighestRowAndColumn(); // dd($highestRowAndColumn); $columns_to_check = $this->member_data_excel_columns; - $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []]; - $keys = array_keys($columns_to_check); + $result = ['error_type' => 1, 'error_summary' => [], 'error_data' => []]; + $keys = array_keys($columns_to_check); $allowedHighestColumn = end($columns_to_check); - $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']); - $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data); + $excel_data = $sheet->rangeToArray('A1:' . $allowedHighestColumn['col_cell_name'] . $highestRowAndColumn['row']); + $excel_data = ExcelSanitizeHelper::sanitizeArrayData($excel_data); $this->myLogger->logme('error', 'Excel data sanitized count : {row_count}', ['row_count' => count($excel_data)]); // dd($excel_data); @@ -6201,9 +6753,9 @@ class LeadsController extends BaseController $this->leadFilesModel ->where('lead_id', $lead_id) ->where('type', 2) - ->set(['status' => 'failed','error_data' => json_encode(['error_summary' => array_count_values([6]),'error_data' => $message])]) + ->set(['status' => 'failed', 'error_data' => json_encode(['error_summary' => array_count_values([6]), 'error_data' => $message])]) ->update(); - return array('error_summary' => [6], 'error_data' => $message); + return ['error_summary' => [6], 'error_data' => $message]; } $relationship = $this->general_relationships; @@ -6225,63 +6777,62 @@ class LeadsController extends BaseController //iterate each row for columns validations foreach ($row as $col_key => $col) { - $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory']; - $format = $columns_to_check[$keys[$col_key]]['format']; - $allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values']; + $is_mandatory = $columns_to_check[$keys[$col_key]]['is_mandatory']; + $format = $columns_to_check[$keys[$col_key]]['format']; + $allowed_values = $columns_to_check[$keys[$col_key]]['allowed_values']; $custom_function = isset($columns_to_check[$keys[$col_key]]['custom']) ? $columns_to_check[$keys[$col_key]]['custom'] : null; - $binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null; + $binding_params = isset($columns_to_check[$keys[$col_key]]['params']) ? $columns_to_check[$keys[$col_key]]['params'] : null; $column_dispaly_name = $columns_to_check[$keys[$col_key]]['col_name']; - $column_index = $columns_to_check[$keys[$col_key]]['col_idx']; - $column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name']; - + $column_index = $columns_to_check[$keys[$col_key]]['col_idx']; + $column_cell = $columns_to_check[$keys[$col_key]]['col_cell_name']; //mandatory check if (is_bool($is_mandatory) && $is_mandatory === true) { - if ($col == "" || $col == NULL) { - array_push($result['error_summary'], 1); //push error code for summary + if ($col == "" || $col == null) { + array_push($result['error_summary'], 1); //push error code for summary $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name - $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index - $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory'; //push exact error desc + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory'; //push exact error desc } } //if is_mandatory is array (action based mandatory check) if (is_array($is_mandatory)) { $allowed_actions = $columns_to_check[$keys[$col_key]]['is_mandatory']; - if ($col == "" || $col == NULL) { + if ($col == "" || $col == null) { array_push($result['error_summary'], 1); $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name - $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index - $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory for this action/event'; + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = 'Value is mandatory for this action/event'; } } //format check if (isset($format)) { $format_error = check_excel_date_format($col, $format); - if (!$format_error['status']) { + if (! $format_error['status']) { array_push($result['error_summary'], 2); $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name - $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index - $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $format_error['error']; + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $format_error['error']; } } //allowed values check if (($is_mandatory === true && isset($allowed_values) && is_array($allowed_values)) || (is_array($is_mandatory) && (isset($allowed_values) && is_array($allowed_values)))) { - if (!in_array((trim($col)), $allowed_values)) { + if (! in_array((trim($col)), $allowed_values)) { array_push($result['error_summary'], 3); $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name - $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index - $result['error_data'][$row_key][$keys[$col_key]]['error'][] = "Value not allowed: Expected " . implode(",", $allowed_values) . " and received $col"; + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = "Value not allowed: Expected " . implode(",", $allowed_values) . " and received $col"; } } //custom function check if (isset($custom_function)) { //convert string params into PHP variables - // Create an array of variables to pass custom helper funcitons + // Create an array of variables to pass custom helper funcitons $param_values = []; foreach ($binding_params as $bkey => $bparam) { $param_values[] = ($$bparam); @@ -6291,27 +6842,27 @@ class LeadsController extends BaseController if ($res['status'] === false) { array_push($result['error_summary'], 4); $result['error_data'][$row_key][$keys[$col_key]]['col_name'] = $column_dispaly_name; //push column name - $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index - $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $res['error']; + $result['error_data'][$row_key][$keys[$col_key]]['col_idx'] = $column_index; //push column index + $result['error_data'][$row_key][$keys[$col_key]]['error'][] = $res['error']; } } - } + } //age validation $age_validation = isset($columns_to_check['dob']['age_validation']) ?? null; - if (isset($age_validation) && $age_validation && $age_validation_check && !empty($family_composition)) { + if (isset($age_validation) && $age_validation && $age_validation_check && ! empty($family_composition)) { $format_error = check_age_validation($row, $family_composition); - if (!$format_error['status']) { + if (! $format_error['status']) { array_push($result['error_summary'], 2); $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['col_name'] = $columns_to_check['dob']['col_name']; //push column name - $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['col_idx'] = $columns_to_check['dob']['col_idx']; //push column index - $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['error'][] = $format_error['error']; + $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['col_idx'] = $columns_to_check['dob']['col_idx']; //push column index + $result['error_data'][$row_key][$keys[$columns_to_check['dob']['col_idx']]]['error'][] = $format_error['error']; } } $row['row_index'] = $row_key; - $relation_idx = $columns_to_check['relationship']['col_idx']; - $emp_code_idx = $columns_to_check['emp_code']['col_idx']; + $relation_idx = $columns_to_check['relationship']['col_idx']; + $emp_code_idx = $columns_to_check['emp_code']['col_idx']; if (isset($row[$relation_idx]) && strtolower($row[$relation_idx]) == 'self' && isset($member_family_data[$row[$emp_code_idx]])) { array_unshift($member_family_data[$row[$emp_code_idx]], $row); @@ -6325,7 +6876,7 @@ class LeadsController extends BaseController $check_row_dublicate = check_duplicate_rows_and_contacts($excel_data, $columns_to_check, $result); // dd($check_row_dublicate); - if(count($check_row_dublicate)){ + if (count($check_row_dublicate)) { $result = $check_row_dublicate; } @@ -6335,12 +6886,12 @@ class LeadsController extends BaseController if (isset($result['error_summary']) && count($result['error_summary'])) { $result['error_summary'] = array_count_values($result['error_summary']); - $status = 'failed'; - $failure_reason = ((json_encode($result))); - $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => $status,'error_data' => $failure_reason])->update(); + $status = 'failed'; + $failure_reason = ((json_encode($result))); + $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => $status, 'error_data' => $failure_reason])->update(); $this->myLogger->logme("error", '{lead_id} uploaded failed for this lead id', ['lead_id' => $lead_id]); } else { - $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'success','error_data' => ''])->update(); + $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->set(['status' => 'success', 'error_data' => ''])->update(); $r = Jobs::addJob(['job_name' => 'calculateMembersDemography', 'payload' => ['lead_id' => $lead_id]]); } @@ -6348,22 +6899,22 @@ class LeadsController extends BaseController } public function getAgeRatioFromRfqJson($lead_id, $porposel_data) - { + { $age_ratio = []; - $rfq_data = $this->RFQModel->where('is_active', 1)->where('lead_id', $lead_id)->orderBy('id', 'desc')->first(); - if(empty($rfq_data) || empty($rfq_data['json'])){ + $rfq_data = $this->RFQModel->where('is_active', 1)->where('lead_id', $lead_id)->orderBy('id', 'desc')->first(); + if (empty($rfq_data) || empty($rfq_data['json'])) { return $age_ratio; } - $data = json_decode($rfq_data['json'], true); + $data = json_decode($rfq_data['json'], true); $proposal_and_insurer = json_decode($porposel_data, true); - $insurer_key = $proposal_and_insurer['insurer_name'] ?? null; + $insurer_key = $proposal_and_insurer['insurer_name'] ?? null; - if(isset($data['table_data']['data'])){ + if (isset($data['table_data']['data'])) { foreach ($data['table_data']['data'] as $key => $value) { - if($value['items'] == 'family_composition'){ + if ($value['items'] == 'family_composition') { foreach ($value['data'] as $family_composition) { - if($family_composition['subth'] == $insurer_key){ + if ($family_composition['subth'] == $insurer_key) { $age_ratio = json_decode($family_composition['input_value'] ?? "", true) ?? []; } } @@ -6399,7 +6950,7 @@ class LeadsController extends BaseController public function getMemberDataListExcelErrorData($lead_id) { try { - $file = $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->where('is_active', 1)->first(); + $file = $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->where('is_active', 1)->first(); $error_data = json_decode($file['error_data']); // dd($error_data); // return $error_data; @@ -6407,17 +6958,17 @@ class LeadsController extends BaseController $file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $file['file_name']; //check the file exist or not - if (!file_exists($file_name_with_path)) { + if (! file_exists($file_name_with_path)) { $error_message = "File not found"; $this->myLogger->logme('error', ($error_message . ' for file id ' . $lead_id)); return 0; } $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_name_with_path); - $sheet = $spreadsheet->getActiveSheet(); + $sheet = $spreadsheet->getActiveSheet(); - $highestRowAndColumn = $sheet->getHighestRowAndColumn(); - $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); + $highestRowAndColumn = $sheet->getHighestRowAndColumn(); + $excel_data = $sheet->rangeToArray('A1:' . $highestRowAndColumn['column'] . $highestRowAndColumn['row']); $excelErrorData['excel_header'] = $excel_data[0]; unset($excel_data[0]); // Kint::dump($excel_data); @@ -6428,8 +6979,8 @@ class LeadsController extends BaseController foreach ($error_data->error_data as $key => $value) { foreach ($value as $key2 => $value2) { - $error_data = $value2->error; - $data = ['value' => $excel_data[$key][$value2->col_idx], 'error' => $error_data,]; + $error_data = $value2->error; + $data = ['value' => $excel_data[$key][$value2->col_idx], 'error' => $error_data]; $excel_data[$key][$value2->col_idx] = $data; } array_push($finalArray, $excel_data[$key]); @@ -6437,9 +6988,9 @@ class LeadsController extends BaseController foreach ($finalArray as $fkey => $value) { foreach ($value as $vkey => $arrayData) { - if (!is_array($arrayData)) { - $data = ['value' => $arrayData]; - $finalArray[$fkey][$vkey] = $data; + if (! is_array($arrayData)) { + $data = ['value' => $arrayData]; + $finalArray[$fkey][$vkey] = $data; } } } @@ -6448,14 +6999,13 @@ class LeadsController extends BaseController return $excelErrorData; } else if ($error_data->error_type == 2) { - - $allErrors = []; + $allErrors = []; $typeTowArray = []; foreach ($error_data->error_data as $index => $item) { foreach ($item as $field) { - if (!isset($allErrors[$index])) { + if (! isset($allErrors[$index])) { $allErrors[$index] = []; } $allErrors[$index] = array_merge($allErrors[$index], $field->error); @@ -6468,7 +7018,7 @@ class LeadsController extends BaseController // print_r($value); foreach ($excel_data as $excel_data_index => $excel_data_value) { if ($excel_data_value[0] == $key) { - $data = ['value' => $excel_data[$excel_data_index][1], 'error' => $value,]; + $data = ['value' => $excel_data[$excel_data_index][1], 'error' => $value]; $excel_data[$excel_data_index][1] = $data; array_push($typeTowArray, $excel_data[$excel_data_index]); break; @@ -6478,9 +7028,9 @@ class LeadsController extends BaseController // dd($data); foreach ($typeTowArray as $fkey => $value) { foreach ($value as $vkey => $arrayData) { - if (!is_array($arrayData)) { - $data = ['value' => $arrayData]; - $typeTowArray[$fkey][$vkey] = $data; + if (! is_array($arrayData)) { + $data = ['value' => $arrayData]; + $typeTowArray[$fkey][$vkey] = $data; } } } @@ -6489,7 +7039,7 @@ class LeadsController extends BaseController return $excelErrorData; } } catch (\Exception $e) { - // Handle any exceptions + // Handle any exceptions $errorMessage = $e->getMessage(); //die(); $this->myLogger->logme('error', $errorMessage); return false; // You can return an error response here @@ -6501,10 +7051,10 @@ class LeadsController extends BaseController // Get file data from the database $file_data = $this->leadFilesModel->where('lead_id', $lead_id)->where('type', 2)->where('is_active', 1)->first(); - $error = json_decode($file_data['error_data']); + $error = json_decode($file_data['error_data']); // Check if the file exists - if (!$file_data) { + if (! $file_data) { $error_message = "File not found"; $this->myLogger->logme('error', $error_message . ' for file id ' . $lead_id); return $error_message; @@ -6514,7 +7064,7 @@ class LeadsController extends BaseController $filePath = WRITEPATH . '/uploads/lead_files/' . $fileName; // Check if the file exists - if (!file_exists($filePath)) { + if (! file_exists($filePath)) { $error_message = "File not found"; $this->myLogger->logme('error', $error_message . ' for file id ' . $lead_id); $data['message'] = 'Physical File Not Found'; @@ -6523,7 +7073,7 @@ class LeadsController extends BaseController // Load the Excel file $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath); - $sheet = $spreadsheet->getActiveSheet(); + $sheet = $spreadsheet->getActiveSheet(); foreach ($error->error_data as $index => $error_data) { @@ -6537,36 +7087,34 @@ class LeadsController extends BaseController $originalValue = $sheet->getCell([$colIndex, $rowIndex])->getValue(); - $newValue = implode(', ', $value->error); - $val = $originalValue . ' ( ' . $newValue . ' )'; - $sheet->setCellValue([$colIndex, $rowIndex], $val); + $newValue = implode(', ', $value->error); + $val = $originalValue . ' ( ' . $newValue . ' )'; + $sheet->setCellValue([$colIndex, $rowIndex], $val); $style = [ 'fill' => [ - 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, - 'startColor' => ['rgb' => 'ffad99'] // Red color - ] + 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'ffad99'], // Red color + ], ]; $sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style); } } else if ($error->error_type == 2) { - foreach ($error_data as $key => $value) { - $originalValue = $sheet->getCell([1, $rowIndex])->getValue(); - $newValue = implode(', ', $value->error); - $val = $originalValue . ' ( ' . $newValue . ' )'; - $sheet->setCellValue([$colIndex, $rowIndex], $val); + $newValue = implode(', ', $value->error); + $val = $originalValue . ' ( ' . $newValue . ' )'; + $sheet->setCellValue([$colIndex, $rowIndex], $val); $style = [ 'fill' => [ - 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, - 'startColor' => ['rgb' => 'ffad99'] // Red color - ] + 'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, + 'startColor' => ['rgb' => 'ffad99'], // Red color + ], ]; $sheet->getStyle([$colIndex, $rowIndex])->applyFromArray($style); } @@ -6578,7 +7126,7 @@ class LeadsController extends BaseController // Save the modified Excel file to a new location $newFilePath = WRITEPATH . '/uploads/lead_files/' . $newFileName; - $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); + $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet); $writer->save($newFilePath); // Set headers to force download @@ -6610,17 +7158,17 @@ class LeadsController extends BaseController return $this->respond([ 'status' => false, 'code' => 400, - 'message' => 'Opportunity ID is required' + 'message' => 'Opportunity ID is required', ], 400); } - $lead_id = $params['lead_id']; + $lead_id = $params['lead_id']; $proposal_insurer = $params['proposal_insurer'] ?? ''; // Handle proposal and insurer details - if (!empty($proposal_insurer) && strpos($proposal_insurer, '-') !== false) { + if (! empty($proposal_insurer) && strpos($proposal_insurer, '-') !== false) { list($proposal_key, $insurer_key) = explode('-', $proposal_insurer, 2); - $lead_update_data = json_encode([ + $lead_update_data = json_encode([ 'proposel_name' => $proposal_key, 'insurer_name' => $insurer_key, 'insurer' => $params['insurer_and_branch'] ?? null, @@ -6633,8 +7181,8 @@ class LeadsController extends BaseController $data = [ 'proposel_data' => $lead_update_data, - 'placement_date' => !empty($params['placement_date']) ? change_date_format($params['placement_date']) : null, - 'payment_date' => !empty($params['payment_date']) ? change_date_format($params['payment_date']) : null, + 'placement_date' => ! empty($params['placement_date']) ? change_date_format($params['placement_date']) : null, + 'payment_date' => ! empty($params['payment_date']) ? change_date_format($params['payment_date']) : null, 'utr_no' => $params['utr_no'] ?? null, 'is_cd' => $params['is_cd'] ?? null, 'premium_amount' => $params['premium_amount'] ?? null, @@ -6649,7 +7197,7 @@ class LeadsController extends BaseController $lead_data = $this->leadsModel->where('id', $lead_id)->first(); // Compare and update only if changed the start and end date - if (!empty($params['policy_start_date'])) { + if (! empty($params['policy_start_date'])) { $converted_start = change_date_format($params['policy_start_date']); if ($converted_start !== $lead_data['policy_start_date']) { $data['policy_start_date'] = $converted_start; @@ -6657,7 +7205,7 @@ class LeadsController extends BaseController } } - if (!empty($params['policy_end_date'])) { + if (! empty($params['policy_end_date'])) { $converted_end = change_date_format($params['policy_end_date']); if ($converted_end !== $lead_data['policy_end_date']) { $data['policy_end_date'] = $converted_end; @@ -6666,10 +7214,10 @@ class LeadsController extends BaseController } // Handle TPA details - if (!empty($params['tpa_id']) && strpos($params['tpa_id'], '-') !== false) { + if (! empty($params['tpa_id']) && strpos($params['tpa_id'], '-') !== false) { list($tpaBranchId, $tpaId) = explode('-', $params['tpa_id']); - $data['tpa_branch_id'] = $tpaBranchId; - $data['tpa_id'] = $tpaId; + $data['tpa_branch_id'] = $tpaBranchId; + $data['tpa_id'] = $tpaId; $this->myLogger->logme('error', "TPA details added: branch=$tpaBranchId, id=$tpaId"); } @@ -6680,19 +7228,19 @@ class LeadsController extends BaseController $this->myLogger->logme('error', "Lead updated successfully for ID: $lead_id"); // Save installment details - if (!empty($params['installments'])) { + if (! empty($params['installments'])) { $installments = json_decode($params['installments'], true); $this->myLogger->logme('error', "Installments data received: " . json_encode($installments)); - if (is_array($installments) && !empty($installments)) { + if (is_array($installments) && ! empty($installments)) { foreach ($installments as $installment) { - $installment['payment_date'] = !empty($installment['payment_date']) && strtotime($installment['payment_date']) + $installment['payment_date'] = ! empty($installment['payment_date']) && strtotime($installment['payment_date']) ? date('Y-m-d', strtotime($installment['payment_date'])) : null; $installment['lead_id'] = $lead_id; - if (!empty($installment['id'])) { + if (! empty($installment['id'])) { $this->leadInstallmentPaymentDetails->update($installment['id'], $installment); $this->myLogger->logme('error', "Installment updated: " . json_encode($installment)); } else { @@ -6720,7 +7268,7 @@ class LeadsController extends BaseController 'message' => 'Placement data saved successfully. File being validated', 'lead_id' => $lead_id, 'data' => $data, - 'params' => $params + 'params' => $params, ], 200); } catch (\Exception $e) { @@ -6735,7 +7283,7 @@ class LeadsController extends BaseController 'status' => false, 'code' => 500, 'message' => 'Error while validating the member data', - 'error' => $errorDetails + 'error' => $errorDetails, ], 500); } } @@ -6747,7 +7295,7 @@ class LeadsController extends BaseController return $this->respond([ 'status' => false, 'code' => 400, - 'message' => 'lead_id is required' + 'message' => 'lead_id is required', ], 400); } @@ -6758,11 +7306,11 @@ class LeadsController extends BaseController ->where('type', 2) ->first(); - if (!$lead_file) { + if (! $lead_file) { return $this->respond([ 'status' => false, 'code' => 404, - 'message' => 'No file found for this lead_id' + 'message' => 'No file found for this lead_id', ], 404); } @@ -6772,7 +7320,7 @@ class LeadsController extends BaseController 'status' => true, 'code' => 202, // Accepted - still processing 'message' => 'Validation in progress', - 'data' => ['status' => $lead_file['status']] + 'data' => ['status' => $lead_file['status']], ], 200); } @@ -6781,12 +7329,10 @@ class LeadsController extends BaseController 'status' => true, 'code' => 200, 'message' => 'Validation completed', - 'data' => $lead_file + 'data' => $lead_file, ], 200); } - // ----------- END OF MEMBER DATA VALIDAATION ------------------------------------------------------------------------------------------------------ - } diff --git a/app/Controllers/TicketController.php b/app/Controllers/TicketController.php index c3d5e86e..3833e4e0 100644 --- a/app/Controllers/TicketController.php +++ b/app/Controllers/TicketController.php @@ -1027,7 +1027,8 @@ class TicketController extends BaseController $data['claim_status'] = $this->transFormClaimStatus($claim_status_id, $ticket_type); $data['client_for_motor'] = $this->clientModel->select('id,client_name,phone')->where('client_type', 2)->where('is_active', 1)->findAll(); } - + $data['tab_name'] = "Claims"; + $data['page_name'] = "Claims"; return $this->loadLayout('ticket_edit_onbording', $data); } diff --git a/app/Libraries/GoogleSheetLib.php b/app/Libraries/GoogleSheetLib.php index a04ab1e9..e5eb8caf 100644 --- a/app/Libraries/GoogleSheetLib.php +++ b/app/Libraries/GoogleSheetLib.php @@ -1,10 +1,11 @@ -client = new Google_Client(); @@ -28,7 +28,7 @@ class GoogleSheetLib // Required scopes $this->client->addScope([ Google_Service_Drive::DRIVE, - Google_Service_Sheets::SPREADSHEETS + Google_Service_Sheets::SPREADSHEETS, ]); // Init services @@ -53,7 +53,7 @@ class GoogleSheetLib public function write(string $spreadsheetId, array $values, string $range = 'Sheet1') { $body = new Google_Service_Sheets_ValueRange([ - 'values' => $values + 'values' => $values, ]); $this->sheets @@ -81,7 +81,6 @@ class GoogleSheetLib return $response->getBody()->getContents(); } - /* ================= COPY TEMPLATE ================= */ public function copyTemplate(string $templateId, string $name, string $folderId): string @@ -92,10 +91,10 @@ class GoogleSheetLib 'name' => $name, 'parents' => [$folderId], - ]),[ - 'supportsAllDrives' => true, - 'fields' => 'id, name, parents' - ] + ]), [ + 'supportsAllDrives' => true, + 'fields' => 'id, name, parents', + ] ); return $file->id; @@ -116,7 +115,7 @@ class GoogleSheetLib private function createPermission(string $fileId, string $email, string $role) { - $type = str_starts_with($email, 'group:') ? 'group' : 'user'; + $type = str_starts_with($email, 'group:') ? 'group' : 'user'; $email = str_replace('group:', '', $email); $this->drive->permissions->create( @@ -124,9 +123,9 @@ class GoogleSheetLib new \Google_Service_Drive_Permission([ 'type' => $type, 'role' => $role, - 'emailAddress' => $email + 'emailAddress' => $email, ]), - ['sendNotificationEmail' => false,'supportsAllDrives' => true] + ['sendNotificationEmail' => false, 'supportsAllDrives' => true] ); } @@ -135,7 +134,7 @@ class GoogleSheetLib public function applyProtectionsold(string $spreadsheetId, array $ranges) { $spreadsheet = $this->sheets->spreadsheets->get($spreadsheetId); - $sheetId = $spreadsheet->getSheets()[0]->getProperties()->getSheetId(); + $sheetId = $spreadsheet->getSheets()[0]->getProperties()->getSheetId(); $requests = []; @@ -145,96 +144,95 @@ class GoogleSheetLib $requests[] = [ 'addProtectedRange' => [ 'protectedRange' => [ - 'range' => [ - 'sheetId' => $sheetId + 'range' => [ + 'sheetId' => $sheetId, ], - 'warningOnly' => false - ] - ] + 'warningOnly' => false, + ], + ], ]; } $this->sheets->spreadsheets->batchUpdate( $spreadsheetId, new Google_Service_Sheets_BatchUpdateSpreadsheetRequest([ - 'requests' => $requests + 'requests' => $requests, ]) ); } - public function applyProtections(string $spreadsheetId, array $protections) -{ - // Fetch spreadsheet metadata - $spreadsheet = $this->sheets->spreadsheets->get( - $spreadsheetId, - ['fields' => 'sheets(properties(sheetId,title,gridProperties))'] - ); - - // Map sheet names - $sheetMap = []; - foreach ($spreadsheet->getSheets() as $sheet) { - $props = $sheet->getProperties(); - $sheetMap[$props->getTitle()] = [ - 'sheetId' => $props->getSheetId(), - 'rowCount' => $props->getGridProperties()->getRowCount(), - 'colCount' => $props->getGridProperties()->getColumnCount(), - ]; - } - - $requests = []; - - foreach ($protections as $protection) { - - $rangeStr = $protection['range']; - - if (!str_contains($rangeStr, '!')) { - throw new \Exception("Invalid range format: {$rangeStr}"); - } - - [$sheetName, $a1] = explode('!', $rangeStr, 2); - - if (!isset($sheetMap[$sheetName])) { - throw new \Exception("Sheet not found: {$sheetName}"); - } - - $sheetMeta = $sheetMap[$sheetName]; - - $gridRange = $this->convertA1ToGridRange( - $a1, - $sheetMeta['sheetId'], - $sheetMeta['rowCount'], - $sheetMeta['colCount'] + { + // Fetch spreadsheet metadata + $spreadsheet = $this->sheets->spreadsheets->get( + $spreadsheetId, + ['fields' => 'sheets(properties(sheetId,title,gridProperties))'] ); - $protectedRange = [ - 'range' => $gridRange, - 'description' => 'RFQ Protected Area', - 'warningOnly' => false, - 'editors' => [ - 'users' => $protection['users'] ?? [], - 'groups' => $protection['groups'] ?? [] - ] - ]; + // Map sheet names + $sheetMap = []; + foreach ($spreadsheet->getSheets() as $sheet) { + $props = $sheet->getProperties(); + $sheetMap[$props->getTitle()] = [ + 'sheetId' => $props->getSheetId(), + 'rowCount' => $props->getGridProperties()->getRowCount(), + 'colCount' => $props->getGridProperties()->getColumnCount(), + ]; + } - $requests[] = [ - 'addProtectedRange' => [ - 'protectedRange' => $protectedRange - ] - ]; + $requests = []; + + foreach ($protections as $protection) { + + $rangeStr = $protection['range']; + + if (! str_contains($rangeStr, '!')) { + throw new \Exception("Invalid range format: {$rangeStr}"); + } + + [$sheetName, $a1] = explode('!', $rangeStr, 2); + + if (! isset($sheetMap[$sheetName])) { + throw new \Exception("Sheet not found: {$sheetName}"); + } + + $sheetMeta = $sheetMap[$sheetName]; + + $gridRange = $this->convertA1ToGridRange( + $a1, + $sheetMeta['sheetId'], + $sheetMeta['rowCount'], + $sheetMeta['colCount'] + ); + + $protectedRange = [ + 'range' => $gridRange, + 'description' => 'RFQ Protected Area', + 'warningOnly' => false, + 'editors' => [ + 'users' => $protection['users'] ?? [], + 'groups' => $protection['groups'] ?? [], + ], + ]; + + $requests[] = [ + 'addProtectedRange' => [ + 'protectedRange' => $protectedRange, + ], + ]; + } + + if (! empty($requests)) { + $batch = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest([ + 'requests' => $requests, + ]); + + $this->sheets->spreadsheets->batchUpdate($spreadsheetId, $batch); + } + + return true; } - if (!empty($requests)) { - $batch = new \Google_Service_Sheets_BatchUpdateSpreadsheetRequest([ - 'requests' => $requests - ]); - - $this->sheets->spreadsheets->batchUpdate($spreadsheetId, $batch); - } - - return true; -} - /* ================= URL ================= */ public function sheetUrl(string $sheetId): string @@ -242,43 +240,41 @@ class GoogleSheetLib return "https://docs.google.com/spreadsheets/d/{$sheetId}/edit"; } + private function convertA1ToGridRange($a1, $sheetId, $maxRows, $maxCols) + { + if (preg_match('/^([A-Z]+)(\d+)(?::([A-Z]+)(\d+))?$/i', $a1, $m)) { - private function convertA1ToGridRange($a1, $sheetId, $maxRows, $maxCols) -{ - if (preg_match('/^([A-Z]+)(\d+)(?::([A-Z]+)(\d+))?$/i', $a1, $m)) { + $startCol = $this->colToIndex($m[1]); + $startRow = intval($m[2]) - 1; - $startCol = $this->colToIndex($m[1]); - $startRow = intval($m[2]) - 1; + if (! empty($m[3])) { + $endCol = $this->colToIndex($m[3]) + 1; + $endRow = intval($m[4]); + } else { + $endCol = $startCol + 1; + $endRow = $startRow + 1; + } - if (!empty($m[3])) { - $endCol = $this->colToIndex($m[3]) + 1; - $endRow = intval($m[4]); - } else { - $endCol = $startCol + 1; - $endRow = $startRow + 1; + return [ + 'sheetId' => $sheetId, + 'startRowIndex' => $startRow, + 'endRowIndex' => $endRow, + 'startColumnIndex' => $startCol, + 'endColumnIndex' => $endCol, + ]; } - return [ - 'sheetId' => $sheetId, - 'startRowIndex' => $startRow, - 'endRowIndex' => $endRow, - 'startColumnIndex' => $startCol, - 'endColumnIndex' => $endCol - ]; + throw new \Exception("Unsupported A1 format: {$a1}"); } - throw new \Exception("Unsupported A1 format: {$a1}"); -} - -private function colToIndex($letters) -{ - $letters = strtoupper($letters); - $index = 0; - for ($i = 0; $i < strlen($letters); $i++) { - $index = $index * 26 + (ord($letters[$i]) - 64); + private function colToIndex($letters) + { + $letters = strtoupper($letters); + $index = 0; + for ($i = 0; $i < strlen($letters); $i++) { + $index = $index * 26 + (ord($letters[$i]) - 64); + } + return $index - 1; } - return $index - 1; -} - } diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index 3ba0e2bd..507786c6 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -1,13 +1,12 @@ join('lead_files', 'leads.id = lead_files.lead_id AND lead_files.type = 2 AND lead_files.is_active = 1', 'left') ->where('leads.is_active', 1); - if (!empty($where)) { + if (! empty($where)) { $data->where($where); } @@ -186,7 +184,7 @@ class LeadsModel extends Model public function getLeadForInsertClientList($type = null, $client_id = null) { - $query = $this->db->table('leads') + $query = $this->db->table('leads') ->select('leads.*, user_profiles.first_name as user_name') ->join('user_profiles', 'leads.created_by = user_profiles.id') ->where('leads.is_active', 1) @@ -195,8 +193,6 @@ class LeadsModel extends Model ->where("(leads.is_client_created = '' OR leads.is_client_created IS NULL)") ->where("(leads.is_policy_created = '' OR leads.is_policy_created IS NULL)"); - - if ($type) { $query->where('leads.lead_type', $type); } @@ -243,8 +239,8 @@ class LeadsModel extends Model // $builder->select($select); // // Auditing subquery - // $subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change - // FROM auditing_history + // $subquery = "(SELECT pk, MAX(created_at) AS last_claim_status_change + // FROM auditing_history // WHERE table_name = 'leads' AND field_name = 'status' // GROUP BY pk)"; @@ -282,7 +278,7 @@ class LeadsModel extends Model // // if (!str_ends_with($key, '_ids') && $key != "won") { // // $total += (int) $value; // // } - + // if (!str_ends_with($key, '_ids')) { // $total += (int) $value; // } @@ -292,12 +288,10 @@ class LeadsModel extends Model // $lead_data[0]['total'] = $total; // $lead_data[0]['policy_with_correction'] = $policy_with_correction_count; - // // dd($lead_data[0]); // return $lead_data[0]; // } - public function getDashData() { // Get all unique statuses @@ -322,7 +316,7 @@ class LeadsModel extends Model $selectParts = []; foreach ($statuses as $row) { $status = $row['status']; - $alias = strtolower(str_replace(' ', '_', $status)); + $alias = strtolower(str_replace(' ', '_', $status)); $selectParts[] = "SUM(CASE WHEN status = '{$status}' THEN 1 ELSE 0 END) AS `{$alias}`"; $selectParts[] = "GROUP_CONCAT(CASE WHEN status = '{$status}' THEN id END) AS `{$alias}_ids`"; @@ -340,19 +334,17 @@ class LeadsModel extends Model // Calculate total $total = 0; foreach ($lead_data as $key => $val) { - if (!str_ends_with($key, '_ids')) { + if (! str_ends_with($key, '_ids')) { $total += (int) $val; } } - $lead_data['total'] = $total; - $lead_data['policy_with_correction'] = $policy_with_correction_data['count'] ?? 0; + $lead_data['total'] = $total; + $lead_data['policy_with_correction'] = $policy_with_correction_data['count'] ?? 0; $lead_data['policy_with_correction_ids'] = $policy_with_correction_data['ids'] ?? null; // dd($lead_data); return $lead_data; } - - } diff --git a/app/Models/PolicyTypeModel.php b/app/Models/PolicyTypeModel.php index 90aa1758..4e2dd802 100755 --- a/app/Models/PolicyTypeModel.php +++ b/app/Models/PolicyTypeModel.php @@ -1,14 +1,13 @@ -
+ +
diff --git a/app/Views/UserList.php b/app/Views/UserList.php index 919e7de1..9659eaf4 100755 --- a/app/Views/UserList.php +++ b/app/Views/UserList.php @@ -355,7 +355,7 @@ table.dataTable tbody td {
-
+
-
- - - - - - - - - - + -> + --> +
+
Insurer Name Insurer Branch Name CD Account Number Current Balance Action
+ + + + + + + + + - - - + + + + + - - - - - - - - - -
Insurer Name Insurer Branch Name CD Account Number Current Balance Action
insurer_name;?>insurer_branch_name;?>cd_master_account_no;?>insurer_name;?>insurer_branch_name;?>cd_master_account_no;?>₹ - insurer_id; - $cd_ac_pk = $value->cd_ac_pk; - // Check if the balance information exists for the insurer - if (isset($balances[$insurerId . '-'. $cd_ac_pk])) { - $balance = $balances[$insurerId . '-'. $cd_ac_pk]->balance; - echo $balance; - } else { - echo "N/A"; // Display "Not Available" if balance information is not present - } - ?> - - insurer_id}?client_id={$value->client_id}&cd_ac_pk={$value->cd_ac_pk}"); ?>"> - View Deposit - -
+ ₹ + insurer_id; + $cd_ac_pk = $value->cd_ac_pk; + // Check if the balance information exists for the insurer + if (isset($balances[$insurerId . '-'. $cd_ac_pk])) { + $balance = $balances[$insurerId . '-'. $cd_ac_pk]->balance; + echo $balance; + } else { + echo "N/A"; // Display "Not Available" if balance information is not present + } + ?> + + + insurer_id}?client_id={$value->client_id}&cd_ac_pk={$value->cd_ac_pk}"); ?>"> + View Deposit + + + + + + +
@@ -70,7 +75,7 @@ $(document).ready(function() { $('#tickets-table').DataTable({ // dom: "<'row'<'col-sm-0'f><'col-sm-9 text-right'B>>", - dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>", + dom: "<'row'<'col-12 d-flex justify-content-between align-items-center'<'datatable-search dataTables_filter'f><'datatable-buttons dt-buttons'B>>>" + "<'row'<'col-sm-12'tr>>" + "<'row align-items-center'<'col-5 text-start'i><'col-7 d-flex justify-content-end align-items-center'<'me-2'l>p>>", lengthMenu: [[10, 20, 50, 100], [10, 20, 50, 100]], diff --git a/app/Views/client_onboarding.php b/app/Views/client_onboarding.php index 928836a0..e7af7f88 100755 --- a/app/Views/client_onboarding.php +++ b/app/Views/client_onboarding.php @@ -271,14 +271,18 @@
-
+ +
diff --git a/app/Views/dms_search.php b/app/Views/dms_search.php index f3e1bad0..ea953fff 100644 --- a/app/Views/dms_search.php +++ b/app/Views/dms_search.php @@ -25,83 +25,102 @@ .dataTables_length label {height: 21px !important;} + .filter-sidebar { + height: 100%; + width: 0; + position: fixed; + z-index: 1001; + top: 0; + right: 0; + background-color: #f8f9fa; + overflow-x: hidden; + transition: 0.5s; + box-shadow: -2px 0 5px rgba(0,0,0,0.1); + display: flex; + flex-direction: column; + } + + .filter-sidebar-header { + padding: 15px 20px; + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 1px solid #dee2e6; + flex-shrink: 0; + } + + .filter-sidebar-header .closebtn { + font-size: 28px; + text-decoration: none; + color: #6c757d; + } + + .filter-sidebar .closebtn:hover { + color: #000; + } + + .filter-sidebar-content { + padding: 20px; + flex-grow: 1; + overflow-y: auto; + } + + .filter-sidebar-footer { + padding: 15px 20px; + display: flex; + justify-content: flex-end; + border-top: 1px solid #dee2e6; + flex-shrink: 0; + gap: 10px; + } + -
-
-
-
-
-

- Filter - - - -

-
-
-
-
" id='dms_search_form'> -
+
+
+

Filter

+ × +
+
+ " id='dms_search_form'> +
-
- - - - - - -
- -
- - - - -
-
- -
- OR -
-
- -
- - - - - - -
- -
- - - - -
- -
- - - -
- -
- -
-
-
+
+ + + +
-
-
+
+ + +
+
+ OR +
+
+ + + + +
+ +
+ + +
+
+ +
+
+
@@ -109,9 +128,7 @@

Files

-
-
@@ -131,18 +148,15 @@ - - - - + @@ -157,10 +171,15 @@ \ No newline at end of file diff --git a/app/Views/endorsement_list.php b/app/Views/endorsement_list.php index 76642e9a..66ef74c5 100755 --- a/app/Views/endorsement_list.php +++ b/app/Views/endorsement_list.php @@ -13,50 +13,88 @@ left: 79px; } .dataTables_length label {height: 21px !important;} + .filter-sidebar { + height: 100%; + width: 0; + position: fixed; + z-index: 1001; + top: 0; + right: 0; + background-color: #f8f9fa; + overflow-x: hidden; + transition: 0.5s; + box-shadow: -2px 0 5px rgba(0,0,0,0.1); + display: flex; + flex-direction: column; + } + .filter-sidebar-header { + padding: 15px 20px; + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 1px solid #dee2e6; + flex-shrink: 0; + } + + .filter-sidebar-header .closebtn { + font-size: 28px; + text-decoration: none; + color: #6c757d; + } + + .filter-sidebar .closebtn:hover { + color: #000; + } + + .filter-sidebar-content { + padding: 20px; + flex-grow: 1; + overflow-y: auto; + } + + .filter-sidebar-footer { + padding: 15px 20px; + display: flex; + justify-content: flex-end; + border-top: 1px solid #dee2e6; + flex-shrink: 0; + gap: 10px; + }
-
-
-
-
-
-

- Filter - - - -

-
-
- -
-
-
- -
+
+
+

Filter

+ × +
+
+
+
+
+ + +
+
+ + +
-
-
- -
+
+ + +
-
-
- -
- -
-
+
+
-
- -
- - -
-
+ +
- +
+
@@ -87,12 +118,12 @@
-
+
- + href="">
@@ -212,11 +243,9 @@ function fetchClientPolicies() { - $('#loader').show(); var apiURL = '' + 'util/clients-with-policies'; console.log('fetchClientPolicies'); - // console.log(apiURL); $.ajax({ url: apiURL, method: 'GET', @@ -225,9 +254,7 @@ "X-Requested-With": "XMLHttpRequest" }, success: function(response) { - // console.log(response.code); - // console.log(response.dataStatus); - // console.log(response.data); + $('#loader').hide(); // ✅ hide AFTER data received if (response.code === 200 && response.dataStatus === true && response.data !== "") { try { clientPolicies = (response.data); @@ -280,13 +307,20 @@ } }, error: function(xhr, status, error) { + $('#loader').hide(); // ✅ hide on error too console.error('Error fetching data from API:', error); } }); - - $('#loader').hide(); + } + /* Modified by Gemini Code Assist */ + function openEndorsementListFilterNav() { + document.getElementById("filter-sidebar").style.width = "350px"; } + /* Modified by Gemini Code Assist */ + function closeFilterNav() { + document.getElementById("filter-sidebar").style.width = "0"; + } function appendClients(data) { @@ -432,11 +466,7 @@ } - document.getElementById('toggleIcon').addEventListener('click', function() { - var icon = document.getElementById('icon'); - icon.classList.toggle('mdi-chevron-down'); - icon.classList.toggle('mdi-chevron-up'); - }); + $('.emp_data_model').click(function() { @@ -611,6 +641,13 @@ // openTicket(); // } // }, + { + text: ' Filter ', + className: 'btn app-btn-primary mr-2', + action: function(e, dt, node, config) { + openEndorsementListFilterNav(); + } + }, { extend: 'collection', text: ' Export ', @@ -632,24 +669,6 @@ ] } ], - // buttons: [{ - // extend: 'csv', - // text: 'CSV', - // title: 'Endorsement-List', - // className: 'my_class', - // exportOptions: { - // columns: ':not(:last-child)', - // format: { - // body: function (data, row, column, node) { - // // Convert data to string to avoid scientific notation in CSV - // if (!isNaN(data) && parseFloat(data) > 1e20) { - // return `'${data}`; - // } - // return data.toString();// Ensures all data is treated as strings - // } - // } - // } - // }], initComplete: function(settings, json) { $('.my_class').css({ "position": "relative", diff --git a/app/Views/faq_list.php b/app/Views/faq_list.php index bc49cd41..3df7a4ae 100644 --- a/app/Views/faq_list.php +++ b/app/Views/faq_list.php @@ -36,7 +36,7 @@
-
+
diff --git a/app/Views/frontend_content_list.php b/app/Views/frontend_content_list.php index 71f8e0ed..2a2b5ee7 100644 --- a/app/Views/frontend_content_list.php +++ b/app/Views/frontend_content_list.php @@ -35,7 +35,7 @@
-
+
diff --git a/app/Views/gsheet_editor.php b/app/Views/gsheet_editor.php index e3c9f316..df694995 100644 --- a/app/Views/gsheet_editor.php +++ b/app/Views/gsheet_editor.php @@ -12,7 +12,7 @@ -

Google Sheet Editor

+

Edit RFQ

@@ -44,9 +44,9 @@ function createRfq() {
-
+
diff --git a/app/Views/insurer_list.php b/app/Views/insurer_list.php index 05e0dc7e..57e04cbb 100755 --- a/app/Views/insurer_list.php +++ b/app/Views/insurer_list.php @@ -46,7 +46,7 @@
-
+
-
+