Subversion Repositories SmartDukaan

Rev

Rev 37171 | Rev 37282 | 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
 
790
function getHotdealsForItems(catalogId, itemId, description, callback) {
35459 amit 791
    bootBoxObj = {
32301 amit.gupta 792
        size: "small",
793
        className: "item-wrapper",
794
        title: description,
795
        callback: callback,
796
        inputType: 'checkbox',
35459 amit 797
    }
32301 amit.gupta 798
    doGetAjaxRequestHandler(context + "/hotdealsitemsByCatalogId?catalogId="
799
        + catalogId + "&itemId=" + itemId, function (response) {
35459 amit 800
        coloredItems = JSON.parse(response);
801
        inputOptions = [{
32301 amit.gupta 802
            text: "All",
803
            value: "0",
804
            onclick: "toggleAll('itemIds')"
805
        }];
806
        coloredItems.forEach(function (item) {
807
            inputOptions.push({
808
                text: item.color,
809
                value: item.id,
810
                selected: item.hotDeals
811
            });
812
        });
813
        bootBoxObj['inputOptions'] = inputOptions;
35459 amit 814
        promptObj = bootbox.prompt(bootBoxObj);
815
        promptObj.modal('show')
32301 amit.gupta 816
        $('.item-wrapper').find("input[type='checkbox']").slice(1).each(
817
            function (index, checkbox) {
818
                checkbox.checked = coloredItems[index].hotDeals;
819
            });
820
    });
28055 tejbeer 821
}
30017 amit.gupta 822
 
27763 tejbeer 823
$(document).on('change', ".item-wrapper input[type='checkbox']:first",
32301 amit.gupta 824
    function () {
35459 amit 825
        if (this.value == "0") {
32301 amit.gupta 826
            $(this).closest('.item-wrapper').find("input[type='checkbox']")
827
                .slice(1).prop('checked', $(this).prop('checked'));
828
        }
829
    });
30017 amit.gupta 830
 
27618 tejbeer 831
function getItemAheadOptions(jqElement, anyColor, callback) {
35459 amit 832
    console.log(anyColor)
32301 amit.gupta 833
    jqElement.typeahead('destroy').typeahead({
834
        source: function (q, process) {
835
            if (q.length >= 3) {
836
                return $.ajax(context + "/item?anyColor=" + anyColor, {
837
                    global: false,
838
                    data: {
839
                        query: q
840
                    },
33758 ranu 841
                    headers: {
842
                        'IdempotencyKey': IdempotencyKey
843
                    },
32301 amit.gupta 844
                    success: function (data) {
35459 amit 845
                        //IdempotencyKey = uuidv4();
846
                        queryData = JSON.parse(data);
32301 amit.gupta 847
                        process(queryData);
848
                    },
849
                });
850
            }
851
        },
852
        delay: 300,
853
        items: 20,
854
        displayText: function (item) {
855
            return item.itemDescription;
856
        },
857
        autoSelect: true,
858
        afterSelect: callback
859
    });
24176 amit.gupta 860
}
28795 tejbeer 861
 
862
 
32195 tejbeer 863
function getVendorItemAheadOptions(jqElement, vendorId, callback) {
32301 amit.gupta 864
    jqElement.typeahead('destroy').typeahead({
865
        source: function (q, process) {
866
            if (q.length >= 3) {
867
                return $.ajax(context + "/vendorItem?vendorId=" + vendorId, {
868
                    global: false,
869
                    data: {
870
                        query: q
871
                    },
33758 ranu 872
                    headers: {
873
                        'IdempotencyKey': IdempotencyKey
874
                    },
32301 amit.gupta 875
                    success: function (data) {
35459 amit 876
                        //IdempotencyKey = uuidv4();
877
                        queryData = JSON.parse(data);
32301 amit.gupta 878
                        process(queryData);
879
                    },
880
                });
881
            }
882
        },
883
        delay: 300,
884
        items: 20,
885
        displayText: function (item) {
886
            return item.itemDescription;
887
        },
888
        autoSelect: true,
889
        afterSelect: callback
890
    });
32195 tejbeer 891
}
892
 
