Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
35289 amit 1
/*window.alert = function(message) {
33973 tejus.loha 2
    Swal.fire({
3
        text: message,
4
        icon: 'info',
5
        confirmButtonText: 'OK'
6
    });
35289 amit 7
};*/
27711 amit.gupta 8
const MAIN_CONTAINER = "#main-content";
24440 amit.gupta 9
var logosmapping = {
32301 amit.gupta 10
    mobile_insurance_providers: {
11
        "0": context + '/resources/images/icons/provider-logos/iffco.png',
12
        "1": context + '/resources/images/icons/provider-logos/icici.jpg',
13
        "2": context + '/resources/images/icons/provider-logos/tataaig.png',
14
        "3": context + '/resources/images/icons/provider-logos/bharti.jpg',
15
        "4": context + '/resources/images/icons/provider-logos/bharti.jpg',
16
        "5": context + '/resources/images/icons/provider-logos/oneassist.jpeg'
17
    }
24440 amit.gupta 18
}
30414 amit.gupta 19
 
33756 ranu 20
function uuidv4() {
21
    return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
22
        (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
23
    );
24
}
25
 
26
let IdempotencyKey = uuidv4();
27
 
24595 tejbeer 28
function badRequestAlert(response) {
33756 ranu 29
    //console.log(response.responseText);
30
    try {
31
        var errorObject = JSON.parse(response.responseText);
32
        errorObject = errorObject.response;
33
        bootbox.alert('Bad Request\n' + 'rejectedType : '
34
            + errorObject.rejectedType + '\n' + 'rejectedValue : '
35
            + errorObject.rejectedValue + '\n' + 'message : '
36
            + errorObject.message);
37
    } catch (e) {
33765 ranu 38
        console.log("response.responseText", response.responseText);
39
        bootbox.alert("Error occurred! Please contact your manager");
33756 ranu 40
    }
22956 ashik.ali 41
}
24595 tejbeer 42
 
43
function internalServerErrorAlert(response) {
33756 ranu 44
    // console.log(response.responseText);
45
    try {
46
        var errorObject = JSON.parse(response.responseText);
47
        errorObject = errorObject.response;
48
        bootbox.alert('Internal Server Error\n' + 'rejectedType : '
49
            + errorObject.rejectedType + '\n' + 'rejectedValue : '
50
            + errorObject.rejectedValue + '\n' + 'message : '
51
            + errorObject.message);
52
    } catch (e) {
33765 ranu 53
        console.log("response.responseText", response.responseText);
54
        bootbox.alert("Error occurred! Please contact your manager");
33756 ranu 55
    }
22956 ashik.ali 56
}
57
 
32301 amit.gupta 58
$(document).ajaxError(function (event, jqxhr, settings, thrownError) {
35459 amit 59
    if (typeof loaderDialogObj != "undefined") {
32301 amit.gupta 60
        loaderDialogObj.modal('hide');
35459 amit 61
        // $('div.modal-backdrop.fade').remove();
32301 amit.gupta 62
    }
35459 amit 63
    if (jqxhr.status == 400) {
64
        // $('#error-prompt-model').modal();
32301 amit.gupta 65
        badRequestAlert(jqxhr);
66
    } else {
67
        internalServerErrorAlert(jqxhr);
68
    }
22956 ashik.ali 69
});
70
 
36819 amit 71
$(document).ajaxSend(function (ev, req, settings) {
72
    // Attach the idempotency key only to state-changing requests. GET/HEAD are
73
    // safe/repeatable and must not be pulled into server-side dedup.
74
    var method = (settings && settings.type ? settings.type : 'GET').toUpperCase();
75
    if (method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE') {
76
        req.setRequestHeader('IdempotencyKey', IdempotencyKey);
77
    }
33788 ranu 78
});
79
 
35459 amit 80
$(document).ajaxSuccess(function () {
81
    IdempotencyKey = uuidv4();
82
    console.log('succcess handlor');
83
});
84
 
32301 amit.gupta 85
$(document).ajaxComplete(function () {
35459 amit 86
    if (typeof loaderDialogObj != "undefined") {
32301 amit.gupta 87
        loaderDialogObj.modal('hide');
35459 amit 88
        // $('div.modal-backdrop.fade').remove();
32301 amit.gupta 89
    }
36819 amit 90
    // NOTE: do NOT rotate IdempotencyKey here. ajaxComplete fires on every finish
91
    // (including errors/timeouts); rotating here gave each retry a fresh key and
92
    // defeated dedup. The key is reset only on confirmed success (ajaxSuccess),
93
    // so a logical action and all its retries share a single key.
23946 amit.gupta 94
});
30017 amit.gupta 95
 
24992 tejbeer 96
function ajaxStartHandler() {
35459 amit 97
    if (typeof loaderDialogObj != "undefined")
32301 amit.gupta 98
        loaderDialogObj.modal('show');
24976 amit.gupta 99
}
30017 amit.gupta 100
 
24976 amit.gupta 101
$(document).ajaxStart(ajaxStartHandler);
24595 tejbeer 102
 
34859 vikas 103
function doAjaxRequestWithParamsHandler(urlString, httpType, params, callback_function) {
32301 amit.gupta 104
    $.ajax({
105
        url: urlString,
106
        async: true,
107
        cache: false,
108
        data: params,
109
        // dataType:'json',
110
        type: httpType,
111
        success: function (response) {
33790 ranu 112
            IdempotencyKey = uuidv4();
32301 amit.gupta 113
            callback_function(response);
32308 amit.gupta 114
            formatCurrency();
32301 amit.gupta 115
        }
116
    });
23193 ashik.ali 117
}
118
 
24595 tejbeer 119
function doGetAjaxRequestWithParamsHandler(urlString, params, callback_function) {
32301 amit.gupta 120
    doAjaxRequestWithParamsHandler(urlString, "GET", params, callback_function);
23500 ashik.ali 121
}
122
 
33973 tejus.loha 123
function doPostAjaxRequestWithParamsHandler(urlString, params, callback_function) {
32301 amit.gupta 124
    doAjaxRequestWithParamsHandler(urlString, "POST", params, callback_function);
23500 ashik.ali 125
}
126
 
32308 amit.gupta 127
function formatCurrency() {
128
    $('.currency').each(function (index, ele) {
129
        if (!isNaN(parseInt($(ele).html()))) {
35510 amit 130
            $(ele).html(formatValueInCrore($(ele).html()));
32308 amit.gupta 131
        }
132
    });
133
 
134
}
135
 
33973 tejus.loha 136
function doAjaxRequestWithJsonHandler(urlString, httpType, json, callback_function) {
32301 amit.gupta 137
    $.ajax({
138
        url: urlString,
139
        async: true,
140
        cache: false,
141
        processData: false,
142
        data: json,
143
        contentType: 'application/json',
144
        type: httpType,
145
        success: function (response) {
146
            // console.log("response"+JSON.stringify(data));
147
            callback_function(response);
32308 amit.gupta 148
            formatCurrency();
36572 amit 149
        },
150
        error: function (xhr) {
151
            var msg = xhr.responseText || xhr.statusText || 'Unknown error';
152
            console.error(httpType + ' ' + urlString + ' failed: ' + xhr.status + ' - ' + msg);
153
            alert('Request failed: ' + msg);
32301 amit.gupta 154
        }
155
    });
23032 ashik.ali 156
}
157
 
24595 tejbeer 158
function doPostAjaxRequestWithJsonHandler(urlString, json, callback_function) {
32301 amit.gupta 159
    doAjaxRequestWithJsonHandler(urlString, "POST", json, callback_function);
23500 ashik.ali 160
}
23032 ashik.ali 161
 
