Compare commits

...

10 Commits

Author SHA1 Message Date
bca9ba3ca5 Log files added by Sriram R for Payment logs track 2026-09-01 16:43:04 +05:30
Srinivas-Saravanan
e420e651db FIX_PAYMENT_STATUS_NAME_ISSUE 2025-05-20 15:54:16 +05:30
Srinivas-Saravanan
d68674377b REMOVES_SMS_TEST 2025-05-16 10:53:24 +05:30
Srinivas-Saravanan
3a042dceba CHANGE_EMAIL_SUB_LINK 2025-04-30 17:46:27 +05:30
Srinivas-Saravanan
7fd45d8749 FIX_SMS_EMPTY_MOBILE_CASE 2025-04-30 17:35:17 +05:30
Srinivas-Saravanan
f04d40a452 FEAT_SMS_INTEGRATION 2025-04-30 16:23:29 +05:30
Srinivas-Saravanan
c45493eb0a FEAT_URL_QUERY_PARAM_SRI 2025-04-21 12:34:17 +05:30
Srinivas-Saravanan
c9596d7af6 CHANGE_LISTING_ORDER_IN_PAYMENT_STATUS 2025-03-07 17:48:08 +05:30
Srinivas-Saravanan
6bbb97f1ec CHANGE_BASE_URL_IN_CONFIG 2025-03-07 17:34:27 +05:30
Srinivas-Saravanan
a85a43f69c FIX_INVOICE_ORDER_IN_REPORTS 2025-03-07 16:02:22 +05:30
23 changed files with 2499 additions and 1619 deletions

View File

