Subversion Repositories SmartDukaan

Rev

Rev 23340 | Rev 23347 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

$(function() {
        
        $(".create-order").live('click', function() {
                checkout("main-content");
        });
        
        $("form#cd input.discountAmount").live('change paste keyup mouseup', function() {
                var discountAmount = parseFloat($(this).val());
                if (isNaN(discountAmount)){
                        discountAmount = 0;
                }
                if(discountAmount < 0){
                        alert("Invalid insurance Value");
                        $(this).val(0);
                }
                calculateTotalAmount();
        });
        
        $("form#cd input.unitPrice").live('change paste keyup mouseup', function() {
                
                var unitPrice = parseFloat($(this).val());
                if (isNaN(unitPrice)){
                        unitPrice = 0;
                }
                if(unitPrice < 0){
                        alert("Invalid unit price");
                        $(this).val(0);
                }
                
                calculateTotalAmount();
        });
        
        
        $("form#cd input.insuranceAmount").live('change paste keyup mouseup', function() {
                calculateTotalAmount();
        });
        
});

$().ready(function() {
        $("form#cd input").each(function(){
                $(this).attr('autocomplete', 'off');
        });
});
$().ready(function() {
        // validate the comment form when it is submitted
        $('#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:"Please enter the name"
                        },
                        line1:{
                                required:"Please enter the address"
                        },
                        state:{
                                required: "Please select a state"
                        },
                        city:{
                                required: "Please enter the city"
                        },
                        email:{
                                require: "Please enter a valid email address"
                        },
                        pincode:{
                                required: "Please enter the pincode",
                                digits:"Please enter a valid pincode"
                        },
                        phone:{
                                required: "Please enter the phone number",
                                digits:"Please enter a valid 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;
                        }
             $.ajax({
                 type: "POST",
                 url: "create-order",
                 data: payload,
                 contentType:'application/json',
                                async: false,
                                success: function (data) {
                                        emptyBag();
                                        $('#main-content').html(data);
                                },
                                cache: false,
                                processData: false
             });
             return false; // required to block normal submit since you used ajax
         }
        });
    
        $("input.unitPrice").blur(function() {
                console.log("unitPrice blur called");
                var $element = $(this);
                var unitPrice = $element.val();
                var mopPrice = parseFloat($(this).attr('mopPrice'));
                if(parseFloat(unitPrice) < mopPrice){
                        //error = true;
                        alert("sellingPrice must be greater than equal to mop")
                        $element.addClass("border-highlight");
                }else{
                        $element.removeClass("border-highlight")
                        if(unitPrice == mopPrice){
                                $("input.discountAmount").removeAttr("readonly");
                        }
                        if(unitPrice != ''){
                            $.ajax({
                                 type: "GET",
                                 url: "insurancePrices?price="+unitPrice,
                                 //data: payload,
                                 //contentType:'application/json',
                                        async: false,
                                        success: function (data) {
                                                console.log("response : "+JSON.stringify(data));
                                                var insurancePriceMap = data.response;
                                                for(key in insurancePriceMap){
                                                        var dealerPrice = insurancePriceMap[key].dealerPrice;
                                                        var sellingPrice = insurancePriceMap[key].sellingPrice;
                                                        $element.closest('tr').find('.insuranceAmount').attr("placeholder", dealerPrice + "-" + sellingPrice);
                                                        break;
                                                }
                                        },
                                        error : function() {
                                                alert("OOPS!!!Failed to do changes.Try Again.",'ERROR');
                                        },
                                        cache: false,
                                        processData: false
                            });
                    }
                }
        }).focus(function(){
                console.log("unitPrice focus called");
                var $element = $(this);
                $element.closest('tr').find('.insuranceAmount').attr("placeholder", "");
        });
        
        $( "input.phone").blur(function() {
                console.log("phone blur called");
                var mobileNumber = $(this).val();
                writeOldCustomerDetailsByMobileNumber(mobileNumber);
        });
  
});


