the_mechanic/app/Views/sales_order_form.php
venba-Inspriron-3558 3a2456b629 FIX_minor Bugs
2025-11-13 17:54:23 +05:30

1228 lines
56 KiB
PHP
Executable File

<?php include('layout/header.php'); ?>
<style>
.fixed-dropdown-container {
/* position: fixed; */
/* top: 50px; Adjust as needed */
/* left: 50px; Adjust as needed */
width: 300px; /* Adjust as needed */
}
.form-control{
padding: 5px !important;
}
</style>
<div class="row">
<div class="col-12">
<div class="page-title-box page-title-box-alt">
<h4 class="page-title"><?php echo $page_name?></h4>
<div class="page-title-right">
<a href="<?= base_url() . "sales_order_index"; ?>" class="btn btn-secondary waves-effect">Cancel</a>
<ol class="breadcrumb m-0">
</li>
<!-- <li class="breadcrumb-item"><a href="javascript: void(0);">Tables</a></li>
<li class="breadcrumb-item active">Datatables</li> -->
</ol>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<form action="<?= base_url() . "add_sales"; ?>" method="post" style="line-height:0.5;" id="salesForm">
<!-- <h4 class="header-title">Sales Order Details :</h4><br> -->
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4" class="col-form-label">Vehicle<span
class="text-danger">*</span></label>
<?= isset($sales['vehicle_id']) ? '' : '<i type="button" class="fe-plus-circle" id="addVehicleModalButton" style="font-size: 18px;" data-toggle="modal" data-target="#addVehicleModal" title="Add Vehicle"></i>' ?>
<select class="form-control vehicle-select SelExample" name="vehicle_id" id="vehicle_id"
<?= isset($sales['vehicle_id']) ? 'disabled' : 'required="true"' ?>>
<?= isset($sales['vehicle_id']) ? '' : '<option value="">Select a vehicle</option>' ?>
<?php foreach ($vehicle as $value) : ?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["vehicle_id"] ?>"
<?= isset($sales['vehicle_id']) && $sales['vehicle_id'] == $value["vehicle_id"] ? 'selected' : '' ?>>
<?= $value["reg_no"]?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4" class="col-form-label">Make and Model</label>
<input type="text" class="form-control" id="makeAndModel" readonly>
</div>
<div class="form-group col-md-4">
<label for="inputPassword4" class="col-form-label">Client Name<span
class="text-danger"></span></label>
<input type="text" class="form-control" name="client_id" placeholder="Client"
value="<?= isset($sales['client_name']) ? $sales['client_name'] : '' ?>" readonly>
</div>
<div class="form-group col-md-4">
<label for="inputPassword4" class="col-form-label">Mobile No<span
class="text-danger">*</span></label>
<input type="text" class="form-control" name="mobile_no" placeholder="Mobile"
value="<?= isset($sales['mobile_no']) ? $sales['mobile_no'] : '' ?>" maxlength="16"
minlength="6" onkeypress="return onlyNumbers(event)" readonly>
</div>
<div class="form-group col-md-4">
<label for="inputPassword4" class="col-form-label">Status
<?php if (isset($sales['status']) && $sales['status'] !== ''): ?>
<?php echo "( ". $sales['status']." )"; ?>
<?php endif; ?></label>
<select class="form-control status-select status_class_for_change" name="status" data-toggle="select2" >
<?php if (isset($sales['status'])): ?>
<?php if ($sales['status'] === 'Cancelled'): ?>
<option value="Draft" <?= $sales['status'] === 'Draft' ? 'selected' : '' ?> >Draft </option>
<option value="Approved" <?= $sales['status'] === 'Approved' ? 'selected' : '' ?>>Approved</option>
<?php else: ?>
<option value>Select Status</option>
<option value="Approved" <?= $sales['status'] === 'Approved' ? 'selected' : '' ?>>Approved</option>
<option value="Cancelled" <?= $sales['status'] === 'Cancelled' ? 'selected' : '' ?>>Cancelled</option>
<?php endif; ?>
<?php else: ?>
<option value="Draft" selected>Draft</option>
<?php endif; ?>
</select>
</div>
<?php if (isset($sales['status']) && $sales['status'] !== ''): ?>
<div class="form-group col-md-4" id="mode_of_payment_parent_div_id" <?= $sales['status'] === 'Approved' ? '' : 'style="display:none;"' ?>>
<label for="mode_of_payment" class="col-form-label">Mode Of Payment<span class="text-danger">*</span>
<select class="form-control" name="mode_of_payment" id="mode_of_payment" >
<option value>Select Mode Of Payment</option>
<option value="online" <?= $sales['mode_of_payment'] === 'online' ? 'selected' : '' ?> >Online</option>
<option value="cash" <?= $sales['mode_of_payment'] === 'cash' ? 'selected' : '' ?>>Cash</option>
</select>
</div>
<?php endif; ?>
</div>
<!-- <h4 class="header-title">Billing Address Details :</h4><br> -->
<div class="form-row">
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Address<span class="text-danger"></span></label>
<textarea class="form-control" name="billing_address" placeholder="Address"><?= isset($sales['billing_address']) ? $sales['billing_address'] : '' ?></textarea>
</div>
<input type="hidden" id="sales_order_id" name="sales_order_id"
value="<?= isset($sales['sales_order_id']) ? $sales['sales_order_id'] : '' ?>" readonly>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">City<span
class="text-danger"></span></label>
<input type="text" class="form-control" name="city" placeholder="City"
value="<?= isset($sales['billing_city']) ? $sales['billing_city'] : 'Chennai' ?>">
</div>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">State<span
class="text-danger"></span></label>
<input type="text" class="form-control" name="state" placeholder="State"
value="<?= isset($sales['billing_state']) ? $sales['billing_state'] : 'Tamil Nadu' ?>">
</div>
<div class="form-group col-md-3">
<label for="inputPassword4" class="col-form-label">Pin Code<span
class="text-danger"></span></label>
<input type="text" class="form-control" name="postalcode" placeholder="Pin Code"
value="<?= isset($sales['billing_postal_code']) ? $sales['billing_postal_code'] : '' ?>"
maxlength="6" minlength="6">
</div>
<div class="form-group col-md-4" style="display: flex;align-items: center; gap: 8px;">
<input class="form-check-input" type="checkbox" name="update_client_address" style=" margin: 0;">
<label class="form-check-label" for="flexCheckDefault" style=" margin: 0;padding-left: 20px;">
Update client address
</label>
</div>
</div>
<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>Rate</th>
<th>Qty</th>
<th>Amt</th>
<th>Tax</th>
<th>Tax Amt</th>
<!-- <th style="text-align: center !important" colspan="2">Discount</th> -->
<th>Tot Amt</th>
<th hidden></th>
<th></th>
</tr>
</thead>
<tbody>
<!-- Dynamically add rows for item details -->
<?php if (isset($sales_product) && !empty($sales_product)) : ?>
<?php foreach ($sales_product as $salechild) :
if ($salechild['isactive'] == 1) : ?>
<tr>
<td style="width:30%;" class="fixed-dropdown-container">
<input type="hidden" name="product_names_id[]" value="<?= isset($salechild['product_names_id']) ? $salechild['product_names_id'] : '' ?>">
<select class="form-control book-select SelExample" name="item_details[]"
required data-toggle="select2" id="" style="width: 249px !important;" onchange="addProductNamesId(this)">
<option value="">Select a Product</option>
<?php foreach ($product as $value) : ?>
<?php if ($value['per'] == 'ml') {
$value_ml = ' ('.$value['ml'].$value['per'].')';
} else {
$value_ml = '';
}
?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["product_id"] ?>"
<?= isset($salechild['product_id']) && $salechild['product_id'] == $value["product_id"] ? 'selected' : '' ?>>
<?= $value["product_name"].$value_ml.($value["manufacturer_name"] ? ' - '.$value["manufacturer_name"] : ''); ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</td>
<td style="width:12%;">
<input type="text" class="form-control item-rate" name="unit-price[]"
readonly
value="<?= isset($salechild['net_price']) ? $salechild['net_price'] : '' ?>">
</td>
<td style="width:10%;">
<input type="number" class="form-control item-quantity" name="quantity[]"
min="0"
value="<?= isset($salechild['qty']) ? $salechild['qty'] : '1' ?>" onchange="updateThirdColumnValue(this); updateTaxAmount(this)" onkeydown="return false;">
</td>
<td style="width:14%;">
<?php if (isset($salechild['net_price']) && isset($salechild['qty'])) {
$result = $salechild['net_price'] * $salechild['qty'];
echo '<input type="text" class="form-control item-result" value="' . $result . '" readonly>';
} ?>
</td>
<td style="width:8%;">
<input type="text" class="form-control item-tax" name="item-tax[]"
value="<?= isset($salechild['tax']) ? $salechild['tax'] : '' ?>" onchange="updateTaxAmount(this)" readonly>
</td>
<td style="width:13%;">
<?php if (isset($salechild['tax']) && isset($result) ) {
$tax_amount= $result * $salechild['tax'] / 100;
} else {
$tax_amount=0 ;
}
?>
<input type="text" class="form-control tax-amount" name="tax-amount[]" value="<?= number_format($tax_amount,2); ?>" readonly>
</td>
<!-- <td style="width:12%;">
<input type="number" class="form-control item-discount-amount" min="0" name="discount_amount[]" value="<?= isset($salechild['discount']) ? $salechild['discount'] : '' ?>">
</td>
<td style="width:10%;">
<select class="form-control item-discount-type" name="discount_type[]">
<option value="₹" <?= isset($salechild['discount_type']) && $salechild['discount_type'] == '₹' ? 'selected' : '' ?>>₹</option>
<option value="%" <?= isset($salechild['discount_type']) && $salechild['discount_type'] == '%' ? 'selected' : '' ?>>%</option>
</select>
</td> -->
<td style="width:13%;">
<input type="text" class="form-control item-amount" name="amount[]"
value="<?= isset($salechild['amount']) ? $salechild['amount'] : '' ?>" >
</td>
<td hidden><input type="hidden"
value="<?= isset($salechild['sales_order_product_id']) ? $salechild['sales_order_product_id'] : '' ?>"
name="sales_order_product_id[]"></td>
<td style="width:7%;">
<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">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>
<?php if (!isset($sales['status']) || $sales['status'] !== 'Approved') : ?>
<button type="submit" id="editaddbutton" class="btn btn-primary" style="float:right;">Submit</button>
<?php endif; ?>
</form>
</div>
</div>
</div>
</div>
<?php include('layout/footer.php'); ?>
</div>
<div class="modal fade" id="addVehicleModal" tabindex="-1" role="dialog" aria-labelledby="addVehicleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addVehicleModalLabel">Add New Vehicle</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-row">
<div class="form-group col-md-6">
<!-- <div class="form-group"> -->
<label for="inputPassword4" class="col-form-label">Make</label>
<select class="form-control SelExample" name="make" id="make"
<?= isset($vehicle['make']) ? '' : 'required' ?>>
<?= isset($vehicle['make']) ? '' : '<option value="">Select a Make</option>' ?>
<?php foreach ($makeData as $value) : ?>
<?php if ((int)$value["isactive"] === 1) : ?>
<option value="<?= $value["make_id"] ?>"
<?= isset($vehicle['make']) && $vehicle['make'] == $value["make_id"] ? 'selected' : '' ?>>
<?= $value["make"]; ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-6">
<label for="inputPassword4" class="col-form-label">Model</label>
<select class="form-control SelExample" name="model" id="model"
<?= isset($vehicle['model']) ? '' : 'required' ?>>
<?php if (isset($vehicle["model_name"])) : ?>
<option value="<?= $vehicle["model"] ?>">
<?= $vehicle["model_name"]; ?>
</option>
<?php endif; ?>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputPassword4" class="col-form-label">Reg Number</label>
<input type="text" class="form-control" name="reg_no" id="reg_no" placeholder="Reg Number"
value="<?= isset($vehicle['reg_no']) ? $vehicle['reg_no'] : '' ?>" required>
</div>
</div>
<div class="form-row">
<input type="text" value="select" id="formType" hidden>
<div class="form-group col-md-12 select">
<label for="clientName">Client Name</label>
<i type="button" class="fe-user-plus" id="createClient" style="font-size: 18px;"></i>
<select class="form-control cleint-select SelExample" id="clientName" required>
<option value="">Select a Client</option>
<?php foreach ($client as $value) : ?>
<option value="<?= $value["client_id"] ?>">
<?= $value["client_name"]; ?> <!-- $value["mobile_no"] .' - '. $value["client_name"]; -->
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-12 select">
<label for="clientMobile">Mobile</label>
<input type="text" class="form-control" id="clientMobile" placeholder="Enter mobile number"
maxlength="16" minlength="6" onkeypress="return onlyNumbers(event)" required>
</div>
<div class="form-group col-md-12 create" style="display:none;">
<label for="create-clientName">Client Name</label>
<i type="button" class="fe-user-check" id="selectClient" style="font-size: 18px;"></i>
<input type="text" class="form-control" id="create-clientName"
placeholder="Enter client name" required>
</div>
<div class="form-group col-md-6 create" style="display:none;">
<label for="create-clientMobile">Mobile</label>
<input type="text" class="form-control" id="create-clientMobile"
placeholder="Enter mobile number" maxlength="16" minlength="6"
onkeypress="return onlyNumbers(event)" required>
</div>
<div class="form-group col-md-6 create" style="display:none;">
<label for="create-clientType">Client Type</label>
<select class="form-control status-select" id="create-clientType" required>
<option value="">Select a Type</option>
<option value="Direct">Direct</option>
<option value="Mechanic">Mechanic</option>
<option value="Exp">Exp</option>
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="saveVehcileBtn">Save Vehicle</button>
</div>
</div>
</div>
</div>
<script>
productarray = [];
$(document).ready(function() {
// Event listener for vehicle selection change
$('.vehicle-select').change(function() {
var vehicleId = $(this).val();
console.log("**");
console.log(vehicleId);
$('input[id="makeAndModel"],input[name="client_id"], input[name="client_name"], textarea[name="billing_address"], input[name="city"], input[name="state"], input[name="country"], input[name="mobile_no"], input[name="email"], input[name="postalcode"]').val('');
if (vehicleId !== '') {
// Find the selected vehicle
var selectedVehicle = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == vehicleId;
});
// Extract makeId and modelId from the selected vehicle
var makeId = selectedVehicle.make;
var modelId = selectedVehicle.model;
// Fetch make and model information
fetchMakeAndModel(makeId, modelId);
}
});
// Edit scenario: Populate make and model based on stored vehicle ID
var storedVehicleId = "<?php echo isset($sales['vehicle_id']) ? $sales['vehicle_id'] : ''; ?>";
if (storedVehicleId !== '') {
// Find the selected vehicle from the vehicles array
var selectedVehicle = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == storedVehicleId;
});
// Extract makeId and modelId from the selected vehicle
var makeId = selectedVehicle.make;
var modelId = selectedVehicle.model;
// Fetch make and model information
fetchMakeAndModel(makeId, modelId);
}
});
<?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) {
// 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);
var tax = cgst + sgst;
$(row).find('.item-tax').val(tax);
var rate = $(row).find('.item-rate').val();
var quantity = $(row).find('.item-quantity').val();
var amount = rate * quantity;
var taxamount = amount * tax / 100;
$(row).find('.tax-amount').val(parseFloat(taxamount).toFixed(2));
var finalamt = amount + taxamount;
$(row).find('.item-amount').val(parseFloat(finalamt).toFixed(2));
}
function calculateTotalAmount(row) {
// 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);
var tax = cgst + sgst;
var quantity = $(row).find('.item-quantity').val();
var final_amount = $(row).find('.item-amount').val();
var taxRate = tax/100;
// console.log(taxRate);
var amt = final_amount/((1+taxRate));
// console.log(amt);
$(row).find('.item-result').val(parseFloat(amt).toFixed(2));
var taxAmount = final_amount-amt;
// console.log(taxAmount);
$(row).find('.tax-amount').val(parseFloat(taxAmount).toFixed(2));
var rate = amt / quantity;
// console.log(rate);
$(row).find('.item-rate').val(parseFloat(rate).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(1);
if(productId == 0){
$(this).closest('tr').find('.item-quantity').prop('readonly', true);
// $(this).closest('tr').find('.item-amount').prop('readonly', false);
}
// Find product details from JSON
var product = products.find(function(item) {
return item.product_id == productId;
});
console.log(product);
var cgst = parseInt(product.cgst);
var sgst = parseInt(product.sgst);
var totalTax = cgst + sgst;
var total_tax_amount = product.unit_price * totalTax / 100;
var total_tax_amount = parseFloat(total_tax_amount).toFixed(2);
$(this).closest('tr').find('.item-quantity').attr('max', product.qty_stock);
// Access unit price from product and set it as rate
var unitPrice = parseFloat(product.unit_price).toFixed(2);
$(this).closest('tr').find('.item-rate').val(unitPrice);
$(this).closest('tr').find('.item-result').val(unitPrice);
$(this).closest('tr').find('.tax-amount').val(total_tax_amount);
// Calculate amount and update amount input field
calculateAmount($(this).closest('tr'));
updateCalculations();
});
$(document).on('keyup', '.item-amount', function()
{
// var total_amount = $(this).val();
// var totalTax = $(this).closest('tr').find('.item-tax').val();
// var unitPrice = total_amount / parseFloat((totalTax / 100) + 1);
// var unitPrice = parseFloat(unitPrice).toFixed(2);
// var taxAmt = total_amount - unitPrice;
// var taxAmt = parseFloat(taxAmt).toFixed(2)
// $(this).closest('tr').find('.tax-amount').val(taxAmt);
// $(this).closest('tr').find('.item-rate').val(unitPrice);
// $(this).closest('tr').find('.item-result').val(unitPrice);
calculateTotalAmount($(this).closest('tr'));
updateCalculations();
});
// 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;
var value1 = $(this).val();
var qty = $(this).parent().parent().find('.item-quantity').val();
var rate = $(this).parent().parent().find('.item-rate').val();
// console.log(value1);
// console.log(value2);
subtotal += qty * rate;
});
return subtotal;
}
// Function to calculate total tax
function calculateTax() {
var tax = 0;
$('.item-tax').each(function() {
var taxPercentage = parseFloat($(this).val()) || 0;
// console.log(taxPercentage);
var amount = parseFloat($(this).closest('tr').find('.item-amount').val()) || 0;
// console.log(amount);
var qty = parseFloat($(this).closest('tr').find('.item-quantity').val()) || 0;
// console.log(qty);
var rate = parseFloat($(this).closest('tr').find('.item-rate').val()) || 0;
var taxamount = rate * qty;
// console.log(taxamount);
var taxValue = (taxPercentage / 100) * taxamount; // 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 total_tax_amount = $('#invoicetax').val();
// console.log(total_tax_amount + parseInt(subtotal));
var discount = calculateDiscount();
var total = parseFloat(total_tax_amount) + parseFloat(subtotal) - 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() {
selected_pr = [];
$('tr .form-control.book-select.SelExample.select2-hidden-accessible').each(function() {
var rowProductid = $(this).val();
selected_pr.push(rowProductid);
});
console.log(productarray);
if(productarray == 'No Product'){
toastr.warning("First Add the Product!");
}else if (productarray.length > 0) {
var newRow = '<tr>' +
`<td style="width:30%" class="fixed-dropdown-container">
<input type="hidden" name="product_names_id[]">
<select class="form-control book-select SelExample" name="item_details[]" required data-toggle="select2" style="width: 2px !important;" onchange="addProductNamesId(this)">
<option value="">Select a Product</option>`;
for (var i = 0; i < productarray.length; i++) {
var product = productarray[i];
// console.log("product",product);
var value_ml = '';
if (product.per === 'ml') {
value_ml = " (" + product.ml + product.per + ")";
}
if (!selected_pr.includes(product.product_id)) {
newRow += '<option value="' + product.product_id + '">' +
product.product_name + value_ml +
(product.manufacturer_name ? ' - ' + product.manufacturer_name : '') +
'</option>';
}
}
newRow += '</select></td>' +
'<td style="width:12%;"><input type="text" class="form-control item-rate" name="unit-price[]" readonly /></td>' +
'<td style="width:10%;"><input type="number" class="form-control item-quantity" min="1" max="" name="quantity[]" onchange="updateThirdColumnValue(this); updateTaxAmount(this)" onkeydown="return false;" /></td>' +
'<td style="width:14%;"><input type="text" class="form-control item-result" readonly /></td>' +
'<td style="width:8%;"><input type="text" class="form-control item-tax" name="item-tax[]" readonly /></td>' +
'<td style="width:13%;"><input type="text" class="form-control tax-amount" name="tax-amount[]" readonly /></td>' +
'<td style="width:13%;"><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();
updateCalculations();
initializeRowCalculations(row);
}else{
toastr.warning("First Choose the Vehicle!");
}
});
// 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
});
});
function initializeRowCalculations(row) {
calculateAmount(row);
updateCalculations();
}
</script>
<script>
// Event listener for removing item
// Event listener for removing item
$(document).on('click', '.remove-item', function() {
var salesOrderProductId = $(this).closest('tr').find('input[name="sales_order_product_id[]"]').val();
// AJAX request to delete the sales order product
$.ajax({
url: '<?php echo base_url()."delete_sales_product"?>',
method: 'POST',
data: {
sales_order_product_id: salesOrderProductId
},
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() {
$('tbody').empty();
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;
});
console.log(":( ",selectedClient);// sad
$('input[name="client_id"]').val(selectedClient.client_name);
$('textarea[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 vehicles = <?php echo json_encode($vehicle); ?>;
var clients = <?php echo json_encode($client); ?>;
</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({
// dropdownParent: $('.fixed-dropdown-container')
});
});
function initializeSelect2() {
$('.SelExample').select2({
// dropdownParent: $('.fixed-dropdown-container'),
width: '150px'
});
}
</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 !== ''";
}
const button = $('#saveVehcileBtn');
button.prop('disabled', true).text('Processing...');
if (reg_no) {
$.ajax({
url: '<?= base_url("checkRegisterNo") ?>', // URL to your controller method for fetching models
type: 'POST',
dataType: 'json',
data: { register_number: reg_no },
success: function(response) {
if (response) {
$('#reg_no').val("");
toastr.warning("Register Number Already Added!");
button.prop('disabled', false).text('Save Vehicle');
}else{
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 && response.code == 200 ) {
toastr.success("Vehicle saved successfully!");
localStorage.setItem('vehicle_id',response.vehicle_id);
$('#addVehicleModal').modal('hide');
window.location.reload();
}else if (response.success && response.code == 404 ) {
$('#'+response.field).val("");
toastr.warning(response.message);
button.prop('disabled', false).text('Save Vehicle');
}else {
toastr.warning("Failed to save vehicle. Please try again");
button.prop('disabled', false).text('Save Vehicle');
}
},
error: function(xhr, status, error) {
console.error('Error occurred while saving vehicle:', error);
toastr.warning("Failed to save vehicle. Please try again");
button.prop('disabled', false).text('Save Vehicle');
}
});
} else {
toastr.warning("Please Fill All Data");
button.prop('disabled', false).text('Save Vehicle');
}
}
},
error: function(xhr, status, error) {
console.error(error); // Log any errors to the console
button.prop('disabled', false).text('Save Vehicle');
}
});
}
});
});
</script>
<script>
$(".SelExample").select2({
// dropdownParent: $('.fixed-dropdown-container')
});
// 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('');
// $('.select2-selection__rendered').html('');
$('#clientMobile').val('');
});
$(document).on('click', '#selectClient', function() {
$('.select').show();
$('.create').hide();
$('#formType').val('select');
$('#create-clientName').val('');
$('#create-clientMobile').val('');
$('#create-clientType').val('');
});
</script>
<style>
.select2-container--default .select2-results__option--highlighted[aria-selected] {
color: #ffffff;
background: #526dee !important;
}
.select2-container .select2-selection--single {
height: 36px;
border: 1px solid #ced4da;
}
.select2-container--default .select2-selection--single .select2-selection__rendered {
line-height: 36px;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
top: 4px;
}
</style>
<script>
// Assuming you have an edit button with an ID 'editButton'
$('#editaddbutton').click(function() {
// Enable the vendor dropdown
$('#vehicle_id').prop('disabled', false);
});
$('.status_class_for_change').change(function (params) {
if($(this).val() === 'Approved'){
$('#mode_of_payment_parent_div_id').css('display','');
$('#mode_of_payment').prop('required','required');
}else{
$('#mode_of_payment_parent_div_id').css('display','none');
$('#mode_of_payment').removeAttr('required');
}
})
</script>
<script>
function updateThirdColumnValue(input) {
const itemRate = parseFloat(input.parentNode.previousElementSibling.querySelector('.item-rate').value);
const quantity = parseFloat(input.value);
const result = itemRate * quantity;
finalValue = parseFloat(result).toFixed(2)
input.parentNode.nextElementSibling.querySelector('.item-result').value = finalValue;
// After updating the third column, also update tax amount
//updateTaxAmount(input);
}
function updateTaxAmount(input) {
const row = input.closest('tr');
const itemResult = parseFloat(row.querySelector('.item-result').value);
const taxValue = parseFloat(row.querySelector('.item-tax').value);
const taxAmount = itemResult * taxValue / 100;
row.querySelector('[name="tax-amount[]"]').value = parseFloat(taxAmount).toFixed(2); // Ensure two decimal places
}
$(window).on('load', function() {
var vehicle_id = localStorage.getItem('vehicle_id');
if (vehicle_id) {
$('#vehicle_id').val(vehicle_id).trigger('change');
localStorage.removeItem('vehicle_id');
$('input[id="makeAndModel"], input[name="client_id"], textarea[name="billing_address"], input[name="city"], input[name="state"], input[name="country"], input[name="mobile_no"], input[name="email"], input[name="postalcode"]').val('');
// Find the selected vehicle details
var selectedVehicle = vehicles.find(function(vehicle) {
return vehicle.vehicle_id == vehicle_id;
});
if (selectedVehicle) {
var makeId = selectedVehicle.make;
var modelId = selectedVehicle.model;
fetchMakeAndModel(makeId, modelId);
// Fill client & vehicle info fields
$('input[name="client_id"]').val(selectedVehicle.client_id);
$('textarea[name="billing_address"]').val(selectedVehicle.address);
// $('input[name="billing_address"]').val(selectedClient.address);
$('input[name="city"]').val(selectedVehicle.city);
$('input[name="state"]').val(selectedVehicle.state);
$('input[name="country"]').val(selectedVehicle.country);
$('input[name="mobile_no"]').val(selectedVehicle.mobile_no);
$('input[name="email"]').val(selectedVehicle.email);
$('input[name="postalcode"]').val(selectedVehicle.postal_code);
} else {
console.warn("⚠️ Vehicle not found in 'vehicles' list for ID:", vehicle_id);
}
}
});
function fetchMakeAndModel(makeId, modelId) {
console.log("*************************");
// Make sure makeId and modelId are valid
if (makeId !== '' && modelId !== '') {
// Perform AJAX request to fetch product information
$.ajax({
url: '<?php echo base_url().'getProducts'?>', // Replace with the actual backend endpoint
method: 'POST', // or 'GET' based on your server implementation
dataType: 'json',
data: {
make_id: makeId,
model_id: modelId,
general: 1
},
success: function(response) {
// console.log(response);
// Populate make and model in the input field
var makeAndModel = response.makeName + ' - ' + response.modelName;
$('#makeAndModel').val(makeAndModel);
if(response.product.length){
productarray = response.product;
}else{
productarray = "No Product";
}
},
error: function(xhr, status, error) {
// Handle error
console.error('Error fetching product information:', error);
}
});
} else {
productarray = [];
console.error('Make ID or Model ID not found for the selected vehicle');
}
}
</script>
<!-- script for set the product name id -->
<script>
function addProductNamesId(selectElement) {
if (!selectElement) return; // safety
// var product_names_id = $(selectElement).find('option:selected').attr('data-id');
// $(selectElement).closest('tr').find('input[name="product_names_id[]"]').val(product_names_id);
}
// Prevent multiple submissions by disabling the button on first click
document.querySelector('#salesForm').addEventListener('submit', function (e) {
const submitButton = this.querySelector('button[type="submit"]');
submitButton.disabled = true; // Disable the button
submitButton.textContent = 'Processing...'; // Optional: Show loading text
});
</script>