Subversion Repositories SmartDukaan

Rev

Rev 24052 | Rev 25170 | 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;
                        }
                        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").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 < mop){
                                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")
                                if(unitPrice == mopPrice){
                                        $("input.discountAmount").removeAttr("readonly");
                                }
                                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;
                                        }
                                });
                        }
                }
        });
        
        $( "input.phone").change(function() {
                console.log("phone blur called");
                var mobileNumber = $(this).val();
                if(mobileNumber.length < 10) {
                        return;
                }
                writeOldCustomerDetailsByMobileNumber(mobileNumber);
                var itemIds = [];
                $("form#cd input.serialNumber").each(function(){
                        var itemId = parseInt($(this).attr("itemId"));
                        itemIds.push(itemId);
                });
                console.log(itemIds);
                calculateTotalAmount();
        });
  
});


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");
                }
        });
        
        // 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());
        var totalAdvanceAmount = parseFloat($("form#cd input.totalAdvanceAmount").val());
        
        netPayableAmount = netPayableAmount - totalAdvanceAmount;
        
        $("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;

                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'] = startDate;
        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 = {};
        if(globalInsurance){
                retObj['customerDateOfBirth'] = startDate;
        }
        
        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){
                if(response.response=='') {
                        return;
                }
                var customer = response.response;
            $('#firstName').attr('value', customer.firstName);
            $('#lastName').attr('value', customer.lastName);
            $('#email').attr('value', customer.emailId);
            //$('#phone').attr('value', customer.mobileNumber);
            if(customer.address !== null) {
                $('#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);
                $('#phone').attr('addressId', customer.address.id);
            }
            //$('#state').val(customer.address.state).prop('selected', true);
        });
}