24595 tejbeer 162
function doPutAjaxRequestWithJsonHandler(urlString, json, callback_function) {
32301 amit.gupta 163
    doAjaxRequestWithJsonHandler(urlString, "PUT", json, callback_function);
23500 ashik.ali 164
}
165
 
24595 tejbeer 166
function doAjaxRequestHandler(urlString, httpType, callback_function) {
32301 amit.gupta 167
    $.ajax({
168
        url: urlString,
169
        async: true,
170
        cache: false,
171
        type: httpType,
172
        success: function (response) {
173
            callback_function(response);
32308 amit.gupta 174
            formatCurrency();
36572 amit 175
        },
176
        error: function (xhr) {
177
            var msg = xhr.responseText || xhr.statusText || 'Unknown error';
178
            console.error(httpType + ' ' + urlString + ' failed: ' + xhr.status + ' - ' + msg);
179
            alert('Request failed: ' + msg);
32301 amit.gupta 180
        }
181
    });
22982 ashik.ali 182
}
183
 
24595 tejbeer 184
function doGetAjaxRequestHandler(urlString, callback_function) {
32301 amit.gupta 185
    doAjaxRequestHandler(urlString, "GET", callback_function);
23500 ashik.ali 186
}
187
 
24595 tejbeer 188
function doPutAjaxRequestHandler(urlString, callback_function) {
32301 amit.gupta 189
    doAjaxRequestHandler(urlString, "PUT", callback_function);
23500 ashik.ali 190
}
191
 
24595 tejbeer 192
function doPostAjaxRequestHandler(urlString, callback_function) {
32301 amit.gupta 193
    doAjaxRequestHandler(urlString, "POST", callback_function);
23629 ashik.ali 194
}
195
 
24595 tejbeer 196
function doDeleteAjaxRequestHandler(urlString, callback_function) {
32301 amit.gupta 197
    doAjaxRequestHandler(urlString, "DELETE", callback_function);
23783 ashik.ali 198
}
199
 
24595 tejbeer 200
function doAjaxUploadRequest(urlString, httpType, file) {
32301 amit.gupta 201
    var response;
202
    doAjaxUploadRequestHandler(urlString, httpType, file,
203
        function (ajaxResponse) {
204
            response = ajaxResponse;
205
        });
206
    return response;
23347 ashik.ali 207
}
208
 
34546 vikas.jang 209
function doAjaxUploadRequestHandler(urlString, httpType, file, callback_function) {
32301 amit.gupta 210
    var formData = new FormData();
211
    formData.append("file", file);
212
    $.ajax({
213
        url: urlString,
214
        type: httpType,
215
        data: formData,
216
        dataType: 'json',
217
        async: true,
218
        cache: false,
219
        contentType: false,
220
        enctype: 'multipart/form-data',
221
        processData: false,
222
        success: function (response) {
223
            // console.log("response"+JSON.stringify(data));
224
            callback_function(response);
225
        }
226
    });
22982 ashik.ali 227
}
30017 amit.gupta 228
 
34859 vikas 229
function doAjaxUploadRequestJsonHandler(urlString, httpType, file, json, callback_function) {
32301 amit.gupta 230
    var formData = new FormData();
231
    formData.append("file", file);
232
    formData.append('json', new Blob([json]));
233
    $.ajax({
234
        url: urlString,
235
        type: httpType,
236
        data: formData,
237
        enctype: 'multipart/form-data',
238
        contentType: false,
239
        processData: false,
240
        success: function (response) {
241
            // console.log("response"+JSON.stringify(data));
242
            callback_function(response);
243
        }
244
    });
24171 govind 245
}
22982 ashik.ali 246
 
33508 tejus.loha 247
function uploadDocument(file, callback) {
32301 amit.gupta 248
    var url = context + '/document-upload';
249
    doAjaxUploadRequestHandler(url, 'POST', file, function (response) {
250
        var documentId = response.response.document_id;
33756 ranu 251
        //console.log("documentId : " + documentId);
33508 tejus.loha 252
        callback(documentId);
32301 amit.gupta 253
    });
23347 ashik.ali 254
}
255
 
24595 tejbeer 256
function doAjaxGetDownload(urlString, fileName) {
33756 ranu 257
    // console.log("fileName : " + fileName);
32301 amit.gupta 258
    doAjaxDownload(urlString, "GET", null, fileName);
22982 ashik.ali 259
}
260
 
31702 amit.gupta 261
function doAjaxPostDownload(urlString, data, fileName, callback) {
32301 amit.gupta 262
    doAjaxDownload(urlString, "POST", data, fileName, callback);
21627 kshitij.so 263
}
264
 
31702 amit.gupta 265
function doAjaxDownload(urlString, httpType, data, fileName, callback) {
35459 amit 266
    xhttp = new XMLHttpRequest();
267
    if (typeof loaderDialogObj != "undefined")
32301 amit.gupta 268
        loaderDialogObj.modal('show');
269
    xhttp.onreadystatechange = function () {
35459 amit 270
        var a;
32301 amit.gupta 271
        if (xhttp.readyState === 2) {
35459 amit 272
            if (xhttp.status == 200) {
273
                xhttp.responseType = "blob";
274
            } else {
275
                xhttp.responseType = "text";
276
            }
277
        } else if (xhttp.readyState === 4 && xhttp.status === 200) {
278
            // Trick for making downloadable link
279
            if (typeof loaderDialogObj != "undefined") {
32301 amit.gupta 280
                loaderDialogObj.modal('hide');
35459 amit 281
                // $('div.modal-backdrop.fade').remove();
32301 amit.gupta 282
            }
35459 amit 283
 
284
            a = document.createElement('a');
285
            a.href = window.URL.createObjectURL(xhttp.response);
286
            // Give filename you wish to download
287
            a.download = fileName;
288
            a.style.display = 'none';
289
            document.body.appendChild(a);
290
            a.click();
291
        } else if (xhttp.readyState == 4 && xhttp.status === 400) {
292
            if (typeof loaderDialogObj != "undefined") {
293
                loaderDialogObj.modal('hide');
294
                // $('div.modal-backdrop.fade').remove();
32301 amit.gupta 295
            }
35459 amit 296
            badRequestAlert(xhttp);
297
        } else if (xhttp.readyState == 4 && xhttp.status === 500) {
298
            if (typeof loaderDialogObj != "undefined") {
299
                loaderDialogObj.modal('hide');
300
                // $('div.modal-backdrop.fade').remove();
301
            }
302
            internalServerErrorAlert(xhttp);
32301 amit.gupta 303
        }
304
    };
305
    // Post data to URL which handles post request
306
    xhttp.open(httpType, urlString);
33759 ranu 307
 
308
    // if (IdempotencyKey) {
309
    //     xhttp.setRequestHeader("IdempotencyKey", IdempotencyKey);
310
    // }
311
 
35459 amit 312
    if (httpType == "POST") {
32301 amit.gupta 313
        xhttp.setRequestHeader("Content-Type", "application/json");
314
    }
315
    // You should set responseType as blob for binary responses
316
    // xhttp.responseType = 'blob';
317
    xhttp.send(data);
23405 amit.gupta 318
}
30017 amit.gupta 319
 
