Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
33660 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);
27875 amit.gupta 11
 
33660 amit.gupta 12
    });
27875 amit.gupta 13
 
33660 amit.gupta 14
    $(document).on('click', 'a.mk_partner_view', function () {
15
        let $offerTr = $(this).closest('tr');
16
        let offerId = $offerTr.data('offerid');
17
        if (typeof (offerId) == "undefined") {
18
            offerId = $(this).closest('th').data('offerid');
19
            let idx = $(this).closest('th').data('idx');
20
            priceCircularTable.order([[parseInt(idx), 'desc']]).draw();
21
        }
22
        doGetAjaxRequestHandler(`${context}/getOfferMargins?offerId=${offerId}`, function (data) {
23
            $('#offerDescription .modal-content').html(data);
24
            $("#offerDescription").modal('show');
25
        });
26
    });
30485 tejbeer 27
 
33660 amit.gupta 28
    $(document).on('click', 'a.mk_offer_detail', function () {
29
        let $offerTr = $(this).closest('tr');
30
        let offerId = $offerTr.data('offerid');
35745 amit 31
        doGetAjaxRequestHandler(`${context}/getOfferMargins?offerId=${offerId}`, function (data) {
33660 amit.gupta 32
            $('#offerDescription .modal-content').html(data);
33
            $("#offerDescription").modal('show');
34
        });
35
    });
36
    $(document).on('click', 'a.offer_history', function () {
37
        let dt = new Date();
38
        loadOfferHistory('#main-content', new Date().toISOString().slice(0, 7));
39
    });
40
    $(document).on('click', 'input.create-offer', function () {
41
        console.log("Click called");
42
        createOfferNew();
43
    });
30485 tejbeer 44
 
33660 amit.gupta 45
    $(document).on('click', 'a.process_offer', function () {
46
        let $offerTr = $(this).closest('tr');
47
        let offerId = $offerTr.data('offerid');
35745 amit 48
        let $clicked = $(this);
33660 amit.gupta 49
        if (confirm("Are your sure you want to process?")) {
50
            $clicked.hide();
51
            doGetAjaxRequestHandler(`${context}/offer/process/${offerId}`, function () {
52
                alert("Offer Processed successfully");
53
                $clicked.show();
54
            });
55
        }
56
    });
30485 tejbeer 57
 
33660 amit.gupta 58
    $(document).on('change', 'input[name=schemeType]', function () {
59
        if ($('input[name=schemeType]').val() == 'ACTIVATION') {
60
            $("div.activation-brands").show();
61
        } else {
62
            $("div.activation-brands").hide();
63
        }
64
    });
65
    $(document).on('change', 'input[name^=amountType]', function () {
66
        let holder1 = "Qty";
67
        let holder2 = "pc(s) onwards, ";
68
        let holder3 = "% of value";
69
        if ($(this).val() == "FIXED") {
70
            holder3 = "per pc";
71
        } else if ($(this).val() == "SLAB_FIXED") {
72
            holder3 = "";
73
        }
74
        let slabHtml = `<div class="input-group slab">
27875 amit.gupta 75
        	<span class="input-group-addon">${holder1}</span>
76
        	<input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
77
        	<span class="input-group-addon">${holder2}</span>
78
        	<input type="text" class="form-control payoutValue"  value="0"/>
79
        	<span class="input-group-addon">${holder3}</span>
80
        	</div>`;
35219 amit 81
        $(this).closest('.itemcriteriapayout').find('div.slab-container').html(slabHtml.repeat(15));
33660 amit.gupta 82
        //targetSlabTemplate = $('div.targetslabs').get(0).outerHTML;
83
    });
27875 amit.gupta 84
});
33660 amit.gupta 85
 
27875 amit.gupta 86
function changeTargetType() {
33660 amit.gupta 87
    let holder1 = "Rs.";
88
    let holder2 = "onwards,";
89
    if ($(this).val() == "QUANTITY") {
90
        holder1 = "Qty";
91
        holder2 = "pc(s) onwards, ";
92
    }
93
    let targetHtml = `<span class="input-group-addon">${holder1}</span>
27895 amit.gupta 94
                                    <input type="text" style="width:100px" class="form-control payoutTarget" value="0">
95
                                    <span class="input-group-addon">${holder2}</span>
96
                                    <input type="text" class="form-control targetDescription" placeholder="Description">`;
33660 amit.gupta 97
    $('div.targetContainer').html(targetHtml);
27895 amit.gupta 98
}
33660 amit.gupta 99
 
