Subversion Repositories SmartDukaan

Rev

Rev 35533 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*window.alert = function(message) {
    Swal.fire({
        text: message,
        icon: 'info',
        confirmButtonText: 'OK'
    });
};*/
const MAIN_CONTAINER = "#main-content";
var logosmapping = {
    mobile_insurance_providers: {
        "0": context + '/resources/images/icons/provider-logos/iffco.png',
        "1": context + '/resources/images/icons/provider-logos/icici.jpg',
        "2": context + '/resources/images/icons/provider-logos/tataaig.png',
        "3": context + '/resources/images/icons/provider-logos/bharti.jpg',
        "4": context + '/resources/images/icons/provider-logos/bharti.jpg',
        "5": context + '/resources/images/icons/provider-logos/oneassist.jpeg'
    }
}

function uuidv4() {
    return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
        (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
    );
}

let IdempotencyKey = uuidv4();

function badRequestAlert(response) {
    //console.log(response.responseText);
    try {
        var errorObject = JSON.parse(response.responseText);
        errorObject = errorObject.response;
        bootbox.alert('Bad Request\n' + 'rejectedType : '
            + errorObject.rejectedType + '\n' + 'rejectedValue : '
            + errorObject.rejectedValue + '\n' + 'message : '
            + errorObject.message);
    } catch (e) {
        console.log("response.responseText", response.responseText);
        bootbox.alert("Error occurred! Please contact your manager");
    }
}

function internalServerErrorAlert(response) {
    // console.log(response.responseText);
    try {
        var errorObject = JSON.parse(response.responseText);
        errorObject = errorObject.response;
        bootbox.alert('Internal Server Error\n' + 'rejectedType : '
            + errorObject.rejectedType + '\n' + 'rejectedValue : '
            + errorObject.rejectedValue + '\n' + 'message : '
            + errorObject.message);
    } catch (e) {
        console.log("response.responseText", response.responseText);
        bootbox.alert("Error occurred! Please contact your manager");
    }
}

$(document).ajaxError(function (event, jqxhr, settings, thrownError) {
    if (typeof loaderDialogObj != "undefined") {
        loaderDialogObj.modal('hide');
        // $('div.modal-backdrop.fade').remove();
    }
    if (jqxhr.status == 400) {
        // $('#error-prompt-model').modal();
        badRequestAlert(jqxhr);
    } else {
        internalServerErrorAlert(jqxhr);
    }
});

$(document).ajaxSend(function (ev, req) {
    req.setRequestHeader('IdempotencyKey', IdempotencyKey);
});

$(document).ajaxSuccess(function () {
    IdempotencyKey = uuidv4();
    console.log('succcess handlor');
});

$(document).ajaxComplete(function () {
    if (typeof loaderDialogObj != "undefined") {
        loaderDialogObj.modal('hide');
        // $('div.modal-backdrop.fade').remove();
    }
    IdempotencyKey = uuidv4();
    console.log("idempotency key", IdempotencyKey = uuidv4());
});

function ajaxStartHandler() {
    if (typeof loaderDialogObj != "undefined")
        loaderDialogObj.modal('show');
}

$(document).ajaxStart(ajaxStartHandler);

function doAjaxRequestWithParamsHandler(urlString, httpType, params, callback_function) {
    $.ajax({
        url: urlString,
        async: true,
        cache: false,
        data: params,
        // dataType:'json',
        type: httpType,
        success: function (response) {
            IdempotencyKey = uuidv4();
            callback_function(response);
            formatCurrency();
        }
    });
}

function doGetAjaxRequestWithParamsHandler(urlString, params, callback_function) {
    doAjaxRequestWithParamsHandler(urlString, "GET", params, callback_function);
}

function doPostAjaxRequestWithParamsHandler(urlString, params, callback_function) {
    doAjaxRequestWithParamsHandler(urlString, "POST", params, callback_function);
}

function formatCurrency() {
    $('.currency').each(function (index, ele) {
        if (!isNaN(parseInt($(ele).html()))) {
            $(ele).html(formatValueInCrore($(ele).html()));
        }
    });

}

function doAjaxRequestWithJsonHandler(urlString, httpType, json, callback_function) {
    $.ajax({
        url: urlString,
        async: true,
        cache: false,
        processData: false,
        data: json,
        contentType: 'application/json',
        type: httpType,
        success: function (response) {
            // console.log("response"+JSON.stringify(data));
            callback_function(response);
            formatCurrency();
        }
    });
}

function doPostAjaxRequestWithJsonHandler(urlString, json, callback_function) {
    doAjaxRequestWithJsonHandler(urlString, "POST", json, callback_function);
}

function doPutAjaxRequestWithJsonHandler(urlString, json, callback_function) {
    doAjaxRequestWithJsonHandler(urlString, "PUT", json, callback_function);
}