27618 tejbeer 320
function loadPaginatedCatalogNextItems(url, params, paginatedIdentifier,
32301 amit.gupta 321
                                       tableIdentifier, detailsContainerIdentifier) {
322
    var start = $("#" + paginatedIdentifier + " .start").text();
23405 amit.gupta 323
 
32301 amit.gupta 324
    var end = $("#" + paginatedIdentifier + " .end").text();
27618 tejbeer 325
 
32301 amit.gupta 326
    url = context + url + "?offset=" + end;
27618 tejbeer 327
 
32301 amit.gupta 328
    if (params != null) {
329
        for (var key in params) {
330
            if (params.hasOwnProperty(key)) {
331
                //console.log(key + " -> " + params[key]);
332
                url = url + "&" + key + "=" + params[key];
333
            }
334
        }
335
    }
27618 tejbeer 336
 
32301 amit.gupta 337
    doGetAjaxRequestHandler(url, function (response) {
338
        var size = $("#" + paginatedIdentifier + " .size").text();
339
        if ((parseInt(end) + 20) > parseInt(size)) {
340
            // console.log("(end + 10) > size == true");
341
            $("#" + paginatedIdentifier + " .end").text(size);
342
        } else {
343
            // console.log("(end + 10) > size == false");
344
            $("#" + paginatedIdentifier + " .end").text(+end + +20);
345
        }
346
        $("#" + paginatedIdentifier + " .start").text(+start + +20);
347
        var last = $("#" + paginatedIdentifier + " .end").text();
348
        var temp = $("#" + paginatedIdentifier + " .size").text();
349
        console.log("last" + last);
350
        if (parseInt(last) >= parseInt(temp)) {
351
            $("#" + paginatedIdentifier + " .next").prop('disabled', true);
352
            // $( "#good-inventory-paginated .end" ).text(temp);
353
        }
354
        $('#' + tableIdentifier).html(response);
355
        if (detailsContainerIdentifier != null) {
356
            $('#' + detailsContainerIdentifier).html('');
357
        }
358
        $("#" + paginatedIdentifier + " .previous").prop('disabled', false);
359
    });
27618 tejbeer 360
 
361
}
30017 amit.gupta 362
 
27618 tejbeer 363
function loadPaginatedCatalogPreviousItem(url, params, paginatedIdentifier,
32301 amit.gupta 364
                                          tableIdentifier, detailsContainerIdentifier) {
365
    var start = $("#" + paginatedIdentifier + " .start").text();
33756 ranu 366
    //console.log("start" + start);
32301 amit.gupta 367
    var end = $("#" + paginatedIdentifier + " .end").text();
33756 ranu 368
    //console.log("Startend" + end);
32301 amit.gupta 369
    var size = $("#" + paginatedIdentifier + " .size").text();
33756 ranu 370
    //console.log("size" + size);
32301 amit.gupta 371
    if (parseInt(end) == parseInt(size) && parseInt(end) % 20 != 0) {
372
        var mod = parseInt(end) % 20;
373
        end = parseInt(end) + (20 - mod);
374
    }
375
    var pre = end - 20;
376
    var lat = pre - 20;
377
    //console.log("preCatalog" +pre);
27618 tejbeer 378
 
32301 amit.gupta 379
    url = context + url + "?offset=" + pre;
27618 tejbeer 380
 
32301 amit.gupta 381
    if (params != null) {
382
        for (var key in params) {
383
            if (params.hasOwnProperty(key)) {
384
                url = url + "&" + key + "=" + params[key];
385
            }
386
        }
387
    }
27618 tejbeer 388
 
32301 amit.gupta 389
    doGetAjaxRequestHandler(url, function (response) {
390
        $("#" + paginatedIdentifier + " .end").text(+end - +20);
391
        $("#" + paginatedIdentifier + " .start").text(+start - +20);
392
        $('#' + tableIdentifier).html(response);
393
        if (detailsContainerIdentifier != null) {
394
            $('#' + detailsContainerIdentifier).html('');
395
        }
396
        $("#" + paginatedIdentifier + " .next").prop('disabled', false);
397
        if (parseInt(lat) == 0) {
398
            $("#" + paginatedIdentifier + " .previous").prop('disabled', true);
399
        }
400
    });
27618 tejbeer 401
 
402
}
403
 
24595 tejbeer 404
function loadPaginatedNextItems(url, params, paginatedIdentifier,
32301 amit.gupta 405
                                tableIdentifier, detailsContainerIdentifier) {
406
    var start = $("#" + paginatedIdentifier + " .start").text();
407
    var end = $("#" + paginatedIdentifier + " .end").text();
408
    url = context + url + "?offset=" + end;
24595 tejbeer 409
 
32301 amit.gupta 410
    if (params != null) {
411
        for (var key in params) {
412
            if (params.hasOwnProperty(key)) {
413
                // console.log(key + " -> " + p[key]);
414
                url = url + "&" + key + "=" + params[key];
415
            }
416
        }
417
    }
24595 tejbeer 418
 
32301 amit.gupta 419
    doGetAjaxRequestHandler(url, function (response) {
420
        var size = $("#" + paginatedIdentifier + " .size").text();
421
        if ((parseInt(end) + 10) > parseInt(size)) {
422
            console.log("(end + 10) > size == true");
423
            $("#" + paginatedIdentifier + " .end").text(size);
424
        } else {
425
            console.log("(end + 10) > size == false");
426
            $("#" + paginatedIdentifier + " .end").text(+end + +10);
427
        }
428
        $("#" + paginatedIdentifier + " .start").text(+start + +10);
429
        var last = $("#" + paginatedIdentifier + " .end").text();
430
        var temp = $("#" + paginatedIdentifier + " .size").text();
431
        if (parseInt(last) >= parseInt(temp)) {
432
            $("#" + paginatedIdentifier + " .next").prop('disabled', true);
433
            // $( "#good-inventory-paginated .end" ).text(temp);
434
        }
435
        $('#' + tableIdentifier).html(response);
436
        if (detailsContainerIdentifier != null) {
437
            $('#' + detailsContainerIdentifier).html('');
438
        }
439
        $("#" + paginatedIdentifier + " .previous").prop('disabled', false);
440
    });
24595 tejbeer 441
 
23629 ashik.ali 442
}
23405 amit.gupta 443
 
24595 tejbeer 444
function loadPaginatedPreviousItems(url, params, paginatedIdentifier,
32301 amit.gupta 445
                                    tableIdentifier, detailsContainerIdentifier) {
446
    var start = $("#" + paginatedIdentifier + " .start").text();
447
    var end = $("#" + paginatedIdentifier + " .end").text();
448
    var size = $("#" + paginatedIdentifier + " .size").text();
449
    if (parseInt(end) == parseInt(size) && parseInt(end) % 10 != 0) {
450
        var mod = parseInt(end) % 10;
451
        end = parseInt(end) + (10 - mod);
452
    }
453
    var pre = end - 10;
24595 tejbeer 454
 
32301 amit.gupta 455
    url = context + url + "?offset=" + pre;
24595 tejbeer 456
 
32301 amit.gupta 457
    if (params != null) {
458
        for (var key in params) {
459
            if (params.hasOwnProperty(key)) {
460
                url = url + "&" + key + "=" + params[key];
461
            }
462
        }
463
    }
24595 tejbeer 464
 
32301 amit.gupta 465
    doGetAjaxRequestHandler(url, function (response) {
466
        $("#" + paginatedIdentifier + " .end").text(+end - +10);
467
        $("#" + paginatedIdentifier + " .start").text(+start - +10);
468
        $('#' + tableIdentifier).html(response);
469
        if (detailsContainerIdentifier != null) {
470
            $('#' + detailsContainerIdentifier).html('');
471
        }
472
        $("#" + paginatedIdentifier + " .next").prop('disabled', false);
473
        if (parseInt(pre) == 0) {
474
            $("#" + paginatedIdentifier + " .previous").prop('disabled', true);
475
        }
476
    });
24595 tejbeer 477
 
23629 ashik.ali 478
}
479
 