27895 amit.gupta 100
function changePayoutType() {
33660 amit.gupta 101
    let holder1 = "Rs.";
102
    let holder2 = "onwards,";
103
    let holder3 = "% of value";
104
    $allSlabContainers = $('div.slab-container');
105
    $('div.slab-payout input:radio[value="PERCENTAGE"]').prop('checked', true);
106
    if ($(this).val() == "QUANTITY") {
107
        holder1 = "Qty";
108
        holder2 = "pc(s) onwards, ";
109
        $('div.slab-payout input:radio[value!="PERCENTAGE"]').prop('checked', false).prop('disabled', false);
110
    } else {
111
        $('div.slab-payout input:radio[value!="PERCENTAGE"]').prop('checked', false).prop('disabled', true);
112
    }
113
    let slabHtml = `<div class="input-group slab">
27875 amit.gupta 114
    	<span class="input-group-addon">${holder1}</span>
115
    	<input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
116
    	<span class="input-group-addon">${holder2}</span>
117
    	<input type="text" class="form-control payoutValue"  value="0"/>
118
    	<span class="input-group-addon">${holder3}</span>
119
    	</div>`;
35218 amit 120
    $allSlabContainers.html(slabHtml.repeat(15));
27875 amit.gupta 121
}
33660 amit.gupta 122
 
123
$(document).on('click', 'a.mk_offer_active', function () {
35745 amit 124
    let $clicked = $(this);
33660 amit.gupta 125
    let offerId = $clicked.closest('tr').data("offerid");
126
    if (confirm(`Are you sure want to activate ${offerId}?`)) {
127
        doGetAjaxRequestHandler(`${context}/offer/active/${offerId}`, function (response) {
128
            alert("Offer is now active");
129
            $clicked.closest("li").html(`<a class="mk_offer_inactive" href="javascript:void(0)">Mark Inactive</a>`);
130
        });
131
    }
27875 amit.gupta 132
});
33660 amit.gupta 133
$(document).on('click', 'a.mk_offer_inactive', function () {
35745 amit 134
    let $clicked = $(this);
33660 amit.gupta 135
    let offerId = $clicked.closest('tr').data("offerid");
35745 amit 136
    if (confirm(`Are you sure want to deactivate ${offerId}?`)) {
33660 amit.gupta 137
        doGetAjaxRequestHandler(`${context}/offer/active/${offerId}?active=false`, function (response) {
138
            alert("Offer is now inactive");
139
            $clicked.closest("li").html(`<a class="mk_offer_active" href="javascript:void(0)">Mark Active</a>`);
140
        });
141
    }
29907 amit.gupta 142
});
35857 amit 143
$(document).on('click', 'a.delete_offer', function () {
144
    let $clicked = $(this);
145
    let offerId = $clicked.closest('tr').data("offerid");
146
    if (confirm(`Are you sure you want to delete offer ${offerId}? This cannot be undone.`)) {
147
        doDeleteAjaxRequestHandler(`${context}/offer/delete/${offerId}`, function (response) {
148
            alert("Offer deleted");
149
            $clicked.closest('tr').remove();
150
        });
151
    }
152
});
153
$(document).on('click', '#publish-all-btn', function () {
154
    let yearMonth = $("#yearmonth").val();
155
    if (!yearMonth) {
156
        yearMonth = new Date().toISOString().slice(0, 7);
157
    }
158
    if (confirm(`Publish all unpublished offers for ${yearMonth}?`)) {
159
        doPostAjaxRequestHandler(`${context}/offers/publishAll?yearMonth=${yearMonth}`, function (response) {
160
            alert(response);
161
            loadOfferHistory('#main-content', yearMonth);
162
        });
163
    }
164
});
33660 amit.gupta 165
$(document).on('click', 'button.slab-add', function () {
166
    newTargetSlab = $(targetSlabTemplate);
167
    $('div.targetslabscontainer').append(newTargetSlab);
168
    newTargetSlab.find("select.criteria-brands").toggle().next().remove();
169
    newTargetSlab.find("select.criteria-brands").chosen({no_results_text: "Oops, nothing found!"});
27875 amit.gupta 170
});
33660 amit.gupta 171
$(document).on('click', 'button.slab-remove', function () {
172
    targetSlabContainer = $('div.targetslabscontainer');
173
    if (targetSlabContainer.find(".targetslabs").length > 1) {
174
        targetSlabContainer.find(".targetslabs:last").remove();
175
    } else {
176
        alert("Cant remove single Slab");
177
    }
27875 amit.gupta 178
});
33660 amit.gupta 179
$(document).on('click', 'button.slab-copy', function () {
180
    newTargetSlab = $('div.targetslabs').eq(0).clone().appendTo('div.targetslabscontainer');
181
    catalogIdSelectContainers = $('div.targetslabs').eq(0).find('select.criteria-catalogids');
182
    newCatalogIdSelectContainers = newTargetSlab.find('select.criteria-catalogids');
35219 amit 183
    for (let i = 0; i < 15; i++) {
33660 amit.gupta 184
        let selectContainer = catalogIdSelectContainers.get(i);
185
        let newSelectContainer = newCatalogIdSelectContainers.get(i);
186
        for (let j = 0; j < selectContainer.options.length; j++) {
187
            newSelectContainer.options[j].selected = selectContainer.options[j].selected;
188
        }
189
        newSelectContainer.closest('span').replaceWith(newSelectContainer);
190
        $(newSelectContainer).multiselect({
191
            includeSelectAllOption: true,
192
            maxHeight: 400,
193
            buttonWidth: '240px',
194
            numberDisplayed: 1,
195
            nonSelectedText: 'Items',
196
            nSelectedText: ' - Items Selected',
197
            allSelectedText: 'All Items Selected',
198
            enableFiltering: true,
199
            enableCaseInsensitiveFiltering: true,
200
        });
201
    }
202
    selectContainers = newTargetSlab.find("select.criteria-brands");
203
    selectContainers.each((y, x) => {
204
        $next = $(x).toggle().next();
205
        $next.find("a.search-choice-close").each(function (index, ele) {
206
            x.options[$(ele).data('option-array-index') + 0].selected = true;
207
        });
208
        $next.remove();
209
    });
210
    newTargetSlab.find("select.criteria-brands").chosen({no_results_text: "Oops, nothing found!"});
211
    //createSlabFrom(currentHtml);
27875 amit.gupta 212
});
213
 
