This commit is contained in:
VENKATESHWARAN 2024-01-25 17:42:47 +05:30
parent 76f2045126
commit fa52664f6b
11 changed files with 1121 additions and 590 deletions

View File

@ -77,6 +77,20 @@ class Business extends BaseController
}
$sign = $this->request->getFile('signature');
$business_id = $this->request->getPost('business_id');
$filePath = 'public/uploads/' . $this->request->getPost('signature');
$signFileName = $sign->getName();
if($signFileName !== ""){
if ($sign->isValid() && !$sign->hasMoved()) {
$sign->move(ROOTPATH . 'public/uploads', $signFileName);
}
}
$BusinessModel = new BusinessModel();
$data = [
@ -90,13 +104,17 @@ class Business extends BaseController
'pan_no'=>$this->request->getPost('pan_no'),
'org_reg_no'=>$this->request->getPost('org_reg_no'),
'terms'=>$this->request->getPost('bterms'),
'80G'=>$this->request->getPost('80G')
'80G'=>$this->request->getPost('80G'),
];
if($fileName !== "")
{
$data['business_logo'] = $fileName;
}
if($signFileName !== "")
{
$data['signature'] = $signFileName;
}
$business_id = $this->request->getPost('business_id'); // Get the business ID for update

View File

@ -309,157 +309,12 @@ class Invoice extends BaseController
}
public function approve_notifications($receipt_id)
{
$model = new InvoiceModel();
$where = ['I.business_id' => (int)get_business_id(), 'I.receipt_id' => $receipt_id, 'I.isactive' => 1];
$details = $model->getDetailForApproveNotifications($where);
$records = [];
$reference_number = "";
$invoice_serial_number = "";
$recipient_name = "";
$approval_date = "";
$approved_by = "";
$recipient_email = "";
$recipient_mobile = "";
$subtotal = "";
$tax = "";
$total_amount = "";
$payment_method = "";
$business_name= "";
$business_address= "";
$business_city= "";
$business_state= "";
$business_postal_code= "";
$business_email= "";
$business_mobile_no= "";
if (isset($details)) {
$this->logger->info("Invoice: approve notification Request data type = ".gettype($details));
}
helper('notification');
$notification = new NotificationHelper();
foreach ($details['invoice'] as $rec) {
$reference_number = $rec['order_number'];
$invoice_serial_number = $rec['invoice_number'];
$recipient_name = $rec['customer_name'];
$approval_date = $rec['updated_on'];
$approved_by = $rec['updated_by_name'];
$recipient_email = $rec['customer_email'];
$recipient_mobile = $rec['customer_mobile'];
$subtotal = $rec['subtotal'];
$tax = $rec['tax'];
$total_amount = $rec['total_amount'];
$payment_method = $rec['payment_method'];
$business_name= $rec['business_name'];
$business_address= $rec['business_address'];
$business_city= $rec['business_city'];
$business_state= $rec['business_state'];
$business_postal_code= $rec['business_postal_code'];
$business_email= $rec['business_email'];
$business_mobile_no= $rec['business_mobile_no'];
}
$records['invoice_order_number'] = $reference_number;
$records['invoice_serial_number'] = $invoice_serial_number;
$records['recipient_name'] = $recipient_name;
$records['recipient_email'] = $recipient_email ? $recipient_email : "sanjeev.p@venbainfotech.com";
$records['subtotal'] = $subtotal;
$records['tax'] = $tax;
$records['total_amount'] = $total_amount;
$records['payment_method'] = $payment_method;
$records['favicon'] = base_url("public/uploads/default.ico");
$records['browser_title'] = "bbb-bp | Approve Template";
$records['page_name'] = 'Approve Template';
// view('approve_template',$records);
// $this->logger->info("Approve : Request data = ".json_encode($records));
// view('approve_template',$records);
$records['template_name'] = 'approve_template';
$records['item'] = $details['item'];
$records['subject'] = $invoice_serial_number . " - Approval Notification";
$records['description'] = "<html><head><title>VBP Approve Information</title></head><body>
<p>Dear $recipient_name,</p>
<p> &ensp;&ensp; We are pleased to inform you that your Invoice has been approved.</p>
<p><strong>Details:</strong></p>
<ul><li>Approval Date:" . $approval_date . "</li>
<li>Approved By:" . $approved_by . "</li>
<li>Reference ID:" . $reference_number . "</li>
</ul><br>
<p>Best regards,</p>
<ul style='list-style: none;'>
<li>".$business_name.",</li>
<li>".$business_address." ".$business_city." ".$business_state." - ".$business_postal_code."</li>
<li>Call Us: +91 ".$business_mobile_no."</li>
<li>Email Us: ".$business_email."</li></body></html>";
$template = "Dear " . $recipient_name . ",\r\r\n\nYour Invoice has been approved.\n\nDetails:\r\n- Approval Date: " . $approval_date . "\r\n- Approved By: " . $approved_by . "\r\n- Reference ID: " . $reference_number . "\r\n\nBest regards,\n".$business_name.",\n".$business_address." ".$business_city." ".$business_state." - ".$business_postal_code.".\nCall Us: +91 ".$business_mobile_no."\nEmail Us:".$business_email;
$params = (object) Null;
$params->number = (int)'91' . $recipient_mobile;
$params->type = "text";
$params->message = $template;
$params->instance_id = WAAI_INSTANCE;
$params->access_token = WAAI_TOKEN;
$this->logger->info("receipt: approve notification Email Request data = ".json_encode($records));
$email_result = $notification->sendEmail($records);
$this->logger->info("receipt: approve notification Email Response = " . json_encode($email_result));
$this->logger->info("receipt: approve notification Whatsapp Request data = ".json_encode($params));
$whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
$this->logger->info("receipt: approve notification Whatsapp Response = " . json_encode($whatsapp_result));
}
## To Generate receipt PDF based on receipt ID
// public function generate_invoice_pdf($id)
// {
// // Fetch the receipt data based on $receipt_id
// $model = new InvoiceModel();
// $data = $model->getInvoiceData($id);
// // print_r($data);die;
// $config = [
// 'mode' => 'utf-8',
// 'format' => 'letter', // You can also use [215.9, 279.4] for specifying dimensions manually
// 'default_font_size' => 12,
// 'default_font' => 'Arial',
// 'margin_left' => 0,
// 'margin_right' => 0,
// 'margin_top' => 0,
// 'margin_bottom' => 0,
// 'margin_header' => 0,
// 'margin_footer' => 0,
// 'orientation' => 'L', // Portrait
// ];
// // Create an mPDF object
// $mpdf = new Mpdf($config);
// $mpdf->autoLangToFont = true;
// $mpdf->autoScriptToLang = true;
// // Set PDF properties
// $mpdf->SetTitle('Receipt');
// $mpdf->SetAuthor('ORG');
// $mpdf->SetCreator('');
// $mpdf->AddPage('L', 'LETTER');
// // Generate the PDF content (HTML) with data
// $html = view('invoice_pdf_template', ['data' => $data[0]]);
// // echo $html; die;
// // Load HTML into the mPDF instance
// $mpdf->WriteHTML($html);
// // Output the PDF to the browser for download
// $mpdf->Output('Receipt' . date('Y-m-d H-i-s') . '.pdf', 'D');
// }
public function generate_invoice_pdf($id)
{
// Fetch the receipt data based on $receipt_id
$model = new InvoiceModel();
$data = $model->getInvoiceData($id);
// echo '<pre>';
// print_r($data);die;
$options = new Options();
@ -477,7 +332,6 @@ class Invoice extends BaseController
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('letter', 'landscape');
$dompdf->set_option('font_subsetting', true);
$dompdf->render();
@ -488,128 +342,189 @@ class Invoice extends BaseController
}
public function print_address($id)
{
// Fetch the invoice data based on $id
$model = new InvoiceModel();
$invoiceData = $model->getInvoiceData($id);
// print_r($invoiceData);die();
// Initialize an empty PDF with custom paper size (4x6 inches)
$config = [
'mode' => 'utf-8',
'format' => [101.6, 152.4],
'default_font_size' => 12,
'default_font' => 'Arial',
'margin_left' => 0,
'margin_right' => 0,
'margin_top' => 0,
'margin_bottom' => 0,
'margin_header' => 0,
'margin_footer' => 0,
'orientation' => 'P', // Portrait
];
$mpdf = new Mpdf($config);
$mpdf->SetTitle('Donor Address');
$mpdf->SetAuthor('Venba');
$mpdf->SetCreator('');
// Generate the PDF content (HTML) with customer and address data
$html = view('address_pdf_template', ['invoiceData' => $invoiceData]);
// Load HTML content into mPDF
$mpdf->WriteHTML($html);
// Output the PDF for download
// public function approve_notifications($receipt_id)
// {
// $model = new InvoiceModel();
// $where = ['I.business_id' => (int)get_business_id(), 'I.receipt_id' => $receipt_id, 'I.isactive' => 1];
// $details = $model->getDetailForApproveNotifications($where);
// $records = [];
// $reference_number = "";
// $invoice_serial_number = "";
// $recipient_name = "";
// $approval_date = "";
// $approved_by = "";
// $recipient_email = "";
// $recipient_mobile = "";
// $subtotal = "";
// $tax = "";
// $total_amount = "";
// $payment_method = "";
// $business_name= "";
// $business_address= "";
// $business_city= "";
// $business_state= "";
// $business_postal_code= "";
// $business_email= "";
// $business_mobile_no= "";
// if (isset($details)) {
// $this->logger->info("Invoice: approve notification Request data type = ".gettype($details));
// }
// helper('notification');
// $notification = new NotificationHelper();
// foreach ($details['invoice'] as $rec) {
// $reference_number = $rec['order_number'];
// $invoice_serial_number = $rec['invoice_number'];
// $recipient_name = $rec['customer_name'];
// $approval_date = $rec['updated_on'];
// $approved_by = $rec['updated_by_name'];
// $recipient_email = $rec['customer_email'];
// $recipient_mobile = $rec['customer_mobile'];
// $subtotal = $rec['subtotal'];
// $tax = $rec['tax'];
// $total_amount = $rec['total_amount'];
// $payment_method = $rec['payment_method'];
// $business_name= $rec['business_name'];
// $business_address= $rec['business_address'];
// $business_city= $rec['business_city'];
// $business_state= $rec['business_state'];
// $business_postal_code= $rec['business_postal_code'];
// $business_email= $rec['business_email'];
// $business_mobile_no= $rec['business_mobile_no'];
// }
// $records['invoice_order_number'] = $reference_number;
// $records['invoice_serial_number'] = $invoice_serial_number;
// $records['recipient_name'] = $recipient_name;
// $records['recipient_email'] = $recipient_email ? $recipient_email : "sanjeev.p@venbainfotech.com";
// $records['subtotal'] = $subtotal;
// $records['tax'] = $tax;
// $records['total_amount'] = $total_amount;
// $records['payment_method'] = $payment_method;
// $records['favicon'] = base_url("public/uploads/default.ico");
// $records['browser_title'] = "bbb-bp | Approve Template";
// $records['page_name'] = 'Approve Template';
// // view('approve_template',$records);
// // $this->logger->info("Approve : Request data = ".json_encode($records));
// // view('approve_template',$records);
$pdfFileName = 'customer_address_' . date('Y-m-d H-i-s') . '.pdf';
$mpdf->Output($pdfFileName, 'D');
}
// $records['template_name'] = 'approve_template';
// $records['item'] = $details['item'];
// $records['subject'] = $invoice_serial_number . " - Approval Notification";
// $records['description'] = "<html><head><title>VBP Approve Information</title></head><body>
// <p>Dear $recipient_name,</p>
// <p> &ensp;&ensp; We are pleased to inform you that your Invoice has been approved.</p>
// <p><strong>Details:</strong></p>
// <ul><li>Approval Date:" . $approval_date . "</li>
// <li>Approved By:" . $approved_by . "</li>
// <li>Reference ID:" . $reference_number . "</li>
// </ul><br>
// <p>Best regards,</p>
// <ul style='list-style: none;'>
// <li>".$business_name.",</li>
// <li>".$business_address." ".$business_city." ".$business_state." - ".$business_postal_code."</li>
// <li>Call Us: +91 ".$business_mobile_no."</li>
// <li>Email Us: ".$business_email."</li></body></html>";
public function general_inv_rp()
{
if($this->request->getmethod() == 'get')
{
$model = new InvoiceModel();
$data['report_data'] = $model->get_general_invoice_data();
$this->logger->info("Invoice Report ");
$data['page_name'] = 'General Invoice Report';
$this->render_page('report_general_invoice', $data);
}
else
{
$dateParts = explode(' - ', $this->request->getVar('date') );
$fromDate = $dateParts[0];
$toDate = $dateParts[1];
// $template = "Dear " . $recipient_name . ",\r\r\n\nYour Invoice has been approved.\n\nDetails:\r\n- Approval Date: " . $approval_date . "\r\n- Approved By: " . $approved_by . "\r\n- Reference ID: " . $reference_number . "\r\n\nBest regards,\n".$business_name.",\n".$business_address." ".$business_city." ".$business_state." - ".$business_postal_code.".\nCall Us: +91 ".$business_mobile_no."\nEmail Us:".$business_email;
$dateTime = \DateTime::createFromFormat('m/d/Y', $fromDate);
$dateTime1 = \DateTime::createFromFormat('m/d/Y', $toDate);
$model = new InvoiceModel();
$data['report_data'] = $model->get_general_invoice_data( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') );
$this->logger->info("Invoice Report ");
$data['page_name'] = 'General Invoice Report';
$data['selected_data'] = $this->request->getVar('date');
$this->render_page('report_general_invoice', $data);
}
}
// $params = (object) Null;
// $params->number = (int)'91' . $recipient_mobile;
// $params->type = "text";
// $params->message = $template;
// $params->instance_id = WAAI_INSTANCE;
// $params->access_token = WAAI_TOKEN;
// $this->logger->info("receipt: approve notification Email Request data = ".json_encode($records));
// $email_result = $notification->sendEmail($records);
// $this->logger->info("receipt: approve notification Email Response = " . json_encode($email_result));
// $this->logger->info("receipt: approve notification Whatsapp Request data = ".json_encode($params));
// $whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
// $this->logger->info("receipt: approve notification Whatsapp Response = " . json_encode($whatsapp_result));
// }
public function general_membership_inv_rp()
{
if($this->request->getmethod() == 'get')
{
$model = new InvoiceModel();
$data['report_data'] = $model->get_mem_invoice_data();
$this->logger->info("Membership Invoice Report ");
$data['page_name'] = 'Membership Invoice Report';
$this->render_page('report_mem_invoice', $data);
}
else
{
$dateParts = explode(' - ', $this->request->getVar('date') );
$fromDate = $dateParts[0];
$toDate = $dateParts[1];
$dateTime = \DateTime::createFromFormat('m/d/Y', $fromDate);
$dateTime1 = \DateTime::createFromFormat('m/d/Y', $toDate);
$model = new InvoiceModel();
$data['report_data'] = $model->get_mem_invoice_data( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') );
$this->logger->info("Membership Invoice Report ");
$data['page_name'] = 'Membership Invoice Report';
$data['selected_data'] = $this->request->getVar('date');
$this->render_page('report_mem_invoice', $data);
}
}
public function itemwise_report()
{
if($this->request->getmethod() == 'get')
{
$model = new InvoiceModel();
$data['report_data'] = $model->itemwise_report_data();
$this->logger->info("Itemwise Report ");
$data['page_name'] = 'Itemwise Report';
$this->render_page('report_itemwise', $data);
}
else
{
$dateParts = explode(' - ', $this->request->getVar('date') );
$fromDate = $dateParts[0];
$toDate = $dateParts[1];
$dateTime = \DateTime::createFromFormat('m/d/Y', $fromDate);
$dateTime1 = \DateTime::createFromFormat('m/d/Y', $toDate);
$model = new InvoiceModel();
$data['report_data'] = $model->itemwise_report_data( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') );
$this->logger->info("Itemwise Report ");
$data['page_name'] = 'Itemwise Report';
$data['selected_data'] = $this->request->getVar('date');
$this->render_page('report_itemwise', $data);
}
// public function general_inv_rp()
// {
// if($this->request->getmethod() == 'get')
// {
// $model = new InvoiceModel();
// $data['report_data'] = $model->get_general_invoice_data();
// $this->logger->info("Invoice Report ");
// $data['page_name'] = 'General Invoice Report';
// $this->render_page('report_general_invoice', $data);
// }
// else
// {
// $dateParts = explode(' - ', $this->request->getVar('date') );
// $fromDate = $dateParts[0];
// $toDate = $dateParts[1];
}
// $dateTime = \DateTime::createFromFormat('m/d/Y', $fromDate);
// $dateTime1 = \DateTime::createFromFormat('m/d/Y', $toDate);
// $model = new InvoiceModel();
// $data['report_data'] = $model->get_general_invoice_data( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') );
// $this->logger->info("Invoice Report ");
// $data['page_name'] = 'General Invoice Report';
// $data['selected_data'] = $this->request->getVar('date');
// $this->render_page('report_general_invoice', $data);
// }
// }
// public function general_membership_inv_rp()
// {
// if($this->request->getmethod() == 'get')
// {
// $model = new InvoiceModel();
// $data['report_data'] = $model->get_mem_invoice_data();
// $this->logger->info("Membership Invoice Report ");
// $data['page_name'] = 'Membership Invoice Report';
// $this->render_page('report_mem_invoice', $data);
// }
// else
// {
// $dateParts = explode(' - ', $this->request->getVar('date') );
// $fromDate = $dateParts[0];
// $toDate = $dateParts[1];
// $dateTime = \DateTime::createFromFormat('m/d/Y', $fromDate);
// $dateTime1 = \DateTime::createFromFormat('m/d/Y', $toDate);
// $model = new InvoiceModel();
// $data['report_data'] = $model->get_mem_invoice_data( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') );
// $this->logger->info("Membership Invoice Report ");
// $data['page_name'] = 'Membership Invoice Report';
// $data['selected_data'] = $this->request->getVar('date');
// $this->render_page('report_mem_invoice', $data);
// }
// }
// public function itemwise_report()
// {
// if($this->request->getmethod() == 'get')
// {
// $model = new InvoiceModel();
// $data['report_data'] = $model->itemwise_report_data();
// $this->logger->info("Itemwise Report ");
// $data['page_name'] = 'Itemwise Report';
// $this->render_page('report_itemwise', $data);
// }
// else
// {
// $dateParts = explode(' - ', $this->request->getVar('date') );
// $fromDate = $dateParts[0];
// $toDate = $dateParts[1];
// $dateTime = \DateTime::createFromFormat('m/d/Y', $fromDate);
// $dateTime1 = \DateTime::createFromFormat('m/d/Y', $toDate);
// $model = new InvoiceModel();
// $data['report_data'] = $model->itemwise_report_data( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') );
// $this->logger->info("Itemwise Report ");
// $data['page_name'] = 'Itemwise Report';
// $data['selected_data'] = $this->request->getVar('date');
// $this->render_page('report_itemwise', $data);
// }
// }
}

802
app/Controllers/Notifications.php Normal file → Executable file
View File

@ -8,48 +8,85 @@ use App\Models\NotificationModel;
class Notifications extends BaseController
{
## Email Section :
################################################################
# Custom Email Notification
################################################################
public function mail_custom_notifications()
{
$request = \Config\Services::request();
if ($request->is('post')) {
$records = $request->getVar();
$records['template_name'] = "";
if ($this->request->is('post')) {
$records = $this->request->getVar();
helper('notification');
$notification = new NotificationHelper();
$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,
'donor_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->info('Custom Notifications Email : historychildid = '.$history_child_id);
}
$records = [];
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
}
# mail custom notifications closed
################################################################
# Custom Whatsapp Notification
################################################################
public function whatsapp_custom_notifications()
{
$request = \Config\Services::request();
if ($request->is('post')) {
$records = $request->getVar();
if ($this->request->is('post')) {
$records = $this->request->getVar();
$params = (object) Null;
$this->logger->info("Whatsapp : sending message instance id = " . $_ENV['WAAI_INSTANCE'] ." - ". $_ENV['WAAI_TOKEN']);
$parents_status = 0;
$receiving_status = 0;
$this->logger->info("Whatsapp : sending message instance id = " . $_ENV['WAAI_INSTANCE'] . " - " . $_ENV['WAAI_TOKEN']);
try {
if ($records['categories'] == 'SEND_WAAI_GROUP_URL') {
if($records['group_id'] != ""){ $params->group_id = $records['group_id']; }
else{ throw new \Exception("Group Id Missing Please Try again.."); }
}else if ($records['categories'] == 'SEND_WAAI_URL') {
if($records['mobile'] != ""){ $params->number = (int)'91' . $records['mobile']; }
else{ throw new \Exception("Mobile Number Missing Please Try again.."); }
}else{
if ($records['group_id'] != "") {
$params->group_id = $records['group_id'];
} else {
throw new \Exception("Group Id Missing Please Try again..");
}
if ($records['mobile'] != "") {
$params->number = (int)'91' . $records['mobile'];
} else {
throw new \Exception("Mobile Number Missing Please Try again..");
}
} else if ($records['categories'] == 'SEND_WAAI_URL') {
if ($records['mobile'] != "") {
$params->number = (int)'91' . $records['mobile'];
} else {
throw new \Exception("Mobile Number Missing Please Try again..");
}
} else {
throw new \Exception("Please Choose your Category");
}
if ($records['type'] == 'media') {
if($records['media_url'] != ""){ $params->media_url = $records['media_url']; }
else{ throw new \Exception("Media Url Missing Please Try again.."); }
if ($records['media_url'] != "") {
$params->media_url = $records['media_url'];
} else {
throw new \Exception("Media Url Missing Please Try again..");
}
}
$url = constant($records['categories']);
@ -62,36 +99,53 @@ class Notifications extends BaseController
helper('notification');
$notification = new NotificationHelper();
$success = $notification->sendWhatsAppMessage($url, "POST", $params);
session()->setFlashdata('success', 'Message : ' . $success);
$this->logger->info("Whatsapp : Reponse = " . $success);
$receiving_status = $success['receiving_status'];
$parents_status = $success['receiving_status'];
$history_msg = strtolower(gettype($success)) == "string" ? $success : json_encode($success['reponse']);
session()->setFlashdata('success', 'Message : ' . $success['message']);
$this->logger->info("Whatsapp : Reponse = " . $success['message']);
} catch (\Exception $e) {
$this->logger->error("Whatsapp : Exception Message = " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
session()->setFlashdata('error', 'Message: ' . $e->getMessage());
$history_msg = strtolower(gettype($success)) == "string" ? $success : json_encode($success['reponse']);
}
$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,
'donor_id' => 0,
'receiving_entity' => $records['mobile'],
'receiving_status' => $receiving_status,
'message' => $records['description'],
'result'=>$history_msg];
$history_child_id = $NotificationModel->save_notification_history_child($history_child_data);
}
$records = [];
$data['page_name'] = 'Custom Notifications';
$this->render_page('notifications_form', $data);
$this->logger->info('Custom Notifications Whatsapp : historychildid = '.$history_child_id);
}
# whatsapp custom notifications closed
public function due_date_notifications()
{
$date = $this->request->getGet('date');
$model = new NotificationModel();
$details = $model->getSubscriptionDueDetail($date);
// echo "<pre>";
// print_r($details);
// echo "</pre>";
// die;
$records = [];
$records = [];
$recipient_name = "";
$recipient_email = "";
$recipient_mobile = "";
$subscription_name = "";
$business_name= "";
$to_subscription= "";
$business_name = "";
$to_subscription = "";
if (isset($details)) {
$this->logger->info("Notification : Duedate notification Request data type = ".gettype($details));
$this->logger->info("Notification : Duedate notification Request data type = " . gettype($details));
}
helper('notification');
$notification = new NotificationHelper();
@ -101,23 +155,22 @@ class Notifications extends BaseController
$recipient_mobile = $rec['customer_mobile'];
// $recipient_email = "sanjeev.p@venbainfotech.com";
// $recipient_mobile = 6369084112;
$business_name= $rec['business_name'];
$business_name = $rec['business_name'];
$subscription_name = $rec['title'];
$to_subscription= $rec['to_subscription'];
$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['subject'] = $business_name . " - Due Date Reminder";
$records['description'] = "<!DOCTYPE html>
<html>
<head><title>Due Date Reminder</title></head>
<body>
<p>Hello ".$recipient_name.",</p>
<p>Hello " . $recipient_name . ",</p>
<p>This is a reminder that the following subscription is due soon:</p>
<p><strong>Subscription Name:</strong>".$subscription_name." </p>
<p><strong>Due Date:</strong> ".$to_subscription."</p>
<p><strong>Subscription Name:</strong>" . $subscription_name . " </p>
<p><strong>Due Date:</strong> " . $to_subscription . "</p>
<p>Please make sure to complete this subscription on time.</p>
<p>Thank you.</p>
</body>
@ -131,17 +184,17 @@ class Notifications extends BaseController
$params->message = $template;
$params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN'];
$this->logger->info("Notification : Duedate notification Email Request data = ".json_encode($records));
$this->logger->info("Notification : Duedate notification Email Request data = " . json_encode($records));
$email_result = $notification->sendEmail($records);
$this->logger->info("Notification : Duedate notification Email Response = " . json_encode($email_result));
$this->logger->info("Notification : Duedate notification Whatsapp Request data = ".json_encode($params));
$this->logger->info("Notification : Duedate notification Whatsapp Request data = " . json_encode($params));
$whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params);
$this->logger->info("Notification : Duedate notification Whatsapp Response = " . json_encode($whatsapp_result));
}
public function template_creation(){
public function template_creation()
{
$data['page_name'] = 'Template Details';
$model = new NotificationModel();
$data['template'] = $model->getTemplateDetails();
@ -149,8 +202,12 @@ class Notifications extends BaseController
// echo "templates";die;
}
public function template_creation_form($id){
##################################################################
# 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') {
@ -161,7 +218,7 @@ class Notifications extends BaseController
$this->logger->info("Template Creation: In Edit Page ID =" . $id);
$data['page_name'] = 'Edit Template';
$model->setTable('templates');
$where = ['template_id'=>(int)$id];
$where = ['template_id' => (int)$id];
$result = $model->where($where)->findAll();
$data['template_details'] = !empty($result[0]) ? $result[0] : [];
}
@ -169,36 +226,40 @@ class Notifications extends BaseController
$this->render_page('template_creation_form', $data);
}
public function template_creation_delete($id){
##############################################################################
# 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];
$where = ['template_id' => (int)$id];
$result = $model->where($where)->findAll();
if ($result) {
$this->logger->Info("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.
$this->logger->Info("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->info($statement['log']);
} else if ($statement['error']) {
session()->setFlashdata('success', $statement['success'] ? 'Deleted successfully.' : "");
$this->logger->info($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");
} 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());
$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();
@ -208,51 +269,68 @@ class Notifications extends BaseController
$details = $model->where($where)->orderBy('group_id', 'ASC')->findAll();
return $details;
}
public function get_template_details(){
public function get_template_details()
{
$model = new NotificationModel();
$model->setTable('templates');
$details = $model->where('isactive',1)->orderBy('template_id', 'ASC')->findAll();
$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(){
public function template_creation_insert()
{
$this->logger->info("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';
$data = [
'template_id' => $id,
'template_name' => $this->request->getPost('templatename'),
'subject' => $subject,
'message' => $this->request->getPost('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->info($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');
}
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->info($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(){
//Campaign Creation
public function campaign_creation()
{
$data['page_name'] = 'Campaign Details';
$model = new NotificationModel();
$data['campaign'] = $model->getCampaignDetails();
@ -260,8 +338,9 @@ class Notifications extends BaseController
// echo "templates";die;
}
public function campaign_creation_form($id){
public function campaign_creation_form($id)
{
$data['group_details'] = $this->get_group_details();
$data['template_details'] = $this->get_template_details();
$model = new NotificationModel();
@ -273,167 +352,436 @@ class Notifications extends BaseController
$this->logger->info("Campaign Creation: In Edit Page ID =" . $id);
$data['page_name'] = 'Edit Campaign';
$model->setTable('notification_campaign');
$where = ['campaign_id'=>(int)$id];
$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){
public function campaign_creation_insert()
{
$this->logger->info("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 != "") {
$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'] = 'Notification Campaign already In-Active. can`t able to update.';
$statement['error'] = "";
$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 {
$statement = $model->saveDetails($data, 'campaign_id', 'notification_campaign');
}
if ($statement['success']) {
session()->setFlashdata('success', $statement['success']);
$this->logger->info($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');
}
public function campaign_creation_delete($id)
{
try {
helper('session');
$session_uid = get_logged_user_id();
$model = new NotificationModel();
$model->setTable('templates');
$where = ['campaign_id'=>(int)$id];
$model->setTable('notification_campaign');
$where = ['campaign_id' => (int)$id];
$result = $model->where($where)->findAll();
if ($result) {
$this->logger->Info("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.
$this->logger->Info("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->info($statement['log']);
} else if ($statement['error']) {
session()->setFlashdata('success', $statement['success'] ? 'Deleted successfully.' : "");
$this->logger->info($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");
} 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());
$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');
}
################################################################
# Expiry Notification ReferWith : Hema
################################################################
public function getExpCustomerDetail($window_time = null)
{
# 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->info('EXPIRYDATE T-Date = '.$providedDate.', Given ' .$window_time.' Day, Calacuated Date based on Given days = '.$newDate);
# Step 2 :Get the customer detail//
$NotificationModel = new NotificationModel();
$ExpCustomerDetail = $NotificationModel->getExpDate(); // Retrieve the stored query
if (empty($ExpCustomerDetail)) {
$this->logger->info('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);
if (empty($modifiedQuery)) {
$this->logger->info('There is no sub query');
return;
}
$db = \Config\Database::connect();
$queryResult = $db->query($modifiedQuery)->getResultArray();
$notification = new NotificationHelper();
if (empty($queryResult)) {
$this->logger->info("There is no customer expiring on date:{$newDate}");
return;
}
$emailTemplateName = $NotificationModel->getTempName(EXPIRAY_NOTIFY_TEMPLATE_EMAIL);
foreach ($queryResult as $row) {
$userFirstName = $row['first_name'];
$userLastName = $row['last_name'];
$fullName = $userFirstName . ' ' . $userLastName;
$userMobileNumber = $row['mobile_no'];
$schemename = $row['title'];
$expirydate = $row['to_subscription'];
$customerId = $row['donor_id'];
if (empty($fullName)) {
$this->logger->info('There is no subcription Name');
continue;
}
# EXPIRAY_NOTIFY_TEMPLATE_EMAIL
$emailTemplateName = $NotificationModel->getTempName(EXPIRAY_NOTIFY_TEMPLATE_EMAIL);
if (!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'];
$emailContent = str_replace("{USER_NAME}", $fullName, $emailContent);
$emailContent = str_replace("{SCHEME_NAME}", $schemename, $emailContent);
$emailContent = str_replace("{EXPIRY_DATE}", $expirydate, $emailContent);
$emailData = [
'template_name' => '',
'recipient_email' => $row['email'],
'subject' => 'Your Subscription Expiry Notification',
'description' => $emailContent,
];
$history_child_data = [ 'fkid' => $history_parent_id,
'donor_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->info("EXPIRAY NOTIFY TEMPLATE EMAIL Email CID = ".$customerId." ".json_encode($emailResult));
if (isset($emailResult['success'])) {
$history_msg = 'Email sent successfully';
$receiving_status = 1 ;
echo $history_msg;
} else {
$history_msg = (strtolower(gettype($emailResult)) == "string" ? $emailResult : json_encode($emailResult)) ;
$receiving_status = 0 ;
echo '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->info($history_msg);
continue;
}
# EXPIRAY_NOTIFY_TEMPLATE_EMAIL Closed
# EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP
$whatsappTemplateName = $NotificationModel->getTempName(EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP);
if (!empty($whatsappTemplateName)) {
$campaign_id = 2;
if (empty($userMobileNumber)) {
$history_msg = 'There is no subscriber mobile number';
$this->logger->info($history_msg);
continue;
}
# Insertion on History Whatsapp Means Campaign ID 2 Hardcoded
$history_parents_data = ['campaign_id' => $campaign_id,'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'];
$whatsappContent = str_replace("{USER_NAME}", $fullName, $emailContent);
$whatsappContent = str_replace("{SCHEME_NAME}", $schemename, $emailContent);
$whatsappContent = str_replace("{EXPIRY_DATE}", $expirydate, $emailContent);
# Step 8: Insertion on History Child for whatsapp
$history_child_data = [ 'fkid' => $history_parent_id,
'donor_id' => $customerId,
'receiving_entity' => $userMobileNumber,
'receiving_status' => 0,
'message' => $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 = $whatsappContent;
$params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN'];
$this->logger->info("EXPIRAY NOTIFY TEMPLATE WHATSAPP Request = " . json_encode($params));
$this->logger->info("EXPIRAY NOTIFY TEMPLATE WHATSAPP Request type b4 = " . gettype($params));
$whatsapp_result = $notification->sendWhatsAppMessage($url, "POST", $params);
$this->logger->info("EXPIRAY NOTIFY TEMPLATE WHATSAPP Reponse = " . $whatsapp_result['message']);
$receiving_status = $whatsapp_result['receiving_status'];
$history_msg = strtolower(gettype($whatsapp_result)) == "string" ? $whatsapp_result : json_encode($whatsapp_result['reponse']);
} else {
$receiving_status = 0;
$history_msg = 'There is no Whatsapp template found by the name of EXPIRAY NOTIFY TEMPLATE WHATSAPP ';
$this->logger->info($history_msg);
continue;
}
# EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP Closed
$history_child_where = ['fkid' => $history_parent_id,'id' => (int)$history_child_id];
$history_child_updatedata = ['receiving_status'=>$receiving_status,'result'=>$history_msg];
$history_child_statement = $NotificationModel->update_notification_history_child($history_child_updatedata,$history_child_where);
$this->logger->info($history_child_statement);
$history_parent_statement = $NotificationModel->update_notification_history_parent_status(['status' => 1],$history_parent_id,$campaign_id);
$this->logger->info($history_parent_statement);
}
# Loop Closed
}
# getExpCustomerDetail fns Closed
################################################################
# Auto Scheduled Notification
################################################################
## notification campaign details
public function processScheduledNotifications(){
$this->logger->info("Auto Scheduled Notification Started");
$model = new NotificationModel();
#step 1 get scheduled notification details
$notification_campaign_result = $this->getScheduledNotificationDetails();
$this->logger->info("Auto Scheduled Campaign Details Count = ".count($notification_campaign_result));
if(!count($notification_campaign_result))
{
$this->logger->info("No Auto Scheduled Notification in DB,exiting...!");
$this->logger->info("Auto Scheduled Notification Ends");
exit();
}
//looping multiple notification campaign
if(count($notification_campaign_result))
{
foreach($notification_campaign_result as $index => $single_campaign)
{
#step 2 get template details
$template = $this->getTemplateDetails($single_campaign['template_id']);
$this->logger->info("Auto Scheduled Template Details TID = ".$single_campaign['template_id']);
if(count($template))
{
#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;
#step 3 execute the customer group query and return customer details
$customer_details = $this->getCustomerDetails($single_campaign['group_id']);
$sent_customer_details = [];
if(count($customer_details))
{
foreach($customer_details as $customer)
{
#step 4 replace templates palceholders with data points
$notificationContent = $this->replaceTemplateWithDataPoints($template['message'],$customer);
$history_child_data = [
'fkid' => $single_campaign['history_parent_id'],
'donor_id' => $customer['donor_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['donor_id'],$sent_customer_details))
{
$this->logger->info("Auto Scheduled Customer CID = ".$customer['donor_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->info("Auto Scheduled Email CID = ".$customer['donor_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->info($history_child_statement);
}
else
{
$params = (object) Null;
$url = SEND_WAAI_URL;
$params->type = "text";
$params->instance_id = $_ENV['WAAI_INSTANCE'];
$params->access_token = $_ENV['WAAI_TOKEN'];
$params->message = $notificationContent;
$params->number = (int)'91' . $customer['mobile_no'];
$whatsapp_reponse = $notification->sendWhatsAppMessage($url, "POST", $params);
$this->logger->info("Auto Scheduled Whatsapp CID = ".$customer['donor_id']." ".$whatsapp_reponse['message']);
$history_child_where = ['fkid' => $single_campaign['history_parent_id'],'id' => (int)$history_child_id];
$history_child_updatedata = ['receiving_status'=>$whatsapp_reponse['receiving_status'],'result'=>strtolower(gettype($whatsapp_reponse)) == "string" ? $whatsapp_reponse : json_encode($whatsapp_reponse['reponse'])];
$history_child_statement = $model->update_notification_history_child($history_child_updatedata,$history_child_where);
$this->logger->info($history_child_statement);
}
array_push($sent_customer_details,$customer['donor_id']);
}
}
}
}
#step 6 update campaign status to 1
$statement = $model->update_notification_campaign_status(['status' => 1],$single_campaign['campaign_id']);
$this->logger->info($statement);
#step 7 update history parent status to 1
$history_parent_statement = $model->update_notification_history_parent_status(['status' => 1],$single_campaign['history_parent_id'],$single_campaign['campaign_id']);
$this->logger->info($history_parent_statement);
}
}
}
public function campaign_creation_insert(){
$this->logger->info("Campaign: Inserting/Updating Details");
try {
## Declarions
helper('session');
$model = new NotificationModel();
$session_uid = get_logged_user_id();
$id = $this->request->getPost('campaign_id');
$isactive = $this->request->getPost('isactive');
// print_r($this->request->getPost());die;
$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'),
'mode' => $this->request->getPost('mode'),
'group_id' => serialize($this->request->getPost('group_id')),
'isactive' => $id ? (($isactive == 'on') ? 1 : 0) : 1,
'created_by' => $session_uid,
'updated_by' => $session_uid
];
$statement = $model->saveDetails($data,'campaign_id','notification_campaign');
if ($statement['success']) {
session()->setFlashdata('success', $statement['success']);
$this->logger->info($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');
}
public function getExpCustomerDetail($window_time = null)
{
// Step 1: add the days to retrive th e data//
$providedDate = date('Y-m-d');
$newDate = date('Y-m-d', strtotime($providedDate . ' + ' . $window_time . ' days'));
// Step 2 :Get the custoemr detail//
$NotificationModel = new NotificationModel();
$ExpCustomerDetail = $NotificationModel->getExpDate(); // Retrieve the stored query
if (empty($ExpCustomerDetail)) {
$this->logger->info('There is no query');
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->info('There is no sub query');
return;
}
$db = \Config\Database::connect();
$queryResult = $db->query($modifiedQuery)->getResultArray();
$notification = new NotificationHelper();
if (empty($queryResult)) {
$this->logger->info("There is no data against customer on given date:{$newDate}");
return;
}
foreach ($queryResult as $row) {
$templateName = $NotificationModel->getTempName();
if (empty($templateName)) {
$this->logger->info('There is no template found');
return;
}
$userFirstName = $row['first_name'];
$userLastName = $row['last_name'];
$fullName = $userFirstName . ' ' . $userLastName;
$schemename = $row['title'];
$expirydate = $row['to_subscription'];
if (empty($fullName)) {
$this->logger->info('There is no subcription Name');
return;
}
//Step 4: Prepare email content based on the template
$emailContent = $templateName[0]['message'];
$emailContent = str_replace("{User}", $fullName, $emailContent);
$emailContent = str_replace("{SCHEME_NAME}", $schemename, $emailContent);
$emailContent = str_replace("{EXPIRY_DATE}", $expirydate, $emailContent);
$emailData = [
'template_name'=>'',
'recipient_email' => $row['email'],
'subject' => 'Your Subscription Expiry Notification',
'description' =>$emailContent,
];
// Step 5:Send email using NotificationHelper
$emailResult = $notification->sendEmail($emailData);
if (isset($emailResult['success'])) {
echo 'Email sent successfully';
} else {
echo 'Failed to send email';
}
$templateName = $NotificationModel->getTempName();
}
}
#step 1 get scheduled notification details
function getScheduledNotificationDetails()
{
$model = new NotificationModel();
$today = date('Y-m-d');
$model->setTable('notification_campaign');
$where = ['scheduled_date'=>$today];
$notification_campaign_result = $model->where($where)->findAll();
return $notification_campaign_result;
}
#step 2 get template details
function getTemplateDetails($template_id)
{
$model = new NotificationModel();
$model->setTable('templates');
$where = ['template_id'=>$template_id];
$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->info("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('donor_groups');
$customer_group_result = $model->where(['group_id'=>$group_id])->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;
$notificationContent = str_replace("{USER_NAME}", $dataPointsArray["customer_name"], $notificationContent);
$notificationContent = str_replace("{SCHEME_NAME}", $dataPointsArray["scheme_name"], $notificationContent);
$notificationContent = str_replace("{EXPIRY_DATE}", $dataPointsArray["formatted_due_date"], $notificationContent);
return $notificationContent;
}
############## Auto Scheduled Notification Ends ################
}

View File

@ -18,74 +18,87 @@ class NotificationHelper
public function sendEmail($records)
{
$this->logger->info('Helper : Email Request Data type = '.gettype($records));
$cc = isset($records['carboncopy']) ? $records['carboncopy'] : '';
$bcc = isset($records['blindcarboncopy']) ? $records['blindcarboncopy'] : '';
try {
$this->email->clear();
if($records['recipient_email'] == "" && $records['subject'] == ""){
throw new \Exception("Email and Subject are Must Please Try again..");
}
$this->email->setTo($records['recipient_email']);
$this->logger->info('Helper : Email recipient = '.$records['recipient_email']);
$this->email->setFrom('no-reply@tripapprovaltool.com', isset($records['company'])?$records['company']:"VBP");
$this->email->setFrom('web@vijayabharathambooks.com', isset($records['company'])?$records['company']:"VB");
$this->email->setSubject($records['subject']);
$this->logger->info('Helper : Email subject = '.$records['subject']);
if($records['template_name'] != ""){
$this->logger->info('Helper : Email Template = '.$records['template_name']);
$this->logger->info("Helper : Email Request data = ".json_encode($records));
$emailContent = view($records['template_name'],$records);
$this->email->setMessage($emailContent);
}else{
$this->logger->info('Helper : Email Dynamic Template');
$this->email->setMessage($records['description']);
}
$this->email->setMessage($records['description']);
// if($records['template_name'] != ""){
// $this->logger->info('Helper : Email Template = '.$records['template_name']);
// $this->logger->info("Helper : Email Request data = ".json_encode($records));
// $emailContent = view($records['template_name'],$records);
// $this->email->setMessage($emailContent);
// }else{
// $this->logger->info('Helper : Email Dynamic Template');
// $this->email->setMessage($records['description']);
// }
if (!empty($cc)) {
$ccRecipients = explode(',', $cc);
$this->logger->info('Helper : Email carboncopy CC recipient = '.$ccRecipients);
foreach ($ccRecipients as $ccRecipient) {
$this->email->setCC(trim($ccRecipient));
if ($cc !== '') {
$ccRecipients = explode(',', trim($cc));
$this->logger->info('Helper : Email carbon copy CC recipient = ' . implode(',', $ccRecipients));
if (!empty($ccRecipients)) {
if (getenv('CI_ENVIRONMENT') === "production") {
$this->email->setCC('contact@vijayabharathambooks.com');
}
$this->email->setCC($ccRecipients);
}
} else {
if (getenv('CI_ENVIRONMENT') === "production") {
$this->email->setCC('contact@vijayabharathambooks.com');
}
}
if (!empty($bcc)) {
$bccRecipients = explode(',', $bcc);
$this->logger->info('Helper : Email blindcarboncopy BCC recipient = '.$bccRecipients);
foreach ($bccRecipients as $bccRecipient) {
$this->email->setBCC(trim($bccRecipient));
if ($bcc !== '') {
$bccRecipients = explode(',', trim($bcc));
$this->logger->info('Helper : Email blindcarboncopy BCC recipient = ' . implode(',', $bccRecipients));
if(!empty($bccRecipients)) {
$this->email->setBCC($bccRecipients);
}
}
if ($this->email->send()) {
$message['success'] = 'Email sent successfully';
$this->logger->info('Helper : Email = sent successfully');
$this->logger->info('Helper : Email Status = sent successfully');
} else {
throw new \Exception('Email sending failed.');
}
} catch (\Exception $e) {
$this->logger->error('Helper : Email Error: ' . $e->getMessage());
$this->logger->error('Helper : Email Error = ' . $e->getMessage());
$message['error'] = 'Email Exception Occur : ' . $e->getMessage();
}
return $message;
}
public function sendWhatsAppMessage($url,$method,$data)
public function sendWhatsAppMessage($url, $method, $data)
{
try{
$this->logger->info('Helper : Whatsapp');
$curl = curl_init();
$final_result = []; // Initialize outside try-catch block
try {
$this->logger->info('Helper : Whatsapp');
$curl = curl_init();
$headers = array('Content-Type:application/json');
$jsonencoded = json_encode($data);
curl_setopt( $curl,CURLOPT_URL, $url);
$this->logger->info('Helper : Whatsapp url = '.$url);
curl_setopt($curl, CURLOPT_URL, $url);
$this->logger->info('Helper : Whatsapp url = ' . $url);
switch ($method) {
case "POST":
curl_setopt( $curl,CURLOPT_POST, true );
curl_setopt($curl, CURLOPT_POST, true);
if ($data) {
$this->logger->info('Helper : Whatsapp jsonencoded = '.$jsonencoded);
curl_setopt( $curl,CURLOPT_POSTFIELDS, $jsonencoded);
$this->logger->info('Helper : Whatsapp jsonencoded = ' . $jsonencoded);
curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonencoded);
}
break;
case "PUT":
@ -93,36 +106,50 @@ class NotificationHelper
break;
default:
if ($data) {
// print_r($data);die();
$url = sprintf("%s?%s", $url, http_build_query((array)$data));
}
}
curl_setopt( $curl,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $curl,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl,CURLOPT_SSL_VERIFYPEER, true );
$curl_exec = curl_exec($curl);
$this->logger->info('Helper : Whatsapp Reponse = '.$curl_exec);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
$curl_exec = curl_exec($curl);
$this->logger->info('Helper : Whatsapp Reponse = ' . $curl_exec);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($http_status === 200) {
$result = json_decode($curl_exec);
if ($result->status === "error") {
$this->logger->error('Helper : Whatsapp Err occur = '.$result->message);
$final_result['message'] = $result->message;
$final_result['receiving_status'] = 0 ;
$this->logger->error('Helper : Whatsapp Err occur = ' . $result->message);
throw new \Exception($result->message);
}else{
$final_result = " Sended Success ";
}
}else{
$curl_errno= curl_errno($curl);
$this->logger->error('Helper : Whatsapp curl error occur = '.$curl_errno);
throw new \Exception(" Errno returned ".$curl_errno);
if ($result->status === "success") {
$final_result['message'] = isset($result->message) ? (
(strtolower(gettype($result->message)) === 'string') ?
$result->message : "Sended Success"
) : " Message Not Sent. ";
$final_result['receiving_status'] = isset($result->message) ? ((strtolower(gettype($result->message)) === 'string') ? 0 : 1 ) : 0 ;
}
} else {
$curl_errno = curl_errno($curl);
$this->logger->error('Helper : Whatsapp curl error occur = ' . $curl_errno);
throw new \Exception(" Errno returned " . $curl_errno);
}
curl_close($curl);
}catch (\Exception $e) {
curl_close($curl);
} catch (\Exception $e) {
$this->logger->error('Helper : Whatsapp Exception Occur = ' . $e->getMessage());
$final_result = "Exception Errno returned ".$e->getMessage()." <br/>";
$final_result['message'] = "Exception Errno returned " . $e->getMessage() . " <br/>";
$final_result['receiving_status'] = 0 ;
}
$final_result['reponse'] = json_decode($curl_exec);
return $final_result;
}
}
?>

View File

@ -9,7 +9,7 @@ class BusinessModel extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
protected $allowedFields = ['business_id','title','email','mobile_no','terms','address','city','state','postal_code' ,'business_logo','isactive', 'pan_no', 'org_reg_no', '80G'];
protected $allowedFields = ['business_id','title','email','mobile_no','terms','address','city','state','postal_code' ,'business_logo','isactive', 'pan_no', 'org_reg_no', '80G', 'signature'];
public function insertBusiness($data)
{

View File

@ -125,7 +125,7 @@ public function updateData($table, $data, $where)
->join('donor as C','C.donor_id= receipt.donor_id','left')
->join('business as B','B.business_id = receipt.business_id','left')
->select('receipt.*,concat(C.first_name," ",C.last_name) as customer_name,C.address, C.postal_code,C.city, C.state,C.mobile_no as customer_mobile, C.pan_no as cust_pan_no')
->select('B.title ,B.business_logo,B.terms,B.address,B.city,B.state,B.postal_code,B.email,B.mobile_no, B.pan_no, B.org_reg_no')
->select('B.title ,B.business_logo,B.terms,B.address as org_address ,B.city as org_city,B.state as org_state,B.postal_code as org_zip,B.email as org_email,B.mobile_no as org_mobile, B.pan_no as org_pan, B.org_reg_no, B.signature')
->get()
->getResult();

View File

@ -25,7 +25,7 @@ class NotificationModel extends Model
// $lastWeek = date('Y-m-d', strtotime('+7 days'));
// $date_format = date('Y-m-d', $date);
return $this->db->table('subscription as S' )
->join('donor as C', 'C.donor_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('business as B', 'B.business_id = S.business_id', 'left')
->join('book_categories as BC', 'BC.category_id = S.scheme_id', 'left')
@ -42,35 +42,37 @@ class NotificationModel extends Model
->join('users as U1', 'U1.user_id = T.created_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(U1.first_name," ",U1.last_name) as created_by_name,concat(U2.first_name," ",U2.last_name) as updated_by_name,T.isactive')
->whereNotIn('T.template_name',array('EXPIRAY_NOTIFY_TEMPLATE_EMAIL','EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP'))
->get()->getResultArray();
}
public function saveDetails($data,$pk_name,$t_name){
$id = $data[$pk_name];
$statement_string = ucfirst(str_replace('_', ' ', $t_name));
if($id != ''){
unset($data[$pk_name]); // Remove the id from the data to avoid updating it
unset($data['created_by']); // bcoz here data Updating here.
if ($this->db->table($t_name)->where($pk_name, $id)->update($data)) {
$affectedRows = $this->db->affectedRows();
$statement['success'] = ucfirst($t_name).' has been updated successfully.';
$statement['success'] = $statement_string.' has been updated successfully.';
$statement['error'] = "";
$statement['log'] = ucfirst($t_name).": 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;
} else {
$statement['success'] = "";
$statement['error'] = ucfirst($t_name).' update failed. Please try again.';
$statement['log'] = ucfirst($t_name).": Err Failed to update ID = " .$id ;
$statement['error'] = $statement_string.' update failed. Please try again.';
$statement['log'] = $statement_string.": Err Failed to update ID = " .$id ;
}
}else{
unset($data['updated_by']);
if ($this->db->table($t_name)->insert($data)) {
$insertID = $this->db->insertID();
$statement['success'] = ucfirst($t_name).' has been Inserted successfully.';
$statement['success'] = $statement_string.' has been Inserted successfully.';
$statement['error'] = "";
$statement['log'] = ucfirst($t_name).": has been added successfully. Inserted ID = " .$insertID ;
$statement['log'] = $statement_string.": has been added successfully. Inserted ID = " .$insertID ;
} else {
$statement['success'] = "";
$statement['error'] = ucfirst($t_name)." could not be added. Please try again..";
$statement['log'] = ucfirst($t_name).": Err 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.";
}
}
return $statement;
@ -81,7 +83,8 @@ public function getCampaignDetails(){
->join('users as U1', 'U1.user_id = NC.created_by', 'left')
->join('users as U2', 'U2.user_id = NC.updated_by', '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(U1.first_name," ",U1.last_name) as created_by_name,concat(U2.first_name," ",U2.last_name) as updated_by_name,NC.isactive,NC.group_id,NC.scheduled_date,NC.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(U1.first_name," ",U1.last_name) as created_by_name,concat(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('EXPIRAY_NOTIFY_TEMPLATE_EMAIL','EXPIRAY_NOTIFY_TEMPLATE_WHATSAPP'))
->get()->getResultArray();
if (!empty($result)) {
@ -90,7 +93,7 @@ public function getCampaignDetails(){
$group_names = [];
$group_query = [];
foreach ($group_id as $j) {
$cg_data = $this->db->table('donor_groups as CG')
$cg_data = $this->db->table('customer_groups as CG')
->select('CG.group_id, CG.group_name,CG.group_query, CG.isactive')
->where(['CG.isactive' => 1, 'CG.group_id' => $j])
->get()
@ -103,8 +106,8 @@ public function getCampaignDetails(){
}
}
$result[$i]['group_name'] = !empty($group_names) ? implode(", ", $group_names) : '';
$result[$i]['donor_group'] = !empty($group_query) ? $this->customerGroupQueryExecution($group_query) : '';
$result[$i]['donor_group_count'] = !empty($result[$i]['donor_group']) ? count($this->customerGroupQueryExecution($group_query)) : 0;
$result[$i]['customer_group'] = !empty($group_query) ? $this->customerGroupQueryExecution($group_query) : '';
$result[$i]['customer_group_count'] = !empty($result[$i]['customer_group']) ? count($this->customerGroupQueryExecution($group_query)) : 0;
}
}
return $result;
@ -145,11 +148,15 @@ public function customerGroupQueryExecution($queries){
// echo "</pre>";
// die;
}
// $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'),
// (1, 1, '9638527411','whatapp msg',NULL,'2023-12-22 14:20:50')";
// $result = $db->query($query)->getResultArray();
public function getExpDate()
{
$db = \Config\Database::connect();
$query = "SELECT * FROM donor_groups WHERE group_name = 'EXPIRYDAT'";
$query = "SELECT * FROM customer_groups WHERE group_name = 'EXPIRYDATE'";
$result = $db->query($query)->getResultArray();
@ -164,10 +171,10 @@ public function customerGroupQueryExecution($queries){
}
}
public function getTempName()
public function getTempName($constant)
{
$db = \Config\Database::connect();
$query = "SELECT * FROM templates WHERE template_name = '".EXPIRAY_NOTIFY_TEMPLATE_EMAIL."'";
$query = "SELECT * FROM templates WHERE template_name = '".$constant."'";
// print_r($query);die;
$result = $db->query($query)->getResultArray();
if (isset($result)) {
@ -180,6 +187,86 @@ public function customerGroupQueryExecution($queries){
}
}
public function update_notification_campaign_status($data,$id){
if($id != ''){
$where = ['isactive' => 1, 'status' => 0 ,'campaign_id'=>(int)$id];
if ($this->db->table('notification_campaign')->where($where)->update($data)) {
$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 ;
} else {
$statement = "Notification Campaign Status Update failed. NCID = " .$id;
}
}
else{
$statement = "Notification Campaign Status Update failed. Bcoz Not Found NCID";
}
return $statement;
}
public function save_notification_history_parents($data){
$this->db->table('notification_history_parents')->insert($data);
$insertID = $this->db->insertID();
return $insertID;
}
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 ($this->db->table('notification_history_parents')->where($where)->update($data)) {
$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 ;
} else {
$statement = "Notification history parent Status Update failed. NHPID = " .$id;
}
}
else{
$statement = "Notification history parent Status Update failed. Bcoz Not Found NHPID";
}
return $statement;
}
public function save_notification_history_child($data){
// $this->db->ignore(true); // Enable "INSERT IGNORE" behavior
// $this->db->table('notification_history_children')->insert($data);
// $insertID = $this->db->insertID(); // Get the last inserted ID
// return $insertID;
// $insert_query = $this->db->insert_string('notification_history_children', $data);
// $insert_query = str_replace('INSERT INTO', 'INSERT IGNORE INTO', $insert_query);
// $this->db->query($insert_query);
// $insertID = $this->db->insertID(); // Get the last inserted ID
// return $insertID;
$table = 'notification_history_children';
$insert_query = "INSERT IGNORE INTO $table (" . implode(', ', array_keys($data)) . ") VALUES (" . rtrim(str_repeat('?, ', count($data)), ', ') . ")";
$this->db->query($insert_query, array_values($data));
// print_r($this->db->getLastQuery());die;
$insertID = $this->db->insertID();
return $insertID;
}
public function update_notification_history_child($data, $where){
$id = isset($where['id']) ? $where['id'] : "";
if ($id != '') {
$updateResult = $this->db->table('notification_history_children')->where($where)->update($data);
// print_r($this->db->getLastQuery());die;
if ($updateResult) {
$affectedRows = $this->db->affectedRows();
$statement = 'Notification history children has been updated successfully. Aff Row ' . $affectedRows . ' NHCID = ' . $id;
} else {
$statement = 'Notification history children Update failed. NHCID = ' . $id;
}
} else {
$statement = 'Notification history children Update failed. Bcoz Not Found NHCID';
}
return $statement;
}
}

View File

@ -96,18 +96,33 @@
<?php } ?>
</div>
<?php if (!empty($businesses['business_logo'])) { ?>
<div class="form-group col-md-12">
<label for="bfile" class="col-form-label">Current Organization Logo</label>
<img src="<?= base_url('public/uploads/' . $businesses['business_logo']) ?>" alt="Organization Logo" class="preview-image" />
</div>
<?php } ?>
<div class="form-row">
<div class="form-group col-md-12">
<div class="form-group col-md-6">
<label for="bfile" class="col-form-label">Organization Logo</label>
<input type="file" class="form-control" style="border: 0px !important;" id="bfile" name="bfile" value="<?= isset($businesses['business_logo']) ? $businesses['business_logo'] : null ?>" multiple />
</div>
<?php if (!empty($businesses['business_logo'])) { ?>
<div class="form-group col-md-6">
<label for="bfile" class="col-form-label">Current Organization Logo</label>
<img src="<?= base_url('public/uploads/' . $businesses['business_logo']) ?>" alt="Organization Logo" class="preview-image" />
</div>
<?php } ?>
<div class="form-group col-md-6">
<label for="bfile" class="col-form-label">Signature</label>
<input type="file" onchange="validateImage(this)" class="form-control" style="border: 0px !important;" id="signature" name="signature" value="<?= isset($businesses['signature']) ? $businesses['signature'] : null ?>" multiple />
<p id="error-message"></p>
</div>
<?php if (!empty($businesses['signature'])) { ?>
<div class="form-group col-md-6">
<label for="bfile" class="col-form-label">Current Signature</label>
<img src="<?= base_url('public/uploads/' . $businesses['signature']) ?>" alt="Signature" class="preview-image" />
</div>
<?php } ?>
</div>
<input type="hidden" id="business_id" name="business_id" placeholder="hidden for Organization id" value="<?= isset($businesses['business_id']) ? $businesses['business_id'] : '' ?>" />
@ -143,4 +158,32 @@
$('#submitBtn').prop('disabled', true);
}
});
function validateImage(input) {
const errorMessageElement = document.getElementById('error-message');
errorMessageElement.textContent = '';
const image = input.files[0];
// Check image type
const allowedImageTypes = ['image/jpeg', 'image/png', 'image/gif']; // Add more if needed
if (!allowedImageTypes.includes(image.type)) {
errorMessageElement.textContent = 'Invalid image type. Please select a JPEG, PNG, or GIF image.';
return;
}
const maxWidth = 150;
const maxHeight = 100;
const img = new Image();
img.onload = function () {
if (img.width > maxWidth || img.height > maxHeight) {
errorMessageElement.textContent = `Image dimensions should not exceed ${maxWidth}x${maxHeight}.`;
}
};
img.src = URL.createObjectURL(image);
}
</script>

View File

@ -86,7 +86,7 @@ body{
.invoice_wrapper .header .bill_total_wrap .total_wrap{
text-align: right;
position: relative;
bottom: 80px;
bottom: 90px;
}
.invoice_wrapper .header .invoice_sec .invoice{
@ -147,12 +147,14 @@ body{
.invoice_wrapper .body .paymethod_grandtotal_wrap{
display: flex;
justify-content: space-between;
padding: 5px 0px 30px;
padding: 5px 0px 15px;
align-items: flex-end;
}
.invoice_wrapper .body .paymethod_grandtotal_wrap .paymethod_sec{
padding-left: 20px;
position: relative;
bottom: 50px;
}
.invoice_wrapper .body .paymethod_grandtotal_wrap .grandtotal_sec{
@ -185,7 +187,7 @@ body{
}
.invoice_wrapper .footer{
padding: 30px;
padding: 10px;
}
.invoice_wrapper .footer > p{
@ -203,7 +205,7 @@ body{
.total_wrap{
text-align: right;
position: relative;
bottom: 50px;
bottom: 90px;
right: 20px
}
@ -223,22 +225,26 @@ body{
<div class="header">
<div class="logo_invoice_wrap">
<div class="logo_sec">
<img class="images" src="<?= base_url()."public/assets/images/default_logo.png" ?>" height="50" width="50" >
<img class="images" src="<?= base_url()."public/uploads/".$data->business_logo ?>" height="50" width="50" >
<div class="title_wrap">
<p class="title bold"><?= $data->title ?></p>
<p class="sub_title"><?= $data->address ?></p>
<p class="sub_title"><?= $data->postal_code ?></p>
<p class="sub_title">Email : <?= $data->org_email ?></p>
<p class="sub_title">PAN No : <?= $data->org_pan ?></p>
<p class="sub_title">Register N0 :<?= $data->org_reg_no ?></p>
<p class="sub_title"><?= $data->org_address ?>, <?= $data->org_city ?>,</p>
<p class="sub_title"><?= $data->org_state ?> ,<?= $data->org_zip ?>. MobileNo : <?= $data->org_mobile ?></p>
</div>
</div>
</div>
<div class="bill_total_wrap">
<div class="bill_total_wrap" style="position: relative;top: -32px;">
<div class="bill_sec">
<p>Bill To</p>
<p class="bold name"><?=$data->customer_name?></p>
<span>
<?=$data->mobile_no?><br>
<?=$data->address?><br>
Monile No : <?=$data->customer_mobile?><br>
PAN No : <?=$data->cust_pan_no?><br>
Address :<?=$data->address?><br>
</span>
</div>
@ -250,7 +256,7 @@ body{
</p>
<p class="date">
<span class="bold">Date :</span>
<span><?=$data->receipt_date?></span>
<span><?=date("d-m-Y", strtotime($data->receipt_date));?></span>
</p>
</div>
</div>
@ -267,11 +273,22 @@ body{
<p class="bold price">Rs. <?=$data->amount?> /-</p>
</div>
</div>
<div class="paymethod_grandtotal_wrap" style="position: relative;top: 20px;">
<div class="total_wrap">
<div class="logo_invoice_wrap">
<div class="logo_sec">
<img class="images" src="<?= base_url()."public/uploads/".$data->signature ?>" height="50" width="50" style="position: relative; left: -13px;top: 4px;" >
</div>
</div>
<p class="bold">signature</p>
</div>
</div>
</div>
<div class="footer">
<div class="footer" style="position: relative;bottom: 60px;">
<p>Thank you and Best Wishes</p>
<p class="bold">Receipt Note:</p>
<div class="terms">
<p class="tc bold">Terms & Coditions</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit non praesentium doloribus. Quaerat vero iure itaque odio numquam, debitis illo quasi consequuntur velit, explicabo esse nesciunt error aliquid quis eius!</p>
</div>
</div>

View File

@ -52,7 +52,9 @@
</button>
</div>
<?php endif; ?>
<?php endif; ?>
<?php
unset($_SESSION['success']);unset($_SESSION['error']);
endif; ?>
<div id="textDiv">
<span class="widget-simple text-center">
<div class="media-body align-self-center font-24 avatar-title">
@ -112,7 +114,7 @@
<label for="body" class="col-4 col-form-label">Body</label>
<div class="col-7">
<textarea id="summernote-basic" name="description" class="form-control" rows="7">
<h5>Hello {User}, </h5>
<h5>Hello {USER_NAME}, </h5>
<p>We create simple, flat & responsive custom mail template.</p>
<p>Please, write text here!</p>
</textarea>
@ -176,7 +178,7 @@
<div class="form-group row">
<label for="message" class="col-4 col-form-label">Message</label>
<div class="col-7">
<textarea id="message" name="description" class="form-control" rows="5">Hello {User},Please,write text here!</textarea>
<textarea id="message" name="description" class="form-control" rows="5">Hello {USER_NAME},Please,write text here!</textarea>
</div>
</div>
<div class="form-group text-right m-b-0">

View File

@ -30,14 +30,37 @@
<input type="text" class="form-control" id="subject" name="subject" value="<?= isset($template_details['subject']) ? $template_details['subject'] : '' ?>" placeholder="Subject" />
</div>
<div class="form-group col-md-12">
<label for="templatemessage" class="col-form-label">Template Message<span class="text-danger"> *</span></label>
<textarea id="summernote-basic" name="templatemessage" class="form-control" rows="7">
<?php if(isset($template_details['message'])){ echo $template_details['message']; }else{ ?>
<h5>Hello {User}, </h5>
<p>Please, write text here!</p>
<?php } ?>
</textarea>
<div class="form-group col-md-12" id="emailDescription" style="display: block;">
<div>
<label for="templatemessage" class="col-form-label">Template Message<span class="text-danger"> *</span></label>
<textarea id="summernote-basic" name="templatemessage" class="form-control templatemessage" rows="7">
<?php
if(isset($template_details['message']) && $template_details['message'] != ""){
echo $template_details['message'];
}
else{
echo "Sample Template :<br>
Hello {USER_NAME},<br>
&emsp; Please, write text here!.";
} ?>
</textarea>
<span class="help-block"><small>Keywords are {USER_NAME},{SCHEME_NAME},{EXPIRY_DATE}</small></span>
</div>
<div class="invalid-feedback"> Please provide. </div>
</div>
<div class="form-group col-md-12" id="whatsappDescription" style="display: none;">
<div>
<label for="whatsapptemplatemessage" class="col-form-label">Template Message<span class="text-danger"> *</span></label>
<textarea name="whatsapptemplatemessage" class="form-control whatsapptemplatemessage" rows="7" placeholder="Write something...">
<?php if(isset($template_details['message']) && $template_details['message'] != ""){ echo $template_details['message']; }
else{ echo "Sample Template : \n Hello {USER_NAME}, \n\t\t Please, write text here!.";
} ?>
</textarea>
<span class="help-block"><small>Keywords are {USER_NAME},{SCHEME_NAME},{EXPIRY_DATE}</small></span>
</div>
<div class="invalid-feedback"> Please provide. </div>
</div>
</div>
<input type="hidden" id="template_id" name="template_id" placeholder="hidden for template id" value="<?= isset($template_details['template_id']) ? $template_details['template_id'] : '' ?>" />
@ -70,8 +93,30 @@
var selectedValue = $(this).val();
if (selectedValue === 'Email') {
$('#emailSubject').show();
$('#emailDescription').show();
$('#whatsappDescription').hide();
$('.templatemessage').prop('required',true);
$('.whatsapptemplatemessage').prop('required',false);
} else {
$('#emailSubject').hide();
$('#emailDescription').hide();
$('#whatsappDescription').show();
$('.templatemessage').prop('required',false);
$('.whatsapptemplatemessage').prop('required',true);
whatsapptemplatemessage = $('.whatsapptemplatemessage').val();
if ((whatsapptemplatemessage!==null) || (whatsapptemplatemessage!=='')){
finaltemplate = whatsapptemplatemessage.replace(/<[^>]*>/g, '');
$('.whatsapptemplatemessage').val(finaltemplate.replace(/^\s+/, ''));
}
// if(whatsapptemplatemessage == ''){
// var regex = /(<([^>]+)>)/ig;
// finaltemplate = whatsapptemplatemessage.replace(regex, "");
// $('.whatsapptemplatemessage').val(finaltemplate);
// }
}
});
@ -83,10 +128,20 @@
emailRadio.checked = true;
whatsappRadio.checked = false;
$('#emailSubject').show();
$('#emailDescription').show();
$('#whatsappDescription').hide();
$('.templatemessage').prop('required',true);
$('.whatsapptemplatemessage').prop('required',false);
}else if(mode == 'Whatsapp'){
emailRadio.checked = false;
whatsappRadio.checked = true;
$('#emailSubject').hide();
$('#emailDescription').hide();
$('#whatsappDescription').show();
$('.templatemessage').prop('required',false);
$('.whatsapptemplatemessage').prop('required',true);
}
}
@ -100,7 +155,26 @@
event.preventDefault(); // Prevent form submission if it's not valid
$('#submitBtn').prop('disabled', false);
} else {
$('#submitBtn').prop('disabled', true);
var chooseMode = $('input[name="mode"]').val();
var templatemessage = "";
var fieldname = "";
if (chooseMode === 'Email') {
templatemessage = $('.templatemessage').val();
fieldname = '.templatemessage';
} else if(chooseMode === 'Whatsapp') {
templatemessage = $('.whatsapptemplatemessage').val();
fieldname = '.whatsapptemplatemessage';
}
if(templatemessage == ""){
event.preventDefault(); // Prevent form submission if it's not valid
form.reportValidity();
alert('Template message should not be empty.');
templatemessage = $(fieldname).focus();
$('#submitBtn').prop('disabled', false);
}else{
$('#submitBtn').prop('disabled', true);
}
}
});
</script>