FEAT_SMS_INTEGRATION

This commit is contained in:
Srinivas-Saravanan 2025-04-30 16:23:29 +05:30
parent c45493eb0a
commit f04d40a452
7 changed files with 808 additions and 563 deletions

View File

@ -39,8 +39,10 @@ class Email extends BaseConfig
/** /**
* SMTP Password * SMTP Password
*/ */
// public string $SMTPPass = 'Sz9VueQ2iLgH'; // public string $SMTPPass = 'Sz9VueQ2iLgH'; old zoho pwd
public string $SMTPPass = 'xmxwgnccaekefasa'; public string $SMTPPass = 'xmxwgnccaekefasa';
// public string $SMTPPass = 'FdnFgsqdKgkR'; new zoho pwd
/** /**
* SMTP Port * SMTP Port

View File

@ -210,6 +210,7 @@ $routes->get('/list_log','Payment::listLogs');
$routes->get('/download_log/(:any)','Payment::downloadLog/$1'); $routes->get('/download_log/(:any)','Payment::downloadLog/$1');
$routes->get('/view_log/(:any)','Payment::viewLog/$1'); $routes->get('/view_log/(:any)','Payment::viewLog/$1');
$routes->get("testSMS","Payment::testSMS");
// $routes->group("api", function ($routes) { // $routes->group("api", function ($routes) {

View File

@ -7,18 +7,28 @@ use App\Models\NotificationModel;
use App\Models\SubscriptionModel; use App\Models\SubscriptionModel;
use DateTime; use DateTime;
use App\Helpers\SendSMSHelper;
use Exception;
class Notifications extends BaseController class Notifications extends BaseController
{ {
protected $smsHelper;
public function __construct()
{
$this->smsHelper = new SendSMSHelper();
}
################################################################ ################################################################
# Custom Notification # Custom Notification
################################################################ ################################################################
public function custom_notifications(){ public function custom_notifications()
{
$data['page_name'] = 'Custom Notifications'; $data['page_name'] = 'Custom Notifications';
if ($this->request->is('post')) { if ($this->request->is('post')) {
session()->setFlashdata('reset', true); session()->setFlashdata('reset', true);
$records = $this->request->getVar(); $records = $this->request->getVar();
if($records['mode'] == 'Email'){ if ($records['mode'] == 'Email') {
helper('notification'); helper('notification');
$notification = new NotificationHelper(); $notification = new NotificationHelper();
$records['description'] = $records['maildescription']; $records['description'] = $records['maildescription'];
@ -35,20 +45,21 @@ class Notifications extends BaseController
$receiving_status = 1; $receiving_status = 1;
$history_msg = 'Email sent successfully'; $history_msg = 'Email sent successfully';
} }
$history_msg = (strtolower(gettype($history_msg)) == "string" ? $history_msg : json_encode($history_msg)) ; $history_msg = (strtolower(gettype($history_msg)) == "string" ? $history_msg : json_encode($history_msg));
$NotificationModel = new NotificationModel(); $NotificationModel = new NotificationModel();
$history_parents_data = ['campaign_id' => 0,'status' => $parents_status]; $history_parents_data = ['campaign_id' => 0, 'status' => $parents_status];
$history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
$history_child_data = [ 'fkid' => $history_parent_id, $history_child_data = [
'fkid' => $history_parent_id,
'customer_id' => 0, 'customer_id' => 0,
'receiving_entity' => $records['recipient_email'], 'receiving_entity' => $records['recipient_email'],
'receiving_status' => $receiving_status, 'receiving_status' => $receiving_status,
'message' => $records['description'], 'message' => $records['description'],
'result'=>strtolower(gettype($history_msg)) == "string" ? $history_msg : json_encode($history_msg)]; 'result' => strtolower(gettype($history_msg)) == "string" ? $history_msg : json_encode($history_msg)
];
$history_child_id = $NotificationModel->save_notification_history_child($history_child_data); $history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
$this->logger->error('Custom Notifications Email : historychildid = '.$history_child_id); $this->logger->error('Custom Notifications Email : historychildid = ' . $history_child_id);
} else {
}else{
$records = $this->request->getVar(); $records = $this->request->getVar();
$doc_details = $this->request->getFile('media_doc'); $doc_details = $this->request->getFile('media_doc');
$params = (object) Null; $params = (object) Null;
@ -58,7 +69,7 @@ class Notifications extends BaseController
$doc_name = ''; $doc_name = '';
$errorMessages = []; $errorMessages = [];
$this->logger->error("Whatsapp : sending message instance id = " . $_ENV['WAAI_INSTANCE'] . " - " . $_ENV['WAAI_TOKEN']); $this->logger->error("Whatsapp : sending message instance id = " . $_ENV['WAAI_INSTANCE'] . " - " . $_ENV['WAAI_TOKEN']);
if($records['mobile'] != ""){ if ($records['mobile'] != "") {
$string = $records['mobile']; $string = $records['mobile'];
$mobile_no_arr = explode(',', $string); $mobile_no_arr = explode(',', $string);
$total_number_count = count($mobile_no_arr); $total_number_count = count($mobile_no_arr);
@ -74,7 +85,7 @@ class Notifications extends BaseController
$this->render_page('notifications_form', $data); $this->render_page('notifications_form', $data);
return; return;
} }
}else if ($records['categories'] == 'SEND_WAAI_URL') { } else if ($records['categories'] == 'SEND_WAAI_URL') {
if ($records['mobile'] == "") { if ($records['mobile'] == "") {
session()->setFlashdata('error', 'Mobile Number Missing Please Try again..'); session()->setFlashdata('error', 'Mobile Number Missing Please Try again..');
$data['page_name'] = 'Custom Notifications'; $data['page_name'] = 'Custom Notifications';
@ -99,7 +110,7 @@ class Notifications extends BaseController
$this->render_page('notifications_form', $data); $this->render_page('notifications_form', $data);
return; return;
} }
}elseif ($records['type'] == 'document') { } elseif ($records['type'] == 'document') {
$doc_details = $this->request->getFile('media_doc'); $doc_details = $this->request->getFile('media_doc');
$doc_path = APPPATH . '../public/uploads/'; $doc_path = APPPATH . '../public/uploads/';
@ -131,15 +142,15 @@ class Notifications extends BaseController
$params->media_url = base_url() . 'public/uploads/' . $doc_name; $params->media_url = base_url() . 'public/uploads/' . $doc_name;
$params->type = "media"; $params->type = "media";
$this->logger->error("Name After Upload: " . $doc_name); $this->logger->error("Name After Upload: " . $doc_name);
}else{ } else {
$params->type = "text" ; $params->type = "text";
} }
$NotificationModel = new NotificationModel(); $NotificationModel = new NotificationModel();
$history_parents_data = ['campaign_id' => 0,'status' => 0,'field_value' =>$records['mobile']]; $history_parents_data = ['campaign_id' => 0, 'status' => 0, 'field_value' => $records['mobile']];
$history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
// print_r($mobile_no_arr); // print_r($mobile_no_arr);
if(!empty($mobile_no_arr)){ if (!empty($mobile_no_arr)) {
foreach ($mobile_no_arr as $mobile) { foreach ($mobile_no_arr as $mobile) {
// try { // try {
$exceptionOccurred = false; $exceptionOccurred = false;
@ -152,14 +163,14 @@ class Notifications extends BaseController
$params->instance_id = $_ENV['WAAI_INSTANCE']; $params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN']; $params->access_token = $_ENV['WAAI_TOKEN'];
$params->message = strip_tags(ltrim($records['description'])); $params->message = strip_tags(ltrim($records['description']));
$this->logger->error("Whatsapp : Request Type ==> Mobile Number = ".$mobile." - " . gettype($params)); $this->logger->error("Whatsapp : Request Type ==> Mobile Number = " . $mobile . " - " . gettype($params));
helper('notification'); helper('notification');
$notification = new NotificationHelper(); $notification = new NotificationHelper();
$success = $notification->sendWhatsAppMessage($url, "POST", $params); $success = $notification->sendWhatsAppMessage($url, "POST", $params);
// echo "<pre>";print_r($success);echo "</pre>"; // echo "<pre>";print_r($success);echo "</pre>";
$receiving_status = $success['receiving_status']; $receiving_status = $success['receiving_status'];
$parents_status = $success['receiving_status']; $parents_status = $success['receiving_status'];
$this->logger->error("Whatsapp : Reponse ==> Mobile Number = ".$mobile." Waai Reponse = ". json_encode($success['reponse'])); $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']); $history_msg = strtolower(gettype($success)) == "string" ? $success : json_encode($success['reponse']);
// $tag = (int)$receiving_status === 1 ? 'success' : 'error' ; // $tag = (int)$receiving_status === 1 ? 'success' : 'error' ;
// session()->setFlashdata($tag, 'Message : ' . $success['message']); // session()->setFlashdata($tag, 'Message : ' . $success['message']);
@ -167,67 +178,67 @@ class Notifications extends BaseController
} else { } else {
$receiving_status = 0; $receiving_status = 0;
$parents_status = 0; $parents_status = 0;
$history_msg = "Mobile Number = ".$mobile." is invalid."; $history_msg = "Mobile Number = " . $mobile . " is invalid.";
$this->logger->error("Whatsapp : Reponse ==> ".$history_msg); $this->logger->error("Whatsapp : Reponse ==> " . $history_msg);
$not_sended_number_count++; $not_sended_number_count++;
$errorMessages[] = $history_msg; $errorMessages[] = $history_msg;
} }
}elseif (ctype_alpha($mobile)) { } elseif (ctype_alpha($mobile)) {
$receiving_status = 0; $receiving_status = 0;
$parents_status = 0; $parents_status = 0;
$history_msg = "Mobile Number = ".$mobile." is a character."; $history_msg = "Mobile Number = " . $mobile . " is a character.";
$this->logger->error("Whatsapp : Reponse ==> ".$history_msg); $this->logger->error("Whatsapp : Reponse ==> " . $history_msg);
$not_sended_number_count++; $not_sended_number_count++;
$errorMessages[] = $history_msg; $errorMessages[] = $history_msg;
} else {
}else {
$receiving_status = 0; $receiving_status = 0;
$parents_status = 0; $parents_status = 0;
$history_msg = "Mobile Number = ".$mobile." is a combination of characters and numbers."; $history_msg = "Mobile Number = " . $mobile . " is a combination of characters and numbers.";
$this->logger->error("Whatsapp : Reponse ==> ".$history_msg); $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++; $not_sended_number_count++;
$errorMessages[] = $history_msg; $errorMessages[] = $history_msg;
} }
$history_child_data = [ 'fkid' => $history_parent_id, } 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, 'customer_id' => 0,
'receiving_entity' => $mobile, 'receiving_entity' => $mobile,
'receiving_status' => $receiving_status, 'receiving_status' => $receiving_status,
'message' => $records['description'], 'message' => $records['description'],
'result'=>$history_msg]; 'result' => $history_msg
];
$NotificationModel = new NotificationModel(); $NotificationModel = new NotificationModel();
$history_child_id = $NotificationModel->save_custom_notification_history_child($history_child_data); $history_child_id = $NotificationModel->save_custom_notification_history_child($history_child_data);
$this->logger->error('Custom Notifications Whatsapp : historychildid = '.$history_child_id); $this->logger->error('Custom Notifications Whatsapp : historychildid = ' . $history_child_id);
} }
if (!empty($errorMessages)) { if (!empty($errorMessages)) {
$this->logger->error(implode("\n", $errorMessages)); $this->logger->error(implode("\n", $errorMessages));
session()->setFlashdata('error', implode('<br>', $errorMessages)); session()->setFlashdata('error', implode('<br>', $errorMessages));
$errorMessages = []; $errorMessages = [];
} }
if($sended_number_count > 0){ if ($sended_number_count > 0) {
$NotificationModel = new NotificationModel(); $NotificationModel = new NotificationModel();
$history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,0); $history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1], $history_parent_id, 0);
$this->logger->error($history_parent_statement); $this->logger->error($history_parent_statement);
session()->setFlashdata("success","Message : Sent Success (". $sended_number_count." / ".$total_number_count." )"); 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." ) "); $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'; $data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data); $this->render_page('notifications_form', $data);
return; return;
}else{ } else {
session()->setFlashdata('error', 'Message : Mobile Not Founded'); session()->setFlashdata('error', 'Message : Mobile Not Founded');
$this->logger->error('Message : Mobile Not Founded'); $this->logger->error('Message : Mobile Not Founded');
$data['page_name'] = 'Custom Notifications'; $data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data); $this->render_page('notifications_form', $data);
return; return;
} }
}else{ } else {
session()->setFlashdata('error', 'Message : Mobile Field Empty'); session()->setFlashdata('error', 'Message : Mobile Field Empty');
$this->logger->error('Message : Mobile Field Empty'); $this->logger->error('Message : Mobile Field Empty');
$data['page_name'] = 'Custom Notifications'; $data['page_name'] = 'Custom Notifications';
@ -391,7 +402,7 @@ class Notifications extends BaseController
$model->setTable('templates'); $model->setTable('templates');
$details = $model $details = $model
->where(['templates.isactive' => 1]) ->where(['templates.isactive' => 1])
->whereNotIn('templates.template_name',array('EXPIRY NOTIFY TEMPLATE EMAIL','EXPIRY NOTIFY TEMPLATE WHATSAPP')) ->whereNotIn('templates.template_name', array('EXPIRY NOTIFY TEMPLATE EMAIL', 'EXPIRY NOTIFY TEMPLATE WHATSAPP'))
->orderBy('templates.template_id', 'ASC')->findAll(); ->orderBy('templates.template_id', 'ASC')->findAll();
return $details; return $details;
} }
@ -408,9 +419,9 @@ class Notifications extends BaseController
$subject = $this->request->getPost('subject') ? $this->request->getPost('subject') : NULL; $subject = $this->request->getPost('subject') ? $this->request->getPost('subject') : NULL;
$isactive = $id != "" ? $this->request->getPost('isactive') : 'on'; $isactive = $id != "" ? $this->request->getPost('isactive') : 'on';
$templatemessage = ""; $templatemessage = "";
if($this->request->getPost('mode') === "Email"){ if ($this->request->getPost('mode') === "Email") {
$templatemessage = $this->request->getPost('templatemessage'); $templatemessage = $this->request->getPost('templatemessage');
}else if($this->request->getPost('mode') === "Whatsapp"){ } else if ($this->request->getPost('mode') === "Whatsapp") {
$templatemessage = $this->request->getPost('whatsapptemplatemessage'); $templatemessage = $this->request->getPost('whatsapptemplatemessage');
} }
@ -551,7 +562,7 @@ class Notifications extends BaseController
if ($statement['success']) { if ($statement['success']) {
$tid = $data['template_id']; $tid = $data['template_id'];
$cid = $data['campaign_id'] ? $data['campaign_id'] : $statement['insert_id']; $cid = $data['campaign_id'] ? $data['campaign_id'] : $statement['insert_id'];
$this->scheduledNotifications($tid,$cid,1); $this->scheduledNotifications($tid, $cid, 1);
session()->setFlashdata('success', $statement['success']); session()->setFlashdata('success', $statement['success']);
$this->logger->error($statement['log']); $this->logger->error($statement['log']);
} else if ($statement['error']) { } else if ($statement['error']) {
@ -570,7 +581,7 @@ class Notifications extends BaseController
################################################################ ################################################################
# Expiry Notification ReferWith : Hema # Expiry Notification ReferWith : Hema
################################################################ ################################################################
public function getExpCustomerDetail($window_time = null,$to_time = null) public function getExpCustomerDetail($window_time = null, $to_time = null)
{ {
// dd($window_time); // dd($window_time);
// $valid_dates = [0,1,7,15,30]; // $valid_dates = [0,1,7,15,30];
@ -579,26 +590,26 @@ class Notifications extends BaseController
// } // }
$NotificationModel = new NotificationModel(); $NotificationModel = new NotificationModel();
$this->update_expired_members(); $this->update_expired_members();
$response ="<pre>";// $response = "<pre> Hi, Started. <br>"; $response = "<pre>"; // $response = "<pre> Hi, Started. <br>";
# Step 1: add the days to retrive the data// # Step 1: add the days to retrive the data//
$providedDate = date('Y-m-d'); $providedDate = date('Y-m-d');
// if ($this->request->getmethod() == 'post') { // if ($this->request->getmethod() == 'post') {
// $window_time = $this->request->getGet('params'); // $window_time = $this->request->getGet('params');
// } // }
// dd($window_time); // dd($window_time);
if ($window_time!= ''){ if ($window_time != '') {
if($window_time >= 0){ if ($window_time >= 0) {
$newDate = date('Y-m-d', strtotime("$providedDate + $window_time days")); $newDate = date('Y-m-d', strtotime("$providedDate + $window_time days"));
}else{ } else {
$newDate = date('Y-m-d', strtotime("$providedDate $window_time days")); $newDate = date('Y-m-d', strtotime("$providedDate $window_time days"));
} }
$ExpCustomerDetail = $NotificationModel->getExpDate(); // Retrieve the stored query $ExpCustomerDetail = $NotificationModel->getExpDate(); // Retrieve the stored query
// echo("Inside If"); // echo("Inside If");
// print_r(''.$ExpCustomerDetail);die(); // print_r(''.$ExpCustomerDetail);die();
}else{ } else {
$dateData = $this->request->getGet('to_date'); $dateData = $this->request->getGet('to_date');
$newDate = date('Y-m-d',strtotime($dateData)); $newDate = date('Y-m-d', strtotime($dateData));
$ExpCustomerDetail = $NotificationModel->getExpDate2(); $ExpCustomerDetail = $NotificationModel->getExpDate2();
} }
@ -610,13 +621,12 @@ class Notifications extends BaseController
$this->logger->error('No customer group found by the name of EXPIRYDATE'); $this->logger->error('No customer group found by the name of EXPIRYDATE');
return; return;
} }
if($window_time != ''){ if ($window_time != '') {
$modifiedQuery = str_replace('WINDOW_TIME', $window_time, $ExpCustomerDetail); $modifiedQuery = str_replace('WINDOW_TIME', $window_time, $ExpCustomerDetail);
//print_r($modifiedQuery);die; //print_r($modifiedQuery);die;
} } else {
else{
$from_date2 = $this->request->getGet('from_date'); $from_date2 = $this->request->getGet('from_date');
$to_date2 = $this->request->getGet('to_date'); $to_date2 = $this->request->getGet('to_date');
$from_date = DateTime::createFromFormat('d/m/Y', $from_date2)->format('Y-m-d'); $from_date = DateTime::createFromFormat('d/m/Y', $from_date2)->format('Y-m-d');
@ -624,7 +634,6 @@ class Notifications extends BaseController
// Add single quotes around the date values during the replacement // Add single quotes around the date values during the replacement
$modifiedQuery = str_replace('FROM_DATE', "'$from_date'", $ExpCustomerDetail); $modifiedQuery = str_replace('FROM_DATE', "'$from_date'", $ExpCustomerDetail);
$modifiedQuery = str_replace('TO_DATE', "'$to_date'", $modifiedQuery); $modifiedQuery = str_replace('TO_DATE', "'$to_date'", $modifiedQuery);
} }
if (empty($modifiedQuery)) { if (empty($modifiedQuery)) {
$this->logger->error('There is no sub query'); $this->logger->error('There is no sub query');
@ -636,14 +645,14 @@ class Notifications extends BaseController
$notification = new NotificationHelper(); $notification = new NotificationHelper();
if (empty($queryResult)) { if (empty($queryResult)) {
$this->logger->error("There is no customer expiring on date:{$newDate}"); $this->logger->error("There is no customer expiring on date:{$newDate}");
$response .= "There is no customer expiring. Date = ".date('d/m/Y', strtotime($newDate))." </pre>"; $response .= "There is no customer expiring. Date = " . date('d/m/Y', strtotime($newDate)) . " </pre>";
return $this->response->setBody($response); return $this->response->setBody($response);
} }
$emailTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE EMAIL'); $emailTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE EMAIL');
$this->logger->error("Customer expiring. till {$newDate} There are ".count($queryResult)." persons"); $this->logger->error("Customer expiring. till {$newDate} There are " . count($queryResult) . " persons");
$response .= "Customer expiring list. ( Date = ".date('d/m/Y', strtotime($newDate))." )<br>There are ".count($queryResult)." persons <br>"; $response .= "Customer expiring list. ( Date = " . date('d/m/Y', strtotime($newDate)) . " )<br>There are " . count($queryResult) . " persons <br>";
if(!empty($queryResult)){ if (!empty($queryResult)) {
usort($queryResult, function ($a, $b) { usort($queryResult, function ($a, $b) {
return $a['to_subscription'] <=> $b['to_subscription']; //Asc order return $a['to_subscription'] <=> $b['to_subscription']; //Asc order
}); });
@ -682,7 +691,7 @@ class Notifications extends BaseController
if (empty($existingEmailCheck)) { if (empty($existingEmailCheck)) {
$campaign_id = 1; $campaign_id = 1;
# Insertion on History Email Means Campaign ID 1 Hardcoded # Insertion on History Email Means Campaign ID 1 Hardcoded
$history_parents_data = ['campaign_id' => $campaign_id,'status' => 0]; $history_parents_data = ['campaign_id' => $campaign_id, 'status' => 0];
$history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
$emailContent = $emailTemplateName[0]['message']; $emailContent = $emailTemplateName[0]['message'];
@ -703,54 +712,55 @@ class Notifications extends BaseController
'subject' => 'Your Subscription Expiry Notification', 'subject' => 'Your Subscription Expiry Notification',
'description' => $emailContent, 'description' => $emailContent,
]; ];
$history_child_data = [ 'fkid' => $history_parent_id, $history_child_data = [
'fkid' => $history_parent_id,
'customer_id' => $customerId, 'customer_id' => $customerId,
'receiving_entity' => $email, 'receiving_entity' => $email,
'receiving_status' => 0, 'receiving_status' => 0,
'subscription_id' => $subscription_id, 'subscription_id' => $subscription_id,
'message' => $emailContent]; 'message' => $emailContent
];
$history_child_id = $NotificationModel->save_notification_history_child($history_child_data); $history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
$emailResult = $notification->sendEmail($emailData); $emailResult = $notification->sendEmail($emailData);
if (isset($emailResult['success']) && !empty($emailResult['success'])) { if (isset($emailResult['success']) && !empty($emailResult['success'])) {
$history_msg = 'Email sent successfully'; $history_msg = 'Email sent successfully';
$history_child_updatedata = ['receiving_status'=>1,'result'=>$history_msg]; $history_child_updatedata = ['receiving_status' => 1, 'result' => $history_msg];
$history_child_where = ['fkid' => $history_parent_id,'id' => (int)$history_child_id]; $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); $history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata, $history_child_where);
$this->logger->error($history_child_statement); $this->logger->error($history_child_statement);
$history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,$campaign_id); $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_parent_statement);
$response .= ($inx+1).") ".$history_msg."<br>"; $response .= ($inx + 1) . ") " . $history_msg . "<br>";
} else { } else {
$history_msg = (strtolower(gettype($emailResult)) == "string" ? $emailResult : json_encode($emailResult)) ; $history_msg = (strtolower(gettype($emailResult)) == "string" ? $emailResult : json_encode($emailResult));
$history_child_updatedata = ['receiving_status'=>0,'result'=>$history_msg]; $history_child_updatedata = ['receiving_status' => 0, 'result' => $history_msg];
$history_child_where = ['fkid' => $history_parent_id,'id' => (int)$history_child_id]; $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); $history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata, $history_child_where);
$this->logger->error($history_child_statement); $this->logger->error($history_child_statement);
$history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,$campaign_id); $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_parent_statement);
$response .= ($inx+1).") Failed to send email <br>"; $response .= ($inx + 1) . ") Failed to send email <br>";
} }
} else { } else {
$check_existing = 0; $check_existing = 0;
$check_email_date = ""; $check_email_date = "";
if(!empty($existingEmailCheck)){ if (!empty($existingEmailCheck)) {
foreach ($existingEmailCheck as $i => $r) { foreach ($existingEmailCheck as $i => $r) {
$check_email_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : ""; $check_email_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : "";
} }
} }
if($check_email_date){ if ($check_email_date) {
$response .= ($inx+1).") Email already send on - ".date('d/m/Y h:i A', strtotime($check_email_date))."<br>"; $response .= ($inx + 1) . ") Email already send on - " . date('d/m/Y h:i A', strtotime($check_email_date)) . "<br>";
$this->logger->error(($inx + 1) . ") Email already sent to {$email}"); $this->logger->error(($inx + 1) . ") Email already sent to {$email}");
$this->logger->error(($inx + 1) . ") Email already sent on {$check_email_date}"); $this->logger->error(($inx + 1) . ") Email already sent on {$check_email_date}");
} }
} }
} else { } else {
$response .= ($inx + 1) . ") No email template found<br>"; $response .= ($inx + 1) . ") No email template found<br>";
@ -758,97 +768,142 @@ class Notifications extends BaseController
} }
// WhatsApp Notification // WhatsApp Notification
$whatsappTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE WHATSAPP'); // $whatsappTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE WHATSAPP');
if (!empty($whatsappTemplateName)) { // if (!empty($whatsappTemplateName)) {
$existingWhatsAppCheck = $NotificationModel->checkAlreadyExistingInHistory($userMobileNumber, $customerId, $subscription_id); // $existingWhatsAppCheck = $NotificationModel->checkAlreadyExistingInHistory($userMobileNumber, $customerId, $subscription_id);
if (empty($existingWhatsAppCheck)) { // if (empty($existingWhatsAppCheck)) {
$campaign_id = 2; // $campaign_id = 2;
$history_parents_data = ['campaign_id' => $campaign_id,'status' => 0]; // $history_parents_data = ['campaign_id' => $campaign_id, 'status' => 0];
$history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data); // $history_parent_id = $NotificationModel->save_notification_history_parents($history_parents_data);
$whatsappContent = $whatsappTemplateName[0]['message']; // $whatsappContent = $whatsappTemplateName[0]['message'];
$whatsappContent = str_replace( // $whatsappContent = str_replace(
['{USER_NAME}', '{SCHEME_NAME}', '{EXPIRY_DATE}', '{RENEWAL_LINK}'], // ['{USER_NAME}', '{SCHEME_NAME}', '{EXPIRY_DATE}', '{RENEWAL_LINK}'],
[ // [
$fullName, // $fullName,
$schemename, // $schemename,
date('d-m-Y', strtotime($expirydate)), // date('d-m-Y', strtotime($expirydate)),
base_url() . 'subscription_renewal/' . $customerId, // base_url() . 'subscription_renewal/' . $customerId,
], // ],
$whatsappContent // $whatsappContent
// );
// $params = (object)[
// 'number' => '91' . $userMobileNumber,
// 'type' => 'text',
// 'message' => $whatsappContent,
// 'instance_id' => $_ENV['WAAI_INSTANCE'],
// 'access_token' => $_ENV['WAAI_TOKEN'],
// ];
// $whatsappResult = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
// $history_child_data = [
// 'fkid' => $history_parent_id,
// 'customer_id' => $customerId,
// 'receiving_entity' => $userMobileNumber,
// 'receiving_status' => 0,
// 'subscription_id' => $subscription_id,
// 'message' => strip_tags(ltrim($whatsappContent))
// ];
// $history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
// $receiving_status = $whatsappResult['receiving_status'];
// $history_msg = strtolower(gettype($whatsappResult)) == "string" ? $whatsappResult : json_encode($whatsappResult['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);
// if (strtolower(gettype($whatsappResult)) == "string") {
// $response .= ($inx + 1) . ") " . $whatsappResult . "<br>";
// } else {
// $result = json_encode($whatsappResult['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);
// $response .= ($inx + 1) . ") Whatsapp sent successfully <br>";
// } else {
// // echo "Failed to extract remoteJid";
// $this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Failed to extract remoteJid ");
// $response .= ($inx + 1) . ") Failed to send Whatsapp <br>";
// }
// }
// } else {
// $check_whatsapp_date = "";
// if (!empty($existingWhatsAppCheck)) {
// foreach ($existingWhatsAppCheck as $i => $r) {
// $check_whatsapp_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : "";
// }
// }
// if ($check_whatsapp_date) {
// $response .= ($inx + 1) . ") WhatsApp already send on - " . date('d/m/Y h:i A', strtotime($check_whatsapp_date)) . "<br>";
// $this->logger->error(($inx + 1) . ") WhatsApp already sent to {$userMobileNumber}");
// $this->logger->error(($inx + 1) . ") WhatsApp already sent on {$check_whatsapp_date}");
// }
// }
// } else {
// $response .= ($inx + 1) . ") No WhatsApp template found<br>";
// }
// SMS Notification
$smsTemplateName = $NotificationModel->getTempName('EXPIRY NOTIFY TEMPLATE SMS');
$this->logger->error("SMS Template Name : " . json_encode($smsTemplateName));
if (!empty($smsTemplateName)) {
$this->logger->error("Found SMS Template");
$existingSMSCheck = $NotificationModel->checkAlreadyExistingInHistory($userMobileNumber, $customerId, $subscription_id);
$this->logger->error("Existing SMS Check : " . json_encode($existingSMSCheck));
if (empty($existingSMSCheck)) {
try {
$template_message = $smsTemplateName[0]['message'];
$message = str_replace(
["{#USERNAME#}", "{#EXPIRY#}", "{#LINK#}"],
[$fullName, date('d-m-Y', strtotime($expirydate)), getenv("SMS_SUB_URL") . $membership_id],
$template_message
); );
$params = (object)[ $campaign_id = $NotificationModel->getCampaignID($smsTemplateName[0]['template_id']);
'number' => '91' . $userMobileNumber, $userMobileNumber = "91" . $userMobileNumber;
'type' => 'text',
'message' => $whatsappContent,
'instance_id' => $_ENV['WAAI_INSTANCE'],
'access_token' => $_ENV['WAAI_TOKEN'],
];
$whatsappResult = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params); $sent_status = $this->smsHelper->sendSMS($message, $userMobileNumber, $campaign_id,$membership_id);
$history_child_data = [ 'fkid' => $history_parent_id, $this->logger->error("Sent Status : ".json_encode($sent_status));
'customer_id' => $customerId, $history_msg = $sent_status;
'receiving_entity' => $userMobileNumber, $response .= ($inx + 1) . ") " . $history_msg . "<br>";
'receiving_status' => 0, } catch (Exception $e) {
'subscription_id' => $subscription_id,
'message' => strip_tags(ltrim($whatsappContent))];
$history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
$receiving_status = $whatsappResult['receiving_status'];
$history_msg = strtolower(gettype($whatsappResult)) == "string" ? $whatsappResult : json_encode($whatsappResult['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("Error while sending SMS: " . $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine());
$this->logger->error($history_parent_statement);
if(strtolower(gettype($whatsappResult)) == "string"){
$response .= ($inx+1).") ".$whatsappResult."<br>";
} }
else{
$result = json_encode($whatsappResult['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);
$response .= ($inx+1).") Whatsapp sent successfully <br>";
} else { } else {
// echo "Failed to extract remoteJid";
$this->logger->error("EXPIRAY NOTIFY TEMPLATE WHATSAPP Failed to extract remoteJid "); $check_sms_date = "";
$response .= ($inx+1).") Failed to send Whatsapp <br>"; foreach ($existingSMSCheck as $i => $r) {
$check_sms_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : "";
}
if ($check_sms_date) {
$response .= ($inx + 1) . ") SMS already send on - " . date('d/m/Y h:i A', strtotime($check_sms_date)) . "<br>";
$this->logger->error(($inx + 1) . ") SMS already sent to {$userMobileNumber}");
$this->logger->error(($inx + 1) . ") SMS already sent on {$check_sms_date}");
} }
} }
} else { } else {
$check_whatsapp_date = ""; $response .= ($inx + 1) . ") No SMS template found<br>";
if(!empty($existingWhatsAppCheck)){
foreach ($existingWhatsAppCheck as $i => $r) {
$check_whatsapp_date = ($r['receiving_status'] == 1) ? $r['sent_time'] : "";
}
}
if($check_whatsapp_date){
$response .= ($inx+1).") WhatsApp already send on - ".date('d/m/Y h:i A', strtotime($check_whatsapp_date))."<br>";
$this->logger->error(($inx + 1) . ") WhatsApp already sent to {$userMobileNumber}");
$this->logger->error(($inx + 1) . ") WhatsApp already sent on {$check_whatsapp_date}");
}
}
} else {
$response .= ($inx + 1) . ") No WhatsApp template found<br>";
} }
# Loop Closed # Loop Closed
} }
$response .= "Process Completed <br></pre>"; $response .= "Process Completed <br></pre>";
if ($this->request->getmethod() == 'get') { if ($this->request->getmethod() == 'get') {
return $response; return $response;
}else{ } else {
return $this->response->setBody($response); return $this->response->setBody($response);
} }
}
}
public function update_expired_members() public function update_expired_members()
{ {
@ -857,7 +912,7 @@ class Notifications extends BaseController
$model->where('to_subscription <', $currentDate) $model->where('to_subscription <', $currentDate)
->set(['status' => 0]) ->set(['status' => 0])
->update(); ->update();
log_message('error','inside the update function'); log_message('error', 'inside the update function');
} }
# getExpCustomerDetail fns Closed # getExpCustomerDetail fns Closed
@ -866,52 +921,48 @@ class Notifications extends BaseController
# Auto Scheduled Notification # Auto Scheduled Notification
################################################################ ################################################################
## notification campaign details ## notification campaign details
public function processScheduledNotifications(){ public function processScheduledNotifications()
$this->scheduledNotifications(0,0,0); {
$this->scheduledNotifications(0, 0, 0);
// parameter are template_id is zero , campaign_id is zero , dummy is zero // parameter are template_id is zero , campaign_id is zero , dummy is zero
} }
public function scheduledNotifications($tid,$cid,$dummyvariable){ public function scheduledNotifications($tid, $cid, $dummyvariable)
{
$this->logger->error("Auto Scheduled Notification Started"); $this->logger->error("Auto Scheduled Notification Started");
$model = new NotificationModel(); $model = new NotificationModel();
#step 1 get scheduled notification details #step 1 get scheduled notification details
$notification_campaign_result = $this->getScheduledNotificationDetails($tid,$cid); $notification_campaign_result = $this->getScheduledNotificationDetails($tid, $cid);
$this->logger->error("Auto Scheduled Campaign Details Count = ".count($notification_campaign_result)); $this->logger->error("Auto Scheduled Campaign Details Count = " . count($notification_campaign_result));
if(!count($notification_campaign_result)) if (!count($notification_campaign_result)) {
{
$this->logger->error("No Auto Scheduled Notification in DB,exiting...!"); $this->logger->error("No Auto Scheduled Notification in DB,exiting...!");
$this->logger->error("Auto Scheduled Notification Ends"); $this->logger->error("Auto Scheduled Notification Ends");
if($dummyvariable == 0){ if ($dummyvariable == 0) {
echo "No Scheduled Data Founded"."<br>"; echo "No Scheduled Data Founded" . "<br>";
exit(); exit();
} }
} }
// echo "Notification campaign Result Array in count = ".count($notification_campaign_result)."<br>"; // echo "Notification campaign Result Array in count = ".count($notification_campaign_result)."<br>";
//looping multiple notification campaign //looping multiple notification campaign
if(count($notification_campaign_result)) if (count($notification_campaign_result)) {
{ foreach ($notification_campaign_result as $index => $single_campaign) {
foreach($notification_campaign_result as $index => $single_campaign) if ($dummyvariable == 0) {
{ echo "Notification Campaign Name = " . $single_campaign['campaign_name'] . "<br>";
if($dummyvariable == 0){
echo "Notification Campaign Name = ".$single_campaign['campaign_name']."<br>";
} }
#step 2 get template details #step 2 get template details
$template = $this->getTemplateDetails($single_campaign['template_id']); $template = $this->getTemplateDetails($single_campaign['template_id']);
$customer_details = $this->getCustomerDetails($single_campaign['group_id']); $customer_details = $this->getCustomerDetails($single_campaign['group_id']);
$this->logger->error("Auto Scheduled Template Details TID = ".$single_campaign['template_id']); $this->logger->error("Auto Scheduled Template Details TID = " . $single_campaign['template_id']);
if(count($template) && count($customer_details)) if (count($template) && count($customer_details)) {
{
#step 3 execute the customer group query and return customer details #step 3 execute the customer group query and return customer details
$sent_customer_details = []; $sent_customer_details = [];
if(count($customer_details)) if (count($customer_details)) {
{
#step 2.1 #step 2.1
$history_parents_data = ['campaign_id' => $single_campaign['campaign_id'],'status' => 0]; $history_parents_data = ['campaign_id' => $single_campaign['campaign_id'], 'status' => 0];
$history_parent_id = $model->save_notification_history_parents($history_parents_data); $history_parent_id = $model->save_notification_history_parents($history_parents_data);
$single_campaign['history_parent_id'] = $history_parent_id; $single_campaign['history_parent_id'] = $history_parent_id;
foreach($customer_details as $customer) foreach ($customer_details as $customer) {
{
$customer['customer_name'] = isset($customer['customer_name']) $customer['customer_name'] = isset($customer['customer_name'])
? $customer['customer_name'] ? $customer['customer_name']
@ -921,45 +972,42 @@ class Notifications extends BaseController
$customer['scheme_name'] = isset($customer['scheme_name']) ? $customer['scheme_name'] : (isset($customer['title']) ? $customer['title'] : ""); $customer['scheme_name'] = isset($customer['scheme_name']) ? $customer['scheme_name'] : (isset($customer['title']) ? $customer['title'] : "");
$formatted_due_date = ""; $formatted_due_date = "";
if(isset($customer['to_subscription'])){ if (isset($customer['to_subscription'])) {
$dateObj = date_create($customer['to_subscription']); $dateObj = date_create($customer['to_subscription']);
$formatted_due_date = date_format($dateObj, 'd-m-Y'); $formatted_due_date = date_format($dateObj, 'd-m-Y');
}else{ } else {
$formatted_due_date = $customer['formatted_due_date']; $formatted_due_date = $customer['formatted_due_date'];
} }
$customer['formatted_due_date'] = $formatted_due_date; $customer['formatted_due_date'] = $formatted_due_date;
#step 4 replace templates palceholders with data points #step 4 replace templates palceholders with data points
$notificationContent = $this->replaceTemplateWithDataPoints($template['message'],$customer); $notificationContent = $this->replaceTemplateWithDataPoints($template['message'], $customer);
$history_child_data = [ $history_child_data = [
'fkid' => $single_campaign['history_parent_id'], 'fkid' => $single_campaign['history_parent_id'],
'customer_id' => $customer['customer_id'], 'customer_id' => $customer['customer_id'],
'receiving_entity' => $single_campaign['mode'] == 'Email' ? $customer['email'] : $customer['mobile_no'], 'receiving_entity' => $single_campaign['mode'] == 'Email' ? $customer['email'] : $customer['mobile_no'],
'receiving_status' => 0, 'receiving_status' => 0,
'message' => $notificationContent]; 'message' => $notificationContent
];
$history_child_id = $model->save_notification_history_child($history_child_data); $history_child_id = $model->save_notification_history_child($history_child_data);
//check wheather if notification send to the current customer already //check wheather if notification send to the current customer already
if(!in_array($customer['customer_id'],$sent_customer_details)) if (!in_array($customer['customer_id'], $sent_customer_details)) {
{ $this->logger->error("Auto Scheduled Customer CID = " . $customer['customer_id'] . ", CN = " . $customer['customer_name']);
$this->logger->error("Auto Scheduled Customer CID = ".$customer['customer_id'].", CN = ".$customer['customer_name']);
#step 5 send notification #step 5 send notification
$notification = new NotificationHelper(); $notification = new NotificationHelper();
if($single_campaign['mode'] == 'Email') if ($single_campaign['mode'] == 'Email') {
{ $email_response = $notification->sendEmail(array('recipient_email' => $customer['email'], 'subject' => $template['subject'], 'template_name' => $template['template_name'], 'description' => $notificationContent));
$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'; $mail_log = isset($email_response['success']) ? 'Email sent successfully' : 'Failed to send email';
$receiving_status = isset($email_response['success']) ? 1 : 0; $receiving_status = isset($email_response['success']) ? 1 : 0;
$this->logger->error("Auto Scheduled Email CID = ".$customer['customer_id']." ".$mail_log); $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_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_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); $history_child_statement = $model->update_notification_history_child($history_child_updatedata, $history_child_where);
$this->logger->error($history_child_statement); $this->logger->error($history_child_statement);
} }
if($single_campaign['mode'] == 'Whatsapp') if ($single_campaign['mode'] == 'Whatsapp') {
{
$params = (object) Null; $params = (object) Null;
$url = SEND_WAAI_URL; $url = SEND_WAAI_URL;
$params->type = "text"; $params->type = "text";
@ -970,46 +1018,48 @@ class Notifications extends BaseController
$whatsapp_reponse = $notification->sendWhatsAppMessage($url, "POST", $params); $whatsapp_reponse = $notification->sendWhatsAppMessage($url, "POST", $params);
$whatsapp_reponse_msg = strtolower(gettype($whatsapp_reponse)) == "string" ? $whatsapp_reponse : json_encode($whatsapp_reponse['reponse']); $whatsapp_reponse_msg = strtolower(gettype($whatsapp_reponse)) == "string" ? $whatsapp_reponse : json_encode($whatsapp_reponse['reponse']);
// echo "Whatsapp Response = ".$whatsapp_reponse_msg."<br>"; // echo "Whatsapp Response = ".$whatsapp_reponse_msg."<br>";
$this->logger->error("Auto Scheduled Whatsapp CID = ".$customer['customer_id']." ".$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_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_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); $history_child_statement = $model->update_notification_history_child($history_child_updatedata, $history_child_where);
$this->logger->error($history_child_statement); $this->logger->error($history_child_statement);
} }
array_push($sent_customer_details,$customer['customer_id']); array_push($sent_customer_details, $customer['customer_id']);
} }
} }
} }
// #step 6 update campaign status to 1 // #step 6 update campaign status to 1
$statement = $model->update_notification_campaign_status(['status' => 1],$single_campaign['campaign_id']); $statement = $model->update_notification_campaign_status(['status' => 1], $single_campaign['campaign_id']);
if($dummyvariable == 0){ echo "Final Campaign Status = ".$statement."<br>"; } if ($dummyvariable == 0) {
echo "Final Campaign Status = " . $statement . "<br>";
}
$this->logger->error($statement); $this->logger->error($statement);
#step 7 update history parent status to 1 #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']); $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."<br>"; } if ($dummyvariable == 0) {
echo "Final Acknowlegdement = " . $history_parent_statement . "<br>";
}
$this->logger->error($history_parent_statement); $this->logger->error($history_parent_statement);
} }
} }
} }
} }
#step 1 get scheduled notification details #step 1 get scheduled notification details
function getScheduledNotificationDetails($tid,$cid) function getScheduledNotificationDetails($tid, $cid)
{ {
$model = new NotificationModel(); $model = new NotificationModel();
if($tid == 0&&$cid == 0){ if ($tid == 0 && $cid == 0) {
$templateIds = [1, 2]; $templateIds = [1, 2];
$model->setTable('notification_campaign'); $model->setTable('notification_campaign');
$notification_campaign_result = $model->whereIn('template_id', $templateIds)->where('isactive', 1)->findAll(); $notification_campaign_result = $model->whereIn('template_id', $templateIds)->where('isactive', 1)->findAll();
}else{ } else {
$templateIds = [$tid]; $templateIds = [$tid];
$model->setTable('notification_campaign'); $model->setTable('notification_campaign');
$notification_campaign_result = $model->whereIn('template_id', $templateIds)->where(['isactive'=>1,'campaign_id'=>$cid])->findAll(); $notification_campaign_result = $model->whereIn('template_id', $templateIds)->where(['isactive' => 1, 'campaign_id' => $cid])->findAll();
} }
// $today = date('Y-m-d'); // $today = date('Y-m-d');
@ -1031,7 +1081,7 @@ class Notifications extends BaseController
{ {
$model = new NotificationModel(); $model = new NotificationModel();
$model->setTable('templates'); $model->setTable('templates');
$where = ['template_id'=>$template_id,'isactive'=>1]; $where = ['template_id' => $template_id, 'isactive' => 1];
$result = $model->where($where)->first(); $result = $model->where($where)->first();
return $result; return $result;
} }
@ -1040,25 +1090,22 @@ class Notifications extends BaseController
function getCustomerDetails($group_ids) function getCustomerDetails($group_ids)
{ {
$group_id_arr = unserialize($group_ids); $group_id_arr = unserialize($group_ids);
$this->logger->error("Auto Scheduled Customer Group CGID = ".implode(", ", $group_id_arr)); $this->logger->error("Auto Scheduled Customer Group CGID = " . implode(", ", $group_id_arr));
$customer_details = []; $customer_details = [];
if(count($group_id_arr)) if (count($group_id_arr)) {
{ foreach ($group_id_arr as $group_id) {
foreach($group_id_arr as $group_id)
{
// echo "gid".$group_id; // echo "gid".$group_id;
$model = new NotificationModel(); $model = new NotificationModel();
$model->setTable('customer_groups'); $model->setTable('customer_groups');
$customer_group_result = $model->where(['group_id'=>$group_id,'isactive'=>1])->findAll(); $customer_group_result = $model->where(['group_id' => $group_id, 'isactive' => 1])->findAll();
$db = \Config\Database::connect(); $db = \Config\Database::connect();
if(count($customer_group_result)) if (count($customer_group_result)) {
{
$sql = (string)$customer_group_result[0]['group_query']; $sql = (string)$customer_group_result[0]['group_query'];
$query = $db->query($sql); $query = $db->query($sql);
$sql_group_results = $query->getResultArray(); $sql_group_results = $query->getResultArray();
// print_r($sql_group_results); // print_r($sql_group_results);
$customer_details = array_merge($customer_details,$sql_group_results); $customer_details = array_merge($customer_details, $sql_group_results);
} }
} }
} }
@ -1066,7 +1113,7 @@ class Notifications extends BaseController
} }
#step 4 #step 4
function replaceTemplateWithDataPoints($originalTemplate,$dataPointsArray) function replaceTemplateWithDataPoints($originalTemplate, $dataPointsArray)
{ {
// print_r($dataPointsArray['customer_name']); // print_r($dataPointsArray['customer_name']);
// echo $originalTemplate; // echo $originalTemplate;
@ -1092,7 +1139,8 @@ class Notifications extends BaseController
# Notification Acknowlegdement # Notification Acknowlegdement
################################################################ ################################################################
## notification acknowlegdement ## notification acknowlegdement
public function noifications_acknowlegdement(){ public function noifications_acknowlegdement()
{
$model = new NotificationModel(); $model = new NotificationModel();
$data['noifications_acknowlegdement'] = $model->get_noifications_acknowlegdement_data(); $data['noifications_acknowlegdement'] = $model->get_noifications_acknowlegdement_data();
$data['page_name'] = 'Notifications Status'; $data['page_name'] = 'Notifications Status';

View File

@ -10,6 +10,8 @@ use App\Models\SubscriptionModel;
use App\Models\AuthenticationModel; use App\Models\AuthenticationModel;
use App\Models\PaymentStatusModel; use App\Models\PaymentStatusModel;
use App\Helpers\SendSMSHelper;
require_once('vendor/autoload.php'); require_once('vendor/autoload.php');
define('PROJECT', 'vendor/paytm/paytm-pg'); define('PROJECT', 'vendor/paytm/paytm-pg');
@ -17,10 +19,12 @@ define('PROJECT', 'vendor/paytm/paytm-pg');
class Payment extends BaseController class Payment extends BaseController
{ {
protected $paymentModel; protected $paymentModel;
protected $sendSMSHelper;
public function __construct() { public function __construct() {
helper('encdec_paytm'); helper('encdec_paytm');
$this->paymentModel = new PaymentStatusModel(); $this->paymentModel = new PaymentStatusModel();
$this->sendSMSHelper = new SendSMSHelper();
} }
public function index($membership_id = null) public function index($membership_id = null)
@ -504,6 +508,19 @@ public function paymentStatus(){
} }
public function testSMS(){
$mobile_number = '916382156701';
$name = "Srinivas";
$expiryDate = "10/10/2025";
$link = "https://bit.ly/44Iy4Zm";
// Exactly matching the approved template
$message = "Hi {$name}, your subscription for Pusthakam scheme is about to expire on {$expiryDate}. Renew now to continue enjoying our books for one more year. Tap here to renew: {$link} -Vijayabharatham Prasuram";
$status = $this->sendSMSHelper->sendSMS($message,$mobile_number);
echo $status;
}
} }

View File

@ -0,0 +1,120 @@
<?php
namespace App\Helpers;
/**
* SendSMSHelper
*
* This class is responsible for sending SMS messages using a third-party SMS service.
* It constructs the URL for the API request, sends the SMS, and logs the response and record the status in db.
*
* @package App\Helpers
*/
use App\Models\NotificationModel;
class SendSMSHelper
{
protected $apiKey;
protected $logger;
protected $senderId;
protected $smsType;
protected $templateType;
protected $url;
protected $renewalTemplateID;
protected $notificationModel;
public function __construct(){
$this->apiKey = trim(getenv('SMS_API_KEY'));
$this->senderId = getenv('SMS_SENDER_ID');
$this->templateType = getenv('SMS_TEMPLATE_TYPE');
$this->logger = service('logger');
$this->url = trim(getenv('SMS_BASE_URL'));
$this->renewalTemplateID = getenv('SMS_RENEWAL_TEMPLATE_ID');
$this->notificationModel = new NotificationModel();
}
public function sendSMS($message,$mobile_number,$campaignID = null,$membershipID = null){
$this->logger->error('SMS Helper : SMS Request Data type = '.($campaignID));
$this->logger->error('SMS Helper : SMS Request Data = '.json_encode($message));
$this->logger->error('SMS Helper : SMS Request Mobile Number = '.json_encode($mobile_number));
if (is_array($mobile_number)){
$mobile_number = implode(",",$mobile_number);
}
$message_encode = ($message);
$this->logger->error('SMS Helper : SMS URLENCODED MESSAGE = '.$message_encode);
$url = $this->constructSMSURL($message_encode,$mobile_number);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set a timeout of 10 seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
if ($output === false) {
$this->logger->error('SMS Helper : SMS CURL Error = '.curl_error($ch));
} else {
$this->logger->error('SMS Helper : SMS CURL Response = '.$output);
// return $output;
}
curl_close($ch);
$mobile_number = str_replace("91","",$mobile_number);
if (!empty($campaignID)){
$this->saveSMSHistory($output,$mobile_number,$message,$campaignID,$membershipID);
}
$output_to_display = str_contains($output, 'success')? "SMS Sent Successfully" : "SMS Sending Failed";
return $output_to_display;
}
public function constructSMSURL($message, $mobile_number){
$this->logger->error('SMS Helper : SMS URL Construction');
$params = [
'APIKEY' => $this->apiKey,
'MobileNo' => $mobile_number,
'SenderID' => $this->senderId,
'Message' => $message,
'ServiceName' => $this->templateType,
'DLTTemplateID' => $this->renewalTemplateID,
];
$URL = $this->url.http_build_query($params);
$this->logger->error('SMS Helper : SMS URL = '.$URL);
return $URL;
}
public function saveSMSHistory($output,$mobile_number,$message,$campaignID = null,$membershipID){
$where = [
'mobile_no' => $mobile_number,
'isactive' => 1
];
$insertStatus = $this->notificationModel->saveSmSHistory($where,$campaignID,$message, $output,$membershipID);
if ($insertStatus){
$this->logger->error('SMS Helper : SMS History Inserted Successfully');
}else{
$this->logger->error('SMS Helper : SMS History Insertion Failed');
}
}
}

