Subversion Repositories SmartDukaan

Rev

Rev 32065 | Rev 33622 | 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_partner_view', function() {
                let $offerTr = $(this).closest('tr');
                let offerId = $offerTr.data('offerid');
                if (typeof (offerId) == "undefined") {
                        offerId = $(this).closest('th').data('offerid');
                        let idx = $(this).closest('th').data('idx');
                        priceCircularTable.order([[parseInt(idx), 'desc']]).draw();
                }
                doGetAjaxRequestHandler(`${context}/getOfferMargins?offerId=${offerId}`, function(data) {
                        $('#offerDescription .modal-content').html(data);
                        $("#offerDescription").modal('show');
                });
        });

        $(document).on('click', 'a.mk_offer_detail', function() {
                let $offerTr = $(this).closest('tr');
                let offerId = $offerTr.data('offerid');
                doGetAjaxRequestHandler(`${context}\getOfferMargins?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.process_offer', function () {
                let $offerTr = $(this).closest('tr');
                let offerId = $offerTr.data('offerid');
                if (confirm("Are your sure you want to process?")) {
                        doGetAjaxRequestHandler(`${context}/offer/process/${offerId}`, function () {
                                alert("Offer Processed successfully");
                        });
                }
        });

        $(document).on('change', 'input[name=schemeType]', function() {
                if ($('input[name=schemeType]').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";
                } else if ($(this).val() == "SLAB_FIXED") {
                        holder3 = "";
                }
                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(9));
                //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!="PERCENTAGE"]').prop('checked', false).prop('disabled', false);
        } else {
                $('div.slab-payout input:radio[value!="PERCENTAGE"]').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(9));
}
$(document).on('click', 'a.mk_offer_active', function() {
        $clicked = $(this);
        let offerId = $clicked.closest('tr').data("offerid");
        if (confirm(`Are you sure want to activate ${offerId}?`)) {
                doGetAjaxRequestHandler(`${context}/offer/active/${offerId}`, function(response) {
                        alert("Offer is now active");
                        $clicked.closest("li").html(`<a class="mk_offer_inactive" href="javascript:void(0)">Mark Inactive</a>`);
                });
        }
});
$(document).on('click', 'a.mk_offer_inactive', function() {
        $clicked = $(this);
        let offerId = $clicked.closest('tr').data("offerid");
        if (confirm(`Are you sure want to activate ${offerId}?`)) {
                doGetAjaxRequestHandler(`${context}/offer/active/${offerId}?active=false`, function(response) {
                        alert("Offer is now inactive");
                        $clicked.closest("li").html(`<a class="mk_offer_active" href="javascript:void(0)">Mark Active</a>`);
                });
        }
});
$(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 < 9; 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();
                let led = $(this).closest('.item-criteria').find('input[name=led]').is(":checked");
                $brandsContainer = $(this);
                let categoryId = 3;
                if (led) {
                        categoryId = 14202;
                }
                var url = `${context}/entity?brands=${brands.join(",")}&categoryId=${categoryId}&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;
        }
});

var ckEditor;

function createOfferNew() {
        let validated = true;
        let rangePicker = getDatesFromPicker('input[name="dateRange"]');
        let createOfferRequest = {};
        createOfferRequest['name'] = $("#offer_name").val();
        createOfferRequest['startDate'] = rangePicker.startDate;
        createOfferRequest['endDate'] = rangePicker.endDate;
        createOfferRequest['offerNotes'] = $("#offer_notes").val();
        createOfferRequest['baseCriteria'] = $("input[name=base_criteria]").is(":checked");
        createOfferRequest['terms'] = ckEditor.getData() //$("#offer_terms").val();
        createOfferRequest['targetType'] = $("input[name=targetType]:checked").val();
        createOfferRequest['payoutType'] = $("input[name=payoutType]:checked").val();
        createOfferRequest['schemeType'] = $("select[name=schemeType]").val();
        createOfferRequest['booster'] = false;
        createOfferRequest['activationBrands'] = null;
    createOfferRequest['discount'] = $("input[name=discount]").is(':checked');
        if (createOfferRequest['schemeType'] == 'ACTIVATION') {
                createOfferRequest['activationBrands'] = $("div.activation-brands select").val().join(",") || null;
        } else if (createOfferRequest['schemeType'] == 'SELLINBOOSTER') {
                createOfferRequest['schemeType'] = 'SELLIN';
                createOfferRequest['booster'] = true;
        }
        createOfferRequest['sellinPercentage'] = $("#sellinPercentage").val();
        createOfferRequest['brandShareTerms'] = $('#brandShare').val();
        createOfferRequest['partnerCriteria'] = {};
        createOfferRequest['partnerCriteria']['fofoIds'] = ($("#partners").val() || []).map(Number);
        createOfferRequest['partnerCriteria']['excludeFofoIds'] = [];
        let excludeFofoIdChecked = $('input.excludeFofoId').is(':checked');
        if (excludeFofoIdChecked) {
                createOfferRequest['partnerCriteria']['excludeFofoIds'] = createOfferRequest['partnerCriteria']['fofoIds'];
                createOfferRequest['partnerCriteria']['fofoIds'] = [];
        }
        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 startDate = $itemCriteriaPayoutContainer.find('input.startDate').val();
                                        let endDate = $itemCriteriaPayoutContainer.find('input.endDate').val();
                                        if((startDate=="" && endDate!="") && (startDate!="" && endDate=="")) {
                                                alert("Criteria specific date is required");
                                                return false;
                                        }
                                        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,
                                                        startDate: jsonStartDate(startDate),
                                                        endDate: jsonEndDate(endDate)
                                                };
                                                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 led = $container.find("input[name=led]").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,
                led: led
        };
}

function loadOffer(domId) {
        console.log(domId);
        doGetAjaxRequestHandler(context + "/getCreateOffer", function(response) {
                $('#' + domId).html(response);

                DecoupledEditor
                        .create(document.querySelector('#offer_terms'))



                        .then(newEditor => {
                                const toolbarContainer = document.querySelector('#toolbar-container');

                                toolbarContainer.appendChild(newEditor.ui.view.toolbar.element);

                                ckEditor = newEditor
                        })
                        .catch(error => {
                                console.error(error);
                        });

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