28795 tejbeer 893
function getImeiAheadOptions(jqElement, fofoId, callback) {
32301 amit.gupta 894
    jqElement.typeahead('destroy').typeahead({
895
            source: function (q, process) {
896
                if (q.length >= 3) {
897
                    return $.ajax(context + "/imei?fofoId=" + fofoId, {
898
                        global: false,
899
                        data: {
900
                            query: q
901
                        },
33758 ranu 902
                        headers: {
903
                            'IdempotencyKey': IdempotencyKey
904
                        },
32301 amit.gupta 905
                        success: function (data) {
35459 amit 906
                            //IdempotencyKey = uuidv4();
907
                            queryData = JSON.parse(data);
32301 amit.gupta 908
                            process(queryData);
909
                        },
910
                    });
911
                }
912
            },
913
            delay: 300,
914
            items: 20,
915
            displayText: function (imei) {
916
                return imei;
917
            },
918
            autoSelect: true,
919
            afterSelect: callback
920
        }
921
    );
31762 tejbeer 922
}
923
 
924
 
925
function getAllImeiAheadOptions(jqElement, callback) {
32301 amit.gupta 926
    jqElement.typeahead('destroy').typeahead({
927
        source: function (q, process) {
928
            if (q.length >= 3) {
929
                return $.ajax(context + "/allimei", {
930
                    global: false,
931
                    data: {
932
                        query: q
933
                    },
33758 ranu 934
                    headers: {
935
                        'IdempotencyKey': IdempotencyKey
936
                    },
32301 amit.gupta 937
                    success: function (data) {
33788 ranu 938
                        //IdempotencyKey = uuidv4();
32301 amit.gupta 939
                        queryData = JSON.parse(data);
940
                        process(queryData);
941
                    },
942
                });
943
            }
944
        },
945
        delay: 300,
946
        items: 20,
947
        displayText: function (imei) {
948
            return imei;
949
        },
950
        autoSelect: true,
951
        afterSelect: callback
952
    });
28795 tejbeer 953
}
954
 
955
 
25394 amit.gupta 956
function getEntityAheadOptions(jqElement, callback) {
32301 amit.gupta 957
    jqElement.typeahead('destroy').typeahead({
958
        source: function (q, process) {
959
            if (q.length >= 3) {
960
                return $.ajax(context + "/entity", {
961
                    global: false,
962
                    data: {
963
                        query: q
964
                    },
33758 ranu 965
                    headers: {
966
                        'IdempotencyKey': IdempotencyKey
967
                    },
32301 amit.gupta 968
                    success: function (data) {
33788 ranu 969
                        //IdempotencyKey = uuidv4();
32301 amit.gupta 970
                        queryData = JSON.parse(data);
971
                        process(queryData);
972
                    },
973
                });
974
            }
975
        },
976
        delay: 300,
977
        items: 30,
978
        displayText: function (entity) {
979
            return entity.title_s + "(" + entity.catalogId_i + ")";
980
        },
981
        autoSelect: true,
982
        afterSelect: callback
983
    });
25394 amit.gupta 984
}
30017 amit.gupta 985
 
24349 amit.gupta 986
function getPartnerAheadOptions(jqElement, callback) {
32301 amit.gupta 987
    jqElement.typeahead('destroy').typeahead({
988
        source: function (q, process) {
989
            if (q.length >= 3) {
990
                return $.ajax(context + "/partners", {
991
                    global: false,
992
                    data: {
993
                        query: q
994
                    },
33758 ranu 995
                    headers: {
996
                        'IdempotencyKey': IdempotencyKey
997
                    },
32301 amit.gupta 998
                    success: function (data) {
33788 ranu 999
                        //IdempotencyKey = uuidv4();
32301 amit.gupta 1000
                        queryData = JSON.parse(data);
1001
                        process(queryData);
1002
                    },
1003
                });
1004
            }
1005
        },
1006
        delay: 300,
1007
        items: 20,
1008
        displayText: function (partner) {
1009
            return partner.displayName;
1010
        },
1011
        autoSelect: true,
1012
        afterSelect: callback
1013
    });
24349 amit.gupta 1014
}
24406 amit.gupta 1015
 
