diff --git a/app/Config/Routes.php b/app/Config/Routes.php index ca0cbe4f..e94c6ad4 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -18,8 +18,9 @@ $routes->get("update-policy-terms-for-corrections", "ClientController::updatePol $routes->get("update_rack_rate_json", "ClientController::updateRackRateJson"); $routes->get("updatajson", "EmpDataServiceController::updatajson"); $routes->get("view", "EmployeeController::viewECard/$1"); - - +// $routes->get("exportQCRandRFQ", "LeadsController::exportQCRandRFQ"); +$routes->get("smapletest", "ClientController::smapletest"); +$routes->get("testMailAttachments", "ClientController::testMailAttachments"); $routes->post("add_advertise_image", "AppContentManagementController::add_advertise_image"); $routes->get("add_image_index", "AppContentManagementController::add_image_index"); @@ -73,7 +74,9 @@ $routes->group("/client", ["filter" => "authMVC"], function ($routes) { $routes->group("notification", ["filter" => "authMVC"], function ($routes) { $routes->post("create", "NotificationController::createNotification"); $routes->post("update_enable", "NotificationController::update_enable"); + $routes->post("add_attachment", "NotificationController::insertAttachmentsForMailTemplates"); $routes->get("getMailTemplateData/(:any)/(:any)", "NotificationController::getMailTemplateData/$1/$2"); + $routes->get("removeAttachment/(:any)", "NotificationController::removeAttachmentsForMailTemplates/$1"); }); $routes->group("general", ["filter" => "authMVC"], function ($routes) { @@ -297,8 +300,14 @@ $routes->group("/util", ["filter" => "authMVC"], function ($routes) { $routes->get("base_policy_for_policy_inception/(:any)", "PolicyTransactionController::getBasePolicy/$1"); $routes->get("sentTestMail/(:any)", "NotificationController::sentTestMail/$1"); $routes->get("send_manual_reminder/(:any)", "DashboardController::sendManualReminder/$1"); + $routes->get("send_manual_ecard/(:any)", "DashboardController::sendManualEcard/$1"); $routes->get("get_client_policy_list_for_remainder/(:any)", "EmployeeController::get_client_policy_list_for_remainder/$1"); $routes->get("get_client_branch_data/(:any)", "ClientController::get_client_branch_data/$1"); + $routes->get("getLevelContects", "LeadsController::getLevelContects"); + $routes->get("get_emp_master_data_for_update/(:any)", "EmployeeController::get_emp_master_data_for_update/$1"); + $routes->get("send_mail_for_individual_employee_ecard/(:any)", "EmployeeController::send_mail_for_individual_employee_ecard/$1"); + $routes->post("update_emp_data", "EmployeeController::update_emp_data"); + $routes->get("checkDeletionGetDataFunction", "EmployeeController::checkDeletionGetDataFunction"); }); @@ -343,8 +352,18 @@ $routes->group("leads", ["filter" => "authMVC"], function ($routes) { $routes->get("list", "LeadsController::viewLeadsList"); $routes->post("create", "LeadsController::createLead"); $routes->get("list/(:any)", "LeadsController::getLeadDataForEdit/$1"); + $routes->get("sendMail", "LeadsController::sendMailWithAttachement"); + $routes->get("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$1"); + $routes->get("featchLeadDataAndInsertClient/(:any)", "LeadsController::featchLeadDataAndInsertClient/$1"); }); +$routes->group("rfq", ["filter" => "authMVC"], function ($routes) { + $routes->post("create", "LeadsController::createRFQ"); + $routes->post("createQCR", "LeadsController::createQCR"); + $routes->get("list/(:any)", "LeadsController::viewRFQ/$1"); +}); + + $routes->get("driveListFiles", "GoogleDriveController::listFiles"); $routes->post('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']); $routes->get('dmsSearch', 'PolicyTransactionController::dmsSearch', ['filter' => 'authMVC']); @@ -355,16 +374,17 @@ $routes->cli('cli/processjobs', 'JobWorker::processJobs'); $routes->get("processjob", "JobWorker::processJob"); $routes->cli('cli/new_gmail_token', 'MasterController::generateNewGmailAPIToken'); -$routes->cli('cli/send_mail_cli(/:any)?', 'MasterController::testGmailAPIViaCLI$1'); +$routes->cli('cli/send_mail_cli', 'MasterController::testGmailAPIViaCLI'); +$routes->cli('cli/check_bounce_mail_cli', 'MasterController::testCheckBounceMails'); $routes->cli('cli/app_check_list', 'MasterController::appCheckList'); $routes->cli('cli/new_gdrive_token', 'GoogleDriveController::generateNewGoogleDriveAccessToken'); - //Employee login api's $routes->post("/employeeRest/verifyEmployeeNumber", "RestAuthenticationController::verifyEmployeeWithMobileNumber"); $routes->post("/employeeRest/getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData"); $routes->post("/employeeRest/verifyMpin", "RestAuthenticationController::verifyMpin"); $routes->post("/employeeRest/checkMpin", "RestAuthenticationController::checkMpin"); + //HR login api's $routes->post("/employeeRest/verifyHrWithMobileNumber", "RestAuthenticationController::verifyHrWithMobileNumber"); $routes->post("/employeeRest/getVerifiedHrData", "RestAuthenticationController::getVerifiedHrData"); @@ -374,9 +394,6 @@ $routes->group("/api", ["filter" => "authJWT"], function ($routes) { $routes->post("getId", "RestAuthenticationController::getUserIdFromToken"); }); - - - $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { $routes->post("getVerifiedUserData", "RestAuthenticationController::getVerifiedUserData"); @@ -419,17 +436,9 @@ $routes->group("employeeRest", ["filter" => "authJWT"], function ($routes) { }); $routes->get("sendPushNotification", "EmployeeRestController::sendPushNotification"); - - - - $routes->post("sendEmail", "EmployeeRestController::send_email"); - - - - // Ticketing System // Ticketing System End's diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index c6b3f152..b937e835 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -38,6 +38,7 @@ use App\Models\PolicyTypeModel; use App\Models\PolicyTransactionModel; use App\Models\PolicyTransactionStatusModel; use App\Models\VehicleModel; +use App\Models\LeadsModel; use App\Controllers\EmpDataServiceController; use App\Controllers\GoogleDriveController; @@ -78,6 +79,7 @@ class ClientController extends AdminController protected $policyTransactionModel; protected $policyTransactionStatusModel; protected $vehicleModel; + protected $leadsModel; @@ -113,6 +115,31 @@ class ClientController extends AdminController $this->policyTransactionModel = new PolicyTransactionModel(); $this->policyTransactionStatusModel = new PolicyTransactionStatusModel(); $this->vehicleModel = new VehicleModel(); + $this->leadsModel = new LeadsModel(); + } + + public function smapletest() + { + $headers = ['S.No','EMP ID','EMP NAME','DOB','GENDER','RELATIONSHIP','SUM INSURED','Date of Leaving','Policy End Date','No Of Days','Premium','Pro Rata Premium','GST','Total','Claim Status','ENDORSEMENT_ID']; + $filePath = generateExcelWithHeader($headers); + echo "Excel file created at: $filePath"; + } + + public function testMailAttachments($email = 'venkateshraman786@gmail.com') + { + $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

'; + + $attachments = [ + ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"], + ["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"], + ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"] + ]; + + $res = MailHelper::send_email(['mail' => $email, 'subject' => 'Mail Via Attachment Testing URL', 'message' => $message,'attachments' => $attachments]); + + print_rr($res); + echo '------------------------------------------------------------------------------------------'; + print_rr($attachments); } public function testingForReviewMail($client_id = 77, $emp_code = 'MGL-004', $mail_active = 0) //this function for only tsesting some logics not use for business logic @@ -238,6 +265,7 @@ class ClientController extends AdminController $headerData['page_name'] = 'Client List'; $data['clientList'] = $this->clientModel->getCreatedByUserName(); $data['client_rm'] = $this->clientRMModel->getAllClientRM(); + // $data['lead_data'] = $this->leadsModel->getLeadForInsertClientList(); // dd($data); @@ -1705,15 +1733,6 @@ class ClientController extends AdminController } - public function editUploadVehicleFile() {} - - public function listVehicleFiles() {} - - public function deleteVehicleFiles() {} - - - - public function getKycDocsById($id = null) { diff --git a/app/Controllers/DashboardController.php b/app/Controllers/DashboardController.php index bd126144..dfa0841a 100755 --- a/app/Controllers/DashboardController.php +++ b/app/Controllers/DashboardController.php @@ -20,6 +20,7 @@ use App\Models\ClientPolicyModel; use App\Models\NotificationModel; use App\Models\EmployeePolicyModel; use App\Controllers\PendingActionsContrller; +use App\Controllers\EmpDataServiceController; class DashboardController extends AdminController { @@ -544,6 +545,35 @@ class DashboardController extends AdminController } } + public function sendManualEcard($client_id, $client_branch_id, $policy_id) + { + $this->myLogger->logme('error', "sendManualEcard called with client_id: {$client_id}, client_branch_id: {$client_branch_id}, policy id : {$policy_id}"); + + $notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', 'member_ecard_mail')->first(); + // print_r(($notification)); die; + if($notification && $notification['enabled'] == 0 && $notification['mail_content'] == '') + { + return $this->respond(['status' => false, 'code' => 400, 'message' => 'No template found','message2' => 'Failed' ], 200); + } + + $emp_data = $this->employeePolicyModel->getEmployeePolicyForEcard($policy_id); + if(count($emp_data) == 0) + { + return $this->respond(['status' => false, 'code' => 400, 'message' => 'No employees found','message2' => 'Failed' ], 200); + } + $ids = array_column($emp_data, 'id'); + // print_r(($ids)); die; + // print_r($this->clientPolicyModel->getLastQuery()); die; + // $this->myLogger->logme('error', "Policy details fetched: " . json_encode($client_policy_data)); + Jobs::addJob(['job_name' => 'sendMailForDownloadingECard', 'payload' => $ids]); + // $empEmpDataServiceController = new EmpDataServiceController(); + // $empEmpDataServiceController->sendMailForDownloadingECard($ids); + + + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Mail Queued'], 200); + + } + public function data_construct_for_bds($data){ $groupedData = [ diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 5cefd249..ff8e0413 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -168,19 +168,23 @@ class EmpDataServiceController extends BaseController $cash_balance['balance'] = $balance['opening_bal']; } - - // Calculate the total amount from the objects - $totals = 0; - foreach ($objects as $item) { - $totals = $totals + $item->total; - } - $totals = round($totals, 2); - if (!empty($cash_balance)) { - if ((int) $cash_balance['balance'] < (int) $totals) { - $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.'); - $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]); - return 0; + // Calculate the total amount from the objects + $totals = 0; + foreach ($objects as $item) { + $totals = $totals + $item->total; + } + + $totals = round($totals, 2); + + if($export_data['insurer_or_tpa'] == 'insurer') //check CD amt related issue for only insurer, not tpa + { + if (!empty($cash_balance)) { + if ((int) $cash_balance['balance'] < (int) $totals) { + $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.'); + $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount. CASH BALANCE : {balance} and TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]); + return 0; + } } } @@ -298,7 +302,7 @@ class EmpDataServiceController extends BaseController ], [ 'column_index' => 18, - 'column_name' => 'PR0 RATA PREMIUM', + 'column_name' => 'PRO RATA PREMIUM', 'db_column_name' => 'rata_premimum' ], [ @@ -408,7 +412,7 @@ class EmpDataServiceController extends BaseController ], [ 'column_index' => 18, - 'column_name' => 'PR0 RATA PREMIUM', + 'column_name' => 'PRO RATA PREMIUM', 'db_column_name' => 'pro_rata_premium' ], [ @@ -636,11 +640,14 @@ class EmpDataServiceController extends BaseController // echo '
';
         // print_r($ids); die;
 
-        if (!empty($cash_balance)) {
-            if ((int) $cash_balance['balance']  < (int) $rounded_totals) {
-                $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.');
-                $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.  CASH BALANCE : {balance}  and  TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
-                return 0;
+        if($export_data['insurer_or_tpa'] == 'insurer') //check CD amt related issue for only insurer, not tpa
+        {
+            if (!empty($cash_balance)) {
+                if ((int) $cash_balance['balance']  < (int) $rounded_totals) {
+                    $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.');
+                    $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.  CASH BALANCE : {balance}  and  TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
+                    return 0;
+                }
             }
         }
 
@@ -704,7 +711,6 @@ class EmpDataServiceController extends BaseController
             
         }
 
-
         $excel_data_info = generate_insurer_based_excel($excel_header_columns, $objects);
 
         // Generate Excel file
@@ -921,18 +927,23 @@ class EmpDataServiceController extends BaseController
                 $cash_balance['balance'] = $balance['opening_bal'];
             }
 
-            // Calculate the total amount from the objects
-            $totals = 0;
-            foreach ($inceptionData as $item) {
-                $totals =  $totals + $item->total;
-            }
+
             
