From 411249fd632432dadc2a7e9ce4bdf4f2f8ab0068 Mon Sep 17 00:00:00 2001 From: velz Date: Fri, 25 Oct 2024 13:50:16 +0530 Subject: [PATCH 01/16] FIX_LIVE_UNHANDLED_ISSUES --- app/Controllers/EmployeeController.php | 10 +++++---- app/Controllers/EmployeeRestController.php | 4 ++++ app/Controllers/EmployeeServiceController.php | 17 +++++++++++--- app/Helpers/excel_util_helper.php | 22 ++++++++++++++++++- app/Views/batch_list.php | 2 +- app/Views/file_list.php | 2 +- 6 files changed, 47 insertions(+), 10 deletions(-) diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index 1df4dc16..673f2933 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -279,7 +279,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 +301,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 +319,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(); diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index c13eb6ba..b0d07d2e 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -804,6 +804,7 @@ class EmployeeRestController extends AdminController 'basic_pay'=> $extra['11'][$index], 'unit'=> isset($extra['12'][$index]) ? $extra['12'][$index] : null, 'client_branch_id' => $client_branch_id + 'date_coverage' => $extra['13'][$index] ]; $basic_cover_si_value = null; @@ -840,6 +841,8 @@ class EmployeeRestController extends AdminController $count = 0; for ($a=0; $a employeeModel->checkExistingEmployee($dataToInsert[$a],$client_branch_id); $emp_id =0; @@ -891,6 +894,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 ]; diff --git a/app/Controllers/EmployeeServiceController.php b/app/Controllers/EmployeeServiceController.php index ef99ee20..b6236313 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) @@ -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/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index 6de54c74..bf911f77 100755 --- a/app/Helpers/excel_util_helper.php +++ b/app/Helpers/excel_util_helper.php @@ -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/Views/batch_list.php b/app/Views/batch_list.php index 00e5b465..a2c371b2 100755 --- a/app/Views/batch_list.php +++ b/app/Views/batch_list.php @@ -67,7 +67,7 @@ - by + by 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'] . '' ?> Date: Sat, 26 Oct 2024 17:51:09 +0530 Subject: [PATCH 02/16] FEAT_EXPLORED_GMAILAPI_ATTACHEMENT&MAIL_DELIVERY_STATUS --- app/Config/Routes.php | 3 +- app/Controllers/MasterController.php | 4 +- app/Helpers/MailHelper.php | 5 +- app/Libraries/GmailAPI.php | 158 +++++++++++++++++++++------ app/Views/employee_data_list.php | 2 + public/sample_excel/enrollment.xlsx | Bin 7646 -> 7762 bytes 6 files changed, 132 insertions(+), 40 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index ca0cbe4f..8c1521be 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -355,7 +355,8 @@ $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'); diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 691234eb..0a5bb5d1 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; @@ -1672,7 +1674,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/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/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/Views/employee_data_list.php b/app/Views/employee_data_list.php index 69ca1f74..2a70d76a 100755 --- a/app/Views/employee_data_list.php +++ b/app/Views/employee_data_list.php @@ -67,6 +67,7 @@ Name EMP Code Relationship + Gender Date of Birth Policy name Insurer name @@ -100,6 +101,7 @@ + - diff --git a/public/sample_excel/enrollment.xlsx b/public/sample_excel/enrollment.xlsx index dec7c20ffda4228bd47b41a2be60ea38311f37f9..568e3b5e8e6c534f0f3fbb277383bb8cf3bfb1d6 100755 GIT binary patch delta 4147 zcmZ8k2{aU57awCU*|)J~r;Ig>B_V^c%WhD%zkL{6QcM{862>ydlq?}xMi>#Y?~*05 zCA*S+i6Wo=edm1jy>s3<_uO-T@4dUcyL?n0QK2=~BPC-7P*G6R%7e<8^Us0Mch7BAzFWKANq_eB!{)X6#iGZa#h6zL3Zwh#6b_zO1hsnN zX5Tb3%CJ*aIElD_eR2X6|1oQ)sv~ZJpU-j8Zw0f8&3lo}T7s#hE(Ys-@FKfmbW*KK z_FPk3GhJ3C;wrvPVev-vb6b-K*SoENEaA@tAXzf^HX!aOscvcA+dE{kfx-*?TDQ34 zvoXTJ0;%`;SS9-x?*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db800e261669 Mon Sep 17 00:00:00 2001 From: velz Date: Sat, 26 Oct 2024 18:02:15 +0530 Subject: [PATCH 03/16] CHNAGE_MAIL_PARAMS_CLI --- app/Controllers/MasterController.php | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php index 0a5bb5d1..42f3d660 100755 --- a/app/Controllers/MasterController.php +++ b/app/Controllers/MasterController.php @@ -1607,11 +1607,21 @@ class MasterController extends AdminController { // print_r($email_id);die(); // $gmailapi = \Config\Services::gmailapi(); + $email_id = CLI::getOption('to') ? CLI::getOption('to') : $email_id; $res = MailHelper::send_email(['mail' => $email_id, 'subject' => 'Mail Via CLI', 'message' => 'This is sample mail sent via CLI mode']); 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() { From 13a8f999e5a325a0fd4eff08e6e71a8209d57937 Mon Sep 17 00:00:00 2001 From: velz Date: Mon, 28 Oct 2024 17:29:40 +0530 Subject: [PATCH 04/16] FIX_RELATED_ENROLMENTFILE_DOC_CAPTURE --- app/Controllers/EmployeeController.php | 2 +- app/Controllers/EmployeeRestController.php | 7 ++++--- app/Controllers/EmployeeServiceController.php | 2 +- app/Helpers/excel_util_helper.php | 2 +- app/Models/EmployeePolicyModel.php | 4 ++-- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index 4b5f3f64..569f1c65 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -827,7 +827,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')); diff --git a/app/Controllers/EmployeeRestController.php b/app/Controllers/EmployeeRestController.php index a8a6e3d8..0c43d7cd 100755 --- a/app/Controllers/EmployeeRestController.php +++ b/app/Controllers/EmployeeRestController.php @@ -703,7 +703,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(); @@ -834,7 +834,7 @@ 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] ]; @@ -925,7 +925,7 @@ class EmployeeRestController extends AdminController 'employee_id'=>$emp_id, 'client_policy_id'=>$policy_id, 'status'=> 'draft', - 'date_coverage' => $date_coverage + 'date_coverage' => $date_coverage, 'basic_cover_si'=>isset($basic_cover_si[$a]) ? $basic_cover_si[$a] : null ]; @@ -967,6 +967,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 b6236313..f697a04a 100755 --- a/app/Controllers/EmployeeServiceController.php +++ b/app/Controllers/EmployeeServiceController.php @@ -1097,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'])) { diff --git a/app/Helpers/excel_util_helper.php b/app/Helpers/excel_util_helper.php index bf911f77..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']; } diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 180f810c..18dff3a9 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -806,8 +806,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); } From 9699c6de7286ab409ecd86ee5f3f06b38dbe5378 Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Tue, 29 Oct 2024 15:16:31 +0530 Subject: [PATCH 05/16] FEAT_RFQ_AND_QCR_MODULE : RV --- app/Config/Routes.php | 8 + app/Controllers/LeadsController.php | 270 ++ app/Models/LeadsModel.php | 19 +- app/Models/PolicyTypeModel.php | 1 + app/Models/RFQModel.php | 60 + app/Views/leads_list.php | 7 +- .../policy_transaction_inception_form.php | 29 +- app/Views/tpa_basic_info.php | 22 +- app/Views/view_rfq.php | 2825 +++++++++++++++++ 9 files changed, 3212 insertions(+), 29 deletions(-) create mode 100644 app/Models/RFQModel.php create mode 100644 app/Views/view_rfq.php diff --git a/app/Config/Routes.php b/app/Config/Routes.php index ca0cbe4f..3d943692 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -18,6 +18,7 @@ $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"); @@ -343,6 +344,13 @@ $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("exportQCRandRFQ/(:any)", "LeadsController::exportQCRandRFQ/$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"); diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 9c9d153f..737a686f 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,8 @@ use App\Models\KYCEntityTypeModel; use App\Models\PolicyTransactionStatusModel; use App\Models\InsurerBranchModel; use App\Models\TPABranchModel; +use App\Models\RFQModel; +use App\Models\InsurerModel; class LeadsController extends BaseController { @@ -35,6 +40,8 @@ class LeadsController extends BaseController protected $policyTransactionStatusModel; protected $insurerBranchModel; protected $tpaBranchModel; + protected $RFQModel; + protected $insurerModel; //variables for storing array protected $issuer; @@ -58,6 +65,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']; @@ -296,4 +305,265 @@ 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(); + + + // 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'; + + // Add headers in the first row and subheaders in the second row + 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.'; + } + + $sheet->setCellValue("{$columnLetter}{$rowNumber}", $header['parentHeader']); + + // Apply bold style to the header + $sheet->getStyle("{$columnLetter}{$rowNumber}")->applyFromArray([ + 'font' => [ + 'bold' => true, + ], + ]); + + foreach ($header['subHeaders'] as $subHeader) { + $sheet->setCellValue("{$columnLetter}{$subHeaderRow}", $subHeader); + + // 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 + 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']); + $columnLetter++; + } + $rowNumber++; + } + + // 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 + } + } diff --git a/app/Models/LeadsModel.php b/app/Models/LeadsModel.php index 239ce3c5..9de34d05 100644 --- a/app/Models/LeadsModel.php +++ b/app/Models/LeadsModel.php @@ -91,14 +91,27 @@ class LeadsModel extends Model 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(); diff --git a/app/Models/PolicyTypeModel.php b/app/Models/PolicyTypeModel.php index 82c06d70..3edd01f1 100755 --- a/app/Models/PolicyTypeModel.php +++ b/app/Models/PolicyTypeModel.php @@ -22,5 +22,6 @@ class PolicyTypeModel extends Model "etp", "iep", "itp", + "question_json", ]; } diff --git a/app/Models/RFQModel.php b/app/Models/RFQModel.php new file mode 100644 index 00000000..f74a1313 --- /dev/null +++ b/app/Models/RFQModel.php @@ -0,0 +1,60 @@ +" onclick="getLeadsDataForEdit('')"> Edit - + RFQ + 0) { ?> + + QCR + + diff --git a/app/Views/policy_transaction_inception_form.php b/app/Views/policy_transaction_inception_form.php index c6d0e22a..c6e29bfe 100644 --- a/app/Views/policy_transaction_inception_form.php +++ b/app/Views/policy_transaction_inception_form.php @@ -799,7 +799,7 @@
- +
@@ -858,7 +858,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"); + } + }); } From 4fa40f0fc863b5d7702c12077a7bddde54dc848f Mon Sep 17 00:00:00 2001 From: velz Date: Mon, 11 Nov 2024 08:46:19 +0530 Subject: [PATCH 12/16] FIX_IMPORT&EXPORT_ISSUES --- app/Controllers/ClientController.php | 2 +- app/Controllers/EmpDataServiceController.php | 4 ++-- app/Models/EmployeePolicyModel.php | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 78c8c7a5..41291548 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -248,7 +248,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(); + // $data['lead_data'] = $this->leadsModel->getLeadForInsertClientList(); // dd($data); diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 42fa56e2..04cdc654 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -302,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' ], [ @@ -1281,7 +1281,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){ diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 4f265aff..5eabd0bb 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -568,10 +568,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) + 1 AS no_of_days, + ROUND((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + 1)) / 365, 2) AS pro_rata_premium, + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + 1)) / 365) * 0.18, 2) AS gst, + ROUND(((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + 1)) / 365) + (((employee_polices.rata_premimum * (DATEDIFF(employee_polices.policy_end_date, deletiondata.dateofexit) + 1)) / 365) * 0.18), 2) AS total FROM emp_endorsement a LEFT JOIN From 179ec2811872c3cf9021616fefdf1c882a172cf0 Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Mon, 11 Nov 2024 15:49:59 +0530 Subject: [PATCH 13/16] CHANGE_RFQ_AND TESTING_VIEW_MEMBERS_STATUS_TO_CHANGE_MULTISELCT : RV --- app/Controllers/EmployeeController.php | 29 ++-- app/Controllers/LeadsController.php | 43 ++++-- app/Models/EmployeePolicyModel.php | 39 +++-- app/Views/employee_list.php | 47 ++++++- app/Views/view_rfq.php | 188 +++++++++++++++---------- 5 files changed, 241 insertions(+), 105 deletions(-) diff --git a/app/Controllers/EmployeeController.php b/app/Controllers/EmployeeController.php index e5c6a9ab..2770ea29 100755 --- a/app/Controllers/EmployeeController.php +++ b/app/Controllers/EmployeeController.php @@ -87,22 +87,31 @@ 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'])) { + $filterData['status'] = explode(",", $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()); diff --git a/app/Controllers/LeadsController.php b/app/Controllers/LeadsController.php index 2d4a68ef..9d2c246c 100644 --- a/app/Controllers/LeadsController.php +++ b/app/Controllers/LeadsController.php @@ -500,26 +500,31 @@ class LeadsController extends BaseController $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'; - - // Add headers in the first row and subheaders in the second row + + // 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'){ + + 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([ @@ -528,9 +533,13 @@ class LeadsController extends BaseController ], ]); + // 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' => [ @@ -541,11 +550,11 @@ class LeadsController extends BaseController $columnLetter++; } } - + // Move to next row for data entries $rowNumber = $subHeaderRow + 1; - - // Add data rows + + // Add data rows and enable word wrap for data cells foreach ($data['table_data']['data'] as $dataRow) { $columnLetter = 'A'; foreach ($dataRow['data'] as $cellData) { @@ -553,11 +562,20 @@ class LeadsController extends BaseController 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'; @@ -586,7 +604,8 @@ class LeadsController extends BaseController $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 = 'velz1990@gmail.com,vitvelz@gmail.com'; + $cc = ""; $result_data = []; // dd($recipient_mail); diff --git a/app/Models/EmployeePolicyModel.php b/app/Models/EmployeePolicyModel.php index 5eabd0bb..00dff6ca 100755 --- a/app/Models/EmployeePolicyModel.php +++ b/app/Models/EmployeePolicyModel.php @@ -78,6 +78,7 @@ class EmployeePolicyModel extends Model // ---------------------------------------------------------------------------------------------------------- public function getEmployeePolicy($client_id = 0, $policy_id=0, $status=0, $branch_id=0, $emp_code="", $emp_name="") { + // dd($status); $result = $this->select([ 'employee_polices.*', @@ -132,17 +133,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); } diff --git a/app/Views/employee_list.php b/app/Views/employee_list.php index fed29d5d..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) { ?>
+

@@ -106,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'); // } @@ -119,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() { @@ -330,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.'); @@ -343,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); diff --git a/app/Views/view_rfq.php b/app/Views/view_rfq.php index 95b5297e..65f88a5f 100644 --- a/app/Views/view_rfq.php +++ b/app/Views/view_rfq.php @@ -216,6 +216,7 @@ body { +
@@ -765,6 +766,7 @@ function moveAddRowButton() { // Event listener to handle row removal rfqTable.addEventListener('click', function(e) { + if (e.target.classList.contains('removeRow')) { const row = e.target.closest('tr'); // Get the row to be removed const rowKey = row.getAttribute('id'); @@ -778,6 +780,7 @@ rfqTable.addEventListener('click', function(e) { moveAddRowButton(); // Move the add row button to the last row realignSpecialConditions(); } + }); // Function to add new columns @@ -1670,8 +1673,16 @@ function changeInsurer(event) { function changeState(event) { - var type = event.target.className; - console.log(type); + let type = event.target.className; + console.log('1 : ', type); + + // if (type.includes('sendClientProposal') && type.includes('fa fa-check-square')) { + // type = 'sendClientProposal'; + // } else if (type.includes('qcrProposal') && type.includes('fa fa-check-square')) { + // type = 'qcrProposal'; + // } + + // console.log('2 : ',type); if (['qcrProposal', 'sendClientProposal'].includes(type)) { @@ -2175,6 +2186,7 @@ function showModal(){ } function ajaxRequestForGetMailData(url){ + $.ajax({ url: url, type: "GET", @@ -2212,7 +2224,7 @@ function appendInput(data) { if (!data.contact_person_email) { html += ` `; } @@ -2282,36 +2294,49 @@ function constructURL() { } function ajaxRequest(url){ + console.log(url); + + $('.loader').fadeIn(); + $('.loader-mask').fadeIn(); + $.ajax({ - url: url, - type: "GET", - dataType: 'json', - success: function (res) { + url: url, + type: "GET", + dataType: 'json', + success: function (res) { - console.log(res); - if(res.status == 'success' && res.code == 200){ - toastr.success('Mail send Successfully', 'SUCCESS') + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + + console.log(res); + if(res.status == 'success' && res.code == 200){ + toastr.success('Mail send Successfully', 'SUCCESS') + }else{ + if(res.messgae){ + toastr.error(res.messgae, 'ERROR') }else{ - if(res.messgae){ - toastr.error(res.messgae, 'ERROR') - }else{ - toastr.error('Mail send failed', 'ERROR') - } + toastr.error('Mail send failed', 'ERROR') } + } - $('.close').click() - }, - error: function (xhr, status, error) { - console.error(xhr.responseText); - console.error(status, error); - } + $('.close').click() + }, + error: function (xhr, status, error) { + + $('.loader').fadeOut(); + $('.loader-mask').delay(350).fadeOut('slow'); + + console.error(xhr.responseText); + console.error(status, error); + } }); } //-------------------------------------------------------------------------------------------------------------------------------------------- +// not in use do not remove this function function tableToJson() { const headers = []; @@ -2522,14 +2547,14 @@ function jsonToTable(json) { proposel_count++; // Extract qcr and stc status for the main headers - const dropdown_data_qcr = proposels[header.parentHeader]?.qcr === 1 ? + const dropdown_data_qcr = proposels[header.parentHeader]?.qcr == 1 ? 'style="background-color: rgb(221, 221, 221);"' : ''; - const dropdown_data_stc = proposels[header.parentHeader]?.stc === 1 ? + const dropdown_data_stc = proposels[header.parentHeader]?.stc == 1 ? 'style="background-color: rgb(221, 221, 221);"' : ''; - const check_icon_qcr = proposels[header.parentHeader]?.qcr === 1 ? + const check_icon_qcr = proposels[header.parentHeader]?.qcr == 1 ? `` : ''; - const check_icon_stc = proposels[header.parentHeader]?.stc === 1 ? + const check_icon_stc = proposels[header.parentHeader]?.stc == 1 ? `` : ''; @@ -2539,7 +2564,7 @@ function jsonToTable(json) { `; @@ -2603,15 +2628,15 @@ function jsonToTable(json) { const insurerData = proposels[header.parentHeader]?.insurers[index - 1] || {}; - dropdownDataQCRForInsurer = insurerData.qcr === 1 ? + dropdownDataQCRForInsurer = insurerData.qcr == 1 ? 'style="background-color: rgb(221, 221, 221);"' : ''; - dropdownDataSTCForInsurer = insurerData.stc === 1 ? + dropdownDataSTCForInsurer = insurerData.stc == 1 ? 'style="background-color: rgb(221, 221, 221);"' : ''; - checkDropdownDataQCRForInsurer = insurerData.qcr === 1 ? + checkDropdownDataQCRForInsurer = insurerData.qcr == 1 ? `` : ''; - checkDropdownDataSTCForInsurer = insurerData.stc === 1 ? + checkDropdownDataSTCForInsurer = insurerData.stc == 1 ? `` : ''; @@ -2814,57 +2839,72 @@ function jsonToTable(json) { console.log(over_all_column_data); - try { + let qcr_count = $('#qcr_count').val() + let lead_id = $('#lead_id').val() - $('.loader').fadeIn(); - $('.loader-mask').fadeIn(); + if(qcr_count != 0){ - const jsonData = await convertJsonForQCR(); // Construct the JSON data + console.log('qcr found') - // Create a FormData object - const formData = new FormData(); + url = '' + lead_id + '/' + 2; + window.location.href = url; - let lead_id = $('#lead_id').val(); + }else{ - formData.append('json', JSON.stringify(jsonData)); - formData.append('lead_id', lead_id); + console.log('qcr not found') - const postUrl = ''; - console.log(postUrl); + try { - const response = await $.ajax({ - url: postUrl, - type: 'POST', - data: formData, - processData: false, // Important to prevent jQuery from processing the data - contentType: false, // Important to set this to false to let jQuery set the content type correctly - }); + $('.loader').fadeIn(); + $('.loader-mask').fadeIn(); - console.log('Data sent successfully:', response); - if(response.status == true){ - toastr.success(response.message, 'SUCCESS'); - }else{ - toastr.warning(response.message, 'WARNING'); - } + const jsonData = await convertJsonForQCR(); // Construct the JSON data - window.location.href = '' + lead_id + '/' + 2; + // Create a FormData object + const formData = new FormData(); - } catch (error) { - console.error('An error occurred during the AJAX request:'); - - if (error.responseText) { - try { - const errorResponse = JSON.parse(error.responseText); - console.error('Server Response:', errorResponse); - } catch (parseError) { - console.error('Error Message:', error.message); - console.error('Could not parse error response:', error.responseText); + let lead_id = $('#lead_id').val(); + + formData.append('json', JSON.stringify(jsonData)); + formData.append('lead_id', lead_id); + + const postUrl = ''; + console.log(postUrl); + + const response = await $.ajax({ + url: postUrl, + type: 'POST', + data: formData, + processData: false, // Important to prevent jQuery from processing the data + contentType: false, // Important to set this to false to let jQuery set the content type correctly + }); + + console.log('Data sent successfully:', response); + if(response.status == true){ + toastr.success(response.message, 'SUCCESS'); + }else{ + toastr.warning(response.message, 'WARNING'); } - } else { - console.error('Error Message:', error.message); - } - console.error('Full Error Object:', error); + window.location.href = '' + lead_id + '/' + 2; + + } catch (error) { + console.error('An error occurred during the AJAX request:'); + + if (error.responseText) { + try { + const errorResponse = JSON.parse(error.responseText); + console.error('Server Response:', errorResponse); + } catch (parseError) { + console.error('Error Message:', error.message); + console.error('Could not parse error response:', error.responseText); + } + } else { + console.error('Error Message:', error.message); + } + + console.error('Full Error Object:', error); + } } }); }); @@ -2882,15 +2922,21 @@ function jsonToTable(json) { let headerIndex = 0; parentHeaders.forEach((header) => { + + console.log('header names', header); + console.log('header header.innerText', header.innerText); + const colspan = header.getAttribute('colspan') || 1; const subHeaderArray = []; for (let i = 0; i < colspan; i++) { - subHeaderArray.push(subHeaders[headerIndex].innerText.replace('⋮', '').trim()); + const cleanedText = subHeaders[headerIndex].innerText.split('⋮')[0].trim(); + subHeaderArray.push(cleanedText); headerIndex++; } + headers.push({ - parentHeader: header.innerText.replace('⋮', '').trim(), + parentHeader: header.innerText.split('⋮')[0].trim(), subHeaders: subHeaderArray }); }); From 0e895de4298d58102c0d1eef55d3f3630adc2dd2 Mon Sep 17 00:00:00 2001 From: "venkatesh.r" Date: Tue, 12 Nov 2024 17:41:41 +0530 Subject: [PATCH 14/16] FEAT_MAIL_ATTACHMENT : RV --- app/Config/Routes.php | 4 +- app/Controllers/ClientController.php | 23 +- app/Controllers/EmpDataServiceController.php | 101 +++--- app/Controllers/MasterController.php | 20 +- app/Controllers/NotificationController.php | 83 ++++- app/Helpers/sendMailNotification.php | 39 ++- app/Models/MailAttachmentModel.php | 56 ++++ app/Views/insurer_or_tpa_data.php | 38 ++- app/Views/layout/header.php | 4 +- app/Views/notification.php | 309 ++++++++++++++++--- app/Views/view_rfq.php | 23 +- 11 files changed, 575 insertions(+), 125 deletions(-) create mode 100644 app/Models/MailAttachmentModel.php diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 34478d0c..9c7af0c5 100755 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -20,7 +20,7 @@ $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"); @@ -74,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) { diff --git a/app/Controllers/ClientController.php b/app/Controllers/ClientController.php index 41291548..b937e835 100755 --- a/app/Controllers/ClientController.php +++ b/app/Controllers/ClientController.php @@ -118,11 +118,28 @@ class ClientController extends AdminController $this->leadsModel = new LeadsModel(); } - public function smapletest(){ - + 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"; + echo "Excel file created at: $filePath"; + } + + public function testMailAttachments($email = 'venkateshraman786@gmail.com') + { + $message = ''; + + $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 diff --git a/app/Controllers/EmpDataServiceController.php b/app/Controllers/EmpDataServiceController.php index 04cdc654..7ed5aae0 100755 --- a/app/Controllers/EmpDataServiceController.php +++ b/app/Controllers/EmpDataServiceController.php @@ -640,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;
+                }
             }
         }
 
@@ -708,7 +711,6 @@ class EmpDataServiceController extends BaseController
             
         }
 
-
         $excel_data_info = generate_insurer_based_excel($excel_header_columns, $objects);
 
         // Generate Excel file
@@ -1667,6 +1669,7 @@ class EmpDataServiceController extends BaseController
 
         $file_id = $params['file_id'];
         $file = $this->batchFileModel->find($file_id);
+
         if (!$file) {
 
             $data = [
@@ -1697,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')
@@ -1780,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');
@@ -1817,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');
@@ -2854,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');
@@ -3381,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');
diff --git a/app/Controllers/MasterController.php b/app/Controllers/MasterController.php
index a4927e3d..13305f50 100755
--- a/app/Controllers/MasterController.php
+++ b/app/Controllers/MasterController.php
@@ -1611,18 +1611,26 @@ class MasterController extends AdminController
          // $gmailapi = \Config\Services::gmailapi();
          $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" => 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"]
+            ["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();
@@ -1661,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) {
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/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/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 @@
+
 
                     
-                    
+                    
 
                     
 
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 @@