Subversion Repositories SmartDukaan

Rev

Rev 36572 | Rev 36697 | 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
 
36598 amit 1031
function getCatalogAheadOptions(jqElement, minPrice, callback) {
1032
    jqElement.typeahead('destroy').typeahead({
1033
        source: function (q, process) {
1034
            if (q.length >= 3) {
1035
                return $.ajax(context + "/catalogItem?minPrice=" + minPrice, {
1036
                    global: false,
1037
                    data: {
1038
                        query: q
1039
                    },
1040
                    headers: {
1041
                        'IdempotencyKey': IdempotencyKey
1042
                    },
1043
                    success: function (data) {
1044
                        queryData = JSON.parse(data);
1045
                        process(queryData);
1046
                    },
1047
                });
1048
            }
1049
        },
1050
        delay: 300,
1051
        items: 20,
1052
        displayText: function (item) {
1053
            return item.itemDescription;
1054
        },
1055
        autoSelect: true,
1056
        afterSelect: callback
1057
    });
1058
}
1059
 
24595 tejbeer 1060
function loadPriceDrop(domId) {
32301 amit.gupta 1061
    doGetAjaxRequestHandler(context + "/getItemDescription",
1062
        function (response) {
1063
            $('#' + domId).html(response);
1064
        });
24406 amit.gupta 1065
}
30017 amit.gupta 1066
 
32301 amit.gupta 1067
$(document).on('click', ".price_drop", function () {
1068
    loadPriceDrop("main-content");
24595 tejbeer 1069
});
25649 tejbeer 1070
 
27618 tejbeer 1071
 
32301 amit.gupta 1072
$(document).on('click', ".closed_pricedrop", function () {
1073
    loadClosedPriceDrop("main-content");
28569 amit.gupta 1074
});
1075
 
1076
function loadClosedPriceDrop(domId) {
32301 amit.gupta 1077
    doGetAjaxRequestHandler(context + "/getClosedPricedropItemDescription",
1078
        function (response) {
1079
            $('#' + domId).html(response);
1080
        });
28569 amit.gupta 1081
}
1082
 
27696 tejbeer 1083
function notifyTypeChange(messageType, $container) {
32301 amit.gupta 1084
    var messageQueryString = "?messageType=" + messageType;
1085
    if (messageType == null) {
1086
        messageQueryString = "";
1087
    }
1088
    doGetAjaxRequestHandler(context + "/notifications" + messageQueryString, function (response) {
1089
        if ($container != null) {
1090
            loaderDialogObj.one('hidden.bs.modal', function () {
1091
                $container.popover({
1092
                    container: $container,
1093
                    template: '<div class="popover popover1" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content popover2"></div></div>',
1094
                    content: response,
1095
                    html: true,
1096
                    placement: "bottom",
1097
                    trigger: "manual",
1098
                    sanitize: false
1099
                }).popover('show');
1100
                setTimeout(function () {
1101
                    $container.focus().one('blur', function () {
1102
                        $container.popover('destroy');
1103
                    });
1104
                }, 100);
1105
            });
1106
        }
1107
    });
25649 tejbeer 1108
}
25651 tejbeer 1109
 
25689 amit.gupta 1110
function downloadNotifyDocument(documentId, cid, documentName) {
32301 amit.gupta 1111
    doAjaxGetDownload(context + "/notifyDocument/download?cid=" + cid,
1112
        documentName);
25651 tejbeer 1113
}
28051 amit.gupta 1114
 
1115
 
1116
/* Create an array with the values of all the input boxes in a column */
32301 amit.gupta 1117
$.fn.dataTable.ext.order['dom-text'] = function (settings, col) {
1118
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1119
        return $('input', td).val();
1120
    });
28051 amit.gupta 1121
}
28795 tejbeer 1122
 
28063 amit.gupta 1123
/* Create an array with the values of all the input boxes in a column, parsed as numbers */
32301 amit.gupta 1124
$.fn.dataTable.ext.order['dom-text-numeric'] = function (settings, col) {
1125
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1126
        return $('input', td).val() * 1;
1127
    });
28051 amit.gupta 1128
}
28795 tejbeer 1129
 
32301 amit.gupta 1130
$.fn.dataTable.ext.order['dom-stock-numeric'] = function (settings, col) {
1131
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1132
        return $(td).html().split("/")[0] * 1;
1133
    });