32074 tejbeer 1016
function getVendorAheadOptions(jqElement, callback) {
32301 amit.gupta 1017
    jqElement.typeahead('destroy').typeahead({
1018
        source: function (q, process) {
1019
            if (q.length >= 3) {
1020
                return $.ajax(context + "/vendors", {
1021
                    global: false,
1022
                    data: {
1023
                        query: q
1024
                    },
33758 ranu 1025
                    headers: {
1026
                        'IdempotencyKey': IdempotencyKey
1027
                    },
32301 amit.gupta 1028
                    success: function (data) {
33788 ranu 1029
                        //IdempotencyKey = uuidv4();
32301 amit.gupta 1030
                        queryData = JSON.parse(data);
1031
                        process(queryData);
1032
                    },
1033
                });
1034
            }
1035
        },
1036
        delay: 300,
1037
        items: 20,
1038
        displayText: function (vendor) {
1039
            return vendor.name;
1040
        },
1041
        autoSelect: true,
1042
        afterSelect: callback
1043
    });
32074 tejbeer 1044
}
1045
 
36598 amit 1046
function getCatalogAheadOptions(jqElement, minPrice, callback) {
1047
    jqElement.typeahead('destroy').typeahead({
1048
        source: function (q, process) {
1049
            if (q.length >= 3) {
1050
                return $.ajax(context + "/catalogItem?minPrice=" + minPrice, {
1051
                    global: false,
1052
                    data: {
1053
                        query: q
1054
                    },
1055
                    headers: {
1056
                        'IdempotencyKey': IdempotencyKey
1057
                    },
1058
                    success: function (data) {
1059
                        queryData = JSON.parse(data);
1060
                        process(queryData);
1061
                    },
1062
                });
1063
            }
1064
        },
1065
        delay: 300,
1066
        items: 20,
1067
        displayText: function (item) {
1068
            return item.itemDescription;
1069
        },
1070
        autoSelect: true,
1071
        afterSelect: callback
1072
    });
1073
}
1074
 
24595 tejbeer 1075
function loadPriceDrop(domId) {
32301 amit.gupta 1076
    doGetAjaxRequestHandler(context + "/getItemDescription",
1077
        function (response) {
1078
            $('#' + domId).html(response);
1079
        });
24406 amit.gupta 1080
}
30017 amit.gupta 1081
 
32301 amit.gupta 1082
$(document).on('click', ".price_drop", function () {
1083
    loadPriceDrop("main-content");
24595 tejbeer 1084
});
25649 tejbeer 1085
 
27618 tejbeer 1086
 
32301 amit.gupta 1087
$(document).on('click', ".closed_pricedrop", function () {
1088
    loadClosedPriceDrop("main-content");
28569 amit.gupta 1089
});
1090
 
1091
function loadClosedPriceDrop(domId) {
32301 amit.gupta 1092
    doGetAjaxRequestHandler(context + "/getClosedPricedropItemDescription",
1093
        function (response) {
1094
            $('#' + domId).html(response);
1095
        });
28569 amit.gupta 1096
}
1097
 
27696 tejbeer 1098
function notifyTypeChange(messageType, $container) {
32301 amit.gupta 1099
    var messageQueryString = "?messageType=" + messageType;
1100
    if (messageType == null) {
1101
        messageQueryString = "";
1102
    }
1103
    doGetAjaxRequestHandler(context + "/notifications" + messageQueryString, function (response) {
1104
        if ($container != null) {
1105
            loaderDialogObj.one('hidden.bs.modal', function () {
1106
                $container.popover({
1107
                    container: $container,
1108
                    template: '<div class="popover popover1" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content popover2"></div></div>',
1109
                    content: response,
1110
                    html: true,
1111
                    placement: "bottom",
1112
                    trigger: "manual",
1113
                    sanitize: false
1114
                }).popover('show');
1115
                setTimeout(function () {
1116
                    $container.focus().one('blur', function () {
1117
                        $container.popover('destroy');
1118
                    });
1119
                }, 100);
1120
            });
1121
        }
1122
    });
25649 tejbeer 1123
}
25651 tejbeer 1124
 
25689 amit.gupta 1125
function downloadNotifyDocument(documentId, cid, documentName) {
32301 amit.gupta 1126
    doAjaxGetDownload(context + "/notifyDocument/download?cid=" + cid,
1127
        documentName);
25651 tejbeer 1128
}
28051 amit.gupta 1129
 
1130
 
