diff --git a/app/Controllers/Business.php b/app/Controllers/Business.php index 37ac81d..9a437af 100644 --- a/app/Controllers/Business.php +++ b/app/Controllers/Business.php @@ -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 diff --git a/app/Controllers/Invoice.php b/app/Controllers/Invoice.php index 0383166..20f0cce 100644 --- a/app/Controllers/Invoice.php +++ b/app/Controllers/Invoice.php @@ -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'] = "
Dear $recipient_name,
-We are pleased to inform you that your Invoice has been approved.
-Details:
-Best regards,
-';
// 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'] = "VBP Approve Information
+ // Dear $recipient_name,
+ // We are pleased to inform you that your Invoice has been approved.
+ // Details:
+ // Best regards,
+ //";
// print_r($details);
// echo "";
// 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'] = "
Hello ".$recipient_name.",
+Hello " . $recipient_name . ",
This is a reminder that the following subscription is due soon:
-Subscription Name:".$subscription_name."
-Due Date: ".$to_subscription."
+Subscription Name:" . $subscription_name . "
+Due Date: " . $to_subscription . "
Please make sure to complete this subscription on time.
Thank you.
@@ -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; } - - \ No newline at end of file + + + #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 ################ + +} diff --git a/app/Helpers/NotificationHelper.php b/app/Helpers/NotificationHelper.php index 4603c5a..da34e98 100644 --- a/app/Helpers/NotificationHelper.php +++ b/app/Helpers/NotificationHelper.php @@ -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()."= $data->title ?>
-= $data->address ?>
-= $data->postal_code ?>
+Email : = $data->org_email ?>
+PAN No : = $data->org_pan ?>
+Register N0 := $data->org_reg_no ?>
+= $data->org_address ?>, = $data->org_city ?>,
+= $data->org_state ?> ,= $data->org_zip ?>. MobileNo : = $data->org_mobile ?>
Bill To
+=$data->customer_name?>
- =$data->mobile_no?>Date : - =$data->receipt_date?> + =date("d-m-Y", strtotime($data->receipt_date));?>
Rs. =$data->amount?> /-
signature
+