Subversion Repositories SmartDukaan

Rev

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