Subversion Repositories SmartDukaan

Rev

Rev 36054 | Rev 36522 | 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 () {
36054 amit 66
        let payoutType = $('input[name=payoutType]:checked').val();
67
        let holder1 = payoutType == "QUANTITY" ? "Qty" : "Rs.";
68
        let holder2 = payoutType == "QUANTITY" ? "pc(s) onwards, " : "onwards,";
33660 amit.gupta 69
        let holder3 = "% of value";
70
        if ($(this).val() == "FIXED") {
71
            holder3 = "per pc";
72
        } else if ($(this).val() == "SLAB_FIXED") {
73
            holder3 = "";
74
        }
75
        let slabHtml = `<div class="input-group slab">
27875 amit.gupta 76
        	<span class="input-group-addon">${holder1}</span>
77
        	<input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
78
        	<span class="input-group-addon">${holder2}</span>
79
        	<input type="text" class="form-control payoutValue"  value="0"/>
80
        	<span class="input-group-addon">${holder3}</span>
81
        	</div>`;
35219 amit 82
        $(this).closest('.itemcriteriapayout').find('div.slab-container').html(slabHtml.repeat(15));
33660 amit.gupta 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
    $allSlabContainers = $('div.slab-container');
104
    $('div.slab-payout input:radio[value="PERCENTAGE"]').prop('checked', true);
36052 amit 105
    $('div.slab-payout input:radio[value!="PERCENTAGE"]').prop('checked', false).prop('disabled', false);
33660 amit.gupta 106
    if ($(this).val() == "QUANTITY") {
107
        holder1 = "Qty";
108
        holder2 = "pc(s) onwards, ";
109
    }
36054 amit 110
    let holder3 = "% of value";
111
    $allSlabContainers.each(function() {
112
        let slabHtml = `<div class="input-group slab">
113
        	<span class="input-group-addon">${holder1}</span>
114
        	<input  type="text" class="slabOnwardsAmount form-control"  value="0"/>
115
        	<span class="input-group-addon">${holder2}</span>
116
        	<input type="text" class="form-control payoutValue"  value="0"/>
117
        	<span class="input-group-addon">${holder3}</span>
118
        	</div>`;
119
        $(this).html(slabHtml.repeat(15));
120
    });
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;
36452 amit 404
    if (!$("#offer_reference").val() || $("#offer_reference").val().trim() === '') {
405
        alert("Reference is required");
406
        $("#offer_reference").focus();
407
        return;
408
    }
33660 amit.gupta 409
    let rangePicker = getDatesFromPicker('input[name="dateRange"]');
410
    let createOfferRequest = {};
411
    createOfferRequest['name'] = $("#offer_name").val();
412
    createOfferRequest['startDate'] = rangePicker.startDate;
413
    createOfferRequest['endDate'] = rangePicker.endDate;
414
    createOfferRequest['offerNotes'] = $("#offer_notes").val();
415
    createOfferRequest['baseCriteria'] = $("input[name=base_criteria]").is(":checked");
416
    createOfferRequest['terms'] = ckEditor.getData() //$("#offer_terms").val();
417
    createOfferRequest['targetType'] = $("input[name=targetType]:checked").val();
418
    createOfferRequest['payoutType'] = $("input[name=payoutType]:checked").val();
419
    createOfferRequest['schemeType'] = $("select[name=schemeType]").val();
420
    createOfferRequest['booster'] = false;
421
    createOfferRequest['activationBrands'] = null;
32065 amit.gupta 422
    createOfferRequest['discount'] = $("input[name=discount]").is(':checked');
36452 amit 423
    createOfferRequest['reference'] = $("#offer_reference").val();
33660 amit.gupta 424
    if (createOfferRequest['schemeType'] == 'ACTIVATION') {
425
        createOfferRequest['activationBrands'] = $("div.activation-brands select").val().join(",") || null;
426
    } else if (createOfferRequest['schemeType'] == 'SELLINBOOSTER') {
427
        createOfferRequest['schemeType'] = 'SELLIN';
428
        createOfferRequest['booster'] = true;
429
    }
430
    createOfferRequest['sellinPercentage'] = $("#sellinPercentage").val();
431
    createOfferRequest['brandShareTerms'] = $('#brandShare').val();
432
    createOfferRequest['partnerCriteria'] = {};
433
    createOfferRequest['partnerCriteria']['fofoIds'] = ($("#partners").val() || []).map(Number);
434
    createOfferRequest['partnerCriteria']['excludeFofoIds'] = [];
435
    let excludeFofoIdChecked = $('input.excludeFofoId').is(':checked');
436
    if (excludeFofoIdChecked) {
437
        createOfferRequest['partnerCriteria']['excludeFofoIds'] = createOfferRequest['partnerCriteria']['fofoIds'];
438
        createOfferRequest['partnerCriteria']['fofoIds'] = [];
439
    }
440
    createOfferRequest['partnerCriteria']['partnerTypes'] = ($("select.criteria-partner-type").val() || []);
441
    createOfferRequest['partnerCriteria']['regionIds'] = ($("select.criteria-warehouseregion").val() || []).map(Number);
27875 amit.gupta 442
 
33660 amit.gupta 443
    createOfferRequest['itemCriteria'] = itemCriteria($('div.itemCriteria'));
444
    let targetSlabs = [];
445
    $('div.targetslabs').each(function (index, ele) {
446
        let $targetSlab = $(ele);
447
        let targetOnwardsValue = $targetSlab.find('.payoutTarget').val();
448
        let targetDescription = $targetSlab.find('.targetDescription').val();
449
        let itemCriteriaPayouts = [];
450
        if (isNaN(targetOnwardsValue) || targetOnwardsValue < 0) {
451
            validated = false;
452
            alert(`Invalid Number - ${targetOnwardsValue}`);
453
        } else {
454
            if (index == 0 || targetOnwardsValue > 0) {
455
                let $itemCriteriaPayoutContainers = $targetSlab.find('.itemcriteriapayout');
456
                $itemCriteriaPayoutContainers.each(function (index, itemCriteriaPayoutContainer) {
457
                    let $itemCriteriaPayoutContainer = $(itemCriteriaPayoutContainer);
458
                    let amountType = $itemCriteriaPayoutContainer.find('input[name^=amountType]:checked').val();
459
                    let startDate = $itemCriteriaPayoutContainer.find('input.startDate').val();
460
                    let endDate = $itemCriteriaPayoutContainer.find('input.endDate').val();
461
                    if ((startDate == "" && endDate != "") && (startDate != "" && endDate == "")) {
462
                        alert("Criteria specific date is required");
463
                        return false;
464
                    }
465
                    let payoutSlabs = [];
466
                    let itemCriteria1 = itemCriteria($itemCriteriaPayoutContainer);
467
                    let $payoutSlabContainers = $itemCriteriaPayoutContainer.find('.slab');
468
                    let itemCriteriaChanged = itemCriteria1['smartPhone'] || itemCriteria1['featuredPhone']
469
                        || itemCriteria1['catalogIds'].length > 0 || itemCriteria1['brands'].length > 0
470
                        || itemCriteria1['excludeCatalogIds'].length > 0
471
                        || itemCriteria1['startPrice'] > 0 || itemCriteria1['endPrice'] > itemCriteria1['startPrice'] > 0;
472
                    if (itemCriteriaChanged || index == 0) {
473
                        $payoutSlabContainers.each(function (slabContainerIndex, slabContainer) {
474
                            let $slab = $(slabContainer);
30485 tejbeer 475
 
33660 amit.gupta 476
                            let slabOnwardsAmount = $slab.find('.slabOnwardsAmount').val();
477
                            if (isNaN(slabOnwardsAmount) || slabOnwardsAmount < 0) {
478
                                validated = false;
479
                                alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
480
                            } else {
481
                                if (slabContainerIndex == 0 || slabOnwardsAmount > 0) {
482
                                    let payoutAmount = $slab.find('.payoutValue').val();
483
                                    if (isNaN(payoutAmount) || payoutAmount <= 0) {
484
                                        validated = false;
485
                                        alert(`Invalid Payout Slab Amount - ${slabOnwardsAmount}`);
486
                                    }
487
                                    let payoutSlab = {
488
                                        onwardsAmount: Number(slabOnwardsAmount),
489
                                        payoutAmount: Number(payoutAmount)
490
                                    }
491
                                    payoutSlabs.push(payoutSlab);
492
                                }
493
                            }
494
                        });
495
                        let itemCriteriaPayout = {
496
                            itemCriteria: itemCriteria1,
497
                            payoutSlabs: payoutSlabs,
498
                            amountType: amountType,
499
                            startDate: jsonStartDate(startDate),
500
                            endDate: jsonEndDate(endDate)
501
                        };
502
                        itemCriteriaPayouts.push(itemCriteriaPayout);
503
                    }
504
                });
505
                targetSlabs.push({
506
                    onwardsAmount: targetOnwardsValue,
507
                    targetDescription: targetDescription,
508
                    itemCriteriaPayouts: itemCriteriaPayouts
509
                });
510
            }
511
        }
512
    });
513
    createOfferRequest['targetSlabs'] = targetSlabs;
514
    if (validated && confirm("Confirm creating scheme offer")) {
515
        console.log("Validated");
516
        console.log(createOfferRequest);
517
        doPostAjaxRequestWithJsonHandler(`${context}/createOffer`, JSON.stringify(createOfferRequest), function (response) {
518
            alert("Offer created successfully");
519
            let dt = new Date();
520
            loadOfferHistory('#main-content', new Date().toISOString().slice(0, 7));
521
        });
522
    } else {
523
        console.log("Invalid Offer");
524
    }
27875 amit.gupta 525
}
526
 