1131
/* Create an array with the values of all the input boxes in a column */
32301 amit.gupta 1132
$.fn.dataTable.ext.order['dom-text'] = function (settings, col) {
1133
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1134
        return $('input', td).val();
1135
    });
28051 amit.gupta 1136
}
28795 tejbeer 1137
 
28063 amit.gupta 1138
/* Create an array with the values of all the input boxes in a column, parsed as numbers */
32301 amit.gupta 1139
$.fn.dataTable.ext.order['dom-text-numeric'] = function (settings, col) {
1140
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1141
        return $('input', td).val() * 1;
1142
    });
28051 amit.gupta 1143
}
28795 tejbeer 1144
 
32301 amit.gupta 1145
$.fn.dataTable.ext.order['dom-stock-numeric'] = function (settings, col) {
1146
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1147
        return $(td).html().split("/")[0] * 1;
1148
    });
28870 tejbeer 1149
}
28051 amit.gupta 1150
/* Create an array with the values of all the select options in a column */
32301 amit.gupta 1151
$.fn.dataTable.ext.order['dom-select'] = function (settings, col) {
1152
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1153
        return $('select', td).val();
1154
    });
28051 amit.gupta 1155
}
28795 tejbeer 1156
 
28051 amit.gupta 1157
/* Create an array with the values of all the checkboxes in a column */
32301 amit.gupta 1158
$.fn.dataTable.ext.order['dom-checkbox'] = function (settings, col) {
1159
    return this.api().column(col, {
1160
        order: 'index'
1161
    }).nodes().map(function (td, i) {
1162
        return $('input', td).prop('checked') ? '1' : '0';
1163
    });
30414 amit.gupta 1164
}
1165
 
32301 amit.gupta 1166
$.fn.dataTable.Api.register('sum()', function () {
1167
    return this.flatten().reduce(function (a, b) {
1168
        if (typeof a === 'string') {
1169
            a = a.replace(/[^\d.-]/g, '') * 1;
1170
            a = isNaN(a) ? 0 : a;
1171
        }
1172
        if (typeof b === 'string') {
1173
            b = b.replace(/[^\d.-]/g, '') * 1;
1174
            b = isNaN(b) ? 0 : b;
1175
        }
30414 amit.gupta 1176
 
32301 amit.gupta 1177
        return a + b;
1178
    }, 0);
30694 amit.gupta 1179
});
1180
 
1181
const debounce = (func, delay) => {
32301 amit.gupta 1182
    let debounceTimer
1183
    return function () {
1184
        const context = this
1185
        const args = arguments
1186
        clearTimeout(debounceTimer)
1187
        debounceTimer
1188
            = setTimeout(() => func.apply(context, args), delay)
1189
    }
30694 amit.gupta 1190
}
31687 amit.gupta 1191
 
32301 amit.gupta 1192
function parseDate(str) {
1193
    var m = str.match(/^(\d{1,2})[-/](\d{1,2})[-/](\d{4})$/);
1194
    return (m) ? new Date(m[3], m[2] - 1, m[1]) : null;
1195
}
31687 amit.gupta 1196
 
32130 amit.gupta 1197
function ExportToExcel(container, fn) {
32301 amit.gupta 1198
    let tableId = $(container).data('tableid');
1199
    var elt = document.getElementById(tableId);
33220 amit.gupta 1200
    console.log('elt', elt);
32301 amit.gupta 1201
    if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
33220 amit.gupta 1202
        let dataTable = $(`#${tableId}`).DataTable();
1203
        dataTable.page.len(-1).draw();
1204
        elt = dataTable.table(0).container();
32301 amit.gupta 1205
    }
1206
    ExportTableToExcel(elt, fn);
31687 amit.gupta 1207
}
1208
 
32301 amit.gupta 1209
function ExportTableToExcel(tableElt, fn) {
1210
    $table = $(tableElt)
1211
    $table.find('td').each((index, value) => {
1212
        let $tdElement = $(value);
1213
        console.log($tdElement);
1214
        let parsedDate = parseDate($tdElement.html());
1215
        if (parsedDate != null) {
1216
            let days = Math.floor(parsedDate.getTime() / 86400 * 1000);
1217
            $tdElement.data('v', days);
1218
            $tdElement.data("t", "n");
1219
            $tdElement.data("z", "yyyy-mm-dd");
1220
        }
1221
    });
1222
    console.log($table.get(0))
1223
    var wb = XLSX.utils.table_to_book($table.get(0), {sheet: "sheet1"});
1224
    XLSX.writeFile(wb, fn + '.xlsx');
1225
}
31687 amit.gupta 1226
 