34210 tejus.loha 214
$(document).on('click', '.scheme_block_imeis_panel', function () {
215
    reloadBlockImeiPanel();
216
    $('div.modal-backdrop.fade').remove();
217
 
218
 
219
});
220
 
221
$(document).on('click', '.eligible_offer_imeis_panel', function () {
34216 tejus.loha 222
    doGetAjaxRequestHandler(`${context}/offerEligibleImeis/panel`, function (response) {
34210 tejus.loha 223
        $('#main-content').html(response);
224
    });
225
    $('div.modal-backdrop.fade').remove();
226
 
227
 
228
});
229
 
230
 
231
$(document).on('click', '#submit_scheme_block_imeis', function () {
232
    let blockImei = $('#block_imei_scheme').val();
233
    console.log("blockImei - ", blockImei);
234
    if (!blockImei) {
235
        alert("Please enter Imei");
236
        return;
237
    }
238
 
239
    let url = `${context}/createBlockImei?imeiNumbers=${blockImei}`;
240
    if (confirm('Are you sure to block all enter Imei numbers')) {
241
        doPostAjaxRequestHandler(url, function (response) {
242
            if (response) {
243
                alert("Imei blocked successfully");
244
                reloadBlockImeiList();
245
            }
246
        });
247
    } else {
248
        return;
249
    }
250
 
251
});
252
$(document).on('click', '#submit_offer_eligible_imeis', function () {
34216 tejus.loha 253
    let eligibleImeis = $('#offer_eligible_imeis').val();
34210 tejus.loha 254
    let offerId = $('#offerId').val();
34216 tejus.loha 255
    console.log("Eligible Imeeis - ", eligibleImeis);
34210 tejus.loha 256
    console.log("offer id - ", offerId);
257
    if (!offerId) {
258
        alert("Please enter Offer Id");
259
        return;
260
    }
34216 tejus.loha 261
    if (!eligibleImeis) {
262
        alert("Please enter Imei");
263
        return;
264
    }
265
 
266
    let url = `${context}/offerEligibleImeis/create?imeis=${eligibleImeis}&offerId=${offerId}`;
267
    if (confirm('Are you sure to submit')) {
34210 tejus.loha 268
        doPostAjaxRequestHandler(url, function (response) {
269
            if (response) {
270
                reloadOfferEligibleImeisList();
271
                alert("submited successfully");
272
            }
273
        });
274
    } else {
275
        return;
276
    }
277
});
278
 