527
function itemCriteria($container) {
33660 amit.gupta 528
    let smartPhone = $container.find("input[name=smartphone]").is(":checked");
529
    let featuredPhone = $container.find("input[name=featuredphone]").is(":checked");
530
    let led = $container.find("input[name=led]").is(":checked");
531
    let smartWatch = $container.find("input[name=smartwatch]").is(":checked");
532
    let catalogIds = $container.find('.criteria-catalogids').val() || [];
533
    let excludeCatalogIds = [];
534
    let excludeChecked = $container.find('input.exclude').is(':checked');
535
    if (excludeChecked) {
536
        excludeCatalogIds = catalogIds;
537
        catalogIds = [];
538
    }
539
    let brands = $container.find('.criteria-brands').val() || [];
540
    return {
541
        startPrice: Number($container.find('.startValue').val()),
542
        endPrice: Number($container.find('.endValue').val()),
543
        catalogIds: catalogIds.map(Number),
544
        excludeCatalogIds: excludeCatalogIds.map(Number),
545
        brands: brands,
546
        smartPhone: smartPhone,
547
        featuredPhone: featuredPhone,
548
        smartWatch: smartWatch,
549
        led: led
550
    };
27875 amit.gupta 551
}
552
 
553
function loadOffer(domId) {
33660 amit.gupta 554
    console.log(domId);
555
    doGetAjaxRequestHandler(context + "/getCreateOffer", function (response) {
556
        $('#' + domId).html(response);
30485 tejbeer 557
 
33660 amit.gupta 558
        DecoupledEditor
559
            .create(document.querySelector('#offer_terms'))
30485 tejbeer 560
 
561
 
33660 amit.gupta 562
            .then(newEditor => {
563
                const toolbarContainer = document.querySelector('#toolbar-container');
30485 tejbeer 564
 
33660 amit.gupta 565
                toolbarContainer.appendChild(newEditor.ui.view.toolbar.element);
30485 tejbeer 566
 
33660 amit.gupta 567
                ckEditor = newEditor
568
            })
569
            .catch(error => {
570
                console.error(error);
571
            });
30485 tejbeer 572
 
33660 amit.gupta 573
    });
574
}
30485 tejbeer 575
 