@ -18,7 +18,6 @@ class App extends BaseConfig
* *
* http://example.com/ * http://example.com/
*/ */
// public string $baseURL = 'http://localhost:8080/';
public string $baseURL = 'http://localhost/vb_book/'; public string $baseURL = 'http://localhost/vb_book/';
/** /**

View File

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

View File

@ -202,6 +202,16 @@ $routes->get('/payment_process','Payment::payment_process');
$routes->get('payment_success','Payment::payment_success'); $routes->get('payment_success','Payment::payment_success');
$routes->match(['get','post'],'/subscription_renewal/(:any)','Payment::index/$1'); $routes->match(['get','post'],'/subscription_renewal/(:any)','Payment::index/$1');
$routes->match(['get','post'],'payment_status','Payment::paymentStatus'); $routes->match(['get','post'],'payment_status','Payment::paymentStatus');
$routes->post('payment_reconcile','Payment::reconcileOrder');
// Logs -> List/View/Download
$routes->group('logs', ['namespace' => 'App\Controllers'], function ($routes) {
$routes->get('/', 'LogViewer::index');
$routes->get('view/(:any)', 'LogViewer::view/$1');
$routes->get('download/(:any)', 'LogViewer::download/$1');
});
// Logs // Logs
@ -210,6 +220,7 @@ $routes->get('/list_log','Payment::listLogs');
$routes->get('/download_log/(:any)','Payment::downloadLog/$1'); $routes->get('/download_log/(:any)','Payment::downloadLog/$1');
$routes->get('/view_log/(:any)','Payment::viewLog/$1'); $routes->get('/view_log/(:any)','Payment::viewLog/$1');
$routes->get("testSMS","Payment::testSMS");
// $routes->group("api", function ($routes) { // $routes->group("api", function ($routes) {

View File

@ -865,6 +865,9 @@ class ApiIntegration extends ResourceController
$basic_message .= $insert_result['info'] ? " Invoice id : " . $insert_result['info'] : "Invoice details Not Inserted"; $basic_message .= $insert_result['info'] ? " Invoice id : " . $insert_result['info'] : "Invoice details Not Inserted";
$insert_result['info'] ? $this->logger->info("Api SaveSalesDetails : Invoice id = ".$insert_result['info']):""; $insert_result['info'] ? $this->logger->info("Api SaveSalesDetails : Invoice id = ".$insert_result['info']):"";
$insert_result['err'] ? $this->logger->error("Api SaveSalesDetails : Err = ".$insert_result['err']):""; $insert_result['err'] ? $this->logger->error("Api SaveSalesDetails : Err = ".$insert_result['err']):"";
if ($insert_result['info']) {
log_message('info', '[PAYMENT] Online store payment received — WooCommerce order ' . $wordpress_order_id . ', invoice ' . ($invoice_data['invoice_number'] ?? '') . ', amount Rs.' . ($invoice_data['exact_total_amount'] ?? $invoice_data['total_amount'] ?? 0) . ', method ' . ($invoice_data['payment_method'] ?? '') . ', payment status ' . ($invoice_data['payment_status'] ?? ''));
}
} else { } else {
$last_insert_invoice_id = $invoice_id; $last_insert_invoice_id = $invoice_id;
$customer_where = ['invoice_id' => $invoice_id, 'isactive' => 1, 'wp_api_order_id' => $wordpress_order_id]; $customer_where = ['invoice_id' => $invoice_id, 'isactive' => 1, 'wp_api_order_id' => $wordpress_order_id];
@ -875,6 +878,9 @@ class ApiIntegration extends ResourceController
$basic_message .= "Invoice id : " . $last_insert_invoice_id; $basic_message .= "Invoice id : " . $last_insert_invoice_id;
$update_result['info'] ? $this->logger->info("Api SaveSalesDetails : Invoice id : " . $last_insert_invoice_id . " ( " . $update_result['info'] . ")"):""; $update_result['info'] ? $this->logger->info("Api SaveSalesDetails : Invoice id : " . $last_insert_invoice_id . " ( " . $update_result['info'] . ")"):"";
$update_result['err'] ? $this->logger->error("Api SaveSalesDetails : Err = ".$update_result['err']):""; $update_result['err'] ? $this->logger->error("Api SaveSalesDetails : Err = ".$update_result['err']):"";
if ($update_result['info']) {
log_message('info', '[PAYMENT] Online store payment updated — WooCommerce order ' . $wordpress_order_id . ', invoice ' . ($invoice_data['invoice_number'] ?? '') . ', amount Rs.' . ($invoice_data['exact_total_amount'] ?? $invoice_data['total_amount'] ?? 0) . ', method ' . ($invoice_data['payment_method'] ?? '') . ', payment status ' . ($invoice_data['payment_status'] ?? ''));
}
} }
$line_item_data = []; $line_item_data = [];

View File

@ -424,6 +424,7 @@ class Invoice extends BaseController
// Send notification if invoice is approved // Send notification if invoice is approved
$this->logger->info($msg_flag_name . ": ID = " . $invoice_id . ", Status =" . $invoice_status); $this->logger->info($msg_flag_name . ": ID = " . $invoice_id . ", Status =" . $invoice_status);
if ($invoice_status == 'Approved' && $invoice_id != "") { if ($invoice_status == 'Approved' && $invoice_id != "") {
log_message('info', '[PAYMENT] Approved ' . trim($msg_flag_name) . ' saved with payment — invoice ID ' . $invoice_id);
if(null!=($this->request->getPost('contact_method_mail'))){ if(null!=($this->request->getPost('contact_method_mail'))){
$contact_method['msg_mail'] = 1; $contact_method['msg_mail'] = 1;
@ -444,6 +445,7 @@ class Invoice extends BaseController
} catch (\Exception $e) { } catch (\Exception $e) {
$this->logger->error("Error Occurred: " . $e->getMessage()); $this->logger->error("Error Occurred: " . $e->getMessage());
log_message('error', '[PAYMENT] Invoice save failed: ' . $e->getMessage());
session()->setFlashdata('error', 'Message: ' . $e->getMessage()); session()->setFlashdata('error', 'Message: ' . $e->getMessage());
} }
} }
@ -460,6 +462,7 @@ public function create_or_update_invoice($invoice_id, $msg_flag_name)
$data['created_by'] = (int)get_logged_user_id(); $data['created_by'] = (int)get_logged_user_id();
if ($model->insert($data, 'invoices')) { if ($model->insert($data, 'invoices')) {
$invoice_id = $model->insertID(); $invoice_id = $model->insertID();
$this->logInvoicePayment('created', $data, (int) $invoice_id);
if($data['status'] == 'Approved'){ if($data['status'] == 'Approved'){
session()->setFlashdata('success', $msg_flag_name . 'has been added successfully.'); session()->setFlashdata('success', $msg_flag_name . 'has been added successfully.');
$this->logger->info($msg_flag_name . ": Added successfully. ID = " . $invoice_id); $this->logger->info($msg_flag_name . ": Added successfully. ID = " . $invoice_id);
@ -474,6 +477,7 @@ public function create_or_update_invoice($invoice_id, $msg_flag_name)
} else { } else {
$data['updated_by'] = (int)get_logged_user_id(); $data['updated_by'] = (int)get_logged_user_id();
if ($model->update($invoice_id, $data)) { if ($model->update($invoice_id, $data)) {
$this->logInvoicePayment('updated', $data, (int) $invoice_id);
session()->setFlashdata('success', $msg_flag_name . 'has been updated successfully.'); session()->setFlashdata('success', $msg_flag_name . 'has been updated successfully.');
$this->logger->info($msg_flag_name . ": Updated successfully. ID = " . $invoice_id); $this->logger->info($msg_flag_name . ": Updated successfully. ID = " . $invoice_id);
} else { } else {
@ -554,7 +558,6 @@ public function create_or_update_subscription($invoice_id,$invoice_status, $msg_
$renewal = 0; $renewal = 0;
if (!empty($membership_id)){ if (!empty($membership_id)){
$sub_id = $subModel->select('sub_id')->where('membership_id',$membership_id)->first(); $sub_id = $subModel->select('sub_id')->where('membership_id',$membership_id)->first();
log_message('error','going to call the function');
$this->checkPaymentStatus($membership_id); $this->checkPaymentStatus($membership_id);
} }
foreach ($invoiceItems as $item) { foreach ($invoiceItems as $item) {
@ -606,22 +609,38 @@ public function create_or_update_subscription($invoice_id,$invoice_status, $msg_
} }
public function checkPaymentStatus($membership_id){ public function checkPaymentStatus($membership_id){
log_message("error","Function Called");
try { try {
$id = $this->paymentModel->where('membership_id', $membership_id)->where('payment_status','Not Received')->first()['id']; $paymentRow = $this->paymentModel->where('membership_id', $membership_id)->where('payment_status','Not Received')->first();
if ($id) { if ($paymentRow) {
$data['status'] = 999999; $this->paymentModel->update($paymentRow['id'], [
$data['payment_status'] = "Approved"; 'status' => 999999,
$data['updated_by'] = (int)get_logged_user_id(); 'payment_status' => 'Approved',
$this->paymentModel->update($id, $data); 'updated_by' => (int) get_logged_user_id(),
log_message('error', 'Payment Status Found and updated by User' . $data['updated_by']); ]);
log_message('info', '[PAYMENT] Staff recorded offline renewal for membership ' . $membership_id . ' — linked Paytm order ' . ($paymentRow['order_id'] ?? '') . ' marked as Approved by user ' . get_logged_user_id());
} else { } else {
log_message("error", "id not found" . $membership_id); log_message('debug', '[PAYMENT] No pending Paytm payment found to approve for membership ' . $membership_id);
}
} catch (\Exception $e) {
log_message('warning', '[PAYMENT] Could not update payment status for membership ' . $membership_id . ': ' . $e->getMessage());
} }
}catch (\Exception $e){
log_message('error','Id not found on the checkpaymentstatus ');
} }
private function logInvoicePayment(string $action, array $invoiceData, int $invoiceId): void
{
$type = ((int) ($invoiceData['invoice_type'] ?? 0) === 2) ? 'Subscription' : 'Invoice';
$status = $invoiceData['status'] ?? 'Unknown';
$method = $invoiceData['payment_method'] ?? 'Not specified';
$amount = $invoiceData['exact_total_amount'] ?? ($invoiceData['total_amount'] ?? 0);
$number = $invoiceData['invoice_number'] ?? (string) $invoiceId;
$customerId = $invoiceData['customer_id'] ?? '';
if ($status === 'Draft') {
log_message('info', '[PAYMENT] ' . $type . ' draft saved — invoice ' . $number . ', customer ' . $customerId . ', amount Rs.' . $amount . '. Payment not recorded yet.');
return;
}
log_message('info', '[PAYMENT] ' . $type . ' ' . $action . ' — invoice ' . $number . ', customer ' . $customerId . ', amount Rs.' . $amount . ', method ' . $method . ', payment status ' . ($invoiceData['payment_status'] ?? ''));
} }
@ -740,12 +759,17 @@ public function create_or_update_subscription($invoice_id,$invoice_status, $msg_
$this->logger->Info("Invoice : Going to Inactive ID = " . $id); $this->logger->Info("Invoice : Going to Inactive ID = " . $id);
if ($existed) { if ($existed) {
$invoiceRow = $model->select('invoice_number, payment_method, payment_status, total_amount')
->where('invoice_id', (int) $id)->first();
$data['isactive'] = 0; $data['isactive'] = 0;
$data['updated_by'] = get_logged_user_id(); $data['updated_by'] = get_logged_user_id();
if ($model->update($id, $data)) { if ($model->update($id, $data)) {
session()->setFlashdata('success', 'Deleted successfully.'); session()->setFlashdata('success', 'Deleted successfully.');
$this->logger->info("Invoice: has been Inactived successfully. Inactived ID = " . $id); $this->logger->info("Invoice: has been Inactived successfully. Inactived ID = " . $id);
if ($invoiceRow && ($invoiceRow['payment_status'] ?? '') === 'Paid') {
log_message('warning', '[PAYMENT] Paid invoice ' . ($invoiceRow['invoice_number'] ?? '') . ' was deleted (ID ' . $id . '), method ' . ($invoiceRow['payment_method'] ?? ''));
}
} else { } else {
$this->logger->error("Invoice: Not able to Inactive ID =" . $id); $this->logger->error("Invoice: Not able to Inactive ID =" . $id);
throw new \Exception("Data Not able to Deleted"); throw new \Exception("Data Not able to Deleted");
@ -779,8 +803,13 @@ public function create_or_update_subscription($invoice_id,$invoice_status, $msg_
$where = ['isactive' => 1, 'status' => 'Approved', 'invoice_id' => (int)$id]; $where = ['isactive' => 1, 'status' => 'Approved', 'invoice_id' => (int)$id];
$details = $model->where($where)->findAll(); $details = $model->where($where)->findAll();
if (empty($details)) { // Array Empty Means allow to Approve. if (empty($details)) { // Array Empty Means allow to Approve.
$invoiceRow = $model->select('invoice_number, customer_id, total_amount, exact_total_amount, payment_method, payment_status, invoice_type')
->where('invoice_id', (int) $id)->first();
$data = ['status' => 'Approved', 'updated_by' => get_logged_user_id()]; $data = ['status' => 'Approved', 'updated_by' => get_logged_user_id()];
if ($model->update($id, $data)) { if ($model->update($id, $data)) {
if ($invoiceRow) {
$this->logInvoicePayment('approved', array_merge($invoiceRow, ['status' => 'Approved']), (int) $id);
}
$this->approve_notifications((int)$id); $this->approve_notifications((int)$id);
session()->setFlashdata('success', 'Invoice has been Approved Successfully.'); session()->setFlashdata('success', 'Invoice has been Approved Successfully.');
$this->logger->info("Invoice: has been Approved successfully. ID = " . $id); $this->logger->info("Invoice: has been Approved successfully. ID = " . $id);

View File

@ -0,0 +1,167 @@
<?php
namespace App\Controllers;
class LogViewer extends BaseController
{
protected $logsPath;
public function __construct()
{
$this->logsPath = WRITEPATH . 'logs/';
}
public function index()
{
$files = [];
if (is_dir($this->logsPath)) {
$items = scandir($this->logsPath);
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$fullPath = $this->logsPath . $item;
if (is_file($fullPath)) {
$files[] = [
'name' => $item,
'size' => $this->formatSize(filesize($fullPath)),
'modified' => date('Y-m-d H:i:s', filemtime($fullPath)),
];
}
}
}
usort($files, function ($a, $b) {
return strcmp($b['modified'], $a['modified']);
});
$showPayment = $this->request->getGet('payment') === '1';
$entries = [];
$lineCount = 0;
if ($showPayment) {
foreach ($files as $file) {
$fullPath = $this->logsPath . $file['name'];
$lines = $this->extractPaymentLogLines($fullPath);
if (!empty($lines)) {
$entries[] = [
'file' => $file['name'],
'lines' => $lines,
];
$lineCount += count($lines);
}
}
}
$data['files'] = $files;
$data['showPayment'] = $showPayment;
$data['entries'] = $entries;
$data['lineCount'] = $lineCount;
$data['page_name'] = $showPayment ? 'Payment Logs' : 'Log Files';
$this->render_page('logviewer/index', $data);
}
public function view($filename = null)
{
$filename = $this->sanitizeFilename($filename);
if (!$filename) {
return redirect()->to('/logs')->with('error', 'Invalid file name.');
}
$fullPath = $this->logsPath . $filename;
if (!is_file($fullPath)) {
return redirect()->to('/logs')->with('error', 'File not found.');
}
$showPayment = $this->request->getGet('payment') === '1';
$content = file_get_contents($fullPath);
if ($showPayment) {
$lines = $this->extractPaymentLogLines($fullPath);
$content = !empty($lines) ? implode("\n", $lines) : '';
}
$data['filename'] = $filename;
$data['content'] = $content;
$data['showPayment'] = $showPayment;
$data['page_name'] = $showPayment ? 'Payment Logs' : 'View Log';
$this->render_page('logviewer/view', $data);
}
public function download($filename = null)
{
$filename = $this->sanitizeFilename($filename);
if (!$filename) {
return redirect()->to('/logs')->with('error', 'Invalid file name.');
}
$fullPath = $this->logsPath . $filename;
if (!is_file($fullPath)) {
return redirect()->to('/logs')->with('error', 'File not found.');
}
return $this->response->download($fullPath, null);
}
private function extractPaymentLogLines(string $fullPath): array
{
if (!is_readable($fullPath)) {
return [];
}
$lines = [];
$handle = fopen($fullPath, 'r');
if ($handle === false) {
return [];
}
while (($line = fgets($handle)) !== false) {
if (strpos($line, '[PAYMENT]') !== false) {
$lines[] = rtrim($line, "\r\n");
}
}
fclose($handle);
return $lines;
}
private function sanitizeFilename($filename)
{
if (!$filename) {
return false;
}
$filename = basename($filename);
if (!preg_match('/^[A-Za-z0-9_\-\.]+\.(log|php|txt|html)$/', $filename)) {
return false;
}
return $filename;
}
private function formatSize($bytes)
{
if ($bytes >= 1073741824) {
return number_format($bytes / 1073741824, 2) . ' GB';
} elseif ($bytes >= 1048576) {
return number_format($bytes / 1048576, 2) . ' MB';
} elseif ($bytes >= 1024) {
return number_format($bytes / 1024, 2) . ' KB';
}
return $bytes . ' bytes';
}
}

View File

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

View File

@ -10,6 +10,8 @@ use App\Models\SubscriptionModel;
use App\Models\AuthenticationModel; use App\Models\AuthenticationModel;
use App\Models\PaymentStatusModel; use App\Models\PaymentStatusModel;
use App\Helpers\SendSMSHelper;
require_once('vendor/autoload.php'); require_once('vendor/autoload.php');
define('PROJECT', 'vendor/paytm/paytm-pg'); define('PROJECT', 'vendor/paytm/paytm-pg');
@ -17,10 +19,12 @@ define('PROJECT', 'vendor/paytm/paytm-pg');
class Payment extends BaseController class Payment extends BaseController
{ {
protected $paymentModel; protected $paymentModel;
protected $sendSMSHelper;
public function __construct() { public function __construct() {
helper('encdec_paytm'); helper('encdec_paytm');
$this->paymentModel = new PaymentStatusModel(); $this->paymentModel = new PaymentStatusModel();
$this->sendSMSHelper = new SendSMSHelper();
} }
public function index($membership_id = null) public function index($membership_id = null)
@ -54,14 +58,35 @@ class Payment extends BaseController
]; ];
$response['favicon'] = !empty($details[0]['favicon']) && file_exists(FCPATH."public/uploads/".$details[0]['favicon']) ? base_url("public/uploads/".$details[0]['favicon']) : base_url("public/uploads/default.ico"); $response['favicon'] = !empty($details[0]['favicon']) && file_exists(FCPATH."public/uploads/".$details[0]['favicon']) ? base_url("public/uploads/".$details[0]['favicon']) : base_url("public/uploads/default.ico");
// var_dump($response);die(); log_message('info', '[PAYMENT] Customer opened renewal page for membership ' . $membership_id . ', amount Rs.' . $amount);
log_message('error','Membership ID : '.$membership_id.' renewal link clicked and user is redirected to subscription renewal Page');
return view('subscription_renewal',$response); return view('subscription_renewal',$response);
} }
else{ else{
if ($this->request->getMethod() == 'get') { if ($this->request->getMethod() == 'get') {
log_message('error','Renewal link clicked and user is redirected to subscription renewal Page'); $membership_id = $this->request->getGet('ID');
if (isset($membership_id) && !empty($membership_id)){
$customer_id = $model2->select('customer_id')->where('membership_id',$membership_id)->first();
$customer_details = $model->get_customer_details_by_customer_id($customer_id);
$scheme = $model2->get_subscription_details_by_membership_id($membership_id);
//var_dump($customer_details);die();
$book_id = env('RENEWAL_SCHEME_ID');
$price = $bookModel->select('price')->where('book_id', $book_id)->first();
$amount = $price['price'];
log_message('debug','amount is '.$amount);
$response = [
'customer_details' => $customer_details,
'scheme' => $scheme,
'membership_id' =>$membership_id,
'CustomerID' =>$customer_id,
'amount' =>$amount
];
$response['favicon'] = !empty($details[0]['favicon']) && file_exists(FCPATH."public/uploads/".$details[0]['favicon']) ? base_url("public/uploads/".$details[0]['favicon']) : base_url("public/uploads/default.ico");
}
log_message('info', '[PAYMENT] Customer opened renewal page for membership ' . ($membership_id ?? ''));
return view('subscription_renewal',$response); return view('subscription_renewal',$response);
} }
else { else {
@ -70,7 +95,7 @@ class Payment extends BaseController
$scheme = $model2->get_subscription_details_by_membership_id($membership_id); $scheme = $model2->get_subscription_details_by_membership_id($membership_id);
$customer_id = $model2->select('customer_id')->where('membership_id',$membership_id)->first(); $customer_id = $model2->select('customer_id')->where('membership_id',$membership_id)->first();
$customer_details = $model->get_customer_details_by_customer_id($customer_id); $customer_details = $model->get_customer_details_by_customer_id($customer_id);
log_message('info','inside the method post'); log_message('debug', '[PAYMENT] Renewal page loaded customer details for membership ' . $membership_id);
$book_id = env('RENEWAL_SCHEME_ID'); $book_id = env('RENEWAL_SCHEME_ID');
$price = $bookModel->select('price')->where('book_id', $book_id)->first(); $price = $bookModel->select('price')->where('book_id', $book_id)->first();
$amount = $price['price']; $amount = $price['price'];
@ -122,54 +147,49 @@ class Payment extends BaseController
'payment_status'=> 'Not Received' 'payment_status'=> 'Not Received'
]; ];
$result = $this->paymentModel->insert($payment_status_data); $result = $this->paymentModel->insert($payment_status_data);
if ($result){ if ($result) {
log_message('info','Data Inserted to Payment Status '.json_encode($payment_status_data)); log_message('info', '[PAYMENT] Payment initiated — customer ' . $CUST_ID . ', membership ' . $membership_id . ', order ' . $ORDER_ID . ', amount Rs.' . $TXN_AMOUNT . ' via ' . ($payment_method === 'mobile' ? 'Mobile' : 'Web'));
} }
log_message('error','Data Sent to Paytm: '.json_encode($data['paramList'])); log_message('info', '[PAYMENT] Redirecting customer to Paytm gateway for order ' . $ORDER_ID);
return view('/tresponse', $data); return view('/tresponse', $data);
} }
public function tresponse() { public function tresponse() {
$paytmChecksum = "";
$paramList = $_POST; $paramList = $_POST;
//print_r($paramList); $orderId = $paramList['ORDERID'] ?? 'unknown';
$isValidChecksum = "FALSE"; $paytmChecksum = $paramList['CHECKSUMHASH'] ?? '';
$paramList = $_POST; $txnStatus = $paramList['STATUS'] ?? 'unknown';
// dd($paramList);
log_message('error','data receieved through Paytm: '.json_encode($paramList)); log_message('info', '[PAYMENT] Paytm callback received for order ' . $orderId . ' with status ' . $txnStatus);
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : "";
$result['receivedFromPaytm'] = $paramList;
// Verify checksum
$isValidChecksum = verifychecksum_e($paramList, env('Merchant_Key'), $paytmChecksum); $isValidChecksum = verifychecksum_e($paramList, env('Merchant_Key'), $paytmChecksum);
if ($isValidChecksum == "TRUE") { if ($isValidChecksum !== 'TRUE') {
//echo "<b>Checksum matched.</b><br/>"; log_message('error', '[PAYMENT] Paytm callback rejected — checksum mismatch for order ' . $orderId . '. Payment was not recorded.');
if (isset($_POST) && count($_POST) > 0) {
// foreach($_POST as $paramName => $paramValue) {
// // echo "<br/>" . htmlspecialchars($paramName) . " = " . htmlspecialchars($paramValue);
// }
log_message('error',json_encode($paramList));
log_message('error','data receieved through Paytm under the if condition post> 0: '.json_encode($paramList));
}
if ($_POST["STATUS"] == "TXN_SUCCESS") {
$queryString = http_build_query($paramList);
echo "<b>Transaction status is success</b><br/>";
log_message('error','Transaction is Successfull');
return redirect()->to(base_url('/payment_process?' . $queryString));
} else {
echo "<b>Processing ...</b><br/>";
$queryString = http_build_query($paramList);
log_message('error','Transaction is Failed');
return redirect()->to(base_url('/payment_failure?' . $queryString));
}
} else {
log_message('error','Checksum Mismatched');
return view('/payment_failure'); return view('/payment_failure');
} }
log_message('info', '[PAYMENT] Paytm callback verified successfully for order ' . $orderId);
if ($txnStatus === 'TXN_SUCCESS') {
$processResult = $this->processSuccessfulPayment($paramList);
if ($processResult['success'] || $processResult['already_processed']) {
log_message('info', '[PAYMENT] Renewal payment recorded successfully for order ' . $orderId);
return redirect()->to(base_url('/payment_success'));
}
log_message('error', '[PAYMENT] Paytm reported success but renewal could not be saved for order ' . $orderId . ': ' . $processResult['message'] . '. Customer will be sent to retry page.');
$queryString = http_build_query($paramList);
return redirect()->to(base_url('/payment_process?' . $queryString));
}
$this->updateFailedPayment($paramList);
log_message('warning', '[PAYMENT] Paytm payment failed or was cancelled for order ' . $orderId . ' — status: ' . $txnStatus);
$queryString = http_build_query($paramList);
return redirect()->to(base_url('/payment_failure?' . $queryString));
} }
public function payment_failure(){ public function payment_failure(){
$paramList = [ $paramList = [
@ -182,194 +202,361 @@ public function payment_failure(){
'TXNAMOUNT' => $this->request->getVar('TXNAMOUNT'), 'TXNAMOUNT' => $this->request->getVar('TXNAMOUNT'),
'TXNDATE' => $this->request->getVar('TXNDATE'), 'TXNDATE' => $this->request->getVar('TXNDATE'),
'TXNID' => $this->request->getVar('TXNID'), 'TXNID' => $this->request->getVar('TXNID'),
'is_active' => 1 'is_active' => 1,
]; ];
$model4 = new TransactionModel(); $orderId = $paramList['ORDERID'] ?? '';
$model4->insert($paramList); if (! empty($orderId)) {
// $insertId = $model4->insertID(); log_message('info', '[PAYMENT] Customer reached payment failure page for order ' . $orderId . ', status ' . ($paramList['STATUS'] ?? 'unknown'));
$payment_status_id = $this->paymentModel->select('id')->where('order_id',$this->request->getVar('ORDERID'))->first()['id']; }
// echo "payment status id :";
// var_dump($payment_status_id);die();
// $payement_status_update['status'] = $insertId;
$converted_status = ucfirst(strtolower(str_replace("TXN_", "", $this->request->getVar('STATUS'))));
$payement_status_update['payment_status'] = $converted_status;
// $payement_status_update['status'] = $payment_status_id; $this->updateFailedPayment($paramList);
$updated = $this->paymentModel->update($payment_status_id, $payement_status_update);
log_message('error', 'Payment Status Updated: ' . json_encode($updated));
return view('/payment_failure'); return view('/payment_failure');
} }
public function payment_process() { public function payment_process() {
echo "Do not hit refresh or go back. Confirming your Order"; $paramList = $this->request->getGet();
helper('session'); $orderId = $paramList['ORDERID'] ?? 'unknown';
helper('financial_year_helper');
$subModel = new SubscriptionModel(); log_message('info', '[PAYMENT] Processing renewal page opened for order ' . $orderId . ' (browser follow-up after Paytm)');
$ORDER_ID = $this->request->getVar('ORDERID');
$parts = explode('_', $ORDER_ID); $processResult = $this->processSuccessfulPayment($paramList);
$customer_id = (int)$parts[0];
if ($processResult['success'] || $processResult['already_processed']) {
return redirect()->to(base_url('/payment_success'));
}
log_message('error', '[PAYMENT] Could not complete renewal for order ' . $orderId . ': ' . $processResult['message']);
return redirect()->to(base_url('/payment_failure?' . http_build_query($paramList)));
}
/**
* Record a failed Paytm payment and update payment status.
*/
private function updateFailedPayment(array $paramList): void
{
$orderId = $paramList['ORDERID'] ?? null;
if (empty($orderId)) {
log_message('warning', '[PAYMENT] Failed payment callback received without an order ID');
return;
}
$model4 = new TransactionModel();
$model4->insert([
'BANKTXNID' => $paramList['BANKTXNID'] ?? null,
'CHECKSUMHASH' => $paramList['CHECKSUMHASH'] ?? null,
'GATEWAYNAME' => $paramList['GATEWAYNAME'] ?? null,
'ORDERID' => $orderId,
'PAYMENTMODE' => $paramList['PAYMENTMODE'] ?? null,
'STATUS' => $paramList['STATUS'] ?? null,
'TXNAMOUNT' => $paramList['TXNAMOUNT'] ?? null,
'TXNDATE' => $paramList['TXNDATE'] ?? null,
'TXNID' => $paramList['TXNID'] ?? null,
'isactive' => 1,
]);
$paymentRow = $this->paymentModel->select('id')->where('order_id', $orderId)->first();
if ($paymentRow === null) {
log_message('warning', '[PAYMENT] No payment record found to mark as failed for order ' . $orderId);
return;
}
$status = $paramList['STATUS'] ?? '';
$convertedStatus = ucfirst(strtolower(str_replace('TXN_', '', $status)));
$this->paymentModel->update($paymentRow['id'], [
'payment_status' => $convertedStatus,
]);
log_message('info', '[PAYMENT] Payment marked as ' . $convertedStatus . ' for order ' . $orderId);
}
/**
* Create invoice, subscription, and transaction for a successful Paytm payment.
*
* @return array{success: bool, already_processed: bool, message: string}
*/
private function processSuccessfulPayment(array $paramList): array
{
helper(['session', 'financial_year_helper']);
$orderId = $paramList['ORDERID'] ?? null;
if (empty($orderId)) {
return ['success' => false, 'already_processed' => false, 'message' => 'Missing order ID'];
}
if ($this->isOrderAlreadyProcessed($orderId)) {
log_message('info', '[PAYMENT] Order ' . $orderId . ' was already processed — skipping duplicate renewal');
return ['success' => true, 'already_processed' => true, 'message' => 'Already processed'];
}
$parts = explode('_', $orderId, 3);
if (count($parts) < 2) {
log_message('error', '[PAYMENT] Invalid order ID format for order ' . $orderId);
return ['success' => false, 'already_processed' => false, 'message' => 'Invalid order ID format'];
}
$customer_id = (int) $parts[0];
$past_membership_id = $parts[1]; $past_membership_id = $parts[1];
// $payment_method = $this->request->getVar('PAYMENTMODE');
$payment_method = 'paytm'; $payment_method = 'paytm';
//dd($past_membership_id);
// $parts = explode('_', $ORDER_ID);
// $customer_id = (int)$parts[0];
$currentDate = date('Y-m-d'); $currentDate = date('Y-m-d');
$db = \Config\Database::connect();
$subModel = new SubscriptionModel();
$bookModel = new BooksModel(); $bookModel = new BooksModel();
$model = new InvoiceModel(); $model = new InvoiceModel();
$db = \Config\Database::connect();
$baddress = $db->table('customer_addresses')->select('address_1,customer_address_id')->where('customer_id',$customer_id)->where('address_type',1)->get()->getRowArray();
$saddress = $db->table('customer_addresses')->select('address_1,customer_address_id')->where('customer_id',$customer_id)->where('address_type',2)->get()->getRowArray();
$next_id_row = $db->table('invoice_number_formatting')->select('next_id, left_pad')->get()->getRowArray();
$filtered_data = [ try {
[ $db->transStart();
'next_id' => $next_id_row['next_id'],
'left_pad' => $next_id_row['left_pad'] $baddress = $db->table('customer_addresses')
] ->select('address_1,customer_address_id')
]; ->where('customer_id', $customer_id)
->where('address_type', 1)
->get()->getRowArray();
$saddress = $db->table('customer_addresses')
->select('address_1,customer_address_id')
->where('customer_id', $customer_id)
->where('address_type', 2)
->get()->getRowArray();
$next_id_row = $db->table('invoice_number_formatting')
->select('next_id, left_pad')
->get()->getRowArray();
if ($next_id_row === null) {
throw new \RuntimeException('Invoice numbering configuration not found');
}
$filtered_data = [['next_id' => $next_id_row['next_id'], 'left_pad' => $next_id_row['left_pad']]];
$financial_year = get_financial_year(); $financial_year = get_financial_year();
$result = $this->generateSerialNumber($filtered_data, $financial_year); $result = $this->generateSerialNumber($filtered_data, $financial_year);
//var_dump($result);die();
$invoice_number = $result['serial_number']; $invoice_number = $result['serial_number'];
$next_id_numeric = $result['next_id']; $next_id_numeric = $result['next_id'];
$book_id = env('RENEWAL_SCHEME_ID'); $book_id = env('RENEWAL_SCHEME_ID');
$price = $bookModel->select('price')->where('book_id', $book_id)->first(); $price = $bookModel->select('price')->where('book_id', $book_id)->first();
$amount = $price['price']; $amount = $price['price'] ?? ($paramList['TXNAMOUNT'] ?? 0);
$data = [ $data = [
'invoice_number' => $invoice_number, 'invoice_number' => $invoice_number,
'invoice_type' => 2, 'invoice_type' => 2,
'customer_id' => $customer_id, 'customer_id' => $customer_id,
'payment_status' => 'Paid', 'payment_status' => 'Paid',
'status'=>'Approved', 'status' => 'Approved',
'subtotal' => $amount, 'subtotal' => $amount,
'sub_total' => $amount, 'sub_total' => $amount,
'exact_total_amount' => $amount, 'exact_total_amount' => $amount,
'grand_total' => $amount, 'grand_total' => $amount,
'total_amount' => $amount, 'total_amount' => $amount,
'invoice_date' => $currentDate, 'invoice_date' => $currentDate,
'shipping_address'=> $saddress['address_1'], 'shipping_address' => $saddress['address_1'] ?? '',
'shipping_address_id' => isset($saddress['customer_address_id']) ? $saddress['customer_address_id'] : '', 'shipping_address_id' => $saddress['customer_address_id'] ?? '',
'billing_address'=> $baddress['address_1'], 'billing_address' => $baddress['address_1'] ?? '',
'billing_address_id' => isset($baddress['customer_address_id']) ? $baddress['customer_address_id'] : '', 'billing_address_id' => $baddress['customer_address_id'] ?? '',
'payment_method' => $payment_method, 'payment_method' => $payment_method,
'business_id' =>2 'business_id' => 2,
]; ];
$model->save($data); $model->save($data);
log_message('error','invoice details added to invoice table'); log_message('info', '[PAYMENT] Invoice ' . $invoice_number . ' created for customer ' . $customer_id . ' after Paytm payment, order ' . $orderId);
$update_invoice_numbering = [
$save_invoice = new Invoice();
$save_invoice->update_number_formatting([
'id' => 1, 'id' => 1,
'id_formating' => get_financial_year(), 'id_formating' => get_financial_year(),
'next_id' => (int)$next_id_numeric, 'next_id' => (int) $next_id_numeric,
'business_id' => 2, 'business_id' => 2,
'updated_by' => null !== ($userId = get_logged_user_id()) ? $userId : '', 'updated_by' => null !== ($userId = get_logged_user_id()) ? $userId : '',
]; ]);
// var_dump($update_invoice_numbering);die();
$save_invoice = new Invoice();
$save_invoice->update_number_formatting($update_invoice_numbering);
//get the invoice id to insert into the invoiceitems table
$invoice_id = $model->select('invoice_id')->where('invoice_number',$invoice_number)->first();
$previous_to_sub = $subModel->select('to_subscription')->where('customer_id',$customer_id)->where('membership_id',$past_membership_id)->first();
$new_subscription_date = $previous_to_sub['to_subscription'];
// Create a DateTime object from the existing subscription date
$date = new \DateTime($new_subscription_date);
$currentDate = date('Y-m-d');
if ($currentDate > $new_subscription_date){
$fsubscription = $currentDate; //if subscription is already expired
}else{ $invoice_id = $model->select('invoice_id')->where('invoice_number', $invoice_number)->first();
// Add one day from previous subscrption's to subscription date if ($invoice_id === null) {
throw new \RuntimeException('Invoice was not saved');
}
$previous_to_sub = $subModel->select('to_subscription')
->where('customer_id', $customer_id)
->where('membership_id', $past_membership_id)
->first();
if ($previous_to_sub === null) {
throw new \RuntimeException('Previous subscription not found for membership ' . $past_membership_id);
}
$new_subscription_date = $previous_to_sub['to_subscription'];
if ($currentDate > $new_subscription_date) {
$fsubscription = $currentDate;
} else {
$fsubscription = date('Y-m-d', strtotime('+1 day', strtotime($new_subscription_date))); $fsubscription = date('Y-m-d', strtotime('+1 day', strtotime($new_subscription_date)));
} }
$date->add(new \DateInterval('P1D'));
$tsubscription = date('Y-m-d', strtotime('+1 year', strtotime($fsubscription))); $tsubscription = date('Y-m-d', strtotime('+1 year', strtotime($fsubscription)));
$data['item_details'] = 3;
$requestData = [
'invoice_id' =>$invoice_id['invoice_id'],
'product' => env('RENEWAL_SCHEME_ID'),
'quantity' =>1,
'unit_price'=>$data['sub_total'],
'subtotal' => $data['sub_total'],
'created_on'=>$currentDate,
'isactive'=>1,
'from_subscription' =>$fsubscription,
'to_subscription' =>$tsubscription,
]; $db->table('invoiceitems')->insert([
$db->table('invoiceitems')->insert($requestData); 'invoice_id' => $invoice_id['invoice_id'],
log_message('error','invoice details added to invoice items table'); 'product' => env('RENEWAL_SCHEME_ID'),
'quantity' => 1,
'unit_price' => $data['sub_total'],
'subtotal' => $data['sub_total'],
'created_on' => $currentDate,
'isactive' => 1,
'from_subscription' => $fsubscription,
'to_subscription' => $tsubscription,
]);
log_message('info', '[PAYMENT] Subscription renewed from ' . $fsubscription . ' to ' . $tsubscription . ' for customer ' . $customer_id . ', order ' . $orderId);
$invoice = new Invoice(); $invoice = new Invoice();
$contact_method['msg_mail'] = 1; $invoice->approve_notifications((int) $invoice_id['invoice_id'], ['msg_mail' => 1]);
$invoice->approve_notifications((int)$invoice_id['invoice_id'],$contact_method);
$model3 = new SubscriptionModel();
$invoiceController = new Invoice(); $invoiceController = new Invoice();
$membership_id = $invoiceController->generate_membership_id(6); $membership_id = $invoiceController->generate_membership_id(6);
//$membership_id = $model3->select('membership_id')->where('customer_id',$customer_id)->first();
// if ($membership_id<=0){
// $membership_id = $invoice->generate_membership_id(6);
// }
$subscription = $subModel->select('sub_id')->where('membership_id',$past_membership_id)->first(); $subscription = $subModel->select('sub_id')
$subscriptionData = [ ->where('membership_id', $past_membership_id)
->first();
$db->table('subscription')->insert([
'scheme_id' => env('RENEWAL_SCHEME_ID'), 'scheme_id' => env('RENEWAL_SCHEME_ID'),
'customer_id' => $customer_id, 'customer_id' => $customer_id,
'invoice_id' => $invoice_id, 'invoice_id' => $invoice_id['invoice_id'],
'from_subscription'=> $fsubscription, 'from_subscription' => $fsubscription,
'to_subscription' => $tsubscription, 'to_subscription' => $tsubscription,
'is_renew' => $subscription['sub_id'], 'is_renew' => $subscription['sub_id'] ?? 0,
'business_id' => 2, 'business_id' => 2,
'status' => 1, 'status' => 1,
'membership_id' => $membership_id, 'membership_id' => $membership_id,
'isactive' => 1, 'isactive' => 1,
'business_id' => 2 ]);
];
$db->table('subscription')->insert($subscriptionData);
log_message('error','subscription details added to subscription table');
$paramList = [
'BANKTXNID' => $this->request->getVar('BANKTXNID'),
'CHECKSUMHASH' => $this->request->getVar('CHECKSUMHASH'),
'GATEWAYNAME' => $this->request->getVar('GATEWAYNAME'),
'ORDERID' => $this->request->getVar('ORDERID'),
'PAYMENTMODE' => $this->request->getVar('PAYMENTMODE'),
'STATUS' => $this->request->getVar('STATUS'),
'TXNAMOUNT' => $this->request->getVar('TXNAMOUNT'),
'TXNDATE' => $this->request->getVar('TXNDATE'),
'TXNID' => $this->request->getVar('TXNID'),
'invoice_id' => $invoice_id,
'is_active' => 1
];
$model4 = new TransactionModel(); $model4 = new TransactionModel();
$model4->save($paramList); $model4->insert([
log_message('error','transaction details added to transaction table'); 'BANKTXNID' => $paramList['BANKTXNID'] ?? null,
'CHECKSUMHASH' => $paramList['CHECKSUMHASH'] ?? null,
'GATEWAYNAME' => $paramList['GATEWAYNAME'] ?? null,
'ORDERID' => $orderId,
'PAYMENTMODE' => $paramList['PAYMENTMODE'] ?? null,
'STATUS' => $paramList['STATUS'] ?? 'TXN_SUCCESS',
'TXNAMOUNT' => $paramList['TXNAMOUNT'] ?? null,
'TXNDATE' => $paramList['TXNDATE'] ?? null,
'TXNID' => $paramList['TXNID'] ?? null,
'invoice_id' => $invoice_id['invoice_id'],
'isactive' => 1,
]);
$insertId = $model4->insertID(); $insertId = $model4->getInsertID();
$payment_status_id = $this->paymentModel->select('id')->where('order_id',$this->request->getVar('ORDERID'))->first()['id'];
// echo "payment status id :";
// var_dump($payment_status_id);die();
$payement_status_update['status'] = $insertId;
$converted_status = ucfirst(strtolower(str_replace("TXN_", "", $this->request->getVar('STATUS'))));
$payement_status_update['payment_status'] = $converted_status;
// $payement_status_update['status'] = $payment_status_id; $paymentRow = $this->paymentModel->select('id')->where('order_id', $orderId)->first();
if ($paymentRow !== null) {
$this->paymentModel->update($paymentRow['id'], [
'status' => $insertId,
'payment_status' => 'Success',
]);
}
$updated = $this->paymentModel->update($payment_status_id, $payement_status_update); $db->transComplete();
log_message('error', 'Payment Status Updated: ' . json_encode($updated));
if ($db->transStatus() === false) {
throw new \RuntimeException('Database transaction failed while saving renewal');
}
log_message('info', 'saved data' . json_encode($data)); log_message('info', '[PAYMENT] Renewal completed — order ' . $orderId . ', invoice ' . $invoice_number . ', new membership ' . $membership_id . ', customer ' . $customer_id);
return redirect()->to(base_url('/payment_success')); return ['success' => true, 'already_processed' => false, 'message' => 'Renewal completed'];
} catch (\Throwable $e) {
$db->transRollback();
log_message('error', '[PAYMENT] Renewal failed for order ' . $orderId . ': ' . $e->getMessage());
return ['success' => false, 'already_processed' => false, 'message' => $e->getMessage()];
}
}
private function isOrderAlreadyProcessed(string $orderId): bool
{
$paymentRow = $this->paymentModel->where('order_id', $orderId)->first();
if ($paymentRow !== null && ($paymentRow['payment_status'] ?? '') !== 'Not Received') {
return true;
}
$db = \Config\Database::connect();
return $db->table('transactions')
->where('ORDERID', $orderId)
->where('STATUS', 'TXN_SUCCESS')
->countAllResults() > 0;
}
/**
* Query Paytm for the live status of an order (used to recover stuck payments).
*/
private function fetchPaytmTransactionStatus(string $orderId): ?array
{
$requestParamList = [
'MID' => env('Merchant_ID'),
'ORDERID' => $orderId,
];
$requestParamList['CHECKSUMHASH'] = getChecksumFromArray($requestParamList, env('Merchant_Key'));
$response = callAPI(PAYTM_STATUS_QUERY_URL, $requestParamList);
log_message('info', '[PAYMENT] Checked Paytm status for order ' . $orderId . ' — result: ' . ($response['STATUS'] ?? 'unknown'));
return is_array($response) ? $response : null;
}
/**
* Reconcile a stuck "Not Received" payment by verifying with Paytm and processing if paid.
*/
public function reconcileOrder()
{
if (! $this->request->is('post')) {
return $this->response->setJSON(['status' => false, 'message' => 'Invalid request']);
}
$orderId = $this->request->getPost('order_id');
if (empty($orderId)) {
return $this->response->setJSON(['status' => false, 'message' => 'Order ID is required']);
}
log_message('info', '[PAYMENT] Manual reconciliation started for order ' . $orderId);
if ($this->isOrderAlreadyProcessed($orderId)) {
return $this->response->setJSON([
'status' => true,
'message' => 'This payment was already recorded in the system.',
]);
}
$paytmResponse = $this->fetchPaytmTransactionStatus($orderId);
if ($paytmResponse === null) {
return $this->response->setJSON([
'status' => false,
'message' => 'Could not reach Paytm to verify this payment. Please try again.',
]);
}
if (($paytmResponse['STATUS'] ?? '') !== 'TXN_SUCCESS') {
log_message('warning', '[PAYMENT] Paytm reports order ' . $orderId . ' is not successful — status: ' . ($paytmResponse['STATUS'] ?? 'unknown'));
return $this->response->setJSON([
'status' => false,
'message' => 'Paytm shows this payment as: ' . ($paytmResponse['STATUS'] ?? 'pending/failed') . '. It cannot be recorded as paid.',
]);
}
$processResult = $this->processSuccessfulPayment($paytmResponse);
if ($processResult['success'] || $processResult['already_processed']) {
log_message('info', '[PAYMENT] Manual reconciliation succeeded for order ' . $orderId);
return $this->response->setJSON([
'status' => true,
'message' => 'Payment verified with Paytm and renewal has been recorded successfully.',
]);
}
return $this->response->setJSON([
'status' => false,
'message' => 'Paytm confirmed payment but renewal could not be saved: ' . $processResult['message'],
]);
} }
public function generateSerialNumber($filtered_data, $financial_year) { public function generateSerialNumber($filtered_data, $financial_year) {
@ -384,6 +571,12 @@ public function generateSerialNumber($filtered_data, $financial_year) {
return ['serial_number' => $serial_number, 'next_id' => $next_id_numeric]; return ['serial_number' => $serial_number, 'next_id' => $next_id_numeric];
} }
public function payment_success(){ public function payment_success(){
$orderId = $this->request->getGet('ORDERID');
if (! empty($orderId)) {
log_message('info', '[PAYMENT] Customer reached payment success page for order ' . $orderId);
} else {
log_message('info', '[PAYMENT] Customer reached payment success page');
}
return view('payment_success'); return view('payment_success');
} }
@ -459,7 +652,6 @@ public function paymentStatus(){
return $this->render_page('payment_status_view',$data); return $this->render_page('payment_status_view',$data);
}else{ }else{
$received_data = $this->request->getPost(); $received_data = $this->request->getPost();
log_message('error','data received from post '.json_encode($received_data));
$dateParts = explode(' - ', $received_data['dateRange']); $dateParts = explode(' - ', $received_data['dateRange']);
$status = $received_data['status']; $status = $received_data['status'];
@ -470,8 +662,9 @@ public function paymentStatus(){
$fromDate = \DateTime::createFromFormat('d/m/Y', $dateParts[0])->format('Y-m-d'); $fromDate = \DateTime::createFromFormat('d/m/Y', $dateParts[0])->format('Y-m-d');
$toDate = \DateTime::createFromFormat('d/m/Y', $dateParts[1])->format('Y-m-d'); $toDate = \DateTime::createFromFormat('d/m/Y', $dateParts[1])->format('Y-m-d');
log_message('info', '[PAYMENT] Staff viewed payment status report from ' . $fromDate . ' to ' . $toDate . ', showing ' . (((int) $status === 1) ? 'received' : 'not received') . ' payments');
$payment_data['payment_status_data'] = $this->paymentModel->getPaymentData($fromDate, $toDate,$status); $payment_data['payment_status_data'] = $this->paymentModel->getPaymentData($fromDate, $toDate,$status);
log_message('debug',json_encode($payment_data));
$html = view('payment_status_table',$payment_data); $html = view('payment_status_table',$payment_data);
$data['selected_data'] = $received_data['dateRange']; $data['selected_data'] = $received_data['dateRange'];
@ -482,6 +675,19 @@ public function paymentStatus(){
} }
// public function testSMS(){
// $mobile_number = '916382156701';
// $name = "Srinivas";
// $expiryDate = "10/10/2025";
// $link = "https://bit.ly/44Iy4Zm";
// // Exactly matching the approved template
// $message = "Hi {$name}, your subscription for Pusthakam scheme is about to expire on {$expiryDate}. Renew now to continue enjoying our books for one more year. Tap here to renew: {$link} -Vijayabharatham Prasuram";
// $status = $this->sendSMSHelper->sendSMS($message,$mobile_number);
// echo $status;
// }
} }