28870 tejbeer 1134
}
28051 amit.gupta 1135
/* Create an array with the values of all the select options in a column */
32301 amit.gupta 1136
$.fn.dataTable.ext.order['dom-select'] = function (settings, col) {
1137
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
1138
        return $('select', td).val();
1139
    });
28051 amit.gupta 1140
}
28795 tejbeer 1141
 
28051 amit.gupta 1142
/* Create an array with the values of all the checkboxes in a column */
32301 amit.gupta 1143
$.fn.dataTable.ext.order['dom-checkbox'] = function (settings, col) {
1144
    return this.api().column(col, {
1145
        order: 'index'
1146
    }).nodes().map(function (td, i) {
1147
        return $('input', td).prop('checked') ? '1' : '0';
1148
    });
30414 amit.gupta 1149
}
1150
 
32301 amit.gupta 1151
$.fn.dataTable.Api.register('sum()', function () {
1152
    return this.flatten().reduce(function (a, b) {
1153
        if (typeof a === 'string') {
1154
            a = a.replace(/[^\d.-]/g, '') * 1;
1155
            a = isNaN(a) ? 0 : a;
1156
        }
1157
        if (typeof b === 'string') {
1158
            b = b.replace(/[^\d.-]/g, '') * 1;
1159
            b = isNaN(b) ? 0 : b;
1160
        }
30414 amit.gupta 1161
 
32301 amit.gupta 1162
        return a + b;
1163
    }, 0);
30694 amit.gupta 1164
});
1165
 
1166
const debounce = (func, delay) => {
32301 amit.gupta 1167
    let debounceTimer
1168
    return function () {
1169
        const context = this
1170
        const args = arguments
1171
        clearTimeout(debounceTimer)
1172
        debounceTimer
1173
            = setTimeout(() => func.apply(context, args), delay)
1174
    }
30694 amit.gupta 1175
}
31687 amit.gupta 1176
 
32301 amit.gupta 1177
function parseDate(str) {
1178
    var m = str.match(/^(\d{1,2})[-/](\d{1,2})[-/](\d{4})$/);
1179
    return (m) ? new Date(m[3], m[2] - 1, m[1]) : null;
1180
}
31687 amit.gupta 1181
 
32130 amit.gupta 1182
function ExportToExcel(container, fn) {
32301 amit.gupta 1183
    let tableId = $(container).data('tableid');
1184
    var elt = document.getElementById(tableId);
33220 amit.gupta 1185
    console.log('elt', elt);
32301 amit.gupta 1186
    if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
33220 amit.gupta 1187
        let dataTable = $(`#${tableId}`).DataTable();
1188
        dataTable.page.len(-1).draw();
1189
        elt = dataTable.table(0).container();
32301 amit.gupta 1190
    }
1191
    ExportTableToExcel(elt, fn);
31687 amit.gupta 1192
}
1193
 
32301 amit.gupta 1194
function ExportTableToExcel(tableElt, fn) {
1195
    $table = $(tableElt)
1196
    $table.find('td').each((index, value) => {
1197
        let $tdElement = $(value);
1198
        console.log($tdElement);
1199
        let parsedDate = parseDate($tdElement.html());
1200
        if (parsedDate != null) {
1201
            let days = Math.floor(parsedDate.getTime() / 86400 * 1000);
1202
            $tdElement.data('v', days);
1203
            $tdElement.data("t", "n");
1204
            $tdElement.data("z", "yyyy-mm-dd");
1205
        }
1206
    });
1207
    console.log($table.get(0))
1208
    var wb = XLSX.utils.table_to_book($table.get(0), {sheet: "sheet1"});
1209
    XLSX.writeFile(wb, fn + '.xlsx');
1210
}
31687 amit.gupta 1211
 
32301 amit.gupta 1212
 
1213
$(document).on('click', ".manage-pcm", function () {
1214
    managePCM();
31687 amit.gupta 1215
});
1216
 
1217
function managePCM() {
32301 amit.gupta 1218
    doGetAjaxRequestHandler(`${context}/brand-pcm`, function (response) {
1219
        $('#main-content').html(response);
1220
    });
31687 amit.gupta 1221
}
31786 tejbeer 1222
 
1223
 