27875 amit.gupta 576
function loadOfferHistory(domId, yearMonth) {
33660 amit.gupta 577
    doGetAjaxRequestHandler(`${context}/offerHistory?yearMonth=${yearMonth}`, function (response) {
578
        $(domId).html(response);
579
        $(domId).find("#yearmonth").val(yearMonth);
580
    });
27875 amit.gupta 581
}
582
 
35886 amit 583
// ===== Offer Partner & Target Management =====
584
 
585
// Manage Partners - open modal
586
$(document).on('click', 'a.manage_offer_partners', function () {
587
    let offerId = $(this).closest('tr').data('offerid');
588
    doGetAjaxRequestHandler(`${context}/offer/partners?offerId=${offerId}`, function (data) {
589
        $('#offerDescription .modal-content').html(data);
590
        $("#offerDescription").modal('show');
591
    });
592
});
593
 
594
// Select All checkbox
595
$(document).on('change', '#select-all-partners', function () {
596
    $('.partner-checkbox').prop('checked', $(this).is(':checked'));
597
});
598
 
599
// Remove Selected Partners - show options
600
$(document).on('click', '.remove-selected-partners', function () {
601
    let checked = $('.partner-checkbox:checked');
602
    if (checked.length === 0) {
603
        alert("Please select at least one partner to remove.");
604
        return;
605
    }
606
    $('#remove-options').show();
607
});
608
 
609
// Cancel remove
610
$(document).on('click', '.cancel-remove-partners', function () {
611
    $('#remove-options').hide();
612
    $('#create-new-offer-checkbox').prop('checked', false);
613
    $('#custom-targets-section').hide();
614
});
615
 