function doAjaxRequestHandler(urlString, httpType, callback_function) {
    $.ajax({
        url: urlString,
        async: true,
        cache: false,
        type: httpType,
        success: function (response) {
            callback_function(response);
            formatCurrency();
        }
    });
}

function doGetAjaxRequestHandler(urlString, callback_function) {
    doAjaxRequestHandler(urlString, "GET", callback_function);
}

function doPutAjaxRequestHandler(urlString, callback_function) {
    doAjaxRequestHandler(urlString, "PUT", callback_function);
}

function doPostAjaxRequestHandler(urlString, callback_function) {
    doAjaxRequestHandler(urlString, "POST", callback_function);
}

function doDeleteAjaxRequestHandler(urlString, callback_function) {
    doAjaxRequestHandler(urlString, "DELETE", callback_function);
}

function doAjaxUploadRequest(urlString, httpType, file) {
    var response;
    doAjaxUploadRequestHandler(urlString, httpType, file,
        function (ajaxResponse) {
            response = ajaxResponse;
        });
    return response;
}

function doAjaxUploadRequestHandler(urlString, httpType, file, callback_function) {
    var formData = new FormData();
    formData.append("file", file);
    $.ajax({
        url: urlString,
        type: httpType,
        data: formData,
        dataType: 'json',
        async: true,
        cache: false,
        contentType: false,
        enctype: 'multipart/form-data',
        processData: false,
        success: function (response) {
            // console.log("response"+JSON.stringify(data));
            callback_function(response);
        }
    });
}

function doAjaxUploadRequestJsonHandler(urlString, httpType, file, json, callback_function) {
    var formData = new FormData();
    formData.append("file", file);
    formData.append('json', new Blob([json]));
    $.ajax({
        url: urlString,
        type: httpType,
        data: formData,
        enctype: 'multipart/form-data',
        contentType: false,
        processData: false,
        success: function (response) {
            // console.log("response"+JSON.stringify(data));
            callback_function(response);
        }
    });
}

function uploadDocument(file, callback) {
    var url = context + '/document-upload';
    doAjaxUploadRequestHandler(url, 'POST', file, function (response) {
        var documentId = response.response.document_id;
        //console.log("documentId : " + documentId);
        callback(documentId);
    });
}

function doAjaxGetDownload(urlString, fileName) {
    // console.log("fileName : " + fileName);
    doAjaxDownload(urlString, "GET", null, fileName);
}

function doAjaxPostDownload(urlString, data, fileName, callback) {
    doAjaxDownload(urlString, "POST", data, fileName, callback);
}

function doAjaxDownload(urlString, httpType, data, fileName, callback) {
    xhttp = new XMLHttpRequest();
    if (typeof loaderDialogObj != "undefined")
        loaderDialogObj.modal('show');
    xhttp.onreadystatechange = function () {
        var a;
        if (xhttp.readyState === 2) {
            if (xhttp.status == 200) {
                xhttp.responseType = "blob";
            } else {
                xhttp.responseType = "text";
            }
        } else if (xhttp.readyState === 4 && xhttp.status === 200) {
            // Trick for making downloadable link
            if (typeof loaderDialogObj != "undefined") {
                loaderDialogObj.modal('hide');
                // $('div.modal-backdrop.fade').remove();
            }

            a = document.createElement('a');
            a.href = window.URL.createObjectURL(xhttp.response);
            // Give filename you wish to download
            a.download = fileName;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
        } else if (xhttp.readyState == 4 && xhttp.status === 400) {
            if (typeof loaderDialogObj != "undefined") {
                loaderDialogObj.modal('hide');
                // $('div.modal-backdrop.fade').remove();
            }
            badRequestAlert(xhttp);
        } else if (xhttp.readyState == 4 && xhttp.status === 500) {
            if (typeof loaderDialogObj != "undefined") {
                loaderDialogObj.modal('hide');
                // $('div.modal-backdrop.fade').remove();
            }
            internalServerErrorAlert(xhttp);
        }
    };
    // Post data to URL which handles post request
    xhttp.open(httpType, urlString);

    // if (IdempotencyKey) {
    //     xhttp.setRequestHeader("IdempotencyKey", IdempotencyKey);
    // }

    if (httpType == "POST") {
        xhttp.setRequestHeader("Content-Type", "application/json");
    }
    // You should set responseType as blob for binary responses
    // xhttp.responseType = 'blob';
    xhttp.send(data);
}