32308 amit.gupta 480
function numberToComma(x, rounded) {
32301 amit.gupta 481
    if (isNaN(x)) {
482
        x = x.replaceAll(",", '');
483
    }
484
    x = parseFloat(x);
32308 amit.gupta 485
    if (typeof rounded != "undefined" && rounded) {
486
        x = Math.round(x);
487
    } else {
488
        x = Math.round(x * 100) / 100;
489
    }
35544 amit 490
    // Handle scientific notation (e.g., 1.37E7) - convert to full decimal string
491
    x = x.toLocaleString('en-US', {useGrouping: false, maximumFractionDigits: 2});
32301 amit.gupta 492
    x = x.split('.');
493
    var x1 = x[0];
494
    var x2 = x.length > 1 && x[1] != '0' ? '.' + x[1] : '';
495
    var lastThree = x1.substring(x1.length - 3);
496
    var otherNumbers = x1.substring(0, x1.length - 3);
497
    if (x1.charAt(x1.length - 4) == ',' || x1.charAt(x1.length - 4) == '-') {
498
        console.log(lastThree)
499
    } else {
500
        if (otherNumbers != '')
501
            lastThree = ',' + lastThree;
502
    }
503
    return otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + (lastThree)
504
        + x2;
24992 tejbeer 505
 
23786 amit.gupta 506
}
23870 amit.gupta 507
 
35510 amit 508
function formatValueInCrore(value) {
509
    if (isNaN(value)) return value;
510
    value = parseFloat(value);
35533 amit 511
    return numberToComma(value);
512
    /*if (value >= 10000000) {  // >= 1 Crore
35510 amit 513
        var croreValue = value / 10000000;
514
        // Remove trailing zeros: 1.500 -> 1.5, 1.000 -> 1
515
        var formatted = croreValue.toFixed(3).replace(/\.?0+$/, '');
516
        return formatted + ' Cr';
517
    } else {
518
        // Less than 1 Crore - show full number with Indian comma format
519
        return numberToComma(value);
35533 amit 520
    }*/
35510 amit 521
}
522
 
30599 amit.gupta 523
function getSingleDatePicker(startMoment) {
32301 amit.gupta 524
    var singleDatePicker = {
525
        "todayHighlight": true,
526
        "startDate": startMoment || moment(),
527
        "autoclose": true,
528
        "autoUpdateInput": true,
529
        "singleDatePicker": true,
530
        "locale": {
531
            'format': 'DD/MM/YYYY'
532
        }
533
    };
534
    return singleDatePicker;
23886 amit.gupta 535
}
536
 
30599 amit.gupta 537
function getDatesFromPicker(pickerElement) {
32301 amit.gupta 538
    return {
539
        startDate: $(pickerElement).data('daterangepicker').startDate.format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS),
540
        endDate: $(pickerElement).data('daterangepicker').endDate.format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
541
    }
30599 amit.gupta 542
}
543
 
544
function getReporticoDatesFromPicker(pickerElement) {
32301 amit.gupta 545
    let datePickerData = $(pickerElement).data('daterangepicker');
546
    let formattedEndDate = null;
547
    if (typeof datePickerData.endDate == "object") {
548
        formattedEndDate = datePickerData.endDate.format(moment.HTML5_FMT.DATE);
549
    }
550
    return {
551
        startDate: datePickerData.startDate.format(moment.HTML5_FMT.DATE),
552
        endDate: formattedEndDate
553
    };
30599 amit.gupta 554
}
555
 
33220 amit.gupta 556
function getStartOfFinancialYear(momentObj) {
557
    recentQuarter = momentObj.startOf('quarter').set('quarter', 2);
558
    return momentObj.quarter >= 2 ? recentQuarter : recentQuarter.subtract('year', 1);
559
}
30599 amit.gupta 560
 