32301 amit.gupta 1224
$(document).on('click', ".digify-retailer-login", function () {
31786 tejbeer 1225
 
32301 amit.gupta 1226
    doGetAjaxRequestHandler(context + "/digify/register", function (response) {
32074 tejbeer 1227
 
1228
 
32301 amit.gupta 1229
        $('#main-content').html(response);
32074 tejbeer 1230
 
32301 amit.gupta 1231
    });
1232
    //$('#main-content').html(`<iframe class="wrapper" src="${context}/digify/register" style="width:100%;height:100vh"> </iframe>`);
1233
    //$('#main-content').html(`<a class="wrapper" href="${context}/digify/register" target="_blank" style="width:100%;height:100vh"> </a>`);
32074 tejbeer 1234
 
31786 tejbeer 1235
});
31878 tejbeer 1236
 
32301 amit.gupta 1237
$(document).on('click', '.warehousewise_stock', function () {
1238
    doGetAjaxRequestHandler(`${context}/warehouse/stock-qty`, function (response) {
1239
        $('#main-content').html(response);
1240
    });
32130 amit.gupta 1241
});
31878 tejbeer 1242
 
35594 amit 1243
// Partner name link - opens partner performance in new tab (reusable across all pages)
1244
$(document).on('click', '.partner-link', function (e) {
1245
    e.preventDefault();
1246
    var fofoId = $(this).data('fofoid');
1247
    if (fofoId) {
1248
        window.open(context + '/partnerPerformance?fofoId=' + fofoId, '_blank');
1249
    }
1250
});
1251
 
32567 tejbeer 1252
function loadMainContent(htmlContent) {
1253
    $('#main-content').html(htmlContent);
1254
}
31878 tejbeer 1255
 
1256
 
32979 amit.gupta 1257
function jsonStartDate(dateInputString) {
33220 amit.gupta 1258
    if (dateInputString === '') return null;
33141 amit.gupta 1259
    return moment(dateInputString, "yyyy-MM-DD").format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
32979 amit.gupta 1260
}
33220 amit.gupta 1261
 
32979 amit.gupta 1262
function jsonEndDate(dateInputString) {
33220 amit.gupta 1263
    if (dateInputString === '') return null;
33141 amit.gupta 1264
    return moment(dateInputString, "yyyy-MM-DD").endOf('day').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
32979 amit.gupta 1265
}
31878 tejbeer 1266
 
33167 amit.gupta 1267
function showToast(message) {
1268
    Toastify({
1269
        text: message,
1270
        duration: 3000, // 3 seconds
1271
        gravity: "top", // or "bottom"
1272
        position: "right", // "left", "center", "right"
1273
        backgroundColor: "green", // specify the background color
33400 ranu 1274
        offset: {
1275
            x: 20, // Horizontal margin from the right
1276
            y: 70 // Vertical margin from the top
1277
        }
33167 amit.gupta 1278
    }).showToast();
1279
}
31878 tejbeer 1280
 
33612 amit.gupta 1281
function loadHtml(html) {
1282
    $("#main-content").html(html);
1283
}
32130 amit.gupta 1284
 
33612 amit.gupta 1285
 
33508 tejus.loha 1286
function objectifyForm(formArray) {
35459 amit 1287
    //serialize data function
1288
    console.log('Row form  data ', formArray);
1289
    var returnArray = {};
1290
    for (var i = 0; i < formArray.length; i++) {
1291
        var name = formArray[i]['name'];
1292
        var value = formArray[i]['value'];
33927 tejus.loha 1293
        if (typeof returnArray[name] === 'undefined') {
1294
            returnArray[name] = value.trim();
35459 amit 1295
        } else if (typeof returnArray[name] === 'object') {
33927 tejus.loha 1296
            returnArray[name].push(value);
1297
        } else {
35459 amit 1298
            var a = returnArray[name];
1299
            returnArray[name] = [returnArray[name]];
1300
            a.push(value);
1301
            returnArray[name] = a;
33927 tejus.loha 1302
        }
33508 tejus.loha 1303
    }
1304
    return returnArray;
1305
}
32567 tejbeer 1306
 
33780 tejus.loha 1307
function isValidEmail(email) {
1308
    const EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(com|in|net)$/;
1309
    return EMAIL_REGEX.test(email);
1310
}
32979 amit.gupta 1311
 
