AuditHistoryModel = new AuditHistoryModel(); $this->UserModel = new UsersModel(); $this->BusinessModel = new BusinessModel(); } ## For Invoice Listing.. public function index() { helper('session'); if (is_session_active()) { $session_role = get_user_role(); $session_bid = get_business_id(); $model = new InvoiceModel(); $where = ['business_id' => (int)get_business_id()]; $data['Donors'] = $model->getData('donor', $where); $data['page_name'] = 'Receipt Details'; $default_financial_year_condition = [ 'created_at >= CONCAT(YEAR(NOW()) - IF(MONTH(NOW()) >= 1 AND MONTH(NOW()) <= 3, 1, 0), "-01-01")', 'created_at < CONCAT(YEAR(NOW()) + IF(MONTH(NOW()) >= 1 AND MONTH(NOW()) <= 3, 1, 0), "-01-01")' ]; // $where = array_merge($where, $default_financial_year_condition); $data['receipt'] = $model->where($where)->findAll(); $data['temp_receipt_count'] = $model->where(["business_id"=>$session_bid, 'receipt_header' => 'Temporary Receipt'])->countAllResults(); foreach ($data['receipt'] as $key => $value) { $data['receipt'][$key]['created_name'] = $this->UserModel->where('user_id', $value['created_by'])->get()->getRow()->first_name; } $this->logger->info("Invoice: Listing Count ." . count($data['receipt'])); $this->render_page('invoice_list', $data); } else { return redirect()->to('login'); } } public function donations_accepted() { try { helper('session'); if (is_session_active()) { $session_role = get_user_role(); $session_bid = get_business_id(); $model = new InvoiceModel(); // $where = ['business_id' => (int)get_business_id()]; $data['list'] = $model->getData('donations_accepted',null); $data['page_name'] = 'Donations Accepted'; // print_r($data);die(); $this->render_page('donations_accepted', $data); } else { return redirect()->to('login'); } } catch (\Throwable $e) { $this->logger->error("donations_accepted: Err Occur =" . $e->getMessage()); } } public function save_donations_accepted() { try { helper('session'); // print_r($this->request->getPost());die; $model = new InvoiceModel(); $list = $model->getData('donations_accepted',null); foreach ($list as $key => $value) { if(in_array($value->id, $this->request->getPost('name'))) { $where = ['id' => $value->id ]; $data['is_active'] = 1; $upt_data = $model->updateData('donations_accepted', $data, $where); } else { $where = ['id' => $value->id]; $data['is_active'] = 0; $upt_data = $model->updateData('donations_accepted', $data, $where); } } session()->setFlashdata('success', 'Recepit Updated Successfully.'); return redirect()->route('donations_accepted'); } catch (\Throwable $e) { $this->logger->error("donations_accepted: Err Occur =" . $e->getMessage()); } } ## To Save/Update the Recepit Details public function new_receipt($id = '0') { helper('session'); $model = new InvoiceModel(); $bmodel = new BooksModel(); $where = ['business_id' => (int)get_business_id() ]; $rec_where = ['business_id' => (int)get_business_id(), 'YEAR(created_on)' => date('Y')]; $receipt = $model->getData('receipt', $rec_where); // receipt number $settingData = $this->BusinessModel->select('*')->where($where)->findAll(); $count_receipt_no = (count($receipt) > 0) ? count($receipt) + $settingData[0]['start_no'] : $settingData[0]['start_no']; // Calculate padding based on the count of digits in count_receipt_no $padding_count = max(0, $settingData[0]['left_pad'] - strlen($count_receipt_no)); $padding = str_repeat('0', $padding_count); $data['count_receipt_no'] = $settingData[0]['prefix_format'] . $padding . $count_receipt_no; // Get customer names for the dropdown, events details, and books details $data['currency'] = $this->BusinessModel->select('currency')->where($where)->findAll(); $data['currency_code'] = $this->BusinessModel->select('currency')->where($where)->first()['currency'] ?? null; $query = $this->BusinessModel->select('currency')->where($where)->first(); $data['currencies'] = unserialize($query['currency']); $data['causes'] = $bmodel->select('*')->where('business_id', (int)get_business_id())->where('isactive',1)->get()->getResult(); $data['campaign'] = $model->getData('campaign', $where); $data['invoice_number_formatting'] = $model->getData('business', $where); $data['receipt_type'] = "individual"; if ($id === '0') { $this->logger->info("Receipt: In Add Details"); $data['page_name'] = 'Add Receipt Details'; $data['receipt_details'] = []; } elseif ($id !== '0') { $this->logger->info(" Book Invoice: In Edit Details ID = " . $id); $data['page_name'] = 'Edit Receipt Details'; if(get_user_role() == 'accounts') { $data['receipt_details'] = $model->where(['receipt_id' => $id])->first(); } else { $data['receipt_details'] = $model->where(['receipt_id' => $id, 'isactive' => 1])->first(); } $data['receipt_type'] = $data['receipt_details']['receipt_type']; } $cus_where = ['business_id' => (int)get_business_id() , 'isactive' => 1, 'donor_type'=>$data['receipt_type']]; $data['typebaseddonors'] = $model->getData('donor', $cus_where); $data['alldonors'] = $model->getData('donor', ['business_id' => (int)get_business_id() , 'isactive' => 1]); // print_r($data);die; $this->render_page('invoice_form', $data); } public function donor_cash_success() { helper('session'); $model = new InvoiceModel(); // echo $this->request->getPost('id');die; $where = ['business_id' => (int)get_business_id(),'receipt_id' => $this->request->getPost('id') ]; $data['receipt_header'] = 'Receipt'; $data['isactive'] = 1; $updata = $model->getData('receipt', $where); $upt_data = $model->updateData('receipt', $data, $where); //**********AUDIT HISTORY*************/ $myArray = array(); array_push($myArray, $data); $olddata['receipt_header'] = $updata[0]->receipt_header; $olddata['isactive'] = $updata[0]->isactive; $myArray1 = array(); array_push($myArray1, $olddata); /************************** */ $currentDateTime = date('Y-m-d H:i:s'); $audit_data = [ 'module' => 'receipt', 'business_id' => (int)get_business_id(), 'is_edit' => 1, 'old_data' => json_encode($myArray1), 'current_data' => json_encode($myArray), 'updated_on' => $currentDateTime, 'updated_by' => (int)get_logged_user_id() ]; $this->AuditHistoryModel->save($audit_data); /************************************* */ if($upt_data){ session()->setFlashdata('success', 'Recepit has been accepted successfully.');echo true; } else echo false; } public function donor_cash_delete() { helper('session'); $model = new InvoiceModel(); $where = ['business_id' => (int)get_business_id(),'receipt_id' => $this->request->getPost('id') ]; $data['isactive'] = 0; $data['receipt_header'] = 'Rejected'; $data['reason'] = $this->request->getPost('reason'); $updata = $model->getData('receipt', $where); $upt_data = $model->updateData('receipt', $data, $where); //**********AUDIT HISTORY*************/ /**get old data for history */ $olddata['receipt_number'] = $updata[0]->receipt_number; $myArray = array(); array_push($myArray, $olddata); /************************** */ $currentDateTime = date('Y-m-d H:i:s'); $audit_data = [ 'module' => 'receipt', 'business_id' => (int)get_business_id(), 'is_delete' => 1, // 'old_data' => json_encode($myArray1), 'current_data' => json_encode($myArray), 'updated_on' => $currentDateTime, 'updated_by' => (int)get_logged_user_id() ]; $this->AuditHistoryModel->save($audit_data); /************************************* */ session()->setFlashdata('success', 'Recepit has been rejected successfully.'); return redirect()->route('receipt_list'); } ## To insert or update the details of the invoice public function save_invoice() { $this->logger->info("Invoice: Insert/Update Details"); try { ## Declarions helper('session'); $model = new InvoiceModel(); $receipt_date = $this->request->getVar('receipt_date'); $receipt_id = (!empty($this->request->getPost('receipt_id'))) ? $this->request->getPost('receipt_id') : ""; $donor_id = (int)$this->request->getPost('donor_id'); $data = [ 'receipt_type' => $this->request->getPost('receipt_type'), 'receipt_number' => $this->request->getPost('receipt_number'), 'donor_id' => $donor_id, 'campaign_id' => (int)$this->request->getPost('campaign_id'), 'notes'=>$this->request->getPost('notes'), 'receipt_date' => (!empty($receipt_date)) ? date("Y-m-d", strtotime($receipt_date)) : NULL, 'amount' => $this->request->getPost('amount'), 'payment_mode' => $this->request->getPost('payment_mode'), 'payment_ref_no' => $this->request->getPost('payment_ref_no'), 'causes_id' => (int)$this->request->getPost('causes_id'), 'currency' => $this->request->getPost('currency'), 'business_id' => (int)get_business_id(), 'isactive' => 1 ]; // print_r($data);die; ## Based on the invoice ID, we designated Insert or Update on Details... if (empty($receipt_id)) { $data['created_by'] = (int)get_logged_user_id(); if ($model->insert($data, 'invoices')) { $receipt_id = $model->insertID(); //**********AUDIT HISTORY*************/ $myArray = array(); array_push($myArray, $data); $currentDateTime = date('Y-m-d H:i:s'); $audit_data = [ 'module' => 'receipt', 'business_id' => (int)get_business_id(), 'is_add' => 1, 'current_data' => json_encode($myArray), 'created_by' => (int)get_logged_user_id(), 'updated_on' => $currentDateTime, 'updated_by' => (int)get_logged_user_id() ]; $this->AuditHistoryModel->save($audit_data); /************************************* */ session()->setFlashdata('success', 'Receipt has been added successfully.'); $this->logger->info("Receipt: has been added successfully. Inserted ID = " . $receipt_id); } else { session()->setFlashdata('error', 'Receipt could not be added. Please try again.'); $this->logger->error("Receipt: Err Occur could not be added. Please try again."); } } else { /**get old data for history */ $where = ['business_id' => (int)get_business_id(), 'receipt_id' => $receipt_id]; $olddata = $model->getData('receipt', $where); /************************** */ $data['updated_by'] = (int)get_logged_user_id(); if ($model->update($receipt_id, $data)) { $newdata = $model->getData('receipt', $where); //**********AUDIT HISTORY***********/ $currentDateTime = date('Y-m-d H:i:s'); $audit_data = [ 'module' => 'receipt', 'business_id' => (int)get_business_id(), 'is_edit' => 1, 'old_data' => json_encode($olddata), 'current_data' => json_encode($newdata), 'updated_on' => $currentDateTime, 'updated_by' => (int)get_logged_user_id() ]; $this->AuditHistoryModel->save($audit_data); /************************************* */ session()->setFlashdata('success', 'Receipt has been updated successfully.'); $this->logger->info("Receipt: has been updated successfully. Updated ID = " . $receipt_id); } else { session()->setFlashdata('error', 'Receipt update failed. Please try again.'); $this->logger->error("Receipt: Err Failed to update ID =" . $receipt_id); } } if($this->request->getPost('next_id')){ ## Array Formation For Events Details And Updating Events also Here.. $update_events = [ // 'id' => 1, 'start_no' => (int)$this->request->getPost('next_id'), 'business_id' => (int)get_business_id(), 'updated_by' => get_logged_user_id() ]; // print_r($update_events); $this->update_number_formatting($update_events);} // get donor whatsapp no and mail $where = ['donor_id' => (int)$this->request->getPost('donor_id') ,'business_id' => (int)get_business_id()]; $donordata = $model->getData('donor', $where); // generate recipt $html = $this->generate_invoice_pdf($receipt_id, 'mail'); // send mail $notification = new NotificationHelper(); if($donordata[0]->email != null || $donordata[0]->email != '') { $records['recipient_email'] = $donordata[0]->email; $records['subject'] = 'DONOR RECEIPT'; $records['description'] = $html; $notification->sendEmail($records); } $notificationModel = new NotificationModel(); $bmodel = new BooksModel(); $donormodel = new CustomerModel(); $template_data = $notificationModel->select('*')->where('template_id',7)->findAll(); $cause = $bmodel->select('name')->where('causes_id',(int)$this->request->getPost('causes_id'))->findAll(); $d_name = $donormodel->select('first_name')->where('donor_id',$donor_id)->findAll(); $business = $this->BusinessModel->select('*')->where('business_id',(int)get_business_id())->findAll(); $donor_name = $d_name[0]['first_name']; $currency_amount = $this->request->getPost('amount'); $cause_name = $cause[0]['name']; $receipt_number = $this->request->getPost('receipt_number'); $r_date = (!empty($receipt_date)) ? date("d-m-Y", strtotime($receipt_date)) : NULL; $business_name = $business[0]['title']; // Your original message $message = $template_data[0]['message']; // Replace placeholders with actual values $message = str_replace( array('{donor_name}', '{currency_amount}', '{cause_name}', '{receipt_name}', '{receipt_date}', '{bisuness_name}'), array($donor_name, $currency_amount, $cause_name, $receipt_number, $receipt_date, $business_name), $message ); // Output the modified message // echo $message;die; // // WHATSAPP $params = (object) Null; // $params->number = (int)'91' . $donordata[0]->mobile_no; $params->number = (int)'919677462018'; $params->type = "text"; $params->message = $message; $params->instance_id = '65C9B978325A2'; $params->access_token = '65c715e797d16'; $whatsapp_result = $notification->sendWhatsAppMessage(SEND_WAAI_URL, "POST", $params); } catch (\Exception $e) { $this->logger->error("Receipt: Err Occur =" . $e->getMessage()); session()->setFlashdata('error', 'Message: ' . $e->getMessage()); } $success = true; // Your existing code... $invoice_id = $receipt_id; // Replace with the actual invoice_id // Pass the invoice_id and success variable to the view return $this->response->setJSON(['success' => true, 'invoice_id' => $invoice_id]); // Load the view with the success variable // return view('invoice_modal', ['success' => $success]); // $this->load->view('invoice_modal', array('success' => $success)); return redirect()->route('receipt_list'); } public function audit_history() { helper('session'); $model = new InvoiceModel(); $where = ['business_id' => (int)get_business_id()]; $data = $model->getData('audit_history', $where); // echo $data[0]->current_data;die; $diff = []; foreach ($data as $audit_data) { $arr1 = json_decode($audit_data->current_data, true); $arr2 = json_decode($audit_data->old_data, true); $temp_diff = []; // Check each key-value pair in arr1 foreach ($arr1[0] as $key => $value) { $con = $key != 'created_on' && $key != 'created_by' && $key != 'updated_on' && $key != 'updated_by'; if ($audit_data->is_edit == 1 && $arr2[0][$key] !== $value) { $user = $this->UserModel->select('first_name,last_name')->where('user_id',$audit_data->updated_by)->findAll(); if($con){ $temp_diff[] = (object) [ 'id' => $audit_data->id, 'key' => $key, 'old_value' => $value, 'new_value' => $arr2[0][$key], 'module' => $audit_data->module, 'mode' => 'Update', 'updated_by' => $user[0]['first_name'].' '.$user[0]['last_name'], 'updated_on' => $audit_data->updated_on ]; } } else if($con && $audit_data->is_add == 1){ // echo $key;die; $user = $this->UserModel->select('first_name,last_name')->where('user_id',$audit_data->created_by)->findAll(); $temp_diff[] = (object) [ 'id' => $audit_data->id, 'key' => '-', 'old_value' => '-', 'new_value' => 'New Receipt No "'.$arr1[0]['receipt_number'].'" Created', 'module' => $audit_data->module, 'mode' => 'Create', 'updated_by' => $user[0]['first_name'].' '.$user[0]['last_name'], 'updated_on' => $audit_data->created_on ]; break; } else if($con && $audit_data->is_delete == 1){ // echo $key;die; $user = $this->UserModel->select('first_name,last_name')->where('user_id',$audit_data->updated_by)->findAll(); $temp_diff[] = (object) [ 'id' => $audit_data->id, 'key' => '-', 'old_value' => '-', 'new_value' => 'Receipt No "'.$arr1[0]['receipt_number'].'" Deleted', 'module' => $audit_data->module, 'mode' => 'Delete', 'updated_by' => $user[0]['first_name'].' '.$user[0]['last_name'], 'updated_on' => $audit_data->created_on ]; break; } } // Add temp_diff to $diff array if it's not empty if (!empty($temp_diff)) { $diff[] = $temp_diff; } } // print_r($diff); $response['page_name'] = 'History'; $response['data'] = $diff; $this->render_page('audit_history', $response); } ## For Updating Events Details .. public function update_number_formatting($update_events) { // `id``event_name``business_id``updated_by``updated_on``next_id` $model = new InvoiceModel(); $model->setTable('business'); $where = ['isactive' => 1, 'business_id' => (int)$update_events['business_id'], 'start_no' => $update_events['start_no']]; $details = $model->where($where)->findAll(); if (empty($details)) { $update_where = ['business_id' => (int)$update_events['business_id']]; $update_data = ['start_no' => $update_events['start_no'], 'updated_by' => $update_events['updated_by']]; $model->updateData('business', $update_data, $update_where); } } public function generate_invoice_pdf($id, $dest = null) { try { // Fetch the receipt data based on $receipt_id $model = new InvoiceModel(); $where = ['business_id' => (int)get_business_id()]; $currency_data = $model->setTable('business')->select('currency')->where($where)->findAll(); $terms_data = $this->BusinessModel->select('terms,signature,80G as eightyG ,12AA as twelveAA,80G_vaildupto as eightyGVaildUpto,12AA_vaildupto as twelveAAVaildUpto')->where($where)->findAll(); $data = $model->getInvoiceData($id); // Check if data is empty if (!$data || !$currency_data) { throw new \Exception('Data not found or empty'); } $options = new Options(); $options->set('defaultFont', 'DejaVu Sans'); $options->set('isHtml5ParserEnabled', true); $options->set('isFontSubsettingEnabled', true); $options->set('isPhpEnabled', true); $options->set('isRemoteEnabled', true); $options->set('font_subsetting', true); $options->set('tempDir', sys_get_temp_dir()); //$options->set('chroot', base_url()."public/uploads"); $options->set('chroot', FCPATH . 'public/uploads'); $dompdf = new Dompdf($options); define("DOMPDF_UNICODE_ENABLED", true); $user = $this->UserModel->select('first_name, last_name')->where('user_id',$data[0]->created_by)->findAll(); clearstatcache(); $logoPath = FCPATH . "public/uploads/" . $data[0]->business_logo; $baseurl = $data[0]->business_logo && file_exists($logoPath) ? base_url("public/uploads/" . $data[0]->business_logo) : base_url("public/uploads/default.png"); $digits = strlen((string)$data[0]->amount); $amount_in_words = $digits <= 9 ? $this->convertNumberToWords($data[0]->amount) : $data[0]->amount; $html = view('invoice_pdf_template', [ 'data' => $data[0], 'currency' => $data[0]->currency, 'currency_in_words' => $amount_in_words , 'baseurl' => $baseurl, 'signature' => $data[0]->signature, 'staff_name' => $user[0]['first_name'] . ' ' .$user[0]['last_name'], 'Notes' => $terms_data[0]['terms'], 'eightyG' => $terms_data[0]['eightyG'], 'eightyGVaildUpto' => $terms_data[0]['eightyGVaildUpto'], 'twelveAA' => $terms_data[0]['twelveAA'], 'twelveAAVaildUpto' => $terms_data[0]['twelveAAVaildUpto'], ]); //echo $html;die; $dompdf->loadHtml($html); // $dompdf->setPaper('letter', 'landscape'); $dompdf->setPaper('A5', 'landscape'); $dompdf->render(); if($dest == 'mail') { // Generate filename based on current date and time // $filename = date('dmYHis') . '.pdf'; // // Save PDF file to a directory // $outputFilePath = base_url() . 'pdf/' . $filename; // Assuming WRITEPATH is defined // file_put_contents($outputFilePath, $dompdf->output()); // // Provide download link with the generated filename // $downloadLink = base_url() . 'pdf/' . $filename; // echo $downloadLink;die; return $html; } $original_name = isset($data[0]->receipt_number) && !empty($data[0]->receipt_number) ? $data[0]->receipt_number : 'Receipt'; $sanitized_name = preg_replace("/[^A-Za-z0-9_\-\.]/", "_", $original_name); $pdf_extension_name = $sanitized_name . '.pdf'; $dompdf->stream($pdf_extension_name, ['Attachment' => 1]); } catch (\Exception $e) { // Handle the exception // For example, log the error, display a user-friendly message, or return an error response echo 'Error: ' . $e->getMessage(); log_message('error', sprintf( "Exception caught: [message: %s] [code: %d] [file: %s] [line: %d]", $e->getMessage(), $e->getCode(),$e->getFile(),$e->getLine() )); log_message('error', $e->getTraceAsString()); } } public function convertNumberToWords($number) { $words = array( 0 => 'Zero', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine', 10 => 'Ten', 11 => 'Eleven', 12 => 'Twelve', 13 => 'Thirteen', 14 => 'Fourteen', 15 => 'Fifteen', 16 => 'Sixteen', 17 => 'Seventeen', 18 => 'Eighteen', 19 => 'Nineteen', 20 => 'Twenty', 30 => 'Thirty', 40 => 'Forty', 50 => 'Fifty', 60 => 'Sixty', 70 => 'Seventy', 80 => 'Eighty', 90 => 'Ninety' ); // Special case for zero if ($number == 0) { return $words[0]; } $num = (int)$number; $result = ''; // Handle numbers greater than 10 million (crores) if ($num >= 10000000) { $crores = floor($num / 10000000); $result .= $this->convertNumberToWords($crores) . ' Crore '; $num %= 10000000; } // Handle numbers between 1 million and 9 million (lakhs) if ($num >= 100000) { $lakhs = floor($num / 100000); $result .= $this->convertNumberToWords($lakhs) . ' Lakh '; $num %= 100000; } // Handle numbers between 1000 and 99999 if ($num >= 1000) { $thousands = floor($num / 1000); $result .= $this->convertNumberToWords($thousands) . ' Thousand '; $num %= 1000; } // Handle numbers between 100 and 999 if ($num >= 100) { $hundreds = floor($num / 100); $result .= $words[$hundreds] . ' Hundred '; $num %= 100; } // Handle numbers between 20 and 99 if ($num >= 20) { $tens = floor($num / 10) * 10; $result .= $words[$tens] . ' '; $num %= 10; } // Handle numbers between 1 and 19 if ($num > 0) { $result .= $words[$num]; } return $result; } ## For Ajax Call To Retrive Donor Details Based On Donor type... public function get_donor_details() { helper('session'); $model = new InvoiceModel(); $value = $this->request->getPost('donor_type'); //For Donor Name And Donor Mobile Number Dropdown.. $where = ['business_id' => (int)get_business_id() , 'donor_type'=>$value, 'isactive' => 1]; $data['donor_details'] = $model->getData('donor', $where); return $this->response->setJSON(['data' => $data]); } public function export_receipt(){ helper('session'); $session_bid = (int)get_business_id(); $model = new InvoiceModel(); $where = ['business_id' => $session_bid]; $receipt = $model->where($where)->findAll(); $alldonors = $model->getData('donor', ['business_id' => $session_bid , 'isactive' => 1]); $export = []; if(!empty($receipt)){ foreach ($receipt as $key => $value) { $export[$key]['receipt_number'] = $receipt[$key]['receipt_number'] ; $export[$key]['receipt_date'] = (isset($receipt[$key]['receipt_date']) && !empty($receipt[$key]['receipt_date']) && strtotime($receipt[$key]['receipt_date']) !== false) ? date("d-m-Y", strtotime($receipt[$key]['receipt_date'])) : '-'; $export[$key]['receipt_type'] = $receipt[$key]['receipt_type']; $export[$key]['donor'] = ''; foreach ($alldonors as $DonorData) { if ($receipt[$key]['donor_id'] === $DonorData->donor_id) { $suffix = ""; if ($receipt[$key]['receipt_type'] == "organization" && !empty($DonorData->org_name)) { $suffix = !empty($DonorData->org_name) ? " (" . $DonorData->org_name . ")" : " (-)"; } $export[$key]['donor'] = $DonorData->first_name . ' ' . $DonorData->last_name . $suffix; break; } } $currencySymbol = ''; switch (strtoupper($receipt[$key]['currency'])) { case 'RS': case 'INR': $currencySymbol = '₹'; break; case 'USD': $currencySymbol = '$'; break; case 'EUR': $currencySymbol = '€'; break; default: $currencySymbol = ''; break; } $export[$key]['amount'] = $currencySymbol . ' ' . $receipt[$key]['amount']; $paymentMode = ''; switch (strtoupper($receipt[$key]['payment_mode'])) { case 'DEBIT': $paymentMode = 'Debit Card'; break; case 'CREDIT': $paymentMode = 'Credit Card'; break; case 'CASH': $paymentMode = 'Cash'; break; case 'UPI': $paymentMode = 'UPI'; break; default: $paymentMode = $receipt[$key]['payment_mode']; break; } $status = ''; switch (strtoupper($receipt[$key]['receipt_header'])) { case 'TEMPORARY RECEIPT ': $status = 'Draft'; break; case 'RECEIPT': $status = 'Completed'; break; case 'REJECTED': $status = 'Rejected'; break; default: $status = $receipt[$key]['receipt_header']; break; } $export[$key]['status'] = $status; $export[$key]['payment_mode'] = $paymentMode; $export[$key]['payment_ref_no'] = $receipt[$key]['payment_ref_no']; $export[$key]['notes'] = $receipt[$key]['notes'] == null ? '-' : $receipt[$key]['notes']; $export[$key]['reason'] = ($receipt[$key]['reason'] == null) ? '-' :$receipt[$key]['reason']; $export[$key]['created_by'] = $this->UserModel->where('user_id', $receipt[$key]['created_by'])->get()->getRow()->first_name;// 2 $export[$key]['updated_by'] = (isset($receipt[$key]['updated_by']) && !empty($receipt[$key]['updated_by']) && $receipt[$key]['updated_by'] !== null) ? $this->UserModel->where('user_id', $receipt[$key]['updated_by'])->get()->getRow()->first_name : '-';// 2 $export[$key]['created_on'] = (isset($receipt[$key]['created_on']) && !empty($receipt[$key]['created_on']) && strtotime($receipt[$key]['created_on']) !== false) ? date("d-m-Y", strtotime($receipt[$key]['created_on'])) : '-'; $export[$key]['updated_on'] = (isset($receipt[$key]['updated_on']) && !empty($receipt[$key]['updated_on']) && strtotime($receipt[$key]['updated_on']) !== false) ? date("d-m-Y", strtotime($receipt[$key]['updated_on'])) : '-'; $export[$key]['isactive'] = (int)$receipt[$key]['isactive'] == 1 ? 'Active' : 'Inactive'; } } $this->fetch_receipt($export); } public function fetch_receipt($export){ $spreadsheet = new Spreadsheet(); // instantiate Spreadsheet $sheet = $spreadsheet->getActiveSheet(); $sheet->mergeCells('B3:R3'); $sheet->getStyle('B3')->getAlignment()->setHorizontal('center'); $sheet->setTitle('Receipt details'); $headers = [ 'B3' => 'Receipt Details', 'A5' => 'Receipt Number', 'B5' => 'Receipt Date', 'C5' => 'Receipt Type', 'D5' => 'Contributor Name', 'E5' => 'Amount', 'F5' => 'Status', 'G5' => 'Payment Mode', 'H5' => 'Payment Ref no', 'I5' => 'Notes', 'J5' => 'Reason', 'K5' => 'CreatedBy', 'L5' => 'UpdatedBy', 'M5' => 'CreatedAt', 'N5' => 'UpdatedAt', 'O5' => 'IsActive' ]; foreach ($headers as $cell => $value) { $sheet->setCellValue($cell, $value); $sheet->getStyle($cell)->getFont()->setSize($cell == 'B3' ? 14 : 12); $sheet->getStyle($cell)->getFont()->setBold(true); } if($export){ $row = 6; // Start from row 6 foreach ($export as $d) { $col = 'A'; // Start from column A foreach ($d as $value) { if (is_numeric($value)) { $sheet->setCellValueExplicit($col . $row, $value, DataType::TYPE_STRING); $sheet->getStyle($col . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER); } else { $sheet->setCellValue($col . $row, $value); } $sheet->setCellValue($col . $row, $value); $col++; } $row++; } } // Clear the output buffer to prevent any other output ob_clean(); $writer = new Xlsx($spreadsheet); $filename = 'exportReceipt.xlsx'; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="'. $filename .'"'); header('Cache-Control: max-age=0'); header('Expires: 0'); header('Pragma: public'); $writer->save('php://output'); exit; } public function import_receipt() { $ip_address = $_SERVER['REMOTE_ADDR']; $InvoiceModel = new InvoiceModel(); helper('session'); $session_uid = get_logged_user_id(); $session_bid = get_business_id(); $json = []; // Arr - Json For Message FrontEnd $list = []; // Arr - Store on DB $path = ROOTPATH . 'public/import/receipt/'; $fileNewName = ""; $file = $this->request->getFile('file'); if (!is_dir($path)) { mkdir($path, 0777, true); } $fileName = $file->getName(); if ($fileName !== "") { if ($file->isValid() && !$file->hasMoved()) { $newName = $file->getRandomName(); $file->move($path, $newName); $fileNewName = $newName; } } if (!$fileNewName) { $json = ['error_message' => "Failed to upload file"]; return $this->response->setJSON($json); } $arr_file = explode('.', $fileName); $extension = $arr_file[1]; if ('csv' == $extension) { $reader = new ReaderCsv(); } else if ('xlsx' == $extension) { $reader = new ReaderXlsx(); } else { $json = ['error_message' => "Unsupported file type"]; return $this->response->setJSON($json); } if (!$reader) { $json = ['error_message' => "Failed to initialize reader"]; return $this->response->setJSON($json); } $spreadsheet = $reader->load($path.$fileNewName); $sheet_data = $spreadsheet->getActiveSheet()->toArray(); if(!empty($sheet_data)){ foreach ($sheet_data as $key => $val) { if ($key != 0) { // key zero - header $list[] = [ 'business_id' => $session_bid, 'first_name' => $val[0], 'donor_type' => $val[1], 'org_name' => $val[2] ? $val[2] : null , 'org_reg_details' => $val[3] ? $val[3] : null, 'mobile_no' => $val[4] ? $val[4] : null, 'email' => $val[5], 'pan_no' => $val[6], 'adhar_no' => $val[7], 'passport_no' => $val[8] ? $val[8] : null , 'address' => $val[9], 'country' => $val[10], 'state' => $val[11], 'city' => $val[12], 'postal_code' => $val[13], 'created_by' => $session_uid, 'XL_file_name' => $fileNewName, 'ip_address' => $ip_address ]; } } }else{ $json = ['error_message' => "There is no record to import"]; return $this->response->setJSON($json); } if (count($list) > 0) { $result = $InvoiceModel->bulkInsert($list); ($result) ? ['success_message' => "All Entries are imported successfully."] : ['error_message' => "Something went wrong. Please try again."]; } else { $json = ['error_message' => "No new record is found."]; } return $this->response->setJSON($json); } }