Subversion Repositories SmartDukaan

Rev

Rev 29174 | Rev 29681 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
27875 amit.gupta 1
$(document).ready(function () {
2
	$(document).on('change','select.criteria-brands', function() {
3
		changed = true;
4
	});
5
    $(document).on('click', ".scheme_offer", function () {
6
        loadOffer("main-content");
7
    });
8
    $(document).on('click', '#yearmonth-submit', function(){
9
    	let yearMonth = $("#yearmonth").val();
10
    	loadOfferHistory('#main-content', yearMonth);
11
 
12
    });
13
 
14
    $(document).on('click', 'a.mk_offer_detail', function() {
15
    	let $offerTr = $(this).closest('tr');
16
        let offerId = $offerTr.data('offerid');
29189 amit.gupta 17
        doGetAjaxRequestHandler(`${context}/getOfferMargins?offerId=${offerId}`, function(data) {
27875 amit.gupta 18
        	$('#offerDescription .modal-content').html(data);
19
        	$("#offerDescription").modal('show');
20
        });
21
    });
22
    $(document).on('click', 'a.offer_history', function () {
23
        let dt = new Date();
24
        loadOfferHistory('#main-content', new Date().toISOString().slice(0,7));
25
    });
26
    $(document).on('click', 'input.create-offer', function () {
27
        console.log("Click called");
28
        createOfferNew();
29
    });
30
 
31
    $(document).on('click', 'a.download_offer', function () {
32
        let $offerTr = $(this).closest('tr');
33
        let offerId = $offerTr.data('offerid');
34
        let fileName = `offer-${$offerTr.find('td:first')}.csv`;
35
        doAjaxGetDownload(`${context}\offerDownload?offerId=${offerId}`, fileName);
36
    });
37
 
38
    $(document).on('change', 'input[name=schemeType]', function () {
39
		if($('input[name=schemeType]:checked').val()=='ACTIVATION') {
40
			$("div.activation-brands").show();
41
		} else {
42
			$("div.activation-brands").hide();
43
		}
44
    });
27879 amit.gupta 45
    $(document).on('change', 'input[name^=amountType]', function () {
27875 amit.gupta 46
    	let holder1 = "Qty";
47
		let holder2 = "pc(s) onwards, ";
48
    	let holder3 = "% of value";
49
    	if($(this).val()=="FIXED") {
50
    		holder3 = "per pc";
29173 amit.gupta 51
    	} else if ($(this).val()=="SLAB_FIXED") {
29174 amit.gupta 52
    		holder3 = "";
29173 amit.gupta 53
		}    	
27875 amit.gupta 54
    	let slabHtml = `<div class="input-group slab">
55
        	<span class="input-group-addon">${holder1}</span>
56
        	<input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
57
        	<span class="input-group-addon">${holder2}</span>
58
        	<input type="text" class="form-control payoutValue"  value="0"/>
59
        	<span class="input-group-addon">${holder3}</span>
60
        	</div>`;
29167 amit.gupta 61
        $(this).closest('.itemcriteriapayout').find('div.slab-container').html(slabHtml.repeat(9));
27875 amit.gupta 62
        //targetSlabTemplate = $('div.targetslabs').get(0).outerHTML;
63
    });
64
});
65
function changeTargetType() {
66
	let holder1 = "Rs.";
67
	let holder2 = "onwards,";
27895 amit.gupta 68
	if ($(this).val() == "QUANTITY") {
69
		holder1 = "Qty";
70
		holder2 = "pc(s) onwards, ";
71
	}
72
	let targetHtml = `<span class="input-group-addon">${holder1}</span>
73
                                    <input type="text" style="width:100px" class="form-control payoutTarget" value="0">
74
                                    <span class="input-group-addon">${holder2}</span>
75
                                    <input type="text" class="form-control targetDescription" placeholder="Description">`;
76
	$('div.targetContainer').html(targetHtml);
77
}
78
function changePayoutType() {
79
	let holder1 = "Rs.";
80
	let holder2 = "onwards,";
27875 amit.gupta 81
	let holder3 = "% of value";
82
	$allSlabContainers = $('div.slab-container');
83
	$('div.slab-payout input:radio[value="PERCENTAGE"]').prop('checked',true);
84
    if ($(this).val() == "QUANTITY") {
85
    		holder1 = "Qty";
86
    		holder2 = "pc(s) onwards, ";
29173 amit.gupta 87
        	$('div.slab-payout input:radio[value!="PERCENTAGE"]').prop('checked',false).prop('disabled',false);
27875 amit.gupta 88
    } else {
29173 amit.gupta 89
    	$('div.slab-payout input:radio[value!="PERCENTAGE"]').prop('checked',false).prop('disabled',true);
27875 amit.gupta 90
    }
91
    let slabHtml = `<div class="input-group slab">
92
    	<span class="input-group-addon">${holder1}</span>
93
    	<input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
94
    	<span class="input-group-addon">${holder2}</span>
95
    	<input type="text" class="form-control payoutValue"  value="0"/>
96
    	<span class="input-group-addon">${holder3}</span>
97
    	</div>`;
29167 amit.gupta 98
    $allSlabContainers.html(slabHtml.repeat(9));
27875 amit.gupta 99
}
100
$(document).on('click', 'a.mk_offer_active', function(){
101
	let spanContainer = $(this).closest('span.mk_active');
102
	let offerId = spanContainer.data("id");
103
	doGetAjaxRequestHandler(`${context}/offer/active/${offerId}`, function (response) {
104
		alert("Offer is now active");
105
		spanContainer.html("Now Active");
106
    });
107
});
108
$(document).on('click', 'button.slab-add', function(){
109
	newTargetSlab = $(targetSlabTemplate);
110
	$('div.targetslabscontainer').append(newTargetSlab);	
111
	newTargetSlab.find("select.criteria-brands").toggle().next().remove();
112
	newTargetSlab.find("select.criteria-brands").chosen({no_results_text: "Oops, nothing found!"});
113
});
114
$(document).on('click', 'button.slab-remove', function(){
115
	targetSlabContainer = $('div.targetslabscontainer');
116
	if(targetSlabContainer.find(".targetslabs").length > 1) {
117
		targetSlabContainer.find(".targetslabs:last").remove();
118
	} else {
119
		alert("Cant remove single Slab");
120
	}
121
});
122
$(document).on('click', 'button.slab-copy', function(){
123
	newTargetSlab = $('div.targetslabs').eq(0).clone().appendTo('div.targetslabscontainer');
27975 amit.gupta 124
	catalogIdSelectContainers = $('div.targetslabs').eq(0).find('select.criteria-catalogids');
125
	newCatalogIdSelectContainers = newTargetSlab.find('select.criteria-catalogids');
28950 amit.gupta 126
	for(let i=0;i<9;i++) {
27975 amit.gupta 127
		let selectContainer = catalogIdSelectContainers.get(i);
128
		let newSelectContainer = newCatalogIdSelectContainers.get(i);
129
		for(let j=0;j<selectContainer.options.length;j++) {
130
			newSelectContainer.options[j].selected = selectContainer.options[j].selected;
131
		}
132
		newSelectContainer.closest('span').replaceWith(newSelectContainer);
133
		$(newSelectContainer).multiselect({
134
			includeSelectAllOption : true,
135
			maxHeight : 400,
136
			buttonWidth : '240px',
137
			numberDisplayed : 1,
138
			nonSelectedText : 'Items',
139
			nSelectedText : ' - Items Selected',
140
			allSelectedText : 'All Items Selected',
141
			enableFiltering : true,
142
			enableCaseInsensitiveFiltering : true,
143
		});
144
	}
27875 amit.gupta 145
	selectContainers = newTargetSlab.find("select.criteria-brands");
146
	selectContainers.each((y,x)=>{
147
		$next = $(x).toggle().next();
148
		$next.find("a.search-choice-close").each(function(index,ele){
149
			x.options[$(ele).data('option-array-index') + 0].selected=true; 
150
		});
151
		$next.remove();
152
	});
153
	newTargetSlab.find("select.criteria-brands").chosen({no_results_text: "Oops, nothing found!"});
154
	//createSlabFrom(currentHtml);
155
});
156
 
