From da41a90bd9d3e359227898285e6cf5b397ad5015 Mon Sep 17 00:00:00 2001 From: VE10-Sanjeev Date: Tue, 2 Apr 2024 19:00:10 +0530 Subject: [PATCH] Live Issues addresses are not printing fixes : ps --- app/Config/Routes.php | 2 +- app/Controllers/ApiIntegration.php | 12 +- app/Controllers/Invoice.php | 883 +++++++++--------- app/Controllers/Users.php | 10 +- app/Views/invoice_form.php | 1398 ++++++++++++++-------------- app/Views/invoice_list.php | 119 +-- app/Views/invoice_pdf_template.php | 308 +++--- app/Views/template/topbar.php | 2 +- app/Views/user_form.php | 8 +- app/Views/user_list.php | 4 +- 10 files changed, 1401 insertions(+), 1345 deletions(-) diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 00661747..edd66cb4 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -49,7 +49,7 @@ $routes->get('dashboard/', 'Home::index'); # Users Routes $routes->get("user_list/", "Users::index"); -$routes->get("user_page/(:any)", "Users::user_page/$1"); +$routes->get("user_page/(:any)/(:any)", "Users::user_page/$1/$2"); $routes->post("insert_users", "Users::insert_users"); $routes->get('users/fetch_event_names', 'Users::fetch_event_names'); diff --git a/app/Controllers/ApiIntegration.php b/app/Controllers/ApiIntegration.php index 6a8c9c3f..1faa7b55 100644 --- a/app/Controllers/ApiIntegration.php +++ b/app/Controllers/ApiIntegration.php @@ -742,8 +742,10 @@ class ApiIntegration extends ResourceController $billing_addr = NULL;$shipping_addr = NULL; $lineitems_array = []; $billing_array = []; $shipping_array = []; - $lineitems_subtotal = 0; $lineitems_tax = 0; - $lineitems_discount = 0; $lineitems_total=0; + $lineitems_subtotal = 0; ## for lineitem product wise price total + $lineitems_tax = 0; ## for lineitem product wise tax + $lineitems_discount = 0; ## for lineitem product wise discount + $lineitems_total=0; ## for lineitem grand total // $line_items = ; @@ -794,7 +796,8 @@ class ApiIntegration extends ResourceController } } - $subtotal = (float)$lineitems_subtotal + (float)$records['shipping_total']; + // $subtotal = (float)$lineitems_subtotal + (float)$records['shipping_total']; + $subtotal = (float)$lineitems_subtotal; $tax = $lineitems_tax + (float)$records['shipping_tax']; $total = ($lineitems_total)+(float)$records['shipping_total'] + (float)$records['shipping_tax']; $final_status = ''; @@ -830,7 +833,8 @@ class ApiIntegration extends ResourceController $invoice_data['subtotal']=(int)$subtotal; $invoice_data['tax']=(int)$tax; $invoice_data['discount']=(int)$lineitems_discount; - $invoice_data['total_amount']= $records['total']; + $invoice_data['total_amount']= round($records['total']); + $invoice_data['exact_total_amount']= (float)$records['total']; $invoice_data['payment_status']=$records['status']; $invoice_data['order_number']=$records['order_key']; $invoice_data['payment_method']=$records['payment_method_title']; diff --git a/app/Controllers/Invoice.php b/app/Controllers/Invoice.php index aea543f5..d206e80a 100644 --- a/app/Controllers/Invoice.php +++ b/app/Controllers/Invoice.php @@ -10,6 +10,7 @@ use App\Helpers\NotificationHelper; use Mpdf\Mpdf; use Dompdf\Dompdf; + class Invoice extends BaseController { ## For Invoice Listing.. @@ -22,10 +23,10 @@ class Invoice extends BaseController if (!empty($session_role) && $session_role !== "sadmin") { $this->logger->info("Invoice: Listing In Admin BID = " . $session_bid); - $where = ['I.business_id' => (int)$session_bid, 'I.isactive' => 1,'I.invoice_type'=>1]; + $where = ['I.business_id' => (int)$session_bid, 'I.isactive' => 1, 'I.invoice_type' => 1]; } else { $this->logger->info("Invoice: Listing In the Super-Admin "); - $where = ['I.business_id != ' => NULL, 'I.isactive != ' => NULL,'I.invoice_type'=>1]; + $where = ['I.business_id != ' => NULL, 'I.isactive != ' => NULL, 'I.invoice_type' => 1]; } $model = new InvoiceModel(); @@ -46,10 +47,10 @@ class Invoice extends BaseController if (!empty($session_role) && $session_role !== "sadmin") { $this->logger->info("Invoice: Listing In Admin BID = " . $session_bid); - $where = ['I.business_id' => (int)$session_bid, 'I.isactive' => 1,'I.invoice_type'=>1]; + $where = ['I.business_id' => (int)$session_bid, 'I.isactive' => 1, 'I.invoice_type' => 1]; } else { $this->logger->info("Invoice: Listing In the Super-Admin "); - $where = ['I.business_id != ' => NULL, 'I.isactive != ' => NULL,'I.invoice_type'=>1]; + $where = ['I.business_id != ' => NULL, 'I.isactive != ' => NULL, 'I.invoice_type' => 1]; } $model = new InvoiceModel(); @@ -67,10 +68,10 @@ class Invoice extends BaseController { helper('session'); helper('financial_year_helper'); - + $model = new InvoiceModel(); $where = ['business_id' => (int)get_business_id()]; - + // Get customer names for the dropdown, events details, and books details $data['customers'] = $model->getData('customers', $where); $data['events'] = $model->getData('events', $where); @@ -87,17 +88,17 @@ class Invoice extends BaseController } elseif ($id !== '0') { $this->logger->info("Book Invoice: In Edit Details ID =" . $id); $data['page_name'] = 'Edit Book Invoice Details'; - $data['invoice_type'] ='1'; - $data['invoice_details'] = $model->where(['invoice_id' => $id, 'isactive' => 1])->first(); + $data['invoice_type'] = '1'; + $data['invoice_details'] = $model->where(['invoice_id' => $id, 'isactive' => 1])->first(); $select = ["customer_address_id", "CONCAT(address_1,' ',address_2) as address"]; - $where = ['address_type'=>2,'customer_addresses.isactive' => 1, 'customer_addresses.customer_id' => (int)$data['invoice_details']['customer_id']]; + $where = ['address_type' => 2, 'customer_addresses.isactive' => 1, 'customer_addresses.customer_id' => (int)$data['invoice_details']['customer_id']]; $data['customer_shipping_arr'] = $this->get_customer_address($where, $select); $data['invoice_item_details'] = $this->get_invoice_item($id); } - // print_r($data['invoice_details']);die; + // print_r($data['invoice_details']);die; $this->render_page('invoice_form', $data); } - + public function new_subscription_invoice($id = '0') { helper('session'); @@ -105,7 +106,7 @@ class Invoice extends BaseController $data['financial_year'] = get_financial_year(); $model = new InvoiceModel(); $where = ['business_id' => (int)get_business_id()]; - + // Get customer names for the dropdown, events details, and subscription books details $data['customers'] = $model->getData('customers', $where); $data['events'] = $model->getData('events', $where); @@ -114,28 +115,28 @@ class Invoice extends BaseController if ($id === '0') { $this->logger->info("Subscription Invoice: In Add Page"); $data['page_name'] = 'Add Subscription Invoice Details'; - $data['invoice_type'] ='2'; + $data['invoice_type'] = '2'; $data['invoice_details'] = []; $data['invoice_item_details'] = []; } elseif ($id !== '0') { $this->logger->info("Subscription Invoice: In Edit Page ID =" . $id); $data['page_name'] = 'Edit Subscription Invoice Details'; - $data['invoice_type'] ='2'; + $data['invoice_type'] = '2'; $data['invoice_details'] = $model->where(['invoice_id' => $id, 'isactive' => 1])->first(); $select = ["customer_address_id", "CONCAT(address_1,' ',address_2) as address"]; - $where = ['address_type'=>2,'customer_addresses.isactive' => 1, 'customer_addresses.customer_id' => (int)$data['invoice_details']['customer_id']]; + $where = ['address_type' => 2, 'customer_addresses.isactive' => 1, 'customer_addresses.customer_id' => (int)$data['invoice_details']['customer_id']]; $data['customer_shipping_arr'] = $this->get_customer_address($where, $select); $data['invoice_item_details'] = $this->get_invoice_item($id); } - + $this->render_page('invoice_form', $data); } - + ## For Ajax Call To Fetch/Retrive Membership Details Only Based On Customer... public function get_customer_membership_details() { $customer_id = $this->request->getPost('customer_id'); - $data['customer_membership'] = $this->get_customer_membership("membership",(int)$customer_id); + $data['customer_membership'] = $this->get_customer_membership("membership", (int)$customer_id); return $this->response->setJSON(['data' => $data]); } @@ -168,22 +169,23 @@ class Invoice extends BaseController $model = new CustomerModel(); $model->setTable('customer_addresses'); if (empty($select)) { - $select = ["customer_addresses.customer_id","customer_addresses.customer_address_id","customer_addresses.first_name","customer_addresses.last_name ","customer_addresses.company","customer_addresses.email","customer_addresses.mobile_no","customer_addresses.address_type","customer_addresses.address_1","customer_addresses.address_2","customer_addresses.city","customer_addresses.state","customer_addresses.postal_code","customer_addresses.country","states.state_name","countries.country_name"]; + $select = ["customer_addresses.customer_id", "customer_addresses.customer_address_id", "customer_addresses.first_name", "customer_addresses.last_name ", "customer_addresses.company", "customer_addresses.email", "customer_addresses.mobile_no", "customer_addresses.address_type", "customer_addresses.address_1", "customer_addresses.address_2", "customer_addresses.city", "customer_addresses.state", "customer_addresses.postal_code", "customer_addresses.country", "states.state_name", "countries.country_name"]; } $address_details = $model->select($select)->join('states', 'states.state_short_name = customer_addresses.state AND customer_addresses.country = "IN"', 'left')->join('countries', 'countries.country_short_name = customer_addresses.country', 'left')->where($where)->findAll(); return $address_details; } - public function get_customer_membership($category,$id){ + public function get_customer_membership($category, $id) + { $model = new InvoiceModel(); - $result = $model->getMembershipListForCustomer($category,$id); + $result = $model->getMembershipListForCustomer($category, $id); return $result; } ## To insert or update the details of the invoice public function save_invoice() { - + $this->logger->info("Invoice: Insert/Update Details"); try { @@ -204,7 +206,7 @@ class Invoice extends BaseController $requestData = $this->request->getPost(); $itemid = $requestData['invoice_child_id']; $count = count($itemid); - $scheme_id = null; + $scheme_id = null; if ($count > 0) { for ($x = 0; $x < $count; $x++) { if (!empty($requestData['item_details'][$x])) { @@ -214,26 +216,26 @@ class Invoice extends BaseController } // $now = date('Y-m-d'); // $get_exists_subscription_where = ['S.customer_id' => (int)$customer_id,'S.scheme_id' => $scheme_id,'I.status' => 'Approved','I.isactive' => 1,"S.to_subscription <= "=>$now]; - $get_exists_subscription_where = ['S.customer_id' => (int)$customer_id,'S.scheme_id' => $scheme_id,'I.status' => 'Approved','I.isactive' => 1]; + $get_exists_subscription_where = ['S.customer_id' => (int)$customer_id, 'S.scheme_id' => $scheme_id, 'I.status' => 'Approved', 'I.isactive' => 1]; $get_exists_subscription_dtls = $model->existsSubscriptionDetails($get_exists_subscription_where); - + if ($get_exists_subscription_dtls) { // session()->setFlashdata('success', 'This Scheme Already Existing in this Customer.'); $this->logger->info($msg_flag_name . ": This Scheme Already Existing in this Customer. "); $renewal = 1; } } - + ## Array Formation For Invoice Details.. $data = [ 'invoice_number' => $this->request->getPost('invoice_number'), - 'invoice_type'=> $this->request->getPost('invoice_type'), + 'invoice_type' => $this->request->getPost('invoice_type'), 'customer_id' => $customer_id, 'billing_address_id' => (int)$this->request->getPost('billing_address_id'), 'billing_address' => $this->request->getPost('billing_address'), 'shipping_address_id' => (int)$this->request->getPost('shipping_address_id'), 'shipping_address' => $this->request->getPost('shipping_address'), - 'notes'=>$this->request->getPost('notes'), + 'notes' => $this->request->getPost('notes'), 'invoice_date' => (!empty($invdate)) ? date("Y-m-d", strtotime($invdate)) : NULL, 'due_date' => (!empty($duedate)) ? date("Y-m-d", strtotime($duedate)) : NULL, 'subtotal' => (float)$this->request->getPost('sub_total'), @@ -242,133 +244,131 @@ class Invoice extends BaseController 'exact_total_amount' => (float)$this->request->getPost('exact_total_amount'), 'total_amount' => (int)$this->request->getPost('grand_total'), 'shipping_charge' => ((int)$invoiceType === 1) ? (float)$this->request->getPost('shippingCharges') : NULL, - 'shipping_label' => ((int)$invoiceType === 1) ? $this->request->getPost('shippingChargesLabel') : NULL, + 'shipping_label' => ((int)$invoiceType === 1) ? $this->request->getPost('shippingChargesLabel') : NULL, 'order_number' => $this->request->getPost('order_number'), 'payment_method' => $invoice_status !== 'Draft' ? $this->request->getPost('payment_method') : NULL, // "Credit Card," "Cash on Delivery," "PayPal","PayTm","Gpay" 'payment_status' => 'Pending', //"Paid," "Pending," "Failed," "Refunded," "Canceled," "Authorized," and "Completed." - 'payment_note'=> $this->request->getPost('payment_note'), + 'payment_note' => $this->request->getPost('payment_note'), 'event_id' => (int)$this->request->getPost('event_id'), 'business_id' => (int)get_business_id(), 'status' => $invoice_status, 'isactive' => 1 ]; - + ## Based on the invoice ID, we designated Insert or Update on Details... if (empty($invoice_id)) { $data['created_by'] = (int)get_logged_user_id(); if ($model->insert($data, 'invoices')) { $invoice_id = $model->insertID(); - session()->setFlashdata('success', $msg_flag_name.'has been added successfully.'); - $this->logger->info($msg_flag_name.": has been added successfully. Inserted ID = " . $invoice_id); + session()->setFlashdata('success', $msg_flag_name . 'has been added successfully.'); + $this->logger->info($msg_flag_name . ": has been added successfully. Inserted ID = " . $invoice_id); // If it's a subscription invoice, also store data in the 'subscription' table - + } else { - session()->setFlashdata('error', $msg_flag_name.'could not be added. Please try again.'); - $this->logger->error($msg_flag_name.": Err Occur could not be added. Please try again."); + session()->setFlashdata('error', $msg_flag_name . 'could not be added. Please try again.'); + $this->logger->error($msg_flag_name . ": Err Occur could not be added. Please try again."); } - } else { $data['updated_by'] = (int)get_logged_user_id(); if ($model->update($invoice_id, $data)) { // echo $model->getLastQuery();die; - session()->setFlashdata('success', $msg_flag_name.'has been updated successfully.'); - $this->logger->info($msg_flag_name.": has been updated successfully. Updated ID = " . $invoice_id); + session()->setFlashdata('success', $msg_flag_name . 'has been updated successfully.'); + $this->logger->info($msg_flag_name . ": has been updated successfully. Updated ID = " . $invoice_id); } else { - session()->setFlashdata('error', $msg_flag_name.'update failed. Please try again.'); - $this->logger->error($msg_flag_name.": Err Failed to update ID =" . $invoice_id); + session()->setFlashdata('error', $msg_flag_name . 'update failed. Please try again.'); + $this->logger->error($msg_flag_name . ": Err Failed to update ID =" . $invoice_id); } } $requestData = $this->request->getPost(); - if($this->request->getPost('next_id')){ - ## Array Formation For Invoice Numbering Format Details.. - $update_invoice_numbering = [ - 'id' => 1, - 'id_formating' => get_financial_year(), - 'next_id' => (int)$this->request->getPost('next_id'), - 'business_id' => (int)get_business_id(), - 'updated_by' => get_logged_user_id() - ]; - $this->update_number_formatting($update_invoice_numbering);} + if ($this->request->getPost('next_id')) { + ## Array Formation For Invoice Numbering Format Details.. + $update_invoice_numbering = [ + 'id' => 1, + 'id_formating' => get_financial_year(), + 'next_id' => (int)$this->request->getPost('next_id'), + 'business_id' => (int)get_business_id(), + 'updated_by' => get_logged_user_id() + ]; + $this->update_number_formatting($update_invoice_numbering); + } ## For Invoice Item Details Insert/Update.. $this->save_invoice_item($invoice_id, $requestData, (int)$this->request->getVar('product')); ## Subscription.. if ((int)$invoiceType === 2) { - + // Loop through invoice items and store them in the 'subscription' table $subscriptionModel = new InvoiceModel(); // Replace with your actual model $invoiceItems = $this->get_invoice_item($invoice_id); - + foreach ($invoiceItems as $item) { - + $product_id = $item['product']; $from_sub_date = $item['from_subscription']; $to_sub_date = $item['to_subscription']; - - + + $subscription_data = [ 'customer_id' => (int)$customer_id, 'invoice_id' => $invoice_id, 'scheme_id' => $product_id, - 'from_subscription'=>$from_sub_date, - 'to_subscription'=> $to_sub_date, + 'from_subscription' => $from_sub_date, + 'to_subscription' => $to_sub_date, 'business_id' => get_business_id(), - 'created_by' =>get_logged_user_id(), + 'created_by' => get_logged_user_id(), 'is_renew' => $renewal ]; if ($invoice_status == 'Draft') { - $get_subscription_draft_dtl_where = ['S.customer_id'=>$customer_id,'I.status'=>$invoice_status]; - // $get_subscription_draft_dtl_id = $model->InactiveSubscriptionDraftDetails($get_subscription_draft_dtl_where,get_logged_user_id()); - // $this->logger->info($msg_flag_name.": has been Inactived. Inv ID = ".implode(", ", $get_subscription_draft_dtl_id)); - $get_subscription_draft_dtl_id = $model->deleteSubscriptionDraftDetails($get_subscription_draft_dtl_where,get_logged_user_id()); - $this->logger->info($msg_flag_name.": has been Deleted. Inv ID = ".implode(", ", $get_subscription_draft_dtl_id)); - // $subscriptionModel->insertSubscriptionData($subscription_data); + $get_subscription_draft_dtl_where = ['S.customer_id' => $customer_id, 'I.status' => $invoice_status]; + // $get_subscription_draft_dtl_id = $model->InactiveSubscriptionDraftDetails($get_subscription_draft_dtl_where,get_logged_user_id()); + // $this->logger->info($msg_flag_name.": has been Inactived. Inv ID = ".implode(", ", $get_subscription_draft_dtl_id)); + $get_subscription_draft_dtl_id = $model->deleteSubscriptionDraftDetails($get_subscription_draft_dtl_where, get_logged_user_id()); + $this->logger->info($msg_flag_name . ": has been Deleted. Inv ID = " . implode(", ", $get_subscription_draft_dtl_id)); + // $subscriptionModel->insertSubscriptionData($subscription_data); + } else { + // Check if there is a draft entry for the customer_id and scheme_id + $get_subscription_draft_dtl_where = [ + 'S.customer_id' => $customer_id, + 'S.scheme_id' => $scheme_id, // Assuming scheme_id is available here + 'I.status' => 'Draft' + ]; + + $get_subscription_draft_dtl_id = $model->deleteSubscriptionDraftDetails($get_subscription_draft_dtl_where, get_logged_user_id()); + + $this->logger->info($msg_flag_name . ": Draft entry has been deleted. Inv ID = " . implode(", ", $get_subscription_draft_dtl_id)); + + // Now insert the new entry + + } } - else{ - // Check if there is a draft entry for the customer_id and scheme_id - $get_subscription_draft_dtl_where = [ - 'S.customer_id' => $customer_id, - 'S.scheme_id' => $scheme_id, // Assuming scheme_id is available here - 'I.status' => 'Draft' - ]; - - $get_subscription_draft_dtl_id = $model->deleteSubscriptionDraftDetails($get_subscription_draft_dtl_where, get_logged_user_id()); - - $this->logger->info($msg_flag_name . ": Draft entry has been deleted. Inv ID = " . implode(", ", $get_subscription_draft_dtl_id)); - - // Now insert the new entry - - } - } - $subscriptionModel->insertSubscriptionData($subscription_data); + $subscriptionModel->insertSubscriptionData($subscription_data); } ## Notification For Approve.. - $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 != "") { - $this->logger->info($msg_flag_name.": in ".$invoice_status.". ID = " . $invoice_id); + $this->logger->info($msg_flag_name . ": in " . $invoice_status . ". ID = " . $invoice_id); $this->approve_notifications((int)$invoice_id); } - } catch (\Exception $e) { - $this->logger->error($msg_flag_name.": Err Occur =" . $e->getMessage()); + $this->logger->error($msg_flag_name . ": Err Occur =" . $e->getMessage()); session()->setFlashdata('error', 'Message: ' . $e->getMessage()); } - - - if ($invoiceType === '2') { - $this->logger->info(session()->getFlashdata()); - // If the invoice_type is 2 (subscription invoice), redirect to the subscription list. - return redirect()->route('subscribers_list'); // Adjust the route name as needed. - } else { - // For other invoice types, redirect to the invoice list. - $this->logger->info(session()->getFlashdata()); - return redirect()->route('offline_invoice'); // Adjust the route name as needed. - } + + + if ($invoiceType === '2') { + $this->logger->info(session()->getFlashdata()); + // If the invoice_type is 2 (subscription invoice), redirect to the subscription list. + return redirect()->route('subscribers_list'); // Adjust the route name as needed. + } else { + // For other invoice types, redirect to the invoice list. + $this->logger->info(session()->getFlashdata()); + return redirect()->route('offline_invoice'); // Adjust the route name as needed. + } } ## For Updating Events Details .. @@ -414,7 +414,7 @@ class Invoice extends BaseController $where = ['isactive' => 1, 'invoice_id' => (int)$id]; // $model->inactiveMissingInvoiceItemDetails($where, $missingValues); $model->deleteMissingInvoiceItemDetails($where, $missingValues); - $this->logger->info("Child Item Details : has been Deleted. Inv Child ID = ".implode(", ", $missingValues)); + $this->logger->info("Child Item Details : has been Deleted. Inv Child ID = " . implode(", ", $missingValues)); } } } @@ -423,7 +423,7 @@ class Invoice extends BaseController $invoiceitem_arr = []; if ($count > 0) { for ($x = 0; $x < $count; $x++) { - if(!empty($requestData['item_details'][$x])){ + if (!empty($requestData['item_details'][$x])) { $invoiceitem_arr[$x]['invoice_id'] = $id; $invoiceitem_arr[$x]['product'] = (int)$requestData['item_details'][$x]; $invoiceitem_arr[$x]['quantity'] = (int)$requestData['quantity'][$x]; @@ -431,11 +431,11 @@ class Invoice extends BaseController $invoiceitem_arr[$x]['unit_price'] = (float)$requestData['rate'][$x]; $invoiceitem_arr[$x]['subtotal'] = (float)$requestData['amount'][$x]; $invoiceitem_arr[$x]['discount_amount'] = (float)$requestData['discount_amount'][$x]; - $invoiceitem_arr[$x]['discount_type'] =$requestData['discount_type'][$x]; + $invoiceitem_arr[$x]['discount_type'] = $requestData['discount_type'][$x]; if (!empty($requestData['from_subscription'])) { $invoiceitem_arr[0]['from_subscription'] = $requestData['from_subscription']; } - + if (!empty($requestData['to_subscription'])) { $invoiceitem_arr[0]['to_subscription'] = $requestData['to_subscription']; } @@ -531,25 +531,26 @@ class Invoice extends BaseController // Redirect back to the invoice list return redirect()->route('offline_invoice'); } - public function subscription_inactive(){ + public function subscription_inactive() + { $model = new InvoiceModel(); $details = $model->subscription_inactive(); $now = date('d-m-Y'); - if(strtolower(gettype($details)) == "string"){ + if (strtolower(gettype($details)) == "string") { $this->logger->info("Subscription Inactive : " . $details); - $result = $details ; - }else{ - $this->logger->info("Subscription Inactive : " .count($details) . " Subscription Records ". json_encode($details)); - $success_rating = isset($details['success_rating'])?$details['success_rating']:0; - $error_rating = isset($details['error_rating'])?$details['error_rating']:0; - $result = "Total ". count($details) . " Subscription Records.\n success rating = ".$success_rating."\n fail rating = ".$error_rating ."\n Note : Check Your Log File"; + $result = $details; + } else { + $this->logger->info("Subscription Inactive : " . count($details) . " Subscription Records " . json_encode($details)); + $success_rating = isset($details['success_rating']) ? $details['success_rating'] : 0; + $error_rating = isset($details['error_rating']) ? $details['error_rating'] : 0; + $result = "Total " . count($details) . " Subscription Records.\n success rating = " . $success_rating . "\n fail rating = " . $error_rating . "\n Note : Check Your Log File"; } - return $now." ".$result; + return $now . " " . $result; } public function approve_notifications($invoice_id) { - $this->logger->info("Approve Notifications : ID ".$invoice_id); + $this->logger->info("Approve Notifications : ID " . $invoice_id); $model = new InvoiceModel(); $where = ['I.business_id' => (int)get_business_id(), 'I.invoice_id' => $invoice_id, 'I.isactive' => 1]; $details = $model->getDetailForApproveNotifications($where); @@ -565,15 +566,15 @@ class Invoice extends BaseController $tax = ""; $total_amount = ""; $payment_method = ""; - $business_name= ""; - $business_address= ""; - $business_city= ""; - $business_state= ""; - $business_postal_code= ""; - $business_email= ""; - $business_mobile_no= ""; + $business_name = ""; + $business_address = ""; + $business_city = ""; + $business_state = ""; + $business_postal_code = ""; + $business_email = ""; + $business_mobile_no = ""; if (isset($details)) { - $this->logger->info("Invoice: approve notification Request data type = ".gettype($details)); + $this->logger->info("Invoice: approve notification Request data type = " . gettype($details)); } helper('notification'); $notification = new NotificationHelper(); @@ -587,18 +588,17 @@ class Invoice extends BaseController $recipient_mobile = $rec['customer_mobile']; $subtotal = $rec['subtotal']; $tax = $rec['tax']; - $invoiceDate=$rec['invoice_date']; - + $invoiceDate = $rec['invoice_date']; + $total_amount = $rec['total_amount']; $payment_method = $rec['payment_method']; - $business_name= $rec['business_name']; - $business_address= $rec['business_address']; - $business_city= $rec['business_city']; - $business_state= $rec['business_state']; - $business_postal_code= $rec['business_postal_code']; - $business_email= $rec['business_email']; - $business_mobile_no= $rec['business_mobile_no']; - + $business_name = $rec['business_name']; + $business_address = $rec['business_address']; + $business_city = $rec['business_city']; + $business_state = $rec['business_state']; + $business_postal_code = $rec['business_postal_code']; + $business_email = $rec['business_email']; + $business_mobile_no = $rec['business_mobile_no']; } $records['invoice_order_number'] = $reference_number; $records['invoice_serial_number'] = $invoice_serial_number; @@ -614,20 +614,18 @@ class Invoice extends BaseController // view('approve_template',$records); // $this->logger->info("Approve : Request data = ".json_encode($records)); // view('approve_template',$records); - + $records['template_name'] = 'approve_template'; $records['item'] = $details['item']; // print_r($records['item']);die; - $lineitem_html=""; + $lineitem_html = ""; foreach ($records['item'] as $inv) { // print_r($item->title);die; - $lineitem_html.='