View File

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

View File

@ -1,4 +1,5 @@
<?php <?php
namespace App\Models; namespace App\Models;
use App\Controllers\Books; use App\Controllers\Books;
@ -7,64 +8,67 @@ use CodeIgniter\Model;
class InvoiceModel extends Model class InvoiceModel extends Model
{ {
protected $table = 'invoice'; protected $table = 'invoice';
protected $primaryKey = 'invoice_id'; protected $primaryKey = 'invoice_id';
// protected $allowedFields = ['invoice_id','invoice_number','customer_id','invoice_date','event_id','business_id','created_on','business_id']; // protected $allowedFields = ['invoice_id','invoice_number','customer_id','invoice_date','event_id','business_id','created_on','business_id'];
protected $allowedFields = ['invoice_id', 'invoice_number', 'customer_id','notes', 'invoice_date', 'due_date', 'subtotal', 'tax','dis_type', 'discount', 'shipping_charge','shipping_label','total_amount', 'payment_status', 'order_number','invoice_type', 'payment_method', 'event_id', 'business_id', 'shipping_address_id', 'billing_address_id', 'created_on', 'created_by', 'updated_on', 'updated_by','category','isactive','billing_address','shipping_address','status','payment_note','exact_total_amount']; protected $allowedFields = ['invoice_id', 'invoice_number', 'customer_id', 'notes', 'invoice_date', 'due_date', 'subtotal', 'tax', 'dis_type', 'discount', 'shipping_charge', 'shipping_label', 'total_amount', 'payment_status', 'order_number', 'invoice_type', 'payment_method', 'event_id', 'business_id', 'shipping_address_id', 'billing_address_id', 'created_on', 'created_by', 'updated_on', 'updated_by', 'category', 'isactive', 'billing_address', 'shipping_address', 'status', 'payment_note', 'exact_total_amount'];
public function saveInvoiceItemDetails($data){ public function saveInvoiceItemDetails($data)
{
$i = 0; $i = 0;
$statement = []; $statement = [];
foreach ($data as $row) { foreach ($data as $row) {
$id = isset($row['invoice_child_id']) ? $row['invoice_child_id'] : ''; $id = isset($row['invoice_child_id']) ? $row['invoice_child_id'] : '';
if($id != ''){ if ($id != '') {
unset($row['invoice_child_id']); // Remove the id from the data to avoid updating it unset($row['invoice_child_id']); // Remove the id from the data to avoid updating it
unset($row['created_by']); // bcoz here data are Updating here. unset($row['created_by']); // bcoz here data are Updating here.
$this->db->table('invoiceitems')->where('invoice_child_id', $id)->update($row);// Update the row with the specified id $this->db->table('invoiceitems')->where('invoice_child_id', $id)->update($row); // Update the row with the specified id
$affectedRows = $this->db->affectedRows(); $affectedRows = $this->db->affectedRows();
$statement[$i] = "Invoice Item - ".$id." ".$affectedRows ? " Updated":" Not Updated"; $statement[$i] = "Invoice Item - " . $id . " " . $affectedRows ? " Updated" : " Not Updated";
}else{ } else {
if (!empty($row['updated_by'])){ if (!empty($row['updated_by'])) {
unset($row['updated_by']); // bcoz here data are inserting here. unset($row['updated_by']); // bcoz here data are inserting here.
} }
$this->db->table('invoiceitems')->insert($row); $this->db->table('invoiceitems')->insert($row);
$insertID = $this->db->insertID(); $insertID = $this->db->insertID();
$statement[$i] = "Invoice Item - ".$insertID." Inserted"; $statement[$i] = "Invoice Item - " . $insertID . " Inserted";
} }
} }
return $statement; return $statement;
} }
public function inactiveMissingInvoiceItemDetails($where,$missingValues){ public function inactiveMissingInvoiceItemDetails($where, $missingValues)
{
$dataToUpdate = ['isactive' => 0]; $dataToUpdate = ['isactive' => 0];
$this->db->table('invoiceitems')->where($where)->whereIn('invoice_child_id',$missingValues)->update($dataToUpdate); $this->db->table('invoiceitems')->where($where)->whereIn('invoice_child_id', $missingValues)->update($dataToUpdate);
} }
public function deleteMissingInvoiceItemDetails($where, $missingValues) { public function deleteMissingInvoiceItemDetails($where, $missingValues)
{
$this->db->table('invoiceitems') $this->db->table('invoiceitems')
->where($where) ->where($where)
->whereIn('invoice_child_id', $missingValues) ->whereIn('invoice_child_id', $missingValues)
->delete(); ->delete();
} }
public function updateData($table, $data, $where) public function updateData($table, $data, $where)
{ {
$this->db->table($table)->update($data, $where); $this->db->table($table)->update($data, $where);
$affected_rows = $this->db->affectedRows(); $affected_rows = $this->db->affectedRows();
return $affected_rows; return $affected_rows;
} }
public function InactiveSubscriptionDraftDetails($where,$update_by_id) public function InactiveSubscriptionDraftDetails($where, $update_by_id)
{ {
$result = $this->getJoinedData($where); $result = $this->getJoinedData($where);
$inactive_invoice_ids = array(); $inactive_invoice_ids = array();
foreach ($result as $item) { foreach ($result as $item) {
$inactive_invoice_ids[] = $item['invoice_id']; $inactive_invoice_ids[] = $item['invoice_id'];
} }
if(count($inactive_invoice_ids)>0){ if (count($inactive_invoice_ids) > 0) {
$this->db->table('subscription') $this->db->table('subscription')
->whereIn('invoice_id', $inactive_invoice_ids) ->whereIn('invoice_id', $inactive_invoice_ids)
->set('isactive', 0) ->set('isactive', 0)
@ -73,35 +77,36 @@ public function InactiveSubscriptionDraftDetails($where,$update_by_id)
} }
return $inactive_invoice_ids; return $inactive_invoice_ids;
} }
public function deleteSubscriptionDraftDetails($where,$update_by_id) public function deleteSubscriptionDraftDetails($where, $update_by_id)
{ {
$result = $this->getJoinedData($where); $result = $this->getJoinedData($where);
$delete_invoice_ids = array(); $delete_invoice_ids = array();
foreach ($result as $item) { foreach ($result as $item) {
$delete_invoice_ids[] = $item['invoice_id']; $delete_invoice_ids[] = $item['invoice_id'];
} }
if(count($delete_invoice_ids)>0){ if (count($delete_invoice_ids) > 0) {
$this->db->table('subscription') $this->db->table('subscription')
->whereIn('invoice_id', $delete_invoice_ids) ->whereIn('invoice_id', $delete_invoice_ids)
->delete(); ->delete();
} }
return $delete_invoice_ids; return $delete_invoice_ids;
} }
## check the customer the scheme already Exist ## check the customer the scheme already Exist
public function existsSubscriptionDetails($where){ public function existsSubscriptionDetails($where)
{
$result = $this->getJoinedData($where); $result = $this->getJoinedData($where);
if(count($result)>0){ if (count($result) > 0) {
return 1; return 1;
}else{ } else {
return 0; return 0;
} }
} }
public function getSubscriptionInvoiceDetail($where) public function getSubscriptionInvoiceDetail($where)
{ {
$result = $this->getJoinedData($where); $result = $this->getJoinedData($where);
// print_r($result);die; // print_r($result);die;
if (!empty($result)) { if (!empty($result)) {
@ -113,7 +118,7 @@ public function getSubscriptionInvoiceDetail($where)
if (strtolower($child->category_name) == strtolower('Membership')) { if (strtolower($child->category_name) == strtolower('Membership')) {
$schemes[] = [ $schemes[] = [
'scheme_name' => $child->title, 'scheme_name' => $child->title,
'scheme_code' => !empty($child->short_code)?$child->short_code:$child->title, 'scheme_code' => !empty($child->short_code) ? $child->short_code : $child->title,
]; ];
} }
} }
@ -124,12 +129,12 @@ public function getSubscriptionInvoiceDetail($where)
} }
} }
return $result; return $result;
} }
public function getJoinedData($where, $orderby = []) public function getJoinedData($where, $orderby = [])
{ {
// dd($where); // dd($where);
$query = $this->db->table($this->table.' as I' ) $query = $this->db->table($this->table . ' as I')
->join('customers as C', 'C.customer_id = I.customer_id', 'left') ->join('customers as C', 'C.customer_id = I.customer_id', 'left')
->join('subscription as S', 'S.invoice_id = I.invoice_id', 'left') ->join('subscription as S', 'S.invoice_id = I.invoice_id', 'left')
->join('events as E', 'E.event_id = I.event_id', 'left') ->join('events as E', 'E.event_id = I.event_id', 'left')
@ -153,29 +158,32 @@ public function getJoinedData($where, $orderby = [])
//echo $this->db->getLastQuery();die; //echo $this->db->getLastQuery();die;
return $resultArray; return $resultArray;
} }
## subscription_inactive ## subscription_inactive
public function subscription_inactive(){ public function subscription_inactive()
{
$now = date('Y-m-d'); $now = date('Y-m-d');
$result = $this->db->table('subscription as S') $result = $this->db->table('subscription as S')
->select('S.sub_id, S.scheme_id, S.customer_id, S.business_id,S.invoice_id,S.mode,S.from_subscription, S.to_subscription, S.is_renew, S.isactive') ->select('S.sub_id, S.scheme_id, S.customer_id, S.business_id,S.invoice_id,S.mode,S.from_subscription, S.to_subscription, S.is_renew, S.isactive')
->where("S.isactive",1) ->where("S.isactive", 1)
->where("S.to_subscription < ",$now) ->where("S.to_subscription < ", $now)
->get() ->get()
->getResultArray(); ->getResultArray();
// echo "<pre>";print_r($result);echo "</pre>";die; // echo "<pre>";print_r($result);echo "</pre>";die;
$returnMessages = [];$i = 0 ;$j = 0; $returnMessages = [];
$i = 0;
$j = 0;
if (!empty($result)) { if (!empty($result)) {
foreach ($result as $row) { foreach ($result as $row) {
// $this->db->table('invoiceitems')->where(['invoice_id' => $row['invoice_id']])->update(['from_subscription' => NULL,'to_subscription' => NULL]);//first child // $this->db->table('invoiceitems')->where(['invoice_id' => $row['invoice_id']])->update(['from_subscription' => NULL,'to_subscription' => NULL]);//first child
$this->db->table('subscription')->where(['sub_id' => $row['sub_id']])->update(['isactive' => 0]);//second child $this->db->table('subscription')->where(['sub_id' => $row['sub_id']])->update(['isactive' => 0]); //second child
$affectedRows = $this->db->affectedRows(); $affectedRows = $this->db->affectedRows();
if ($affectedRows) { if ($affectedRows) {
$returnMessages['message'] = "Success for sub_id: " . $row['sub_id']; $returnMessages['message'] = "Success for sub_id: " . $row['sub_id'];
$returnMessages['success_rating'] = $i++; $returnMessages['success_rating'] = $i++;
}else { } else {
$returnMessages['message'] = 'Failed to update subscription with sub_id ' . $row['sub_id'] . '. No rows were affected.'; $returnMessages['message'] = 'Failed to update subscription with sub_id ' . $row['sub_id'] . '. No rows were affected.';
$returnMessages['error_rating'] = $j++; $returnMessages['error_rating'] = $j++;
} }
@ -190,12 +198,12 @@ public function getJoinedData($where, $orderby = [])
public function getDetailForApproveNotifications($where) public function getDetailForApproveNotifications($where)
{ {
$result = $this->getJoinedData($where); $result = $this->getJoinedData($where);
if(!empty($result)){ if (!empty($result)) {
foreach ($result as $object) { foreach ($result as $object) {
$invoiceId = $object['invoice_id']; $invoiceId = $object['invoice_id'];
$items = $this->getInvoiceItems($invoiceId,''); $items = $this->getInvoiceItems($invoiceId, '');
} }
}else{ } else {
$items = []; $items = [];
} }
$data['invoice'] = $result; $data['invoice'] = $result;
@ -240,10 +248,10 @@ public function getJoinedData($where, $orderby = [])
// Fetch invoice data // Fetch invoice data
return $this->db->table('invoice') return $this->db->table('invoice')
->where('invoice_id', $id) ->where('invoice_id', $id)
->join('customers as C','C.customer_id= invoice.customer_id','left') ->join('customers as C', 'C.customer_id= invoice.customer_id', 'left')
->join('business as B','B.business_id = invoice.business_id','left') ->join('business as B', 'B.business_id = invoice.business_id', 'left')
->join('customer_addresses as A','A.customer_address_id=invoice.billing_address_id AND A.address_type = 1','left') ->join('customer_addresses as A', 'A.customer_address_id=invoice.billing_address_id AND A.address_type = 1', 'left')
->join('customer_addresses as S','S.customer_address_id=invoice.shipping_address_id AND S.address_type = 2','left') ->join('customer_addresses as S', 'S.customer_address_id=invoice.shipping_address_id AND S.address_type = 2', 'left')
->join('states', 'states.state_short_name = A.state AND A.country = "IN"', 'left') ->join('states', 'states.state_short_name = A.state AND A.country = "IN"', 'left')
->join('countries', 'countries.country_short_name = A.country', 'left') ->join('countries', 'countries.country_short_name = A.country', 'left')
->select('invoice.*,DATE_FORMAT(invoice.invoice_date, "%d/%m/%Y") AS formatted_invoice_date,DATE_FORMAT(invoice.due_date, "%d/%m/%Y") AS formatted_due_date ,CONCAT_WS(" ", C.first_name, C.last_name) as customer_name,C.mobile_no,C.email,A.address_1, A.address_2,A.postal_code,A.city, A.state,C.mobile_no as customer_mobile') ->select('invoice.*,DATE_FORMAT(invoice.invoice_date, "%d/%m/%Y") AS formatted_invoice_date,DATE_FORMAT(invoice.due_date, "%d/%m/%Y") AS formatted_due_date ,CONCAT_WS(" ", C.first_name, C.last_name) as customer_name,C.mobile_no,C.email,A.address_1, A.address_2,A.postal_code,A.city, A.state,C.mobile_no as customer_mobile')
@ -254,10 +262,9 @@ public function getJoinedData($where, $orderby = [])
->select('CONCAT_WS(" ", S.first_name, S.last_name) as customer_shipper_name,concat(S.address_1," ", S.address_2) as customer_ship_address,S.postal_code as customer_ship_postal_code ,S.city as customer_ship_city, countries.country_name as customer_ship_country,S.country as scountry,S.state as sstate,S.customer_address_id as saddr_id,S.email as semail,S.mobile_no as smobile') ->select('CONCAT_WS(" ", S.first_name, S.last_name) as customer_shipper_name,concat(S.address_1," ", S.address_2) as customer_ship_address,S.postal_code as customer_ship_postal_code ,S.city as customer_ship_city, countries.country_name as customer_ship_country,S.country as scountry,S.state as sstate,S.customer_address_id as saddr_id,S.email as semail,S.mobile_no as smobile')
->get() ->get()
->getResult(); ->getResult();
} }
// this function Also Used For Approve Notification. // this function Also Used For Approve Notification.
public function getInvoiceItems($id,$stringflag) public function getInvoiceItems($id, $stringflag)
{ {
if ($stringflag == 'groupby') { if ($stringflag == 'groupby') {
@ -308,7 +315,7 @@ public function getJoinedData($where, $orderby = [])
public function getProductImgs($productId) public function getProductImgs($productId)
{ {
$data = $this->db->table('book_images') $data = $this->db->table('book_images')
->where(['book_id' => $productId,'book_images.isactive'=>1]) ->where(['book_id' => $productId, 'book_images.isactive' => 1])
// ->join('books as B', 'B.book_id = invoiceitems.product', 'left') // ->join('books as B', 'B.book_id = invoiceitems.product', 'left')
// ->join('book_images as BI', 'BI.book_id = invoiceitems.product', 'left') // ->join('book_images as BI', 'BI.book_id = invoiceitems.product', 'left')
->select('book_images.*') ->select('book_images.*')
@ -355,13 +362,13 @@ public function getJoinedData($where, $orderby = [])
return $data; return $data;
} }
public function insertupdateSubscriptionData($data,$invoice_status) public function insertupdateSubscriptionData($data, $invoice_status)
{ {
if (!empty($data)) { if (!empty($data)) {
$invoice_id = $data['invoice_id']; $invoice_id = $data['invoice_id'];
$customer_id = $data['customer_id']; $customer_id = $data['customer_id'];
$scheme_id = $data['scheme_id']; $scheme_id = $data['scheme_id'];
$data['isactive'] = $invoice_status === 'Approved' ? 1 : 0 ; $data['isactive'] = $invoice_status === 'Approved' ? 1 : 0;
$where = ['invoice_id' => $invoice_id]; // invoice id refer with srinivasan // initally invoice id, scheme id and customer id $where = ['invoice_id' => $invoice_id]; // invoice id refer with srinivasan // initally invoice id, scheme id and customer id
$query = $this->db->table('subscription')->select('sub_id')->where($where)->get()->getRow(); $query = $this->db->table('subscription')->select('sub_id')->where($where)->get()->getRow();
@ -374,12 +381,12 @@ public function insertupdateSubscriptionData($data,$invoice_status)
} }
} }
return false; return false;
} }
// ***********************REPORT********************** // ***********************REPORT**********************
public function get_general_invoice_data($f_date = null, $t_date = null) public function get_general_invoice_data($f_date = null, $t_date = null)
{ {
// Fetch invoice data // Fetch invoice data
$query = $this->db->table('invoice') $query = $this->db->table('invoice')
->select('invoice.*,DATE_FORMAT(invoice.invoice_date, "%d/%m/%Y") AS formatted_invoice_date, customers.*, COUNT(invoiceitems.product) as item_count') ->select('invoice.*,DATE_FORMAT(invoice.invoice_date, "%d/%m/%Y") AS formatted_invoice_date, customers.*, COUNT(invoiceitems.product) as item_count')
@ -402,11 +409,11 @@ public function get_general_invoice_data($f_date = null, $t_date = null)
->getResult(); ->getResult();
return $result; return $result;
} }
public function get_mem_invoice_data($f_date = null, $t_date = null) public function get_mem_invoice_data($f_date = null, $t_date = null)
{ {
// Fetch invoice data // Fetch invoice data
$query = $this->db->table('invoice') $query = $this->db->table('invoice')
->select('invoice.*, customers.*, COUNT(invoiceitems.product) as item_count,DATE_FORMAT(invoice.invoice_date, "%d/%m/%Y") AS formatted_invoice_date,subscription.from_subscription,subscription.to_subscription,DATE_FORMAT(subscription.from_subscription, "%d/%m/%Y") AS formatted_from_date,DATE_FORMAT(subscription.to_subscription, "%d/%m/%Y") AS formatted_to_date') ->select('invoice.*, customers.*, COUNT(invoiceitems.product) as item_count,DATE_FORMAT(invoice.invoice_date, "%d/%m/%Y") AS formatted_invoice_date,subscription.from_subscription,subscription.to_subscription,DATE_FORMAT(subscription.from_subscription, "%d/%m/%Y") AS formatted_from_date,DATE_FORMAT(subscription.to_subscription, "%d/%m/%Y") AS formatted_to_date')
@ -429,40 +436,39 @@ public function get_mem_invoice_data($f_date = null, $t_date = null)
->getResult(); ->getResult();
return $result; return $result;
}
} // public function itemwise_report_data($f_date = null, $t_date = null)
// {
// // Fetch invoice data
// $query = $this->db->table('invoice')
// ->select('invoice.*, books.* , COUNT(invoiceitems.product) as item_count , sum(invoiceitems.product * invoiceitems.unit_price) as item_cost')
// ->where('invoice.isactive', 1)
// ->where('books.isactive', 1);
// public function itemwise_report_data($f_date = null, $t_date = null) // // Add date range filter if provided
// { // if ($f_date !== null && $t_date !== null) {
// // Fetch invoice data // $query->where('invoice.invoice_date >=', $f_date)
// $query = $this->db->table('invoice') // ->where('invoice.invoice_date <=', $t_date);
// ->select('invoice.*, books.* , COUNT(invoiceitems.product) as item_count , sum(invoiceitems.product * invoiceitems.unit_price) as item_cost') // }
// ->where('invoice.isactive', 1)
// ->where('books.isactive', 1);
// // Add date range filter if provided // $result = $query->join('invoiceitems', 'invoiceitems.invoice_id = invoice.invoice_id', 'left')
// if ($f_date !== null && $t_date !== null) { // ->join('books', 'books.book_id = invoiceitems.product', 'left')
// $query->where('invoice.invoice_date >=', $f_date) // ->groupBy('books.book_id')
// ->where('invoice.invoice_date <=', $t_date); // ->get()
// } // ->getResult();
// $result = $query->join('invoiceitems', 'invoiceitems.invoice_id = invoice.invoice_id', 'left') // return $result;
// ->join('books', 'books.book_id = invoiceitems.product', 'left') // }
// ->groupBy('books.book_id') public function itemwise_report_data($f_date = null, $t_date = null)
// ->get() {
// ->getResult();
// return $result;
// }
public function itemwise_report_data($f_date = null, $t_date = null)
{
// Fetch invoice data // Fetch invoice data
$query = $this->db->table('invoice') $query = $this->db->table('invoice')
->select('books.publishers_code, COUNT(invoiceitems.product) as publisher_item_count, books.title as book_name, COUNT(invoiceitems.product) as item_count, SUM(invoiceitems.quantity * invoiceitems.unit_price) as total_cost ,DATE_FORMAT(books.publication_date, "%d/%m/%Y") AS book_publication_date'); ->select('books.publishers_code, COUNT(invoiceitems.product) as publisher_item_count, books.title as book_name, COUNT(invoiceitems.product) as item_count, SUM(invoiceitems.quantity * invoiceitems.unit_price) as total_cost ,DATE_FORMAT(books.publication_date, "%d/%m/%Y") AS book_publication_date');
$query->where('invoice.isactive', 1) $query->where('invoice.isactive', 1)
->where('invoice.invoice_type',1) ->where('invoice.invoice_type', 1)
->where('books.isactive', 1); ->where('books.isactive', 1);
// Add date range filter if provided // Add date range filter if provided
@ -493,7 +499,7 @@ public function itemwise_report_data($f_date = null, $t_date = null)
'publisher_item_count' => 0, 'publisher_item_count' => 0,
'publisher_total_cost' => 0, 'publisher_total_cost' => 0,
'books' => [], 'books' => [],
'book_name'=>'', 'book_name' => '',
]; ];
} }
@ -505,16 +511,16 @@ public function itemwise_report_data($f_date = null, $t_date = null)
'book_name' => $row->book_name, 'book_name' => $row->book_name,
'item_count' => $row->item_count, 'item_count' => $row->item_count,
'total_cost' => $row->total_cost, 'total_cost' => $row->total_cost,
'book_publication_date' =>$row->book_publication_date, 'book_publication_date' => $row->book_publication_date,
]; ];
} }
return array_values($groupedResult); return array_values($groupedResult);
} }
public function getInvoiceIdByMd5($md5Hash) public function getInvoiceIdByMd5($md5Hash)
{ {
$result = $this->db->table($this->table) $result = $this->db->table($this->table)
->select('invoice_id') ->select('invoice_id')
->get() ->get()
@ -527,61 +533,61 @@ public function getInvoiceIdByMd5($md5Hash)
} }
return null; return null;
} }
// public function getExpiredCustomers($f_date = null, $t_date = null) // public function getExpiredCustomers($f_date = null, $t_date = null)
// { // {
// $now = date('Y-m-d'); // $now = date('Y-m-d');
// $futureDate = date('Y-m-d', strtotime($now . ' +30 days')); // $futureDate = date('Y-m-d', strtotime($now . ' +30 days'));
// $query = $this->db->table('subscription as S'); // Define $query here // $query = $this->db->table('subscription as S'); // Define $query here
// if ($f_date !== null && $t_date !== null) { // if ($f_date !== null && $t_date !== null) {
// $query->where('S.to_subscription >=', $f_date) // $query->where('S.to_subscription >=', $f_date)
// ->where('S.to_subscription <=', $t_date); // ->where('S.to_subscription <=', $t_date);
// } // }
// $result = $query // $result = $query
// ->select('S.customer_id,S.sub_id, S.from_subscription, S.to_subscription, C.first_name, C.last_name, C.email, C.mobile_no, S.scheme_id,B.short_code') // ->select('S.customer_id,S.sub_id, S.from_subscription, S.to_subscription, C.first_name, C.last_name, C.email, C.mobile_no, S.scheme_id,B.short_code')
// ->join('customers as C', 'C.customer_id = S.customer_id', 'left') // ->join('customers as C', 'C.customer_id = S.customer_id', 'left')
// ->join('books as B', 'B.book_id = S.scheme_id', 'left') // ->join('books as B', 'B.book_id = S.scheme_id', 'left')
// ->where('S.isactive', 1) // ->where('S.isactive', 1)
// ->where('S.to_subscription <', $futureDate) // ->where('S.to_subscription <', $futureDate)
// ->get() // ->get()
// ->getResultArray(); // ->getResultArray();
// // print_r($result); // // print_r($result);
// // echo "<pre>"; // // echo "<pre>";
// // echo $this->db->getLastQuery(); // // echo $this->db->getLastQuery();
// // echo "</pre>";die; // // echo "</pre>";die;
// echo $this->db->getLastQuery(); // echo $this->db->getLastQuery();
// die(); // die();
// return $result; // return $result;
// } // }
public function getExpiredCustomers($f_date = null, $t_date = null) public function getExpiredCustomers($f_date = null, $t_date = null)
{ {
// Set timezone for accurate date calculation // Set timezone for accurate date calculation
date_default_timezone_set('Asia/Kolkata'); date_default_timezone_set('Asia/Kolkata');
// Calculate the date 30 days from now // Calculate the date 30 days from now
$futureDate = date('Y-m-d', strtotime('+30 days')); $futureDate = date('Y-m-d', strtotime('+30 days'));
$query = $this->db->table('subscription as S'); $query = $this->db->table('subscription as S');
if (!empty($f_date) && !empty($t_date)) { if (!empty($f_date) && !empty($t_date)) {
$query->where('S.to_subscription >=', $f_date) $query->where('S.to_subscription >=', $f_date)
->where('S.to_subscription <=', $t_date); ->where('S.to_subscription <=', $t_date);
} else { } else {
$query->where('S.to_subscription >=', date('Y-m-d')) $query->where('S.to_subscription >=', date('Y-m-d'))
->where('S.to_subscription <=', $futureDate); ->where('S.to_subscription <=', $futureDate);
} }
$subquery = $this->db->table('subscription as S2') $subquery = $this->db->table('subscription as S2')
->select('S.sub_id') ->select('S.sub_id')
->where('S2.customer_id = S.customer_id') ->where('S2.customer_id = S.customer_id')
->where('S.sub_id = S2.is_renew'); ->where('S.sub_id = S2.is_renew');
$result = $query $result = $query
->select('S.customer_id, S.sub_id, S.from_subscription, S.to_subscription, ->select('S.customer_id, S.sub_id, S.from_subscription, S.to_subscription,
C.first_name, C.last_name, C.email, C.mobile_no, C.first_name, C.last_name, C.email, C.mobile_no,
S.scheme_id, B.short_code, S.membership_id') S.scheme_id, B.short_code, S.membership_id')
@ -599,8 +605,9 @@ $result = $query
// Fetch results as an associative array // Fetch results as an associative array
return $result->getResultArray(); return $result->getResultArray();
} }
public function getActiveMembers(){ public function getActiveMembers()
{
$result = $result =
$this->db->table('subscription as S') $this->db->table('subscription as S')
->select('S.customer_id, S.sub_id, S.from_subscription, S.to_subscription, ->select('S.customer_id, S.sub_id, S.from_subscription, S.to_subscription,
@ -613,11 +620,10 @@ public function getActiveMembers(){
->orderBy('S.to_subscription', 'ASC') ->orderBy('S.to_subscription', 'ASC')
->get(); ->get();
return $result->getResultArray(); return $result->getResultArray();
}
} public function itemwise_report_data_with_publish_code($f_date = null, $t_date = null)
{
public function itemwise_report_data_with_publish_code($f_date = null, $t_date = null)
{
// Fetch invoice data // Fetch invoice data
$query = $this->db->table('invoice') $query = $this->db->table('invoice')
->select('invoice.*, books.* , COUNT(invoiceitems.product) as item_count , sum(invoiceitems.product * invoiceitems.unit_price) as item_cost') ->select('invoice.*, books.* , COUNT(invoiceitems.product) as item_count , sum(invoiceitems.product * invoiceitems.unit_price) as item_cost')
@ -639,11 +645,9 @@ public function itemwise_report_data_with_publish_code($f_date = null, $t_date =
// print_r($result);die; // print_r($result);die;
return $result; return $result;
} }
public function userwise_eventwise_report($f_date = null, $t_date = null){
public function userwise_eventwise_report($f_date = null, $t_date = null) {
$builder = $this->db->table('invoice'); $builder = $this->db->table('invoice');
$builder->select([ $builder->select([
@ -654,6 +658,7 @@ public function userwise_eventwise_report($f_date = null, $t_date = null){
'COUNT(invoice.created_by) AS books_sold', 'COUNT(invoice.created_by) AS books_sold',
'ABS(SUM(invoice.exact_total_amount)) AS total_amount', 'ABS(SUM(invoice.exact_total_amount)) AS total_amount',
'invoice.payment_method', 'invoice.payment_method',
// 'DATE(invoice.invoice_date) AS invoice_date' // Convert to DATE
'invoice.invoice_date' 'invoice.invoice_date'
]); ]);
@ -663,26 +668,31 @@ public function userwise_eventwise_report($f_date = null, $t_date = null){
$builder->join('books', 'books.book_id = invoiceitems.product'); $builder->join('books', 'books.book_id = invoiceitems.product');
$builder->where('invoice.event_id <>', 0); $builder->where('invoice.event_id <>', 0);
if ($f_date !== null && $t_date !== null) { if ($f_date !== null && $t_date !== null) {
$builder->where('invoice.invoice_date >=', $f_date) $builder->where('invoice.invoice_date >=', $f_date)
->where('invoice.invoice_date <=', $t_date); ->where('invoice.invoice_date <=', $t_date);
} }
$builder->groupBy([ $builder->groupBy([
'invoice_date',
'users.user_id', 'users.user_id',
'users.first_name', 'events.event_name'
'events.event_name',
'payment_method'
]); ]);
// Order by the converted date
$builder->orderBy('invoice_date', 'DESC');
$query = $builder->get(); $query = $builder->get();
$results = $query->getResultArray(); $result = $query->getResultArray();
return $results; // dd($result);
} return $result;
}
public function getPaymentReport($f_date = null, $t_date = null)
{ public function getPaymentReport($f_date = null, $t_date = null)
{
$builder = $this->db->table('invoice'); $builder = $this->db->table('invoice');
$builder->select('invoice.invoice_number, customers.first_name, invoice.total_amount, invoice.payment_status, invoice.payment_method, invoice.invoice_date'); $builder->select('invoice.invoice_number, customers.first_name, invoice.total_amount, invoice.payment_status, invoice.payment_method, invoice.invoice_date');
@ -691,7 +701,7 @@ public function getPaymentReport($f_date = null, $t_date = null)
$builder->where('invoice.invoice_date >=', $f_date) $builder->where('invoice.invoice_date >=', $f_date)
->where('invoice.invoice_date <=', $t_date); ->where('invoice.invoice_date <=', $t_date);
} }
$builder->where('invoice.status','Approved'); $builder->where('invoice.status', 'Approved');
$query = $builder->get(); $query = $builder->get();
$result1 = $query->getResultArray(); $result1 = $query->getResultArray();
$builder->select('payment_method, SUM(exact_total_amount) as total_amount'); $builder->select('payment_method, SUM(exact_total_amount) as total_amount');
@ -703,20 +713,20 @@ public function getPaymentReport($f_date = null, $t_date = null)
$query2 = $builder->get(); $query2 = $builder->get();
$paymentMethodTotals = $query2->getResultArray(); $paymentMethodTotals = $query2->getResultArray();
$paymentMethodMap = []; $paymentMethodMap = [];
foreach ($paymentMethodTotals as $row) { foreach ($paymentMethodTotals as $row) {
$paymentMethodMap[$row['payment_method']] = $row['total_amount']; $paymentMethodMap[$row['payment_method']] = $row['total_amount'];
} }
$result2 = $paymentMethodMap; $result2 = $paymentMethodMap;
// log_message('info',json_encode($results)); // log_message('info',json_encode($results));
// dd($results); // dd($results);
$results = [ $results = [
'result1'=>$result1, 'result1' => $result1,
'result2'=>$result2 'result2' => $result2
]; ];
return $results; return $results;
} }
public function itemwise_report_data_with_payment_method($f_date = null, $t_date = null) public function itemwise_report_data_with_payment_method($f_date = null, $t_date = null)
{ {
$builder = $this->db->table('invoice'); $builder = $this->db->table('invoice');
$builder->select('books.publishers_code, $builder->select('books.publishers_code,
COUNT(invoiceitems.product) AS publisher_item_count, COUNT(invoiceitems.product) AS publisher_item_count,
@ -771,11 +781,11 @@ public function itemwise_report_data_with_payment_method($f_date = null, $t_date
} }
return array_values($groupedResult); return array_values($groupedResult);
} }
public function updateInvoiceStatus($invoiceId, $voidReason) public function updateInvoiceStatus($invoiceId, $voidReason)
{ {
// Assuming 'invoices' is the name of your table // Assuming 'invoices' is the name of your table
$builder = $this->db->table('invoice'); $builder = $this->db->table('invoice');
@ -793,9 +803,9 @@ public function updateInvoiceStatus($invoiceId, $voidReason)
$updated = $builder->update($data); $updated = $builder->update($data);
return $updated; return $updated;
} }
public function updateInvoiceCancelStatus($invoiceIds, $cancelReason) public function updateInvoiceCancelStatus($invoiceIds, $cancelReason)
{ {
// Assuming 'invoices' is the name of your table // Assuming 'invoices' is the name of your table
$builder = $this->db->table('invoice'); $builder = $this->db->table('invoice');
@ -813,23 +823,19 @@ public function updateInvoiceCancelStatus($invoiceIds, $cancelReason)
$updated = $builder->update($data); $updated = $builder->update($data);
return $updated; return $updated;
} }
public function getActiveSchemes(){ public function getActiveSchemes()
$builder = $this->db->table($this->table.' as I' ); {
$builder = $this->db->table($this->table . ' as I');
$builder->select('books.short_code'); $builder->select('books.short_code');
$builder->join('subscription','subscription.invoice_id = I.invoice_id'); $builder->join('subscription', 'subscription.invoice_id = I.invoice_id');
$builder->join('invoiceitems','invoiceitems.invoice_id = I.invoice_id'); $builder->join('invoiceitems', 'invoiceitems.invoice_id = I.invoice_id');
$builder->join('books','invoiceitems.product = books.book_id'); $builder->join('books', 'invoiceitems.product = books.book_id');
$builder->groupBy('short_code'); $builder->groupBy('short_code');
$query = $builder->get(); $query = $builder->get();
$results = $query->getResultArray(); $results = $query->getResultArray();
return $results; return $results;
}
} }
}

View File

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

View File

@ -30,7 +30,7 @@ class PaymentStatusModel extends Model
public function getPaymentData($fromDate, $toDate, $status) public function getPaymentData($fromDate, $toDate, $status)
{ {
$builder = $this->db->table('payment_status')->select('payment_status.*,concat(customers.first_name," ",customers.last_name) as customer_name,books.short_code as scheme_name') $builder = $this->db->table('payment_status')->select('payment_status.*,CONCAT(COALESCE(customers.first_name, ""), " ", COALESCE(customers.last_name, "")) AS customer_name,books.short_code as scheme_name')
->join('customers','customers.customer_id = payment_status.customer_id and customers.isactive = 1') ->join('customers','customers.customer_id = payment_status.customer_id and customers.isactive = 1')
->join('books','books.book_id = payment_status.scheme_id and books.isactive = 1'); ->join('books','books.book_id = payment_status.scheme_id and books.isactive = 1');
@ -46,6 +46,7 @@ class PaymentStatusModel extends Model
} }
$builder->where('payment_status.is_active',1); $builder->where('payment_status.is_active',1);
$builder->orderBy('payment_status.created_at','desc');
$data = $builder->get()->getResultArray(); $data = $builder->get()->getResultArray();
// log_message('error',json_encode($this->db->getLastQuery()->getQuery())); // log_message('error',json_encode($this->db->getLastQuery()->getQuery()));
return $data; // Fetch and return as an array return $data; // Fetch and return as an array

View File

@ -0,0 +1,131 @@
<!-- start page title -->
<div class="row d-flex align-items-center">
<div class="col-md-4">
<div class="page-title-box page-title-box-alt">
<h4 class="page-title"><?= !empty($showPayment) ? 'Payment Logs' : 'Log Files' ?></h4>
</div>
</div>
<div class="col-md-8 text-md-right">
<?php if (!empty($showPayment)): ?>
<a href="<?= site_url('logs') ?>" class="btn btn-secondary">
<i class="mdi mdi-arrow-left"></i> View All Logs
</a>
<?php else: ?>
<a href="<?= site_url('logs?payment=1') ?>" class="btn btn-warning">
<i class="mdi mdi-credit-card-outline"></i> View Payment Logs
</a>
<?php endif; ?>
</div>
</div>
<!-- end page title -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<?php if (session()->getFlashdata('message')): ?>
<div class="alert alert-success"><?= esc(session()->getFlashdata('message')) ?></div>
<?php endif; ?>
<?php if (session()->getFlashdata('error')): ?>
<div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
<?php endif; ?>
<?php if (!empty($showPayment)): ?>
<p class="text-muted mb-3">
Showing <strong><?= (int) $lineCount ?></strong> log <?= $lineCount === 1 ? 'entry' : 'entries' ?>
containing <code>[PAYMENT]</code> across all log files.
</p>
<?php if (empty($entries)): ?>
<div class="alert alert-info mb-0">
No payment log entries found. Payment activity is logged with the <code>[PAYMENT]</code> tag.
</div>
<?php else: ?>
<?php foreach ($entries as $entry): ?>
<h5 class="mt-3 mb-2">
<i class="mdi mdi-file-document-outline"></i> <?= esc($entry['file']) ?>
<span class="badge badge-soft-warning"><?= count($entry['lines']) ?> entries</span>
<a href="<?= site_url('logs/view/' . $entry['file'] . '?payment=1') ?>" class="btn btn-sm btn-outline-warning ml-2">
Open File
</a>
</h5>
<pre class="payment-log-block"><?= esc(implode("\n", $entry['lines'])) ?></pre>
<?php endforeach; ?>
<?php endif; ?>
<?php else: ?>
<div class="table-responsive">
<table id="datatable-buttons" class="table table-striped nowrap w-100">
<thead>
<tr>
<th>File Name</th>
<th>Size</th>
<th>Last Modified</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if (empty($files)): ?>
<tr>
<td colspan="4" class="text-center text-muted">No log files found.</td>
</tr>
<?php else: ?>
<?php foreach ($files as $file): ?>
<tr>
<td><?= esc($file['name']) ?></td>
<td><span class="badge badge-soft-secondary"><?= esc($file['size']) ?></span></td>
<td><?= esc($file['modified']) ?></td>
<td>
<a href="<?= site_url('logs/view/' . $file['name']) ?>" class="btn btn-sm btn-primary">
<i class="mdi mdi-eye"></i> View
</a>
<a href="<?= site_url('logs/view/' . $file['name'] . '?payment=1') ?>" class="btn btn-sm btn-warning">
<i class="mdi mdi-credit-card-outline"></i> Payment Logs
</a>
<a href="<?= site_url('logs/download/' . $file['name']) ?>" class="btn btn-sm btn-success">
<i class="mdi mdi-download"></i> Download
</a>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div><!-- end card-body -->
</div><!-- end card -->
</div><!-- end col -->
</div>
<!-- end row -->
<style>
.payment-log-block {
background: #1e1e2e;
color: #d4d4d4;
padding: 20px;
border-radius: 8px;
max-height: 75vh;
overflow: auto;
white-space: pre-wrap;
word-wrap: break-word;
font-size: 13px;
margin-bottom: 1rem;
}
</style>
<script>
$(document).ready(function () {
if ($('#datatable-buttons').length) {
$('#datatable-buttons').DataTable({
"order": [[2, 'desc']],
"dom": '<"row mb-3"<"col-md-6 d-flex align-items-center"f><"col-md-6 d-flex justify-content-end">>rtip',
columnDefs: [
{ orderable: false, targets: [3] }
]
});
}
});
</script>

View File

@ -0,0 +1,41 @@
<!-- start page title -->
<div class="row d-flex align-items-center">
<div class="col-md-8">
<div class="page-title-box page-title-box-alt">
<h4 class="page-title">
<?= !empty($showPayment) ? 'Payment Logs' : 'Viewing Log' ?>: <?= esc($filename) ?>
</h4>
</div>
</div>
<div class="col-md-4 text-md-right">
<a href="<?= site_url('logs') ?>" class="btn btn-secondary">
<i class="mdi mdi-arrow-left"></i> Back to Log Files
</a>
<?php if (!empty($showPayment)): ?>
<a href="<?= site_url('logs/view/' . $filename) ?>" class="btn btn-primary">
<i class="mdi mdi-eye"></i> View Full Log
</a>
<?php else: ?>
<a href="<?= site_url('logs/view/' . $filename . '?payment=1') ?>" class="btn btn-warning">
<i class="mdi mdi-credit-card-outline"></i> View Payment Logs
</a>
<?php endif; ?>
</div>
</div>
<!-- end page title -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<?php if (!empty($showPayment) && $content === ''): ?>
<div class="alert alert-info mb-0">
No payment log entries found in this file.
</div>
<?php else: ?>
<pre style="background:#1e1e2e; color:#d4d4d4; padding:20px; border-radius:8px; max-height:75vh; overflow:auto; white-space:pre-wrap; word-wrap:break-word; font-size:13px;"><?= esc($content) ?></pre>
<?php endif; ?>
</div>
</div>
</div>
</div>

View File

@ -12,7 +12,7 @@
<button type="button" id="callajax" class="btn btn-primary" onclick="sendsms()">Send Message</button> <button type="button" id="callajax" class="btn btn-primary" onclick="sendsms()">Send Message</button>
</div> </div>
<div class="col-md-4"> <div class="col-md-4">
<input id = 'date_picker' class="form-control input-daterange-datepicker" type="text" name="date" value="<?php echo $selected_data; ?>" /> <input id='date_picker' class="form-control input-daterange-datepicker" type="text" name="date" value="<?php echo $selected_data; ?>" />
</div> </div>
<div class="col-md-2"> <div class="col-md-2">
<button type="submit" class="btn btn-primary" onclick="generateData()">Generate Report</button> <button type="submit" class="btn btn-primary" onclick="generateData()">Generate Report</button>
@ -23,8 +23,8 @@
<br> <br>
<div class="col-md-12" style="margin: 15px;" id="target-div"></div> <div class="col-md-12" style="margin: 15px;" id="target-div"></div>
</div> </div>
<div id="modal_table"> <div id="modal_table">
<div class="table-responsive"> <div class="table-responsive">
<table id="datatable-buttons" class="table table-striped nowrap w-100"> <table id="datatable-buttons" class="table table-striped nowrap w-100">
<thead> <thead>
<tr> <tr>
@ -40,10 +40,13 @@
<tbody id="table-body"> <tbody id="table-body">
</tbody> </tbody>
</table> </table>
</div></div></div></div> <!-- end card body--> </div>
</div>
</div>
</div> <!-- end card body-->
</div> <!-- end card --> </div> <!-- end card -->
</div><!-- end col--><!-- end row--> </div><!-- end col--><!-- end row-->
<script> <script>
$(document).ready(function() { $(document).ready(function() {
@ -53,7 +56,7 @@
"ordering": false, "ordering": false,
"paging": true, "paging": true,
"searching": true, "searching": true,
"autoWidth":true "autoWidth": true
}); });
@ -77,15 +80,14 @@
.on('cancel.daterangepicker', function() { .on('cancel.daterangepicker', function() {
$(this).val(''); $(this).val('');
}); });
}); });
</script> </script>
<script> <script>
function sendsms() {
function sendsms(){
var params = $("#params").val(); var params = $("#params").val();
var params2 = $("#date_picker").val(); var params2 = $("#date_picker").val();
console.log("The param passed is "+params2); console.log("The param passed is " + params2);
if(params2){ if (params2) {
var dates = params2.split(" - "); var dates = params2.split(" - ");
var from_date = dates[0]; var from_date = dates[0];
var to_date = dates[1]; var to_date = dates[1];
@ -93,17 +95,17 @@
if (!params && !(params2)) { if (!params && !(params2)) {
alert("Enter a valid number of days."); alert("Enter a valid number of days.");
return; return;
}else{ } else {
console.log("param 1 is "+params); console.log("param 1 is " + params);
console.log("params 2 is "+ params2); console.log("params 2 is " + params2);
console.log('<?= base_url() . 'getExpCustomerDetail/' ?>'); console.log('<?= base_url() . 'getExpCustomerDetail/' ?>');
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: `<?= base_url() . 'getExpCustomerDetail/' ?>${params}/${params2}`, url: `<?= base_url() . 'getExpCustomerDetail/' ?>${params}/${params2}`,
data: { data: {
from_date : from_date, from_date: from_date,
to_date : to_date, to_date: to_date,
params : params params: params
}, },
success: function(response) { success: function(response) {
@ -121,7 +123,7 @@
} }
} }
function generateData(){ function generateData() {
var date = $("#date_picker").val(); var date = $("#date_picker").val();
console.log(date); console.log(date);
$.ajax({ $.ajax({
@ -130,7 +132,7 @@
data: { data: {
date: date date: date
}, },
success: function(response){ success: function(response) {
console.log(response); console.log(response);
var data = response.data; var data = response.data;
var table = $('#datatable-buttons').DataTable(); var table = $('#datatable-buttons').DataTable();
@ -144,9 +146,14 @@
var sentDateFormatted = ('0' + sentTime.getDate()).slice(-2) + '/' + var sentDateFormatted = ('0' + sentTime.getDate()).slice(-2) + '/' +
('0' + (sentTime.getMonth() + 1)).slice(-2) + '/' + ('0' + (sentTime.getMonth() + 1)).slice(-2) + '/' +
sentTime.getFullYear(); sentTime.getFullYear();
var sentTimeFormatted = ('0' + sentTime.getHours()).slice(-2) + ':' + var hours = sentTime.getHours();
('0' + sentTime.getMinutes()).slice(-2) + ':' + var minutes = ('0' + sentTime.getMinutes()).slice(-2);
('0' + sentTime.getSeconds()).slice(-2); var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12 || 12; // Convert 0 (midnight) and 12 (noon) properly
var sentTimeFormatted = ('0' + hours).slice(-2) + ':' + minutes + ' ' + ampm;
var sentDateTimeFormatted = sentDateFormatted + ' ' + sentTimeFormatted; // Combine date and time
var sentDateTimeFormatted = sentDateFormatted + ' ' + sentTimeFormatted; // Combine date and time var sentDateTimeFormatted = sentDateFormatted + ' ' + sentTimeFormatted; // Combine date and time
table.row.add([ table.row.add([
item.first_name + ' ' + item.last_name, item.first_name + ' ' + item.last_name,
@ -170,12 +177,13 @@
$('#modal_table').show(); $('#modal_table').show();
} }
}, },
error: function(xhr, status, error){ error: function(xhr, status, error) {
console.error("Ajax Error: ", error); console.error("Ajax Error: ", error);
} }
}); });
} }
function regenerateFilters(table) {
function regenerateFilters(table) {
$('#datatable-buttons thead tr:eq(1)').remove(); $('#datatable-buttons thead tr:eq(1)').remove();
$('#datatable-buttons thead tr').clone(true).appendTo('#datatable-buttons thead'); $('#datatable-buttons thead tr').clone(true).appendTo('#datatable-buttons thead');
@ -200,7 +208,5 @@ function regenerateFilters(table) {
} }
}); });
}); });
} }
</script> </script>