33220 amit.gupta 561
function getStatementRanges() {
562
    return {
563
        ranges: {
564
            'This Month': [moment().startOf('month'), moment().startOf('day')],
33927 tejus.loha 565
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
566
            'Last 3 Months': [moment().subtract(3, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
567
            'Last 6 Months': [moment().subtract(6, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
36697 amit 568
            'Current Financial Year': [getStartOfFinancialYear(moment()), getStartOfFinancialYear(moment()).add('year', 1).subtract(1, 'day').endOf('day')],
569
            'Last Financial Year': [getStartOfFinancialYear(moment()).subtract('year', 1), getStartOfFinancialYear(moment()).subtract(1, 'day').endOf('day')]
33220 amit.gupta 570
        },
571
        alwaysShowCalendars: false,
572
        showCustomRangeLabel: false,
573
        showDropdowns: true,
574
        locale: {
575
            format: 'DD/MM/YYYY'
576
        }
577
    }
578
}
579
 
34236 ranu 580
function getYearMonthPicker() {
581
    return {
582
        "todayHighlight": true,
583
        "showDropdowns": true,
584
        "opens": "right",
585
        "startDate": moment().startOf('month'),
586
        "endDate": moment().endOf('month'),
587
        "singleDatePicker": true, // Ensures only one month selection
588
        "showCustomRangeLabel": false,
589
        "autoApply": true,
590
        "locale": {
591
            'format': 'YYYY-MM' // Year-Month format
592
        },
593
        "isInvalidDate": function (date) {
594
            return date.date() !== 1; // Only allows selecting the first day of a month
595
        }
596
    };
597
}
598
 
30599 amit.gupta 599
function getRangedDatePicker(showRanges, startMoment, endMoment) {
32301 amit.gupta 600
    if (typeof showRanges == "undefined") {
601
        showRanges = false;
602
    }
603
    var rangedDatePicker = {
604
        "todayHighlight": true,
33220 amit.gupta 605
        "showDropdowns": true,
32301 amit.gupta 606
        "opens": "right",
607
        "startDate": startMoment || moment().startOf('day'),
608
        "endDate": endMoment || moment().endOf('day'),
609
        "autoclose": true,
610
        "alwaysShowCalendars": false,
611
        "autoUpdateInput": true,
612
        "locale": {
613
            'format': 'DD/MM/YYYY'
614
        }
615
    };
616
    if (showRanges) {
617
        rangedDatePicker['ranges'] = {
618
            'Today': [moment(), moment()],
619
            'Yesterday': [moment().subtract(1, 'days'),
620
                moment().subtract(1, 'days')],
621
            'Last 7 Days': [moment().subtract(6, 'days'), moment()],
622
            'Last 30 Days': [moment().subtract(29, 'days'), moment()],
623
            'This Month': [moment().startOf('month'), moment().endOf('month')],
624
            'Last Month': [moment().subtract(1, 'month').startOf('month'),
625
                moment()],
626
            'Last 3 Months': [moment().subtract(3, 'month').startOf('month'),
627
                moment()],
628
            'Last 6 Months': [moment().subtract(6, 'month').startOf('month'),
629
                moment()]
34859 vikas 630
        };
32301 amit.gupta 631
    }
632
    return rangedDatePicker;
23892 amit.gupta 633
}
30017 amit.gupta 634
 
23946 amit.gupta 635
function showPosition(position) {
32301 amit.gupta 636
    if (typeof latitude == "undefined") {
637
        var coords = {
638
            latitude: position.coords.latitude,
639
            longitude: position.coords.longitude
34859 vikas 640
        };
32301 amit.gupta 641
        doAjaxRequestWithJsonHandler('partner/location', 'PUT', JSON
642
            .stringify(coords), function () {
643
            latitude = position.coords.latitude;
644
            longitude = position.coords.longitude;
645
        });
646
    }
647
    // distance = getDistance(latitude, longitude, position.coords.latitude,
648
    // position.coords.longitude);
24168 amit.gupta 649
}
650
 
24595 tejbeer 651
function getAuthorisedWarehouses(callback) {
32301 amit.gupta 652
    bootBoxObj = {
653
        size: "small",
654
        title: "Choose Warehouse",
655
        callback: callback,
656
        inputType: 'select',
34859 vikas 657
        inputOptions: typeof inputOptions == "undefined" ? undefined : inputOptions
658
    };
32301 amit.gupta 659
    if (typeof inputOptions == "undefined") {
660
        doGetAjaxRequestHandler(context + "/authorisedWarehouses", function (
661
            response) {
662
            response = JSON.parse(response);
663
            inputOptions = [];
664
            response.forEach(function (warehouse) {
665
                inputOptions.push({
666
                    text: warehouse.name,
667
                    value: warehouse.id,
668
                });
669
            });
670
            bootBoxObj['inputOptions'] = inputOptions;
671
            bootbox.prompt(bootBoxObj);
672
        });
673
    } else if (inputOptions.length == 1) {
674
        callback(inputOptions[0].warehouse.id);
675
    } else {
676
        bootbox.prompt(bootBoxObj);
677
    }
24595 tejbeer 678
 
24176 amit.gupta 679
}
30017 amit.gupta 680
 
24410 amit.gupta 681
function getColorsForItems(catalogId, itemId, description, callback) {
32301 amit.gupta 682
    colorCheckboxHandler(catalogId, itemId, description, callback);
30017 amit.gupta 683
}
684
 
685
function colorNumberHandler(catalogId, itemId, title, actionText, callback) {
32301 amit.gupta 686
    doGetAjaxRequestHandler(context + "/itemsByCatalogId?catalogId="
687
        + catalogId + "&itemId=" + itemId, function (response) {
688
        let coloredItems = JSON.parse(response);
689
        let modalBody = [];
690
        coloredItems.forEach(function (item) {
691
            modalBody.push(`
30017 amit.gupta 692
                <div class="row">
693
                    <div class="col-sm-2">
694
                        ${item.color}
695
                    </div>
696
                    <div class="col-sm-2">
697
                            <input data-itemid="${item.id}" type="text" class="form-control" />
698
                    </div>
699
                </div>
700
            `);
32301 amit.gupta 701
        });
702
        let dialogBoxHtml = `<div class="modal modal" tabindex="-1" role="dialog">
30017 amit.gupta 703
                              <div class="modal-dialog" >
704
                                <div class="modal-content">
705
                                  <div class="modal-header">
706
                                    <h5 class="modal-title">${title}</h5>
707
                                  </div>
708
                                  <div class="modal-body">
709
                                        ${modalBody.join('')}
710
                                  </div>
711
                                  <div class="modal-footer">
712
                                    <button type="button" class="btn btn-primary number_dialog">${actionText}</button>
713
                                  </div>
714
                                </div>
715
                              </div>
716
                            </div>`;
32301 amit.gupta 717
        let $dialog = $(dialogBoxHtml);
718
        let modalObj = $dialog.modal('show');
719
        modalObj.on('hidden.bs.modal', function (e) {
720
            $dialog.remove();
721
        });
722
        $('button.number_dialog').on('click', function () {
723
            let itemQty = [];
724
            let anySelected = false;
725
            $(modalObj).find('.modal-body').find('input').each(function () {
726
                $input = $(this);
727
                if ($input.val() > 0) {
728
                    itemQty.push({
729
                        itemId: $input.data("itemid"),
730
                        quantity: $input.val()
731
                    });
732
                    anySelected = true;
733
                }
734
            });
735
            if (anySelected && confirm("Are you sure want to notify?")) {
35459 amit 736
                $that = $(this);
32301 amit.gupta 737
                callback(itemQty, function () {
738
                    $that.off('click');
739
                    modalObj.hide();
740
                });
741
            } else {
35459 amit 742
                alert("Pls mention quantity");
32301 amit.gupta 743
            }
744
        });
745
    });
30017 amit.gupta 746
}
747
 
748
 
30021 amit.gupta 749
function colorCheckboxHandler(catalogId, itemId, description, callback) {
32301 amit.gupta 750
    let bootBoxObj = {
751
        size: "small",
752
        className: "item-wrapper",
753
        title: description,
754
        callback: callback,
755
        inputType: 'checkbox',
756
    }
757
    doGetAjaxRequestHandler(context + "/itemsByCatalogId?catalogId="
758
        + catalogId + "&itemId=" + itemId, function (response) {
35459 amit 759
        coloredItems = JSON.parse(response);
760
        inputOptions = [{
32301 amit.gupta 761
            text: "All",
762
            value: "0",
763
            onclick: "toggleAll('itemIds')"
764
        }];
765
        coloredItems.forEach(function (item) {
766
            inputOptions.push({
767
                text: item.color,
768
                value: item.id,
769
                selected: item.active
770
            });
771
        });
772
        bootBoxObj['inputOptions'] = inputOptions;
35459 amit 773
        promptObj = bootbox.prompt(bootBoxObj);
774
        promptObj.modal('show')
32301 amit.gupta 775
        $('.item-wrapper').find("input[type='checkbox']").slice(1).each(
776
            function (index, checkbox) {
777
                checkbox.checked = coloredItems[index].active;
778
            });
779
    });
24406 amit.gupta 780
}
28055 tejbeer 781
 
782
function getHotdealsForItems(catalogId, itemId, description, callback) {
35459 amit 783
    bootBoxObj = {
32301 amit.gupta 784
        size: "small",
785
        className: "item-wrapper",
786
        title: description,
787
        callback: callback,
788
        inputType: 'checkbox',
35459 amit 789
    }
32301 amit.gupta 790
    doGetAjaxRequestHandler(context + "/hotdealsitemsByCatalogId?catalogId="
791
        + catalogId + "&itemId=" + itemId, function (response) {
35459 amit 792
        coloredItems = JSON.parse(response);
793
        inputOptions = [{
32301 amit.gupta 794
            text: "All",
795
            value: "0",
796
            onclick: "toggleAll('itemIds')"
797
        }];
798
        coloredItems.forEach(function (item) {
799
            inputOptions.push({
800
                text: item.color,
801
                value: item.id,
802
                selected: item.hotDeals
803
            });
804
        });
805
        bootBoxObj['inputOptions'] = inputOptions;
35459 amit 806
        promptObj = bootbox.prompt(bootBoxObj);
807
        promptObj.modal('show')
32301 amit.gupta 808
        $('.item-wrapper').find("input[type='checkbox']").slice(1).each(
809
            function (index, checkbox) {
810
                checkbox.checked = coloredItems[index].hotDeals;
811
            });
812
    });
28055 tejbeer 813
}
30017 amit.gupta 814
 
27763 tejbeer 815
$(document).on('change', ".item-wrapper input[type='checkbox']:first",
32301 amit.gupta 816
    function () {
35459 amit 817
        if (this.value == "0") {
32301 amit.gupta 818
            $(this).closest('.item-wrapper').find("input[type='checkbox']")
819
                .slice(1).prop('checked', $(this).prop('checked'));
820
        }
821
    });
30017 amit.gupta 822
 
27618 tejbeer 823
function getItemAheadOptions(jqElement, anyColor, callback) {
35459 amit 824
    console.log(anyColor)
32301 amit.gupta 825
    jqElement.typeahead('destroy').typeahead({
826
        source: function (q, process) {
827
            if (q.length >= 3) {
828
                return $.ajax(context + "/item?anyColor=" + anyColor, {
829
                    global: false,
830
                    data: {
831
                        query: q
832
                    },
33758 ranu 833
                    headers: {
834
                        'IdempotencyKey': IdempotencyKey
835
                    },
32301 amit.gupta 836
                    success: function (data) {
35459 amit 837
                        //IdempotencyKey = uuidv4();
838
                        queryData = JSON.parse(data);
32301 amit.gupta 839
                        process(queryData);
840
                    },
841
                });
842
            }
843
        },
844
        delay: 300,
845
        items: 20,
846
        displayText: function (item) {
847
            return item.itemDescription;
848
        },
849
        autoSelect: true,
850
        afterSelect: callback
851
    });
24176 amit.gupta 852
}
28795 tejbeer 853
 
854
 
32195 tejbeer 855
function getVendorItemAheadOptions(jqElement, vendorId, callback) {
32301 amit.gupta 856
    jqElement.typeahead('destroy').typeahead({
857
        source: function (q, process) {
858
            if (q.length >= 3) {
859
                return $.ajax(context + "/vendorItem?vendorId=" + vendorId, {
860
                    global: false,
861
                    data: {
862
                        query: q
863
                    },
33758 ranu 864
                    headers: {
865
                        'IdempotencyKey': IdempotencyKey
866
                    },
32301 amit.gupta 867
                    success: function (data) {
35459 amit 868
                        //IdempotencyKey = uuidv4();
869
                        queryData = JSON.parse(data);
32301 amit.gupta 870
                        process(queryData);
871
                    },
872
                });
873
            }
874
        },
875
        delay: 300,
876
        items: 20,
877
        displayText: function (item) {
878
            return item.itemDescription;
879
        },
880
        autoSelect: true,
881
        afterSelect: callback
882
    });
32195 tejbeer 883
}
884
 
28795 tejbeer 885
function getImeiAheadOptions(jqElement, fofoId, callback) {
32301 amit.gupta 886
    jqElement.typeahead('destroy').typeahead({
887
            source: function (q, process) {
888
                if (q.length >= 3) {
889
                    return $.ajax(context + "/imei?fofoId=" + fofoId, {
890
                        global: false,
891
                        data: {
892
                            query: q
893
                        },
33758 ranu 894
                        headers: {
895
                            'IdempotencyKey': IdempotencyKey
896
                        },
32301 amit.gupta 897
                        success: function (data) {
35459 amit 898
                            //IdempotencyKey = uuidv4();
899
                            queryData = JSON.parse(data);
32301 amit.gupta 900
                            process(queryData);
901
                        },
902
                    });
903
                }
904
            },
905
            delay: 300,
906
            items: 20,
907
            displayText: function (imei) {
908
                return imei;
909
            },
910
            autoSelect: true,
911
            afterSelect: callback
912
        }
913
    );
31762 tejbeer 914
}
915
 
916
 
917
function getAllImeiAheadOptions(jqElement, callback) {
32301 amit.gupta 918
    jqElement.typeahead('destroy').typeahead({
919
        source: function (q, process) {
920
            if (q.length >= 3) {
921
                return $.ajax(context + "/allimei", {
922
                    global: false,
923
                    data: {
924
                        query: q
925
                    },
33758 ranu 926
                    headers: {
927
                        'IdempotencyKey': IdempotencyKey
928
                    },
32301 amit.gupta 929
                    success: function (data) {
33788 ranu 930
                        //IdempotencyKey = uuidv4();
32301 amit.gupta 931
                        queryData = JSON.parse(data);
932
                        process(queryData);
933
                    },
934
                });
935
            }
936
        },
937
        delay: 300,
938
        items: 20,
939
        displayText: function (imei) {
940
            return imei;
941
        },
942
        autoSelect: true,
943
        afterSelect: callback
944
    });
28795 tejbeer 945
}
946
 
947
 
25394 amit.gupta 948
function getEntityAheadOptions(jqElement, callback) {
32301 amit.gupta 949
    jqElement.typeahead('destroy').typeahead({
950
        source: function (q, process) {
951
            if (q.length >= 3) {
952
                return $.ajax(context + "/entity", {
953
                    global: false,
954
                    data: {
955
                        query: q
956
                    },
33758 ranu 957
                    headers: {
958
                        'IdempotencyKey': IdempotencyKey
959
                    },
32301 amit.gupta 960
                    success: function (data) {
33788 ranu 961
                        //IdempotencyKey = uuidv4();
32301 amit.gupta 962
                        queryData = JSON.parse(data);
963
                        process(queryData);
964
                    },
965
                });
966
            }
967
        },
968
        delay: 300,
969
        items: 30,
970
        displayText: function (entity) {
971
            return entity.title_s + "(" + entity.catalogId_i + ")";
972
        },
973
        autoSelect: true,
974
        afterSelect: callback
975
    });
25394 amit.gupta 976
}
30017 amit.gupta 977
 
24349 amit.gupta 978
function getPartnerAheadOptions(jqElement, callback) {
32301 amit.gupta 979
    jqElement.typeahead('destroy').typeahead({
980
        source: function (q, process) {
981
            if (q.length >= 3) {
982
                return $.ajax(context + "/partners", {
983
                    global: false,
984
                    data: {
985
                        query: q
986
                    },
33758 ranu 987
                    headers: {
988
                        'IdempotencyKey': IdempotencyKey
989
                    },
32301 amit.gupta 990
                    success: function (data) {
33788 ranu 991
                        //IdempotencyKey = uuidv4();
32301 amit.gupta 992
                        queryData = JSON.parse(data);
993
                        process(queryData);
994
                    },
995
                });
996
            }
997
        },
998
        delay: 300,
999
        items: 20,
1000
        displayText: function (partner) {
1001
            return partner.displayName;
1002
        },
1003
        autoSelect: true,
1004
        afterSelect: callback
1005
    });
24349 amit.gupta 1006
}
24406 amit.gupta 1007
 
32074 tejbeer 1008
function getVendorAheadOptions(jqElement, callback) {
32301 amit.gupta 1009
    jqElement.typeahead('destroy').typeahead({
1010
        source: function (q, process) {
1011
            if (q.length >= 3) {
1012
                return $.ajax(context + "/vendors", {
1013
                    global: false,
1014
                    data: {
1015
                        query: q
1016
                    },
33758 ranu 1017
                    headers: {
1018
                        'IdempotencyKey': IdempotencyKey
1019
                    },
32301 amit.gupta 1020
                    success: function (data) {
33788 ranu 1021
                        //IdempotencyKey = uuidv4();
32301 amit.gupta 1022
                        queryData = JSON.parse(data);
1023
                        process(queryData);
1024
                    },
1025
                });
1026
            }
1027
        },
1028
        delay: 300,
1029
        items: 20,
1030
        displayText: function (vendor) {
1031
            return vendor.name;
1032
        },
1033
        autoSelect: true,
1034
        afterSelect: callback
1035
    });
32074 tejbeer 1036
}
1037
 
36598 amit 1038
function getCatalogAheadOptions(jqElement, minPrice, callback) {
1039
    jqElement.typeahead('destroy').typeahead({
1040
        source: function (q, process) {
1041
            if (q.length >= 3) {
1042
                return $.ajax(context + "/catalogItem?minPrice=" + minPrice, {
1043
                    global: false,
1044
                    data: {
1045
                        query: q
1046
                    },
1047
                    headers: {
1048
                        'IdempotencyKey': IdempotencyKey
1049
                    },
1050
                    success: function (data) {
1051
                        queryData = JSON.parse(data);
1052
                        process(queryData);
1053
                    },
1054
                });
1055
            }
1056
        },
1057
        delay: 300,
1058
        items: 20,
1059
        displayText: function (item) {
1060
            return item.itemDescription;
1061
        },
1062
        autoSelect: true,
1063
        afterSelect: callback
1064
    });
1065
}
1066
 
24595 tejbeer 1067
function loadPriceDrop(domId) {
32301 amit.gupta 1068
    doGetAjaxRequestHandler(context + "/getItemDescription",
1069
        function (response) {
1070
            $('#' + domId).html(response);
1071
        });
24406 amit.gupta 1072
}
30017 amit.gupta 1073
 
32301 amit.gupta 1074
$(document).on('click', ".price_drop", function () {
1075
    loadPriceDrop("main-content");
24595 tejbeer 1076
});
25649 tejbeer 1077
 
27618 tejbeer 1078
 
32301 amit.gupta 1079
$(document).on('click', ".closed_pricedrop", function () {
1080
    loadClosedPriceDrop("main-content");
28569 amit.gupta 1081
});
1082
 
1083
function loadClosedPriceDrop(domId) {
32301 amit.gupta 1084
    doGetAjaxRequestHandler(context + "/getClosedPricedropItemDescription",
1085
        function (response) {
1086
            $('#' + domId).html(response);
1087
        });
28569 amit.gupta 1088
}
1089
 
27696 tejbeer 1090
function notifyTypeChange(messageType, $container) {
32301 amit.gupta 1091
    var messageQueryString = "?messageType=" + messageType;
1092
    if (messageType == null) {
1093
        messageQueryString = "";
1094
    }
1095
    doGetAjaxRequestHandler(context + "/notifications" + messageQueryString, function (response) {
1096
        if ($container != null) {
1097
            loaderDialogObj.one('hidden.bs.modal', function () {
1098
                $container.popover({
1099
                    container: $container,
1100
                    template: '<div class="popover popover1" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content popover2"></div></div>',
1101
                    content: response,
1102
                    html: true,
1103
                    placement: "bottom",
1104
                    trigger: "manual",
1105
                    sanitize: false
1106
                }).popover('show');
1107
                setTimeout(function () {
1108
                    $container.focus().one('blur', function () {
1109
                        $container.popover('destroy');
1110
                    });
1111
                }, 100);
1112
            });
1113
        }
1114
    });
25649 tejbeer 1115
}
25651 tejbeer 1116
 
25689 amit.gupta 1117
function downloadNotifyDocument(documentId, cid, documentName) {
32301 amit.gupta 1118
    doAjaxGetDownload(context + "/notifyDocument/download?cid=" + cid,
1119
        documentName);
25651 tejbeer 1120
}
28051 amit.gupta 1121
 
1122
 
1123
/* Create an array with the values of all the input boxes in a column */
32301 amit.gupta 1124
$.fn.dataTable.ext.order['dom-text'] = function (settings, col) {
1125
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1126
        return $('input', td).val();
1127
    });
28051 amit.gupta 1128
}
28795 tejbeer 1129
 
28063 amit.gupta 1130
/* Create an array with the values of all the input boxes in a column, parsed as numbers */
32301 amit.gupta 1131
$.fn.dataTable.ext.order['dom-text-numeric'] = function (settings, col) {
1132
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1133
        return $('input', td).val() * 1;
1134
    });
28051 amit.gupta 1135
}
28795 tejbeer 1136
 
