Subversion Repositories SmartDukaan

Rev

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