Rev 35549 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed
var customerId;function formLoaded() {$("form#cd input").each(function () {$(this).attr('autocomplete', 'off');});$('form#cd').validate({rules: {name: {required: true},email: {required: true,email: true},line1: {required: true},state: {required: true},city: {required: true},pincode: {required: true,digits: true,minlength: 6,maxlength: 6,},phone: {required: true,minlength: 10,maxlength: 10,digits: true},},messages: {name: {required: "Required"},line1: {required: "Required"},state: {required: "State required"},city: {required: "City required"},email: {require: "Required"},pincode: {required: "Required",digits: "Invalid pin"},phone: {required: "Required",digits: "Invalid number",minlength: "Number should be of 10 digits"}},submitHandler: function (form, event) {event.preventDefault();var payload = orderDetailsPayload();if (!validateOrderDetails()) {alert("Please fix highlighted errors");return false;}doPostAjaxRequestWithJsonHandler(context + "/create-order", payload, function (response) {emptyBag();$('#main-content').html(response);});return false; // required to block normal submit since you used// ajax}});$('form#newaddress').validate({rules: {firstName: {required: true},line1: {required: true},state: {required: true},city: {required: true},pinCode: {required: true,digits: true,minlength: 6,maxlength: 6,},alternatePhone: {required: true,minlength: 10,maxlength: 10,digits: true},},messages: {firstName: {required: "Required"},line1: {required: "Required"},state: {required: "State required"},city: {required: "City required"},pinCode: {required: "Required",digits: "Invalid pin"},alternatePhone: {required: "Required",digits: "Invalid number",minlength: "Number should be of 10 digits"}},submitHandler: function (form, event) {event.preventDefault();if ($(form).data('submitting')) return;$(form).data('submitting', true);let customerAddress = {};customerAddress['name'] = $("#firstName").val();customerAddress['lastName'] = $("#lastName").val();customerAddress['line1'] = $("#line1").val();customerAddress['line2'] = $("#line2").val();customerAddress['landmark'] = $("#landmark").val();customerAddress['city'] = $("#city").val();customerAddress['state'] = $('select[name=state] option:selected').val();customerAddress['pinCode'] = $("#pinCode").val();customerAddress['phoneNumber'] = $("#alternatePhone").val();customerAddress['country'] = "India";doPostAjaxRequestWithJsonHandler(`${context}/customer/address?customerId=${customerId}`, JSON.stringify(customerAddress), function (response) {$("#address-body").prepend(getAddressTr(response.response));$('#newaddressModal').modal('toggle');$("#address-body").find('a.select-address').click();$(form).data('submitting', false);});}});$("input.unitPrice").on('change', function () {var $element = $(this);var unitPrice = parseFloat($element.val());if (!isNaN(unitPrice)) {var itemType = parseFloat($(this).closest('tr').find('.serialNumber').attr("itemType"));var mopPrice = parseFloat($(this).attr('mopPrice'));var isMop = JSON.parse($(this).attr('isMop'));var dp = parseFloat($(this).attr('dp'));var mrp = parseFloat($(this).attr('mrp'));if (mrp != 0 && unitPrice > mrp) {alert("Selling Price should not be greater than MRP");$element.addClass("border-highlight");} else if (!accessoriesDeals && unitPrice < mopPrice) {alert("Selling Price must be greater than equal to MOP");$element.addClass("border-highlight");} else if (itemType == 'SERIALIZED' && unitPrice < mopPrice) {if (isMop) {alert("Selling Price must be greater than equal to MOP");$element.addClass("border-highlight");}} else if (itemType == 'NON_SERIALIZED' && unitPrice < dp) {alert("Selling Price must be greater than equal to DP");$element.addClass("border-highlight");} else {$element.removeClass("border-highlight");}// Clear insurance values if price changes$(this).closest('tr').find('.insuranceid').val("");$(this).closest('tr').find('.insuranceamount').val("0");}//calculateTotalAmount();});customerInfo = $("div.customerinfo").html();billingInfo = $("div.billinginfo").html();$("input.search-phone").change(function () {resetInputs();var mobileNumber = $(this).val();console.log(mobileNumber);if (mobileNumber.length < 10 || mobileNumber.length > 10) {alert("Mobile Number is must be 10 digits");return false;} else {writeOldCustomerDetailsByMobileNumber(mobileNumber);}});$(document).on('click', 'button.new-address-btn', function () {$('#newaddressModal').modal({show: true});});$(document).on('click', 'button.mk_add_email', function () {let customerObj = {};customerObj['customerId'] = customerId;customerObj['emailId'] = $("#emailId").val();if (validateEmail(customerObj['emailId'])) {doPostAjaxRequestWithJsonHandler(`${context}/customer/add-email`, JSON.stringify(customerObj), function (response) {alert("Email added");$("input.search-phone").val(customerObj['mobileNumber']).change();});} else {alert("Invalid email id");}});$(document).on('click', 'button.mk_add_customer', function () {customerObj = {}if ($("input.firstName").val().length == 0) {alert("First Name is required");return false;}customerObj['firstName'] = $("input.firstName").val();customerObj['lastName'] = $("input.lastName").val();customerObj['emailId'] = $("#emailId").val();console.log(customerObj['emailId']);customerObj['mobileNumber'] = $("input.phone").val();if (customerObj['emailId']) {if (!validateEmail(customerObj['emailId'])) {alert("Invalid email id");return false;}}doPostAjaxRequestWithJsonHandler(`${context}/customer/add`, JSON.stringify(customerObj), function (response) {alert("Customer added");$("input.search-phone").change();});});$(document).on('click', 'a.select-address', function () {$(this).closest('table').data("addressselected", "true").find('td').css("font-weight", "normal");$(this).closest('tr').find('td').css("font-weight", "bold");selectedAddressId = $(this).data("addressid");});$(document).on('click', 'button.btn-add-address', function () {var $btn = $(this);if ($btn.prop('disabled')) return;$btn.prop('disabled', true);$("form#newaddress").submit();setTimeout(function () {$btn.prop('disabled', false);}, 2000);});$('#newaddressModal').on('hidden.bs.modal', function () {$('form#newaddress').data('submitting', false);});}function validateOrderDetails() {var sNumbers = [];var error = false;$("form#cd input.serialNumber").each(function () {var input = $(this).val().trim();var itemType = $(this).attr("itemType");$(this).removeClass("border-highlight");if (itemType !== 'SERIALIZED') {return;}// Split multiple serial numbers by commavar serials = input.split(',').map(s => s.trim()).filter(s => s !== "");// Check for empty or duplicatefor (let sn of serials) {if (!sn || sNumbers.indexOf(sn) !== -1) {error = true;$(this).addClass("border-highlight");}sNumbers.push(sn);}});$("form#cd input.unitPrice").each(function () {var input = $(this).val().trim();$(this).removeClass("border-highlight");if (!input || parseInt(input) <= 0 || isNaN(input)) {error = true;$(this).addClass("border-highlight");}});var gstNumber = $("form#cd input[name=gstNumber]").val();$("form#cd input[name=gstNumber]").removeClass("border-highlight");if (gstNumber.length > 0 && gstNumber.length != 15) {alert("Please provide valid gstNumber");error = true;$("form#cd input[name=gstNumber]").addClass("border-highlight");}var amount = 0;var netPayableAmount = parseFloat($("form#cd input.netPayableAmount").val());$("form#cd input.amount").each(function () {if ($(this).val() == "") {$(this).val(0);}var tmpAmount = parseFloat($(this).val());amount = amount + tmpAmount;});console.log(amount);console.log(netPayableAmount);if (amount != netPayableAmount) {if (amount < netPayableAmount) {alert("[" + (netPayableAmount - amount) + "] is more required to complete the payment");} else {alert("[" + (amount - netPayableAmount) + "] is extra amount, please reduce the amount");}$("form#cd input.netPayableAmount").each(function () {$(this).addClass("border-highlight");});error = true;}if (error) {return false;}return true;}function getSerialNumbersFromOrder($el) {var $serialNumberElement = $el.find('.serialNumber');if ($serialNumberElement.val() == '') {return null;}var insuranceAmount = parseFloat($el.find('.insuranceamount').val());if (insuranceAmount > 0) {insurance = true;globalInsurace = true;} else {insurance = false;}return {'serialNumber': $serialNumberElement.val(), 'insurance': insurance, 'amount': insuranceAmount}}function orderDetailsPayload() {var priceQtyArray = [];var customerObj = {};var paymentOptionIdAmount = [];var globalInsurance = false;$("#order-items").find("tr:not(:first-child)").each(function (index, el) {console.log("el------------", el);// console.log(index);var $el = $(el);var $customerOfferItemId = $el.find('.offerSelect');var $unitPriceElement = $el.find('.unitPrice');var itemId = parseInt($unitPriceElement.attr("itemId"));var qty = parseInt($unitPriceElement.attr("quantity"));var found = false;var customSerialNumberEl = $(el).find('.customSerialNumber');let tmpObj;let filteredList = priceQtyArray.filter(x => x.itemId === itemId);if (filteredList.length === 0) {var $discountElement = $el.find('.discount');var $poiId = $el.find('.poiId');var unitPrice = parseFloat($unitPriceElement.val());var discount = parseFloat($discountElement.val());var poiId = $poiId.val();var customerOfferItemId = [];if ($customerOfferItemId && $customerOfferItemId.length > 0) {var selectedOption = $customerOfferItemId.find("option:selected");var offerIds = selectedOption.data("customeroffer-ids");if (offerIds) {customerOfferItemId = offerIds.toString().split(",").map(id => id.trim());}}if (isNaN(discount)) {discount = 0;}let customSerialNumbers = [];if (customSerialNumberEl.val() !== '') {customSerialNumbers = customSerialNumberEl.val().split(",").map(function (serial) {return serial.trim(); // Trim spaces from each serial number});if (customSerialNumbers.length !== qty) {alert("Please add all serial numbers");return false;}}tmpObj = {itemId: itemId,poiId: poiId,sellingPrice: unitPrice - discount,quantity: 0,customerOfferItemId: customerOfferItemId,discountAmount: discount,customSerialNumbers: customSerialNumberEl.val().split(","),serialNumberDetails: []};priceQtyArray.push(tmpObj);} else {tmpObj = filteredList[0];}tmpObj.quantity += qty;// Handle serial numbers and insurance per rowvar $serialNumberElement = $el.find('.serialNumber');var serialNumbers = $serialNumberElement.val()? $serialNumberElement.val().split(',').map(s => s.trim()): [];tmpObj.customSerialNumbers = serialNumbers;// Get insurance detailsvar insuranceEle = $el.find('.insuranceamount');var insuranceIds = ($el.find('.insuranceid').val() || "").split(',');var correlationIds = ($el.find('.correlationid').val() || "").split(',');var amounts = (insuranceEle.data('all-amounts') || "").toString().split(',');var ram = $el.find('.ram').val();var memory = $el.find('.memory').val();var rawDate = $el.find('.mfgdate').val();var mfgDate = rawDate ? new Date(rawDate).toISOString().split('.')[0] : "";// Map each serial number to its corresponding insurancefor (let i = 0; i < serialNumbers.length; i++) {let sn = serialNumbers[i];if (insuranceIds[i]) {for (let j = 0; j < insuranceIds.length; j++) {let serialNumberDetail = {serialNumber: sn,insurance: insuranceIds[j] || "",correlationId: correlationIds[i] || "",amount: parseFloat(amounts[j] || 0),ram: ram,memory: memory,mfgDate: mfgDate};tmpObj.serialNumberDetails.push(serialNumberDetail);}} else {let serialNumberDetail = {serialNumber: sn,insurance: insuranceIds[i] || "",correlationId: correlationIds[i] || "",amount: parseFloat(amounts[i] || 0),ram: ram,memory: memory,mfgDate: mfgDate};tmpObj.serialNumberDetails.push(serialNumberDetail);}}});customerObj['gstNumber'] = $("form#cd input[name=gstNumber]").val();if (customerId == undefined) {alert("Please choose customer");return false;}if ($("#customer-address").data("addressselected") == "true") {alert("Please select address");return false;}customerObj['customerId'] = customerId;// Check if selectedAddressId is defined and not emptyif (typeof selectedAddressId !== "undefined" && selectedAddressId !== null && selectedAddressId !== "") {customerObj['customerAddressId'] = selectedAddressId;} else {customerObj['customerAddressId'] = null;}customerObj['gender'] = $("#gender").val();customerObj['dateOfBirth'] = $("#dateOfBirth").val();var paymentOptionSize = parseInt($('#payment-option-id-amount-container').attr("paymentOptionSize"));// console.log("paymentOptionSize = "+paymentOptionSize);for (var index = 0; index < paymentOptionSize; index++) {var paymentOptionAmount = 0.0;if ($('#paymentOptionIdAmount' + index).val() != "") {paymentOptionAmount = parseFloat($('#paymentOptionIdAmount' + index).val());}var paymentOptionId = $('#paymentOptionIdAmount' + index).attr("paymentOptionId");var paymentOptionIdAmountObject = {};paymentOptionIdAmountObject['paymentOptionId'] = paymentOptionId;paymentOptionIdAmountObject['amount'] = paymentOptionAmount;paymentOptionIdAmount.push(paymentOptionIdAmountObject);}var retObj = {};retObj['fofoOrderItems'] = (priceQtyArray);retObj['customer'] = (customerObj);retObj['paymentOptions'] = (paymentOptionIdAmount);retObj['poId'] = $('#poid').val();retObj['poItemId'] = $('#poItemId').val();retObj['sendInvoiceOnWhatsApp'] = $('#sendInvoiceOnWhatsApp').is(':checked');console.log(retObj);return JSON.stringify(retObj);}function resetInputs() {$("div.customerinfo").html(customerInfo);$("div.billinginfo").html(billingInfo).hide();}function writeOldCustomerDetailsByMobileNumber(mobileNumber) {doAjaxRequestHandler(context + "/customer/mobileNumber?mobileNumber=" + mobileNumber, "GET", function (response) {if (response.response == '') {return;}var customer = response.response;if (customer == null) {$('input.phone').attr('value', mobileNumber).attr('readonly', true);$('button.mk_add_customer').show();return;}$('input.firstName').attr('value', customer.firstName).attr('readonly', true);$('input.lastName').attr('value', customer.lastName).attr('readonly', true);$('input.phone').attr('value', customer.mobileNumber).attr('readonly', true);if (customer.emailId != null && customer.emailId != '') {$('#emailId').attr('value', customer.emailId).attr('readonly', true);console.log('helo');} else {$('button.mk_add_email').show();}$('#firstName').val(customer.firstName);$('#lastName').val(customer.lastName);$('#alternatePhone').val(customer.mobileNumber);customerId = customer.customerId;$("div.billinginfo").show();trs = [];if (customer.addresses != null) {for (address of customer.addresses) {if (pendingPO != null) {if (pendingPO.customerAddressId == address.id) {trs.push(getAddressTr(address));}} else {trs.push(getAddressTr(address));}}}$("#address-body").html(trs.join(""));});}function getAddressTr(address) {var tr = [];tr.push(`<tr><td>${address.name} ${address.lastName}</td>`);tr.push(`<td>${address.line1}, ${address.line2}</td>`);tr.push(`<td>${address.city}</td>`);tr.push(`<td>${address.state}</td>`);tr.push(`<td>${address.pinCode}</td>`);tr.push(`<td>${address.phoneNumber}</td>`);tr.push(`<td><a class="select-address" href="javascript:void(0);" data-addressid="${address.id}">Select address</a></td></tr>`);return tr.join("");}function validateEmail(email) {const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;return re.test(String(email).toLowerCase());}function sendInvoiceOnWApp(orderId){let whatsAppMobile = $('#whatsApp-invoice-number').val();if(!whatsAppMobile){alert('Please enter valid whatsApp number');return;}if(whatsAppMobile.length<10){alert('Mobile number must be at least 10 digits');return;}if(confirm('Are you sure you want to send invoice on whatsApp?')){doPutAjaxRequestHandler(`${context}/sendInvoiceOnWhatsApp?orderId=${orderId}&whatsAppMobile=${whatsAppMobile}`, function (response) {console.log("sendInvoiceOnWhatsApp res - ",response);if(response){alert('Invoice send successfully on whatsApp');}});}else {return;}}