616
// Toggle custom targets section
617
$(document).on('change', '#create-new-offer-checkbox', function () {
618
    if ($(this).is(':checked')) {
619
        $('#custom-targets-section').show();
620
    } else {
621
        $('#custom-targets-section').hide();
622
    }
623
});
624
 
625
// Confirm Remove Partners
626
$(document).on('click', '.confirm-remove-partners', function () {
627
    let offerId = $('#offer-partners-table').data('offerid');
628
    let fofoIds = [];
629
    $('.partner-checkbox:checked').each(function () {
630
        fofoIds.push($(this).val());
631
    });
632
    let createNewOffer = $('#create-new-offer-checkbox').is(':checked');
633
    let targets = [];
634
    if (createNewOffer) {
635
        $('.new-offer-target').each(function () {
636
            targets.push($(this).val());
637
        });
638
    }
639
 
640
    let url = `${context}/offer/removePartners?offerId=${offerId}&fofoIds=${fofoIds.join(',')}`;
641
    url += `&createNewOffer=${createNewOffer}`;
642
    if (createNewOffer && targets.length > 0) {
643
        url += `&targets=${targets.join(',')}`;
644
    }
645
 
646
    if (confirm("Are you sure you want to remove " + fofoIds.length + " partner(s) from this offer?")) {
647
        doPostAjaxRequestHandler(url, function (response) {
648
            let data = typeof response === 'string' ? JSON.parse(response) : response;
649
            alert(data.message || "Partners removed successfully.");
650
            $('#offerDescription').modal('hide');
651
            let yearMonth = data.yearMonth || $("#yearmonth").val() || new Date().toISOString().slice(0, 7);
652
            loadOfferHistory('#main-content', yearMonth);
653
        });
654
    }
655
});
656
 
657
// Add Partners
658
$(document).on('click', '.add-selected-partners', function () {
659
    let offerId = $('#offer-partners-table').data('offerid');
660
    if (!offerId) {
661
        offerId = $(this).closest('.modal-body').find('[data-offerid]').data('offerid');
662
    }
663
    let selectedFofoIds = $('#add-partner-select').val();
664
    if (!selectedFofoIds || selectedFofoIds.length === 0) {
665
        alert("Please select at least one partner to add.");
666
        return;
667
    }
668
 
669
    let url = `${context}/offer/addPartners?offerId=${offerId}&fofoIds=${selectedFofoIds.join(',')}`;
670
    if (confirm("Add " + selectedFofoIds.length + " partner(s) to Offer #" + offerId + "?")) {
671
        doPostAjaxRequestHandler(url, function (response) {
672
            let data = typeof response === 'string' ? JSON.parse(response) : response;
673
            alert(data.message || "Partners added successfully.");
674
            // Reload the modal to show updated partner list
675
            doGetAjaxRequestHandler(`${context}/offer/partners?offerId=${offerId}`, function (modalData) {
676
                $('#offerDescription .modal-content').html(modalData);
677
            });
678
        });
679
    }
680
});
681
 
35925 amit 682
// Update Offer Targets & Payouts (per slab)
683
$(document).on('click', '.update-offer-slabs', function () {
684
    let offerId = $('#edit-slabs-table').data('offerid');
685
    let slabs = [];
686
 
687
    $('#edit-slabs-table tbody tr').each(function () {
688
        let $target = $(this).find('.edit-slab-target');
689
        let $payout = $(this).find('.edit-slab-payout');
690
        if ($target.length) {
691
            slabs.push({
692
                id: parseInt($target.data('slabid')),
693
                payoutTarget: parseInt($target.val()),
694
                payoutValue: parseFloat($payout.val())
695
            });
696
        }
35886 amit 697
    });
698
 
35925 amit 699
    if (slabs.length === 0) {
700
        alert("No slabs to update.");
35886 amit 701
        return;
702
    }
703
 
35925 amit 704
    if (confirm("Update targets & payouts for Offer #" + offerId + "?")) {
705
        $.ajax({
706
            url: context + '/offer/updateSlabs',
707
            type: 'POST',
708
            contentType: 'application/json',
709
            data: JSON.stringify({ offerId: offerId, slabs: slabs }),
710
            success: function (response) {
711
                alert("Targets & payouts updated for Offer #" + offerId + ".");
712
                $('#offerDescription').modal('hide');
713
                let yearMonth = $("#yearmonth").val() || new Date().toISOString().slice(0, 7);
714
                loadOfferHistory('#main-content', yearMonth);
715
            },
716
            error: function (xhr) {
717
                alert("Failed to update: " + (xhr.responseJSON ? xhr.responseJSON.statusMessage : xhr.statusText));
718
            }
35886 amit 719
        });
720
    }
721
});
722