Subversion Repositories SmartDukaan

Rev

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

$(document).ready(function () {
        $(document).on('change','select.criteria-brands', function() {
                changed = true;
        });
    $(document).on('click', ".scheme_offer", function () {
        loadOffer("main-content");
    });
    $(document).on('click', '#yearmonth-submit', function(){
        let yearMonth = $("#yearmonth").val();
        loadOfferHistory('#main-content', yearMonth);
        
    });
    
    $(document).on('click', 'a.mk_offer_detail', function() {
        let $offerTr = $(this).closest('tr');
        let offerId = $offerTr.data('offerid');
        doGetAjaxRequestHandler(`${context}\offer-details?offerId=${offerId}`, function(data) {
                $('#offerDescription .modal-content').html(data);
                $("#offerDescription").modal('show');
        });
    });
    $(document).on('click', 'a.offer_history', function () {
        let dt = new Date();
        loadOfferHistory('#main-content', new Date().toISOString().slice(0,7));
    });
    $(document).on('click', 'input.create-offer', function () {
        console.log("Click called");
        createOfferNew();
    });

    $(document).on('click', 'a.download_offer', function () {
        let $offerTr = $(this).closest('tr');
        let offerId = $offerTr.data('offerid');
        let fileName = `offer-${$offerTr.find('td:first')}.csv`;
        doAjaxGetDownload(`${context}\offerDownload?offerId=${offerId}`, fileName);
    });

    $(document).on('change', 'input[name=schemeType]', function () {
                if($('input[name=schemeType]:checked').val()=='ACTIVATION') {
                        $("div.activation-brands").show();
                } else {
                        $("div.activation-brands").hide();
                }
    });
    $(document).on('change', 'input[name^=amountType]', function () {
        let holder1 = "Qty";
                let holder2 = "pc(s) onwards, ";
        let holder3 = "% of value";
        if($(this).val()=="FIXED") {
                holder3 = "per pc";
        }
        let slabHtml = `<div class="input-group slab">
                <span class="input-group-addon">${holder1}</span>
                <input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
                <span class="input-group-addon">${holder2}</span>
                <input type="text" class="form-control payoutValue"  value="0"/>
                <span class="input-group-addon">${holder3}</span>
                </div>`;
        $(this).closest('.itemcriteriapayout').find('div.slab-container').html(slabHtml.repeat(4));
        //targetSlabTemplate = $('div.targetslabs').get(0).outerHTML;
    });
});
function changeTargetType() {
        let holder1 = "Rs.";
        let holder2 = "onwards,";
        if ($(this).val() == "QUANTITY") {
                holder1 = "Qty";
                holder2 = "pc(s) onwards, ";
        }
        let targetHtml = `<span class="input-group-addon">${holder1}</span>
                                    <input type="text" style="width:100px" class="form-control payoutTarget" value="0">
                                    <span class="input-group-addon">${holder2}</span>
                                    <input type="text" class="form-control targetDescription" placeholder="Description">`;
        $('div.targetContainer').html(targetHtml);
}
function changePayoutType() {
        let holder1 = "Rs.";
        let holder2 = "onwards,";
        let holder3 = "% of value";
        $allSlabContainers = $('div.slab-container');
        $('div.slab-payout input:radio[value="PERCENTAGE"]').prop('checked',true);
    if ($(this).val() == "QUANTITY") {
                holder1 = "Qty";
                holder2 = "pc(s) onwards, ";
                $('div.slab-payout input:radio[value="FIXED"]').prop('checked',false).prop('disabled',false);
    } else {
        $('div.slab-payout input:radio[value="FIXED"]').prop('checked',false).prop('disabled',true);
    }
    let slabHtml = `<div class="input-group slab">
        <span class="input-group-addon">${holder1}</span>
        <input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
        <span class="input-group-addon">${holder2}</span>
        <input type="text" class="form-control payoutValue"  value="0"/>
        <span class="input-group-addon">${holder3}</span>
        </div>`;
    $allSlabContainers.html(slabHtml.repeat(4));
}
$(document).on('click', 'a.mk_offer_active', function(){
        let spanContainer = $(this).closest('span.mk_active');
        let offerId = spanContainer.data("id");
        doGetAjaxRequestHandler(`${context}/offer/active/${offerId}`, function (response) {
                alert("Offer is now active");
                spanContainer.html("Now Active");
    });
});
$(document).on('click', 'button.slab-add', function(){
        newTargetSlab = $(targetSlabTemplate);
        $('div.targetslabscontainer').append(newTargetSlab);    
        newTargetSlab.find("select.criteria-brands").toggle().next().remove();
        newTargetSlab.find("select.criteria-brands").chosen({no_results_text: "Oops, nothing found!"});
});
$(document).on('click', 'button.slab-remove', function(){
        targetSlabContainer = $('div.targetslabscontainer');
        if(targetSlabContainer.find(".targetslabs").length > 1) {
                targetSlabContainer.find(".targetslabs:last").remove();
        } else {
                alert("Cant remove single Slab");
        }
});
$(document).on('click', 'button.slab-copy', function(){
        newTargetSlab = $('div.targetslabs').eq(0).clone().appendTo('div.targetslabscontainer');
        catalogIdSelectContainers = $('div.targetslabs').eq(0).find('select.criteria-catalogids');
        newCatalogIdSelectContainers = newTargetSlab.find('select.criteria-catalogids');
        for(let i=0;i<4;i++) {
                let selectContainer = catalogIdSelectContainers.get(i);
                let newSelectContainer = newCatalogIdSelectContainers.get(i);
                for(let j=0;j<selectContainer.options.length;j++) {
                        newSelectContainer.options[j].selected = selectContainer.options[j].selected;
                }
                newSelectContainer.closest('span').replaceWith(newSelectContainer);
                $(newSelectContainer).multiselect({
                        includeSelectAllOption : true,
                        maxHeight : 400,
                        buttonWidth : '240px',
                        numberDisplayed : 1,
                        nonSelectedText : 'Items',
                        nSelectedText : ' - Items Selected',
                        allSelectedText : 'All Items Selected',
                        enableFiltering : true,
                        enableCaseInsensitiveFiltering : true,
                });
        }
        selectContainers = newTargetSlab.find("select.criteria-brands");
        selectContainers.each((y,x)=>{
                $next = $(x).toggle().next();
                $next.find("a.search-choice-close").each(function(index,ele){
                        x.options[$(ele).data('option-array-index') + 0].selected=true; 
                });
                $next.remove();
        });
        newTargetSlab.find("select.criteria-brands").chosen({no_results_text: "Oops, nothing found!"});
        //createSlabFrom(currentHtml);
});