function loadPaginatedCatalogNextItems(url, params, paginatedIdentifier,
                                       tableIdentifier, detailsContainerIdentifier) {
    var start = $("#" + paginatedIdentifier + " .start").text();

    var end = $("#" + paginatedIdentifier + " .end").text();

    url = context + url + "?offset=" + end;

    if (params != null) {
        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                //console.log(key + " -> " + params[key]);
                url = url + "&" + key + "=" + params[key];
            }
        }
    }

    doGetAjaxRequestHandler(url, function (response) {
        var size = $("#" + paginatedIdentifier + " .size").text();
        if ((parseInt(end) + 20) > parseInt(size)) {
            // console.log("(end + 10) > size == true");
            $("#" + paginatedIdentifier + " .end").text(size);
        } else {
            // console.log("(end + 10) > size == false");
            $("#" + paginatedIdentifier + " .end").text(+end + +20);
        }
        $("#" + paginatedIdentifier + " .start").text(+start + +20);
        var last = $("#" + paginatedIdentifier + " .end").text();
        var temp = $("#" + paginatedIdentifier + " .size").text();
        console.log("last" + last);
        if (parseInt(last) >= parseInt(temp)) {
            $("#" + paginatedIdentifier + " .next").prop('disabled', true);
            // $( "#good-inventory-paginated .end" ).text(temp);
        }
        $('#' + tableIdentifier).html(response);
        if (detailsContainerIdentifier != null) {
            $('#' + detailsContainerIdentifier).html('');
        }
        $("#" + paginatedIdentifier + " .previous").prop('disabled', false);
    });

}

function loadPaginatedCatalogPreviousItem(url, params, paginatedIdentifier,
                                          tableIdentifier, detailsContainerIdentifier) {
    var start = $("#" + paginatedIdentifier + " .start").text();
    //console.log("start" + start);
    var end = $("#" + paginatedIdentifier + " .end").text();
    //console.log("Startend" + end);
    var size = $("#" + paginatedIdentifier + " .size").text();
    //console.log("size" + size);
    if (parseInt(end) == parseInt(size) && parseInt(end) % 20 != 0) {
        var mod = parseInt(end) % 20;
        end = parseInt(end) + (20 - mod);
    }
    var pre = end - 20;
    var lat = pre - 20;
    //console.log("preCatalog" +pre);

    url = context + url + "?offset=" + pre;

    if (params != null) {
        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                url = url + "&" + key + "=" + params[key];
            }
        }
    }

    doGetAjaxRequestHandler(url, function (response) {
        $("#" + paginatedIdentifier + " .end").text(+end - +20);
        $("#" + paginatedIdentifier + " .start").text(+start - +20);
        $('#' + tableIdentifier).html(response);
        if (detailsContainerIdentifier != null) {
            $('#' + detailsContainerIdentifier).html('');
        }
        $("#" + paginatedIdentifier + " .next").prop('disabled', false);
        if (parseInt(lat) == 0) {
            $("#" + paginatedIdentifier + " .previous").prop('disabled', true);
        }
    });

}

function loadPaginatedNextItems(url, params, paginatedIdentifier,
                                tableIdentifier, detailsContainerIdentifier) {
    var start = $("#" + paginatedIdentifier + " .start").text();
    var end = $("#" + paginatedIdentifier + " .end").text();
    url = context + url + "?offset=" + end;

    if (params != null) {
        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                // console.log(key + " -> " + p[key]);
                url = url + "&" + key + "=" + params[key];
            }
        }
    }

    doGetAjaxRequestHandler(url, function (response) {
        var size = $("#" + paginatedIdentifier + " .size").text();
        if ((parseInt(end) + 10) > parseInt(size)) {
            console.log("(end + 10) > size == true");
            $("#" + paginatedIdentifier + " .end").text(size);
        } else {
            console.log("(end + 10) > size == false");
            $("#" + paginatedIdentifier + " .end").text(+end + +10);
        }
        $("#" + paginatedIdentifier + " .start").text(+start + +10);
        var last = $("#" + paginatedIdentifier + " .end").text();
        var temp = $("#" + paginatedIdentifier + " .size").text();
        if (parseInt(last) >= parseInt(temp)) {
            $("#" + paginatedIdentifier + " .next").prop('disabled', true);
            // $( "#good-inventory-paginated .end" ).text(temp);
        }
        $('#' + tableIdentifier).html(response);
        if (detailsContainerIdentifier != null) {
            $('#' + detailsContainerIdentifier).html('');
        }
        $("#" + paginatedIdentifier + " .previous").prop('disabled', false);
    });

}

function loadPaginatedPreviousItems(url, params, paginatedIdentifier,
                                    tableIdentifier, detailsContainerIdentifier) {
    var start = $("#" + paginatedIdentifier + " .start").text();
    var end = $("#" + paginatedIdentifier + " .end").text();
    var size = $("#" + paginatedIdentifier + " .size").text();
    if (parseInt(end) == parseInt(size) && parseInt(end) % 10 != 0) {
        var mod = parseInt(end) % 10;
        end = parseInt(end) + (10 - mod);
    }
    var pre = end - 10;

    url = context + url + "?offset=" + pre;

    if (params != null) {
        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                url = url + "&" + key + "=" + params[key];
            }
        }
    }

    doGetAjaxRequestHandler(url, function (response) {
        $("#" + paginatedIdentifier + " .end").text(+end - +10);
        $("#" + paginatedIdentifier + " .start").text(+start - +10);
        $('#' + tableIdentifier).html(response);
        if (detailsContainerIdentifier != null) {
            $('#' + detailsContainerIdentifier).html('');
        }
        $("#" + paginatedIdentifier + " .next").prop('disabled', false);
        if (parseInt(pre) == 0) {
            $("#" + paginatedIdentifier + " .previous").prop('disabled', true);
        }
    });

}