function orderDetailsPayload(){
        var orderObj = {};
        var priceQtyArray = [];
        var customerObj = {};
        var paymentOption = [];
        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-details").find("tr:not(:first-child)").each(function(index, el){
                //console.log(el);
                //console.log(index);
                var $el = $(el);
                var $unitPriceElement = $el.find('.unitPrice');
                var $discountAmountElement = $el.find('.discountAmount');
                
                var itemId = parseInt($unitPriceElement.attr("itemId"));
                var unitPrice = parseFloat($unitPriceElement.val());
                var qty = parseInt($unitPriceElement.attr("quantity"));
                var discountAmount = parseFloat($discountAmountElement.val());
                var mop = $discountAmountElement.attr("mop");
                var tmpObj = {'itemId':itemId,'sellingPrice':unitPrice,'quantity':qty};
                tmpObj.discountAmount = discountAmount;
                /*tmpObj['serialNumberDetails'] = [];
                var found = false;
                for(var i = 0; i < priceQtyArray.length; i++){                  
                        if (priceQtyArray[i]["itemId"] == itemId){
                                found = true;
                                break;
                        }
                }
                if(!found){
                        priceQtyArray.push(tmpObj);
                }else{
                        for(var i = 0; i < priceQtyArray.length; i++){                  
                                if (priceQtyArray[i]["itemId"] == itemId){
                                        priceQtyArray[i]["quantity"] = priceQtyArray[i]["quantity"] + 1;
                                        break;
                                }
                        }
                }
                var serialNumberDetails = getSerialNumbersFromOrder($el);
                if(serialNumberDetails != null){
                        for(var i = 0; i < priceQtyArray.length; i++){                  
                                if (priceQtyArray[i]["itemId"] == itemId){
                                        priceQtyArray[i]["serialNumberDetails"].push(serialNumberDetails);
                                        break;
                                }
                        }
                }
        });*/
                
                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-details").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 insuranceAmount = parseFloat($(el).find('.insuranceAmount').val());
                //if (priceQtyArray['fofoLineItems'][itemId] !=undefined){
                        
                //}
                //console.log($serialNumberElement.val());
                //console.log(itemId);
                for(var i = 0; i < priceQtyArray.length; i++){
                        console.log(priceQtyArray[i]["itemId"]);
                        if (priceQtyArray[i]["itemId"] == itemId){
                                if(insuranceAmount > 0){
                                        insurance = true;
                                        globalInsurance = true;
                                }else{
                                        insurance = false;
                                }
                                var serialNumberDetails = {'serialNumber':$serialNumberElement.val(),'insurance':insurance,'amount':insuranceAmount}
                                priceQtyArray[i]['serialNumberDetails'].push(serialNumberDetails);
                        }
        }
        });
        
        console.log("priceQtyArray : "+JSON.stringify(priceQtyArray));
        customerObj['firstName'] = $("form#cd input[name=firstName]").val();
        customerObj['lastName'] = $("form#cd input[name=lastName]").val();
        customerObj['mobileNumber'] = $("form#cd input[name=phone]").val(); 
        customerObj['emailId'] = $("form#cd input[name=email]").val();
        customerObj['dateOfBirth'] = $("form#cd input[name=dateOfBirth]").val();
        var customerAddress = {};
        customerAddress['name'] = $("form#cd input[name=firstName]").val() + " " + $("form#cd input[name=lastName]").val();
        customerAddress['line1'] = $("form#cd input[name=line1]").val();
        customerAddress['line2'] = $("form#cd input[name=line2]").val();
        customerAddress['landmark'] = $("form#cd input[name=landmark]").val();
        customerAddress['city'] = $("form#cd input[name=city]").val();
        customerAddress['state'] = $('select[name=state] option:selected').val();
        customerAddress['pinCode'] = $("form#cd input[name=pinCode]").val();
        customerAddress['phoneNumber'] = $("form#cd input[name=alternatePhone]").val();
        customerAddress['country'] = "India";
        customerObj['customerAddressId'] = parseInt($("form#cd input[name=phone]").attr("addressId"));
        customerObj['address'] = customerAddress; 
        console.log( JSON.stringify(customerObj));
        $("#payment-details input").each(function(){
        console.log($(this).attr('name'));
        if ($(this).attr('name') =="" ){
                return;
        }
        var paymentObj = {};
        paymentObj['type'] = $(this).attr('name');
        if ($(this).val() == ""){
                paymentObj['amount'] = 0.0;
        }
        else{
                paymentObj['amount'] = parseFloat($(this).val());
        }
        paymentOption.push(paymentObj);
        });
        console.log( JSON.stringify(paymentOption));
        
        var retObj = {};
        var dateOfBirth = $("form#cd input[name=dateOfBirth]").val();
        if(globalInsurance){
                retObj['customerDateOfBirth'] = (dateOfBirth);
        }
        retObj['fofoOrderItems'] = (priceQtyArray);
        retObj['customer'] = (customerObj);
        retObj['paymentOptions'] =  (paymentOption);
        
        console.log(retObj);
        return  JSON.stringify(retObj);
}

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 calculateTotalAmount() {
        var netPayableAmount = 0;
        $("#cd").find('tr:gt(0)').each(function(index, el){
                var rowTotal = 0;
                $tr = $(el);

                var insuranceAmount = $tr.find('.insuranceAmount').val();
                if (!insuranceAmount){
                        insuranceAmount = 0;
                }else{
                        insuranceAmount = parseFloat(insuranceAmount);
                }
                
                var qty = parseFloat($(el).find('.unitPrice').attr('quantity'));
                var unitPrice = parseFloat($(el).find('.unitPrice').val());
                
                var discountAmount =  parseFloat($(el).find('.discountAmount').val());
                if(isNaN(discountAmount)){
                        discountAmount = 0;
                }

                rowTotal = unitPrice*qty + insuranceAmount - discountAmount; 
                $tr.find('.totalPrice').val(rowTotal);
                netPayableAmount += rowTotal;
        });
        $('#cd').find('input.netPayableAmount').val(netPayableAmount);
}