$(document).on('click', 'select.criteria-catalogids+div > button', function(){
        if(changed) {
                let brands = $(this).closest('.item-criteria').find('select').val();
                $brandsContainer = $(this);
                var url = `${context}/entity?brands=${brands.join(",")}&categoryId=3&limit=0`;
                $select = $brandsContainer.closest('.item-criteria').find('.criteria-catalogids');
                $select.html('');
                if(brands.length > 0) {
                        doGetAjaxRequestHandler(url, function(response) {
                                data = JSON.parse(response);
                                for(i = 0; i < data.length; i++) {
                                        $select.append(`<option value="${data[i].catalogId_i}">${data[i].title_s}</option>`);
                                }
                                $select.multiselect('rebuild');
                        });
                } else {
                        $select.html('');
                        $select.multiselect('rebuild');
                }
                changed = !changed;
        }
});

function createOfferNew() {
    let validated = true;
    let createOfferRequest = {};
    createOfferRequest['name'] = $("#offer_name").val();
    createOfferRequest['startDate'] = startDate;
    createOfferRequest['endDate'] = endDate;
    createOfferRequest['offerNotes'] = $("#offer_notes").val();
    createOfferRequest['incrementalTarget'] = $("input[name=incremental_target]").is(":checked");
    createOfferRequest['terms'] = $("#offer_terms").val();
    createOfferRequest['targetType'] = $("input[name=targetType]:checked").val();
    createOfferRequest['payoutType'] = $("input[name=payoutType]:checked").val();
    createOfferRequest['schemeType'] = $("input[name=schemeType]:checked").val();
    if(createOfferRequest['schemeType']=='ACTIVATION') {
        createOfferRequest['activationBrands'] = $("div.activation-brands select").val().join(",") || null;
    } else {
        createOfferRequest['activationBrands'] = null;
        
    }
    createOfferRequest['sellinPercentage'] = $("#sellinPercentage").val();
    createOfferRequest['brandShareTerms'] = $('#brandShare').val();
    createOfferRequest['partnerCriteria'] = {};
    createOfferRequest['partnerCriteria']['fofoIds'] = ($("#partners").val() || []).map(Number);
    createOfferRequest['partnerCriteria']['partnerTypes'] = ($("select.criteria-partner-type").val() || []);
    createOfferRequest['partnerCriteria']['regionIds'] = ($("select.criteria-warehouseregion").val() || []).map(Number);

    createOfferRequest['itemCriteria'] = itemCriteria($('div.itemCriteria'));
    let targetSlabs = [];
    $('div.targetslabs').each(function (index, ele) {
        let $targetSlab = $(ele);
        let targetOnwardsValue = $targetSlab.find('.payoutTarget').val();
        let targetDescription = $targetSlab.find('.targetDescription').val();
        let itemCriteriaPayouts = [];
        if (isNaN(targetOnwardsValue) || targetOnwardsValue < 0) {
            validated = false;
            alert(`Invalid Number - ${targetOnwardsValue}`);
        } else {
            if (index == 0 || targetOnwardsValue > 0) {
                let $itemCriteriaPayoutContainers = $targetSlab.find('.itemcriteriapayout');
                $itemCriteriaPayoutContainers.each(function (index, itemCriteriaPayoutContainer) {
                    let $itemCriteriaPayoutContainer = $(itemCriteriaPayoutContainer);
                    let amountType = $itemCriteriaPayoutContainer.find('input[name^=amountType]:checked').val();
                    let payoutSlabs = [];
                    let itemCriteria1 = itemCriteria($itemCriteriaPayoutContainer);
                    let $payoutSlabContainers = $itemCriteriaPayoutContainer.find('.slab');
                    let itemCriteriaChanged = itemCriteria1['smartPhone'] || itemCriteria1['featuredPhone']
                        || itemCriteria1['catalogIds'].length > 0 || itemCriteria1['brands'].length > 0
                        || itemCriteria1['excludeCatalogIds'].length > 0 
                        || itemCriteria1['startPrice'] > 0 || itemCriteria1['endPrice'] > itemCriteria1['startPrice'] > 0;
                    if (itemCriteriaChanged || index == 0) {
                        $payoutSlabContainers.each(function (slabContainerIndex, slabContainer) {
                            let $slab = $(slabContainer);

                            let slabOnwardsAmount = $slab.find('.slabOnwardsAmount').val();
                            if (isNaN(slabOnwardsAmount) || slabOnwardsAmount < 0) {
                                validated = false;
                                alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
                            } else {
                                if (slabContainerIndex == 0 || slabOnwardsAmount > 0) {
                                    let payoutAmount = $slab.find('.payoutValue').val();
                                    if (isNaN(payoutAmount) || payoutAmount <= 0) {
                                        validated = false;
                                        alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
                                    }
                                    let payoutSlab = {
                                        onwardsAmount: Number(slabOnwardsAmount),
                                        payoutAmount: Number(payoutAmount)
                                    }
                                    payoutSlabs.push(payoutSlab);
                                }
                            }
                        });
                        let itemCriteriaPayout = {
                            itemCriteria: itemCriteria1,
                            payoutSlabs: payoutSlabs,
                            amountType: amountType
                        };
                        itemCriteriaPayouts.push(itemCriteriaPayout);
                    }
                });
                targetSlabs.push({
                    onwardsAmount: targetOnwardsValue,
                    targetDescription : targetDescription, 
                    itemCriteriaPayouts: itemCriteriaPayouts
                });
            }
        }
    });
    createOfferRequest['targetSlabs'] = targetSlabs;
    if (validated && confirm("Confirm creating scheme offer")) {
        console.log("Validated");
        console.log(createOfferRequest);
        doPostAjaxRequestWithJsonHandler(`${context}/createOffer`, JSON.stringify(createOfferRequest), function (response) {
            alert("Offer created successfully");
            let dt = new Date();
            loadOfferHistory('#main-content', new Date().toISOString().slice(0,7));
        });
    } else {
        console.log("Invalid Offer");
    }
}

