Subversion Repositories SmartDukaan

Rev

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

$().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;
                        }
                        doAjaxRequestWithJsonHandler(context+"/create-order", "POST", payload, function(response){
                                emptyBag();
                                $('#main-content').html(response);
                        });
            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 != ''){
                                doAjaxRequestHandler(context+"/insurancePrices?price="+unitPrice, "GET", function(response){
                                        console.log("response : "+JSON.stringify(response));
                                        var insurancePriceMap = response.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;
                                        }
                                });
                    }
                }
        }).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();
                if(mobileNumber.length < 10) {
                        return;
                }
                writeOldCustomerDetailsByMobileNumber(mobileNumber);
        });
  
});


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 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-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['gstNumber'] = $("form#cd input[name=gstNumber]").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));
                
                
                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);
                }
                
                console.log( JSON.stringify(paymentOptionIdAmount));
                
                var retObj = {};
                var dateOfBirth = $("form#cd input[name=dateOfBirth]").val();
                if(globalInsurance){
                        retObj['customerDateOfBirth'] = (dateOfBirth);
                }
                retObj['fofoOrderItems'] = (priceQtyArray);
                retObj['customer'] = (customerObj);
                retObj['paymentOptions'] =  (paymentOptionIdAmount);
                
                console.log(retObj);
                return  JSON.stringify(retObj);
}


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