279
 
280
$(document).on('click', '.scheme_imei_block_unblock_button', function () {
281
    let blockedImeiId = $(this).val();
282
    if (confirm("Are you sure to change status")) {
283
        doPutAjaxRequestHandler(`${context}/blockUnblockImei?id=${blockedImeiId}`, function (response) {
284
            reloadBlockImeiList();
285
        });
286
    } else {
287
        return;
288
    }
289
});
290
 
291
$(document).on('click', '.offer_eligible_imeis_EligibilityChange_button', function () {
292
    let blockedImeiId = $(this).val();
293
    if (confirm("Are you sure to change status")) {
34216 tejus.loha 294
        doPutAjaxRequestHandler(`${context}/offerEligibleImeis/changeStatus?id=${blockedImeiId}`, function (response) {
34210 tejus.loha 295
            reloadOfferEligibleImeisList();
296
            alert("Status changed successfully");
297
        });
298
    } else {
299
        return;
300
    }
301
});
302
 
303
$(document).on('click', '.scheme_blocked_imei_remove_button', function () {
304
    let blockedImeiId = $(this).val();
305
    if (confirm("Are you sure to remove")) {
306
        doDeleteAjaxRequestHandler(`${context}/removeBlockedImei?id=${blockedImeiId}`, function (response) {
307
            if (response) {
308
                reloadBlockImeiList();
309
            }
310
        });
311
    } else {
312
        return;
313
    }
314
 
315
 
316
});
317
$(document).on('click', '.offer_eligible_imei_remove_button', function () {
318
    let offerId = $(this).val();
319
    if (confirm("Are you sure to remove")) {
34216 tejus.loha 320
        doDeleteAjaxRequestHandler(`${context}/offerEligibleImeis/deleteByOfferId?offerId=${offerId}`, function (response) {
34210 tejus.loha 321
            if (response) {
322
                reloadOfferEligibleImeisList();
323
                alert("Removed successfully");
324
            }
325
        });
326
    } else {
327
        return;
328
    }
329
});
330
 
331
function reloadBlockImeiPanel() {
332
    doGetAjaxRequestHandler(`${context}/blockImeiPanel`, function (response) {
333
        $('#main-content').html(response);
334
    });
335
    // $('div.modal-backdrop.fade').remove();
336
}
337
function reloadBlockImeiOfferPanel() {
338
    doGetAjaxRequestHandler(`${context}/blockImeiOfferPanel`, function (response) {
339
        $('#main-content').html(response);
340
    });
341
    $('div.modal-backdrop.fade').remove();
342
}
343
 
344
function reloadBlockImeiList() {
345
    doGetAjaxRequestHandler(`${context}/blockImeiList`, function (response) {
346
        $('#scheme_blocked_imeis_div').empty();
347
        $('#scheme_blocked_imeis_div').html(response);
348
    });
349
}
350
 
351
function reloadOfferEligibleImeisList() {
34216 tejus.loha 352
    doGetAjaxRequestHandler(`${context}/offerEligibleImeis/allList`, function (response) {
34210 tejus.loha 353
        $('#offer_eligible_imeis_div').empty();
354
        $('#offer_eligible_imeis_div').html(response);
355
 
356
    });
357
}
358
 