function numberToComma(x, rounded) {
    if (isNaN(x)) {
        x = x.replaceAll(",", '');
    }
    x = parseFloat(x);
    if (typeof rounded != "undefined" && rounded) {
        x = Math.round(x);
    } else {
        x = Math.round(x * 100) / 100;
    }
    // Handle scientific notation (e.g., 1.37E7) - convert to full decimal string
    x = x.toLocaleString('en-US', {useGrouping: false, maximumFractionDigits: 2});
    x = x.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 && x[1] != '0' ? '.' + x[1] : '';
    var lastThree = x1.substring(x1.length - 3);
    var otherNumbers = x1.substring(0, x1.length - 3);
    if (x1.charAt(x1.length - 4) == ',' || x1.charAt(x1.length - 4) == '-') {
        console.log(lastThree)
    } else {
        if (otherNumbers != '')
            lastThree = ',' + lastThree;
    }
    return otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + (lastThree)
        + x2;

}

function formatValueInCrore(value) {
    if (isNaN(value)) return value;
    value = parseFloat(value);
    return numberToComma(value);
    /*if (value >= 10000000) {  // >= 1 Crore
        var croreValue = value / 10000000;
        // Remove trailing zeros: 1.500 -> 1.5, 1.000 -> 1
        var formatted = croreValue.toFixed(3).replace(/\.?0+$/, '');
        return formatted + ' Cr';
    } else {
        // Less than 1 Crore - show full number with Indian comma format
        return numberToComma(value);
    }*/
}

function getSingleDatePicker(startMoment) {
    var singleDatePicker = {
        "todayHighlight": true,
        "startDate": startMoment || moment(),
        "autoclose": true,
        "autoUpdateInput": true,
        "singleDatePicker": true,
        "locale": {
            'format': 'DD/MM/YYYY'
        }
    };
    return singleDatePicker;
}

function getDatesFromPicker(pickerElement) {
    return {
        startDate: $(pickerElement).data('daterangepicker').startDate.format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS),
        endDate: $(pickerElement).data('daterangepicker').endDate.format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS)
    }
}

function getReporticoDatesFromPicker(pickerElement) {
    let datePickerData = $(pickerElement).data('daterangepicker');
    let formattedEndDate = null;
    if (typeof datePickerData.endDate == "object") {
        formattedEndDate = datePickerData.endDate.format(moment.HTML5_FMT.DATE);
    }
    return {
        startDate: datePickerData.startDate.format(moment.HTML5_FMT.DATE),
        endDate: formattedEndDate
    };
}

function getStartOfFinancialYear(momentObj) {
    recentQuarter = momentObj.startOf('quarter').set('quarter', 2);
    return momentObj.quarter >= 2 ? recentQuarter : recentQuarter.subtract('year', 1);
}

