the_mechanic/app/Controllers/Sales.php
2025-10-30 14:24:14 +05:30

594 lines
26 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use App\Models\SalesOrderModel;
use App\Models\SalesOrderProductModel;
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 Mpdf\Mpdf;
use CodeIgniter\API\ResponseTrait;
use App\Helpers\InvNoHelper;
use App\Helpers\ClientDetailsUpdate;
class Sales extends BaseController
{
public $session;
use ResponseTrait;
protected $BikemodelsModel;
protected $BikemakeModel;
protected $additionalProductNameModal;
protected $SalesOrderModel;
protected $SalesOrderProductModel;
protected $ProductModel;
protected $ClientModel;
protected $VehicleModel;
protected $BranchModel;
public function __construct()
{
$this->session = session();
$this->BikemodelsModel = new BikemodelsModel();
$this->BikemakeModel = new BikemakeModel();
$this->additionalProductNameModal = new AdditionalProductNameModal();
$this->SalesOrderModel = new SalesOrderModel();
$this->SalesOrderProductModel = new SalesOrderProductModel();
$this->ProductModel = new ProductModel();
$this->ClientModel = new ClientModel();
$this->VehicleModel = new VehicleModel();
$this->BranchModel = new BranchModel();
}
public function sales_order_index()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$data['sales'] = $this->SalesOrderModel->getSalesOrdersWithProducts($this->session->get('logged_user_branch_id'));
return view('sales_list',$data);
}
public function new_sale($sales_order_id)
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
if ($sales_order_id === '0') {
$data['page_name']="Create Sales Order";
$data['sales'] = [];
$data['client'] = $this->ClientModel->where('isactive',1)
->where('branch_id',$this->session->get('logged_user_branch_id'))
->findAll();
$data['vehicle'] = $this->VehicleModel->getCustomerandVehicle($this->session->get('logged_user_branch_id'));
$data['product'] = $this->ProductModel->select('products.*, manufacturer.manufacturer_name')
->join('manufacturer', 'products.manufacturer_id = manufacturer.manufacturer_id', 'left')
->where('products.isactive', 1)
->where('products.qty_stock >',0)
->where('products.branch_id', $this->session->get('logged_user_branch_id'))
->findAll();
} else if ($sales_order_id !== '0') {
$data['page_name'] = "Edit Sale Order";
$data['client'] = $this->ClientModel->where('isactive',1)->where('branch_id',$this->session->get('logged_user_branch_id'))->findAll();
$data['sales'] = $this->SalesOrderModel->where('sales_order_id', $sales_order_id)->get()->getRowArray();
$vehicles = $this->VehicleModel->where('isactive',1)->where('vehicle_id',$data['sales']['vehicle_id'])
->where('branch_id',$this->session->get('logged_user_branch_id'))
->first();
// $makeId = $vehicles['make'];
// $modelId = $vehicles['model'];
// 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);
// $data['product']=$product;
$data['product'] = $this->ProductModel->select('products.*, manufacturer.manufacturer_name')
->join('manufacturer', 'products.manufacturer_id = manufacturer.manufacturer_id', 'left')
->where('products.isactive', 1)
->where('products.qty_stock >',0)
->where('products.branch_id', $this->session->get('logged_user_branch_id'))
->findAll();
$sales_product = $this->SalesOrderProductModel->where('sales_order_id', $sales_order_id)->findAll();
$data['sales_product']=$sales_product;
$data['vehicle'] = $this->VehicleModel->where('isactive',1)->where('branch_id',$this->session->get('logged_user_branch_id'))->findAll();
}
$data['sales_order_id'] = $sales_order_id;
$data['makeData'] = $this->BikemakeModel->findAll();
return view('sales_order_form',$data);
}
public function add_sales()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
// Prepare data for sales order
$status = $this->request->getPost('status') != '' ? $this->request->getPost('status') : 'Draft';
$data = [
'client_name' => $this->request->getPost('client_id'),
'vehicle_id'=>$this->request->getPost('vehicle_id'),
'billing_address' => $this->request->getPost('billing_address'),
'billing_city' => $this->request->getPost('city'),
'mobile_no' => $this->request->getPost('mobile_no'),
'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'),
];
$update_client_address = $this->request->getPost('update_client_address');
if(isset($update_client_address) && $update_client_address == 'on')
{
ClientDetailsUpdate::updateClientAddress($this->request->getPost('vehicle_id'),$data);
}
// Insert or update sales order
$sales_order_id = $this->request->getPost('sales_order_id');
if (!empty($sales_order_id)) {
//update sales-order
if ($status === "Approved") {
$data['mode_of_payment'] = $this->request->getPost('mode_of_payment');
}
$this->SalesOrderModel->update($sales_order_id, $data);
} else {
//create sales-order
$data['inv_no'] = InvNoHelper::generateInvoiceNumber();
$this->SalesOrderModel->insert($data);
$sales_order_id = $this->SalesOrderModel->getInsertID();
// Update sales order with generated order number
$orderNumber = 'SO-' . date('md') . '-' . str_pad($sales_order_id, 5, '0', STR_PAD_LEFT);
$this->SalesOrderModel->update($sales_order_id, ['order_number' => $orderNumber]);
}
// 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');
$sales_product_id = $this->request->getPost('sales_order_product_id');
$product_names_id = $this->request->getPost('product_names_id');
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;
$product_data = [
'sales_order_id' => $sales_order_id,
'product_id' => $product_id,
'product_names_id' => $product_names_id[$key],
'qty' => $qty,
'discount' => $discount,
'discount_type' => $discount_type,
'net_price'=>$rate,
'tax'=>$tax,
'amount' => $amount,
'isactive'=>1,
];
// print_r($product_data);die;
if (!empty($sales_product_id[$key])) {
$this->SalesOrderProductModel->update($sales_product_id[$key], $product_data);
} else {
$this->SalesOrderProductModel->insert($product_data);
}
}
return redirect()->to('sales_order_index');
}
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_sales_product()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$sales_order_product_id = $this->request->getPost('sales_order_product_id');
if (!empty($sales_order_product_id)) {
$data['isactive'] = 0;
if ($this->SalesOrderProductModel->update($sales_order_product_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_sale($sales_order_id)
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$where = ['sales_order_id' => $sales_order_id, 'isactive' => 1]; // Assuming 'isactive' is a column in your database
$existingProduct = $this->SalesOrderModel->where($where)->first();
if ($existingProduct) {
$data['isactive'] = 0;
if ($this->SalesOrderModel->update($sales_order_id, $data)) {
session()->setFlashdata('success', 'Deleted successfully.');
$this->logger->info("Users: has been Inactivated successfully. Inactivated ID = ".$sales_order_id);
}
}
return redirect()->to('sales_order_index');
}
public function download_invoice($sales_order_id)
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
// Fetch the invoice data based on $invoice_id
$saleOrderCount = count($this->SalesOrderModel->where('status','Approved')->findAll());
$data['sales'] = $this->SalesOrderModel->getSalesPdf($sales_order_id);
$data['branch'] = $this->BranchModel->where('branch_id', $data['sales'][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['sales'][0]->vehicle_id)
->first();
$data['items'] = $this->SalesOrderModel->getSalesOrderProductsForPdf($sales_order_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['sales'][0]->branch_name);
$mpdf->SetCreator('');
// Generate the PDF content (HTML)
if ($data['sales'][0]->status === 'Draft') {
$mpdf->SetWatermarkText('Draft');
$mpdf->showWatermarkText = true;
}
if ($data['sales'][0]->status === 'Cancelled') {
$mpdf->SetWatermarkText('Cancelled');
$mpdf->showWatermarkText = true;
}
// Generate the PDF content (HTML) with data
$html = view('invoice_pdf_template', $data);
$mpdf->WriteHTML($html);
date_default_timezone_set('Asia/Kolkata');
$mpdf->Output($data['sales'][0]->order_number .'_' . date('Y-m-d H-i-s') . '.pdf', 'D');
}
public function preview_invoice($sales_order_id)
{
// Fetch the invoice data based on $invoice_id
$saleOrderCount = count($this->SalesOrderModel->where('status','Approved')->findAll());
$data['sales'] = $this->SalesOrderModel->getSalesPdf($sales_order_id);
$data['branch'] = $this->BranchModel->where('branch_id', $data['sales'][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['sales'][0]->vehicle_id)
->first();
$data['items'] = $this->SalesOrderModel->getSalesOrderProductsForPdf($sales_order_id);
$html = view('invoice_pdf_template', $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 getProducts()
{
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.*, manufacturer.manufacturer_name')
->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id','left')
->where('products.qty_stock >',0)
->where('products.isactive', 1)
->findAll();
// $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')
// ->whereIn('product_names.model_id',[$modelId, 0])
// ->where('qty_stock >',0)
// ->where('product_names.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
}