Subversion Repositories SmartDukaan

Rev

Rev 36703 | Details | Compare with Previous | Last modification | View Log | RSS feed

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