33660 amit.gupta 359
$(document).on('click', 'select.criteria-catalogids+div > button', function () {
360
    if (changed) {
361
        let brands = $(this).closest('.item-criteria').find('select').val();
362
        let led = $(this).closest('.item-criteria').find('input[name=led]').is(":checked");
363
        let tablet = $(this).closest('.item-criteria').find('input[name=tablet]').is(":checked");
364
        let smartWatch = $(this).closest('.item-criteria').find('input[name=smartwatch]').is(":checked");
35497 ranu 365
        let openBoxLapTops = $(this).closest('.item-criteria').find('input[name=openboxlaptops]').is(":checked");
33660 amit.gupta 366
        $brandsContainer = $(this);
367
        let categoryId = 3;
368
        if (led) {
369
            categoryId = 14202;
370
        }
371
        if (tablet) {
372
            categoryId = 10010;
373
        }
374
        if (smartWatch) {
375
            categoryId = 6;
376
        }
35497 ranu 377
 
378
        if (openBoxLapTops) {
35498 ranu 379
            categoryId = 6;
35497 ranu 380
        }
33660 amit.gupta 381
        var url = `${context}/entity?brands=${brands.join(",")}&categoryId=${categoryId}&limit=0`;
382
        $select = $brandsContainer.closest('.item-criteria').find('.criteria-catalogids');
383
        $select.html('');
384
        if (brands.length > 0) {
385
            doGetAjaxRequestHandler(url, function (response) {
386
                data = JSON.parse(response);
387
                for (i = 0; i < data.length; i++) {
388
                    $select.append(`<option value="${data[i].catalogId_i}">${data[i].title_s}</option>`);
389
                }
390
                $select.multiselect('rebuild');
391
            });
392
        } else {
393
            $select.html('');
394
            $select.multiselect('rebuild');
395
        }
396
        changed = !changed;
397
    }
27875 amit.gupta 398
});
399
 
30485 tejbeer 400
var ckEditor;
401
 