View File

@ -1,6 +1,9 @@
<?php <?php
namespace App\Models; namespace App\Models;
use CodeIgniter\Model; use CodeIgniter\Model;
class NotificationModel extends Model class NotificationModel extends Model
{ {
protected $table; protected $table;
@ -21,11 +24,12 @@ class NotificationModel extends Model
// } // }
/** This Function used for due_date_notifications routes */ /** This Function used for due_date_notifications routes */
public function getSubscriptionDueDetail($date){ public function getSubscriptionDueDetail($date)
{
// $now = date('Y-m-d'); // $now = date('Y-m-d');
// $lastWeek = date('Y-m-d', strtotime('+7 days')); // $lastWeek = date('Y-m-d', strtotime('+7 days'));
// $date_format = date('Y-m-d', $date); // $date_format = date('Y-m-d', $date);
return $this->db->table('subscription as S' ) return $this->db->table('subscription as S')
->join('customers as C', 'C.customer_id = S.customer_id', 'left') ->join('customers as C', 'C.customer_id = S.customer_id', 'left')
->join('category as CM', 'CM.id = S.scheme_id', 'left') ->join('category as CM', 'CM.id = S.scheme_id', 'left')
->join('business as B', 'B.business_id = S.business_id', 'left') ->join('business as B', 'B.business_id = S.business_id', 'left')
@ -33,13 +37,14 @@ class NotificationModel extends Model
->join('books as BK', 'BC.book_id = BK.book_id', 'left') ->join('books as BK', 'BC.book_id = BK.book_id', 'left')
->select('concat("Your subscription going to expried in ",DATEDIFF(S.to_subscription, CURDATE())," days") as statement,DATEDIFF(S.to_subscription, CURDATE()) as countdays,CM.name,CONCAT_WS(" ", C.first_name, C.last_name) as customer_name,C.email as customer_email,C.mobile_no as customer_mobile,S.sub_id,S.scheme_id,S.customer_id,S.from_subscription,S.to_subscription,S.business_id,B.title as business_name,B.address as business_address,B.city as business_city,B.state as business_state,B.postal_code as business_postal_code,B.email as business_email,B.mobile_no as business_mobile_no,S.to_subscription,S.from_subscription,BK.title,BK.book_id') ->select('concat("Your subscription going to expried in ",DATEDIFF(S.to_subscription, CURDATE())," days") as statement,DATEDIFF(S.to_subscription, CURDATE()) as countdays,CM.name,CONCAT_WS(" ", C.first_name, C.last_name) as customer_name,C.email as customer_email,C.mobile_no as customer_mobile,S.sub_id,S.scheme_id,S.customer_id,S.from_subscription,S.to_subscription,S.business_id,B.title as business_name,B.address as business_address,B.city as business_city,B.state as business_state,B.postal_code as business_postal_code,B.email as business_email,B.mobile_no as business_mobile_no,S.to_subscription,S.from_subscription,BK.title,BK.book_id')
// ->where('S.to_subscription >=', $now)->where('S.to_subscription <=',$lastWeek) // ->where('S.to_subscription >=', $now)->where('S.to_subscription <=',$lastWeek)
->where('S.to_subscription =',date('Y-m-d', strtotime($date))) ->where('S.to_subscription =', date('Y-m-d', strtotime($date)))
->groupBy('S.sub_id') ->groupBy('S.sub_id')
->get()->getResultArray(); ->get()->getResultArray();
} }
public function getTemplateDetails(){ public function getTemplateDetails()
return $this->db->table('templates as T' ) {
return $this->db->table('templates as T')
->join('users as U1', 'U1.user_id = T.created_by', 'left') ->join('users as U1', 'U1.user_id = T.created_by', 'left')
->join('users as U2', 'U2.user_id = T.updated_by', 'left') ->join('users as U2', 'U2.user_id = T.updated_by', 'left')
->select('T.template_id,T.template_name,T.mode,T.created_on,T.created_by,T.updated_on,T.updated_by,DATE_FORMAT(T.created_on, "%d/%m/%Y %h:%i %p") AS formatted_created_on,CONCAT_WS(" ", U1.first_name, U1.last_name) as created_by_name,CONCAT_WS(" ", U2.first_name, U2.last_name) as updated_by_name,T.isactive') ->select('T.template_id,T.template_name,T.mode,T.created_on,T.created_by,T.updated_on,T.updated_by,DATE_FORMAT(T.created_on, "%d/%m/%Y %h:%i %p") AS formatted_created_on,CONCAT_WS(" ", U1.first_name, U1.last_name) as created_by_name,CONCAT_WS(" ", U2.first_name, U2.last_name) as updated_by_name,T.isactive')
@ -47,50 +52,51 @@ class NotificationModel extends Model
->get()->getResultArray(); ->get()->getResultArray();
} }
public function saveDetails($data,$pk_name,$t_name){ public function saveDetails($data, $pk_name, $t_name)
{
$id = $data[$pk_name]; $id = $data[$pk_name];
$statement_string = ucfirst(str_replace('_', ' ', $t_name)); $statement_string = ucfirst(str_replace('_', ' ', $t_name));
if($id != ''){ if ($id != '') {
unset($data[$pk_name]); // Remove the id from the data to avoid updating it unset($data[$pk_name]); // Remove the id from the data to avoid updating it
unset($data['created_by']); // bcoz here data Updating here. unset($data['created_by']); // bcoz here data Updating here.
if ($this->db->table($t_name)->where($pk_name, $id)->update($data)) { if ($this->db->table($t_name)->where($pk_name, $id)->update($data)) {
$affectedRows = $this->db->affectedRows(); $affectedRows = $this->db->affectedRows();
$statement['success'] = $statement_string.' has been updated successfully.'; $statement['success'] = $statement_string . ' has been updated successfully.';
$statement['error'] = ""; $statement['error'] = "";
$statement['log'] = $statement_string.": has been updated successfully. Updated ".$pk_name." = " .$id." Affected Rows = ".$affectedRows; $statement['log'] = $statement_string . ": has been updated successfully. Updated " . $pk_name . " = " . $id . " Affected Rows = " . $affectedRows;
$statement['insert_id'] = $id; $statement['insert_id'] = $id;
} else { } else {
$statement['success'] = ""; $statement['success'] = "";
$statement['error'] = $statement_string.' update failed. Please try again.'; $statement['error'] = $statement_string . ' update failed. Please try again.';
$statement['log'] = $statement_string.": Err Failed to update ID = " .$id ; $statement['log'] = $statement_string . ": Err Failed to update ID = " . $id;
$statement['insert_id'] = $id; $statement['insert_id'] = $id;
} }
}else{ } else {
unset($data['updated_by']); unset($data['updated_by']);
if ($this->db->table($t_name)->insert($data)) { if ($this->db->table($t_name)->insert($data)) {
$insertID = $this->db->insertID(); $insertID = $this->db->insertID();
$statement['success'] = $statement_string.' has been Inserted successfully.'; $statement['success'] = $statement_string . ' has been Inserted successfully.';
$statement['error'] = ""; $statement['error'] = "";
$statement['log'] = $statement_string.": has been added successfully. Inserted ID = " .$insertID ; $statement['log'] = $statement_string . ": has been added successfully. Inserted ID = " . $insertID;
$statement['insert_id'] = $insertID; $statement['insert_id'] = $insertID;
} else { } else {
$statement['success'] = ""; $statement['success'] = "";
$statement['error'] = $statement_string." could not be added. Please try again.."; $statement['error'] = $statement_string . " could not be added. Please try again..";
$statement['log'] = $statement_string.": Err could not be added. Please try again."; $statement['log'] = $statement_string . ": Err could not be added. Please try again.";
$statement['insert_id'] = ""; $statement['insert_id'] = "";
} }
} }
return $statement; return $statement;
} }
public function getCampaignDetails(){ public function getCampaignDetails()
$result = $this->db->table('notification_campaign as NC' ) {
$result = $this->db->table('notification_campaign as NC')
->join('users as U1', 'U1.user_id = NC.created_by', 'left') ->join('users as U1', 'U1.user_id = NC.created_by', 'left')
->join('users as U2', 'U2.user_id = NC.updated_by', 'left') ->join('users as U2', 'U2.user_id = NC.updated_by', 'left')
->join('templates as T', 'T.template_id = NC.template_id', 'left') ->join('templates as T', 'T.template_id = NC.template_id', 'left')
->select('NC.campaign_id,NC.campaign_name,T.template_id,T.template_name,NC.mode,NC.created_on,NC.created_by,NC.updated_on,NC.updated_by,DATE_FORMAT(NC.created_on, "%d/%m/%Y %h:%i %p") AS formatted_created_on,CONCAT_WS(" ", U1.first_name, U1.last_name) as created_by_name,CONCAT_WS(" ", U2.first_name, U2.last_name) as updated_by_name,NC.isactive,NC.group_id,NC.scheduled_date,if(NC.scheduled_time IS NULL ,"",NC.scheduled_time) as scheduled_time') ->select('NC.campaign_id,NC.campaign_name,T.template_id,T.template_name,NC.mode,NC.created_on,NC.created_by,NC.updated_on,NC.updated_by,DATE_FORMAT(NC.created_on, "%d/%m/%Y %h:%i %p") AS formatted_created_on,CONCAT_WS(" ", U1.first_name, U1.last_name) as created_by_name,CONCAT_WS(" ", U2.first_name, U2.last_name) as updated_by_name,NC.isactive,NC.group_id,NC.scheduled_date,if(NC.scheduled_time IS NULL ,"",NC.scheduled_time) as scheduled_time')
->whereNotIn('T.template_name',array('EXPIRY NOTIFY TEMPLATE EMAIL','EXPIRY NOTIFY TEMPLATE WHATSAPP')) ->whereNotIn('T.template_name', array('EXPIRY NOTIFY TEMPLATE EMAIL', 'EXPIRY NOTIFY TEMPLATE WHATSAPP','EXPIRY NOTIFY TEMPLATE SMS'))
->get()->getResultArray(); ->get()->getResultArray();
if (!empty($result)) { if (!empty($result)) {
@ -117,17 +123,19 @@ public function getCampaignDetails(){
} }
} }
return $result; return $result;
} }
public function customerGroupQueryExecution($queries){ public function customerGroupQueryExecution($queries)
{
$results = []; $results = [];
// Execute the queries // Execute the queries
foreach ($queries as $query) { foreach ($queries as $query) {
if(!empty($query)){ if (!empty($query)) {
$queryResult = $this->db->query($query)->getResult(); $queryResult = $this->db->query($query)->getResult();
$results[] = $queryResult;} $results[] = $queryResult;
}
} }
// echo "<pre>"; // echo "<pre>";
// print_r($results); // print_r($results);
@ -154,12 +162,12 @@ public function customerGroupQueryExecution($queries){
// echo "</pre>"; // echo "</pre>";
// die; // die;
} }
// $query = "INSERT IGNORE INTO notification_history_children (fkid,customer_id,receiving_entry,message,result,sent_time) // $query = "INSERT IGNORE INTO notification_history_children (fkid,customer_id,receiving_entry,message,result,sent_time)
// VALUES (1, 1, 'somes@gmail2.com','mail msg',NULL,'2023-12-22 14:20:50'), // VALUES (1, 1, 'somes@gmail2.com','mail msg',NULL,'2023-12-22 14:20:50'),
// (1, 1, '9638527411','whatapp msg',NULL,'2023-12-22 14:20:50')"; // (1, 1, '9638527411','whatapp msg',NULL,'2023-12-22 14:20:50')";
// $result = $db->query($query)->getResultArray(); // $result = $db->query($query)->getResultArray();
public function getExpDate() public function getExpDate()
{ {
$db = \Config\Database::connect(); $db = \Config\Database::connect();
$query = "SELECT * FROM customer_groups WHERE group_name = 'EXPIRYDATE' AND isactive = 1"; $query = "SELECT * FROM customer_groups WHERE group_name = 'EXPIRYDATE' AND isactive = 1";
@ -172,12 +180,12 @@ public function customerGroupQueryExecution($queries){
error_log('group_query is not available in getExpDate()'); error_log('group_query is not available in getExpDate()');
return ; return;
}
} }
}
public function getExpDate2(){ public function getExpDate2()
{
$db = \Config\Database::connect(); $db = \Config\Database::connect();
$query = "SELECT * FROM customer_groups WHERE group_name = 'EXPIRYDATE_2' AND isactive = 1"; $query = "SELECT * FROM customer_groups WHERE group_name = 'EXPIRYDATE_2' AND isactive = 1";
@ -190,15 +198,14 @@ public function getExpDate2(){
error_log('group_query is not available in getExpDate()'); error_log('group_query is not available in getExpDate()');
return ; return;
}
} }
}
public function getTempName($name) public function getTempName($name)
{ {
$db = \Config\Database::connect(); $db = \Config\Database::connect();
$query = "SELECT * FROM templates WHERE isactive = 1 AND template_name = '".$name."'"; $query = "SELECT * FROM templates WHERE isactive = 1 AND template_name = '" . $name . "'";
$result = $db->query($query)->getResultArray(); $result = $db->query($query)->getResultArray();
if (isset($result)) { if (isset($result)) {
return $result; return $result;
@ -207,50 +214,51 @@ public function getExpDate2(){
error_log('group_query is not available in getExpDate()'); error_log('group_query is not available in getExpDate()');
return $query; return $query;
} }
} }
public function update_notification_campaign_status($data,$id){ public function update_notification_campaign_status($data, $id)
if($id != ''){ {
$where = ['isactive' => 1, 'status' => 0 ,'campaign_id'=>(int)$id]; if ($id != '') {
$where = ['isactive' => 1, 'status' => 0, 'campaign_id' => (int)$id];
if ($this->db->table('notification_campaign')->where($where)->update($data)) { if ($this->db->table('notification_campaign')->where($where)->update($data)) {
$affectedRows = $this->db->affectedRows(); $affectedRows = $this->db->affectedRows();
$statement = $affectedRows > 0 ? 'Notification Campaign Status has been updated successfully. Aff Row'.$affectedRows." NCID = " .$id : 'Notification Campaign Status Update failed. Bcoz Already Affected Count = '.$affectedRows.". NCID = " .$id ; $statement = $affectedRows > 0 ? 'Notification Campaign Status has been updated successfully. Aff Row' . $affectedRows . " NCID = " . $id : 'Notification Campaign Status Update failed. Bcoz Already Affected Count = ' . $affectedRows . ". NCID = " . $id;
} else { } else {
$statement = "Notification Campaign Status Update failed. NCID = " .$id; $statement = "Notification Campaign Status Update failed. NCID = " . $id;
} }
} } else {
else{
$statement = "Notification Campaign Status Update failed. Bcoz Not Found NCID"; $statement = "Notification Campaign Status Update failed. Bcoz Not Found NCID";
} }
return $statement; return $statement;
} }
public function save_notification_history_parents($data){ public function save_notification_history_parents($data)
{
$this->db->table('notification_history_parents')->insert($data); $this->db->table('notification_history_parents')->insert($data);
$insertID = $this->db->insertID(); $insertID = $this->db->insertID();
return $insertID; return $insertID;
} }
public function update_notification_history_parent_status($data,$id,$campaign_id){ public function update_notification_history_parent_status($data, $id, $campaign_id)
if($id != ''){ {
$where = ['id' => (int)$id, 'status' => 0 ,'campaign_id'=>(int)$campaign_id]; if ($id != '') {
$where = ['id' => (int)$id, 'status' => 0, 'campaign_id' => (int)$campaign_id];
if ($this->db->table('notification_history_parents')->where($where)->update($data)) { if ($this->db->table('notification_history_parents')->where($where)->update($data)) {
$affectedRows = $this->db->affectedRows(); $affectedRows = $this->db->affectedRows();
$statement = $affectedRows > 0 ? 'Notification history parent Status has been updated successfully. Aff Row'.$affectedRows." NHPID = " .$id : 'Notification history parent Status Update failed. Bcoz Already Affected Count = '.$affectedRows.". NHPID = " .$id ; $statement = $affectedRows > 0 ? 'Notification history parent Status has been updated successfully. Aff Row' . $affectedRows . " NHPID = " . $id : 'Notification history parent Status Update failed. Bcoz Already Affected Count = ' . $affectedRows . ". NHPID = " . $id;
} else { } else {
$statement = "Notification history parent Status Update failed. NHPID = " .$id; $statement = "Notification history parent Status Update failed. NHPID = " . $id;
} }
} } else {
else{
$statement = "Notification history parent Status Update failed. Bcoz Not Found NHPID"; $statement = "Notification history parent Status Update failed. Bcoz Not Found NHPID";
} }
return $statement; return $statement;
} }
public function save_notification_history_child($data){ public function save_notification_history_child($data)
{
// $this->db->ignore(true); // Enable "INSERT IGNORE" behavior // $this->db->ignore(true); // Enable "INSERT IGNORE" behavior
// $this->db->table('notification_history_children')->insert($data); // $this->db->table('notification_history_children')->insert($data);
// $insertID = $this->db->insertID(); // Get the last inserted ID // $insertID = $this->db->insertID(); // Get the last inserted ID
@ -269,13 +277,15 @@ public function getExpDate2(){
return $insertID; return $insertID;
} }
public function save_custom_notification_history_child($data){ public function save_custom_notification_history_child($data)
{
$this->db->table('notification_history_children')->insert($data); $this->db->table('notification_history_children')->insert($data);
$insertID = $this->db->insertID(); $insertID = $this->db->insertID();
return $insertID; return $insertID;
} }
public function update_notification_history_child($data, $where){ public function update_notification_history_child($data, $where)
{
$id = isset($where['id']) ? $where['id'] : ""; $id = isset($where['id']) ? $where['id'] : "";
@ -325,7 +335,8 @@ public function getExpDate2(){
return $query->get()->getResultArray(); return $query->get()->getResultArray();
} }
public function getAllCustomerMobileNumber(){ public function getAllCustomerMobileNumber()
{
$arr = $this->select('mobile_no') $arr = $this->select('mobile_no')
->where('mobile_no IS NOT NULL') ->where('mobile_no IS NOT NULL')
@ -333,22 +344,23 @@ public function getExpDate2(){
->groupBy('mobile_no') ->groupBy('mobile_no')
->having('COUNT(*) >', 1) ->having('COUNT(*) >', 1)
->findAll(); ->findAll();
return count($arr)>0 ? $arr : []; return count($arr) > 0 ? $arr : [];
} }
public function checkAlreadyExistingInHistory($email,$customerId,$subscriptionId){ public function checkAlreadyExistingInHistory($email, $customerId, $subscriptionId)
return $this->db->table('notification_history_children as nhc' ) {
return $this->db->table('notification_history_children as nhc')
->join('customers as C', 'C.customer_id = nhc.customer_id', 'left') ->join('customers as C', 'C.customer_id = nhc.customer_id', 'left')
->join('subscription as S', 'S.sub_id = nhc.subscription_id', 'left') ->join('subscription as S', 'S.sub_id = nhc.subscription_id', 'left')
->where('nhc.receiving_entity =',$email) ->where('nhc.receiving_entity =', $email)
->where('C.customer_id =',$customerId) ->where('C.customer_id =', $customerId)
->where('S.sub_id =',$subscriptionId) ->where('S.sub_id =', $subscriptionId)
->where('nhc.sent_time >', date('Y-m-d', strtotime('-5 days'))) ->where('nhc.sent_time >', date('Y-m-d', strtotime('-5 days')))
->where('nhc.receiving_status = ',1) ->where('nhc.receiving_status = ', 1)
->get()->getResultArray(); ->get()->getResultArray();
} }
public function get_email_data($f_date = null , $t_date = null){ public function get_email_data($f_date = null, $t_date = null)
{
$builder = $this->db->table('notification_history_parents as nhp'); $builder = $this->db->table('notification_history_parents as nhp');
$builder->select('nhp.*, nhc.*, nc.*,C.first_name,C.last_name,C.email, S.sub_id,S.membership_id, DATEDIFF(S.to_subscription, CURDATE()) AS countdays'); $builder->select('nhp.*, nhc.*, nc.*,C.first_name,C.last_name,C.email, S.sub_id,S.membership_id, DATEDIFF(S.to_subscription, CURDATE()) AS countdays');
$builder->join('notification_history_children as nhc', 'nhc.fkid = nhp.id'); $builder->join('notification_history_children as nhc', 'nhc.fkid = nhp.id');
@ -357,16 +369,62 @@ public function getExpDate2(){
$builder->join('subscription as S', 'S.sub_id = nhc.subscription_id'); $builder->join('subscription as S', 'S.sub_id = nhc.subscription_id');
$builder->where('DATE(nhp.start_date_time) >=', $f_date); $builder->where('DATE(nhp.start_date_time) >=', $f_date);
$builder->where('DATE(nhp.start_date_time) <=', $t_date); $builder->where('DATE(nhp.start_date_time) <=', $t_date);
$builder->whereIn('nhp.campaign_id', [1, 2]); $builder->whereIn('nhp.campaign_id', [1, 2,getenv("SMS_CAMPAIGN_ID")]);
$builder->where('nc.isactive', 1); $builder->where('nc.isactive', 1);
$query = $builder->get(); $query = $builder->get();
$results = $query->getResult(); $results = $query->getResult();
log_message('info',json_encode($results)); log_message('info', json_encode($results));
return $results; return $results;
} }
public function saveSmSHistory($where, $messageType, $message, $result, $membershipID)
{
try {
$customer = $this->db->table('customers')->where($where)->get()->getRowArray();
$subscriber = $this->db->table('subscription')->where('membership_id',$membershipID)->get()->getRowArray();
$customer_id = $customer['customer_id'];
$subscriptionId = $subscriber['sub_id'];
$campaign_id = $messageType;
$status = str_contains($result, 'success') ? 1 : 0;
$data = [
'campaign_id' => $campaign_id,
'status' => $status
];
$this->db->table("notification_history_parents")->insert($data);
$insertID = $this->db->insertID();
$child_data = [
'fkid' => $insertID,
'customer_id' => $customer_id,
'receiving_entity' => $where['mobile_no'],
'receiving_status' => $status,
'message' => $message,
'subscription_id' => $subscriptionId,
'result' => json_encode($result)
];
$this->db->table("notification_history_children")->insert($child_data);
$insertID = $this->db->insertID();
return $insertID;
} catch (\Exception $e) {
// Handle the exception
log_message('error', 'Error in saveSmSHistory: ' . $e->getMessage());
return false;
}
}
public function getCampaignID($template_id){
$result = $this->db->table("notification_campaign")->where("template_id",$template_id)->get()->getRowArray()['campaign_id'];
return $result;
}
} }

View File

@ -8,8 +8,7 @@
.custom-thead th { .custom-thead th {
text-align: center; /* Center-align the main table column headings */ text-align: center; /* Center-align the main table column headings */
} }
om /* .nested-table-data th,
/* .nested-table-data th,
.nested-table-data td { .nested-table-data td {
text-align: center; /* Center-align the nested table data text-align: center; /* Center-align the nested table data
} */ } */