-            $totals = round($totals, 2);
-            if (!empty($cash_balance)) {
-                if ((int) $cash_balance['balance']  < (int) $totals) {
-                    $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.');
-                    $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.  CASH BALANCE : {balance}  and  TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
-                    return 0;
+                // Calculate the total amount from the objects
+                $totals = 0;
+                foreach ($inceptionData as $item) {
+                    $totals =  $totals + $item->total;
+                }
+             $totals = round($totals, 2);
+            
+            if($export_data['insurer_or_tpa'] != 'tpa')// check overal emp premium amt with cd balance only for insurer export, not tpa export
+            { 
+                if (!empty($cash_balance)) {
+                    if ((int) $cash_balance['balance']  < (int) $totals) {
+                        $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.');
+                        $this->myLogger->logme('error', 'Inception export failed due to insufficient deposit amount.  CASH BALANCE : {balance}  and  TOTAL AMOUNT : {total}', ['balance' => $cash_balance['balance'], 'total' => $totals]);
+                        return 0;
+                    }
                 }
             }
         }
@@ -1272,7 +1283,7 @@ class EmpDataServiceController extends BaseController
         unset($excel_data[0]);
         // array_pop($excel_data);
 
-        $inceptionHeader = ['S.No', 'NAME OF EMP/DEP','EMP ID','EMP/DEP TYPE','RELATIONSHIP CODE','DOB','GENDER','PRE EXISTING AILMENTS','BASIC COVER SI','DATE OF COVERAGE','AGE','RELATIONSHIP','REMARKS','POLICY END DATE','NO OF DAYS','TPA ID','UHID','PREMIUM','PR0 RATA PREMIUM','GST','TOTAL AMOUNT'];
+        $inceptionHeader = ['S.No', 'NAME OF EMP/DEP','EMP ID','EMP/DEP TYPE','RELATIONSHIP CODE','DOB','GENDER','PRE EXISTING AILMENTS','BASIC COVER SI','DATE OF COVERAGE','AGE','RELATIONSHIP','REMARKS','POLICY END DATE','NO OF DAYS','TPA ID','UHID','PREMIUM','PRO RATA PREMIUM','GST','TOTAL AMOUNT'];
 
         foreach ($inceptionHeader as $key => $value) {
             if($excel_header[$key] != $value){
@@ -1658,6 +1669,7 @@ class EmpDataServiceController extends BaseController
 
         $file_id = $params['file_id'];
         $file = $this->batchFileModel->find($file_id);
+
         if (!$file) {
 
             $data = [
@@ -1688,7 +1700,6 @@ class EmpDataServiceController extends BaseController
                     ->where('insurer_id', $insurer_id['insurer_id'])
                     ->first();
 
-
         $get_policy_type = $this->clientPolicyModel
             ->select('policy_type.policy_type, policies.policy_type_id as policy_type_id')
             ->join('policies', 'policies.id = client_policy.policy_id')
@@ -1771,12 +1782,11 @@ class EmpDataServiceController extends BaseController
             'amount' => $totals,
         ]);
 
-
         $this->myLogger->logme('error', 'Inception Update TPA and UHID --    employee count : {data}', ['data' => $emp_count]);
         $this->myLogger->logme('error', 'Inception Update TPA and UHID --    batch file status : {data}', ['data' => $status_val]);
         $this->myLogger->logme('error', 'Inception Update TPA and UHID --    total amount for cash deposite : {data}', ['data' => $totals]);
 
-
+        //update CD transaction entry if only insurer
         if ($file['insurer_or_tpa'] == 'insurer') {
 
             $this->myLogger->logme('error', 'Inception Update TPA and UHID --    set  cashDepositCalculationForInception and sendMailForDownloadingECard in JOB QUEUE');
@@ -1808,15 +1818,20 @@ class EmpDataServiceController extends BaseController
                 'user_id' => $user_id,
             ]]);
 
+            // $this->cashDepositCalculationForInception($depositeData);
+            // $this->sendMailForDownloadingECard($emp_policy_ids);
+
+        }
+
+        //send ecard mail if the event is tpa only
+        if ($file['insurer_or_tpa'] == 'tpa') {
+
             if ($get_policy_type['policy_type_id'] != 1) {
 
                 $job_details  = new Jobs();
                 $r = Jobs::addJob(['job_name' => 'sendMailForDownloadingECard', 'payload' => $emp_policy_ids]);
             }
 
-            // $this->cashDepositCalculationForInception($depositeData);
-            // $this->sendMailForDownloadingECard($emp_policy_ids);
-
         }
 
         $file_data = $this->getDataByFileId($file_id, 'success');
@@ -2845,27 +2860,29 @@ class EmpDataServiceController extends BaseController
         $this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID --      Employee count : {data}', ['data' => $emp_count]);
         $this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID --      Batch File status : {data}', ['data' => $status_val]);
 
+        //call the cash deposite function
+        if ($file['insurer_or_tpa'] == 'insurer') {
+
+            $policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id);
+            $job_details  = new Jobs();                             
+            $r = Jobs::addJob(['job_name' => 'cashDepositCalculationForSIEnhancement','payload' => [
+                'employeeIds' => $insertedIds,
+                'client_id' => $client_id,
+                'client_policy_id' => $client_policy_id,
+                'client_branch_id' => $client_branch_id,
+                'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
+                'endorsement_no' => $endorsement_id ?? null,
+                'count' => $emp_count,
+                'event_name' => $file['event_type'],
+                'policy_name' => $policy_name['policy_name'],
+                'user_id' => $user_id,
+            ]]);
+
+        }
 
         $file_data = $this->getDataByFileId($file_id, 'success');
         $this->setPullNotification($file_data);
 
-        //call the cash deposite function
-
-        $policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id);
-        $job_details  = new Jobs();                             
-        $r = Jobs::addJob(['job_name' => 'cashDepositCalculationForSIEnhancement','payload' => [
-            'employeeIds' => $insertedIds,
-            'client_id' => $client_id,
-            'client_policy_id' => $client_policy_id,
-            'client_branch_id' => $client_branch_id,
-            'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
-            'endorsement_no' => $endorsement_id ?? null,
-            'count' => $emp_count,
-            'event_name' => $file['event_type'],
-            'policy_name' => $policy_name['policy_name'],
-            'user_id' => $user_id,
-        ]]);
-
         //import file to upload Google Drive
         // if(excelFileGDriveUpload($file_id, 'batch_file')){
         //     $this->myLogger->logme('error', 'SI Enhancement File Update Google Drive File Upload --    File Uploaded Successfully');
@@ -3372,28 +3389,27 @@ class EmpDataServiceController extends BaseController
         $this->myLogger->logme('error', 'Deletion Update Endorsement ID --      Employee count : {data}', ['data' => $emp_count]);
         $this->myLogger->logme('error', 'Deletion Update Endorsement ID --      Batch File status : {data}', ['data' => $status_val]);
 
+        //call the cash deposite function
+        if ($file['insurer_or_tpa'] == 'insurer') {
+            $policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id);
+            $job_details  = new Jobs();
+            $r = Jobs::addJob(['job_name' => 'cashDepositCalculationForDeletion', 'payload' => [
+                'employeeIds' => $employee_policy_table_primaryKey,
+                'client_id' => $client_id,
+                'client_policy_id' => $client_policy_id,
+                'client_branch_id' => $client_branch_id,
+                'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
+                'endorsement_no' => $endorsement_id ?? null,
+                'count' => $emp_count,
+                'event_name' => $file['event_type'],
+                'policy_name' => $policy_name['policy_name'],
+                'user_id' => $user_id,
+            ]]);
+        }
 
         $file_data = $this->getDataByFileId($file_id, 'success');
         $this->setPullNotification($file_data);
 
-        //call the cash deposite function
-
-        $policy_name = $this->getPolicyNameUsingClientPolicyId($client_policy_id);
-
-        $job_details  = new Jobs();
-        $r = Jobs::addJob(['job_name' => 'cashDepositCalculationForDeletion', 'payload' => [
-            'employeeIds' => $employee_policy_table_primaryKey,
-            'client_id' => $client_id,
-            'client_policy_id' => $client_policy_id,
-            'client_branch_id' => $client_branch_id,
-            'cd_ac_no' => $CD_Account_Number['cd_ac_no'] ?? null,
-            'endorsement_no' => $endorsement_id ?? null,
-            'count' => $emp_count,
-            'event_name' => $file['event_type'],
-            'policy_name' => $policy_name['policy_name'],
-            'user_id' => $user_id,
-        ]]);
-
         //import file to upload Google Drive
         // if(excelFileGDriveUpload($file_id, 'batch_file')){
         //     $this->myLogger->logme('error', 'Deletion File Update Google Drive File Upload --    File Uploaded Successfully');
@@ -4215,7 +4231,7 @@ class EmpDataServiceController extends BaseController
         return true;
     }
 
-    public function sendMailForDownloadingECard(array $ids)
+    public function sendMailForDownloadingECard(array $ids, $single_mail = null)
     {
         
         $this->myLogger->logme('error', 'sendMailForDownloadingECard - function called');
@@ -4260,7 +4276,6 @@ class EmpDataServiceController extends BaseController
 
                             $this->myLogger->logme('error', 'sendMailForDownloadingECard - Send Bulk Mail function inside if condition ',);
 
-
                             $rand_string =  $get_emp_email_and_other_details['rand_string'];
                             $tpa_id =  $get_emp_email_and_other_details['tpa_id'];
 
@@ -4275,14 +4290,21 @@ class EmpDataServiceController extends BaseController
 
                             if (isset($get_emp_email_and_other_details['email_corporate']) && !empty($get_emp_email_and_other_details['email_corporate']) && $get_emp_email_and_other_details['relationship'] == 'Self') {
                                 $wholeData[] = sendMailNotification::sendMailNotification('member_ecard_mail', $params);
-
                                 // print_r($wholeData);die;
                                 $count++;
                             }
 
                             $counts++;
-                            
+
+                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - counts : {data}', ['data' => $counts]);
+                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - count : {data}', ['data' => $count]);
+                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - ids count : {data}', ['data' => count($ids)]);
+                            $this->myLogger->logme('error', 'sendMailForDownloadingECard - whole count : {data}', ['data' => count($wholeData)]);
+
                             if ($count == 20 || $counts == count($ids) - 1) {
+
+                                $this->myLogger->logme('error', 'sendMailForDownloadingECard - ids count : {data}', ['data' => count($ids)]);
+
                                 if(count($wholeData) > 0){
 
                                     $this->myLogger->logme('error', 'sendMailForDownloadingECard - create a job to bulk mail',);
@@ -4293,6 +4315,27 @@ class EmpDataServiceController extends BaseController
                                     $count = 0;
 
                                 }
+                            }else{
+
+                                // for view member individual employee send self and self family ecard 
+                                if($single_mail){
+
+                                    if(count($wholeData) > 0){
+
+                                        $this->myLogger->logme('error', 'sendMailForDownloadingECard - create a job for single mail to bulk mail function',);
+    
+                                        $mail_send_return =  MailHelper::send_email($wholeData[0]);
+                                        $this->myLogger->logme("info", $mail_send_return);
+                                        return $mail_send_return;
+
+                                        // $job_details  = new Jobs();
+                                        // $r = Jobs::addJob(['job_name' => 'bulk_mail', 'payload' => $wholeData]);
+                                        // $wholeData = [];
+                                        // $count = 0;
+    
+                                    }
+
+                                }
 
                             }
 
@@ -4313,6 +4356,7 @@ class EmpDataServiceController extends BaseController
                 $this->myLogger->logme('error', 'sendMailForDownloadingECard - the client notification setup not created or not enabled the E-Card Notification');
                 return false;
             }