32301 amit.gupta 1137
$.fn.dataTable.ext.order['dom-stock-numeric'] = function (settings, col) {
1138
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1139
        return $(td).html().split("/")[0] * 1;
1140
    });
28870 tejbeer 1141
}
28051 amit.gupta 1142
/* Create an array with the values of all the select options in a column */
32301 amit.gupta 1143
$.fn.dataTable.ext.order['dom-select'] = function (settings, col) {
1144
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1145
        return $('select', td).val();
1146
    });
28051 amit.gupta 1147
}
28795 tejbeer 1148
 
28051 amit.gupta 1149
/* Create an array with the values of all the checkboxes in a column */
32301 amit.gupta 1150
$.fn.dataTable.ext.order['dom-checkbox'] = function (settings, col) {
1151
    return this.api().column(col, {
1152
        order: 'index'
1153
    }).nodes().map(function (td, i) {
1154
        return $('input', td).prop('checked') ? '1' : '0';
1155
    });
30414 amit.gupta 1156
}
1157
 
32301 amit.gupta 1158
$.fn.dataTable.Api.register('sum()', function () {
1159
    return this.flatten().reduce(function (a, b) {
1160
        if (typeof a === 'string') {
1161
            a = a.replace(/[^\d.-]/g, '') * 1;
1162
            a = isNaN(a) ? 0 : a;
1163
        }
1164
        if (typeof b === 'string') {
1165
            b = b.replace(/[^\d.-]/g, '') * 1;
1166
            b = isNaN(b) ? 0 : b;
1167
        }
30414 amit.gupta 1168
 
32301 amit.gupta 1169
        return a + b;
1170
    }, 0);
30694 amit.gupta 1171
});
1172
 
