Subversion Repositories SmartDukaan

Rev

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