Subversion Repositories SmartDukaan

Rev

Rev 27754 | Rev 28479 | Go to most recent revision | 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
                }
        });

        $("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 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) {
                                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) {
                        return;
                }
                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();
                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 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";
                console.log(customerAddress);
                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();
                });
        });

}
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 (sNumbers.indexOf(input) != -1 || (itemType === 'SERIALIZED' && !input)) {
                        error = true;
                        $(this).addClass("border-highlight");
                }
                sNumbers.push(input);
        });

        $("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 orderObj = {};
        var priceQtyArray = [];
        var customerObj = {};
        var paymentOptionIdAmount = [];
        var globalInsurance = false;

        $("form#cd input.serialNumber").each(function() {
                var itemId = parseInt($(this).attr("itemId"));
                if (orderObj.hasOwnProperty('fofoOrderItems')) {
                        var itemDetails = orderObj['fofoOrderItems'];
                        if (itemDetails.hasOwnProperty(itemId)) {
                                var serialNumbers = itemDetails[itemId];
                                serialNumbers.push($(this).val());
                                itemDetails[itemId] = serialNumbers;
                        } else {
                                var serialNumbers = [];
                                serialNumbers.push($(this).val());
                                itemDetails[itemId] = serialNumbers;
                        }
                } else {
                        var serialNumbers = [];
                        serialNumbers.push($(this).val());
                        var tmp = {};
                        tmp[itemId] = serialNumbers;
                        orderObj['fofoOrderItems'] = tmp;
                }
        });
        console.log(JSON.stringify(orderObj));
        $("#order-items").find("tr:not(:first-child)").each(function(index, el) {
                // console.log(el);
                // console.log(index);
                var $el = $(el);
                var $unitPriceElement = $el.find('.unitPrice');

                var itemId = parseInt($unitPriceElement.attr("itemId"));
                var unitPrice = parseFloat($unitPriceElement.val());
                var qty = parseInt($unitPriceElement.attr("quantity"));
                var tmpObj = { 'itemId': itemId, 'sellingPrice': unitPrice, 'quantity': qty };

                if (orderObj['fofoOrderItems'][itemId] === undefined) {
                        tmpObj['serialNumberDetails'] = [];
                } else {
                        // tmpObj['serialNumbers'] = orderObj['fofoLineItems'][itemId];
                        tmpObj['serialNumberDetails'] = [];
                }
                var found = false;
                for (var i = 0; i < priceQtyArray.length; i++) {
                        if (priceQtyArray[i]["itemId"] == itemId) {
                                priceQtyArray[i]["quantity"] = priceQtyArray[i]["quantity"] + 1;
                                found = true;
                                break;
                        }
                }
                if (!found) {
                        priceQtyArray.push(tmpObj);
                }
        });

        $("#order-items").find("tr:not(:first-child)").each(function(index, el) {
                // console.log(el);
                // console.log(index);
                var $serialNumberElement = $(el).find('.serialNumber');
                var itemId = parseInt($serialNumberElement.attr("itemId"));
                var insuranceEle = $(el).find('.insuranceamount');
                var insuranceAmount = 0;
                if (insuranceEle.length > 0) {
                        insuranceAmount = parseFloat(insuranceEle.val());
                }
                var insuranceId = "";
                if (insuranceAmount > 0) {
                        insuranceId = $(el).find('.insuranceid').val();
                }
                var ram = $(el).find('.ram').val();
                var memory = $(el).find('.memory').val();
                var mfgdate = $(el).find('.mfgdate').val();
                var serialNumberDetails = {
                        'serialNumber': $serialNumberElement.val(), 'insurance': insuranceId, 'amount': insuranceAmount,
                        'ram': ram, 'memory': memory, 'mfgDate': mfgdate
                };
                priceQtyArray[index]['serialNumberDetails'].push(serialNumberDetails);

        });

        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;
        customerObj['customerAddressId'] = selectedAddressId;
        customerObj['gender'] = $("#gender").val();
        customerObj['dateOfBirth'] = startDate;


        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();

        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').attr('value', customer.firstName);
                $('#lastName').attr('value', customer.lastName);
                $('#alternatePhone').attr('value', 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());
}