View File

@ -6,20 +6,30 @@
<th><b>SCHEME Name</b></th> <th><b>SCHEME Name</b></th>
<th>Date/Time</th> <th>Date/Time</th>
<th><b>ORDER ID</b></th> <th><b>ORDER ID</b></th>
<th>Payment Status</th> <th style="text-align: left;">Payment Status</th>
<th><b>Amount</b></th> <th><b>Amount</b></th>
<th><b>Action</b></th>
</tr> </tr>
</thead> </thead>
<tbody class="custom-tbody"> <tbody class="custom-tbody">
<?php foreach ($payment_status_data as $row) { ?> <?php foreach ($payment_status_data as $row) { ?>
<tr> <tr>
<td><?= isset($row['customer_name'])?$row['customer_name']:"-"?></td> <td style="text-align: left;"><?= isset($row['customer_name'])?$row['customer_name']:"-"?></td>
<td><?= isset($row['membership_id'])?$row['membership_id']:"-"?></td> <td style="text-align: left;"><?= isset($row['membership_id'])?$row['membership_id']:"-"?></td>
<td><?= isset($row['scheme_name'])?$row['scheme_name']:"-"?></td> <td style="text-align: left;"><?= isset($row['scheme_name'])?$row['scheme_name']:"-"?></td>
<td><?= isset($row['created_at'])? date("d/m/Y H:i:s", strtotime($row['created_at'])) : '-' ?></td> <td style="text-align: left;"><?= isset($row['created_at']) ? date("d/m/Y h:i A", strtotime($row['created_at'])) : '-' ?></td>
<td><?= isset($row['order_id'])?$row['order_id']:"-"?></td> <td style="text-align: left;"><?= isset($row['order_id'])?$row['order_id']:"-"?></td>
<td><?= isset($row['payment_status'])?$row['payment_status']:"-" ?></td> <td style="text-align: left;"><?= isset($row['payment_status'])?$row['payment_status']:"-" ?></td>
<td><?= isset($row['amount'])?$row['amount']:"-"?></td> <td style="text-align: right;"><?= isset($row['amount'])?$row['amount']:"-"?></td>
<td style="text-align: center;">
<?php if (($row['payment_status'] ?? '') === 'Not Received' && ! empty($row['order_id'])) { ?>
<button type="button" class="btn btn-sm btn-warning reconcile-btn" data-order-id="<?= esc($row['order_id']) ?>">
Sync with Paytm
</button>
<?php } else { ?>
-
<?php } ?>
</td>
</tr> </tr>
<?php } ?> <?php } ?>
</tbody> </tbody>

