Purchase-sale-Product-vendor

This commit is contained in:
heama 2024-04-11 11:17:57 +05:30
parent 5091538fc6
commit a7bfff8865
9 changed files with 775 additions and 100 deletions

View File

@ -123,5 +123,7 @@ $routes->get("new_purchase/(:any)", "Purchase::new_purchase/$1");
$routes->get('get_vendor/(:any)', 'Purchase::get_vendor/$1');
$routes->post("add_purchase", "Purchase::add_purchase");
$routes->get("delete_purchase/(:any)", "Purchase::delete_purchase/$1");
$routes->post("getVendorProducts", "Purchase::getVendorProducts");
$routes->post("delete_purchase_product", "Purchase::delete_purchase_product");
// Reorder Level//
$routes->get('reorder_level_index', 'Reorderlevel::reorder_level_index');

View File

@ -7,6 +7,7 @@ use App\Models\PurchaseOrderModel;
use App\Models\VendorModel;
use App\Models\BranchModel;
use App\Models\BusinessModel;
use App\Models\PurchaseOrderChildModel;
class Purchase extends BaseController
@ -21,9 +22,7 @@ class Purchase extends BaseController
{
$PurchaseOrderModel = new PurchaseOrderModel();
$purchase = $PurchaseOrderModel->select('purchase_order.*, vendor.vendor_name')
->join('vendor', 'vendor.vendor_id = purchase_order.vendor_id')
->findAll();
$purchase = $PurchaseOrderModel->getPurchaseOrdersWithProducts($this->session->get('logged_user_branch_id'));
// echo "<pre>";
// print_r($product);die;
$data['purchase']=$purchase;
@ -48,7 +47,11 @@ class Purchase extends BaseController
$BusinessModel = new BusinessModel();
$branch = $BranchModel->where('branch_id', $this->session->get('logged_user_branch_id'))->get()->getRowArray();
$business = $BusinessModel->where('business_id', $this->session->get('logged_user_business_id'))->get()->getRowArray();
$ProductModel = new ProductModel();
$product=$ProductModel
->where('isactive',1)
->where('branch_id',$this->session->get('logged_user_branch_id'))->findAll();
$data['product']=$product;
$data['branch'] = $branch;
$data['business'] = $business;
@ -61,12 +64,31 @@ class Purchase extends BaseController
$PurchaseOrderModel = new PurchaseOrderModel();
$purchase=$PurchaseOrderModel->where('purchase_order_id', $purchase_order_id)->get()->getRowArray();
$data['purchase'] = $purchase;
$VendorModel = new VendorModel();
$vendor = $VendorModel->select('vendor_id,vendor_name')->findAll();
$data['vendor']=$vendor;
$data['purchase'] = $purchase;
$data['vendor'] = $vendor;
$data['vendor_id'] = $purchase['vendor_id'];
// print_r($vendor);die;
$vendorId=$purchase['vendor_id'];
$encodedVendorId = json_encode([$vendorId]);
$productModel = new ProductModel();
// Query the database to find the product based on make_id and model_id
$product = $productModel->where('JSON_CONTAINS(vendor, \'' . $encodedVendorId . '\')', null, false)
->findAll();
$data['product']=$product;
// print_r($product);die;
$PurchaseOrderChildModel = new PurchaseOrderChildModel();
$purchase_product=$PurchaseOrderChildModel->where('purchase_order_id', $purchase_order_id)->findAll();
$data['purchase_product']=$purchase_product;
}
// echo "<pre>";
@ -77,6 +99,8 @@ class Purchase extends BaseController
public function add_purchase()
{
$PurchaseOrderModel = new PurchaseOrderModel();
$ProductModel = new ProductModel();
$PurchaseOrderChildModel = new PurchaseOrderChildModel();
$data = [
'vendor_id' => $this->request->getPost('vendor_id'),
'order_date' => $this->request->getPost('order_date'),
@ -91,23 +115,97 @@ class Purchase extends BaseController
'shipping_state' => $this->request->getPost('shipping_state'),
'shipping_city' =>$this->request->getPost('shipping_city'),
'shipping_postal_code' => $this->request->getPost('shipping_postal_code'),
'description' => $this->request->getPost('description'),
'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'),
'branch_id'=> $this->session->get('logged_user_branch_id'),
];
// echo "<pre>";
// print_r($this->request->getPost());die;
// print_r($data);
$purchase_order_id = $this->request->getPost('purchase_order_id');
// echo $purchase_order_id;die;
if (!empty($purchase_order_id)) {
$PurchaseOrderModel->update($purchase_order_id, $data);
} else {
$PurchaseOrderModel->insert($data);
$purchase_order_id = $PurchaseOrderModel->getInsertID();
}
$orderNumber = 'PO' . str_pad($purchase_order_id, 8, '0', STR_PAD_LEFT);
// print_r($orderNumber);die;
// Update sales order with generated order number
$PurchaseOrderModel->update($purchase_order_id, ['order_number' => $orderNumber]);
// print_r();die;
// 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');
$purchase_order_child_id = $this->request->getPost('purchase_order_child_id');
// print_r($purchase_order_child_id);die;
// print_r($status);die;
$status = $this->request->getPost('purchase_status');
foreach ($product_ids as $key => $product_id) {
$qty = isset($quantities[$key]) ? $quantities[$key] : 0;
if ($status == 'Released')
// echo "hello";die;
$this->addBackProductQuantity($ProductModel, $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($ProductModel, $product_id, $qty);
// print_r($discount_type);die;
$child_data = [
'purchase_order_id' => $purchase_order_id,
'product_id' => $product_id,
'qty' => $qty,
// 'discount' => $discount,
// 'discount_type' => $discount_type,
'net_price'=>$rate,
'tax'=>$tax,
'amount' => $amount,
'isactive'=>1,
];
// print_r($child_data);die;
if (!empty($purchase_order_child_id[$key])) {
// print_r($purchase_order_child_id[$key]);die;
$PurchaseOrderChildModel->update($purchase_order_child_id[$key], $child_data);
} else {
$PurchaseOrderChildModel->insert($child_data);
}
}
return redirect()->to('purchase_index');
}
private function addBackProductQuantity($ProductModel, $product_id, $sold_qty)
{
// Fetch current product quantity
$product = $ProductModel->find($product_id);
$current_qty = $product['qty_stock'];
// Calculate updated quantity
$new_qty = $current_qty + $sold_qty;
// Update quantity in Product table
$ProductModel->update($product_id, ['qty_stock' => $new_qty]);
}
public function delete_purchase($purchase_order_id)
{
@ -142,5 +240,48 @@ class Purchase extends BaseController
return json_encode($products);
}
public function getVendorProducts()
{
// Retrieve make_id and model_id from the request
// $makeId = $this->request->getPost('');
$vendorId = $this->request->getPost('vendor_id');
// Encode the modelId before searching
$encodedVendorId = json_encode([$vendorId]);
// Load the ProductModel
$productModel = new ProductModel();
// Query the database to find the product based on make_id and model_id
$product = $productModel
->where('JSON_CONTAINS(vendor, \'' . $encodedVendorId . '\')', null, false)
->findAll();
// print_r($product);die;
if($product){
// Send JSON response
return $this->response->setJSON(['product'=>$product] );
} else {
// If product is not found, return an empty response or appropriate message
return $this->response->setJSON(['product'=>[] , 'modelName'=>$modelName ,'makeName'=>$makeName]);
}
}
public function delete_purchase_product()
{
$purchase_order_child_id = $this->request->getPost('purchase_order_child_id');
if (!empty($purchase_order_child_id)) {
$PurchaseOrderChildModel = new PurchaseOrderChildModel();
$data['isactive'] = 0;
if ($PurchaseOrderChildModel->update($purchase_order_child_id, $data)) {
// Return success response
return $this->response->setJSON(['success' => true]);
}
}
// Return error response if deletion fails
return $this->response->setJSON(['success' => false]);
}
}