1173
const debounce = (func, delay) => {
32301 amit.gupta 1174
    let debounceTimer
1175
    return function () {
1176
        const context = this
1177
        const args = arguments
1178
        clearTimeout(debounceTimer)
1179
        debounceTimer
1180
            = setTimeout(() => func.apply(context, args), delay)
1181
    }
30694 amit.gupta 1182
}
31687 amit.gupta 1183
 
32301 amit.gupta 1184
function parseDate(str) {
1185
    var m = str.match(/^(\d{1,2})[-/](\d{1,2})[-/](\d{4})$/);
1186
    return (m) ? new Date(m[3], m[2] - 1, m[1]) : null;
1187
}
31687 amit.gupta 1188
 
32130 amit.gupta 1189
function ExportToExcel(container, fn) {
32301 amit.gupta 1190
    let tableId = $(container).data('tableid');
1191
    var elt = document.getElementById(tableId);
33220 amit.gupta 1192
    console.log('elt', elt);
32301 amit.gupta 1193
    if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
33220 amit.gupta 1194
        let dataTable = $(`#${tableId}`).DataTable();
1195
        dataTable.page.len(-1).draw();
1196
        elt = dataTable.table(0).container();
32301 amit.gupta 1197
    }
1198
    ExportTableToExcel(elt, fn);
31687 amit.gupta 1199
}
1200
 
32301 amit.gupta 1201
function ExportTableToExcel(tableElt, fn) {
1202
    $table = $(tableElt)
1203
    $table.find('td').each((index, value) => {
1204
        let $tdElement = $(value);
1205
        console.log($tdElement);
1206
        let parsedDate = parseDate($tdElement.html());
1207
        if (parsedDate != null) {
1208
            let days = Math.floor(parsedDate.getTime() / 86400 * 1000);
1209
            $tdElement.data('v', days);
1210
            $tdElement.data("t", "n");
1211
            $tdElement.data("z", "yyyy-mm-dd");
1212
        }
1213
    });
1214
    console.log($table.get(0))
1215
    var wb = XLSX.utils.table_to_book($table.get(0), {sheet: "sheet1"});
1216
    XLSX.writeFile(wb, fn + '.xlsx');
1217
}
31687 amit.gupta 1218
 
32301 amit.gupta 1219
 
1220
$(document).on('click', ".manage-pcm", function () {
1221
    managePCM();
31687 amit.gupta 1222
});
1223
 
1224
function managePCM() {
32301 amit.gupta 1225
    doGetAjaxRequestHandler(`${context}/brand-pcm`, function (response) {
1226
        $('#main-content').html(response);
1227
    });
31687 amit.gupta 1228
}
31786 tejbeer 1229
 
1230
 