View File

@ -157,6 +157,35 @@
dom: 'Bfrtip', // 'B' means Buttons dom: 'Bfrtip', // 'B' means Buttons
buttons: [], buttons: [],
}); });
$('#datatable-buttons').off('click', '.reconcile-btn').on('click', '.reconcile-btn', function() {
var orderId = $(this).data('order-id');
var $btn = $(this);
if (!confirm('Verify this payment with Paytm and record the renewal if paid?')) {
return;
}
$btn.prop('disabled', true).text('Syncing...');
$.ajax({
url: "<?= base_url('payment_reconcile') ?>",
method: "POST",
data: { order_id: orderId },
dataType: "json",
success: function(response) {
alert(response.message);
if (response.status) {
var daterange = $('#daterange').val();
var status = $('#statusSwitch').is(':checked') ? 1 : 0;
getTableData(daterange, status);
} else {
$btn.prop('disabled', false).text('Sync with Paytm');
}
},
error: function() {
alert('Could not connect to the server. Please try again.');
$btn.prop('disabled', false).text('Sync with Paytm');
}
});
});
} }
function getPreviousMonthDateRange() { function getPreviousMonthDateRange() {

View File

@ -156,7 +156,7 @@
<script> <script>
$(document).ready(function () { $(document).ready(function () {
var table = $('#datatable-buttons').DataTable({ var table = $('#datatable-buttons').DataTable({
"order": [[1, 'desc']], "order": [[0, 'desc']],
dom: '<"row mb-3"<"col-md-6 d-flex align-items-center"B><"col-md-6 d-flex justify-content-end"f>>rtip', dom: '<"row mb-3"<"col-md-6 d-flex align-items-center"B><"col-md-6 d-flex justify-content-end"f>>rtip',
buttons: [ buttons: [
{ {

View File

@ -149,7 +149,7 @@
var table = $('#datatable-buttons').DataTable({ var table = $('#datatable-buttons').DataTable({
"order": [ "order": [
[1, 'desc'] // [0, 'desc']
], ],
"dom": '<"row mb-3"<"col-md-6 d-flex align-items-center"B><"col-md-6 d-flex justify-content-end"f>>rtip', "dom": '<"row mb-3"<"col-md-6 d-flex align-items-center"B><"col-md-6 d-flex justify-content-end"f>>rtip',
buttons: [{ buttons: [{

View File

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

View File

@ -38,7 +38,7 @@
<th>Event Name</th> <th>Event Name</th>
<th>User Name</th> <th>User Name</th>
<th>Books Sold</th> <th>Books Sold</th>
<th>Payment Method</th> <!-- <th>Payment Method</th> -->
<th>Total Amount</th> <th>Total Amount</th>
</tr> </tr>
</thead> </thead>
@ -46,13 +46,15 @@
<?php foreach ($report_data as $row) { ?> <?php foreach ($report_data as $row) { ?>
<tr> <tr>
<td hidden><?php echo $row["user_id"]; ?></td> <td hidden><?php echo $row["user_id"]; ?></td>
<?php $unixTime = strtotime($row['invoice_date']); <?php
$invoice_date = date("d/m/Y", $unixTime);?> // Since invoice_date is now a proper date, we can format it directly
$invoice_date = date("d/m/Y", strtotime($row['invoice_date']));
?>
<td><?= $invoice_date ?></td> <td><?= $invoice_date ?></td>
<td style="text-align: left;"><?= $row['event_name'] ?></td> <td style="text-align: left;"><?= $row['event_name'] ?></td>
<td style="text-align: left;"><?= $row['first_name'].' ('.$row['role'].')'?></td> <td style="text-align: left;"><?= $row['first_name'] . ' (' . $row['role'] . ')' ?></td>
<td style="text-align: center;"><?= $row['books_sold'] ?></td> <td style="text-align: center;"><?= $row['books_sold'] ?></td>
<td style="text-align: left;"><?= strtoupper($row['payment_method'])?></td> <!-- <td style="text-align: left;"><?= strtoupper($row['payment_method']) ?></td> -->
<td style="text-align:right;padding-right: 67px;"><?= $row['total_amount'] ?></td> <td style="text-align:right;padding-right: 67px;"><?= $row['total_amount'] ?></td>
</tr> </tr>
<?php } ?> <?php } ?>
@ -67,22 +69,22 @@
<!-- end row--> <!-- end row-->
<script> <script>
$(document).ready(function () { $(document).ready(function() {
var table = $('#datatable-buttons').DataTable({ var table = $('#datatable-buttons').DataTable({
"order": [[0, 'desc']], ordering: false,
// "order": [[0, 'desc']],
// "order": [[0, 'desc']], // "order": [[0, 'desc']],
"dom": '<"row mb-3"<"col-md-6 d-flex align-items-center"B><"col-md-6 d-flex justify-content-end"f>>rtip', "dom": '<"row mb-3"<"col-md-6 d-flex align-items-center"B><"col-md-6 d-flex justify-content-end"f>>rtip',
buttons: [ buttons: [{
{
extend: 'print', extend: 'print',
title: '<?= $page_name.' ' .$selected_data ?>', title: '<?= $page_name . ' ' . $selected_data ?>',
text: 'Print', text: 'Print',
customize: function (win) { } customize: function(win) {}
}, },
{ {
extend: 'csv', extend: 'csv',
text: 'CSV', text: 'CSV',
title: '<?= $page_name.' ' .$selected_data ?>', title: '<?= $page_name . ' ' . $selected_data ?>',
exportOptions: {} exportOptions: {}
} }
] ]

View File

@ -27,7 +27,7 @@
<link href="<?= base_url() . "public/assets/libs/bootstrap-datepicker/css/bootstrap-datepicker.min.css" ?>" rel="stylesheet" type="text/css" /> <link href="<?= base_url() . "public/assets/libs/bootstrap-datepicker/css/bootstrap-datepicker.min.css" ?>" rel="stylesheet" type="text/css" />
<link href="<?= base_url() . "public/assets/libs/bootstrap-daterangepicker/daterangepicker.css" ?>" rel="stylesheet" type="text/css"> <link href="<?= base_url() . "public/assets/libs/bootstrap-daterangepicker/daterangepicker.css" ?>" rel="stylesheet" type="text/css">
<link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>"> <script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>
<!-- third party css end --> <!-- third party css end -->
@ -306,6 +306,10 @@
<a href="<?= base_url() . "report_userwise_and_eventwise"; ?>">User Eventwise-Sales</a> <a href="<?= base_url() . "report_userwise_and_eventwise"; ?>">User Eventwise-Sales</a>
</li> </li>
<li>
<a href="<?= base_url() . "logs"; ?>">Logs</a>
</li>
</ul> </ul>
</div> </div>

BIN
public/systemflow.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 555 KiB