View File

@ -69,6 +69,7 @@ class Sales extends BaseController
$SalesOrderModel = new SalesOrderModel();
$sales=$SalesOrderModel->where('sales_order_id', $sales_order_id)->get()->getRowArray();
$data['sales']=$sales;
$VehicleModel = new VehicleModel();
$vehicles = $VehicleModel->where('isactive',1)->where('vehicle_id',$sales['vehicle_id'])
->where('branch_id',$this->session->get('logged_user_branch_id'))
@ -143,7 +144,7 @@ $VehicleModel = new VehicleModel();
$SalesOrderModel->insert($data);
$sales_order_id = $SalesOrderModel->getInsertID(); // Get the last inserted ID
}
$orderNumber = 'SO-' . date('md') . '-' . str_pad($sales_order_id, 5, '0', STR_PAD_LEFT);
$orderNumber = 'SO' . str_pad($sales_order_id, 8, '0', STR_PAD_LEFT);
// print_r($orderNumber);die;
// Update sales order with generated order number
$SalesOrderModel->update($sales_order_id, ['order_number' => $orderNumber]);

View File

@ -0,0 +1,11 @@
<?php
namespace App\Models;
use CodeIgniter\Model;
class PurchaseOrderChildModel extends Model
{
protected $table = 'purchase_order_child';
protected $primaryKey = 'purchase_order_child_id';
protected $allowedFields = ['purchase_order_child_id','purchase_order_id','product_id','qty','total','tax','net_price','amount','discount_type','selling_price','discount','isactive'];
}