27875 amit.gupta 402
function createOfferNew() {
33660 amit.gupta 403
    let validated = true;
404
    let rangePicker = getDatesFromPicker('input[name="dateRange"]');
405
    let createOfferRequest = {};
406
    createOfferRequest['name'] = $("#offer_name").val();
407
    createOfferRequest['startDate'] = rangePicker.startDate;
408
    createOfferRequest['endDate'] = rangePicker.endDate;
409
    createOfferRequest['offerNotes'] = $("#offer_notes").val();
410
    createOfferRequest['baseCriteria'] = $("input[name=base_criteria]").is(":checked");
411
    createOfferRequest['terms'] = ckEditor.getData() //$("#offer_terms").val();
412
    createOfferRequest['targetType'] = $("input[name=targetType]:checked").val();
413
    createOfferRequest['payoutType'] = $("input[name=payoutType]:checked").val();
414
    createOfferRequest['schemeType'] = $("select[name=schemeType]").val();
415
    createOfferRequest['booster'] = false;
416
    createOfferRequest['activationBrands'] = null;
32065 amit.gupta 417
    createOfferRequest['discount'] = $("input[name=discount]").is(':checked');
33660 amit.gupta 418
    if (createOfferRequest['schemeType'] == 'ACTIVATION') {
419
        createOfferRequest['activationBrands'] = $("div.activation-brands select").val().join(",") || null;
420
    } else if (createOfferRequest['schemeType'] == 'SELLINBOOSTER') {
421
        createOfferRequest['schemeType'] = 'SELLIN';
422
        createOfferRequest['booster'] = true;
423
    }
424
    createOfferRequest['sellinPercentage'] = $("#sellinPercentage").val();
425
    createOfferRequest['brandShareTerms'] = $('#brandShare').val();
426
    createOfferRequest['partnerCriteria'] = {};
427
    createOfferRequest['partnerCriteria']['fofoIds'] = ($("#partners").val() || []).map(Number);
428
    createOfferRequest['partnerCriteria']['excludeFofoIds'] = [];
429
    let excludeFofoIdChecked = $('input.excludeFofoId').is(':checked');
430
    if (excludeFofoIdChecked) {
431
        createOfferRequest['partnerCriteria']['excludeFofoIds'] = createOfferRequest['partnerCriteria']['fofoIds'];
432
        createOfferRequest['partnerCriteria']['fofoIds'] = [];
433
    }
434
    createOfferRequest['partnerCriteria']['partnerTypes'] = ($("select.criteria-partner-type").val() || []);
435
    createOfferRequest['partnerCriteria']['regionIds'] = ($("select.criteria-warehouseregion").val() || []).map(Number);
27875 amit.gupta 436
 
33660 amit.gupta 437
    createOfferRequest['itemCriteria'] = itemCriteria($('div.itemCriteria'));
438
    let targetSlabs = [];
439
    $('div.targetslabs').each(function (index, ele) {
440
        let $targetSlab = $(ele);
441
        let targetOnwardsValue = $targetSlab.find('.payoutTarget').val();
442
        let targetDescription = $targetSlab.find('.targetDescription').val();
443
        let itemCriteriaPayouts = [];
444
        if (isNaN(targetOnwardsValue) || targetOnwardsValue < 0) {
445
            validated = false;
446
            alert(`Invalid Number - ${targetOnwardsValue}`);
447
        } else {
448
            if (index == 0 || targetOnwardsValue > 0) {
449
                let $itemCriteriaPayoutContainers = $targetSlab.find('.itemcriteriapayout');
450
                $itemCriteriaPayoutContainers.each(function (index, itemCriteriaPayoutContainer) {
451
                    let $itemCriteriaPayoutContainer = $(itemCriteriaPayoutContainer);
452
                    let amountType = $itemCriteriaPayoutContainer.find('input[name^=amountType]:checked').val();
453
                    let startDate = $itemCriteriaPayoutContainer.find('input.startDate').val();
454
                    let endDate = $itemCriteriaPayoutContainer.find('input.endDate').val();
455
                    if ((startDate == "" && endDate != "") && (startDate != "" && endDate == "")) {
456
                        alert("Criteria specific date is required");
457
                        return false;
458
                    }
459
                    let payoutSlabs = [];
460
                    let itemCriteria1 = itemCriteria($itemCriteriaPayoutContainer);
461
                    let $payoutSlabContainers = $itemCriteriaPayoutContainer.find('.slab');
462
                    let itemCriteriaChanged = itemCriteria1['smartPhone'] || itemCriteria1['featuredPhone']
463
                        || itemCriteria1['catalogIds'].length > 0 || itemCriteria1['brands'].length > 0
464
                        || itemCriteria1['excludeCatalogIds'].length > 0
465
                        || itemCriteria1['startPrice'] > 0 || itemCriteria1['endPrice'] > itemCriteria1['startPrice'] > 0;
466
                    if (itemCriteriaChanged || index == 0) {
467
                        $payoutSlabContainers.each(function (slabContainerIndex, slabContainer) {
468
                            let $slab = $(slabContainer);
30485 tejbeer 469
 
33660 amit.gupta 470
                            let slabOnwardsAmount = $slab.find('.slabOnwardsAmount').val();
471
                            if (isNaN(slabOnwardsAmount) || slabOnwardsAmount < 0) {
472
                                validated = false;
473
                                alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
474
                            } else {
475
                                if (slabContainerIndex == 0 || slabOnwardsAmount > 0) {
476
                                    let payoutAmount = $slab.find('.payoutValue').val();
477
                                    if (isNaN(payoutAmount) || payoutAmount <= 0) {
478
                                        validated = false;
479
                                        alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
480
                                    }
481
                                    let payoutSlab = {
482
                                        onwardsAmount: Number(slabOnwardsAmount),
483
                                        payoutAmount: Number(payoutAmount)
484
                                    }
485
                                    payoutSlabs.push(payoutSlab);
486
                                }
487
                            }
488
                        });
489
                        let itemCriteriaPayout = {
490
                            itemCriteria: itemCriteria1,
491
                            payoutSlabs: payoutSlabs,
492
                            amountType: amountType,
493
                            startDate: jsonStartDate(startDate),
494
                            endDate: jsonEndDate(endDate)
495
                        };
496
                        itemCriteriaPayouts.push(itemCriteriaPayout);
497
                    }
498
                });
499
                targetSlabs.push({
500
                    onwardsAmount: targetOnwardsValue,
501
                    targetDescription: targetDescription,
502
                    itemCriteriaPayouts: itemCriteriaPayouts
503
                });
504
            }
505
        }
506
    });
507
    createOfferRequest['targetSlabs'] = targetSlabs;
508
    if (validated && confirm("Confirm creating scheme offer")) {
509
        console.log("Validated");
510
        console.log(createOfferRequest);
511
        doPostAjaxRequestWithJsonHandler(`${context}/createOffer`, JSON.stringify(createOfferRequest), function (response) {
512
            alert("Offer created successfully");
513
            let dt = new Date();
514
            loadOfferHistory('#main-content', new Date().toISOString().slice(0, 7));
515
        });
516
    } else {
517
        console.log("Invalid Offer");
518
    }
27875 amit.gupta 519
}
520
 
