Subversion Repositories SmartDukaan

Rev

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

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