View File

@ -5,7 +5,24 @@ class PurchaseOrderModel extends Model
{
protected $table = 'purchase_order';
protected $primaryKey = 'purchase_order_id';
protected $allowedFields = ['purchase_order_id','vendor_id','status','billing_address','billing_city','billing_state','billing_country','billing_postal_code','shipping_address','shipping_city','shipping_state','shipping_country','shipping_postal_code','terms_condition','isactive','order_date','contact_person_name','contact_person_mobile','description'];
protected $allowedFields = ['purchase_order_id','order_number','vendor_id','status','billing_address','billing_city','billing_state','billing_country','billing_postal_code','shipping_address','shipping_city','shipping_state','shipping_country','shipping_postal_code','terms_condition','isactive','order_date','contact_person_name','branch_id','contact_person_mobile','description','subtotal','tax','total'];
public function getPurchaseOrdersWithProducts($logged_user_branch_id)
{
// Select required fields from both tables
$this->select('purchase_order.*, COUNT(purchase_order_child.purchase_order_id) AS product_count,vendor.vendor_name');
// Join the sales_order_product table based on sales_order_id
$this->join('purchase_order_child', 'purchase_order_child.purchase_order_id = purchase_order.purchase_order_id');
$this ->join('vendor', 'vendor.vendor_id = purchase_order.vendor_id');
// Group by sales_order_id to get count of products per sales order
$this->groupBy('purchase_order.purchase_order_id');
// Add condition to fetch only active sales orders
$this->where('purchase_order_child.isactive', 1);
$this ->where('purchase_order.branch_id',$logged_user_branch_id);
$this->orderBy('purchase_order.purchase_order_id','DESC');
// Get the results
return $this->findAll();
}
}

View File

@ -78,7 +78,7 @@
<label for="inputAddress" class="col-form-label">Manfacturer Part Number</label>
<input type="text" class="form-control" name="mfr_part_no" placeholder="Manfacturer Part Number" value="<?= isset($products['mfr_part_no']) ? $products['mfr_part_no'] : '' ?>" >
</div>
<div class="form-group col-md-4">
<div class="form-group col-md-8">
<label for="vendor" class="col-form-label">Vendor<span class="text-danger">*</span></label>
<select class="form-control SelExample" id="vendor" name="vendor[]" required multiple>
<!-- Placeholder option -->

View File