function itemCriteria($container) {
        let smartPhone = $container.find("input[name=smartphone]").is(":checked");
        let featuredPhone = $container.find("input[name=featuredphone]").is(":checked");
    let catalogIds = $container.find('.criteria-catalogids').val() || [];
    let excludeCatalogIds = [];
    let excludeChecked = $container.find('input.exclude').is(':checked');
    if(excludeChecked) {
        excludeCatalogIds = catalogIds;
        catalogIds = [];
    }
    let brands = $container.find('.criteria-brands').val() || [];
    return {
        startPrice: Number($container.find('.startValue').val()),
        endPrice: Number($container.find('.endValue').val()),
        catalogIds: catalogIds.map(Number),
        excludeCatalogIds : excludeCatalogIds.map(Number),
        brands: brands,
        smartPhone: smartPhone,
        featuredPhone: featuredPhone
    };
}

function loadOffer(domId) {
    console.log(domId);
    doGetAjaxRequestHandler(context + "/getCreateOffer", function (response) {
        $('#' + domId).html(response);
    });
}
function loadOfferHistory(domId, yearMonth) {
    doGetAjaxRequestHandler(`${context}/offerHistory?yearMonth=${yearMonth}`, function (response) {
        $(domId).html(response);
        $(domId).find("#yearmonth").val(yearMonth);
    });
}