+
         } else {
 
             $this->myLogger->logme('error', 'sendMailForDownloadingECard - employee_policy_ids are empty');
diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php
index 7c5d3f01..810798af 100755
--- a/app/Controllers/EmployeeController.php
+++ b/app/Controllers/EmployeeController.php
@@ -87,22 +87,33 @@ class EmployeeController extends AdminController
     {
         // $model = new UserModel();
         $data = [];
-        $data['status'] = ['draft' => 'Draft', 'active' => 'Active', 'inactive' => 'In-Active', 'pending' => 'Pending'];
+        $data['status'] = ['draft' => 'Draft', 'enrolled' => 'Enrolled', 'active' => 'Active', 'inactive' => 'In-Active', 'pending' => 'Pending'];
+        
         if (count($this->request->getGet())) {
             $filterData = $this->request->getGet();
+        
+            // Convert the status field to an array if it exists in the request data
+            if (isset($filterData['status']) && !empty($filterData['status'])) {
+                $filterData['status'] = explode(",", $filterData['status']);
+            }else{
+                $filterData['status'] = [];
+            }
+        
+            // Fetch employees with the modified $filterData array
             $data['employees'] = $this->employeePolicyModel->getEmployeePolicy(
-                client_id: $filterData['client_id'], 
-                policy_id: $filterData['policy_id'], 
-                branch_id: $filterData['branch_id'],
-                emp_code : $filterData['emp_code'],
-                emp_name : $filterData['emp_name'],
-                status   : $filterData['status'], 
+                client_id: $filterData['client_id'] ?? null, 
+                policy_id: $filterData['policy_id'] ?? null, 
+                branch_id: $filterData['branch_id'] ?? null,
+                emp_code : $filterData['emp_code'] ?? null,
+                emp_name : $filterData['emp_name'] ?? null,
+                status   : $filterData['status'] ?? [], 
             );
-            // dd($this->employeePolicyModel->getLastQuery());
-
+        
+            // Set getData in $data array with the processed $filterData
             $data['getData'] = $filterData;
         }
-
+        
+        // dd($this->employeeModel->getLastQuery());
         // dd( $data['getData']);
 
         // dd($this->request->getGet());
@@ -263,7 +274,7 @@ class EmployeeController extends AdminController
         //for TPA/insurer upload
         $data['events'] = ['inception' => 'Inception (Employee + Dependents)', 'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement'];
         //for inception upload
-        $data['actions'] = ['inception' => 'Inception (Employee + Dependents)',  'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addtion' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement','enrollment' => 'Enrolment'];
+        $data['actions'] = ['inception' => 'Inception (Employee + Dependents)',  'missed_inception' => 'Missed Inception (Employee + Dependents)', 'addition' => 'Addition (Employee + Dependents)', 'dependent_addition' => 'Dependent Addition (Only Dependents)', 'deletion' => 'Deletion', 'correction' => 'Correction', 'si_enhancement' => 'SI Enhancement','enrollment' => 'Enrolment'];
 
         $data['import_or_export'] = ['import' => 'Import', 'export' => 'Export'];
         $data['insurer_or_tpa'] = ['insurer' => 'Insurer', 'tpa' => 'TPA'];
@@ -279,7 +290,7 @@ class EmployeeController extends AdminController
 
         $data['fileList'] = $this->fileModel
                             ->select([
-                                'files.*',
+                                'files.id','files.file_name','files.created_by','files.created_at','files.is_active','files.status','files.client_id','files.policy_id','files.client_branch_id','files.action','files.uploaded_by',
                                 'up.emp_code',
                                 'up.first_name',
                                 'c.short_name',
@@ -301,9 +312,10 @@ class EmployeeController extends AdminController
                             ->join('client_branch cb', 'files.client_branch_id = cb.id', 'left')
                             ->join('policy_type', 'policy_type.id = cp.policy_type_id')
                             ->join('clients c', 'files.client_id = c.id and files.client_id = cp.client_id', 'left')
-                            ->where('files.created_by', get_session_userid())
+                            // ->where('files.created_by', get_session_userid())
                             ->orderBy('files.created_at', 'desc')
-                            ->findAll();
+                            ->limit(100)
+                            ->find();
         // dd($data['fileList']);
 
         $data['batch_list'] = $this->batchFileModel->select(
@@ -318,7 +330,8 @@ class EmployeeController extends AdminController
             ->join('policy_type', 'policy_type.id = client_policy.policy_type_id')
             ->join('clients', 'clients.id = client_policy.client_id')
             ->orderBy('batch_files.id', 'desc')
-            ->findAll();
+            ->limit(100)
+            ->find();
 
 
         // dd($data['fileList']);die();
@@ -443,28 +456,25 @@ class EmployeeController extends AdminController
             'actions' => $actions,
             'file_name' => $file_name,
         ];
-
         if ($actions == 'export') {
 
-            if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition' || $event_type == 'missed_inception') {
+            if ($event_type == 'inception' || $event_type == 'addition' || $event_type == 'dependent_addition' || $event_type == 'missed_inception' ||  ($event_type == 'MultipleEvents' && $insurer_or_tpa == 'tpa')) {
 
                 $return = $empDataServiceController->generateExcelForAdditionandInception($batch_data);
+                    if ($return === 0) {
+                        session()->setFlashdata('error', "Insufficient deposit amount.");
+                        return redirect()->to(base_url('employee/upload'));
 
-                if ($return === 0) {
+                    }else if($return === 5){
 
-                    session()->setFlashdata('error', "Insufficient deposit amount.");
-                    return redirect()->to(base_url('employee/upload'));
+                        session()->setFlashdata('error', "The policy does not have a CD account number.");
+                        return redirect()->to(base_url('employee/upload'));
+                    }
+                    else if($return === 6){
 
-                }else if($return === 5){
-
-                    session()->setFlashdata('error', "The policy does not have a CD account number.");
-                    return redirect()->to(base_url('employee/upload'));
-                }
-                else if($return === 6){
-
-                    session()->setFlashdata('error', "The Insurer does not have an Excel export template format.");
-                    return redirect()->to(base_url('employee/upload'));
-                }
+                        session()->setFlashdata('error', "The Insurer does not have an Excel export template format.");
+                        return redirect()->to(base_url('employee/upload'));
+                    }
 
                 if (!$return) {
 
@@ -825,7 +835,7 @@ class EmployeeController extends AdminController
         $res = $empServiceController->employeesOnboardPreprocess(['client_policy_id' => $client_policy_id,'client_branch_id' => $client_data['client_branch_id']]);
         // dd($res);
 
-        $count = count($res);
+        $count = ($res);
         $message =  $count . ' Employees are Initiate Onboard Process againts Client ' . $client_data['client_name'] . ' and the Policy is ' . $client_data['policy_name'];
         session()->setFlashdata('success1',  $message);
         return redirect()->to(base_url('/employee/upload'));
@@ -1109,6 +1119,7 @@ class EmployeeController extends AdminController
                 $htmlContent = $tmplt_data;
         
                 $placeholders = [
+                    '{CLIENT_NAME}' => $value['client_name'],
                     '{TPA_ID}' => $value['tpa_id'],
                     '{NAME}' => $value['name'],
                     '{UHID}' => $value['uhid'],
@@ -1415,7 +1426,11 @@ class EmployeeController extends AdminController
         $excelErrorData['excel_header'] = $excel_data[0];
         unset($excel_data[0]);
 
-        if($event_type == 'inception' || $event_type == 'deletion'){
+        // if($event_type == 'inception' || $event_type == 'deletion'){
+        //     array_pop($excel_data);
+        // }
+
+        if($event_type == 'deletion'){
             array_pop($excel_data);
         }
 
@@ -1696,4 +1711,79 @@ class EmployeeController extends AdminController
         return $this->respond(['status' => true, 'code' => 200, 'data' => $policies], 200);
 
     }
+
+
+    //-------- Edit individual employee and View & Send E-card  -----------------------------------------------------------------------------------------
+
+    public function get_emp_master_data_for_update($id)
+    {
+        $employee_data = $this->employeeModel->select("employees.*, DATE_FORMAT(dob, '%d/%m/%Y') AS formatted_dob,")->where('id', $id)->first();
+
+        if ($employee_data) {
+            return $this->respond(['status' => true,'code' => 200,'data' => $employee_data,], 200);
+        } else {
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'No data found.'], 404);
+        }
+    }
+
+    public function update_emp_data()
+    {
+        $data = $this->request->getPost();
+        
+        $data['dob'] = date('Y-m-d', strtotime($data['dob']));
+    
+        // Fetch current employee data
+        $employee_data = $this->employeeModel->where('id', $data['employee_primary_id'])->first();
+    
+        if ($employee_data['relationship'] == 'Self') {
+
+            if ($employee_data['gender'] != $data['gender']) {
+
+                $spouse_gender = ($data['gender'] == 'M') ? 'F' : 'M';
+                $this->employeeModel
+                    ->where('emp_code', $employee_data['emp_code'])
+                    ->where('relationship', 'Spouse')
+                    ->set(['gender' => $spouse_gender])
+                    ->update();
+            }
+        }
+    
+        // Update the employee data
+        $result = $this->employeeModel->where('id', $data['employee_primary_id'])->set($data)->update();
+    
+        if ($result) {
+            return $this->respond(['status' => true, 'code' => 200, 'data' => $data, 'message' => 'Employee updated successfully'], 200);
+        } else {
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update employee.'], 404);
+        }
+    }
+    
+    public function send_mail_for_individual_employee_ecard($id)
+    {   
+        $ids[] = $id;
+        $empDataServiceController = new EmpDataServiceController();
+        $result = $empDataServiceController->sendMailForDownloadingECard($ids, 1);
+
+        if ($result) {
+            return $this->respond(['status' => true,'code' => 200,'message' => 'Mail sent successfully', 'result' => $result,], 200);
+        } else {
+            return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to sent mail.'], 404);
+        }
+    }
+
+    public function checkDeletionGetDataFunction()
+    {   
+        $batch_data = [
+            'client_id' => 77,
+            'client_policy_id' => 203,
+            'client_branch_id' => 53,
+            'insurer_or_tpa' => 'tpa',
+        ];
+
+        $result = $this->employeePolicyModel->getDeletionEmployeeDataForExportExcel($batch_data);
+
+        print_rr($result); die;
+    }
+    
+
 }
diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php
index 0cf0e3af..0684f727 100755
--- a/app/Controllers/EmployeeRestController.php
+++ b/app/Controllers/EmployeeRestController.php
@@ -709,7 +709,7 @@ class EmployeeRestController extends AdminController
                 $file_name_with_path = WRITEPATH."/uploads/excel/".$filename;
 
                 //make an entry in DB 
-                 $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $employee_id, 'status' => 'draft', 'action' => 'enrollment', 'client_branch_id' => $client_branch_id]); //here field policy_id have client_policy_id and not policy id from policy master
+                 $file_id = $this->fileModel->insert(['file_name' => $filename, 'client_id' => $client_id, 'policy_id' => $policy_id, 'created_by' => $employee_id, 'status' => 'inprogress', 'action' => 'enrollment', 'client_branch_id' => $client_branch_id]); //here field policy_id have client_policy_id and not policy id from policy master
                 $this->myLogger->logme("error", '{file_id} - client uploaded success', ['file_id' => $file_id]);
 
                  $empServiceController = new EmployeeServiceController();
@@ -840,7 +840,8 @@ class EmployeeRestController extends AdminController
                             'band'=> $extra['10'][$index],
                             'basic_pay'=> $extra['11'][$index],
                             'unit'=> isset($extra['12'][$index]) ? $extra['12'][$index] : null,
-                            'client_branch_id' => $client_branch_id
+                            'client_branch_id' => $client_branch_id,
+                            'date_coverage' => $extra['13'][$index]
                             
                         ];
                         $basic_cover_si_value = null;
@@ -877,6 +878,8 @@ class EmployeeRestController extends AdminController
                 $count = 0;
                 for ($a=0; $a employeeModel->checkExistingEmployee($dataToInsert[$a],$client_branch_id);
                     $emp_id =0;
                     
@@ -928,6 +931,7 @@ class EmployeeRestController extends AdminController
                         'employee_id'=>$emp_id,
                         'client_policy_id'=>$policy_id,
                         'status'=> 'draft',
+                        'date_coverage' => $date_coverage,
                         'basic_cover_si'=>isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null
                     ];
 
@@ -969,6 +973,7 @@ class EmployeeRestController extends AdminController
                         
                     }
                 }
+            $this->fileModel->where('id', $file_id)->set(['status' => 'success','reason' => '','error_data' => ''])->update();
             return $this->respond(['status' => 'success', 'code' => 200, 'message' => "Success" ], 200);
             }else{
                 return $this->respond(['status' => 'failed', 'code' => 404, 'message' => "Client id and Client Policy id is Not Match!" ], 404);
diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php
index ef99ee20..c4565c6c 100755
--- a/app/Controllers/EmployeeServiceController.php
+++ b/app/Controllers/EmployeeServiceController.php
@@ -594,6 +594,15 @@ class EmployeeServiceController extends AdminController
                     'data_type' => 'str',
                     'format' => null,
                     'allowed_values' => null
+                ],
+                'doc' => [
+                    'col_idx' => 13,
+                    'col_cell_name' => 'N',
+                    'col_name' => 'DOC',
+                    'is_mandatory' => false,
+                    'data_type' => 'str',
+                    'format' => 'd-M-Y',
+                    'allowed_values' => null
                 ]
             ];
 
@@ -605,7 +614,7 @@ class EmployeeServiceController extends AdminController
                 4 => 4,    // inception: gender (Gender) -> enrollment: gender (Gender)
                 5 => 5,    // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation)
                 6 => 9,    // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI)
-                7 => null, // inception: doc (Date of Coverage) -> No match in enrollment
+                7 => 13, // inception: doc (Date of Coverage) 
                 8 => 3,    // inception: doj (DOJ) -> enrollment: doj (DOJ)
                 9 => 11,   // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay)
                 10 => 10,  // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade)
@@ -1040,7 +1049,7 @@ class EmployeeServiceController extends AdminController
                             //check self avaialbe  either same policy DB level(i.e.) gMC parents
                             if($file['action'] == 'dependent_addition' || ($policy_details['policy_type_id'] == 3 && !$is_self_available_in_policy_terms)) // 3 is GMC parents as base policy not as dep addon)
                             {
-                               $self_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: $emp_id,client_id: $file['client_id'],emp_status: ['active'],policy_status:['active'],client_branch_id:[ $file['client_branch_id'] ]);
+                               $self_details = $this->employeeModel->getEmpFamilybyEmpCode(emp_code: trim($emp_id),client_id: $file['client_id'],emp_status: ['active'],policy_status:['active'],client_branch_id:[ $file['client_branch_id'] ],relationship:['self']);
                                // dd($self_details);
                                 if(!count($self_details))
                                 {
@@ -1088,7 +1097,7 @@ class EmployeeServiceController extends AdminController
                         }// end of foreach
         }// end of if current action I,DA,A
 
-                // s($result);
+                 // return $result;
                 // die();
                 if(isset($result['error_summary']) && count($result['error_summary']))
                         {
@@ -1249,7 +1258,7 @@ class EmployeeServiceController extends AdminController
             //get policy slab rates 
             $slab_details = $this->policiesModel->getPolicySlabRatesForEmpOnboard($client_policy_id,$client_id);
 
-            $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_status: ['enrolled','draft'],policy_status:['enrolled','draft']);
+            $existing_famility_details = $this->employeeModel->getEmpFamilybyEmpCode(client_id: $client_id,client_policy_id: $client_policy_id,emp_status: ['enrolled'],policy_status:['enrolled']);
 
             // $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception'];
             $file = ['id' => null,'client_id' => $client_id,'policy_id' => $client_policy_id,'action' => 'inception','created_by' => get_session_userid(),'client_branch_id' => $params['client_branch_id']];