27916 amit.gupta 157
$(document).on('click', 'select.criteria-catalogids+div > button', function(){
27875 amit.gupta 158
	if(changed) {
27916 amit.gupta 159
		let brands = $(this).closest('.item-criteria').find('select').val();
160
		$brandsContainer = $(this);
27875 amit.gupta 161
		var url = `${context}/entity?brands=${brands.join(",")}&categoryId=3&limit=0`;
162
		$select = $brandsContainer.closest('.item-criteria').find('.criteria-catalogids');
163
		$select.html('');
164
		if(brands.length > 0) {
165
			doGetAjaxRequestHandler(url, function(response) {
166
				data = JSON.parse(response);
167
				for(i = 0; i < data.length; i++) {
168
					$select.append(`<option value="${data[i].catalogId_i}">${data[i].title_s}</option>`);
169
				}
170
				$select.multiselect('rebuild');
171
			});
172
		} else {
173
			$select.html('');
174
			$select.multiselect('rebuild');
175
		}
176
		changed = !changed;
177
	}
178
});
179
 
180
function createOfferNew() {
181
    let validated = true;
182
    let createOfferRequest = {};
183
    createOfferRequest['name'] = $("#offer_name").val();
184
    createOfferRequest['startDate'] = startDate;
185
    createOfferRequest['endDate'] = endDate;
186
    createOfferRequest['offerNotes'] = $("#offer_notes").val();
28018 amit.gupta 187
    createOfferRequest['incrementalTarget'] = $("input[name=incremental_target]").is(":checked");
27875 amit.gupta 188
    createOfferRequest['terms'] = $("#offer_terms").val();
189
    createOfferRequest['targetType'] = $("input[name=targetType]:checked").val();
27895 amit.gupta 190
    createOfferRequest['payoutType'] = $("input[name=payoutType]:checked").val();
27875 amit.gupta 191
    createOfferRequest['schemeType'] = $("input[name=schemeType]:checked").val();
192
    if(createOfferRequest['schemeType']=='ACTIVATION') {
193
    	createOfferRequest['activationBrands'] = $("div.activation-brands select").val().join(",") || null;
194
    } else {
195
    	createOfferRequest['activationBrands'] = null;
196
 
197
    }
198
    createOfferRequest['sellinPercentage'] = $("#sellinPercentage").val();
199
    createOfferRequest['brandShareTerms'] = $('#brandShare').val();
200
    createOfferRequest['partnerCriteria'] = {};
201
    createOfferRequest['partnerCriteria']['fofoIds'] = ($("#partners").val() || []).map(Number);
202
    createOfferRequest['partnerCriteria']['partnerTypes'] = ($("select.criteria-partner-type").val() || []);
203
    createOfferRequest['partnerCriteria']['regionIds'] = ($("select.criteria-warehouseregion").val() || []).map(Number);
204
 
205
    createOfferRequest['itemCriteria'] = itemCriteria($('div.itemCriteria'));
206
    let targetSlabs = [];
207
    $('div.targetslabs').each(function (index, ele) {
208
        let $targetSlab = $(ele);
209
        let targetOnwardsValue = $targetSlab.find('.payoutTarget').val();
210
        let targetDescription = $targetSlab.find('.targetDescription').val();
211
        let itemCriteriaPayouts = [];
212
        if (isNaN(targetOnwardsValue) || targetOnwardsValue < 0) {
213
            validated = false;
214
            alert(`Invalid Number - ${targetOnwardsValue}`);
215
        } else {
216
            if (index == 0 || targetOnwardsValue > 0) {
217
                let $itemCriteriaPayoutContainers = $targetSlab.find('.itemcriteriapayout');
218
                $itemCriteriaPayoutContainers.each(function (index, itemCriteriaPayoutContainer) {
219
                    let $itemCriteriaPayoutContainer = $(itemCriteriaPayoutContainer);
220
                    let amountType = $itemCriteriaPayoutContainer.find('input[name^=amountType]:checked').val();
221
                    let payoutSlabs = [];
222
                    let itemCriteria1 = itemCriteria($itemCriteriaPayoutContainer);
223
                    let $payoutSlabContainers = $itemCriteriaPayoutContainer.find('.slab');
28018 amit.gupta 224
                    let itemCriteriaChanged = itemCriteria1['smartPhone'] || itemCriteria1['featuredPhone']
27951 amit.gupta 225
                        || itemCriteria1['catalogIds'].length > 0 || itemCriteria1['brands'].length > 0
27952 amit.gupta 226
                        || itemCriteria1['excludeCatalogIds'].length > 0 
27955 amit.gupta 227
                        || itemCriteria1['startPrice'] > 0 || itemCriteria1['endPrice'] > itemCriteria1['startPrice'] > 0;
27875 amit.gupta 228
                    if (itemCriteriaChanged || index == 0) {
229
                        $payoutSlabContainers.each(function (slabContainerIndex, slabContainer) {
230
                            let $slab = $(slabContainer);
231
 
232
                            let slabOnwardsAmount = $slab.find('.slabOnwardsAmount').val();
233
                            if (isNaN(slabOnwardsAmount) || slabOnwardsAmount < 0) {
234
                                validated = false;
235
                                alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
236
                            } else {
237
                                if (slabContainerIndex == 0 || slabOnwardsAmount > 0) {
238
                                    let payoutAmount = $slab.find('.payoutValue').val();
239
                                    if (isNaN(payoutAmount) || payoutAmount <= 0) {
240
                                        validated = false;
241
                                        alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
242
                                    }
243
                                    let payoutSlab = {
244
                                        onwardsAmount: Number(slabOnwardsAmount),
245
                                        payoutAmount: Number(payoutAmount)
246
                                    }
247
                                    payoutSlabs.push(payoutSlab);
248
                                }
249
                            }
250
                        });
251
                        let itemCriteriaPayout = {
252
                            itemCriteria: itemCriteria1,
253
                            payoutSlabs: payoutSlabs,
254
                            amountType: amountType
255
                        };
256
                        itemCriteriaPayouts.push(itemCriteriaPayout);
257
                    }
258
                });
259
                targetSlabs.push({
260
                    onwardsAmount: targetOnwardsValue,
261
                    targetDescription : targetDescription, 
262
                    itemCriteriaPayouts: itemCriteriaPayouts
263
                });
264
            }
265
        }
266
    });
267
    createOfferRequest['targetSlabs'] = targetSlabs;
268
    if (validated && confirm("Confirm creating scheme offer")) {
269
        console.log("Validated");
270
        console.log(createOfferRequest);
271
        doPostAjaxRequestWithJsonHandler(`${context}/createOffer`, JSON.stringify(createOfferRequest), function (response) {
272
            alert("Offer created successfully");
273
            let dt = new Date();
274
            loadOfferHistory('#main-content', new Date().toISOString().slice(0,7));
275
        });
276
    } else {
277
        console.log("Invalid Offer");
278
    }
279
}
280
 