function getStatementRanges() {
    return {
        ranges: {
            'This Month': [moment().startOf('month'), moment().startOf('day')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
            'Last 3 Months': [moment().subtract(3, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
            'Last 6 Months': [moment().subtract(6, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
            'Current Financial Year': [getStartOfFinancialYear(moment()), getStartOfFinancialYear(moment()).add('year', 1).subtract(1, 'day')],
            'Last Financial Year': [getStartOfFinancialYear(moment()).subtract('year', 1), getStartOfFinancialYear(moment()).subtract(1, 'day')]
        },
        alwaysShowCalendars: false,
        showCustomRangeLabel: false,
        showDropdowns: true,
        locale: {
            format: 'DD/MM/YYYY'
        }
    }
}

function getYearMonthPicker() {
    return {
        "todayHighlight": true,
        "showDropdowns": true,
        "opens": "right",
        "startDate": moment().startOf('month'),
        "endDate": moment().endOf('month'),
        "singleDatePicker": true, // Ensures only one month selection
        "showCustomRangeLabel": false,
        "autoApply": true,
        "locale": {
            'format': 'YYYY-MM' // Year-Month format
        },
        "isInvalidDate": function (date) {
            return date.date() !== 1; // Only allows selecting the first day of a month
        }
    };
}

function getRangedDatePicker(showRanges, startMoment, endMoment) {
    if (typeof showRanges == "undefined") {
        showRanges = false;
    }
    var rangedDatePicker = {
        "todayHighlight": true,
        "showDropdowns": true,
        "opens": "right",
        "startDate": startMoment || moment().startOf('day'),
        "endDate": endMoment || moment().endOf('day'),
        "autoclose": true,
        "alwaysShowCalendars": false,
        "autoUpdateInput": true,
        "locale": {
            'format': 'DD/MM/YYYY'
        }
    };
    if (showRanges) {
        rangedDatePicker['ranges'] = {
            'Today': [moment(), moment()],
            'Yesterday': [moment().subtract(1, 'days'),
                moment().subtract(1, 'days')],
            'Last 7 Days': [moment().subtract(6, 'days'), moment()],
            'Last 30 Days': [moment().subtract(29, 'days'), moment()],
            'This Month': [moment().startOf('month'), moment().endOf('month')],
            'Last Month': [moment().subtract(1, 'month').startOf('month'),
                moment()],
            'Last 3 Months': [moment().subtract(3, 'month').startOf('month'),
                moment()],
            'Last 6 Months': [moment().subtract(6, 'month').startOf('month'),
                moment()]
        };
    }
    return rangedDatePicker;
}

function showPosition(position) {
    if (typeof latitude == "undefined") {
        var coords = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude
        };
        doAjaxRequestWithJsonHandler('partner/location', 'PUT', JSON
            .stringify(coords), function () {
            latitude = position.coords.latitude;
            longitude = position.coords.longitude;
        });
    }
    // distance = getDistance(latitude, longitude, position.coords.latitude,
    // position.coords.longitude);
}

function getAuthorisedWarehouses(callback) {
    bootBoxObj = {
        size: "small",
        title: "Choose Warehouse",
        callback: callback,
        inputType: 'select',
        inputOptions: typeof inputOptions == "undefined" ? undefined : inputOptions
    };
    if (typeof inputOptions == "undefined") {
        doGetAjaxRequestHandler(context + "/authorisedWarehouses", function (
            response) {
            response = JSON.parse(response);
            inputOptions = [];
            response.forEach(function (warehouse) {
                inputOptions.push({
                    text: warehouse.name,
                    value: warehouse.id,
                });
            });
            bootBoxObj['inputOptions'] = inputOptions;
            bootbox.prompt(bootBoxObj);
        });
    } else if (inputOptions.length == 1) {
        callback(inputOptions[0].warehouse.id);
    } else {
        bootbox.prompt(bootBoxObj);
    }

}

function getColorsForItems(catalogId, itemId, description, callback) {
    colorCheckboxHandler(catalogId, itemId, description, callback);
}

function colorNumberHandler(catalogId, itemId, title, actionText, callback) {
    doGetAjaxRequestHandler(context + "/itemsByCatalogId?catalogId="
        + catalogId + "&itemId=" + itemId, function (response) {
        let coloredItems = JSON.parse(response);
        let modalBody = [];
        coloredItems.forEach(function (item) {
            modalBody.push(`
                <div class="row">
                    <div class="col-sm-2">
                        ${item.color}
                    </div>
                    <div class="col-sm-2">
                            <input data-itemid="${item.id}" type="text" class="form-control" />
                    </div>
                </div>
            `);
        });
        let dialogBoxHtml = `<div class="modal modal" tabindex="-1" role="dialog">
                              <div class="modal-dialog" >
                                <div class="modal-content">
                                  <div class="modal-header">
                                    <h5 class="modal-title">${title}</h5>
                                  </div>
                                  <div class="modal-body">
                                        ${modalBody.join('')}
                                  </div>
                                  <div class="modal-footer">
                                    <button type="button" class="btn btn-primary number_dialog">${actionText}</button>
                                  </div>
                                </div>
                              </div>
                            </div>`;
        let $dialog = $(dialogBoxHtml);
        let modalObj = $dialog.modal('show');
        modalObj.on('hidden.bs.modal', function (e) {
            $dialog.remove();
        });
        $('button.number_dialog').on('click', function () {
            let itemQty = [];
            let anySelected = false;
            $(modalObj).find('.modal-body').find('input').each(function () {
                $input = $(this);
                if ($input.val() > 0) {
                    itemQty.push({
                        itemId: $input.data("itemid"),
                        quantity: $input.val()
                    });
                    anySelected = true;
                }
            });
            if (anySelected && confirm("Are you sure want to notify?")) {
                $that = $(this);
                callback(itemQty, function () {
                    $that.off('click');
                    modalObj.hide();
                });
            } else {
                alert("Pls mention quantity");
            }
        });
    });
}


function colorCheckboxHandler(catalogId, itemId, description, callback) {
    let bootBoxObj = {
        size: "small",
        className: "item-wrapper",
        title: description,
        callback: callback,
        inputType: 'checkbox',
    }
    doGetAjaxRequestHandler(context + "/itemsByCatalogId?catalogId="
        + catalogId + "&itemId=" + itemId, function (response) {
        coloredItems = JSON.parse(response);
        inputOptions = [{
            text: "All",
            value: "0",
            onclick: "toggleAll('itemIds')"
        }];
        coloredItems.forEach(function (item) {
            inputOptions.push({
                text: item.color,
                value: item.id,
                selected: item.active
            });
        });
        bootBoxObj['inputOptions'] = inputOptions;
        promptObj = bootbox.prompt(bootBoxObj);
        promptObj.modal('show')
        $('.item-wrapper').find("input[type='checkbox']").slice(1).each(
            function (index, checkbox) {
                checkbox.checked = coloredItems[index].active;
            });
    });
}

function getHotdealsForItems(catalogId, itemId, description, callback) {
    bootBoxObj = {
        size: "small",
        className: "item-wrapper",
        title: description,
        callback: callback,
        inputType: 'checkbox',
    }
    doGetAjaxRequestHandler(context + "/hotdealsitemsByCatalogId?catalogId="
        + catalogId + "&itemId=" + itemId, function (response) {
        coloredItems = JSON.parse(response);
        inputOptions = [{
            text: "All",
            value: "0",
            onclick: "toggleAll('itemIds')"
        }];
        coloredItems.forEach(function (item) {
            inputOptions.push({
                text: item.color,
                value: item.id,
                selected: item.hotDeals
            });
        });
        bootBoxObj['inputOptions'] = inputOptions;
        promptObj = bootbox.prompt(bootBoxObj);
        promptObj.modal('show')
        $('.item-wrapper').find("input[type='checkbox']").slice(1).each(
            function (index, checkbox) {
                checkbox.checked = coloredItems[index].hotDeals;
            });
    });
}

$(document).on('change', ".item-wrapper input[type='checkbox']:first",
    function () {
        if (this.value == "0") {
            $(this).closest('.item-wrapper').find("input[type='checkbox']")
                .slice(1).prop('checked', $(this).prop('checked'));
        }
    });

function getItemAheadOptions(jqElement, anyColor, callback) {
    console.log(anyColor)
    jqElement.typeahead('destroy').typeahead({
        source: function (q, process) {
            if (q.length >= 3) {
                return $.ajax(context + "/item?anyColor=" + anyColor, {
                    global: false,
                    data: {
                        query: q
                    },
                    headers: {
                        'IdempotencyKey': IdempotencyKey
                    },
                    success: function (data) {
                        //IdempotencyKey = uuidv4();
                        queryData = JSON.parse(data);
                        process(queryData);
                    },
                });
            }
        },
        delay: 300,
        items: 20,
        displayText: function (item) {
            return item.itemDescription;
        },
        autoSelect: true,
        afterSelect: callback
    });
}


function getVendorItemAheadOptions(jqElement, vendorId, callback) {
    jqElement.typeahead('destroy').typeahead({
        source: function (q, process) {
            if (q.length >= 3) {
                return $.ajax(context + "/vendorItem?vendorId=" + vendorId, {
                    global: false,
                    data: {
                        query: q
                    },
                    headers: {
                        'IdempotencyKey': IdempotencyKey
                    },
                    success: function (data) {
                        //IdempotencyKey = uuidv4();
                        queryData = JSON.parse(data);
                        process(queryData);
                    },
                });
            }
        },
        delay: 300,
        items: 20,
        displayText: function (item) {
            return item.itemDescription;
        },
        autoSelect: true,
        afterSelect: callback
    });
}

function getImeiAheadOptions(jqElement, fofoId, callback) {
    jqElement.typeahead('destroy').typeahead({
            source: function (q, process) {
                if (q.length >= 3) {
                    return $.ajax(context + "/imei?fofoId=" + fofoId, {
                        global: false,
                        data: {
                            query: q
                        },
                        headers: {
                            'IdempotencyKey': IdempotencyKey
                        },
                        success: function (data) {
                            //IdempotencyKey = uuidv4();
                            queryData = JSON.parse(data);
                            process(queryData);
                        },
                    });
                }
            },
            delay: 300,
            items: 20,
            displayText: function (imei) {
                return imei;
            },
            autoSelect: true,
            afterSelect: callback
        }
    );
}


function getAllImeiAheadOptions(jqElement, callback) {
    jqElement.typeahead('destroy').typeahead({
        source: function (q, process) {
            if (q.length >= 3) {
                return $.ajax(context + "/allimei", {
                    global: false,
                    data: {
                        query: q
                    },
                    headers: {
                        'IdempotencyKey': IdempotencyKey
                    },
                    success: function (data) {
                        //IdempotencyKey = uuidv4();
                        queryData = JSON.parse(data);
                        process(queryData);
                    },
                });
            }
        },
        delay: 300,
        items: 20,
        displayText: function (imei) {
            return imei;
        },
        autoSelect: true,
        afterSelect: callback
    });
}


function getEntityAheadOptions(jqElement, callback) {
    jqElement.typeahead('destroy').typeahead({
        source: function (q, process) {
            if (q.length >= 3) {
                return $.ajax(context + "/entity", {
                    global: false,
                    data: {
                        query: q
                    },
                    headers: {
                        'IdempotencyKey': IdempotencyKey
                    },
                    success: function (data) {
                        //IdempotencyKey = uuidv4();
                        queryData = JSON.parse(data);
                        process(queryData);
                    },
                });
            }
        },
        delay: 300,
        items: 30,
        displayText: function (entity) {
            return entity.title_s + "(" + entity.catalogId_i + ")";
        },
        autoSelect: true,
        afterSelect: callback
    });
}

function getPartnerAheadOptions(jqElement, callback) {
    jqElement.typeahead('destroy').typeahead({
        source: function (q, process) {
            if (q.length >= 3) {
                return $.ajax(context + "/partners", {
                    global: false,
                    data: {
                        query: q
                    },
                    headers: {
                        'IdempotencyKey': IdempotencyKey
                    },
                    success: function (data) {
                        //IdempotencyKey = uuidv4();
                        queryData = JSON.parse(data);
                        process(queryData);
                    },
                });
            }
        },
        delay: 300,
        items: 20,
        displayText: function (partner) {
            return partner.displayName;
        },
        autoSelect: true,
        afterSelect: callback
    });
}

function getVendorAheadOptions(jqElement, callback) {
    jqElement.typeahead('destroy').typeahead({
        source: function (q, process) {
            if (q.length >= 3) {
                return $.ajax(context + "/vendors", {
                    global: false,
                    data: {
                        query: q
                    },
                    headers: {
                        'IdempotencyKey': IdempotencyKey
                    },
                    success: function (data) {
                        //IdempotencyKey = uuidv4();
                        queryData = JSON.parse(data);
                        process(queryData);
                    },
                });
            }
        },
        delay: 300,
        items: 20,
        displayText: function (vendor) {
            return vendor.name;
        },
        autoSelect: true,
        afterSelect: callback
    });
}

function loadPriceDrop(domId) {
    doGetAjaxRequestHandler(context + "/getItemDescription",
        function (response) {
            $('#' + domId).html(response);
        });
}

$(document).on('click', ".price_drop", function () {
    loadPriceDrop("main-content");
});


$(document).on('click', ".closed_pricedrop", function () {
    loadClosedPriceDrop("main-content");
});

function loadClosedPriceDrop(domId) {
    doGetAjaxRequestHandler(context + "/getClosedPricedropItemDescription",
        function (response) {
            $('#' + domId).html(response);
        });
}

function notifyTypeChange(messageType, $container) {
    var messageQueryString = "?messageType=" + messageType;
    if (messageType == null) {
        messageQueryString = "";
    }
    doGetAjaxRequestHandler(context + "/notifications" + messageQueryString, function (response) {
        if ($container != null) {
            loaderDialogObj.one('hidden.bs.modal', function () {
                $container.popover({
                    container: $container,
                    template: '<div class="popover popover1" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content popover2"></div></div>',
                    content: response,
                    html: true,
                    placement: "bottom",
                    trigger: "manual",
                    sanitize: false
                }).popover('show');
                setTimeout(function () {
                    $container.focus().one('blur', function () {
                        $container.popover('destroy');
                    });
                }, 100);
            });
        }
    });
}

function downloadNotifyDocument(documentId, cid, documentName) {
    doAjaxGetDownload(context + "/notifyDocument/download?cid=" + cid,
        documentName);
}


/* Create an array with the values of all the input boxes in a column */
$.fn.dataTable.ext.order['dom-text'] = function (settings, col) {
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
        return $('input', td).val();
    });
}

/* Create an array with the values of all the input boxes in a column, parsed as numbers */
$.fn.dataTable.ext.order['dom-text-numeric'] = function (settings, col) {
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
        return $('input', td).val() * 1;
    });
}