@@ -1613,6 +1622,7 @@ class EmployeeServiceController extends AdminController
                                     $value['emp_status'] = 'active';
                                     $value['created_by'] = $file['created_by'];
                                     $value['client_branch_id'] = $file['client_branch_id'];
+                                    $value['family_floater_key'] = generate_family_floater_key($value['relationship']);
                                     $log_message = 'Insert Employee- '.$value['name'] .'('.$value['emp_code'] .') with PK ';
                                     // $this->myLogger->logme('error',('Insert - ' .  $value['emp_code'] .' - '. $value['name']));
                                     // echo 'update emp';
@@ -1983,7 +1993,7 @@ public function employeesEnrollmentInsert($params)
             $value['file_id'] = $file_id;
 
             $value['temp']['emp_id'] = null; // dummy value for using exisitng funciton in model
-            if (strtolower(trim($value['relationship'])) === 'mother' || strtolower(trim($value['relationship'])) === 'Father') {
+            if (strtolower(trim($value['relationship'])) === 'mother' || strtolower(trim($value['relationship'])) === 'father') {
                         $relation = 'parent';
                     } else if(strtolower(trim($value['relationship'])) === 'son' || strtolower(trim($value['relationship'])) === 'daughter'){
                         $relation = 'child';
@@ -1997,6 +2007,7 @@ public function employeesEnrollmentInsert($params)
                     $value['family_floater_key'] = $relation;
 
                     $policy_data['basic_cover_si'] = $row[9];
+                    $policy_data['date_coverage'] = $row[13];
                     $policy_data['client_policy_id'] = $file['policy_id'];
 
                      $employee = $this->employeeModel->checkExistingEmployee($value,$file['client_branch_id']);
diff --git a/app/Controllers/Jobs.php b/app/Controllers/Jobs.php
index 56855efd..ad10f86d 100755
--- a/app/Controllers/Jobs.php
+++ b/app/Controllers/Jobs.php
@@ -49,7 +49,7 @@ class Jobs extends AdminController
             }
 
            $uuid = generate_uuid();
-           $jobid =  $jobModel->insert(['name' => $payload['job_name'],'uuid' => $uuid,'payload' => json_encode($payload['payload'])]);
+           $jobid =  $jobModel->insert(['name' => $payload['job_name'],'uuid' => $uuid,'payload' => json_encode($payload['payload']), 'status' => isset($payload['status']) ? $payload['status'] : 'queued']);
            // echo $jobid;
            $myLogger->logme('error','new job {jobid} added to queue',['jobid' => $jobid]);
            return ['id' => $jobid,'uuid' => $uuid,'job_name' => $payload['job_name']];
diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php
index 9c9d153f..9d2c246c 100644
--- a/app/Controllers/LeadsController.php
+++ b/app/Controllers/LeadsController.php
@@ -4,6 +4,9 @@ namespace App\Controllers;
 
 use CodeIgniter\API\ResponseTrait;
 
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+
 use App\Models\UserModel;
 use App\Models\ClientModel;
 use App\Models\ClientBranchModel;
@@ -15,6 +18,12 @@ use App\Models\KYCEntityTypeModel;
 use App\Models\PolicyTransactionStatusModel;
 use App\Models\InsurerBranchModel;
 use App\Models\TPABranchModel;
+use App\Models\RFQModel;
+use App\Models\InsurerModel;
+
+use App\Helpers\MailHelper;
+use Kint;
+
 
 class LeadsController extends BaseController
 {   
@@ -35,6 +44,8 @@ class LeadsController extends BaseController
     protected $policyTransactionStatusModel;
     protected $insurerBranchModel;
     protected $tpaBranchModel;
+    protected $RFQModel;
+    protected $insurerModel;
 
     //variables for storing array
     protected $issuer;
@@ -58,6 +69,8 @@ class LeadsController extends BaseController
         $this->policyTransactionStatusModel = new PolicyTransactionStatusModel();
         $this->insurerBranchModel = new InsurerBranchModel();
         $this->tpaBranchModel = new TPABranchModel();
+        $this->RFQModel  = new RFQModel();
+        $this->insurerModel  = new InsurerModel();
 
         $this->issuer  = [1 => 'JIBS', 2 => 'Nhance'];
         $this->clientType  = [1 => 'Group', 2 => 'Individual'];
@@ -202,6 +215,7 @@ class LeadsController extends BaseController
                 'branch_code'            => $data['branch_code'],
                 'contact_person_name'    => $data['contact_person_name'],
                 'contact_person_mobile'  => $data['contact_person_mobile'],
+                'contact_person_email'   => $data['contact_person_email'],
                 'client_id'              => $data['client_id'] ?? 0,
                 'client_branch_id'       => $data['client_branch_id'] ?? 0,
                 'source_policy_id'       => $data['source_policy_id'] ?? 0,
@@ -296,4 +310,514 @@ class LeadsController extends BaseController
     }
 
 
+    //--------RFQ-----------------------------------------------------------------------------------------------
+
+
+    public function viewRFQ($id, $type = 1){
+
+        $data['rfq_data'] = $this->RFQModel
+                ->where('lead_id', $id)
+                ->where('type', $type)
+                ->where('is_active', 1)
+                ->first();
+
+        $data['rfq_count'] = $this->RFQModel
+                ->where('lead_id', $id)
+                ->where('type', 1)
+                ->where('is_active', 1)
+                ->countAllResults();
+
+        $data['qcr_count'] = $this->RFQModel
+                ->where('lead_id', $id)
+                ->where('type', 2)
+                ->where('is_active', 1)
+                ->countAllResults();
+
+        // dd(count($data['rfq_data']));
+
+        $data['lead_id'] = $id;
+        $lead_data = $this->leadsModel
+                ->select('policy_type.question_json')
+                ->join('policy_type', 'leads.policy_type_id = policy_type.id')
+                ->where('leads.id', $id)
+                ->first();
+
+        $data['question_json'] = $lead_data['question_json'];
+        $data['page_name'] = isset($data['rfq_data']['type']) && $data['rfq_data']['type'] == 2 ? 'QCR' : 'RFQ';
+        $data['insurer'] = $this->insurerBranchModel->getInsurerBranchesWithInsurerNames();
+
+        $data['lead_data'] = $this->leadsModel->where('leads.id', $id)->where('leads.is_active', 1)->first();
+        // dd($data);
+        $this->loadLayout('view_rfq.php', $data);
+    }
+
+    public function createRFQ(){
+
+        $data = $this->request->getPost();
+        $lead_id = $data['lead_id'];
+        $data['type'] = 1;
+        $this->RFQModel
+            ->where('lead_id', $lead_id)
+            ->where('type', 1)
+            ->where('is_active', 1)
+            ->set('is_active', 0)
+            ->update();
+
+        $result = $this->RFQModel->insert($data);
+
+        if ($result) {
+            return $this->respond(['status' => true, 'id' => $result, 'message' => 'New RFQ created successfully', 'data' =>$data], 200);
+        }
+
+        return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create RFQ", 'data' =>$data], 200);
+
+    }
+
+    public function createQCR(){
+
+        $data = $this->request->getPost();
+        $lead_id = $data['lead_id'];
+        $data['type'] = 2;
+
+        $this->RFQModel
+            ->where('lead_id', $lead_id)
+            ->where('type', 2)
+            ->where('is_active', 1)
+            ->set('is_active', 0)
+            ->update();
+
+        $result = $this->RFQModel->insert($data);
+
+        if ($result) {
+            return $this->respond(['status' => true, 'id' => $result, 'message' => 'New QCR created successfully', 'data' =>$data], 200);
+        }
+
+        return $this->respond(['status' => false, 'id' => $result, 'message' => "Failed to create QCR", 'data' =>$data], 200);
+    }
+
+
+    //-----RFQ and QCR EXPORT------------------------------------------------------------------------------------------------
+
+
+    //export main route function
+    public function exportQCRandRFQ($lead_id, $type, $export_type){
+
+        if($export_type == 'mail'){
+            $this-> exportMailForQCRandRFQ($lead_id, $type);
+        }else{
+            $this-> exportExcelForQCRandRFQ($lead_id, $type);
+        }
+    }
+
+    //FOR EXCEL
+    public function exportExcelForQCRandRFQ($lead_id, $type)
+    {
+        $filepath = $this->constructExcelToSaveTemp($lead_id, $type);
+        $filepath = $filepath['filePath'];
+    
+        if (file_exists($filepath)) {
+            // Set headers to force download
+            header('Content-Description: File Transfer');
+            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
+            header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
+            header('Content-Length: ' . filesize($filepath));
+            header('Pragma: public');
+            
+            // Output the file content
+            readfile($filepath);
+            
+            // Delete the file after download
+            unlink($filepath);
+            
+            exit;
+        } else {
+            echo "File does not exist.";
+        }
+    }
+    
+    //FOR MAIL
+    public function exportMailForQCRandRFQ($lead_id, $type){
+
+        $filepath = $this->constructExcelToSaveTemp($lead_id, $type);
+
+        if ($filepath) {
+            return $this->respond(['status' => true, 'file_path' => $filepath, 'message' => 'Mail send successfully'], 200);
+        }
+
+        return $this->respond(['status' => false, 'file_path' => $filepath, 'message' => "Mail send failed"], 200);
+    }
+
+    //Construct excel file and save the file to the folder and return file path
+    public function constructExcelToSaveTemp($lead_id, $type)
+    {
+        $rfq_data = $this->RFQModel
+            ->select('
+                    leads.client_name,
+                    leads.client_short_name,
+                    insurers.name as insurer_name,
+                    insurer_branch.branch_name as insurer_branch_name,
+                    tpa.name as tpa_name,
+                    tpa_branch.branch_name as tpa_branch_name,
+                    policy_type.policy_type,
+                    rfq.json
+            ')
+            ->join('leads', 'rfq.lead_id = leads.id')
+            ->join('policy_type', 'leads.policy_type_id = policy_type.id')
+            ->join('insurers', 'leads.insurer_id = insurers.id')
+            ->join('insurer_branch', 'leads.insurer_branch_id = insurer_branch.id')
+            ->join('tpa', 'leads.tpa_id = tpa.id')
+            ->join('tpa_branch', 'leads.tpa_branch_id = tpa_branch.id')
+            ->where('rfq.lead_id', $lead_id)
+            ->where('rfq.type', $type)
+            ->where('rfq.is_active', 1)
+            ->first();
+    
+        $lead_data = [
+            'Insured' => $rfq_data['client_name'],
+            'Insurer' => $rfq_data['insurer_name'] . ' - ' . $rfq_data['insurer_branch_name'],
+            'TPA' => $rfq_data['tpa_name'] . ' - ' . $rfq_data['tpa_branch_name'],
+        ];
+    
+        $jsonData = $rfq_data['json'];
+        $data = json_decode($jsonData, true);
+    
+        // Initialize PhpSpreadsheet
+        $spreadsheet = new Spreadsheet();
+        $sheet = $spreadsheet->getActiveSheet();
+    
+        // Start with lead_data at the top
+        $rowNumber = 1;
+        foreach ($lead_data as $key => $value) {
+            $sheet->setCellValue("A{$rowNumber}", $key);
+            $sheet->setCellValue("B{$rowNumber}", $value);
+
+            // Apply bold style to the key
+            $sheet->getStyle("A{$rowNumber}")->applyFromArray([
+                'font' => [
+                    'bold' => true,
+                ],
+            ]);
+
+            $rowNumber++;
+        }
+
+        // Leave two blank rows
+        $rowNumber += 2;
+
+        // Set headers and subheaders starting from current row
+        $headers = $data['table_data']['headers'];
+        $subHeaderRow = $rowNumber + 1;
+        $columnLetter = 'A';
+
+        // Set column width and apply word wrap to headers and subheaders
+        foreach ($headers as $header) {
+            if ($header['parentHeader'] === 'Item Key' || $header['parentHeader'] == 'Action') {
+                continue; // Skip "Item Key" and "Action" columns
+            }
+
+            if ($header['parentHeader'] === 'Sno') {
+                $header['parentHeader'] = 'S.No.';
+            }
+
+            // Set the header cell value
+            $sheet->setCellValue("{$columnLetter}{$rowNumber}", $header['parentHeader']);
+            
+            // Set column width for header
+            $sheet->getColumnDimension($columnLetter)->setWidth(20); // Adjust width as needed
+            $sheet->getStyle("{$columnLetter}{$rowNumber}")->getAlignment()->setWrapText(true);
+
+            // Apply bold style to the header
+            $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray([
+                'font' => [
+                    'bold' => true,
+                ],
+            ]);
+            
+            // Add subheaders in the second row
+            foreach ($header['subHeaders'] as $subHeader) {
+                $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader);
+
+                // Enable word wrap for subheaders
+                $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->getAlignment()->setWrapText(true);
+
+                // Apply bold style to the subheader
+                $sheet->getStyle("{$columnLetter}{$subHeaderRow}")->applyFromArray([
+                    'font' => [
+                        'bold' => true,
+                    ],
+                ]);
+
+                $columnLetter++;
+            }
+        }
+
+        // Move to next row for data entries
+        $rowNumber = $subHeaderRow + 1;
+
+        // Add data rows and enable word wrap for data cells
+        foreach ($data['table_data']['data'] as $dataRow) {
+            $columnLetter = 'A';
+            foreach ($dataRow['data'] as $cellData) {
+                if ($cellData['parentth'] === 'Item Key' || $cellData['parentth'] == 'Action') {
+                    continue; // Skip "Item Key" data
+                }
+                $sheet->setCellValue("{$columnLetter}{$rowNumber}", $cellData['value']);
+                
+                // Enable word wrap for data cells
+                $sheet->getStyle("{$columnLetter}{$rowNumber}")->getAlignment()->setWrapText(true);
+                
+                $columnLetter++;
+            }
+            $rowNumber++;
+        }
+
+        // Auto-size all columns after data is entered
+        foreach ($sheet->getColumnIterator() as $column) {
+            $sheet->getColumnDimension($column->getColumnIndex())->setAutoSize(true);
+        }
+
+        // Set filename based on type
+        $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->save($uploadFilePath);
+    
+        return [
+            'filePath' => $uploadFilePath,
+            'fileName' => $filename,
+        ]; // Return file path and file name
+    }
+    
+    //this funciton for send mail to insurer and client with either RFQ/QCR
+    public function sendMailWithAttachement()
+    {
+         helper('excel_util_helper');
+         helper('MailHelper');
+
+         $params = $this->request->getGet();
+         // dd($params);
+         $lead_id = $params['lead_id'];
+         $file_type  = $params['file_type']; //rfq or qcr
+         $recipient_type = $params['recipient_type'];//insurer or client  
+         $recipient_mail = $params['recipient_mail'];// - only primary key of contacts
+         $recipient_mail = json_decode($params['recipient_mail'], true);;// - only primary key of contacts
+        //  $cc = 'velz1990@gmail.com,vitvelz@gmail.com';
+        $cc = "";
+         
+         $result_data = []; 
+         // dd($recipient_mail);
+         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();
+         //gather lead info
+         $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')
+                ->join('user_profiles','leads.created_by = user_profiles.id')
+                ->where('leads.id', $lead_id)
+                ->first();
+         if( $recipient_type == 'client' && ($lead_data['contact_person_email'] == '' || $lead_data['contact_person_email'] == null))
+         {
+            return $this->respond(['status' => 'failed','code' => 400,'data' => '','messgae' => 'Recipient mail not found ! ' ], 200);
+         }
+         // dd($lead_data);
+         $reply_to = $lead_data['created_person_email'];
+         //get file path to attach
+         $file_info = $this->constructExcelToSaveTemp($lead_id, ( $file_type == 'rfq' ? 1 : 2) );
+         // $file_path = WRITEPATH."uploads/excel/sample/correction.xls";
+         // $file_name = $file_type.'.xlsx';
+         // !dd($file_info);
+         $file_path = $file_info['filePath'];
+         $file_name = $file_info['fileName'];
+         $attachments = [['fileName' => $file_name,'filePath' => $file_path]];
+         
+         //get recipient address
+         if($recipient_type == 'insurer')
+         {
+                $recipient_data = $this->levelContactModel
+                                ->where(['contact_type' => $recipient_type, 'is_active' => 1])
+                                ->whereIn('id', $recipient_mail)
+                                ->findAll();
+         }
+         else
+         {
+            $recipient_data = [['name' => $lead_data['contact_person_name'],'email' => $lead_data['contact_person_email']] ];
+         }
+         // !dd($recipient_data);
+
+            $subject = $file_type == 'rfq' ? 'Request for Quotation from '. $lead_data['client_name'] . ' for '.$lead_data['policy_type'] : 'Quotation Comparison Report for ' .$lead_data['policy_type'];
+            $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.

'; + + + foreach($recipient_data as $recipient) + { + $message = $original_message; + $message = str_replace("{{RECIPIENT_NAME}}", $recipient['name'], $message); + $message = str_replace("{{CLIENT_NAME}}", $lead_data['client_name'], $message); + $message = str_replace("{{POLICY_LONG_NAME}}", $lead_data['long_name'], $message); + $message = str_replace("{{POLICY_START_DATE}}", change_date_format($lead_data['policy_start_date'],'Y-m-d','d-m-Y'), $message); + $message = str_replace("{{DURATION}}", calculate_days_bw_dates($lead_data['policy_end_date'],$lead_data['policy_start_date'])->days, $message); + + // print_rr($message); + + $res = MailHelper::send_email(['mail' => $recipient['email'], 'subject' => $subject, 'message' => $message,'attachments' => $attachments,'reply_to' => $reply_to]); + // !dd($res); + + $result_data[] = ['mail' => $recipient['email'],'status' => $res]; + } + //delete attachment file + unlink($file_path); + return $this->respond(['status' => 'success','code' => 200,'data' => $result_data ], 200); + + } + + public function getLevelContects() + { + + $data = $this->levelContactModel->getContectForRFQ(); + + if($data){ + return $this->respond(['status' => true, 'data' => $data], 200); + }else{ + return $this->respond(['status' => false], 200); + } + + } + + + //----- Featch Lead data and insert Client ------------------------------------------------------------------------------------------- + + + + public function featchLeadDataAndInsertClient($lead_id) + { + $data = $this->leadsModel->where('leads.id', $lead_id)->where('leads.is_active', 1)->first(); + + if (!$data) { + return $this->respond(['status' => false, 'message' => 'Failed to create Client', 'data' => null], 200); + } + + $result = $this->createClientWithLeadData($data); + + if ($result) { + return $this->respond(['status' => true, 'message' => 'New Client created successfully', 'client_id' => $result, 'data' => $data], 200); + } + + return $this->respond(['status' => false, 'message' => 'Failed to create client', 'data' => $data], 200); + } + + public function createClientWithLeadData($data) + { + $client_data = $this->prepareClientData($data); + $client_id = $this->clientModel->insert($client_data); + + if ($client_id) { + $this->createClientBranchAndContactWithLeadData($data, $client_id); + } + + return $client_id; + } + + private function prepareClientData($data) + { + return [ + 'client_type' => $data['client_type'], + 'entity_type_id' => $data['entity_type_id'], + 'client_code' => $data['client_code'], + 'client_name' => $data['client_name'], + 'short_name' => $data['client_short_name'], + 'pan' => $data['pan'], + ]; + } + + public function createClientBranchAndContactWithLeadData($data, $client_id) + { + $branch_data = $this->prepareClientBranchData($data, $client_id); + $branch_id = $this->clientBranchModel->insert($branch_data); + + if ($branch_id) { + + $contact_data = $this->prepareContactData($data, $branch_id); + $this->levelContactModel->insert($contact_data); + + $this->createClientPolicyWithLeadData($data, $client_id, $branch_id); + } + + return $branch_id; + } + + + private function prepareClientBranchData($data, $client_id) + { + $default_unit = trim(($data['client_short_name'] ?? '') . '-' . ($data['branch_code'] ?? ''), '-'); + + return [ + 'client_id' => $client_id, + 'branch_name' => $data['branch_name'], + 'branch_code' => $data['branch_code'], + 'gst' => $data['gst'], + 'units' => json_encode([$default_unit]), + ]; + } + + private function prepareContactData($data, $branch_id) + { + return [ + 'name' => $data['contact_person_name'], + 'mobile' => $data['contact_person_mobile'], + 'email' => $data['contact_person_email'], + 'contact_type' => 'client', + 'ref_id' => $branch_id, + ]; + } + + public function createClientPolicyWithLeadData($data, $client_id, $branch_id) + { + $client_policy_data = $this->prepareClientPolicyData($data, $client_id, $branch_id); + return $this->clientPolicyModel->insert($client_policy_data); + } + + private function prepareClientPolicyData($data, $client_id, $branch_id) + { + $client_policy_data = [ + 'client_id' => $client_id, + 'client_branch_id' => $branch_id, + 'policy_type_id' => $data['policy_type_id'], + 'insurer_id' => $data['insurer_id'], + 'insurer_branch_id' => $data['insurer_branch_id'], + 'tpa_id' => $data['tpa_id'], + 'tpa_branch_id' => $data['tpa_branch_id'], + 'policy_start_date' => $data['policy_start_date'], + 'policy_end_date' => $data['policy_end_date'], + 'policy_status' => 1, + ]; + + $policy_type_id = $data['policy_type_id']; + if (in_array($policy_type_id, [1, 2, 6, 7])) { + $client_policy_data['is_addon'] = 1; // Base Policy + } elseif (in_array($policy_type_id, [4, 5])) { + $client_policy_data['is_addon'] = 2; // SI TOPUP + } elseif ($policy_type_id == 3) { + // if ($base_policy) { + // $data['is_addon'] = 3; // Dependent Addon + // } else { + $data['is_addon'] = 1; + // } + } + + return $client_policy_data; + } + + private function preparePolicyTermsFromRFQ($data) + { + + } + + + } diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 691234eb..13305f50 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -34,6 +34,8 @@ use App\Models\InsurerExcelExportTemplateModel; use App\Models\SettingsModel; use App\Models\VehicleModel; +use CodeIgniter\CLI\CLI; + class MasterController extends AdminController { use ResponseTrait; @@ -1603,13 +1605,42 @@ class MasterController extends AdminController //testing a sample mail from cli public function testGmailAPIViaCLI(string $email_id = 'velmurugan.s@venbainfotech.com') { + + $email_id = CLI::getOption('to') ? CLI::getOption('to') : $email_id; // print_r($email_id);die(); // $gmailapi = \Config\Services::gmailapi(); - $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => 'This is sample mail sent via CLI mode']); + $message = ''; + + // $attachments = [ + // ["filePath" => WRITEPATH."uploads/excel/sample/correction.xls","fileName" => "correction.xls"], + // ["filePath" => WRITEPATH."uploads/excel/sample/deletion.xls","fileName" => "deletion.xls"], + // ["filePath" => "C:\\Users\\Venba\\Desktop\\IQ.pdf","fileName" => "Questions.pdf"], + // ["filePath" => "C:\\Users\\Venba\\Desktop\\config_age.png","fileName" => "config_age.png"] + // ]; + + $attachments = [ + ["filePath" => ROOTPATH."public/sample_excel/sample_addition.xls","fileName" => "sample_addition.xls"], + ["filePath" => ROOTPATH."public/sample_excel/sample_inception.xls","fileName" => "sample_inception.xls"], + ["filePath" => ROOTPATH."public/assets/images/login_bg.jpg","fileName" => "login_bg.jpg"] + ]; + + + $email_id = CLI::getOption('to') ? CLI::getOption('to') : $email_id; + $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => $message,'attachments' => $attachments]); print_r($res); } - + + public function testCheckBounceMails() + { + $gmailapi = \Config\Services::gmailapi(); + $from_date = CLI::getOption('from') ? CLI::getOption('from') : null; + $to_date = CLI::getOption('to') ? CLI::getOption('to') : null; + $count = CLI::getOption('count') ? CLI::getOption('count') : null; + $page = CLI::getOption('page') ? CLI::getOption('page') : null; + $res = $gmailapi->checkBounceStatus(from_date:$from_date,to_date:$to_date,count:$count,page:$page); + print_r($res); + } public function appCheckList() { @@ -1638,7 +1669,9 @@ class MasterController extends AdminController 'uploads' => ROOTPATH . 'public/uploads', 'add_image_upload' => ROOTPATH . 'public/uploads/add_image_upload/',//adverdisement images for enrollment app 'logo' => ROOTPATH . 'public/uploads/logo/', - 'template_bg' => ROOTPATH . 'public/uploads/template_bg/' + 'template_bg' => ROOTPATH . 'public/uploads/template_bg/', + 'attachments' => WRITEPATH . 'uploads/attachments/', + ]; foreach ($folders as $folderName => $folderPath) { @@ -1672,7 +1705,7 @@ class MasterController extends AdminController echo "Check the following..!\n"; echo "1. Update Gmail Oauth credentials in 'gmail_api_oauth_credentials' field in 'settings' table in JSON format.\n"; echo "2. Call this cli route to generate new access token: 'php public/index.php cli/new_gmail_token' from root of the project.\n"; - echo "3. Call this cli route : 'php public/index.php cli/send_mail_cli someone@gmail.com' to send test mail to testGmailAPIViaCLI ( replace someone@gmail.com with real time mail).\n"; + echo "3. Call this cli route : 'php public/index.php cli/send_mail_cli --to someone@gmail.com' to send test mail to testGmailAPIViaCLI ( replace someone@gmail.com with real time mail).\n"; } else { diff --git a/app/Controllers/NotificationController.php b/app/Controllers/NotificationController.php index ff666cef..a3c8efe9 100755 --- a/app/Controllers/NotificationController.php +++ b/app/Controllers/NotificationController.php @@ -16,6 +16,7 @@ use App\Models\NotificationModel; use App\Models\ClientModel; use App\Models\EmployeeModel; use App\Models\UserModel; +use App\Models\MailAttachmentModel; use App\Helpers\sendMailNotification; use App\Helpers\MailHelper; @@ -26,12 +27,14 @@ class NotificationController extends AdminController protected $myLogger; protected $notificationModel; protected $clientModel; + protected $MailAttachmentModel; public function __construct() { $this->myLogger = \Config\Services::mylogger(); $this->notificationModel = new NotificationModel(); $this->clientModel = new ClientModel(); + $this->MailAttachmentModel = new MailAttachmentModel(); } // This is for Template Name Camel Case to Snake Case for store in DB @@ -52,16 +55,21 @@ class NotificationController extends AdminController $notificationModel = new NotificationModel(); $find_notification = $notificationModel->where('client_id',$form_data['client_id'])->where('template_name',$form_data['template_name'])->first(); + if ($find_notification) { + $id = $find_notification['id']; $form_data['updated_by'] = get_session_userid(); $notificationModel->update($id,$form_data); $complete = "Update"; + }else{ + $form_data['created_by'] = get_session_userid(); $notificationModel->insert($form_data); $complete = "Inserted"; } + return json_encode($complete); } @@ -111,8 +119,11 @@ class NotificationController extends AdminController public function getMailTemplateData($template_name,$client_id) { $notificationModel = new NotificationModel(); - $value = $notificationModel->where('client_id',$client_id)->where('template_name',$template_name)->first(); + if($value){ + $value['data'] = $this->MailAttachmentModel->where('notification_id', $value['id'])->where('is_active', 1)->findAll(); + } + // return $this->respond(['status' => true, 'code' => 200, '' => 'Attachment deleted successfully'], 200); return json_encode($value); } @@ -198,4 +209,74 @@ class NotificationController extends AdminController } } + + public function insertAttachmentsForMailTemplates() + { + $form_data = $this->request->getPost(); + + // Check if client_id and template_name are provided + if (empty($form_data['client_id']) || empty($form_data['template_name'])) { + return $this->respond(['status' => false, 'code' => 400, 'message' => 'Client ID and template name are required.'], 400); + } + + // Attempt to find the notification + $find_notification = $this->notificationModel->where('client_id', $form_data['client_id']) + ->where('template_name', $form_data['template_name']) + ->first(); + + if (!$find_notification) { + return $this->respond(['status' => false, 'code' => 404, 'message' => 'Notification data not found.'], 404); + } + + // Define upload path and attempt file upload + $uploadFilePath = WRITEPATH . 'uploads/attachments'; + $uploadedFile = $this->request->getFile('file'); + $fileName = file_Upload($uploadedFile, $uploadFilePath); // Assume file_Upload handles file saving + + if ($fileName) { + // Prepare data for insertion + $data = [ + 'notification_id' => $find_notification['id'], + 'file_name' => $fileName, + 'file_path' => 'uploads/attachments/' . $fileName, + ]; + + + // Insert file attachment record + if ($this->MailAttachmentModel->insert($data)) { + // Retrieve active attachments to return in response + $attachment_data = $this->MailAttachmentModel->where('is_active', 1)->findAll(); + return $this->respond([ + 'status' => true, + 'code' => 200, + 'data' => $attachment_data, + 'message' => 'File uploaded successfully' + ], 200); + } else { + return $this->respond(['status' => false, 'code' => 500, 'message' => 'Failed to save file attachment data.'], 500); + } + } else { + return $this->respond(['status' => false, 'code' => 400, 'message' => 'File upload failed.'], 400); + } + } + + public function removeAttachmentsForMailTemplates($id, $client_id, $template_name) + { + $attachment_data_for_unlink_file = $this->MailAttachmentModel->where('id', $id)->first(); + $file_path = WRITEPATH . $attachment_data_for_unlink_file['file_path']; + + if ($this->MailAttachmentModel->where('id', $id)->delete()) { + + unlink($file_path); + + $find_notification = $this->notificationModel->where('client_id', $client_id)->where('template_name', $template_name)->first(); + $attachmentDatas = $this->MailAttachmentModel->where('notification_id', $find_notification['id'])->where('is_active', 1)->findAll(); + + return $this->respond(['status' => true, 'code' => 200, 'message' => 'Attachment deleted successfully', 'data' => $attachmentDatas], 200); + + } else { + return $this->respond(['status' => false, 'code' => 404, 'message' => 'The Client has active policy'], 200); + } + } + } \ No newline at end of file diff --git a/app/Helpers/MailHelper.php b/app/Helpers/MailHelper.php index f94d6419..a65a5b31 100755 --- a/app/Helpers/MailHelper.php +++ b/app/Helpers/MailHelper.php @@ -93,7 +93,8 @@ class MailHelper $emaill = $params['mail']; $subject = $params['subject']; $message = $params['message']; - + $attachments = isset($params['attachments']) && count($params['attachments']) ? $params['attachments'] : []; + //check BCC mail if (isset($params['bcc'])) { $bcc = $params['bcc']; @@ -118,7 +119,7 @@ class MailHelper try { - $res = $gmailapi->sendMessage($emaill, $subject, $message, 'no-reply@nhanceindia.in', $reply_to, $cc, $bcc); + $res = $gmailapi->sendMessage($emaill, $subject, $message, 'no-reply@nhanceindia.in', $reply_to, $cc, $bcc,$attachments); if($res['status']) { diff --git a/app/Helpers/excel_import_export_helper.php b/app/Helpers/excel_import_export_helper.php index b7eb87c8..3355253e 100755 --- a/app/Helpers/excel_import_export_helper.php +++ b/app/Helpers/excel_import_export_helper.php @@ -972,3 +972,39 @@ if(!function_exists('query_construct_second_stage')){ } } +if (!function_exists('generateExcelWithHeader')) { + /** + * Generate an Excel file with the specified headers + * + * @param array $header The header row for the Excel file + * @param string $filename The name of the Excel file to be created + * @return string Path to the generated Excel file + */ + function generateExcelWithHeader(array $header, string $filename = 'InceptionHeader.xlsx') + { + // Create a new Spreadsheet + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + + // Set header row + $column = 'A'; + foreach ($header as $headerText) { + $sheet->setCellValue($column . '1', $headerText); + $column++; + } + + // // Style the header row (optional) + // $sheet->getStyle('A1:' . $column . '1')->getFont()->setBold(true); + // $sheet->getStyle('A1:' . $column . '1')->getAlignment()->setHorizontal('center'); + + // Define the file path + $filePath = WRITEPATH . 'uploads/' . $filename; // WRITEPATH is typically for writable directories + + // Save the file + $writer = new Xlsx($spreadsheet); + $writer->save($filePath); + + return $filePath; + } +} + diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index 6de54c74..ab6299ac 100755 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -1646,7 +1646,7 @@ if(!function_exists('get_premium_for_si')) // dd($slab_details); foreach ($slab_details as $skey => $slab_value) { - if($slab_value['si'] == $si_amount && $slab_value['grade'] == $band && $slab_value['unit'] == $unit && $slab_value['max_si'] == 0) + if($slab_value['si'] == $si_amount && $slab_value['grade'] == $band && $slab_value['unit'] == $unit) { return $slab_value['premium']; } @@ -1800,7 +1800,7 @@ if(!function_exists('transform_enrollment_row_to_inception_row')) $res[4] = $row[4]; // inception: gender (Gender) -> enrollment: gender (Gender) $res[5] = $row[5]; // inception: relationship (RELATIONSHIP) -> enrollment: relationship (Relation) $res[6] = $row[9]; // inception: basic_cover_si (BASIC COVER SI) -> enrollment: basic_cover_si (SI) - $res[7] = null; // inception: doc (Date of Coverage) -> No match in enrollment + $res[7] = $row[13]; // inception: doc (Date of Coverage) -> No match in enrollment $res[8] = $row[3]; // inception: doj (DOJ) -> enrollment: doj (DOJ) $res[9] = $row[11]; // inception: basic_pay (Basic Pay) -> enrollment: basic_pay (Basic Pay) $res[10] = $row[10]; // inception: band_grade (Band/Grade) -> enrollment: band_grade (Grade) @@ -2119,4 +2119,24 @@ if(!function_exists('group_slab_rates_basedon_name')) return $temp_slab_rates; } +} + + +//this key generating mandantory for display employee info in enrolment app w/o error +if(!function_exists('generate_family_floater_key')) +{ + function generate_family_floater_key($relationship) + { + if (strtolower(trim($relationship)) === 'mother' || strtolower(trim($relationship)) === 'father') { + $relation = 'parent'; + } else if(strtolower(trim($relationship)) === 'son' || strtolower(trim($relationship)) === 'daughter'){ + $relation = 'child'; + }else if(strtolower(trim($relationship)) === 'father in Law' || strtolower(trim($relationship)) === 'mother in Law'){ + $relation = 'parent_in_law'; + }else if(strtolower(trim($relationship)) === 'spouse'){ + $relation = 'spouse'; + }else{ + $relation = 'self'; + } + } } \ No newline at end of file diff --git a/app/Helpers/sendMailNotification.php b/app/Helpers/sendMailNotification.php index 6a729c56..31114293 100755 --- a/app/Helpers/sendMailNotification.php +++ b/app/Helpers/sendMailNotification.php @@ -10,6 +10,7 @@ use App\Models\UserModel; use App\Models\EmployeeModel; use App\Models\PolicyPremium1Model; use App\Models\PolicyPremium2Model; +use App\Models\MailAttachmentModel; class sendMailNotification { @@ -22,6 +23,21 @@ class sendMailNotification $notification = $params['notification']; $client_data = $params['client_data']; + $mailAttachmentModel = new MailAttachmentModel(); + $attachment_data = $mailAttachmentModel + ->select('file_path, file_name') + ->where('notification_id', $notification['id']) + ->where('is_active', 1) + ->findAll(); + + $attachments = []; + foreach ($attachment_data as $data) { + $attachments[] = [ + "filePath" => WRITEPATH . $data['file_path'], + "fileName" => $data['file_name'] + ]; + } + $mail = $dataToInsert['email_corporate']; $subject = $notification['subject']; $app_link = $_ENV['App_Url']; @@ -37,7 +53,7 @@ class sendMailNotification $mail_content = str_replace("[[app_link]]", "Review Details", $mail_content); if ($dataToInsert['relationship'] == 'Self' && $mail != null || $mail != '') { - $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']]; + $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments]; } return $wholeData; @@ -799,7 +815,24 @@ class sendMailNotification $mail = $params['test_mail']; $mail_content = $notification['mail_content']; - $subject = $notification['subject']; + $subject = $notification['subject']; + + $mailAttachmentModel = new MailAttachmentModel(); + $attachment_data = $mailAttachmentModel + ->select('file_path, file_name') + ->where('notification_id', $notification['id']) + ->where('is_active', 1) + ->findAll(); + + $attachments = []; + foreach ($attachment_data as $data) { + $attachments[] = [ + "filePath" => WRITEPATH . $data['file_path'], + "fileName" => $data['file_name'] + ]; + } + + // print_r($attachments); die; $employee_name = 'John Doe'; @@ -816,7 +849,7 @@ class sendMailNotification $mail_content = str_replace("[[app_link]]", "Review Details", $mail_content); if ($mail != null || $mail != '') { - $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to']]; + $wholeData = ['mail' => $mail, 'subject' => $subject,'message'=> $mail_content,'bcc'=> $client_data['common_mails'], 'reply_to' => $client_data['reply_to'], 'attachments' => $attachments]; } return $wholeData; diff --git a/app/Libraries/GmailAPI.php b/app/Libraries/GmailAPI.php index f08a832e..e74101d4 100755 --- a/app/Libraries/GmailAPI.php +++ b/app/Libraries/GmailAPI.php @@ -26,18 +26,20 @@ class GmailAPI 'https://www.googleapis.com/auth/gmail.addons.current.message.readonly', 'https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.labels', - 'https://www.googleapis.com/auth/gmail.send' + 'https://www.googleapis.com/auth/gmail.send', + 'https://mail.google.com/' ]); $this->setAuthConfig(); //die(); $this->client->setAccessType('offline'); $this->client->setPrompt('select_account consent'); - - if (php_sapi_name() !== 'cli' || (uri_string() == 'cli/send_mail_cli' || uri_string() == 'cli/processjob') ) + // echo uri_string();//die(); + if (php_sapi_name() !== 'cli' || (uri_string() == 'cli/send_mail_cli' || uri_string() == 'cli/processjob' || uri_string() == 'cli/check_bounce_mail_cli') ) { + // echo 'getting token';die(); $this->setTokenFromDB(); // Call only if not in CLI } - + // die(); $this->service = new Gmail($this->client); } @@ -99,44 +101,73 @@ class GmailAPI $settingsModel->where('id', 1)->set([$this->tokenField => $token])->update(); } - public function createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = []) - { - $boundary = uniqid(rand(), true); + public function createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = [], $attachments = []) +{ + // print_r($to);die(); + $boundary = uniqid(rand(), true); // Unique boundary for separating parts - $rawMessageString = "From: $from\r\n"; - $rawMessageString .= "To: $to\r\n"; - $rawMessageString .= "Reply-To: $replyTo\r\n"; + // Initialize raw message headers + $rawMessageString = "From: $from\r\n"; + $rawMessageString .= "To: $to\r\n"; + $rawMessageString .= "Reply-To: $replyTo\r\n"; - if (!empty($cc)) { - $rawMessageString .= "Cc: " . implode(',', $cc) . "\r\n"; - } - - if (!empty($bcc)) { - $rawMessageString .= "Bcc: " . implode(',', $bcc) . "\r\n"; - } - - $rawMessageString .= "Subject: $subject\r\n"; - $rawMessageString .= "MIME-Version: 1.0\r\n"; - $rawMessageString .= "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n\r\n"; - $rawMessageString .= "--$boundary\r\n"; - $rawMessageString .= "Content-Type: text/html; charset=UTF-8\r\n"; - $rawMessageString .= "Content-Transfer-Encoding: 7bit\r\n\r\n"; - $rawMessageString .= $htmlContent . "\r\n"; - $rawMessageString .= "--$boundary--"; - - $rawMessage = base64_encode($rawMessageString); - $rawMessage = str_replace(['+', '/', '='], ['-', '_', ''], $rawMessage); - - $message = new Message(); - $message->setRaw($rawMessage); - - return $message; + if (!empty($cc)) { + $rawMessageString .= "Cc: " . implode(',', $cc) . "\r\n"; } - public function sendMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = []) + if (!empty($bcc)) { + $rawMessageString .= "Bcc: " . implode(',', $bcc) . "\r\n"; + } + + $rawMessageString .= "Subject: $subject\r\n"; + $rawMessageString .= "MIME-Version: 1.0\r\n"; + $rawMessageString .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n\r\n"; + + // Add HTML content as an alternative part + $rawMessageString .= "--$boundary\r\n"; + $rawMessageString .= "Content-Type: text/html; charset=UTF-8\r\n"; + $rawMessageString .= "Content-Transfer-Encoding: 7bit\r\n\r\n"; + $rawMessageString .= $htmlContent . "\r\n\r\n"; + + // Process each attachment + foreach ($attachments as $attachment) { + $filePath = $attachment['filePath']; + $fileName = $attachment['fileName']; + $fileData = file_get_contents($filePath); + + if ($fileData === false) { + continue; // Skip this attachment if file cannot be read + } + + $base64File = base64_encode($fileData); + + // Add each attachment with appropriate headers + $rawMessageString .= "--$boundary\r\n"; + $rawMessageString .= "Content-Type: application/octet-stream; name=\"$fileName\"\r\n"; + $rawMessageString .= "Content-Disposition: attachment; filename=\"$fileName\"\r\n"; + $rawMessageString .= "Content-Transfer-Encoding: base64\r\n\r\n"; + $rawMessageString .= chunk_split($base64File) . "\r\n\r\n"; + } + + // End boundary to signify the end of the message + $rawMessageString .= "--$boundary--"; + + // Encode the final raw message in base64 for Gmail API + $rawMessage = base64_encode($rawMessageString); + $rawMessage = str_replace(['+', '/', '='], ['-', '_', ''], $rawMessage); + + // Create Gmail message object + $message = new Message(); + $message->setRaw($rawMessage); + + return $message; +} + + + public function sendMessage($to, $subject, $htmlContent, $from, $replyTo, $cc = [], $bcc = [],$attachments = []) { try { - $message = $this->createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc, $bcc); + $message = $this->createMessage($to, $subject, $htmlContent, $from, $replyTo, $cc, $bcc,$attachments); $res = $this->service->users_messages->send('me', $message); return array('status' => true, 'data' => $res); } catch (\Exception $e) { @@ -177,4 +208,59 @@ class GmailAPI $this->myLogger->logme('error', 'New token generated and stored in the database.'); print 'New token generated and stored in the database.'; } + + + + public function checkBounceStatus( string $userId = 'me',string $from_date = null,string $to_date = null,int $count = null,string $page = null) + { + $query = 'from:mailer-daemon OR "delivery failed" OR "failure notice"'; + if($from_date != '' && $to_date != '') + { + $query .= 'after:' . $from_date . ' before:' . $to_date; + } + $maxResults = $count ? $count : 20; + $pageToken = $page ? $page : null; + + $params = ['q' => $query,'maxResults' => $maxResults]; + if(isset($pageToken)){ $params['pageToken'] = $pageToken; } + $messages = $this->service->users_messages->listUsersMessages($userId, $params); + + $bounceDetails = []; + $pageToken = $messages->getNextPageToken(); + $bounceDetails['pageToken'] = $pageToken; + if (count($messages->getMessages()) > 0) { + foreach ($messages->getMessages() as $message) { + // Get full message details + $msg = $this->service->users_messages->get($userId, $message->getId(), ['format' => 'full']); + + // Extract important headers and content + $headers = $msg->getPayload()->getHeaders(); + $subject = null; + $date = null; + $to = null; + + foreach ($headers as $header) { + if ($header->getName() === 'Subject') { + $subject = $header->getValue(); + } + if ($header->getName() === 'Date') { + $date = $header->getValue(); + } + if ($header->getName() === 'To') { + $to = $header->getValue(); + } + } + + $bounceDetails['data'][] = [ + 'subject' => $subject, + 'date' => $date, + 'to' => $to, + 'snippet' => $msg->getSnippet(), + ]; + } + } + + return $bounceDetails; + } + } diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 180f810c..688b8abf 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -76,8 +76,9 @@ class EmployeePolicyModel extends Model } // ---------------------------------------------------------------------------------------------------------- - public function getEmployeePolicy($client_id = 0, $policy_id=0, $status=0, $branch_id=0, $emp_code="", $emp_name="") + public function getEmployeePolicy($client_id = 0, $policy_id=0, $status=[], $branch_id=0, $emp_code="", $emp_name="") { + // dd($status); $result = $this->select([ 'employee_polices.*', @@ -90,6 +91,7 @@ class EmployeePolicyModel extends Model 'tpab.branch_code as tpa_branch_code', 'cm.client_name', 'cm.short_name as client_short_name', + 'emp.id as employee_primary_id', 'emp.relationship', 'emp.relationship_code', 'emp.change_event', @@ -97,6 +99,7 @@ class EmployeePolicyModel extends Model 'emp.name', 'emp.email_corporate', 'emp.dob', + 'DATE_FORMAT(emp.dob, "%d/%m/%Y") AS formatted_dob', 'emp.gender', 'emp.emp_status', 'emp.is_active as emp_is_active', @@ -132,17 +135,39 @@ class EmployeePolicyModel extends Model if ($policy_id !=0 && !empty($policy_id)) { $result->where('employee_polices.client_policy_id', $policy_id); } - if ($status !=0 && !empty($status)) { - if($status == 'active'){ + + if (is_array($status) && count($status) > 0) { + + $result->where('employee_polices.status !=', 'expired'); + + if (in_array("active", $status)) { + $result->where('employee_polices.tpa_id IS NOT NULL'); - $result->where('employee_polices.uhid IS NOT NULL'); - }else if($status == 'pending'){ - $status = 'active'; - $result->where('employee_polices.status', $status); - }else{ - $result->where('employee_polices.status', $status); + $result->where('employee_polices.uhid IS NOT NULL'); + $result->whereIn('employee_polices.status', $status); + + } elseif (in_array("pending", $status)) { + + $result->where('employee_polices.tpa_id IS NULL'); + $result->where('employee_polices.uhid IS NULL'); + $result->whereIn('employee_polices.status', array_merge($status, ['active'])); + + } else { + + $result->whereIn('employee_polices.status', $status); } + + // if($status == 'active'){ + // $result->where('employee_polices.tpa_id IS NOT NULL'); + // $result->where('employee_polices.uhid IS NOT NULL'); + // }else if($status == 'pending'){ + // $status = 'active'; + // $result->where('employee_polices.status', $status); + // }else{ + // $result->where('employee_polices.status', $status); + // } } + if (!empty($emp_code)) { $result->where('emp.emp_code', $emp_code); } @@ -157,6 +182,27 @@ class EmployeePolicyModel extends Model return $result->findAll(); } + public function getEmployeePolicyForEcard($policy_id = 0) + { + $result = $this->select([ + 'employee_polices.id' + ]) + ->join('employees emp', 'employee_polices.employee_id = emp.id AND emp.relationship = "Self" '); + if ($policy_id !=0 && !empty($policy_id)) { + $result->where('employee_polices.client_policy_id', $policy_id); + } + // Always check these conditions + $result->where('employee_polices.is_active', 1) + ->where('employee_polices.status', 'active') + ->where('employee_polices.tpa_id is not null') + ->where('emp.relationship','Self'); + + return $result->findAll(); + // $result->findAll(); + // print_r($this->db->getLastQuery());die(); + } + + //for emp onboard do not change public function checkExistingEmpPolicy($arr) { @@ -508,6 +554,27 @@ class EmployeePolicyModel extends Model $client_branch_id = $ref_data['client_branch_id']; $insurer_or_tpa = $ref_data['insurer_or_tpa']; + $get_insurer_id_from_client_policy = $this->db->table('client_policy') + ->select('insurer_id') + ->where('id', $client_policy_id) + ->get() + ->getRowArray(); + + $add_one_day = 0; + + if (!empty($get_insurer_id_from_client_policy)) { + + $get_the_insurer_add_one_for_delete = $this->db->table('insurers') + ->select('deletion_add_day') + ->where('id', $get_insurer_id_from_client_policy['insurer_id']) + ->get() + ->getRowArray(); + + if (!empty($get_the_insurer_add_one_for_delete) && $get_the_insurer_add_one_for_delete['deletion_add_day'] == 1) { + $add_one_day = 1; + } + } + $query = $this->db->query(" SELECT DISTINCT a.id as endorsement_primarykey, @@ -547,10 +614,10 @@ class EmployeePolicyModel extends Model deletiondata.reasonforexit, deletiondata.status, - DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) AS no_of_days, - ROUND((employee_polices.rata_premimum * DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit)) / 365, 2) AS pro_rata_premium, - ROUND(((employee_polices.rata_premimum * DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit)) / 365) * 0.18, 2) AS gst, - ROUND(((employee_polices.rata_premimum * DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit)) / 365) + (((employee_polices.rata_premimum * DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit)) / 365) * 0.18), 2) AS total + DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + '$add_one_day' AS no_of_days, + ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365, 2) AS pro_rata_premium, + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18, 2) AS gst, + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) + (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + $add_one_day)) / 365) * 0.18), 2) AS total FROM emp_endorsement a LEFT JOIN @@ -806,8 +873,8 @@ class EmployeePolicyModel extends Model ->where('emp.client_id',$client_id) ->where('employee_polices.client_policy_id',$policy_id); - $result->whereIn('employee_polices.status', ['draft', 'enrolled']); - $result->whereIn('emp.emp_status', ['draft', 'enrolled']); + $result->whereIn('employee_polices.status', ['enrolled']); + $result->whereIn('emp.emp_status', ['enrolled']); $result = $result->findAll(); return ($result); } @@ -845,7 +912,7 @@ class EmployeePolicyModel extends Model e.doj, e.band, TIMESTAMPDIFF(YEAR, e.dob, CURDATE()) AS emp_age, - (SELECT name FROM employees WHERE relationship = "Self" and emp_code = ' . $this->db->escape($emp_code) . ' and client_id = '.$client_id.') AS self, + (SELECT name FROM employees WHERE relationship = "Self" and emp_code = ' . $this->db->escape($emp_code) . ' and client_id = '.$client_id.' LIMIT 1) AS self, ep.tpa_id, @@ -910,7 +977,7 @@ class EmployeePolicyModel extends Model e.doj, e.band, TIMESTAMPDIFF(YEAR, e.dob, CURDATE()) AS emp_age, - (SELECT name FROM employees WHERE relationship = "Self" and emp_code = ' . $this->db->escape($emp_code) . ' and client_id = '.$client_id.') AS self, + (SELECT name FROM employees WHERE relationship = "Self" and emp_code = ' . $this->db->escape($emp_code) . ' and client_id = '.$client_id.' LIMIT 1) AS self, ep.tpa_id, diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index 239ce3c5..705f1587 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -24,6 +24,7 @@ class LeadsModel extends Model 'branch_code', 'contact_person_name', 'contact_person_mobile', + 'contact_person_email', 'client_id', 'client_branch_id', 'source_policy_id', @@ -85,24 +86,46 @@ class LeadsModel extends Model return $data; } - public function getLeadDataForLising(){ + public function getLeadDataForLising() + { return $this->select(' leads.*, kyc_entity_type.name as entity_type, policy_type.policy_type, - user_profiles.first_name as salse_person_name + user_profiles.first_name as salse_person_name, + + ( + SELECT COUNT(*) AS qcr_count + FROM rfq + WHERE type = 2 + AND is_active = 1 and lead_id = leads.id + ) AS qcr_count, + + ( + SELECT COUNT(*) AS rfq_count + FROM rfq + WHERE type = 1 + AND is_active = 1 and lead_id = leads.id + + ) AS rfq_count ') ->join('kyc_entity_type', 'leads.entity_type_id = kyc_entity_type.id', 'left') ->join('user_profiles', 'leads.salse_person_id = user_profiles.id', 'left') ->join('policy_type', 'leads.policy_type_id = policy_type.id', 'left') ->where('leads.is_active', 1) - ->where('leads.is_active', 1) - ->where('leads.is_active', 1) ->orderBy('id', 'desc') ->findAll(); } + + public function getLeadForInsertClientList() + { + return $this + ->where('leads.is_active', 1) + ->where('leads.status', 'won') + ->findAll(); + } } diff --git a/app/Models/LevelContactModel.php b/app/Models/LevelContactModel.php index 88f52ab2..234db3aa 100755 --- a/app/Models/LevelContactModel.php +++ b/app/Models/LevelContactModel.php @@ -25,4 +25,28 @@ class LevelContactModel extends Model "token_time_out" ]; + + public function getContectForRFQ(){ + + $result = $this + + ->select(' + level_contacts.id, + insurers.short_name as insurer_name, + insurer_branch.branch_code, + level_contacts.name as contect_person_name, + level_contacts.email as contect_person_email, + ') + ->join('insurer_branch', 'level_contacts.ref_id = insurer_branch.id') + ->join('insurers', 'insurer_branch.insurer_id = insurers.id') + ->where('level_contacts.contact_type', 'insurer') + ->where('level_contacts.is_active', 1) + ->where('insurer_branch.is_active', 1) + ->where('insurers.is_active', 1) + ->findAll(); + + return $result; + + } + } diff --git a/app/Models/MailAttachmentModel.php b/app/Models/MailAttachmentModel.php new file mode 100644 index 00000000..74519d65 --- /dev/null +++ b/app/Models/MailAttachmentModel.php @@ -0,0 +1,56 @@ + - by + by diff --git a/app/Views/client_list.php b/app/Views/client_list.php index 8d015165..e9499095 100755 --- a/app/Views/client_list.php +++ b/app/Views/client_list.php @@ -26,8 +26,11 @@ table.dataTable thead th {