32301 amit.gupta 1231
$(document).on('click', '.warehousewise_stock', function () {
1232
    doGetAjaxRequestHandler(`${context}/warehouse/stock-qty`, function (response) {
1233
        $('#main-content').html(response);
1234
    });
32130 amit.gupta 1235
});
31878 tejbeer 1236
 
35594 amit 1237
// Partner name link - opens partner performance in new tab (reusable across all pages)
1238
$(document).on('click', '.partner-link', function (e) {
1239
    e.preventDefault();
1240
    var fofoId = $(this).data('fofoid');
1241
    if (fofoId) {
1242
        window.open(context + '/partnerPerformance?fofoId=' + fofoId, '_blank');
1243
    }
1244
});
1245
 
32567 tejbeer 1246
function loadMainContent(htmlContent) {
1247
    $('#main-content').html(htmlContent);
1248
}
31878 tejbeer 1249
 
1250
 
32979 amit.gupta 1251
function jsonStartDate(dateInputString) {
33220 amit.gupta 1252
    if (dateInputString === '') return null;
33141 amit.gupta 1253
    return moment(dateInputString, "yyyy-MM-DD").format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
32979 amit.gupta 1254
}
33220 amit.gupta 1255
 
32979 amit.gupta 1256
function jsonEndDate(dateInputString) {
33220 amit.gupta 1257
    if (dateInputString === '') return null;
33141 amit.gupta 1258
    return moment(dateInputString, "yyyy-MM-DD").endOf('day').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
32979 amit.gupta 1259
}
31878 tejbeer 1260
 
33167 amit.gupta 1261
function showToast(message) {
1262
    Toastify({
1263
        text: message,
1264
        duration: 3000, // 3 seconds
1265
        gravity: "top", // or "bottom"
1266
        position: "right", // "left", "center", "right"
1267
        backgroundColor: "green", // specify the background color
33400 ranu 1268
        offset: {
1269
            x: 20, // Horizontal margin from the right
1270
            y: 70 // Vertical margin from the top
1271
        }
33167 amit.gupta 1272
    }).showToast();
1273
}
31878 tejbeer 1274
 
33612 amit.gupta 1275
function loadHtml(html) {
1276
    $("#main-content").html(html);
1277
}
32130 amit.gupta 1278
 
33612 amit.gupta 1279
 
33508 tejus.loha 1280
function objectifyForm(formArray) {
35459 amit 1281
    //serialize data function
1282
    console.log('Row form  data ', formArray);
1283
    var returnArray = {};
1284
    for (var i = 0; i < formArray.length; i++) {
1285
        var name = formArray[i]['name'];
1286
        var value = formArray[i]['value'];
33927 tejus.loha 1287
        if (typeof returnArray[name] === 'undefined') {
1288
            returnArray[name] = value.trim();
35459 amit 1289
        } else if (typeof returnArray[name] === 'object') {
33927 tejus.loha 1290
            returnArray[name].push(value);
1291
        } else {
35459 amit 1292
            var a = returnArray[name];
1293
            returnArray[name] = [returnArray[name]];
1294
            a.push(value);
1295
            returnArray[name] = a;
33927 tejus.loha 1296
        }
33508 tejus.loha 1297
    }
1298
    return returnArray;
1299
}
32567 tejbeer 1300
 
33780 tejus.loha 1301
function isValidEmail(email) {
1302
    const EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(com|in|net)$/;
1303
    return EMAIL_REGEX.test(email);
1304
}
32979 amit.gupta 1305
 
34387 vikas.jang 1306
function serializeFormToJson(formId) {
1307
    let formArray = $(formId).serializeArray();
1308
    let formData = {};
1309
    $.map(formArray, function(field) {
1310
        formData[field.name] = field.value;
1311
    });
1312
    return formData;
34813 aman 1313
}
1314
 
1315
function getCookie(name) {
1316
    const cookies = document.cookie.split('; ');
1317
    for (let cookie of cookies) {
1318
        const [key, value] = cookie.split('=');
1319
        if (key === name) return decodeURIComponent(value);
1320
    }
1321
    return null;
35626 amit 1322
}
1323
 
1324
// ============================================================
1325
// PROMISE-BASED AJAX UTILITIES (SPA Support)
1326
// ============================================================
1327
 
1328
function doGetAjaxPromise(url, params) {
1329
    return $.ajax({
1330
        url: url,
1331
        method: 'GET',
1332
        data: params,
1333
        dataType: 'json',
1334
        cache: false
1335
    });
1336
}
1337
 
1338
function doPostAjaxJsonPromise(url, data) {
1339
    return $.ajax({
1340
        url: url,
1341
        method: 'POST',
1342
        data: JSON.stringify(data),
1343
        contentType: 'application/json',
1344
        dataType: 'json',
1345
        cache: false
1346
    });
1347
}
1348
 
1349
function doPostAjaxParamsPromise(url, params) {
1350
    return $.ajax({
1351
        url: url,
1352
        method: 'POST',
1353
        data: params,
1354
        dataType: 'json',
1355
        cache: false
1356
    });
1357
}
1358
 
1359
// ============================================================
1360
// SPA UTILITIES
1361
// ============================================================
1362
 
1363
function createSpaModule(config) {
1364
    var defaultConfig = {
1365
        name: 'SpaModule',
1366
        endpoints: {},
1367
        state: {},
1368
        onInit: function() {},
1369
        onDestroy: function() {}
1370
    };
1371
 
1372
    var moduleConfig = $.extend(true, {}, defaultConfig, config);
1373
    var state = $.extend(true, {}, moduleConfig.state);
1374
    var timers = {};
1375
 
1376
    return {
1377
        getName: function() { return moduleConfig.name; },
1378
        getState: function(key) { return key ? state[key] : state; },
1379
        setState: function(key, value) {
1380
            state[key] = value;
1381
            return this;
1382
        },
1383
        getEndpoint: function(name) {
1384
            return context + moduleConfig.endpoints[name];
1385
        },
1386
        setTimer: function(name, callback, delay) {
1387
            this.clearTimer(name);
1388
            timers[name] = setTimeout(callback, delay);
1389
            return timers[name];
1390
        },
1391
        clearTimer: function(name) {
1392
            if (timers[name]) {
1393
                clearTimeout(timers[name]);
1394
                delete timers[name];
1395
            }
1396
            return this;
1397
        },
1398
        clearAllTimers: function() {
1399
            var self = this;
1400
            Object.keys(timers).forEach(function(name) { self.clearTimer(name); });
1401
            return this;
1402
        },
1403
        init: function(options) {
1404
            moduleConfig.onInit.call(this, options);
1405
            return this;
1406
        },
1407
        destroy: function() {
1408
            this.clearAllTimers();
1409
            state = $.extend(true, {}, moduleConfig.state);
1410
            moduleConfig.onDestroy.call(this);
1411
            return this;
1412
        }
1413
    };
1414
}
1415
 
1416
function handleApiResponse(response, successCallback, errorCallback) {
1417
    if (response && response.success) {
1418
        if (typeof successCallback === 'function') {
1419
            successCallback(response.data);
1420
        }
1421
    } else {
1422
        var message = response && response.message ? response.message : 'An error occurred';
1423
        if (typeof errorCallback === 'function') {
1424
            errorCallback(message, response);
1425
        } else {
1426
            bootbox.alert(message);
1427
        }
1428
    }
1429
}
1430
 
1431
function resolveUrlTemplate(template, params) {
1432
    var url = template;
1433
    for (var key in params) {
1434
        if (params.hasOwnProperty(key)) {
1435
            url = url.replace('{' + key + '}', encodeURIComponent(params[key]));
1436
        }
1437
    }
1438
    return url;
34387 vikas.jang 1439
}