$.fn.dataTable.ext.order['dom-stock-numeric'] = function (settings, col) {
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
        return $(td).html().split("/")[0] * 1;
    });
}
/* Create an array with the values of all the select options in a column */
$.fn.dataTable.ext.order['dom-select'] = function (settings, col) {
    return this.api().column(col, {order: 'index'}).nodes().map(function (td, i) {
        return $('select', td).val();
    });
}

/* Create an array with the values of all the checkboxes in a column */
$.fn.dataTable.ext.order['dom-checkbox'] = function (settings, col) {
    return this.api().column(col, {
        order: 'index'
    }).nodes().map(function (td, i) {
        return $('input', td).prop('checked') ? '1' : '0';
    });
}

$.fn.dataTable.Api.register('sum()', function () {
    return this.flatten().reduce(function (a, b) {
        if (typeof a === 'string') {
            a = a.replace(/[^\d.-]/g, '') * 1;
            a = isNaN(a) ? 0 : a;
        }
        if (typeof b === 'string') {
            b = b.replace(/[^\d.-]/g, '') * 1;
            b = isNaN(b) ? 0 : b;
        }

        return a + b;
    }, 0);
});

const debounce = (func, delay) => {
    let debounceTimer
    return function () {
        const context = this
        const args = arguments
        clearTimeout(debounceTimer)
        debounceTimer
            = setTimeout(() => func.apply(context, args), delay)
    }
}