Client List

- + + + + \ No newline at end of file diff --git a/app/Views/employee_data_list.php b/app/Views/employee_data_list.php index 69ca1f74..8ca32f6b 100755 --- a/app/Views/employee_data_list.php +++ b/app/Views/employee_data_list.php @@ -67,6 +67,7 @@ + @@ -77,6 +78,7 @@ + @@ -100,6 +102,7 @@ + @@ -133,6 +136,26 @@ + @@ -157,9 +180,11 @@ + +
Name EMP Code RelationshipGender Date of Birth Policy name Insurer name(₹)Premium (₹)Pro Rata
Premium
(₹)GST Action
- + +
Total
@@ -168,7 +193,82 @@ + + + + diff --git a/app/Views/employee_list.php b/app/Views/employee_list.php index d615e7db..b6d77d34 100755 --- a/app/Views/employee_list.php +++ b/app/Views/employee_list.php @@ -7,6 +7,17 @@ table.dataTable tbody td { padding: 4px 4px !important; } + +.select2-selection__choice { + background-color: #0a8794 !important; + color: white !important; + font-weight: bold; +} + +.select2-selection__choice__remove { + color: white !important; + margin-right: 5px; +}
@@ -48,17 +59,22 @@ table.dataTable tbody td {

- $value) { ?>
+

@@ -70,8 +86,13 @@ table.dataTable tbody td {
-
-
+
+
+ + Send Ecard + +
+
" class="btn btn-primary waves-effect waves-light" id="get-emp-list" onclick="fetchEmpolyeeList(event);">Submit @@ -101,6 +122,13 @@ $(document).ready(function() { $("#policies").select2(); $("#branch_id").select2(); + $("#status2").select2({ + placeholder : 'Select Status' + }); + + $("textarea.select2-search__field").attr('rows', '1'); + $("textarea.select2-search__field").css('resize', 'none'); + // if ($('.select2-selection__arrow').length > 0) { // $('.select2-selection__arrow').removeClass('select2-selection__arrow').addClass('fa fa-chevron-down'); // } @@ -114,11 +142,22 @@ var clientPoliciesWithBranch = { var client_id = ''; var client_branch_id = ''; +var statusData = ; + +$(document).ready(function() { + // Loop through each item in statusData and set the option as selected. + statusData.forEach(function(status) { + $('#status2 option[value="' + status + '"]').prop('selected', true); + }); + + // Refresh the select element (necessary if you are using a plugin like Select2). + $('#status2').trigger('change'); +}); + $(document).ready(function() { console.log("document loaded"); //fetchClientPolicies(); - }); $(window).on("load", function() { @@ -325,6 +364,11 @@ function fetchEmpolyeeList(event) { var emp_code = $('#emp_code').val(); var emp_name = $('#emp_name').val(); + var statusArray = []; + $('#status2 option:selected').each(function() { + statusArray.push($(this).val()); + }); + // console.log(client_id + '-' + policy_id); // if (client_id == '0' || policy_id == '0') { // alert('Please select values in both dropdowns.'); @@ -338,7 +382,7 @@ function fetchEmpolyeeList(event) { branch_id: branch_id, emp_code : emp_code, emp_name : emp_name, - status : status, + status : statusArray, }; const queryString = objectToQueryString(queryParams); @@ -371,4 +415,69 @@ document.getElementById('toggleIcon').addEventListener('click', function() { icon.classList.toggle('mdi-chevron-up'); }); + +function sendManualEcard(input) + { + console.log('sendManualEcard function called'); + + var client_id = $('#clients').val() + var client_branch_id = $('#branch_id').val() + var policy_id = $('#policies').val() + + console.log('input', input); + console.log('client_id', client_id); + console.log('client_branch_id', client_branch_id); + + if(client_id == 0 || client_branch_id == 0 || policy_id == 0) + { + Swal.fire({ + title: "warning!", + text: 'Please select the Client, Client Branch and Policy.', + icon: "warning" + }); + + return false + } + + Swal.fire({ + title: "Do you want to send Ecard Mail?", + showDenyButton: true, + showCancelButton: false, + confirmButtonText: "Yes,Send", + denyButtonText: "Don't Send" + }).then((result) => { + + if (result.isConfirmed) { + + $.ajax({ + url: '' + client_id + '/' + client_branch_id+'/'+policy_id, + type: "GET", + dataType: 'json', + success: function(res) { + + console.log('send_manual_ecard', res) + + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + + if(res.status == false){ + toastr.info(res.message, 'INFO'); + }else{ + toastr.success(res.message, 'SUCCESS'); + } + + }, + error: function(xhr, status, error) { + console.error(xhr.responseText); + console.error(status, error); + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + } + }); + // Swal.fire("Saved!", "", "success"); + } + }); + + } + diff --git a/app/Views/enrollment_list.php b/app/Views/enrollment_list.php index 8459974c..3d37096a 100755 --- a/app/Views/enrollment_list.php +++ b/app/Views/enrollment_list.php @@ -66,7 +66,7 @@
- Search +
@@ -74,17 +74,22 @@ Send Reminder
-
+ -
+ + + + +
+
@@ -713,31 +718,44 @@ return false } - $.ajax({ - url: '' + client_id + '/' + client_branch_id, - type: "GET", - dataType: 'json', - success: function(res) { + Swal.fire({ + title: "Do you want to send reminder mail?", + showDenyButton: true, + showCancelButton: false, + confirmButtonText: "Yes,Send", + denyButtonText: "Don't Send" + }).then((result) => { - console.log('send_manual_reminder', res) + if (result.isConfirmed) { - $('.loader').fadeOut(); - $('.loader-mask').delay(350).fadeOut('slow'); + $.ajax({ + url: '' + client_id + '/' + client_branch_id, + type: "GET", + dataType: 'json', + success: function(res) { - if(res.status == false){ - toastr.info(res.message, 'INFO'); - }else{ - toastr.success(res.message, 'SUCCESS'); + console.log('send_manual_reminder', res) + + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + + if(res.status == false){ + toastr.info(res.message, 'INFO'); + }else{ + toastr.success(res.message, 'SUCCESS'); + } + + }, + error: function(xhr, status, error) { + console.error(xhr.responseText); + console.error(status, error); + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); } - - }, - error: function(xhr, status, error) { - console.error(xhr.responseText); - console.error(status, error); - $('.loader').fadeOut(); - $('.loader-mask').delay(350).fadeOut('slow'); - } - }); + }); + // Swal.fire("Saved!", "", "success"); + } + }); } diff --git a/app/Views/file_list.php b/app/Views/file_list.php index 2cd80976..a504ad5f 100755 --- a/app/Views/file_list.php +++ b/app/Views/file_list.php @@ -53,7 +53,7 @@ - - ' . $file['first_name'] . '' ?> + ' . $file['first_name'] . '' ?> - + diff --git a/app/Views/leads_form.php b/app/Views/leads_form.php index f00ea8b6..c9caf4c1 100644 --- a/app/Views/leads_form.php +++ b/app/Views/leads_form.php @@ -193,24 +193,30 @@ placeholder="Enter Branch Name" required>
-
+
-
+
-
- +
+
+
+ + +
+
@@ -278,6 +284,8 @@ //SELECT2 document ready function $(document).ready(function() { + + getURLParamsForReport() addHTMLInput() setTimeout(function() { $("textarea.select2-search__field").attr('rows', '1'); @@ -372,10 +380,9 @@ function getLeadsDataForEdit(input) { $('#gst').val(res.data.gst); $('#branch_name').val(res.data.branch_name); $('#branch_code').val(res.data.branch_code); - $('#contact_person_name').val(res.data - .contact_person_name); - $('#contact_person_mobile').val(res.data - .contact_person_mobile); + $('#contact_person_name').val(res.data.contact_person_name); + $('#contact_person_mobile').val(res.data.contact_person_mobile); + $('#contact_person_email').val(res.data.contact_person_email); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); @@ -459,6 +466,7 @@ function getBranchData(input) { $('#branch_code').val(res.data.branch_code); $('#contact_person_name').val(res.contact.name); $('#contact_person_mobile').val(res.contact.mobile); + $('#contact_person_email').val(res.contact.email); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); @@ -471,6 +479,7 @@ function getBranchData(input) { $('#branch_code').val(''); $('#contact_person_name').val(''); $('#contact_person_mobile').val(''); + $('#contact_person_email').val(''); console.log(res.message, 'warning'); } @@ -510,6 +519,7 @@ function getPolicyData(input) { $('#branch_code').val(res.data.branch_code); $('#contact_person_name').val(res.contact.name); $('#contact_person_mobile').val(res.contact.mobile); + $('#contact_person_email').val(res.contact.email); $('.loader').fadeOut(); $('.loader-mask').delay(350).fadeOut('slow'); @@ -522,6 +532,7 @@ function getPolicyData(input) { $('#branch_code').val(''); $('#contact_person_name').val(''); $('#contact_person_mobile').val(''); + $('#contact_person_email').val(''); console.log(res.message, 'warning'); } @@ -825,6 +836,7 @@ $('#lead_type').change(function() { $('#branch_code').val(''); $('#contact_person_name').val(''); $('#contact_person_mobile').val(''); + $('#contact_person_email').val(''); } else { @@ -840,6 +852,7 @@ $('#lead_type').change(function() { $('#branch_code').val(''); $('#contact_person_name').val(''); $('#contact_person_mobile').val(''); + $('#contact_person_email').val(''); $('#client_type').val(''); $('#client_name').val(''); @@ -870,19 +883,20 @@ function tpaChange(input, unique_id) { //----------------------------------------------------------------------------------------------------------- function getURLParamsForReport() { - const params = new URLSearchParams(window.location.search); - const pt_id = params.get('pt_id') ?? 0; - if (pt_id != 0) { + const params = new URLSearchParams(window.location.search); + const lead_id = params.get('lead_id') ?? 0; + + if (lead_id != 0) { hide_list_show_add(); setTimeout(() => - getPolicyTransactionDataForEdit(pt_id), + getLeadsDataForEdit(lead_id), 1500); // Reduced timeout } else { show_list_hide_add(); } - console.log('pt_id', pt_id); // Retain the log if necessary + console.log('lead_id', lead_id); // Retain the log if necessary } \ No newline at end of file diff --git a/app/Views/leads_list.php b/app/Views/leads_list.php index 09e2b950..edc17e10 100644 --- a/app/Views/leads_list.php +++ b/app/Views/leads_list.php @@ -98,9 +98,14 @@ table.dataTable tbody td { Edit - + RFQ + 0) { ?> + + QCR + +
diff --git a/app/Views/notification.php b/app/Views/notification.php index 6b15116a..c9bdb5e5 100755 --- a/app/Views/notification.php +++ b/app/Views/notification.php @@ -30,32 +30,32 @@ $account_maneger_summary_mail = 0; $client_hr_summary_mail = 0; if(isset($notification)){ - foreach($notification as $value){ - - if ($value['template_name'] == 'member_welcome_mail') { - $member_welcome_mail = $value['enabled']; - } + foreach($notification as $value){ + + if ($value['template_name'] == 'member_welcome_mail') { + $member_welcome_mail = $value['enabled']; + } - if ($value['template_name'] == 'member_reminder_mail') { - $member_reminder_mail = $value['enabled']; - } + if ($value['template_name'] == 'member_reminder_mail') { + $member_reminder_mail = $value['enabled']; + } - if ($value['template_name'] == 'member_ecard_mail') { - $member_ecard_mail = $value['enabled']; - } + if ($value['template_name'] == 'member_ecard_mail') { + $member_ecard_mail = $value['enabled']; + } - if ($value['template_name'] == 'member_review_and_summary_mail') { - $member_review_and_summary_mail = $value['enabled']; - } + if ($value['template_name'] == 'member_review_and_summary_mail') { + $member_review_and_summary_mail = $value['enabled']; + } - if ($value['template_name'] == 'account_maneger_summary_mail') { - $account_maneger_summary_mail = $value['enabled']; - } + if ($value['template_name'] == 'account_maneger_summary_mail') { + $account_maneger_summary_mail = $value['enabled']; + } - if ($value['template_name'] == 'client_hr_summary_mail') { - $client_hr_summary_mail = $value['enabled']; + if ($value['template_name'] == 'client_hr_summary_mail') { + $client_hr_summary_mail = $value['enabled']; + } } - } } ?>

@@ -197,7 +197,7 @@