Merge branch 'main' of bitbucket.org:venbainformationtechnology/the_mechanic

This commit is contained in:
Gowtham M 2025-10-25 11:08:08 +05:30
commit d3abd1cef6
11 changed files with 2907 additions and 7 deletions

4
.gitignore vendored
View File

@ -1,3 +1,5 @@
/writable
/vendor
vendor/*
.env
!vendor/.gitkeep
composer.lock

View File

@ -76,6 +76,7 @@ $routes->post('status_product', 'Products::status_product');
$routes->get('delete_product_name/(:any)', 'Products::delete_product_name/$1');
$routes->get('get_product_addtional_details/(:any)', 'Products::get_product_addtional_details/$1');
$routes->get('product_categories', 'Products::product_categories');
$routes->post('quick_add', 'Products::quick_add');
//end products//
//Sales order //
@ -247,4 +248,16 @@ $routes->get('product_category_index', 'ProductCategory::index');
$routes->post('create_product_category/(:any)', 'ProductCategory::create_product_category/$1');
$routes->post('status_product_category', 'ProductCategory::status_product_category');
// product category End's //
// product category End's //
//Invoice //
$routes->group('invoices', ['namespace' => 'App\Controllers'], function($routes) {
$routes->get('/', 'Invoice::invoices_order_index');
$routes->get('new/(:any)', 'Invoice::new_invoice/$1');
$routes->post('save', 'Invoice::add_invoices');
$routes->get('delete/(:any)', 'Invoice::delete_invoice/$1');
$routes->post('delete/child', 'Invoice::delete_invoice_child');
$routes->get('download/(:any)', 'Invoice::download_invoice/$1');
$routes->get('preview/(:any)', 'Invoice::preview_invoice/$1');
$routes->post('products', 'Invoice::get_invoice_product');
});

543
app/Controllers/Invoice.php Executable file
View File

@ -0,0 +1,543 @@
<?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;
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'),
];
// 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($invoice_id)
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
// Fetch the invoice data based on $invoice_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
}

View File

@ -646,5 +646,73 @@ class Products extends BaseController
return json_encode($data);
}
public function quick_add()
{
$tax = floatval($this->request->getPost('tax')) / 2;
$bid = $this->session->get('logged_user_branch_id');
$ml = 0;
$box = 0;
$qty_per_box = 0;
$barrel = 0;
$ltr_per_barrel = 0;
$per = $this->request->getPost('per');
if ($per === 'ml') {
$ml = floatval($this->request->getPost('ml') ?? 0);
} elseif ($per === 'box') {
$box = floatval($this->request->getPost('box') ?? 0);
$qty_per_box = floatval($this->request->getPost('qty_per_box') ?? 0);
} elseif ($per === 'barrel') {
$barrel = floatval($this->request->getPost('barrel') ?? 0);
$ltr_per_barrel = floatval($this->request->getPost('ltr_per_barrel') ?? 0);
}
$data = [
'cubic_centimeter_id' => json_encode($this->request->getPost('cubic_centimeter_id')),
'product_name' => $this->request->getPost('productname'),
'product_category' => $this->request->getPost('productcategory'),
'total_amount' => $this->request->getPost('total_amount'),
'unit_price' => $this->request->getPost('unit_price'),
'qty_stock' => $this->request->getPost('qty_stock'),
'sgst' => $tax,
'cgst' => $tax,
'per' => $per,
'ml' => $ml,
'box' => $box,
'qty_per_box' => $qty_per_box,
'barrel' => $barrel,
'ltr_per_barrel' => $ltr_per_barrel,
'isactive' => 1,
'branch_id' => $bid,
'manufacturer_id' => $this->request->getPost('manufacturer'),
];
$insertID = $this->ProductModel->insert($data);
if ($insertID) {
$orderNumber = 'TM' . str_pad($insertID, 8, '0', STR_PAD_LEFT);
$this->ProductModel->update($insertID, ['sku_id' => $orderNumber]);
$pD = $this->ProductModel
->select('products.*')
->where('products.product_id', $insertID)
->where('products.branch_id', $bid)
->where('products.isactive', 1)
->first();
return $this->response->setJSON([
'status' => 'success',
'message' => 'Product added successfully!',
'data' => $pD
]);
} else {
return $this->response->setJSON([
'status' => 'error',
'message' => 'Failed to add product.',
]);
}
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class InvoiceChildModel extends Model
{
protected $table = 'invoice_child';
protected $primaryKey = 'invoice_child_id';
protected $allowedFields = ['invoice_child_id','invoice_id','product_id', 'net_price','qty','discount_type','discount','total','tax','amount','isactive','labour_cost'];
protected $beforeInsert = ['setCreatedBy'];
protected $beforeUpdate = ['setUpdatedBy'];
protected function setCreatedBy(array $data)
{
$data['data']['created_by'] = (int) session()->get('logged_user');
return $data;
}
protected function setUpdatedBy(array $data)
{
$data['data']['updated_by'] = (int) session()->get('logged_user');
return $data;
}
}

View File

@ -5,7 +5,61 @@ class InvoiceModel extends Model
{
protected $table = 'invoice';
protected $primaryKey = 'invoice_id';
protected $allowedFields = ['invoice_id','invoice_number','sale_order','invoice_date','sales_commision','client_name','status','vehicle_reg_number','billing_address','billing_city','billing_state','billing_country','billing_postal_code','terms_condition','job_card_id','isactive'];
protected $allowedFields = ['invoice_id','invoice_number','sale_order','invoice_date','sales_commision','client_name','status','vehicle_reg_number','billing_address','billing_city','billing_state','billing_country','billing_postal_code','terms_condition','job_card_id','isactive',
'type','mobile_no','email','invoice_child_id','order_number','mode_of_payment','subtotal','tax','discount','total','terms_condition','branch_id','vehicle_id' ];
protected $beforeInsert = ['setCreatedBy'];
protected $beforeUpdate = ['setUpdatedBy'];
protected function setCreatedBy(array $data)
{
$data['data']['created_by'] = (int) session()->get('logged_user');
return $data;
}
protected function setUpdatedBy(array $data)
{
$data['data']['updated_by'] = (int) session()->get('logged_user');
return $data;
}
public function getInvoicesPdf($invoice_id){
return $this->db->table('invoice')
->where('invoice_id', $invoice_id)
->join('branches as B','B.branch_id = invoice.branch_id','left')
->join('vehicle as V','V.vehicle_id = invoice.vehicle_id','left')
->join('client as C','V.client_id = C.client_id','left')
->select('invoice.*')
->select('B.branch_name ,B.address as company_address,B.city as company_city,B.state as company_state,B.postal_code as company_postal_code,B.contact_1 as company_mobile_no_1,B.contact_2 as company_mobile_no_2,B.gstno as company_gstno')
->select('C.gstnumber as client_gst')
->get()
->getResult();
}
public function getInvoiceProductsForPdf($invid)
{
$result = $this->db->table('invoice_child')
->where('invoice_child.invoice_id', $invid)
->where('invoice_child.isactive', 1)
->join('products', 'products.product_id = invoice_child.product_id')
->select('invoice_child.*, products.product_name, products.per, products.ml,products.hsn_sac')
->get()
->getResult();
return $result;
}
public function getInvoicesWithProducts($logged_user_branch_id)
{
// Select required fields from both tables
$this->select('invoice.*, COUNT(invoice_child.invoice_child_id) AS product_count,vehicle.reg_no,SUM(invoice_child.qty) AS product_qty ');
$this->join('invoice_child', 'invoice_child.invoice_id = invoice.invoice_id AND invoice_child.isactive = 1', 'left');
$this->join('vehicle', 'vehicle.vehicle_id = invoice.vehicle_id');
$this->groupBy('invoice.invoice_id');
$this->where('invoice.branch_id',$logged_user_branch_id);
$this->orderBy('invoice.invoice_id','desc');
// Get the results
return $this->findAll();
}
}

View File

@ -9,8 +9,21 @@ class ProductModel extends Model
'quality','product_name','branch_id','prefered_vendor','product_category','mfr_part_no','purchase_order_level',
'unit_price','commision_rate','sgst','cgst','purchase_cost','usage_unit','vendor','qty_stock','reorder_level',
'handler','qty_in_demand','product_image','description','specification','hsn_sac','isactive','total_amount',
'per','ml','box','qty_per_box','barrel','ltr_per_barrel'];
'per','ml','box','qty_per_box','barrel','ltr_per_barrel','cubic_centimeter_id'];
protected $beforeInsert = ['setCreatedBy'];
protected $beforeUpdate = ['setUpdatedBy'];
protected function setCreatedBy(array $data)
{
$data['data']['created_by'] = (int) session()->get('logged_user');
return $data;
}
protected function setUpdatedBy(array $data)
{
$data['data']['updated_by'] = (int) session()->get('logged_user');
return $data;
}
public function getTax()
{
@ -40,7 +53,7 @@ class ProductModel extends Model
$this->orderBy('products.product_name');
return $this->findAll();
}
}
?>

1695
app/Views/invoice_form.php Executable file

File diff suppressed because it is too large Load Diff

271
app/Views/invoice_list.php Executable file
View File

@ -0,0 +1,271 @@
<?php include('layout/header.php'); ?>
<style>
.dataTables_wrapper button{
background: #f1f5f7;
color: #343a40;
border-width: 0;
}
.dataTables_wrapper .dt-buttons{
float:left;
}
.cancelled-status {
color: red;
}
.Draft-status {
color: blue;
}
.Approved-status {
color: green;
}
</style>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="page-title-box page-title-box-alt">
<h4 class="page-title">Invoices</h4>
<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class=""> <a href="<?= base_url() . "invoices/new/0"; ?>" class="btn btn-primary waves-effect"> Add Invoice </a></li>
</ol>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<!-- <h4 class="header-title">Business List</h4> -->
<table id="datatable_invoices" class="table table-striped dt-responsive nowrap w-100"
style="width:100% !important;">
<thead>
<tr>
<th>Invoice Id</th>
<th>Invoice Number</th>
<th>Vehicle Reg No</th>
<th>Client Name</th>
<th>Items</th>
<th>Qty</th>
<th>Total</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
foreach ($invoices as $index => $value) :
if ($value['isactive'] == 1) : ?>
<tr class="invoice_tr<?php echo $index+1; ?>">
<td><?= $value['invoice_id']; ?></td>
<td><?= $value['invoice_number']; ?></td>
<td><?= $value['reg_no']; ?></td>
<td><?= $value['client_name']; ?></td>
<td><?= $value['product_count'] ?? 0 ; ?></td>
<td><?= $value['product_qty'] ?? 0 ; ?></td>
<td><?= $value['total']; ?></td>
<td class="<?php if ($value['status'] == 'Cancelled') { echo 'cancelled-status'; } elseif ($value['status'] == 'Draft') { echo 'Draft-status'; } elseif ($value['status'] == 'Approved') { echo 'Approved-status';} ?>">
<?= $value['status']; ?>
</td>
<td>
<div class="btn-group dropdown">
<a href="javascript: void(0);" class="dropdown-toggle arrow-none btn btn-light btn-sm" data-toggle="dropdown" aria-expanded="false"><i class="mdi mdi-dots-horizontal"></i></a>
<div class="dropdown-menu dropdown-menu-right">
<a href="<?= "invoices/new/" . $value['invoice_id']; ?>" class="dropdown-item edit-button" onclick="datatableInvoice('invoice_tr<?php echo $index+1; ?>')"><i class="ri-pencil-line mr-2 text-muted font-18 vertical-middle"></i>Edit</a>
<!-- <a href="<?= "invoices/delete/" . $value['invoice_id']; ?>" class="dropdown-item delete-button" onclick="datatableInvoice('invoice_tr<?php echo $index+1; ?>')"><i class="ri-delete-bin-line mr-2 text-muted font-18 vertical-middle"></i>Delete</a> -->
<a href="#" data-invoices-id="<?= $value['invoice_id']; ?>" class="dropdown-item preview-invoice" href="#" title="Preview Invoice"><i class="ri-book-read-line mr-2 text-muted font-18 vertical-middle"></i>Preview Invoice</a>
</div>
</div>
</td>
<?php endif?>
<?php endforeach; ?>
</tr>
</tbody>
</table>
</div> <!-- end table-responsive-->
</div>
</div> <!-- end card -->
</div> <!-- end col -->
</div>
<?php include('layout/footer.php'); ?>
<div class="modal fade" id="PreviewInvoiceModal" tabindex="-1" role="dialog" aria-labelledby="PreviewInvoiceModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content" style="width: 794px; height: 1123px;">
<div class="modal-header">
<h5 class="modal-title" id="PreviewInvoiceModalLabel"></h5>
<a href="#" class="ri-download-2-fill ml-3 text-muted font-18" id="downloadInvoiceButton" title="Download Invoice"></a>
<a href="#" class="ri-printer-fill ml-3 text-muted font-18" id="printInvoiceButton" title="Print Invoice"></a>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" style="font-size: 27px; margin-bottom: 2px;">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body" style="font-family: Times New Roman, Times, sans-serif !important; font-size: 12px !important;">
</div>
</div>
</div>
</div>
<script>
var datatable_invoice ='';
$(document).ready(function() {
datatable_invoice = $('#datatable_invoices').DataTable({
"order": [[0, 'desc']], // Sort by Id (hidden column)
"dom": 'Bfrtip', // Show export buttons
"buttons": [
{extend: 'pdfHtml5', title: 'Products', text: 'PDF'},
{extend: 'print', title: 'Products', text: 'Print'},
{extend: 'copy', text: 'Copy', titleAttr: 'Copy'},
{extend: 'csv', text: 'CSV', title: 'Products'}
],
"language": {
"search": "Search: " // Customize search label
},
"columnDefs": [
{
"targets": [0], // Target the first column (Id)
"visible": false, // Hide the column
"searchable": false // Make it non-searchable (optional)
}
]
});
//Start DataTable Paging is session is set
var savedPage = sessionStorage.getItem('currentPage');
var hightlight_tr = sessionStorage.getItem('hightlight_tr');
// console.log(savedPage);
// console.log(hightlight_tr);
// Ensure savedPage is a number
savedPage = parseInt(savedPage);
// Check if savedPage is not null and adjust if necessary
if (savedPage !== null && !isNaN(savedPage)) {
// Check if the saved page number is within the bounds of the current DataTable
var totalPages = datatable_invoice.page.info().pages; // Total number of pages in the DataTable
if (savedPage >= totalPages) {
// adjust to the last page of the DataTable
savedPage = totalPages > 0 ? totalPages - 1 : 0;
}
// Move DataTable to the saved page and draw
datatable_invoice.page(savedPage).draw(false);
// Select the highlighted row
var $row = $('.' + hightlight_tr);
// Smoothly scroll to the row and center it in the viewport
$('html, body').animate({
scrollTop: $row.offset().top - ($(window).height() / 2) + ($row.height() / 2)
}, 500, function() {
// After focusing, change background color
$row.css('background', '#faf6ca');
// Remove background color after 4 seconds
setTimeout(function() {
$row.css('background', '');
}, 4000);
});
}
sessionStorage.removeItem('currentPage');
sessionStorage.removeItem('hightlight_tr');
//End DataTable Paging is session is set
})
function datatableInvoice(value) {
console.log(value);
var currentPage = datatable_invoice.page.info().page;
sessionStorage.setItem('currentPage', currentPage);
sessionStorage.setItem('hightlight_tr', value);
}
$(document).on('click', '.preview-invoice', function() {
var Id = $(this).data('invoices-id');
$.ajax({
type: 'GET',
url: 'invoices/preview/'+Id,
dataType: 'json',
success: function(response) {
if (response.status == "success") {
$('#PreviewInvoiceModal').modal('show');
$('#PreviewInvoiceModalLabel').text('Invoice Preview ');
$('#PreviewInvoiceModal .modal-body').html(response.data);
$('#downloadInvoiceButton').attr('href', '<?= base_url("invoices/download/") ?>' + Id);
$('#printInvoiceButton').attr('data-id', Id);
}else{
$('#PreviewInvoiceModal').modal('hide');
$('#PreviewInvoiceModalLabel').text('');
}
},
error: function(xhr, status, error) {
// Handle error response here
console.error(xhr.responseText);
$('#PreviewInvoiceModal').modal('hide');
$('#PreviewInvoiceModalLabel').text('');
}
});
});
$(document).on('click', '#printInvoiceButton', function() {
var Id = $(this).data('id');
$.ajax({
type: 'GET',
url: 'invoices/preview/'+Id,
dataType: 'json',
success: function(response) {
if (response.status == "success") {
var newWin = window.open("", "_blank", "width=600,height=400");
newWin.document.write("<html><head><title>Print</title>");
newWin.document.write(`
<style>
@media print {
@page {
size: A4; /* Set default print size to A4 */
margin: 1cm; /* Set margin as per requirement */
}
body {
font-family: Arial, sans-serif;
}
}
</style>
`);
newWin.document.write("</head><body>");
newWin.document.write(response.data);
newWin.document.write("</body></html>");
newWin.document.close();
newWin.print();
newWin.close();
}else{
$('#PreviewInvoiceModal').modal('hide');
$('#PreviewInvoiceModalLabel').text('');
}
},
error: function(xhr, status, error) {
// Handle error response here
console.error(xhr.responseText);
$('#PreviewInvoiceModal').modal('hide');
$('#PreviewInvoiceModalLabel').text('');
}
});
});
</script>

196
app/Views/invoice_pdf_layout.php Executable file

File diff suppressed because one or more lines are too long

View File

@ -448,6 +448,27 @@
</li>
<?php } ?>
<li>
<a href="<?php echo base_url('invoices') ?>">
<i class="fas fa-file-invoice"></i>
<span> Invoices </span>
</a>
</li>
<!-- <li>
<a href="#sidebarLayouts4" data-toggle="collapse">
<i class="fas fa-file-invoice"></i>
<span> Invoices </span>
<span class="menu-arrow"></span>
</a>
<div class="collapse" id="sidebarLayouts4">
<ul class="nav-second-level">
<li>
<a href="<?php echo base_url('invoices') ?>">Invoice</a>
</li>
</ul>
</div>
</li> -->