@ -22,12 +22,12 @@
<div class="card-body">
<h4 class="header-title"></h4>
<form action="<?= base_url() . "add_purchase"; ?>" method="post">
<input type="text" id="purchase_order_id" name="purchase_order_id" value="<?=isset($purchase_id) && !empty($purchase_id) ? $purchase_id : '' ?>" hidden>
<input type="hidden" id="purchase_order_id" name="purchase_order_id" value="<?= isset($purchase['purchase_order_id']) ? $purchase['purchase_order_id'] : '' ?>"readonly>
<h4 class="header-title">Purchase Details :</h4><br>
<div class="form-row">
<div class="form-group col-md-4">
<label for="make" class="col-form-label">Vendor<span class="text-danger">*</span></label>
<select class="form-control" name="vendor_id" id="vendor_id">
<select class="form-control vendor-select" name="vendor_id" id="vendor_id">
<option value="0">Select Vendor</option>
<?php foreach ($vendor as $item): ?>
<option value="<?= $item['vendor_id'] ?>" <?= isset($item['vendor_id']) && $vendor_id == $item['vendor_id'] ? 'selected' : '' ?>>
@ -36,10 +36,8 @@
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-4">
<label for="order_date" class="col-form-label">Order Date</label>
<input type="date" class="form-control" name="order_date" id="order_date" value="<?= isset($purchase['order_date']) ? date('Y-m-d', strtotime($purchase['order_date'])) : '' ?>" >
</div>
<div class="form-group col-md-4">
<label for="contact_person_name" class="col-form-label">Contact Person Name<span class="text-danger">*</span></label>
@ -47,17 +45,21 @@
</div>
<div class="form-group col-md-4">
<label for="contact_person_mobile" class="col-form-label">Contact Person Mobile<span class="text-danger">*</span></label>
<input type="text" class="form-control" name="contact_person_mobile" id="contact_person_mobile" placeholder="Contact Person Mobile" value="<?= isset($purchase['contact_person_mobile']) ? $purchase['contact_person_mobile'] : '' ?>" required>
<input type="text" class="form-control" name="contact_person_mobile" id="contact_person_mobile" placeholder="Contact Person Mobile" value="<?= isset($purchase['contact_person_mobile']) ? $purchase['contact_person_mobile'] : '' ?>"maxlength="10" minlength="10" onkeypress = "return onlyNumbers(event)" required>
</div>
<div class="form-group col-md-4">
<label for="purchase_status" class="col-form-label">Purchase Status<span class="text-danger">*</span></label>
<select name="purchase_status" id="purchase_status" class="form-control">
<option value="draft" <?= isset($purchase['status']) && $purchase['status'] == 'draft' ? 'selected' : '' ?>>Draft</option>
<option value="released" <?= isset($purchase['status']) && $purchase['status'] == 'released' ? 'selected' : '' ?>>Released</option>
<option value="cancel" <?= isset($purchase['status']) && $purchase['status'] == 'cancel' ? 'selected' : '' ?>>Cancel</option>
<option value="Draft" <?= isset($purchase['status']) && $purchase['status'] == 'Draft' ? 'selected' : '' ?>>Draft</option>
<option value="Cancel" <?= isset($purchase['status']) && $purchase['status'] == 'Cancel' ? 'selected' : '' ?>>Cancel</option>
<option value="Released" <?= isset($purchase['status']) && $purchase['status'] == 'Released' ? 'selected' : '' ?>>Released</option>
</select>
</div>
<div class="form-group col-md-4">
<label for="order_date" class="col-form-label">Order Date</label>
<input type="date" class="form-control" name="order_date" id="order_date" value="<?= empty($purchase['order_date']) ? date('Y-m-d') : date('Y-m-d', strtotime($purchase['order_date'])) ?>" readonly>
</div>
</div>
<h4 class="header-title">Billing Addresss :</h4><br>
<div class="form-row">
@ -98,104 +100,595 @@
<input type="text" class="form-control" name="shipping_postal_code" id="shipping_postal_code" placeholder="Shipping Pin Code"value="<?= isset($branch['postal_code']) ? $branch['postal_code'] : (isset($purchase['shipping_postal_code']) ? $purchase['shipping_postal_code'] : '') ?>" required>
</div>
</div><br>
<h4 class="header-title">Description Details :</h4><br>
<div class="form-row" id="itemTableContainer">
<div class="form-group col-md-12">
<h4>Item Details</h4>
<br />
<table class="table table-bordered" id="itemTable">
<thead>
<tr>
<th>Item Details</th>
<th>Qty</th>
<th>Rate</th>
<th>Tax</th>
<!-- <th style="text-align: center !important" colspan="2">Discount</th> -->
<th>Amount</th>
<th hidden></th>
<th></th>
</tr>
</thead>
<tbody>
<!-- Dynamically add rows for item details -->
<?php if (isset($purchase_product) && !empty($purchase_product)) : ?>
<?php foreach ($purchase_product as $purchasechild) :
if ($purchasechild['isactive'] == 1) : ?>
<tr>
<td>
<select class="form-control book-select SelExample" name="item_details[]" required data-toggle="select2" id="" style="width: 249px !important;">
<option value="">Select a Product</option>
<?php foreach ($product as $value) : ?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["product_id"] ?>" <?= isset($purchasechild['product_id']) && $purchasechild['product_id'] == $value["product_id"] ? 'selected' : '' ?>>
<?= $value["product_name"]; ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</td>
<td style="width:10%;">
<input type="number" class="form-control item-quantity" name="quantity[]" min="0" value="<?= isset($purchasechild['qty']) ? $purchasechild['qty'] : '' ?>">
</td>
<td style="width:10%;">
<input type="text" class="form-control item-rate" name="unit-price[]" readonly value="<?= isset($purchasechild['net_price']) ? $purchasechild['net_price'] : '' ?>">
</td>
<td style="width:10%;">
<input type="text" class="form-control item-tax" name="item-tax[]" value="<?= isset($purchasechild['tax']) ? $purchasechild['tax'] : '' ?>">
</td>
<!-- <td style="width:12%;">
<input type="number" class="form-control item-discount-amount" min="0" name="discount_amount[]" value="<?= isset($purchasechild['discount']) ? $purchasechild['discount'] : '' ?>">
</td>
<td style="width:10%;">
<select class="form-control item-discount-type" name="discount_type[]">
<option value="" <?= isset($purchasechild['discount_type']) && $purchasechild['discount_type'] == '₹' ? 'selected' : '' ?>>₹</option>
<option value="%" <?= isset($purchasechild['discount_type']) && $purchasechild['discount_type'] == '%' ? 'selected' : '' ?>>%</option>
</select>
</td> -->
<td style="width:12%;">
<input type="text" class="form-control item-amount" name="amount[]" value="<?= isset($purchasechild['amount']) ? $purchasechild['amount'] : '' ?>">
</td>
<td hidden><input type="hidden" value="<?= isset($purchasechild['purchase_order_child_id']) ? $purchasechild['purchase_order_child_id'] : '' ?>"name="purchase_order_child_id[]"></td>
<td style="width:12%;">
<center><i class="fa fa-trash remove-item"></i></center>
</td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
<!-- You can add more rows as needed using JavaScript -->
</tbody>
</table>
<div class="form-group text-right m-b-0">
<!-- Show the "Add More Item" button only if invoice_type is not 1 -->
<a class="btn" id="addItem">
<h4><i class="fa fa-plus" aria-hidden="true"></i> Add Product</h4>
</a>
</div>
</div>
</div>
<div class="form-row">
<div class="offset-md-7 col-md-5 card">
<div class="card-body">
<h4>Calculation</h4>
<div class="form-group">
<label for="subtotal">Subtotal</label>
<input type="text" class="form-control" id="subtotal" name="sub_total" value="<?= isset($sales['subtotal']) ? $sales['subtotal'] : '' ?>"readonly >
</div>
<div class="form-group">
<label for="invoicetax">Tax Amount<span id=""></span></label>
<input type="text" class="form-control" id="invoicetax" name="invoice_tax" readonly value="<?= isset($sales['tax']) ? $sales['tax'] : '' ?>">
</div>
<!-- <div class="form-group">
<label for="discount">Discount Amount</label>
<input type="number" class="form-control" id="discount" name="discount" onchange="calculateGrandTotal(this.value)" min="0" readonly value="<?= isset($sales['discount']) ? $sales['discount'] : '' ?>" >
</div> -->
<div class="form-group">
<label for="grandtotal">Total</label>
<input type="text" class="form-control" id="grandtotal" name="grand_total" readonly value="<?= isset($sales['total']) ? $sales['total'] : '' ?>">
</div>
</div>
</div>
</div>
<h4 class="header-title">Terms & Condition :</h4><br>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputPassword4" class="col-form-label">Description</label>
<textarea class="form-control" name="description" placeholder="Description" required><?= isset($purchase['description']) ? $purchase['description'] : '' ?></textarea>
<label for="inputPassword4" class="col-form-label">Terms & Condition</label>
<textarea class="form-control" name="terms_condition" placeholder="Terms & Condition" >
<?= isset($sales['terms_condition']) ? $sales['terms_condition'] : 'Please check the products properly before purchase. Products once sold cannot be returned.' ?>
</textarea>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<?php if (!isset($sales['status']) || $sales['status'] !== 'Paid') : ?>
<button type="submit" class="btn btn-primary">Submit</button>
<?php endif; ?>
</form>
</div>
</div>
</div>
</div>
<?php include('layout/footer.php'); ?>
</div>
<script>
productarray = [];
$(document).ready(function() {
// Check SGST checkbox by default
$('#sgstCheckbox').prop('checked', true);
$('#sgstValue').removeClass('d-none');
// Check CGST checkbox by default
$('#cgstCheckbox').prop('checked', true);
$('#cgstValue').removeClass('d-none');
// Handle change event for SGST checkbox
$('#sgstCheckbox').change(function() {
if ($(this).is(":checked")) {
$('#sgstValue').removeClass('d-none');
} else {
$('#sgstValue').addClass('d-none');
// Event listener for vehicle selection change
$('.vendor-select').change(function() {
var vendorId = $(this).val();
if (vendorId !== '') {
// Find the selected vehicle
var selectedVehicle = vendors.find(function(vendor) {
return vendor.vendor_id == vendorId;
});
// Extract makeId from the selected vehicle
// Make sure makeId exists
if (vendorId !== undefined) {
// Perform AJAX request to fetch product information
$.ajax({
url: '<?php echo base_url().'getVendorProducts'?>', // Replace with the actual backend endpoint
method: 'POST', // or 'GET' based on your server implementation
dataType: 'json',
data: {
vendor_id: vendorId
},
success: function(response) {
console.log(response);
productarray = response.product;
},
error: function(xhr, status, error) {
// Handle error
console.error('Error fetching product information:', error);
}
});
} else {
console.error('Make ID not found for the selected vehicle');
}
}
});
});
// Handle change event for CGST checkbox
$('#cgstCheckbox').change(function() {
if ($(this).is(":checked")) {
$('#cgstValue').removeClass('d-none');
} else {
$('#cgstValue').addClass('d-none');
<?php
$product_json = json_encode($product);
?>
$(document).ready(function() {
function validateProductAdded() {
var rowCount = $('#itemTable tbody tr').length;
if (rowCount < 1) {
toastr.warning("Please add at least one product.");
// alert("Please add at least one product.");
return false;
}
return true;
}
// Event listener for form submission
$('form').submit(function() {
return validateProductAdded();
});
var products = <?php echo $product_json; ?>;
// Function to calculate amount based on rate and quantity
function calculateAmount(row) {
var rate = $(row).find('.item-rate').val();
var quantity = $(row).find('.item-quantity').val();
var amount = rate * quantity;
$(row).find('.item-amount').val(amount);
// Retrieve CGST and SGST values from the database for the selected product
var productId = $(row).find('select[name="item_details[]"]').val();
var product = products.find(function(item) {
return item.product_id == productId;
});
var cgst = parseFloat(product.cgst);
var sgst = parseFloat(product.sgst);
// Calculate total tax by adding CGST and SGST
var tax = cgst + sgst;
$(row).find('.item-tax').val(tax.toFixed(2));
}
// Event listener for product selection
$(document).on('change', 'select[name="item_details[]"]', function() {
var productId = $(this).val();
var quantity = $(this).closest('tr').find('.item-quantity').val(0);
// Find product details from JSON
var product = products.find(function(item) {
return item.product_id == productId;
});
// Access unit price from product and set it as rate
var unitPrice = parseFloat(product.unit_price); // Convert to float if necessary
$(this).closest('tr').find('.item-rate').val(unitPrice);
// Calculate amount and update amount input field
calculateAmount($(this).closest('tr'));
});
// Event listener for quantity change
$(document).on('input', '.item-quantity', function() {
calculateAmount($(this).closest('tr'));
updateCalculations(); // Added for updating calculations when quantity changes
});
// Function to calculate subtotal
function calculateSubtotal() {
var subtotal = 0;
$('.item-amount').each(function() {
subtotal += parseFloat($(this).val()) || 0;
});
return subtotal;
}
// Function to calculate total tax
function calculateTax() {
var tax = 0;
$('.item-tax').each(function() {
var taxPercentage = parseFloat($(this).val()) || 0;
var amount = parseFloat($(this).closest('tr').find('.item-amount').val()) || 0;
var taxValue = (taxPercentage / 100) * amount; // Convert percentage to absolute value
tax += taxValue;
});
return tax;
}
// Function to calculate total discount
function calculateDiscount() {
var totalDiscount = 0;
$('.item-discount-amount').each(function(index, element) {
var discountAmount = parseFloat($(element).val()) || 0;
var discountType = $(element).closest('tr').find('.item-discount-type').val();
if (discountType === '%') {
var rate = $(element).closest('tr').find('.item-rate').val();
var quantity = $(element).closest('tr').find('.item-quantity').val();
var amount = rate * quantity;
discountAmount = amount * discountAmount / 100;
}
totalDiscount += discountAmount;
});
return totalDiscount;
}
// Function to calculate total
function calculateTotal() {
var subtotal = calculateSubtotal();
var tax = calculateTax();
var discount = calculateDiscount();
var total = subtotal + tax - discount;
// return total;
return Math.round(total);
}
// Update subtotal, tax, and total
function updateCalculations() {
$('#subtotal').val(calculateSubtotal().toFixed(2));
$('#invoicetax').val(calculateTax().toFixed(2));
$('#discount').val(calculateDiscount().toFixed(2));
$('#grandtotal').val(calculateTotal().toFixed(2));
}
// Event listener for discount change
$(document).on('input', '.item-discount-amount, .item-discount-type', function() {
updateCalculations();
});
// Calculate initial values on page load
updateCalculations();
// Event listener for "Add More Item" button
$('#addItem').click(function() {
console.log(productarray);
var newRow = '<tr>' + '<td><select class="form-control book-select SelExample" name="item_details[]" required data-toggle="select2" style="width: 249px !important;"><option value="">Select a Product</option>';
for (var i = 0; i < productarray.length; i++)
{
var product = productarray[i];
newRow += '<option value="' + product.product_id + '">' + product.product_name + '</option>';
}
newRow += '</select></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="0" name="quantity[]"/></td>' +
'<td style="width:10%;"><input type="text" class="form-control item-rate" name="unit-price[]" readonly /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" name="item-tax[]" readonly /></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-amount" name="amount[]"/></td>' +
'<td hidden><input type="hidden"></td>' +
'<td><center><i class="fa fa-trash remove-item"></i></center></td>' +
'</tr>';
$('#itemTable tbody').append(newRow);
initializeSelect2();
});
// Event listener for removing item
$(document).on('click', '.remove-item', function() {
$(this).closest('tr').remove();
updateCalculations(); // Added for updating calculations when an item is removed
});
});
</script>
<script>
// Event listener for removing item
// Event listener for removing item
$(document).on('click', '.remove-item', function() {
var purchase_order_child_id = $(this).closest('tr').find('input[name="purchase_order_child_id[]"]').val();
// AJAX request to delete the sales order product
$.ajax({
url: '<?php echo base_url()."delete_purchase_product"?>',
method: 'POST',
data: { purchase_order_child_id: purchase_order_child_id },
success: function(response) {
// Check if the deletion was successful
if (response.success) {
// If successful, remove the row from the table
$(this).closest('tr').remove();
updateCalculations(); // Update calculations after removing the row
} else {
// If not successful, display an error message
// alert('Error occurred while deleting the item.');
}
},
error: function(xhr, status, error) {
console.error('Error occurred while deleting the item:', error);
}
});
});
$(document).ready(function() {
// Event listener for customer selection change
$('.vehicle-select').change(function() {
var vehicleId = $(this).val();
if (vehicleId !== '') {
// Find the selected client in the client data
var selectedClient = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == vehicleId;
});
$('input[name="client_id"]').val(selectedClient.client_name);
$('input[name="billing_address"]').val(selectedClient.address);
$('input[name="billing_address"]').val(selectedClient.address);
$('input[name="city"]').val(selectedClient.city);
$('input[name="state"]').val(selectedClient.state);
$('input[name="country"]').val(selectedClient.country);
$('input[name="mobile_no"]').val(selectedClient.mobile_no);
$('input[name="postalcode"]').val(selectedClient.postal_code);
}
});
});
</script>
<script>
$(document).ready(function() {
// Event listener for customer selection change
$('.cleint-select').change(function() {
var clientId = $(this).val();
// console.log(vehicleId);
if (clientId !== '') {
// Find the selected client in the client data
var selectedClients = clients.find(function(client) {
return client.client_id == clientId;
});
// Populate the billing address, city, state, country, and postal code fields
$('input[id="clientMobile"]').val(selectedClients.mobile_no);
}
});
});
</script>
<script>
// Define the clients array and populate it with data
var vendors = <?php echo json_encode($vendor); ?>;
</script>
<script>
function onlyNumbers(event){
var charcode;
charcode = event.which || event.keyCode;
if(charcode>= 48 && charcode <= 57)return true;
return false;
}
</script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script>
$(document).ready(function(){
// Initialize select2
$(".SelExample").select2();
});
function initializeSelect2() {
$('.SelExample').select2({
width: '249px' // Adjust width as needed
});
}
</script>
<script>
$(document).ready(function() {
// AJAX request to save client
$('#saveVehcileBtn').click(function() {
var formType = $('#formType').val();
console.log(formType);
var reg_no = $('#reg_no').val();
var model = $('#model').val();
var make = $('#make').val();
var clientName = $('#clientName').val();
var clientMobile = $('#clientMobile').val();
var createclientName = $('#create-clientName').val();
var createclientMobile = $('#create-clientMobile').val();
var createclientType = $('#create-clientType').val();
if (formType == 'select')
{
var ifStatementCondition = "clientName !== '' && clientMobile !== '' && reg_no !== '' && model !== '' && make !== ''";
} else {
var ifStatementCondition = "createclientName !== '' && createclientMobile !== '' && createclientType !== '' && reg_no !== '' && model !== '' && make !== ''";
}
console.log(ifStatementCondition);
if( eval(ifStatementCondition) ){
// Send AJAX request to save the client
$.ajax({
url: '<?php echo base_url().'save_vehicle'?>', // URL to your save_client method
method: 'POST',
data: {
client_id: clientName,
mobile_no: clientMobile,
reg_no:reg_no,
model:model,
make:make,
createclientName:createclientName,
createclientMobile:createclientMobile,
createclientType:createclientType,
formType:formType,
},
success: function(response) {
if (response.success) {
$('#addVehicleModal').modal('hide');
toastr.success("Vehicle saved successfully!");
window.location.reload();
} else {
toastr.warning("Failed to save vehicle. Please try again");
}
},
error: function(xhr, status, error) {
console.error('Error occurred while saving vehicle:', error);
toastr.warning("Failed to save vehicle. Please try again");
}
});
}else{
toastr.warning("Please Fill All Data");
}
});
});
</script>
<script>
$(".SelExample").select2();
// Event listener for change in make select dropdown
$("#make").on('change', function() {
var selected_makes = $(this).val(); // Get an array of selected make IDs
// AJAX request to fetch models based on selected make IDs
$.ajax({
url: '<?= base_url("fetch_models") ?>', // URL to your controller method for fetching models
type: 'POST',
dataType: 'json',
data: { selected_makes: [selected_makes] },
success: function(response) {
// Clear existing options in model select dropdown
$("#model").empty();
$("#model").append('<option value=""> Select a Model </option>');
// Populate model select dropdown with fetched models
$.each(response, function(index, model) {
$("#model").append('<option value="' + model.model_id + '">' + model.model_name + '</option>');
});
// Refresh select2 to reflect changes
$("#model").trigger('change');
},
error: function(xhr, status, error) {
console.error(error); // Log any errors to the console
}
});
});
document.getElementById('reg_no').addEventListener('input', function(event) {
var inputText = event.target.value;
event.target.value = inputText.toUpperCase();
});
</script>
<script>
$(document).on('click', '#createClient', function() {
$('.create').show();
$('.select').hide();
$('#formType').val('create');
$('#clientName').val('');
$('#clientMobile').val('');
});
$(document).on('click', '#selectClient', function() {
$('.select').show();
$('.create').hide();
$('#formType').val('select');
$('#create-clientName').val('');
$('#create-clientMobile').val('');
$('#create-clientType').val('');
});
</script>
$(document).ready(function() {
// $('#vendor_id').change(function() {
// var vendor_id = $(this).val();
// $.ajax({
// url: '<?php echo base_url('get_vendor/') ?>' + vendor_id,
// type: 'GET',
// dataType: 'json',
// success: function(response) {
// if (response) {
// $('#contact_person_name').val(response.contact_person_name1);
// $('#contact_person_mobile').val(response.contact_person_mobile1);
// $('#total_price').val(response.unit_price * response.reorder_level);
// var currentDate = new Date().toISOString().split('T')[0]; // Get current date in yyyy-mm-dd format
// $('#order_date').val(currentDate);
// $('#shipping_addresss').val(response.branch.address);
// $('#shipping_state').val(response.branch.state);
// $('#shipping_city').val(response.branch.city);
// $('#shipping_postal_code').val(response.branch.postal_code);
// $('#billing_addresss').val(response.business.address);
// $('#billing_state').val(response.business.state);
// $('#billing_city').val(response.business.city);
// $('#billing_postal_code').val(response.business.postal_code);
// console.log(response.branch);
// }
// },
// error: function(xhr, status, error) {
// // Handle error
// console.error(xhr.responseText);
// }
// });
// });
});
</script>

View File

@ -28,10 +28,15 @@
<thead>
<tr>
<th>Order Number</th>
<th>Vendor Name</th>
<th>Order Date</th>
<th>Contact Person Name</th>
<th>Contact Person Mobile</th>
<th>Contact Person Mobile</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Tax</th>
<th>Total</th>
<th>Status</th>
<th>Actions</th>
</tr>
@ -41,11 +46,16 @@
<?php foreach ($purchase as $value) :
if ($value['isactive'] == 1) : ?>
<tr>
<td><?= $value['order_number']; ?></td>
<td><?= $value['vendor_name']; ?></td>
<td><?= $value['order_date']; ?></td>
<td><?= $value['contact_person_name']; ?>%</td>
<td><?= $value['contact_person_mobile']; ?>%</td>
<td><?= $value['status']; ?>%</td>
<td><?= date('j F Y', strtotime($value['order_date'])); ?></td>
<td><?= $value['contact_person_name']; ?></td>
<td><?= $value['contact_person_mobile']; ?></td>
<td><?= $value['product_count']; ?></td>
<td><?= $value['subtotal']; ?></td>
<td><?= $value['tax']; ?></td>
<td><?= $value['total']; ?></td>
<td><?= $value['status']; ?></td>
<!-- Call the model method -->
<td>

View File

@ -39,12 +39,12 @@
<input type="text" class="form-control" name="category" placeholder="Category" value="<?= isset($vendor['category']) ? $vendor['category'] : '' ?>" >
</div>
<div class="form-group col-md-4">
<div class="form-group col-md-3">
<label for="inputEmail4" class="col-form-label">GST Number<span class="text-danger">*</span></label>
<input type="text" class="form-control" name="gstnumber" placeholder="GST Number" value="<?= isset($vendor['gstnumber']) ? $vendor['gstnumber'] : '' ?>" pattern="[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[0-9]{1}[Z]{1}[0-9A-Z]{1}" title="Enter a valid GST Number">
</div>
<div class="form-group col-md-4">
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Vendor Type<span class="text-danger">*</span></label>
<select class="form-control " name="vendortype" required data-toggle="select2" >
<option value="">Select a Type</option>
@ -55,7 +55,7 @@
</select>
</div>
<div class="form-group col-md-4">
<div class="form-group col-md-6">
<label for="manufacturer" class="col-form-label">Manufacturer<span class="text-danger">*</span></label>
<select class="form-control SelExample" id="manufacturer" name="manufacturer[]" required multiple>
<option value="">Select a Manufacturer</option>