Subversion Repositories SmartDukaan

Rev

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