521
function itemCriteria($container) {
33660 amit.gupta 522
    let smartPhone = $container.find("input[name=smartphone]").is(":checked");
523
    let featuredPhone = $container.find("input[name=featuredphone]").is(":checked");
524
    let led = $container.find("input[name=led]").is(":checked");
525
    let smartWatch = $container.find("input[name=smartwatch]").is(":checked");
526
    let catalogIds = $container.find('.criteria-catalogids').val() || [];
527
    let excludeCatalogIds = [];
528
    let excludeChecked = $container.find('input.exclude').is(':checked');
529
    if (excludeChecked) {
530
        excludeCatalogIds = catalogIds;
531
        catalogIds = [];
532
    }
533
    let brands = $container.find('.criteria-brands').val() || [];
534
    return {
535
        startPrice: Number($container.find('.startValue').val()),
536
        endPrice: Number($container.find('.endValue').val()),
537
        catalogIds: catalogIds.map(Number),
538
        excludeCatalogIds: excludeCatalogIds.map(Number),
539
        brands: brands,
540
        smartPhone: smartPhone,
541
        featuredPhone: featuredPhone,
542
        smartWatch: smartWatch,
543
        led: led
544
    };
27875 amit.gupta 545
}
546
 
547
function loadOffer(domId) {
33660 amit.gupta 548
    console.log(domId);
549
    doGetAjaxRequestHandler(context + "/getCreateOffer", function (response) {
550
        $('#' + domId).html(response);
30485 tejbeer 551
 
33660 amit.gupta 552
        DecoupledEditor
553
            .create(document.querySelector('#offer_terms'))
30485 tejbeer 554
 
555
 
33660 amit.gupta 556
            .then(newEditor => {
557
                const toolbarContainer = document.querySelector('#toolbar-container');
30485 tejbeer 558
 
33660 amit.gupta 559
                toolbarContainer.appendChild(newEditor.ui.view.toolbar.element);
30485 tejbeer 560
 
33660 amit.gupta 561
                ckEditor = newEditor
562
            })
563
            .catch(error => {
564
                console.error(error);
565
            });
30485 tejbeer 566
 
33660 amit.gupta 567
    });
568
}
30485 tejbeer 569
 
27875 amit.gupta 570
function loadOfferHistory(domId, yearMonth) {
33660 amit.gupta 571
    doGetAjaxRequestHandler(`${context}/offerHistory?yearMonth=${yearMonth}`, function (response) {
572
        $(domId).html(response);
573
        $(domId).find("#yearmonth").val(yearMonth);
574
    });
27875 amit.gupta 575
}
576
 
35886 amit 577
// ===== Offer Partner & Target Management =====
578
 
579
// Manage Partners - open modal
580
$(document).on('click', 'a.manage_offer_partners', function () {
581
    let offerId = $(this).closest('tr').data('offerid');
582
    doGetAjaxRequestHandler(`${context}/offer/partners?offerId=${offerId}`, function (data) {
583
        $('#offerDescription .modal-content').html(data);
584
        $("#offerDescription").modal('show');
585
    });
586
});
587
 
588
// Select All checkbox
589
$(document).on('change', '#select-all-partners', function () {
590
    $('.partner-checkbox').prop('checked', $(this).is(':checked'));
591
});
592
 
593
// Remove Selected Partners - show options
594
$(document).on('click', '.remove-selected-partners', function () {
595
    let checked = $('.partner-checkbox:checked');
596
    if (checked.length === 0) {
597
        alert("Please select at least one partner to remove.");
598
        return;
599
    }
600
    $('#remove-options').show();
601
});
602
 
603
// Cancel remove
604
$(document).on('click', '.cancel-remove-partners', function () {
605
    $('#remove-options').hide();
606
    $('#create-new-offer-checkbox').prop('checked', false);
607
    $('#custom-targets-section').hide();
608
});
609
 
610
// Toggle custom targets section
611
$(document).on('change', '#create-new-offer-checkbox', function () {
612
    if ($(this).is(':checked')) {
613
        $('#custom-targets-section').show();
614
    } else {
615
        $('#custom-targets-section').hide();
616
    }
617
});
618
 