function writeOldCustomerDetailsByMobileNumber(mobileNumber){
        doAjaxRequestHandler(context+"/customer/mobileNumber?mobileNumber="+mobileNumber, "GET", function(response){
                var customer = response.response;
            $('#firstName').attr('value', customer.firstName);
            $('#lastName').attr('value', customer.lastName);
            $('#email').attr('value', customer.emailId);
            //$('#phone').attr('value', customer.mobileNumber);
            $('#alternatePhone').attr('value', customer.address.phoneNumber);
            $('#line1').attr('value', customer.address.line1);
            $('#line2').attr('value', customer.address.line2);
            $('#landmark').attr('value', customer.address.landmark);
            $('#pinCode').attr('value', customer.address.pinCode);
            $('#city').attr('value', customer.address.city);
            $('#state').attr('value', customer.address.state).prop('selected',true);
            //$('#state').val(customer.address.state).prop('selected', true);
            $('#phone').attr('addressId', customer.address.id);
        });
        
}


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 unitPrice = parseFloat(input);
                var mopPrice = parseFloat($(this).attr('mopPrice'));
                if(unitPrice < mopPrice){
                        error = true;
                        alert("sellingPrice must be greater than equal to mop")
                        $(this).addClass("border-highlight");
                }
        });
        
        // checking input discountAmount is not greater than maxDiscountAmount
        $("form#cd input.discountAmount").each(function(){
                var input = $(this).val().trim();
                var mop = $(this).attr("mop");
                
                if(mop){
                        var maxDiscountPriceRangeString = $(this).attr("placeholder");
                        var maxDiscountPrice = 0;
                        if(maxDiscountPriceRangeString != undefined && maxDiscountPriceRangeString != ''){
                                maxDiscountPrice = maxDiscountPriceRangeString.substring(6);
                        }
                        $(this).removeClass("border-highlight");
                        if (!input || parseFloat(input)<0 || isNaN(input)){
                                alert("DiscountAmount value can not be lesser than 0 or invalid value");
                                error=true;
                                $(this).addClass("border-highlight");
                        }
                        if(parseFloat(input) > maxDiscountPrice){
                                alert("DiscountAmount [" + parseFloat(input) + "] value can not be greater than the suggested maxDiscountPrice [" + maxDiscountPrice + "]");
                                error=true;
                                $(this).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;
        
}