Subversion Repositories SmartDukaan

Rev

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