32301 amit.gupta 1227
 
1228
$(document).on('click', ".manage-pcm", function () {
1229
    managePCM();
31687 amit.gupta 1230
});
1231
 
1232
function managePCM() {
32301 amit.gupta 1233
    doGetAjaxRequestHandler(`${context}/brand-pcm`, function (response) {
1234
        $('#main-content').html(response);
1235
    });
31687 amit.gupta 1236
}
31786 tejbeer 1237
 
1238
 
32301 amit.gupta 1239
$(document).on('click', '.warehousewise_stock', function () {
1240
    doGetAjaxRequestHandler(`${context}/warehouse/stock-qty`, function (response) {
1241
        $('#main-content').html(response);
1242
    });
32130 amit.gupta 1243
});
31878 tejbeer 1244
 
35594 amit 1245
// Partner name link - opens partner performance in new tab (reusable across all pages)
1246
$(document).on('click', '.partner-link', function (e) {
1247
    e.preventDefault();
1248
    var fofoId = $(this).data('fofoid');
1249
    if (fofoId) {
1250
        window.open(context + '/partnerPerformance?fofoId=' + fofoId, '_blank');
1251
    }
1252
});
1253
 
32567 tejbeer 1254
function loadMainContent(htmlContent) {
1255
    $('#main-content').html(htmlContent);
1256
}
31878 tejbeer 1257
 
1258
 
32979 amit.gupta 1259
function jsonStartDate(dateInputString) {
33220 amit.gupta 1260
    if (dateInputString === '') return null;
33141 amit.gupta 1261
    return moment(dateInputString, "yyyy-MM-DD").format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
32979 amit.gupta 1262
}
33220 amit.gupta 1263
 
32979 amit.gupta 1264
function jsonEndDate(dateInputString) {
33220 amit.gupta 1265
    if (dateInputString === '') return null;
33141 amit.gupta 1266
    return moment(dateInputString, "yyyy-MM-DD").endOf('day').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
32979 amit.gupta 1267
}
31878 tejbeer 1268
 
33167 amit.gupta 1269
function showToast(message) {
1270
    Toastify({
1271
        text: message,
1272
        duration: 3000, // 3 seconds
1273
        gravity: "top", // or "bottom"
1274
        position: "right", // "left", "center", "right"
1275
        backgroundColor: "green", // specify the background color
33400 ranu 1276
        offset: {
1277
            x: 20, // Horizontal margin from the right
1278
            y: 70 // Vertical margin from the top
1279
        }
33167 amit.gupta 1280
    }).showToast();
1281
}
31878 tejbeer 1282
 
33612 amit.gupta 1283
function loadHtml(html) {
1284
    $("#main-content").html(html);
1285
}
32130 amit.gupta 1286
 
33612 amit.gupta 1287
 
33508 tejus.loha 1288
function objectifyForm(formArray) {
35459 amit 1289
    //serialize data function
1290
    console.log('Row form  data ', formArray);
1291
    var returnArray = {};
1292
    for (var i = 0; i < formArray.length; i++) {
1293
        var name = formArray[i]['name'];
1294
        var value = formArray[i]['value'];
33927 tejus.loha 1295
        if (typeof returnArray[name] === 'undefined') {
1296
            returnArray[name] = value.trim();
35459 amit 1297
        } else if (typeof returnArray[name] === 'object') {
33927 tejus.loha 1298
            returnArray[name].push(value);
1299
        } else {
35459 amit 1300
            var a = returnArray[name];
1301
            returnArray[name] = [returnArray[name]];
1302
            a.push(value);
1303
            returnArray[name] = a;
33927 tejus.loha 1304
        }
33508 tejus.loha 1305
    }
1306
    return returnArray;
1307
}
32567 tejbeer 1308
 
33780 tejus.loha 1309
function isValidEmail(email) {
1310
    const EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(com|in|net)$/;
1311
    return EMAIL_REGEX.test(email);
1312
}
32979 amit.gupta 1313
 