619
// Confirm Remove Partners
620
$(document).on('click', '.confirm-remove-partners', function () {
621
    let offerId = $('#offer-partners-table').data('offerid');
622
    let fofoIds = [];
623
    $('.partner-checkbox:checked').each(function () {
624
        fofoIds.push($(this).val());
625
    });
626
    let createNewOffer = $('#create-new-offer-checkbox').is(':checked');
627
    let targets = [];
628
    if (createNewOffer) {
629
        $('.new-offer-target').each(function () {
630
            targets.push($(this).val());
631
        });
632
    }
633
 
634
    let url = `${context}/offer/removePartners?offerId=${offerId}&fofoIds=${fofoIds.join(',')}`;
635
    url += `&createNewOffer=${createNewOffer}`;
636
    if (createNewOffer && targets.length > 0) {
637
        url += `&targets=${targets.join(',')}`;
638
    }
639
 
640
    if (confirm("Are you sure you want to remove " + fofoIds.length + " partner(s) from this offer?")) {
641
        doPostAjaxRequestHandler(url, function (response) {
642
            let data = typeof response === 'string' ? JSON.parse(response) : response;
643
            alert(data.message || "Partners removed successfully.");
644
            $('#offerDescription').modal('hide');
645
            let yearMonth = data.yearMonth || $("#yearmonth").val() || new Date().toISOString().slice(0, 7);
646
            loadOfferHistory('#main-content', yearMonth);
647
        });
648
    }
649
});
650
 
651
// Add Partners
652
$(document).on('click', '.add-selected-partners', function () {
653
    let offerId = $('#offer-partners-table').data('offerid');
654
    if (!offerId) {
655
        offerId = $(this).closest('.modal-body').find('[data-offerid]').data('offerid');
656
    }
657
    let selectedFofoIds = $('#add-partner-select').val();
658
    if (!selectedFofoIds || selectedFofoIds.length === 0) {
659
        alert("Please select at least one partner to add.");
660
        return;
661
    }
662
 
663
    let url = `${context}/offer/addPartners?offerId=${offerId}&fofoIds=${selectedFofoIds.join(',')}`;
664
    if (confirm("Add " + selectedFofoIds.length + " partner(s) to Offer #" + offerId + "?")) {
665
        doPostAjaxRequestHandler(url, function (response) {
666
            let data = typeof response === 'string' ? JSON.parse(response) : response;
667
            alert(data.message || "Partners added successfully.");
668
            // Reload the modal to show updated partner list
669
            doGetAjaxRequestHandler(`${context}/offer/partners?offerId=${offerId}`, function (modalData) {
670
                $('#offerDescription .modal-content').html(modalData);
671
            });
672
        });
673
    }
674
});
675
 
35925 amit 676
// Update Offer Targets & Payouts (per slab)
677
$(document).on('click', '.update-offer-slabs', function () {
678
    let offerId = $('#edit-slabs-table').data('offerid');
679
    let slabs = [];
680
 
681
    $('#edit-slabs-table tbody tr').each(function () {
682
        let $target = $(this).find('.edit-slab-target');
683
        let $payout = $(this).find('.edit-slab-payout');
684
        if ($target.length) {
685
            slabs.push({
686
                id: parseInt($target.data('slabid')),
687
                payoutTarget: parseInt($target.val()),
688
                payoutValue: parseFloat($payout.val())
689
            });
690
        }
35886 amit 691
    });
692
 
35925 amit 693
    if (slabs.length === 0) {
694
        alert("No slabs to update.");
35886 amit 695
        return;
696
    }
697
 
35925 amit 698
    if (confirm("Update targets & payouts for Offer #" + offerId + "?")) {
699
        $.ajax({
700
            url: context + '/offer/updateSlabs',
701
            type: 'POST',
702
            contentType: 'application/json',
703
            data: JSON.stringify({ offerId: offerId, slabs: slabs }),
704
            success: function (response) {
705
                alert("Targets & payouts updated for Offer #" + offerId + ".");
706
                $('#offerDescription').modal('hide');
707
                let yearMonth = $("#yearmonth").val() || new Date().toISOString().slice(0, 7);
708
                loadOfferHistory('#main-content', yearMonth);
709
            },
710
            error: function (xhr) {
711
                alert("Failed to update: " + (xhr.responseJSON ? xhr.responseJSON.statusMessage : xhr.statusText));
712
            }
35886 amit 713
        });
714
    }
715
});
716