281
function itemCriteria($container) {
28018 amit.gupta 282
	let smartPhone = $container.find("input[name=smartphone]").is(":checked");
283
	let featuredPhone = $container.find("input[name=featuredphone]").is(":checked");
27875 amit.gupta 284
    let catalogIds = $container.find('.criteria-catalogids').val() || [];
285
    let excludeCatalogIds = [];
286
    let excludeChecked = $container.find('input.exclude').is(':checked');
287
    if(excludeChecked) {
288
    	excludeCatalogIds = catalogIds;
289
    	catalogIds = [];
290
    }
291
    let brands = $container.find('.criteria-brands').val() || [];
292
    return {
293
        startPrice: Number($container.find('.startValue').val()),
294
        endPrice: Number($container.find('.endValue').val()),
295
        catalogIds: catalogIds.map(Number),
296
        excludeCatalogIds : excludeCatalogIds.map(Number),
297
        brands: brands,
28018 amit.gupta 298
        smartPhone: smartPhone,
299
        featuredPhone: featuredPhone
27875 amit.gupta 300
    };
301
}
302
 
303
function loadOffer(domId) {
304
    console.log(domId);
305
    doGetAjaxRequestHandler(context + "/getCreateOffer", function (response) {
306
        $('#' + domId).html(response);
307
    });
308
}
309
function loadOfferHistory(domId, yearMonth) {
310
    doGetAjaxRequestHandler(`${context}/offerHistory?yearMonth=${yearMonth}`, function (response) {
311
        $(domId).html(response);
312
        $(domId).find("#yearmonth").val(yearMonth);
313
    });
314
}
315