34387 vikas.jang 1312
function serializeFormToJson(formId) {
1313
    let formArray = $(formId).serializeArray();
1314
    let formData = {};
1315
    $.map(formArray, function(field) {
1316
        formData[field.name] = field.value;
1317
    });
1318
    return formData;
34813 aman 1319
}
1320
 
1321
function getCookie(name) {
1322
    const cookies = document.cookie.split('; ');
1323
    for (let cookie of cookies) {
1324
        const [key, value] = cookie.split('=');
1325
        if (key === name) return decodeURIComponent(value);
1326
    }
1327
    return null;
35626 amit 1328
}
1329
 
1330
// ============================================================
1331
// PROMISE-BASED AJAX UTILITIES (SPA Support)
1332
// ============================================================
1333
 
1334
function doGetAjaxPromise(url, params) {
1335
    return $.ajax({
1336
        url: url,
1337
        method: 'GET',
1338
        data: params,
1339
        dataType: 'json',
1340
        cache: false
1341
    });
1342
}
1343
 
1344
function doPostAjaxJsonPromise(url, data) {
1345
    return $.ajax({
1346
        url: url,
1347
        method: 'POST',
1348
        data: JSON.stringify(data),
1349
        contentType: 'application/json',
1350
        dataType: 'json',
1351
        cache: false
1352
    });
1353
}
1354
 
1355
function doPostAjaxParamsPromise(url, params) {
1356
    return $.ajax({
1357
        url: url,
1358
        method: 'POST',
1359
        data: params,
1360
        dataType: 'json',
1361
        cache: false
1362
    });
1363
}
1364
 
1365
// ============================================================
1366
// SPA UTILITIES
1367
// ============================================================
1368
 
1369
function createSpaModule(config) {
1370
    var defaultConfig = {
1371
        name: 'SpaModule',
1372
        endpoints: {},
1373
        state: {},
1374
        onInit: function() {},
1375
        onDestroy: function() {}
1376
    };
1377
 
1378
    var moduleConfig = $.extend(true, {}, defaultConfig, config);
1379
    var state = $.extend(true, {}, moduleConfig.state);
1380
    var timers = {};
1381
 
1382
    return {
1383
        getName: function() { return moduleConfig.name; },
1384
        getState: function(key) { return key ? state[key] : state; },
1385
        setState: function(key, value) {
1386
            state[key] = value;
1387
            return this;
1388
        },
1389
        getEndpoint: function(name) {
1390
            return context + moduleConfig.endpoints[name];
1391
        },
1392
        setTimer: function(name, callback, delay) {
1393
            this.clearTimer(name);
1394
            timers[name] = setTimeout(callback, delay);
1395
            return timers[name];
1396
        },
1397
        clearTimer: function(name) {
1398
            if (timers[name]) {
1399
                clearTimeout(timers[name]);
1400
                delete timers[name];
1401
            }
1402
            return this;
1403
        },
1404
        clearAllTimers: function() {
1405
            var self = this;
1406
            Object.keys(timers).forEach(function(name) { self.clearTimer(name); });
1407
            return this;
1408
        },
1409
        init: function(options) {
1410
            moduleConfig.onInit.call(this, options);
1411
            return this;
1412
        },
1413
        destroy: function() {
1414
            this.clearAllTimers();
1415
            state = $.extend(true, {}, moduleConfig.state);
1416
            moduleConfig.onDestroy.call(this);
1417
            return this;
1418
        }
1419
    };
1420
}
1421
 
1422
function handleApiResponse(response, successCallback, errorCallback) {
1423
    if (response && response.success) {
1424
        if (typeof successCallback === 'function') {
1425
            successCallback(response.data);
1426
        }
1427
    } else {
1428
        var message = response && response.message ? response.message : 'An error occurred';
1429
        if (typeof errorCallback === 'function') {
1430
            errorCallback(message, response);
1431
        } else {
1432
            bootbox.alert(message);
1433
        }
1434
    }
1435
}
1436
 
1437
function resolveUrlTemplate(template, params) {
1438
    var url = template;
1439
    for (var key in params) {
1440
        if (params.hasOwnProperty(key)) {
1441
            url = url.replace('{' + key + '}', encodeURIComponent(params[key]));
1442
        }
1443
    }
1444
    return url;
34387 vikas.jang 1445
}