function parseDate(str) {
    var m = str.match(/^(\d{1,2})[-/](\d{1,2})[-/](\d{4})$/);
    return (m) ? new Date(m[3], m[2] - 1, m[1]) : null;
}

function ExportToExcel(container, fn) {
    let tableId = $(container).data('tableid');
    var elt = document.getElementById(tableId);
    console.log('elt', elt);
    if ($.fn.DataTable.isDataTable(`#${tableId}`)) {
        let dataTable = $(`#${tableId}`).DataTable();
        dataTable.page.len(-1).draw();
        elt = dataTable.table(0).container();
    }
    ExportTableToExcel(elt, fn);
}

function ExportTableToExcel(tableElt, fn) {
    $table = $(tableElt)
    $table.find('td').each((index, value) => {
        let $tdElement = $(value);
        console.log($tdElement);
        let parsedDate = parseDate($tdElement.html());
        if (parsedDate != null) {
            let days = Math.floor(parsedDate.getTime() / 86400 * 1000);
            $tdElement.data('v', days);
            $tdElement.data("t", "n");
            $tdElement.data("z", "yyyy-mm-dd");
        }
    });
    console.log($table.get(0))
    var wb = XLSX.utils.table_to_book($table.get(0), {sheet: "sheet1"});
    XLSX.writeFile(wb, fn + '.xlsx');
}