34387 vikas.jang 1314
function serializeFormToJson(formId) {
1315
    let formArray = $(formId).serializeArray();
1316
    let formData = {};
1317
    $.map(formArray, function(field) {
1318
        formData[field.name] = field.value;
1319
    });
1320
    return formData;
34813 aman 1321
}
1322
 
1323
function getCookie(name) {
1324
    const cookies = document.cookie.split('; ');
1325
    for (let cookie of cookies) {
1326
        const [key, value] = cookie.split('=');
1327
        if (key === name) return decodeURIComponent(value);
1328
    }
1329
    return null;
35626 amit 1330
}
1331
 
1332
// ============================================================
1333
// PROMISE-BASED AJAX UTILITIES (SPA Support)
1334
// ============================================================
1335
 
1336
function doGetAjaxPromise(url, params) {
1337
    return $.ajax({
1338
        url: url,
1339
        method: 'GET',
1340
        data: params,
1341
        dataType: 'json',
1342
        cache: false
1343
    });
1344
}
1345
 
1346
function doPostAjaxJsonPromise(url, data) {
1347
    return $.ajax({
1348
        url: url,
1349
        method: 'POST',
1350
        data: JSON.stringify(data),
1351
        contentType: 'application/json',
1352
        dataType: 'json',
1353
        cache: false
1354
    });
1355
}
1356
 
1357
function doPostAjaxParamsPromise(url, params) {
1358
    return $.ajax({
1359
        url: url,
1360
        method: 'POST',
1361
        data: params,
1362
        dataType: 'json',
1363
        cache: false
1364
    });
1365
}
1366
 
1367
// ============================================================
1368
// SPA UTILITIES
1369
// ============================================================
1370
 
1371
function createSpaModule(config) {
1372
    var defaultConfig = {
1373
        name: 'SpaModule',
1374
        endpoints: {},
1375
        state: {},
1376
        onInit: function() {},
1377
        onDestroy: function() {}
1378
    };
1379
 
1380
    var moduleConfig = $.extend(true, {}, defaultConfig, config);
1381
    var state = $.extend(true, {}, moduleConfig.state);
1382
    var timers = {};
1383
 
1384
    return {
1385
        getName: function() { return moduleConfig.name; },
1386
        getState: function(key) { return key ? state[key] : state; },
1387
        setState: function(key, value) {
1388
            state[key] = value;
1389
            return this;
1390
        },
1391
        getEndpoint: function(name) {
1392
            return context + moduleConfig.endpoints[name];
1393
        },
1394
        setTimer: function(name, callback, delay) {
1395
            this.clearTimer(name);
1396
            timers[name] = setTimeout(callback, delay);
1397
            return timers[name];
1398
        },
1399
        clearTimer: function(name) {
1400
            if (timers[name]) {
1401
                clearTimeout(timers[name]);
1402
                delete timers[name];
1403
            }
1404
            return this;
1405
        },
1406
        clearAllTimers: function() {
1407
            var self = this;
1408
            Object.keys(timers).forEach(function(name) { self.clearTimer(name); });
1409
            return this;
1410
        },
1411
        init: function(options) {
1412
            moduleConfig.onInit.call(this, options);
1413
            return this;
1414
        },
1415
        destroy: function() {
1416
            this.clearAllTimers();
1417
            state = $.extend(true, {}, moduleConfig.state);
1418
            moduleConfig.onDestroy.call(this);
1419
            return this;
1420
        }
1421
    };
1422
}
1423
 
1424
function handleApiResponse(response, successCallback, errorCallback) {
1425
    if (response && response.success) {
1426
        if (typeof successCallback === 'function') {
1427
            successCallback(response.data);
1428
        }
1429
    } else {
1430
        var message = response && response.message ? response.message : 'An error occurred';
1431
        if (typeof errorCallback === 'function') {
1432
            errorCallback(message, response);
1433
        } else {
1434
            bootbox.alert(message);
1435
        }
1436
    }
1437
}
1438
 
1439
function resolveUrlTemplate(template, params) {
1440
    var url = template;
1441
    for (var key in params) {
1442
        if (params.hasOwnProperty(key)) {
1443
            url = url.replace('{' + key + '}', encodeURIComponent(params[key]));
1444
        }
1445
    }
1446
    return url;
34387 vikas.jang 1447
}