the_mechanic/app/Controllers/Invoice.php
venba-Inspriron-3558 78ba1fc582 CHANGE_Client Invoice
2025-11-13 15:28:52 +05:30

547 lines
23 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use App\Models\ProductModel;
use App\Models\ClientModel;
use App\Models\BikemodelsModel;
use App\Models\BikemakeModel;
use App\Models\VehicleModel;
use App\Models\BusinessModel;
use App\Models\BranchModel;
use App\Models\AdditionalProductNameModal;
use App\Models\VendorModel;
use App\Models\ManufacturerModel;
use App\Models\ProductCategoryModel;
use App\Models\ComplaintModel;
use App\Models\InvoiceModel;
use App\Models\InvoiceChildModel;
use Mpdf\Mpdf;
use CodeIgniter\API\ResponseTrait;
use App\Helpers\InvNoHelper;
use App\Helpers\ClientDetailsUpdate;
use Config\Services;
class Invoice extends BaseController
{
public $session;
use ResponseTrait;
protected $BikemodelsModel;
protected $BikemakeModel;
protected $additionalProductNameModal;
protected $ProductModel;
protected $ClientModel;
protected $VehicleModel;
protected $BranchModel;
protected $VendorModel;
protected $ManufacturerModel;
protected $ProductCategoryModel;
protected $ComplaintModel;
public function __construct()
{
$this->session = session();
$this->BikemodelsModel = new BikemodelsModel();
$this->BikemakeModel = new BikemakeModel();
$this->additionalProductNameModal = new AdditionalProductNameModal();
$this->ProductModel = new ProductModel();
$this->ClientModel = new ClientModel();
$this->VehicleModel = new VehicleModel();
$this->BranchModel = new BranchModel();
}
//for List.
public function invoices_order_index()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$InvoiceModel = new InvoiceModel();
$data['invoices'] = $InvoiceModel->getInvoicesWithProducts($this->session->get('logged_user_branch_id'));
return view('invoice_list',$data);
}
// Add and Edit data auto fetch.
public function new_invoice($invoice_id)
{
if (!$this->session->has('logged_user')) {
return redirect()->to(base_url());
}
$InvoiceModel = new InvoiceModel();
$ManufacturerModel = new ManufacturerModel();
$ProductCategoryModel = new ProductCategoryModel();
$ComplaintModel = new ComplaintModel();
$InvoiceChildModel = new InvoiceChildModel();
$data = [
'invoice_id' => $invoice_id,
'invoice' => [],
'invoice_child' => [],
'makeData' => $this->BikemakeModel->findAll(),
'capacity' => $ComplaintModel->getCubicCapacityName(),
'productcategory' => $ProductCategoryModel->orderBy('product_category_id')->findAll(),
'manufacturers' => $ManufacturerModel
->where('business_id', $this->session->get('logged_user_business_id'))
->orderBy('manufacturer_name')
->findAll(),
'client' => $this->ClientModel->where('isactive', 1)
->where('branch_id', $this->session->get('logged_user_branch_id'))
->findAll(),
'vehicle' => $this->VehicleModel->where('isactive', 1)
->where('branch_id', $this->session->get('logged_user_branch_id'))
->findAll(),
'product' => $this->ProductModel->where('products.isactive', 1)
->where('products.branch_id', $this->session->get('logged_user_branch_id'))
->findAll(),
];
if ($invoice_id === '0') {
$data['page_name'] = "Create Invoice";
$data['vehicle'] = $this->VehicleModel->getCustomerandVehicle($this->session->get('logged_user_branch_id'));
} else {
$data['page_name'] = "Edit Invoice";
$data['invoice'] = $InvoiceModel->where('invoice_id', $invoice_id)->get()->getRowArray();
$data['invoice_child'] = $InvoiceChildModel->where('invoice_id', $invoice_id)->findAll();
}
return view('invoice_form', $data);
}
// Insert and Update Invoice Details.
public function add_invoices()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$InvoiceModel = new InvoiceModel();
$InvoiceChildModel = new InvoiceChildModel();
$status = $this->request->getPost('status') != '' ? $this->request->getPost('status') : 'Draft';
$data = [
'type' => $this->request->getPost('type'),
'client_id' => $this->request->getPost('client_id'),
'client_name' => $this->request->getPost('client_name'),
'vehicle_id'=>$this->request->getPost('vehicle_id'),
'vehicle_reg_no'=>$this->request->getPost('vehicle_reg_no'),
'billing_address' => $this->request->getPost('billing_address'),
'billing_city' => $this->request->getPost('city'),
'mobile_no' => $this->request->getPost('mobile_no'),
'email' => $this->request->getPost('email'),
'billing_country' => $this->request->getPost('country'),
'billing_state' => $this->request->getPost('state'),
'billing_postal_code' => $this->request->getPost('postalcode'),
'terms_condition' => $this->request->getPost('terms_condition'),
'subtotal' => $this->request->getPost('sub_total'),
'tax' => $this->request->getPost('invoice_tax'),
'total'=> $this->request->getPost('grand_total'),
'status'=> $status,
'isactive' => 1,
'branch_id'=> $this->session->get('logged_user_branch_id'),
'paid_advance' => $this->request->getPost('paid_advance'),
'discount' => $this->request->getPost('discount'),
];
// Based on invoice_id Insert or update.
$invoice_id = $this->request->getPost('invoice_id');
if (!empty($invoice_id)) {
if ($status === "Approved") {
$data['mode_of_payment'] = $this->request->getPost('mode_of_payment');
}
$InvoiceModel->update($invoice_id, $data);
} else {
$data['invoice_date'] = date('Y-m-d');
$InvoiceModel->insert($data);
$invoice_id = $InvoiceModel->getInsertID();
// $invoice_number ='INV'.'-'.date('md').str_pad($invoice_id, 5, '0', STR_PAD_LEFT);
$invoice_number = date('Y') . '/' . date('md') . str_pad($invoice_id, 5, '0', STR_PAD_LEFT);
$InvoiceModel->update($invoice_id, ['invoice_number' => $invoice_number]);
}
// Prepare data for sales order product
$product_ids = $this->request->getPost('item_details');
$quantities = $this->request->getPost('quantity');
$discounts = $this->request->getPost('discount_amount');
$discount_types = $this->request->getPost('discount_type');
$amounts = $this->request->getPost('amount');
$itemtax=$this->request->getPost('item-tax');
$unitprice=$this->request->getPost('unit-price');
$invoice_child_id = $this->request->getPost('invoice_child_id');
// $labour_cost = $this->request->getPost('labour_cost');
foreach ($product_ids as $key => $product_id)
{
$qty = isset($quantities[$key]) ? $quantities[$key] : 0;
if ($status == 'Approved') {
$this->subractProductQuantity( $product_id, $qty);
}elseif ($status == 'Cancelled'){
// $this->addBackProductQuantity( $product_id, $qty);
}
$discount = isset($discounts[$key]) ? $discounts[$key] : 0;
$discount_type = isset($discount_types[$key]) ? $discount_types[$key] : '';
$tax=isset($itemtax[$key]) ? $itemtax[$key] : 0;
$rate=isset($unitprice[$key]) ? $unitprice[$key] : 0;
$amount = isset($amounts[$key]) ? $amounts[$key] : 0;
// $new_qty = $this->calculateUpdatedQuantity( $product_id, $qty);
// print_r($discount_type);die;
$invoice_child_data = [
'invoice_id' => $invoice_id,
'product_id' => $product_id,
'qty' => $qty,
'discount' => $discount,
'discount_type' => $discount_type,
'net_price'=>$rate,
'tax'=>$tax,
'amount' => $amount,
// 'labour_cost' => $labour_cost,
'isactive'=>1,
];
// print_r($invoice_child_data);die;
if (!empty($invoice_child_id[$key])) {
$InvoiceChildModel->update($invoice_child_id[$key], $invoice_child_data);
} else {
$InvoiceChildModel->insert($invoice_child_data);
}
}
return redirect()->to('invoices');
}
private function addBackProductQuantity($product_id, $sold_qty)
{
// Fetch current product quantity
$product = $this->ProductModel->find($product_id);
$data['qty_stock'] = $product['qty_stock'] + $sold_qty;
if($product['per'] == 'barrel')
{
$data['barrel'] = $data['qty_stock'] / $product['ltr_per_barrel'];
}
else if($product['per'] == 'box')
{
$data['box'] = $data['qty_stock'] / $product['qty_per_box'];
}
// Update quantity in Product table
$this->ProductModel->update($product_id, $data );
}
private function subractProductQuantity( $product_id, $sold_qty)
{
// Fetch current product quantity
$product = $this->ProductModel->find($product_id);
$data['qty_stock'] = $product['qty_stock'] - $sold_qty;
if($product['per'] == 'barrel')
{
$data['barrel'] = $data['qty_stock'] / $product['ltr_per_barrel'];
}
else if($product['per'] == 'box')
{
$data['box'] = $data['qty_stock'] / $product['qty_per_box'];
}
// Update quantity in Product table
$this->ProductModel->update($product_id, $data );
}
public function delete_invoice_child()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$InvoiceChildModel = new InvoiceChildModel();
$invoice_child_id = $this->request->getPost('invoice_child_id');
if (!empty($invoice_child_id)) {
$data['isactive'] = 0;
if ($InvoiceChildModel->update($invoice_child_id, $data)) {
// Return success response
return $this->response->setJSON(['success' => true]);
}
}
// Return error response if deletion fails
return $this->response->setJSON(['success' => false]);
}
public function delete_invoice($invoice_id)
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$InvoiceModel = new InvoiceModel();
$InvoiceChildModel = new InvoiceChildModel();
$where = ['invoice_id' => $invoice_id, 'isactive' => 1]; // Assuming 'isactive' is a column in your database
$existing = $InvoiceModel->where($where)->first();
$existingChild = $InvoiceChildModel->where($where)->first();
if ($existing) {
$data['isactive'] = 0;
if($existingChild){ $InvoiceChildModel->update($invoice_id, $data); }
if($InvoiceModel->update($invoice_id, $data)) {
session()->setFlashdata('success', 'Deleted successfully.');
$this->logger->info("Invoice: has been Inactivated successfully. Inactivated ID = ".$invoice_id);
}
}
return redirect()->to('invoices');
}
public function download_invoice($enc_id)
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
// Fetch the invoice data based on $invoice_id
$invoice_id = base64_decode($enc_id);
$InvoiceModel = new InvoiceModel();
$InvoiceChildModel = new InvoiceChildModel();
$saleOrderCount = count($InvoiceModel->where('status','Approved')->findAll());
$data['invoice'] = $InvoiceModel->getInvoicesPdf($invoice_id);
$data['branch'] = $this->BranchModel->where('branch_id', $data['invoice'][0]->branch_id)->first();
$data['vehicle'] = $this->VehicleModel->select('vehicle.reg_no,vehicle.colour,vehicle.email,vehicle.mobile_no,vehicle.year_of_manufacturing, make.make as make_name, model.model_name')
->join('model', 'model.model_id = vehicle.model', 'left')
->join('make', 'make.make_id = vehicle.make', 'left')
->where('vehicle.vehicle_id', $data['invoice'][0]->vehicle_id)
->first();
$data['invoice_child'] = $InvoiceModel->getInvoiceProductsForPdf($invoice_id);
$mpdf = new Mpdf([
'mode' => '',
'format' => 'A4',
'default_font_size' => 0,
'default_font' => '',
// 'margin_right' => 1,
'margin_top' => 6,
'margin_bottom' => 6,
'margin_header' => 6,
'margin_footer' =>-30,
'orientation' => 'P',
]);
$mpdf->autoLangToFont = true; $mpdf->autoScriptToLang = true;
// Set PDF properties
$mpdf->SetTitle('Invoice');
$mpdf->SetAuthor($data['invoice'][0]->branch_name);
$mpdf->SetCreator('');
// Generate the PDF content (HTML)
if ($data['invoice'][0]->status === 'Draft') {
$mpdf->SetWatermarkText('Draft');
$mpdf->showWatermarkText = true;
}
if ($data['invoice'][0]->status === 'Cancelled') {
$mpdf->SetWatermarkText('Cancelled');
$mpdf->showWatermarkText = true;
}
// Generate the PDF content (HTML) with data
$html = view('invoice_pdf_layout', $data);
$mpdf->WriteHTML($html);
date_default_timezone_set('Asia/Kolkata');
$mpdf->Output($data['invoice'][0]->invoice_number .'_' . date('Y-m-d H-i-s') . '.pdf', 'D');
}
public function preview_invoice($inv_id)
{
$InvoiceModel = new InvoiceModel();
$InvoiceChildModel = new InvoiceChildModel();
// Fetch the invoice data based on $invoice_id
$saleOrderCount = count($InvoiceModel->where('status','Approved')->findAll());
$data['invoice'] = $InvoiceModel->getInvoicesPdf($inv_id);
$data['branch'] = $this->BranchModel->where('branch_id', $data['invoice'][0]->branch_id)->first();
$data['vehicle'] = $this->VehicleModel->select('vehicle.reg_no,vehicle.colour,vehicle.email,vehicle.mobile_no,vehicle.year_of_manufacturing, make.make as make_name, model.model_name')
->join('model', 'model.model_id = vehicle.model', 'left')
->join('make', 'make.make_id = vehicle.make', 'left')
->where('vehicle.vehicle_id', $data['invoice'][0]->vehicle_id)
->first();
$data['invoice_child'] = $InvoiceModel->getInvoiceProductsForPdf($inv_id);
$html = view('invoice_pdf_layout', $data);
return $this->respond(['status' => 'success','code' => 200,'data' => $html],200);
}
public function save_vehicle(){
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
if($this->request->getPost('formType') == 'create')
{
$client['client_name'] = $this->request->getPost('createclientName');
$client['mobile_no'] = $this->request->getPost('createclientMobile');
$client['client_type'] = $this->request->getPost('createclientType');
$client['branch_id'] = $this->session->get('logged_user_branch_id');
$client['isactive'] = 1;
$client['created_by'] = (int)$this->session->get('logged_user');
$existingClient1 = $this->ClientModel->where('client_name', $client['client_name'])->first();
if ($existingClient1) {
return $this->response->setJSON([
'success' => true, 'code' => 404,'field'=>'create-clientName',
'message' => 'The client name is already registered. Please use a different Name.'
]);
}
$existingClient2 = $this->ClientModel->where('mobile_no', $client['mobile_no'])->first();
if ($existingClient2) {
return $this->response->setJSON([
'success' => true,'code' => 404,'field'=>'create-clientMobile',
'message' => 'The mobile number is already registered. Please use a different number.'
]);
}
$client_id = $this->ClientModel->insert($client);
if($client_id){
$data = [
'client_id' => $client_id,
'mobile_no' => $this->request->getPost('createclientMobile'),
'reg_no' => $this->request->getPost('reg_no'),
'model' => $this->request->getPost('model'),
'make' => $this->request->getPost('make'),
'branch_id'=> $this->session->get('logged_user_branch_id'),
'city'=>'Chennai',
'state'=>'Tamil Nadu',
'isactive' => 1,
'created_by' => (int)$this->session->get('logged_user')
];
}
}else{
$data = [
'client_id' => $this->request->getPost('client_id'),
'mobile_no' => $this->request->getPost('mobile_no'),
'reg_no' => $this->request->getPost('reg_no'),
'model' => $this->request->getPost('model'),
'make' => $this->request->getPost('make'),
'branch_id'=> $this->session->get('logged_user_branch_id'),
'city'=>'Chennai',
'state'=>'Tamil Nadu',
'isactive' => 1,
'created_by' => (int)$this->session->get('logged_user')
];
}
// Attempt to insert the client data
$id = $this->VehicleModel->insert($data);
if ($id) {
$vehicleData = $this->VehicleModel->where('vehicle_id',$id)->first();
// If insertion succeeds, return success response
return $this->response->setJSON(['success' => true,'code' => 200, 'message' => 'Client saved successfully.','vehicleData'=>$vehicleData, 'vehicle_id' => $id]);
} else {
// If insertion fails, return error response
return $this->response->setJSON(['success' => false, 'code' => 404,'message' => 'Failed to save client.']);
}
}
public function get_vehicle_products(){
}
public function get_invoice_product()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
// Retrieve make_id and model_id from the request
$makeId = $this->request->getPost('make_id');
$modelId = $this->request->getPost('model_id');
$modelName = $this->BikemodelsModel->where('model_id',$modelId)->get()->getRow()->model_name;
$makeName = $this->BikemakeModel->where('make_id',$makeId)->get()->getRow()->make;
$product = $this->ProductModel->select('products.*')
->where('products.isactive', 1)
->findAll();
if($product){
// Send JSON response
return $this->response->setJSON(['product'=>$product , 'modelName'=>$modelName ,'makeName'=>$makeName] );
} else {
// If product is not found, return an empty response or appropriate message
return $this->response->setJSON(['product'=>[] , 'modelName'=>$modelName ,'makeName'=>$makeName]);
}
}
public function getProducts_old()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
// Retrieve make_id and model_id from the request
$makeId = $this->request->getPost('make_id');
$modelId = $this->request->getPost('model_id');
// Encode the modelId before searching
$encodedMakeId = json_encode([$makeId]);
$encodedModelId = json_encode([$modelId]);
// Query the database to find the product based on make_id and model_id
$makeproduct = $this->additionalProductNameModal->select('products.*, manufacturer.manufacturer_name, product_names.product_names_id, product_names.additional_product_name')
->join('products', 'products.product_id = product_names.product_id')
->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id')
->where('JSON_CONTAINS(make_id, \'' . $encodedMakeId . '\')', null, false)
->where('JSON_CONTAINS(models_id, \'' . $encodedModelId . '\')', null, false)
->where('qty_stock >',0)
->where('products.isactive', 1)
->findAll();
$encodedMakeId = json_encode(['0']);
$encodedModelId = json_encode(['0']);
$common_product = $this->additionalProductNameModal->select('products.*, manufacturer.manufacturer_name, product_names.product_names_id, product_names.additional_product_name')
->join('products', 'products.product_id = product_names.product_id')
->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id')
->where('JSON_CONTAINS(make_id, \'' . $encodedMakeId . '\')', null, false)
->where('JSON_CONTAINS(models_id, \'' . $encodedModelId . '\')', null, false)
->where('qty_stock >',0)
->where('products.isactive', 1)
->findAll();
$product = array_merge($common_product, $makeproduct);
$modelName = $this->BikemodelsModel->where('model_id',$modelId)->get()->getRow()->model_name;
$makeName = $this->BikemakeModel->where('make_id',$makeId)->get()->getRow()->make;
if($product){
// Send JSON response
return $this->response->setJSON(['product'=>$product , 'modelName'=>$modelName ,'makeName'=>$makeName] );
} else {
// If product is not found, return an empty response or appropriate message
return $this->response->setJSON(['product'=>[] , 'modelName'=>$modelName ,'makeName'=>$makeName]);
}
}
// Check if product exists
}