$(document).on('click', ".manage-pcm", function () {
    managePCM();
});

function managePCM() {
    doGetAjaxRequestHandler(`${context}/brand-pcm`, function (response) {
        $('#main-content').html(response);
    });
}


$(document).on('click', ".digify-retailer-login", function () {

    doGetAjaxRequestHandler(context + "/digify/register", function (response) {


        $('#main-content').html(response);

    });
    //$('#main-content').html(`<iframe class="wrapper" src="${context}/digify/register" style="width:100%;height:100vh"> </iframe>`);
    //$('#main-content').html(`<a class="wrapper" href="${context}/digify/register" target="_blank" style="width:100%;height:100vh"> </a>`);

});

$(document).on('click', '.warehousewise_stock', function () {
    doGetAjaxRequestHandler(`${context}/warehouse/stock-qty`, function (response) {
        $('#main-content').html(response);
    });
});

function loadMainContent(htmlContent) {
    $('#main-content').html(htmlContent);
}


function jsonStartDate(dateInputString) {
    if (dateInputString === '') return null;
    return moment(dateInputString, "yyyy-MM-DD").format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
}

function jsonEndDate(dateInputString) {
    if (dateInputString === '') return null;
    return moment(dateInputString, "yyyy-MM-DD").endOf('day').format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS);
}

function showToast(message) {
    Toastify({
        text: message,
        duration: 3000, // 3 seconds
        gravity: "top", // or "bottom"
        position: "right", // "left", "center", "right"
        backgroundColor: "green", // specify the background color
        offset: {
            x: 20, // Horizontal margin from the right
            y: 70 // Vertical margin from the top
        }
    }).showToast();
}

function loadHtml(html) {
    $("#main-content").html(html);
}


function objectifyForm(formArray) {
    //serialize data function
    console.log('Row form  data ', formArray);
    var returnArray = {};
    for (var i = 0; i < formArray.length; i++) {
        var name = formArray[i]['name'];
        var value = formArray[i]['value'];
        if (typeof returnArray[name] === 'undefined') {
            returnArray[name] = value.trim();
        } else if (typeof returnArray[name] === 'object') {
            returnArray[name].push(value);
        } else {
            var a = returnArray[name];
            returnArray[name] = [returnArray[name]];
            a.push(value);
            returnArray[name] = a;
        }
    }
    return returnArray;
}

function isValidEmail(email) {
    const EMAIL_REGEX = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.(com|in|net)$/;
    return EMAIL_REGEX.test(email);
}

function serializeFormToJson(formId) {
    let formArray = $(formId).serializeArray();
    let formData = {};
    $.map(formArray, function(field) {
        formData[field.name] = field.value;
    });
    return formData;
}

function getCookie(name) {
    const cookies = document.cookie.split('; ');
    for (let cookie of cookies) {
        const [key, value] = cookie.split('=');
        if (key === name) return decodeURIComponent(value);
    }
    return null;
}