'.$inv->title. ' x ' .$inv->quantity .' => ' .$inv->subtotal.'

'; - - + $lineitem_html .= '

' . $inv->title . ' x ' . $inv->quantity . ' => ' . $inv->subtotal . '

'; } - // print_r($title);die; + // print_r($title);die; $records['subject'] = $invoice_serial_number . " - Approval Notification"; - + $records['description'] = " @@ -655,11 +653,11 @@ class Invoice extends BaseController "; - - // print_r($records['description']);die; - $url = base_url("download_invoice_pdf/" . md5($invoice_id)); -$encodedUrl = urlencode($url); - $template = "Dear " . $recipient_name . ",\r\r\n\nYour Invoice has been generated.\n\nDetails:\r\n- Invoice Date: " . $invoiceDate . "\r\n- Invoice Number: " . $invoice_serial_number . "\r\n- Click here to download the Invoice: " . base_url("download_invoice_pdf/" .$encodedUrl); + + // print_r($records['description']);die; + $url = base_url("download_invoice_pdf/" . md5($invoice_id)); + $encodedUrl = urlencode($url); + $template = "Dear " . $recipient_name . ",\r\r\n\nYour Invoice has been generated.\n\nDetails:\r\n- Invoice Date: " . $invoiceDate . "\r\n- Invoice Number: " . $invoice_serial_number . "\r\n- Click here to download the Invoice: " . base_url("download_invoice_pdf/" . $encodedUrl); $params = (object) Null; $params->number = (int)'91' . $recipient_mobile; @@ -667,10 +665,10 @@ $encodedUrl = urlencode($url); $params->message = $template; $params->instance_id = $_ENV['WAAI_INSTANCE']; $params->access_token = $_ENV['WAAI_TOKEN']; - $this->logger->info("Approve notification Email Request data = ".json_encode($records)); + $this->logger->info("Approve notification Email Request data = " . json_encode($records)); $email_result = $notification->sendEmail($records); $this->logger->info("Approve notification Email Response = " . json_encode($email_result)); - $this->logger->info("Approve notification Whatsapp Request data = ".json_encode($params)); + $this->logger->info("Approve notification Whatsapp Request data = " . json_encode($params)); $whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params); $this->logger->info("Approve notification Whatsapp Response = " . json_encode($whatsapp_result)); } @@ -682,47 +680,46 @@ $encodedUrl = urlencode($url); // Fetch the invoice data based on $invoice_id $model = new InvoiceModel(); $data = $model->getInvoiceData($id); - $invoiceItems = $model->getInvoiceItems($id,'groupby'); + $invoiceItems = $model->getInvoiceItems($id, 'groupby'); - foreach($invoiceItems as $index => $singleItem) - { - $productImgs= $model->getProductImgs($singleItem->product); + foreach ($invoiceItems as $index => $singleItem) { + $productImgs = $model->getProductImgs($singleItem->product); $invoiceItems[$index]->imgs = $productImgs; - } - - + + // print_r($invoiceItems);die(); $invoice_type = $data[0]->invoice_type; - + // print_r($invoiceItems);die(); // Create an mPDF object $mpdf = new Mpdf([ - 'mode' => '', - 'format' => 'A5', - 'default_font_size' => 0, - 'default_font' => '', - 'margin_left' => 2, - 'margin_right' => 2, - 'margin_top' => 6, - 'margin_bottom' => 6, - 'margin_header' => 6, - 'margin_footer' =>-30, - 'orientation' => 'P', - ]); + 'mode' => '', + 'format' => 'A5', + 'default_font_size' => 0, + 'default_font' => '', + 'margin_left' => 2, + 'margin_right' => 2, + 'margin_top' => 6, + 'margin_bottom' => 6, + 'margin_header' => 6, + 'margin_footer' => -30, + 'orientation' => 'P', + ]); - - $mpdf->autoLangToFont = true; $mpdf->autoScriptToLang = true; + + $mpdf->autoLangToFont = true; + $mpdf->autoScriptToLang = true; // Set PDF properties $mpdf->SetTitle('Invoice'); $mpdf->SetAuthor($data[0]->company_name); $mpdf->SetCreator(''); - - $htmlFooter='
+ + $htmlFooter = '
'; - $mpdf->setHTMLFooter($htmlFooter); + $mpdf->setHTMLFooter($htmlFooter); // Generate the PDF content (HTML) if ($data[0]->status === 'Draft') { @@ -743,8 +740,8 @@ $encodedUrl = urlencode($url); // Generate the PDF content (HTML) with data - $html = view('invoice_pdf_template', ['data' => $data, 'invoiceItems' => $invoiceItems,'invoice_type' => $invoice_type,'invoiceTerms'=>$data]); -// echo $html;die; + $html = view('invoice_pdf_template', ['data' => $data, 'invoiceItems' => $invoiceItems, 'invoice_type' => $invoice_type, 'invoiceTerms' => $data]); + // echo $html;die; // Load HTML into the mPDF instance $mpdf->WriteHTML($html); @@ -756,34 +753,33 @@ $encodedUrl = urlencode($url); // Load required model $model = new InvoiceModel(); $data = $model->getInvoiceData($id); - // print_r($data);die; - $invoiceItems = $model->getInvoiceItems($id,'groupby'); - - foreach($invoiceItems as $index => $singleItem) - { - $productImgs= $model->getProductImgs($singleItem->product); + // print_r($data);die; + $invoiceItems = $model->getInvoiceItems($id, 'groupby'); + + foreach ($invoiceItems as $index => $singleItem) { + $productImgs = $model->getProductImgs($singleItem->product); $invoiceItems[$index]->imgs = $productImgs; } - + $invoice_type = $data[0]->invoice_type; - + // Get status data $status = $data[0]->status; - + // Load view with data $html = view('invoice_pdf_template', ['data' => $data, 'invoiceItems' => $invoiceItems, 'invoice_type' => $invoice_type, 'invoiceTerms' => $data, 'status' => $status]); - + // Return HTML content echo $html; } - + // public function generate_invoice_pdf($id) // { // // Fetch the invoice data based on $invoice_id // $model = new InvoiceModel(); // $data = $model->getInvoiceData($id); // $invoiceItems = $model->getInvoiceItems($id, 'groupby'); - + // foreach ($invoiceItems as $index => $singleItem) { // $productImgs = $model->getProductImgs($singleItem->product); // $invoiceItems[$index]->imgs = $productImgs; @@ -791,36 +787,36 @@ $encodedUrl = urlencode($url); // $invoice_type = $data[0]->invoice_type; // // Create a DOMPDF instance // $dompdf = new Dompdf(); - + // // Set PDF properties // $options = $dompdf->getOptions(); // $options->set("isHtml5ParserEnabled", true); - + // // Set paper size and orientation // $dompdf->setPaper('A5', 'portrait'); - + // // Generate the PDF content (HTML) // if ($data[0]->status === 'Draft') { // // Add a watermark for draft status // $dompdf->set_option('page_script', function ($pageNumber, $pageCount, $canvas) { // $canvas->text(20, 20, 'Draft'); // }); - + // } - + // // Generate the PDF content (HTML) with data // $html = view('invoice_pdf_template', ['data' => $data, 'invoiceItems' => $invoiceItems, 'invoice_type' => $invoice_type, 'invoiceTerms' => $data]); - + // // Load HTML into the DOMPDF instance // $dompdf->loadHtml($html); - + // // Render PDF (first pass to get the number of pages) // $dompdf->render(); - + // // Output the PDF to the browser for download // $dompdf->stream('invoice_' . date('Y-m-d H-i-s') . '.pdf', array('Attachment' => 0)); // } - + public function print_address($id) { // Fetch the invoice data based on $id @@ -860,7 +856,7 @@ $encodedUrl = urlencode($url); $mpdf->WriteHTML($html); // Output the PDF for download - + $pdfFileName = 'customer_address_' . date('Y-m-d H-i-s') . '.pdf'; $mpdf->Output($pdfFileName, 'D'); } @@ -868,7 +864,7 @@ $encodedUrl = urlencode($url); public function general_inv_rp() { $model = new InvoiceModel(); - + if ($this->request->is('get')) { $data['report_data'] = $model->get_general_invoice_data(); $data['selected_data'] = ""; @@ -876,231 +872,218 @@ $encodedUrl = urlencode($url); $dateParts = explode(' - ', $this->request->getVar('date')); $fromDate = $dateParts[0]; $toDate = $dateParts[1]; - + // Update date conversion format using the global namespace $fromDate = \DateTime::createFromFormat('d/m/Y', $dateParts[0])->format('Y-m-d'); $toDate = \DateTime::createFromFormat('d/m/Y', $dateParts[1])->format('Y-m-d'); - + // Debugging statements for date range // var_dump($fromDate, $toDate);die; - + $data['report_data'] = $model->get_general_invoice_data($fromDate, $toDate); $data['selected_data'] = ($this->request->getVar('date')) ? $this->request->getVar('date') : ''; // var_dump( $data['selected_data']);die; - + } - + // Debugging statement for report data // print_r($data['selected_data']);die; - + $data['page_name'] = 'Sales Report'; $this->render_page('report_general_invoice', $data); } - + public function general_membership_inv_rp() - { - if($this->request->getmethod() == 'get') - { + { + if ($this->request->getmethod() == 'get') { $model = new InvoiceModel(); $data['report_data'] = $model->get_mem_invoice_data(); $this->logger->info("Membership Invoice Report "); - $data['page_name'] = 'Membership Invoice Report'; + $data['page_name'] = 'Membership Invoice Report'; $this->render_page('report_mem_invoice', $data); - } - else - { - $dateParts = explode(' - ', $this->request->getVar('date') ); + } else { + $dateParts = explode(' - ', $this->request->getVar('date')); $fromDate = $dateParts[0]; $toDate = $dateParts[1]; $dateTime = \DateTime::createFromFormat('m/d/Y', $fromDate); $dateTime1 = \DateTime::createFromFormat('m/d/Y', $toDate); $model = new InvoiceModel(); - $data['report_data'] = $model->get_mem_invoice_data( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') ); + $data['report_data'] = $model->get_mem_invoice_data($dateTime->format('Y-m-d'), $dateTime1->format('Y-m-d')); $this->logger->info("Membership Invoice Report "); - $data['page_name'] = 'Membership Invoice Report'; - $data['selected_data'] = $this->request->getVar('date'); + $data['page_name'] = 'Membership Invoice Report'; + $data['selected_data'] = $this->request->getVar('date'); $this->render_page('report_mem_invoice', $data); } } public function expired_customer_report() { $model = new InvoiceModel(); - if($this->request->getmethod() == 'get') - { + if ($this->request->getmethod() == 'get') { $data['expired_customers'] = $model->getExpiredCustomers(); $data['selected_data'] = ""; - } - else - { - - $dateParts = explode(' - ', $this->request->getVar('date') ); + } else { + + $dateParts = explode(' - ', $this->request->getVar('date')); $fromDate = $dateParts[0]; $toDate = $dateParts[1]; $dateTime = \DateTime::createFromFormat('d/m/Y', $fromDate); $dateTime1 = \DateTime::createFromFormat('d/m/Y', $toDate); $model = new InvoiceModel(); - $data['expired_customers'] = $model->getExpiredCustomers( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') ); - $data['selected_data'] = $this->request->getVar('date'); + $data['expired_customers'] = $model->getExpiredCustomers($dateTime->format('Y-m-d'), $dateTime1->format('Y-m-d')); + $data['selected_data'] = $this->request->getVar('date'); $this->logger->info("Itemwise Report "); } $this->logger->info("'Membership Renewals Report'"); - $data['page_name'] = 'Membership Renewals Report'; + $data['page_name'] = 'Membership Renewals Report'; $this->render_page('report_expired_customers', $data); -} + } -public function itemwise_report() -{ - if ($this->request->getmethod() == 'get') + public function itemwise_report() { - $model = new InvoiceModel(); - $data['report_data'] = $model->itemwise_report_data(); - $this->logger->info("Itemwise Report "); - $data['page_name'] = 'Bookswise Report'; - $this->render_page('report_itemwise', $data); - } - else - { - if ($this->request->getPost('export_csv')) { - // Handle CSV export - $this->exportCsv(); - } else { - // Handle date range filter - - + if ($this->request->getmethod() == 'get') { $model = new InvoiceModel(); $data['report_data'] = $model->itemwise_report_data(); $this->logger->info("Itemwise Report "); $data['page_name'] = 'Bookswise Report'; - $this->exportCsv(); $this->render_page('report_itemwise', $data); - } - } -} + } else { + if ($this->request->getPost('export_csv')) { + // Handle CSV export + $this->exportCsv(); + } else { + // Handle date range filter -private function exportCsv() -{ - $model = new InvoiceModel(); - $reportData = $model->itemwise_report_data(); - - $csvFileName = 'itemwise_report.csv'; - // Set appropriate headers for CSV download - header('Content-Type: text/csv; charset=UTF-8'); - header('Content-Disposition: attachment; filename="' . $csvFileName . '"'); - header('Pragma: no-cache'); - header('Expires: 0'); - - // Open a PHP output stream for writing CSV data - $output = fopen('php://output', 'w'); - - // Add UTF-8 BOM to the CSV file - fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); - - // Write the CSV headers - fputcsv($output, ['Publisher Code', 'Book Name', 'Item Count', 'Total Cost']); - - // Write the CSV data - foreach ($reportData as $row) { - foreach ($row->books as $book) { - $rowData = [ - $row->publisher_code, - $book->book_name, - $book->item_count, - $book->total_cost, - ]; - - // Convert each field to UTF-8 using iconv - $rowData = array_map(function ($field) { - return iconv('UTF-8', 'UTF-8//IGNORE', $field); - }, $rowData); - - fputcsv($output, $rowData); + $model = new InvoiceModel(); + $data['report_data'] = $model->itemwise_report_data(); + $this->logger->info("Itemwise Report "); + $data['page_name'] = 'Bookswise Report'; + $this->exportCsv(); + $this->render_page('report_itemwise', $data); + } } } - // Close the PHP output stream - fclose($output); + private function exportCsv() + { + $model = new InvoiceModel(); + $reportData = $model->itemwise_report_data(); - // Terminate the script to prevent further output - exit(); -} + $csvFileName = 'itemwise_report.csv'; + + // Set appropriate headers for CSV download + header('Content-Type: text/csv; charset=UTF-8'); + header('Content-Disposition: attachment; filename="' . $csvFileName . '"'); + header('Pragma: no-cache'); + header('Expires: 0'); + + // Open a PHP output stream for writing CSV data + $output = fopen('php://output', 'w'); + + // Add UTF-8 BOM to the CSV file + fprintf($output, chr(0xEF) . chr(0xBB) . chr(0xBF)); + + // Write the CSV headers + fputcsv($output, ['Publisher Code', 'Book Name', 'Item Count', 'Total Cost']); + + // Write the CSV data + foreach ($reportData as $row) { + foreach ($row->books as $book) { + $rowData = [ + $row->publisher_code, + $book->book_name, + $book->item_count, + $book->total_cost, + ]; + + // Convert each field to UTF-8 using iconv + $rowData = array_map(function ($field) { + return iconv('UTF-8', 'UTF-8//IGNORE', $field); + }, $rowData); + + fputcsv($output, $rowData); + } + } + + // Close the PHP output stream + fclose($output); + + // Terminate the script to prevent further output + exit(); + } private function calculateTotalBookQuantity(&$reportData) -{ - // Calculate the total book quantity for each publisher - foreach ($reportData as &$row) { - $totalBookQuantity = array_sum(array_column($row->books, 'quantity')); - $row->total_book_quantity = $totalBookQuantity; + { + // Calculate the total book quantity for each publisher + foreach ($reportData as &$row) { + $totalBookQuantity = array_sum(array_column($row->books, 'quantity')); + $row->total_book_quantity = $totalBookQuantity; + } } -} public function book_publishwise_Report() - { - if($this->request->getmethod() == 'get') - { + { + if ($this->request->getmethod() == 'get') { $model = new InvoiceModel(); $data['report_data'] = $model->itemwise_report_data_with_publish_code(); $data['selected_data'] = ""; $this->logger->info("Itemwise Report "); - $data['page_name'] = 'Books Published'; + $data['page_name'] = 'Books Published'; // print_r($data);die; $this->render_page('report_book_publish', $data); - } - else - { - $dateParts = explode(' - ', $this->request->getVar('date') ); + } else { + $dateParts = explode(' - ', $this->request->getVar('date')); $fromDate = $dateParts[0]; - - $toDate = $dateParts[1]; + + $toDate = $dateParts[1]; $dateTime = \DateTime::createFromFormat('d/m/Y', $fromDate); $dateTime1 = \DateTime::createFromFormat('d/m/Y', $toDate); $model = new InvoiceModel(); - $data['report_data'] = $model->itemwise_report_data_with_publish_code( $dateTime->format('Y-m-d') , $dateTime1->format('Y-m-d') ); + $data['report_data'] = $model->itemwise_report_data_with_publish_code($dateTime->format('Y-m-d'), $dateTime1->format('Y-m-d')); $this->logger->info("Itemwise Report "); $data['page_name'] = 'Books Published'; - $data['selected_data'] = $this->request->getVar('date'); + $data['selected_data'] = $this->request->getVar('date'); $this->render_page('report_book_publish', $data); } - } - -// public function generate_invoice_pdf($id) -// { -// // Load the mPDF library -// $mpdf = new \Mpdf\Mpdf(); -// // Fetch invoice data -// $invoice = $this->find($id); + // public function generate_invoice_pdf($id) + // { + // // Load the mPDF library + // $mpdf = new \Mpdf\Mpdf(); -// if ($invoice) { -// // Fetch related invoice items -// $invoiceItems = $this->getInvoiceItems($id); + // // Fetch invoice data + // $invoice = $this->find($id); -// // Create the HTML content for the PDF -// $html = view('pdf/invoice_template', ['invoice' => $invoice, 'invoiceItems' => $invoiceItems]); + // if ($invoice) { + // // Fetch related invoice items + // $invoiceItems = $this->getInvoiceItems($id); -// // Load HTML content into mPDF -// $mpdf->WriteHTML($html); + // // Create the HTML content for the PDF + // $html = view('pdf/invoice_template', ['invoice' => $invoice, 'invoiceItems' => $invoiceItems]); -// // Set PDF filename -// $pdfFileName = 'invoice_' . $invoice->invoice_number . '.pdf'; + // // Load HTML content into mPDF + // $mpdf->WriteHTML($html); -// // Output the PDF for download -// $mpdf->Output($pdfFileName, 'D'); -// } -// } + // // Set PDF filename + // $pdfFileName = 'invoice_' . $invoice->invoice_number . '.pdf'; -// public function getInvoiceItems($invoiceId) -// { -// // Fetch invoice items related to the given invoice ID -// return $this->db->table('invoice_items')->where('invoice_id', $invoiceId)->get()->getResult(); -// } + // // Output the PDF for download + // $mpdf->Output($pdfFileName, 'D'); + // } + // } + + // public function getInvoiceItems($invoiceId) + // { + // // Fetch invoice items related to the given invoice ID + // return $this->db->table('invoice_items')->where('invoice_id', $invoiceId)->get()->getResult(); + // } // Fetch the invoice data based on $invoice_id @@ -1112,144 +1095,134 @@ private function exportCsv() // Check if the MD5 hash is valid and the invoice ID exists if ($invoice_id) { // Fetch the invoice data based on $invoice_id - + $data = $model->getInvoiceData($invoice_id); $invoiceItems = $model->getInvoiceItems($invoice_id, 'groupby'); - foreach ($invoiceItems as $index => $singleItem) { - $productImgs = $model->getProductImgs($singleItem->product); - $invoiceItems[$index]->imgs = $productImgs; + foreach ($invoiceItems as $index => $singleItem) { + $productImgs = $model->getProductImgs($singleItem->product); + $invoiceItems[$index]->imgs = $productImgs; + } + + $invoice_type = $data[0]->invoice_type; + + // Create an mPDF object + $mpdf = new Mpdf(); + $mpdf->autoLangToFont = true; + $mpdf->autoScriptToLang = true; + + // Set PDF properties + $mpdf->SetTitle('Invoice'); + $mpdf->SetAuthor($data[0]->company_name); + $mpdf->SetCreator(''); + $htmlFooter = '
'; + $mpdf->setHTMLFooter($htmlFooter); + + // Generate the PDF content (HTML) with data + $html = view('invoice_pdf_template', ['data' => $data, 'invoiceItems' => $invoiceItems, 'invoice_type' => $invoice_type, 'invoiceTerms' => $data]); + + // Load HTML into the mPDF instance + $mpdf->WriteHTML($html); + + // Output the PDF to the browser for download + $mpdf->Output("invoice_" . date('Y-m-d H-i-s') . '.pdf', 'D'); + } else { + echo "no code works"; + } + } + // private function getInvoiceIdByMd5($md5Hash) + // { + // // Assuming you have a table named 'invoices' with columns 'invoice_id' and 'md5_hash' + // $result = $this->db->table('invoices')->select('invoice_id')->where('md5_hash', $md5Hash)->get()->getRow(); + // return $result ? $result->invoice_id : null; + // } + public function saveBook() + { + // Retrieve book details from POST data + $bookName = $this->request->getPost('bookName'); + $publication_date = $this->request->getPost('publication_date'); + $publication_code = $this->request->getPost('publishers_code'); + $isbn_code = $this->request->getPost('isbn_code'); + $bookPrice = $this->request->getPost('bookPrice'); + $publisher_name = $this->request->getPost('publisher'); + + // Load the model + $model = new BooksModel(); + + // Call the model function to save the book + $bookId = $model->saveBook($bookName, $bookPrice, $isbn_code, $publication_date, $publication_code, $publisher_name); + + // Return a response (e.g., JSON response) + $response = array(); + if ($bookId) { + $response['success'] = true; + $response['message'] = 'Book saved successfully.'; + $response['book_id'] = $bookId; // Include the book ID in the response + $response['title'] = $bookName; + // $response['tax'] = $bookId; + $response['price'] = $bookPrice; + } else { + $response['success'] = false; + $response['message'] = 'Failed to save book.'; + } + + // Send JSON response + return $this->response->setJSON($response); } - $invoice_type = $data[0]->invoice_type; - // Create an mPDF object - $mpdf = new Mpdf(); - $mpdf->autoLangToFont = true; - $mpdf->autoScriptToLang = true; - // Set PDF properties - $mpdf->SetTitle('Invoice'); - $mpdf->SetAuthor($data[0]->company_name); - $mpdf->SetCreator(''); - $htmlFooter = '
-
'; - $mpdf->setHTMLFooter($htmlFooter); + // Your controller method to handle updating status and reason + public function updateInvoiceStatus() + { + // Retrieve data from the request + $invoiceId = $this->request->getPost('invoice_id'); + $voidReason = $this->request->getPost('void_reason'); - // Generate the PDF content (HTML) with data - $html = view('invoice_pdf_template', ['data' => $data, 'invoiceItems' => $invoiceItems, 'invoice_type' => $invoice_type, 'invoiceTerms' => $data]); + // Perform any validation if needed - // Load HTML into the mPDF instance - $mpdf->WriteHTML($html); + // Update the invoice status and void reason in the database + $model = new InvoiceModel(); // Assuming you have a model named InvoiceModel + $updated = $model->updateInvoiceStatus($invoiceId, $voidReason); - // Output the PDF to the browser for download - $mpdf->Output("invoice_" . date('Y-m-d H-i-s') . '.pdf', 'D'); -}else{ - echo "no code works"; -} - - -} -private function getInvoiceIdByMd5($md5Hash) -{ - - // Assuming you have a table named 'invoices' with columns 'invoice_id' and 'md5_hash' - $result = $this->db->table('invoices')->select('invoice_id')->where('md5_hash', $md5Hash)->get()->getRow(); - - return $result ? $result->invoice_id : null; -} -public function saveBook() { - // Retrieve book details from POST data - $bookName = $this->request->getPost('bookName'); - $publication_date = $this->request->getPost('publication_date'); - $publication_code = $this->request->getPost('publishers_code'); - $isbn_code = $this->request->getPost('isbn_code'); - $bookPrice = $this->request->getPost('bookPrice'); - $publisher_name = $this->request->getPost('publisher'); - - // Load the model - $model = new BooksModel(); - - // Call the model function to save the book - $bookId = $model->saveBook($bookName, $bookPrice, $isbn_code, $publication_date, $publication_code, $publisher_name); - - // Return a response (e.g., JSON response) - $response = array(); - if ($bookId) { - $response['success'] = true; - $response['message'] = 'Book saved successfully.'; - $response['book_id'] = $bookId; // Include the book ID in the response - $response['title'] = $bookName; - // $response['tax'] = $bookId; - $response['price'] = $bookPrice; - } else { - $response['success'] = false; - $response['message'] = 'Failed to save book.'; + // Prepare the response + $response = []; + if ($updated) { + $response['success'] = true; + $response['message'] = 'Invoice status updated successfully.'; + } else { + $response['success'] = false; + $response['message'] = 'Failed to update invoice status.'; + } + if ($updated) { + } + // Return the response as JSON + return $this->response->setJSON($response); } + public function updateInvoiceCancelStatus() + { + // Retrieve data from the request + $invoiceIds = $this->request->getPost('invoice_id'); + $cancelReason = $this->request->getPost('cancel_reason'); - // Send JSON response - return $this->response->setJSON($response); -} + // Perform any validation if needed + // Update the invoice status and cancel reason in the database + $model = new InvoiceModel(); // Assuming you have a model named InvoiceModel + $updated = $model->updateInvoiceCancelStatus($invoiceIds, $cancelReason); + // Prepare the response + $response = []; + if ($updated) { + $response['success'] = true; + $response['message'] = 'Invoice status updated successfully.'; + // Redirect to the invoice_list page upon successful cancellation + // return redirect()->to('invoice_list'); + } else { + $response['success'] = false; + $response['message'] = 'Failed to update invoice status.'; + } -// Your controller method to handle updating status and reason -public function updateInvoiceStatus() -{ - // Retrieve data from the request - $invoiceId = $this->request->getPost('invoice_id'); - $voidReason = $this->request->getPost('void_reason'); - - // Perform any validation if needed - - // Update the invoice status and void reason in the database - $model = new InvoiceModel(); // Assuming you have a model named InvoiceModel - $updated = $model->updateInvoiceStatus($invoiceId, $voidReason); - - // Prepare the response - $response = []; - if ($updated) { - $response['success'] = true; - $response['message'] = 'Invoice status updated successfully.'; - } else { - $response['success'] = false; - $response['message'] = 'Failed to update invoice status.'; + // Return the response as JSON + return $this->response->setJSON($response); } - if ($updated) { - - } - // Return the response as JSON - return $this->response->setJSON($response); } -public function updateInvoiceCancelStatus() -{ - // Retrieve data from the request - $invoiceIds = $this->request->getPost('invoice_id'); - $cancelReason = $this->request->getPost('cancel_reason'); - - // Perform any validation if needed - - // Update the invoice status and cancel reason in the database - $model = new InvoiceModel(); // Assuming you have a model named InvoiceModel - $updated = $model->updateInvoiceCancelStatus($invoiceIds, $cancelReason); - - // Prepare the response - $response = []; - if ($updated) { - $response['success'] = true; - $response['message'] = 'Invoice status updated successfully.'; - // Redirect to the invoice_list page upon successful cancellation - // return redirect()->to('invoice_list'); - } else { - $response['success'] = false; - $response['message'] = 'Failed to update invoice status.'; - } - - // Return the response as JSON - return $this->response->setJSON($response); -} - -} - - - - diff --git a/app/Controllers/Users.php b/app/Controllers/Users.php index b9f502d0..9e674f1d 100755 --- a/app/Controllers/Users.php +++ b/app/Controllers/Users.php @@ -49,12 +49,13 @@ class Users extends BaseController } ## To Load User Add/Update page - public function user_page($id) + public function user_page($id,$flag) { helper('session'); $session_role = get_user_role(); $session_bid = get_business_id(); $session_uid = get_logged_user_id(); + $data['dummy_flag'] = $flag; // for redirect purpose. if ($id === '0') { $this->logger->info("Users: In Add page"); $data['page_name'] = 'Add User'; @@ -247,7 +248,12 @@ class Users extends BaseController $this->logger->error("Users: Err Occur =".$e->getMessage()); session()->setFlashdata('error', 'Message: ' .$e->getMessage()); } - return redirect()->route('user_list'); + // Redirect back to the user_page function or any other appropriate page + if($this->request->getPost('dummy_flag') == 1){ + return redirect()->to(base_url("user_page/{$user_id}/1")); + }else{ + return redirect()->route('user_list'); + } } ## For delete the user details (Which means inactive the details) diff --git a/app/Views/invoice_form.php b/app/Views/invoice_form.php index c45915f7..f12320a7 100644 --- a/app/Views/invoice_form.php +++ b/app/Views/invoice_form.php @@ -1,8 +1,11 @@
@@ -15,30 +18,32 @@
- customer_id === $invoice_details['customer_id']) { - $displayvalue = $customer->first_name . ' ' . $customer->last_name; - } - } ?> - - - - - - + + + + - +
Please select customer.
- - -
+ + +
-
+
- +
@@ -108,7 +113,7 @@

Item Details


- + @@ -129,14 +134,19 @@ - + + + + - @@ -201,7 +213,7 @@
- + @@ -250,14 +262,14 @@
- > + >
- - - step="0.01"> - + + + step="0.01"> +
@@ -296,7 +308,31 @@
- + + + + + @@ -852,34 +866,34 @@ cell1.innerHTML=html; get_customer_membership_details(custid) } if (inv_number != '') { - $("#invoiceNumber").val(inv_number).prop("readonly", true); - }else{ + $("#invoiceNumber").val(inv_number).prop("readonly", true); + } else { var numbering_arr = ; // console.log(numbering_arr); var filtered_data = $.grep(numbering_arr, function(item) { - return item.id === '1'; + return item.id === '1'; }); var final_sno = generateSerialNumber(filtered_data); $("#invoiceNumber").val(final_sno).prop("readonly", true); } - + var fromDateValue = ""; if (fromDateValue != '') { - updateToDateMinDate(fromDateValue) - } - + updateToDateMinDate(fromDateValue) + } + $("#editAddressesCheckbox").on("change", function() { if ($(this).is(":checked")) { $("#storeBillingAddress").prop("readonly", false); $('#hiddenBillingAddressId').val(0); } else { $("#storeBillingAddress").prop("readonly", true); - if(global_billarr !== ""){ + if (global_billarr !== "") { $("#storeBillingAddress").val(global_billarr); - $('#hiddenBillingAddressId').val(global_billid); + $('#hiddenBillingAddressId').val(global_billid); } - - + + } }); @@ -901,21 +915,21 @@ cell1.innerHTML=html; return serial_number; } - + if (custid != '' && (ship_addrid == undefined || ship_addrid == null || ship_addrid == '0' || ship_addrid == '')) { - + $("#storeShippingAddress").prop("readonly", false); console.log('ship addrid is undefined, null, 0, or empty'); } }); - + // Billing ajax call function get_customer_billing_details(cust_id) { - - if(cust_id == '0'){ - $('#customerModal').modal('show'); - }else{ + + if (cust_id == '0') { + $('#customerModal').modal('show'); + } else { $('#editAddressesCheckbox').prop('checked', false); $("#storeBillingAddress").prop("readonly", false); $("#storeShippingAddress").prop("readonly", false); @@ -924,14 +938,14 @@ cell1.innerHTML=html; $('#cus_first_name').val(""); $('#cus_last_name').val(""); $('#cus_email').val(""); - $('.save-invoice-customer').prop('disabled', false); + $('.save-invoice-customer').prop('disabled', false); $.ajax({ type: "POST", url: "", data: { customer_id: cust_id }, - success: function(response) { + success: function(response) { cs = response['data']['customer_shipping']; cb = response['data']['customer_billing']; $('#hiddenBillingAddressId').val(''); @@ -940,17 +954,17 @@ cell1.innerHTML=html; global_billid = ""; var customer_billing_addressDetails = []; if (cb.length > 0) { - $.each(cb, function(k, v) { + $.each(cb, function(k, v) { var state = v.state_name ? v.state_name : v.state; - state = v.postal_code ? state+"-"+v.postal_code : state; - v.address_1 ? customer_billing_addressDetails.push(v.address_1 + " " + v.address_2):""; - v.city ? customer_billing_addressDetails.push(v.city):""; - state ? customer_billing_addressDetails.push(state):""; - v.country_name ? customer_billing_addressDetails.push(v.country_name) :""; + state = v.postal_code ? state + "-" + v.postal_code : state; + v.address_1 ? customer_billing_addressDetails.push(v.address_1 + " " + v.address_2) : ""; + v.city ? customer_billing_addressDetails.push(v.city) : ""; + state ? customer_billing_addressDetails.push(state) : ""; + v.country_name ? customer_billing_addressDetails.push(v.country_name) : ""; customer_billing_id = v.customer_address_id; }); } - global_billarr = customer_billing_addressDetails.join(', \n')+"."; + global_billarr = customer_billing_addressDetails.join(', \n') + "."; global_billid = customer_billing_id; $("#storeBillingAddress").val(global_billarr).prop("readonly", true); $('#hiddenBillingAddressId').val(global_billid); @@ -965,10 +979,9 @@ cell1.innerHTML=html; value: v.customer_address_id, text: v.address, })); - }); + }); $("#storeShippingAddress").val(''); - } - else{ + } else { $("#editAddressesCheckbox").prop("checked", true); $("#storeBillingAddress").prop("readonly", false); } @@ -1000,15 +1013,15 @@ cell1.innerHTML=html; if (cs.length > 0) { $.each(cs, function(k, v) { var state = v.state_name ? v.state_name : v.state; - state = v.postal_code ? state+"-"+v.postal_code : state; + state = v.postal_code ? state + "-" + v.postal_code : state; v.address_1 ? customer_shipping_addressDetails.push(v.address_1 + " " + v.address_2) : ""; v.city ? customer_shipping_addressDetails.push(v.city) : ""; - state ? customer_shipping_addressDetails.push(state) :""; - v.country_name ? customer_shipping_addressDetails.push(v.country_name):""; - customer_shipping_id = v.customer_address_id; + state ? customer_shipping_addressDetails.push(state) : ""; + v.country_name ? customer_shipping_addressDetails.push(v.country_name) : ""; + customer_shipping_id = v.customer_address_id; }); } - $("#storeShippingAddress").val(customer_shipping_addressDetails.join(', \n')+".").prop("readonly", true); + $("#storeShippingAddress").val(customer_shipping_addressDetails.join(', \n') + ".").prop("readonly", true); }, error: function() { alert("Error fetching address."); @@ -1017,59 +1030,56 @@ cell1.innerHTML=html; } // membership ajax call - function get_customer_membership_details(cust_id){ + function get_customer_membership_details(cust_id) { $.ajax({ - type: "POST", - url: "", - data: { - customer_id: cust_id - }, - success: function(response) { - cm = response['data']['customer_membership']; - cm.sort(function(a, b) { - return b.is_renew - a.is_renew; - }); - if (cm.length > 0) { - text1 = cm[0].is_renew == 1 ? " - Renewal" : ""; - text2 = cm[0].isactive == 0 ? " - Expried" : ""; - $(".subscribedetails").show(); // Change this line to use the class selector - $("#schemeName").text("Earlier Membership : "+cm[0].title + " ( From: " + cm[0].formatted_from_subscription + " To: " + cm[0].formatted_to_subscription+" )"+text1+text2); - } else { - $(".subscribedetails").show(); // Change this line to use the class selector - $("#schemeName").text("No Earlier Membership found"); - } - }, - error: function() { - alert("Error fetching address."); + type: "POST", + url: "", + data: { + customer_id: cust_id + }, + success: function(response) { + cm = response['data']['customer_membership']; + cm.sort(function(a, b) { + return b.is_renew - a.is_renew; + }); + if (cm.length > 0) { + text1 = cm[0].is_renew == 1 ? " - Renewal" : ""; + text2 = cm[0].isactive == 0 ? " - Expried" : ""; + $(".subscribedetails").show(); // Change this line to use the class selector + $("#schemeName").text("Earlier Membership : " + cm[0].title + " ( From: " + cm[0].formatted_from_subscription + " To: " + cm[0].formatted_to_subscription + " )" + text1 + text2); + } else { + $(".subscribedetails").show(); // Change this line to use the class selector + $("#schemeName").text("No Earlier Membership found"); } - }); + }, + error: function() { + alert("Error fetching address."); + } + }); } - - \ No newline at end of file diff --git a/app/Views/invoice_list.php b/app/Views/invoice_list.php index 9d7db0ee..742ec1d7 100644 --- a/app/Views/invoice_list.php +++ b/app/Views/invoice_list.php @@ -1,25 +1,30 @@ @@ -28,7 +33,7 @@
- +

@@ -75,7 +80,7 @@
- + - - - - + + + + + + + - total_amount >= $value->exact_total_amount) ? '+' : '-'; - $difference = abs($value->exact_total_amount - $value->total_amount); - ?> + + shipping_label != '') : ?> + + + + + - - - - - - status === 'Draft'): ?> - - - - - -status === 'Approved'): ?> - - - - - -
" name="quantity[]" oninput="calculateInvoice(this,)" value="" min="1" /> @@ -147,7 +157,7 @@ " name="amount[]" value="" readonly /> " name="discount_amount[]" oninput="calculateInvoice(this,)" value="" min="0" step="0.01"/> + " name="discount_amount[]" oninput="calculateInvoice(this,)" value="" min="0" step="0.01" /> @@ -172,28 +182,30 @@ + +
" class="download-pdf-button" title="Download the Invoice">  @@ -117,19 +122,19 @@
shipping_label?> :   ₹shipping_charge, 2, '.', ',') ?>
Subtotal :   ₹subtotal, 2, '.', ',') ?>
Discount :   discount ? "(-)" . number_format($value->discount, 2, '.', ',') : number_format(0, 2, '.', ',') ?>
shipping_label ?> :   ₹shipping_charge, 2, '.', ',') ?>
Rounding :   
Total :   ₹total_amount, 2, '.', ',') ?>
Balance :   ₹total_amount, 2, '.', ',') ?>
Paid :   ₹total_amount, 2, '.', ',') ?>
+ total_amount >= $value->exact_total_amount) ? '+' : '-'; + $difference = abs($value->exact_total_amount - $value->total_amount); + ?> + + Rounding :    + + + Total :   ₹total_amount, 2, '.', ',') ?> + + status === 'Draft') : ?> + + + Balance :   ₹total_amount, 2, '.', ',') ?> + + + status === 'Approved') : ?> + + Paid :   ₹total_amount, 2, '.', ',') ?> + + + +
- +
@@ -305,27 +328,30 @@ p { - reason)){ ?> -

Reason: reason; ?>

+ reason)) { ?> +
+

Reason: reason; ?>

- terms)) { ?> -
+                    
+
                         terms ?>
                     
-
- + - + + - - + + \ No newline at end of file diff --git a/app/Views/template/topbar.php b/app/Views/template/topbar.php index 06040520..fdf30fb4 100644 --- a/app/Views/template/topbar.php +++ b/app/Views/template/topbar.php @@ -70,7 +70,7 @@
- " class="dropdown-item notify-item"> + " class="dropdown-item notify-item"> My Account diff --git a/app/Views/user_form.php b/app/Views/user_form.php index 7b41ff4c..0110e180 100644 --- a/app/Views/user_form.php +++ b/app/Views/user_form.php @@ -42,7 +42,7 @@
- + +
@@ -250,6 +251,11 @@