From 9bcefd7aff2cfef344b42945d88a596f93c4925a Mon Sep 17 00:00:00 2001 From: VE10-Sanjeev Date: Mon, 18 Nov 2024 12:58:21 +0000 Subject: [PATCH] FIX_Notification validation for exist --- Notifications.php | 1048 +++++++++++++++++++++++++++++ app/Controllers/Notifications.php | 68 +- app/Models/NotificationModel.php | 13 +- 3 files changed, 1123 insertions(+), 6 deletions(-) create mode 100644 Notifications.php diff --git a/Notifications.php b/Notifications.php new file mode 100644 index 00000000..72fc4225 --- /dev/null +++ b/Notifications.php @@ -0,0 +1,1048 @@ +request->is('post')) { + session()->setFlashdata('reset', true); + $records = $this->request->getVar(); + if($records['mode'] == 'Email'){ + helper('notification'); + $notification = new NotificationHelper(); + $records['description'] = $records['maildescription']; + $data = $notification->sendEmail($records); + $parents_status = 0; + $receiving_status = 0; + if (isset($data['error'])) { + session()->setFlashdata('error', 'Message: ' . $data['error']); + $history_msg = $data; + } + if (isset($data['success'])) { + session()->setFlashdata('success', 'Message: ' . $data['success']); + $parents_status = 1; + $receiving_status = 1; + $history_msg = 'Email sent successfully'; + } + $history_msg = (strtolower(gettype($history_msg)) == "string" ? $history_msg : json_encode($history_msg)) ; + $NotificationModel = new NotificationModel(); + $history_parents_data = ['campaign_id' => 0,'status' => $parents_status]; + $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); + $history_child_data = [ 'fkid' => $history_parent_id, + 'customer_id' => 0, + 'receiving_entity' => $records['recipient_email'], + 'receiving_status' => $receiving_status, + 'message' => $records['description'], + 'result'=>strtolower(gettype($history_msg)) == "string" ? $history_msg : json_encode($history_msg)]; + $history_child_id = $NotificationModel->save_notification_history_child($history_child_data); + $this->logger->error('Custom Notifications Email : historychildid = '.$history_child_id); + + }else{ + $records = $this->request->getVar(); + $doc_details = $this->request->getFile('media_doc'); + $params = (object) Null; + $parents_status = 0; + $receiving_status = 0; + $doc_path = APPPATH . '../public/uploads/'; + $doc_name = ''; + $errorMessages = []; + $this->logger->error("Whatsapp : sending message instance id = " . $_ENV['WAAI_INSTANCE'] . " - " . $_ENV['WAAI_TOKEN']); + if($records['mobile'] != ""){ + $string = $records['mobile']; + $mobile_no_arr = explode(',', $string); + $total_number_count = count($mobile_no_arr); + $sended_number_count = 0; + $not_sended_number_count = 0; + // Step 1 Categories Check + if ($records['categories'] == 'SEND_WAAI_GROUP_URL') { + if ($records['group_id'] != "") { + $params->group_id = $records['group_id']; + } else { + session()->setFlashdata('error', 'Group Id Missing Please Try again..'); + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + } + }else if ($records['categories'] == 'SEND_WAAI_URL') { + if ($records['mobile'] == "") { + session()->setFlashdata('error', 'Mobile Number Missing Please Try again..'); + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + } + } else { + session()->setFlashdata('error', 'Please Choose your Category..'); + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + } + + // Step 2 Media Check, Document Also Convert into Media Here. + if ($records['type'] == 'media') { + if ($records['media_url'] != "") { + $params->media_url = $records['media_url']; + $params->type = "media"; + } else { + session()->setFlashdata('error', 'Media Url Missing Please Try again..'); + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + } + }elseif ($records['type'] == 'document') { + $doc_details = $this->request->getFile('media_doc'); + $doc_path = APPPATH . '../public/uploads/'; + + if (empty($doc_details)) { + session()->setFlashdata('error', 'Please select a file to upload.'); + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + } + + if (!$doc_details->isValid() || $doc_details->getClientMimeType() !== 'image/jpeg') { + session()->setFlashdata('error', 'Please upload a valid JPEG image.'); + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + } + + $doc_name = $doc_details->getName(); + + if ($doc_name === '') { + $this->logger->error("Err on upload: name not found"); + session()->setFlashdata('error', 'Document name not found. Please try again.'); + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + } + + $doc_details->move($doc_path, $doc_name); + $params->media_url = base_url() . 'public/uploads/' . $doc_name; + $params->type = "media"; + $this->logger->error("Name After Upload: " . $doc_name); + }else{ + $params->type = "text" ; + } + + $NotificationModel = new NotificationModel(); + $history_parents_data = ['campaign_id' => 0,'status' => 0,'field_value' =>$records['mobile']]; + $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); + // print_r($mobile_no_arr); + if(!empty($mobile_no_arr)){ + foreach ($mobile_no_arr as $mobile) { + // try { + $exceptionOccurred = false; + // echo "----$mobile"; + if (trim(strlen($mobile)) == 10) { + if (ctype_digit($mobile)) { + if ($mobile != "") { + $params->number = (int)'91' . $mobile; + $url = constant($records['categories']); + $params->instance_id = $_ENV['WAAI_INSTANCE']; + $params->access_token = $_ENV['WAAI_TOKEN']; + $params->message = strip_tags(ltrim($records['description'])); + $this->logger->error("Whatsapp : Request Type ==> Mobile Number = ".$mobile." - " . gettype($params)); + helper('notification'); + $notification = new NotificationHelper(); + $success = $notification->sendWhatsAppMessage($url, "POST", $params); + // echo "
";print_r($success);echo "
"; + $receiving_status = $success['receiving_status']; + $parents_status = $success['receiving_status']; + $this->logger->error("Whatsapp : Reponse ==> Mobile Number = ".$mobile." Waai Reponse = ". json_encode($success['reponse'])); + $history_msg = strtolower(gettype($success)) == "string" ? $success : json_encode($success['reponse']); + // $tag = (int)$receiving_status === 1 ? 'success' : 'error' ; + // session()->setFlashdata($tag, 'Message : ' . $success['message']); + (int)$receiving_status === 1 ? $sended_number_count++ : $not_sended_number_count++; + } else { + $receiving_status = 0; + $parents_status = 0; + $history_msg = "Mobile Number = ".$mobile." is invalid."; + $this->logger->error("Whatsapp : Reponse ==> ".$history_msg); + $not_sended_number_count++; + $errorMessages[] = $history_msg; + } + }elseif (ctype_alpha($mobile)) { + $receiving_status = 0; + $parents_status = 0; + $history_msg = "Mobile Number = ".$mobile." is a character."; + $this->logger->error("Whatsapp : Reponse ==> ".$history_msg); + $not_sended_number_count++; + $errorMessages[] = $history_msg; + + }else { + $receiving_status = 0; + $parents_status = 0; + $history_msg = "Mobile Number = ".$mobile." is a combination of characters and numbers."; + $this->logger->error("Whatsapp : Reponse ==> ".$history_msg); + $not_sended_number_count++; + $errorMessages[] = $history_msg; + + } + }else { + $history_msg = "Mobile Number = ".$mobile." does not have 10 digits."; + $this->logger->error("Whatsapp : Reponse ==> ".$history_msg); + $not_sended_number_count++; + $errorMessages[] = $history_msg; + } + $history_child_data = [ 'fkid' => $history_parent_id, + 'customer_id' => 0, + 'receiving_entity' => $mobile, + 'receiving_status' => $receiving_status, + 'message' => $records['description'], + 'result'=>$history_msg]; + $NotificationModel = new NotificationModel(); + $history_child_id = $NotificationModel->save_custom_notification_history_child($history_child_data); + $this->logger->error('Custom Notifications Whatsapp : historychildid = '.$history_child_id); + } + if (!empty($errorMessages)) { + $this->logger->error(implode("\n", $errorMessages)); + session()->setFlashdata('error', implode('
', $errorMessages)); + $errorMessages = []; + } + if($sended_number_count > 0){ + $NotificationModel = new NotificationModel(); + $history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,0); + $this->logger->error($history_parent_statement); + session()->setFlashdata("success","Message : Sent Success (". $sended_number_count." / ".$total_number_count." )"); + $this->logger->error("Whatsapp : Final ==> ".$sended_number_count." Sended out of ".$total_number_count." ( Not sended numbers count ".$not_sended_number_count." ) "); + } + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + }else{ + session()->setFlashdata('error', 'Message : Mobile Not Founded'); + $this->logger->error('Message : Mobile Not Founded'); + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + } + }else{ + session()->setFlashdata('error', 'Message : Mobile Field Empty'); + $this->logger->error('Message : Mobile Field Empty'); + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + return; + } + } + } + $data['page_name'] = 'Custom Notifications'; + $this->render_page('notifications_form', $data); + } + + public function due_date_notifications() + { + $date = $this->request->getGet('date'); + + $model = new NotificationModel(); + $details = $model->getSubscriptionDueDetail($date); + // echo "
";
+        // print_r($details);
+        // echo "
"; + // die; + $records = []; + $recipient_name = ""; + $recipient_email = ""; + $recipient_mobile = ""; + $subscription_name = ""; + $business_name = ""; + $to_subscription = ""; + if (isset($details)) { + $this->logger->error("Notification : Duedate notification Request data type = " . gettype($details)); + } + helper('notification'); + $notification = new NotificationHelper(); + foreach ($details as $rec) { + $recipient_name = $rec['customer_name']; + $recipient_email = $rec['customer_email']; + $recipient_mobile = $rec['customer_mobile']; + // $recipient_email = "sanjeev.p@venbainfotech.com"; + // $recipient_mobile = 6369084112; + $business_name = $rec['business_name']; + $subscription_name = $rec['title']; + $to_subscription = $rec['to_subscription']; + } + $records['template_name'] = ''; + $records['recipient_name'] = $recipient_name; + $records['recipient_email'] = $recipient_email ? $recipient_email : "sanjeev.p@venbainfotech.com"; + $records['subject'] = $business_name . " - Due Date Reminder"; + $records['description'] = " + + Due Date Reminder + +

Hello " . $recipient_name . ",

+

This is a reminder that the following subscription is due soon:

+

Subscription Name:" . $subscription_name . "

+

Due Date: " . $to_subscription . "

+

Please make sure to complete this subscription on time.

+

Thank you.

+ + "; + + $template = "Hello " . $recipient_name . ",\r\r\n\nThis is a reminder that the following subscription is due soon:\r\n- Subscription Name: " . $subscription_name . "\r\n Due Date: " . $to_subscription . "\r\n\nPlease make sure to complete this subscription on time.\n Thank you."; + + $params = (object) Null; + $params->number = (int)'91' . $recipient_mobile; + $params->type = "text"; + $params->message = $template; + $params->instance_id = $_ENV['WAAI_INSTANCE']; + $params->access_token = $_ENV['WAAI_TOKEN']; + $this->logger->error("Notification : Duedate notification Email Request data = " . json_encode($records)); + + $email_result = $notification->sendEmail($records); + $this->logger->error("Notification : Duedate notification Email Response = " . json_encode($email_result)); + $this->logger->error("Notification : Duedate notification Whatsapp Request data = " . json_encode($params)); + $whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params); + $this->logger->error("Notification : Duedate notification Whatsapp Response = " . json_encode($whatsapp_result)); + } + + public function template_creation() + { + $data['page_name'] = 'Template Details'; + $model = new NotificationModel(); + $data['template'] = $model->getTemplateDetails(); + $this->render_page('template_creation', $data); + // echo "templates";die; + } + + ################################################################## + # Template Creation Insertion/updation Process ReferWith : Sanjeev + ################################################################## + public function template_creation_form($id) + { + + $data['group_details'] = $this->get_group_details(); + $model = new NotificationModel(); + if ($id === '0') { + $this->logger->error("Template Creation: In Add Page"); + $data['page_name'] = 'Add Template'; + $data['template_id'] = (int)$id; + $data['template_details'] = []; + } elseif ($id !== '0') { + $this->logger->error("Template Creation: In Edit Page ID =" . $id); + $data['page_name'] = 'Edit Template'; + $model->setTable('templates'); + $where = ['template_id' => (int)$id]; + $result = $model->where($where)->findAll(); + $data['template_id'] = (int)$id; + $data['template_details'] = !empty($result[0]) ? $result[0] : []; + } + // print_r($data['template_details']);die(); + $this->render_page('template_creation_form', $data); + } + + ############################################################################## + # Template Creation Delection which means inactive Process ReferWith : Sanjeev + ############################################################################## + public function template_creation_delete($id) + { + try { + helper('session'); + $session_uid = get_logged_user_id(); + $model = new NotificationModel(); + $model->setTable('templates'); + $where = ['template_id' => (int)$id]; + $result = $model->where($where)->findAll(); + if ($result) { + $this->logger->error("Template: Going to Inactive ID = " . $id); + $data = ['isactive' => 0, 'updated_by' => $session_uid, 'template_id' => (int)$id]; + $statement = $model->saveDetails($data, 'template_id', 'templates'); // just updating Inactive status only. + if ($statement['success']) { + session()->setFlashdata('success', $statement['success'] ? 'Deleted successfully.' : ""); + $this->logger->error($statement['log']); + } else if ($statement['error']) { + session()->setFlashdata('error', $statement['error']); + $this->logger->error($statement['log']); + } else { + throw new \Exception("Template: Err Occur on data the Template Inactive"); + } + } + } catch (\Exception $e) { + $this->logger->error("Template: Err Occur = " . $e->getMessage() . " File = " . $e->getFile() . " Line = " . $e->getLine()); + session()->setFlashdata('error', 'Message: ' . $e->getMessage()); + } + return redirect()->route('template_creation'); + } + + + public function get_group_details() + { + $model = new NotificationModel(); + $model->setTable('customer_groups'); + // $details = $model->where('isactive',1)->orderBy('group_id', 'ASC')->findAll(); + $where = ['isactive' => 1, 'group_name != ' => 'EXPIRYDATE']; + $details = $model->where($where)->orderBy('group_id', 'ASC')->findAll(); + return $details; + } + + public function get_template_details() + { + $model = new NotificationModel(); + $model->setTable('templates'); + $details = $model + ->where(['templates.isactive' => 1]) + ->whereNotIn('templates.template_name',array('EXPIRAY_NOTIFY_TEMPLATE_EMAIL','EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP')) + ->orderBy('templates.template_id', 'ASC')->findAll(); + return $details; + } + + public function template_creation_insert() + { + $this->logger->error("Template: Inserting/Updating Details"); + try { + ## Declarions + helper('session'); + $model = new NotificationModel(); + $session_uid = get_logged_user_id(); + $id = $this->request->getPost('template_id'); + $subject = $this->request->getPost('subject') ? $this->request->getPost('subject') : NULL; + $isactive = $id != "" ? $this->request->getPost('isactive') : 'on'; + $templatemessage = ""; + if($this->request->getPost('mode') === "Email"){ + $templatemessage = $this->request->getPost('templatemessage'); + }else if($this->request->getPost('mode') === "Whatsapp"){ + $templatemessage = $this->request->getPost('whatsapptemplatemessage'); + } + + $data = [ + 'template_id' => $id, + 'template_name' => $this->request->getPost('templatename'), + 'subject' => $subject, + 'message' => $templatemessage, + 'mode' => $this->request->getPost('mode'), + 'isactive' => (($isactive == 'on') ? 1 : 0), + 'created_by' => $session_uid, + 'updated_by' => $session_uid + ]; + $statement = $model->saveDetails($data, 'template_id', 'templates'); + if ($statement['success']) { + session()->setFlashdata('success', $statement['success']); + $this->logger->error($statement['log']); + } else if ($statement['error']) { + session()->setFlashdata('error', $statement['error']); + $this->logger->error($statement['log']); + } else { + throw new \Exception("Template: Err Occur"); + } + } catch (\Exception $e) { + $this->logger->error("Template: Err Occur =" . $e->getMessage()); + session()->setFlashdata('error', 'Message: ' . $e->getMessage()); + } + return redirect()->route('template_creation'); + } + + public function campaign_creation() + { + $data['page_name'] = 'Campaign Details'; + $model = new NotificationModel(); + $data['campaign'] = $model->getCampaignDetails(); + $this->render_page('campaign_creation', $data); + // echo "templates";die; + } + + public function campaign_creation_form($id) + { + + $data['group_details'] = $this->get_group_details(); + $data['template_details'] = $this->get_template_details(); + $model = new NotificationModel(); + if ($id === '0') { + $this->logger->error("Campaign Creation: In Add Page"); + $data['page_name'] = 'Add Campaign'; + $data['campaign_details'] = []; + } elseif ($id !== '0') { + $this->logger->error("Campaign Creation: In Edit Page ID =" . $id); + $data['page_name'] = 'Edit Campaign'; + $model->setTable('notification_campaign'); + $where = ['campaign_id' => (int)$id]; + $result = $model->where($where)->findAll(); + if (!empty($result)) { + foreach ($result as $i => $item) { + $result[$i]['group_id'] = unserialize($item['group_id']); + } + } + $data['campaign_details'] = !empty($result[0]) ? $result[0] : []; + } + $this->render_page('campaign_creation_form', $data); + } + + public function campaign_creation_delete($id) + { + try { + helper('session'); + $session_uid = get_logged_user_id(); + $model = new NotificationModel(); + $model->setTable('notification_campaign'); + $where = ['campaign_id' => (int)$id]; + $result = $model->where($where)->findAll(); + if ($result) { + $this->logger->error("Campaign: Going to Inactive ID = " . $id); + $data = ['isactive' => 0, 'updated_by' => $session_uid, 'campaign_id' => (int)$id]; + $statement = $model->saveDetails($data, 'campaign_id', 'notification_campaign'); // just updating Inactive status only. + if ($statement['success']) { + session()->setFlashdata('success', $statement['success'] ? 'Deleted successfully.' : ""); + $this->logger->error($statement['log']); + } else if ($statement['error']) { + session()->setFlashdata('error', $statement['error']); + $this->logger->error($statement['log']); + } else { + throw new \Exception("Campaign: Err Occur on data the Template Inactive"); + } + } + } catch (\Exception $e) { + $this->logger->error("Campaign: Err Occur = " . $e->getMessage() . " File = " . $e->getFile() . " Line = " . $e->getLine()); + session()->setFlashdata('error', 'Message: ' . $e->getMessage()); + } + return redirect()->route('campaign_creation'); + } + + public function campaign_creation_insert() + { + $this->logger->error("Campaign: Inserting/Updating Details"); + try { + ## Declarions + helper('session'); + $model = new NotificationModel(); + $session_uid = get_logged_user_id(); + $id = $this->request->getPost('campaign_id'); + $request_data = $this->request->getPost(); + $isactive = $id == "" ? 1 : (isset($request_data['isactive']) && $request_data['isactive'] == 'on' ? 1 : 0); + + $data = [ + 'campaign_id' => $id, + 'campaign_name' => $this->request->getPost('campaign_name'), + 'template_id' => $this->request->getPost('template_id'), + // 'scheduled_date' => $this->request->getPost('scheduled_date'), + // 'scheduled_time' => $this->request->getPost('scheduled_time') != "" ? $this->request->getPost('scheduled_time') : NULL, + 'mode' => $this->request->getPost('mode'), + 'group_id' => serialize($this->request->getPost('group_id')), + 'isactive' => $isactive, + 'created_by' => $session_uid, + 'updated_by' => $session_uid + ]; + if ($id != "") { + // id has value means updation process. + $notify_mod = new NotificationModel(); + $notify_mod->setTable('notification_campaign'); + $where = ['campaign_id' => (int)$id]; + $isactive_check = $notify_mod->where($where)->select('isactive')->first(); + if ((int)$isactive_check['isactive'] === 0 && $isactive === 0) { + $statement['success'] = ''; + $statement['error'] = 'Notification Campaign already In-Active. can`t able to update.'; + $statement['log'] = "Notification Campaign: already inactive status.Can`t able to update, Notification Campaign Group ID = " . $id; + } else { + $statement = $model->saveDetails($data, 'campaign_id', 'notification_campaign'); + } + } else { + // id has no value means insertion process. + $statement = $model->saveDetails($data, 'campaign_id', 'notification_campaign'); + } + + if ($statement['success']) { + $tid = $data['template_id']; + $cid = $data['campaign_id'] ? $data['campaign_id'] : $statement['insert_id']; + $this->scheduledNotifications($tid,$cid,1); + session()->setFlashdata('success', $statement['success']); + $this->logger->error($statement['log']); + } else if ($statement['error']) { + session()->setFlashdata('error', $statement['error']); + $this->logger->error($statement['log']); + } else { + throw new \Exception("Campaign: Err Occur"); + } + } catch (\Exception $e) { + $this->logger->error("Campaign: Err Occur =" . $e->getMessage()); + session()->setFlashdata('error', 'Message: ' . $e->getMessage()); + } + return redirect()->route('campaign_creation'); + } + + ################################################################ + # Expiry Notification ReferWith : Hema + ################################################################ + public function getExpCustomerDetail($window_time = null) + { + echo "Hi, "; + # Step 1: add the days to retrive the data// + $providedDate = date('Y-m-d'); + $newDate = date('Y-m-d', strtotime($providedDate . ' + ' . $window_time . ' days')); + $this->logger->error('EXPIRYDATE T-Date = '.$providedDate.', Given ' .$window_time.' Day, Calacuated Date based on Given day count = '.$newDate); + + # Step 2 :Get the customer detail// + $NotificationModel = new NotificationModel(); + $ExpCustomerDetail = $NotificationModel->getExpDate(); // Retrieve the stored query + + if (empty($ExpCustomerDetail)) { + $this->logger->error('No customer group found by the name of EXPIRYDATE'); + return; + } + + # Step 3: Replace the placeholder WINDOW_TIME with the user-provided value + $modifiedQuery = str_replace('WINDOW_TIME', $window_time, $ExpCustomerDetail); + // print_r($modifiedQuery);die; + if (empty($modifiedQuery)) { + $this->logger->error('There is no sub query'); + return; + } + $db = \Config\Database::connect(); + $queryResult = $db->query($modifiedQuery)->getResultArray(); + + $notification = new NotificationHelper(); + if (empty($queryResult)) { + $this->logger->error("There is no customer expiring on date:{$newDate}"); + echo " There is no customer expiring. till dated :{$newDate}"; + return; + } + + $emailTemplateName = $NotificationModel->getTempName(EXPIRAY_NOTIFY_TEMPLATE_EMAIL); + echo "Started.
Customer expiring. till dated = ".$newDate."
There are ".count($queryResult)." persons
"; + foreach ($queryResult as $inx => $row) { + $status = $row['status']; + $userFirstName = $row['first_name']; + $userLastName = $row['last_name']; + $fullName = $userFirstName . ' ' . $userLastName; + $userMobileNumber = $row['mobile_no']; + $schemename = $row['title']; + $expirydate = $row['to_subscription']; + $customerId = $row['customer_id']; + $membership_id = $row['membership_id']; + if (empty($fullName)) { + $this->logger->error('There is no subcription Name'); + continue; + } + if ($status === 'Approved') { + # EXPIRAY_NOTIFY_TEMPLATE_EMAIL + $emailTemplateName = $NotificationModel->getTempName(EXPIRAY_NOTIFY_TEMPLATE_EMAIL); + echo "#".$customerId." - Person Name :".$fullName."
"; + if (count($emailTemplateName) && !empty($emailTemplateName)) { + $campaign_id = 1; + # Insertion on History Email Means Campaign ID 1 Hardcoded + $history_parents_data = ['campaign_id' => $campaign_id,'status' => 0]; + $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); + + # Step 4: Prepare email content based on the template + $emailContent = $emailTemplateName[0]['message']; + if (isset($fullName)) { + $emailContent = str_replace("{USER_NAME}", $fullName, $emailContent); + } + if (isset($schemename)) { + $emailContent = str_replace("{SCHEME_NAME}", $schemename, $emailContent); + } + if (isset($expirydate)) { + $expiryon = $expirydate ? date('d-m-Y', strtotime($expirydate)) : ''; + $emailContent = str_replace("{EXPIRY_DATE}", $expiryon, $emailContent); + } + if (isset($membership_id)) { + $emailContent = str_replace("{RENEWAL_LINK}", base_url() . 'subscription_renewal/' . $membership_id, $emailContent); + } + + + + $emailData = [ + 'template_name' => 'EXPIRAY_NOTIFY_TEMPLATE_EMAIL', + 'recipient_email' => $row['email'], + 'subject' => 'Your Subscription Expiry Notification', + 'description' => $emailContent, + ]; + + + $history_child_data = [ 'fkid' => $history_parent_id, + 'customer_id' => $customerId, + 'receiving_entity' => $row['email'], + 'receiving_status' => 0, + 'message' => $emailContent]; + # Step 5: Insertion on History Child + $history_child_id = $NotificationModel->save_notification_history_child($history_child_data); + + # Step 6:Send email using NotificationHelper + $emailResult = $notification->sendEmail($emailData); + + $this->logger->error("EXPIRAY NOTIFY TEMPLATE EMAIL Email CID = ".$customerId." ".json_encode($emailResult)); + + if (isset($emailResult['success'])) { + $history_msg = 'Email sent successfully'; + $history_child_updatedata = ['receiving_status'=>1,'result'=>$history_msg]; + $history_child_where = ['fkid' => $history_parent_id,'id' => (int)$history_child_id]; + $history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata,$history_child_where); + $this->logger->error($history_child_statement); + + $history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,$campaign_id); + $this->logger->error($history_parent_statement); + echo ($inx+1).") ".$history_msg."
"; + } else { + $history_msg = (strtolower(gettype($emailResult)) == "string" ? $emailResult : json_encode($emailResult)) ; + $history_child_updatedata = ['receiving_status'=>0,'result'=>$history_msg]; + $history_child_where = ['fkid' => $history_parent_id,'id' => (int)$history_child_id]; + $history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata,$history_child_where); + $this->logger->error($history_child_statement); + + $history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,$campaign_id); + $this->logger->error($history_parent_statement); + echo ($inx+1).") Failed to send email
"; + } + } else { + $history_msg = 'There is no email template found by the name of EXPIRAY_NOTIFY_TEMPLATE_EMAIL'; + // $receiving_status = 0 ; + $this->logger->error($history_msg); + echo $history_msg."
"; + continue; + } + + } + else{ + $this->logger->error("status is Draft"); + } + # EXPIRAY_NOTIFY_TEMPLATE_EMAIL Closed + if ($status === 'Approved') { + # EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP + $whatsappTemplateName = $NotificationModel->getTempName(EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP); + // print_r($whatsappTemplateName);die; + if ((count($whatsappTemplateName) > 0) && !empty($whatsappTemplateName)) { + $campaign_id = 2; // hardcoded because static Template. + $history_parents_data = ['campaign_id' => 2,'status' => 0]; + $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); + if (empty($userMobileNumber)) { + $history_msg = 'There is no subscriber mobile number'; + $history_child_updatedata = ['receiving_status'=>0,'result'=>$history_msg]; + $history_child_where = ['fkid' => $history_parent_id,'id' => (int)$history_child_id]; + $history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata,$history_child_where); + $this->logger->error($history_child_statement); + + $history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,$campaign_id); + $this->logger->error($history_parent_statement); + $this->logger->error($history_msg); + echo ($inx+1).") ".$history_msg."
"; + continue; + } + # Insertion on History Whatsapp Means Campaign ID 2 Hardcoded + $history_parents_data = ['campaign_id' => 2,'status' => 0]; + $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); + + # Step 7: Prepare whatsapp content based on the template + $whatsappContent = $whatsappTemplateName[0]['message']; + if (isset($fullName)) { + $whatsappContent = str_replace("{USER_NAME}", $fullName, $whatsappContent); + } + if (isset($schemename)) { + $whatsappContent = str_replace("{SCHEME_NAME}", $schemename, $whatsappContent); + } + if (isset($expirydate)) { + $expiryon = $expirydate ? date('d-m-Y', strtotime($expirydate)) : ''; + $whatsappContent = str_replace("{EXPIRY_DATE}", $expiryon, $whatsappContent); + } + if (isset($customerId)) { + $whatsappContent = str_replace("{RENEWAL_LINK}", base_url() . 'subscription_renewal/' . $customerId, $whatsappContent); + } + # Step 8: Insertion on History Child for whatsapp + $history_child_data = [ 'fkid' => $history_parent_id, + 'customer_id' => $customerId, + 'receiving_entity' => $userMobileNumber, + 'receiving_status' => 0, + 'message' => strip_tags(ltrim($whatsappContent))]; + $history_child_id = $NotificationModel->save_notification_history_child($history_child_data); + + + # Step 8: Send Whatsapp using NotificationHelper + $params = (object) Null; + $url = SEND_WAAI_URL; + $params->number = (int)'91' . $userMobileNumber; + $params->type = "text"; + $params->message = strip_tags(ltrim($whatsappContent)); + $params->instance_id = $_ENV['WAAI_INSTANCE']; + $params->access_token = $_ENV['WAAI_TOKEN']; + $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Request = " . json_encode($params)); + $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Request type b4 = " . gettype($params)); + $whatsapp_result = $notification->sendWhatsAppMessage($url, "POST", $params); + $receiving_status = $whatsapp_result['receiving_status']; + $history_msg = strtolower(gettype($whatsapp_result)) == "string" ? $whatsapp_result : json_encode($whatsapp_result['reponse']); + $history_child_updatedata = ['receiving_status'=>$receiving_status,'result'=>$history_msg]; + $history_child_where = ['fkid' => $history_parent_id,'id' => (int)$history_child_id]; + $history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata,$history_child_where); + $this->logger->error($history_child_statement); + + $history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,$campaign_id); + $this->logger->error($history_parent_statement); + $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Reponse = " . $history_msg); + + if(strtolower(gettype($whatsapp_result)) == "string"){ + echo ($inx+1).") ".$whatsapp_result."
"; + } + else{ + $result = json_encode($whatsapp_result['reponse']); + $decodedResult = json_decode($result, true); + if ($decodedResult && isset($decodedResult['message']['key']['remoteJid'])) { + $remoteJid = $decodedResult['message']['key']['remoteJid']; + $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Remote Jid = " . $remoteJid); + echo ($inx+1).") Whatsapp sent successfully
"; + } else { + // echo "Failed to extract remoteJid"; + $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Failed to extract remoteJid "); + echo ($inx+1).") Failed to send Whatsapp
"; + } + } + } else { + // $receiving_status = 0; + $history_msg = 'There is no Whatsapp template found by the name of EXPIRAY NOTIFY TEMPLATE WHATSAPP '; + $this->logger->error($history_msg); + echo "There is no Whatsapp template
"; + continue; + } + + # EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP Closed + } + else{ + $this->logger->error("statsu is draft"); + } + + # Loop Closed + echo "Process Completed
"; + } +} + # getExpCustomerDetail fns Closed + + ################################################################ + # Auto Scheduled Notification + ################################################################ + ## notification campaign details + public function processScheduledNotifications(){ + $this->scheduledNotifications(0,0,0); + // parameter are template_id is zero , campaign_id is zero , dummy is zero + } + + public function scheduledNotifications($tid,$cid,$dummyvariable){ + $this->logger->error("Auto Scheduled Notification Started"); + $model = new NotificationModel(); + #step 1 get scheduled notification details + $notification_campaign_result = $this->getScheduledNotificationDetails($tid,$cid); + $this->logger->error("Auto Scheduled Campaign Details Count = ".count($notification_campaign_result)); + if(!count($notification_campaign_result)) + { + $this->logger->error("No Auto Scheduled Notification in DB,exiting...!"); + $this->logger->error("Auto Scheduled Notification Ends"); + if($dummyvariable == 0){ + echo "No Scheduled Data Founded"."
"; + exit(); + } + } + // echo "Notification campaign Result Array in count = ".count($notification_campaign_result)."
"; + //looping multiple notification campaign + if(count($notification_campaign_result)) + { + foreach($notification_campaign_result as $index => $single_campaign) + { + if($dummyvariable == 0){ + echo "Notification Campaign Name = ".$single_campaign['campaign_name']."
"; + } + #step 2 get template details + $template = $this->getTemplateDetails($single_campaign['template_id']); + $customer_details = $this->getCustomerDetails($single_campaign['group_id']); + $this->logger->error("Auto Scheduled Template Details TID = ".$single_campaign['template_id']); + if(count($template) && count($customer_details)) + { + #step 3 execute the customer group query and return customer details + $sent_customer_details = []; + if(count($customer_details)) + { + #step 2.1 + $history_parents_data = ['campaign_id' => $single_campaign['campaign_id'],'status' => 0]; + $history_parent_id = $model->save_notification_history_parents($history_parents_data); + $single_campaign['history_parent_id'] = $history_parent_id; + + foreach($customer_details as $customer) + { + + $customer['customer_name'] = isset($customer['customer_name']) + ? $customer['customer_name'] + : (isset($customer['first_name']) && isset($customer['last_name']) + ? $customer['first_name'] . ' ' . $customer['last_name'] + : ''); + $customer['scheme_name'] = isset($customer['scheme_name']) ? $customer['scheme_name'] : (isset($customer['title']) ? $customer['title'] : ""); + $formatted_due_date = ""; + + if(isset($customer['to_subscription'])){ + $dateObj = date_create($customer['to_subscription']); + $formatted_due_date = date_format($dateObj, 'd-m-Y'); + }else{ + $formatted_due_date = $customer['formatted_due_date']; + } + $customer['formatted_due_date'] = $formatted_due_date; + + + #step 4 replace templates palceholders with data points + $notificationContent = $this->replaceTemplateWithDataPoints($template['message'],$customer); + $history_child_data = [ + 'fkid' => $single_campaign['history_parent_id'], + 'customer_id' => $customer['customer_id'], + 'receiving_entity' => $single_campaign['mode'] == 'Email' ? $customer['email'] : $customer['mobile_no'], + 'receiving_status' => 0, + 'message' => $notificationContent]; + $history_child_id = $model->save_notification_history_child($history_child_data); + //check wheather if notification send to the current customer already + if(!in_array($customer['customer_id'],$sent_customer_details)) + { + $this->logger->error("Auto Scheduled Customer CID = ".$customer['customer_id'].", CN = ".$customer['customer_name']); + #step 5 send notification + $notification = new NotificationHelper(); + if($single_campaign['mode'] == 'Email') + { + $email_response = $notification->sendEmail(array('recipient_email' => $customer['email'],'subject' => $template['subject'],'template_name' => $template['template_name'],'description' => $notificationContent)); + $mail_log = isset($email_response['success']) ? 'Email sent successfully' : 'Failed to send email'; + $receiving_status = isset($email_response['success']) ? 1 : 0; + $this->logger->error("Auto Scheduled Email CID = ".$customer['customer_id']." ".$mail_log); + + $history_child_where = ['fkid' => $single_campaign['history_parent_id'],'id' => (int)$history_child_id]; + $history_child_updatedata = ['receiving_status'=>$receiving_status, 'result'=>isset($email_response['success']) ? $mail_log : (strtolower(gettype($email_response)) == "string" ? $email_response : json_encode($email_response)) ]; + $history_child_statement = $model->update_notification_history_child($history_child_updatedata,$history_child_where); + $this->logger->error($history_child_statement); + + } + if($single_campaign['mode'] == 'Whatsapp') + { + $params = (object) Null; + $url = SEND_WAAI_URL; + $params->type = "text"; + $params->instance_id = $_ENV['WAAI_INSTANCE']; + $params->access_token = $_ENV['WAAI_TOKEN']; + $params->message = strip_tags(ltrim($notificationContent)); + $params->number = (int)'91' . $customer['mobile_no']; + $whatsapp_reponse = $notification->sendWhatsAppMessage($url, "POST", $params); + $whatsapp_reponse_msg = strtolower(gettype($whatsapp_reponse)) == "string" ? $whatsapp_reponse : json_encode($whatsapp_reponse['reponse']); + // echo "Whatsapp Response = ".$whatsapp_reponse_msg."
"; + $this->logger->error("Auto Scheduled Whatsapp CID = ".$customer['customer_id']." ".$whatsapp_reponse_msg); + $history_child_where = ['fkid' => $single_campaign['history_parent_id'],'id' => (int)$history_child_id]; + + $history_child_updatedata = ['receiving_status'=>$whatsapp_reponse['receiving_status'],'result'=>$whatsapp_reponse_msg]; + $history_child_statement = $model->update_notification_history_child($history_child_updatedata,$history_child_where); + $this->logger->error($history_child_statement); + + } + + array_push($sent_customer_details,$customer['customer_id']); + } + } + } + // #step 6 update campaign status to 1 + $statement = $model->update_notification_campaign_status(['status' => 1],$single_campaign['campaign_id']); + if($dummyvariable == 0){ echo "Final Campaign Status = ".$statement."
"; } + $this->logger->error($statement); + + #step 7 update history parent status to 1 + $history_parent_statement = $model->update_notification_history_parent_status(['status' => 1],$history_parent_id,$single_campaign['campaign_id']); + if($dummyvariable == 0){ echo "Final Acknowlegdement = ".$history_parent_statement."
"; } + $this->logger->error($history_parent_statement); + + } + } + } + } + + #step 1 get scheduled notification details + function getScheduledNotificationDetails($tid,$cid) + { + $model = new NotificationModel(); + if($tid == 0&&$cid == 0){ + $templateIds = [1, 2]; + $model->setTable('notification_campaign'); + $notification_campaign_result = $model->whereIn('template_id', $templateIds)->where('isactive', 1)->findAll(); + }else{ + $templateIds = [$tid]; + $model->setTable('notification_campaign'); + $notification_campaign_result = $model->whereIn('template_id', $templateIds)->where(['isactive'=>1,'campaign_id'=>$cid])->findAll(); + } + + // $today = date('Y-m-d'); + // $currentTime = date('H:i:s'); + // $endTime = date('H:i:s', strtotime('+30 minutes')); + // $where = ['scheduled_date' => $today,'isactive' => 1, + // 'scheduled_time >=' => $currentTime, + // 'scheduled_time <=' => $endTime + // ]; + // $model->setTable('notification_campaign'); + // $notification_campaign_result = $model->where($where)->findAll(); + // echo $model->getLastQuery(); + + return $notification_campaign_result; + } + + #step 2 get template details + function getTemplateDetails($template_id) + { + $model = new NotificationModel(); + $model->setTable('templates'); + $where = ['template_id'=>$template_id,'isactive'=>1]; + $result = $model->where($where)->first(); + return $result; + } + + #step 3 execute the customer group query and return customer details + function getCustomerDetails($group_ids) + { + $group_id_arr = unserialize($group_ids); + $this->logger->error("Auto Scheduled Customer Group CGID = ".implode(", ", $group_id_arr)); + $customer_details = []; + if(count($group_id_arr)) + { + foreach($group_id_arr as $group_id) + { + // echo "gid".$group_id; + $model = new NotificationModel(); + $model->setTable('customer_groups'); + $customer_group_result = $model->where(['group_id'=>$group_id,'isactive'=>1])->findAll(); + $db = \Config\Database::connect(); + if(count($customer_group_result)) + { + + $sql = (string)$customer_group_result[0]['group_query']; + $query = $db->query($sql); + $sql_group_results = $query->getResultArray(); + // print_r($sql_group_results); + $customer_details = array_merge($customer_details,$sql_group_results); + } + } + } + return $customer_details; + } + + #step 4 + function replaceTemplateWithDataPoints($originalTemplate,$dataPointsArray) + { + // print_r($dataPointsArray['customer_name']); + // echo $originalTemplate; + $notificationContent = $originalTemplate; + if (isset($dataPointsArray["customer_name"])) { + $notificationContent = str_replace("{USER_NAME}", $dataPointsArray["customer_name"], $notificationContent); + } + if (isset($dataPointsArray["scheme_name"])) { + $notificationContent = str_replace("{SCHEME_NAME}", $dataPointsArray["scheme_name"], $notificationContent); + } + if (isset($dataPointsArray["formatted_due_date"])) { + $expiryon = $dataPointsArray["formatted_due_date"] ? date('d-m-Y', strtotime($dataPointsArray["formatted_due_date"])) : ''; + $notificationContent = str_replace("{EXPIRY_DATE}", $expiryon, $notificationContent); + } + if (isset($dataPointsArray["customer_id"])) { + $notificationContent = str_replace("{RENEWAL_LINK}", base_url() . 'subscription_renewal/' . $dataPointsArray["customer_id"], $notificationContent); + } + return $notificationContent; + } + ############## Auto Scheduled Notification Ends ################ + + ################################################################ + # Notification Acknowlegdement + ################################################################ + ## notification acknowlegdement + public function noifications_acknowlegdement(){ + $model = new NotificationModel(); + $data['noifications_acknowlegdement'] = $model->get_noifications_acknowlegdement_data(); + $data['page_name'] = 'Notifications Status'; + $this->render_page('noifications_acknowlegdement', $data); + } + ############## Notification Acknowlegdement Ends ################ +} diff --git a/app/Controllers/Notifications.php b/app/Controllers/Notifications.php index 6f271b3b..3ee16d89 100755 --- a/app/Controllers/Notifications.php +++ b/app/Controllers/Notifications.php @@ -619,11 +619,44 @@ class Notifications extends BaseController if (empty($fullName)) { $this->logger->error('There is no subcription Name'); continue; - } + } if ($status === 'Approved') { # EXPIRY NOTIFY TEMPLATE EMAIL $emailTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE EMAIL'); - echo "#".$customerId." - Person Name :".$fullName."
"; + echo "#".$customerId." - Person Name :".$fullName." ----- ( Expiry on ". $expirydate.")
"; + if(empty($row['email'])){ + echo ($inx+1).") Email Not Available
"; + continue; + } + + $existingcheck = $NotificationModel->checkEmailAlreadyExisting($row['email'],$customerId); + $check_existing = 0; + $check_date = ""; + $check_diff_days = ""; + + if(!empty($existingcheck)){ + + foreach ($existingcheck as $i => $r) { + if($r['receiving_status'] == 1){ + $check_existing = 1; + $check_date = $r['sent_time']; + $sentTimestamp = strtotime($r['sent_time']); + $provedTimestamp = strtotime($providedDate); + + + $diffInSeconds = abs($provedTimestamp - $sentTimestamp); + $diffInDays = $diffInSeconds / (60 * 60 * 24); + + $check_diff_days = $diffInDays; + } + } + } + + if($check_existing){ + echo ($inx+1).") Email already send on - ".$check_date."
"; + continue; + } + if (count($emailTemplateName) && !empty($emailTemplateName)) { $campaign_id = 1; # Insertion on History Email Means Campaign ID 1 Hardcoded @@ -704,6 +737,35 @@ class Notifications extends BaseController } # EXPIRY NOTIFY TEMPLATE EMAIL Closed if ($status === 'Approved') { + + + $existingcheck2 = $NotificationModel->checkEmailAlreadyExisting($userMobileNumber,$customerId); + $check_existing2 = 0; + $check_date2 = ""; + $check_diff_days2 = ""; + + if(!empty($existingcheck2)){ + + foreach ($existingcheck2 as $i2 => $r2) { + if($r2['receiving_status'] == 1){ + $check_existing2 = 1; + $check_date2 = $r2['sent_time']; + $sentTimestamp2 = strtotime($r2['sent_time']); + $provedTimestamp2 = strtotime($providedDate); + + + $diffInSeconds2 = abs($provedTimestamp2 - $sentTimestamp2); + $diffInDays2 = $diffInSeconds2 / (60 * 60 * 24); + + $check_diff_days2 = $diffInDays2; + } + } + } + + if($check_existing2){ + echo ($inx+1).") whatsapp already send ".$check_date2."
"; + continue; + } # EXPIRY NOTIFY TEMPLATE WHATSAPP $whatsappTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE WHATSAPP'); // print_r($whatsappTemplateName);die; @@ -817,7 +879,7 @@ class Notifications extends BaseController $model->where('to_subscription <', $currentDate) ->set(['status' => 0]) ->update(); - log_message('info','inside the update function'); + log_message('error','inside the update function'); } # getExpCustomerDetail fns Closed diff --git a/app/Models/NotificationModel.php b/app/Models/NotificationModel.php index 6237fc2e..18fd6de0 100755 --- a/app/Models/NotificationModel.php +++ b/app/Models/NotificationModel.php @@ -177,11 +177,10 @@ public function customerGroupQueryExecution($queries){ } } - public function getTempName($constant) + public function getTempName($name) { $db = \Config\Database::connect(); - $query = "SELECT * FROM templates WHERE isactive = 1 AND template_name = '".$constant."'"; -// print_r($query);die; + $query = "SELECT * FROM templates WHERE isactive = 1 AND template_name = '".$name."'"; $result = $db->query($query)->getResultArray(); if (isset($result)) { return $result; @@ -319,6 +318,14 @@ public function customerGroupQueryExecution($queries){ return count($arr)>0 ? $arr : []; } + public function checkEmailAlreadyExisting($email,$customerId){ + return $this->db->table('notification_history_children as nhc' ) + ->join('customers as C', 'C.customer_id = nhc.customer_id', 'left') + ->where('nhc.receiving_entity =',$email) + ->where('C.customer_id =',$customerId) + ->where('nhc.sent_time >=', date('Y-m-d H:i:s', strtotime('-30 days'))) + ->get()->getResultArray(); + } }