Subversion Repositories SmartDukaan

Rev

Rev 36532 | Blame | Compare with Previous | Last modification | View Log | RSS feed

var authorisedWarehouses = [];
const SELF_PICKUP = "4";
const RUNNER = "5";

function checkSamePincodeAndGiveDistanceField(transactionId, warehouseId) {
    doGetAjaxRequestHandler(`${context}/om/checkAddressPin/${transactionId}/${warehouseId}`, function (response) {
        if (response.isSamePincode) {
            $("#samePinCheck").val(true);
            $('div.mk_distanceField').show();
            if (response.distance != 0) {
                $('div.mk_distanceField').val(response.distance);
            } else {
                $('div.mk_distanceField').val("");
            }
        } else {
            $("#samePinCheck").val(false);
            $('div.mk_distanceField').hide();

        }
    });
}

$(function () {
    $(document).on('click', ".warehouse-management", function () {
        getAuthorisedWarehouseList(function (warehouseId) {
            loadAllTransaction(warehouseId, "main-content");
        });

    });

    $(document).on('change', "#selectedWarehouse", function () {
        var warehouseId = $(this).val();
        loadAllTransaction(warehouseId, "main-content");
    });

    $(document).on('click', ".order_by_transaction", function () {
        var transactionId = $(this).data("transaction");
        var warehouseId = $("#selectedWarehouse").val();

        // add and remive active class
        $(this).addClass("active-tr");

        $(".order_by_transaction").not(this).removeClass("active-tr");

        loadTransactionDetail(transactionId, warehouseId, "transaction-detail-container");
    });

    $(document).on('click', ".change-warehouse-save-mk", function () {
        var selectedFromBillingWarehouse = $("#selectedFromBillingWarehouse").val();
        var orderId = $("#selectedFromBillingWarehouse").data('orderid');
        doPostAjaxRequestHandler(context + `/om/changeBillingWarehouse/?billingFromWarehouseId=${selectedFromBillingWarehouse}&orderId=${orderId}`, function (response) {
            if (response.response === true) {
                var warehouseId = $("#selectedWarehouse").val();
                loadAllTransaction(warehouseId, "main-content");
            } else {
                alert('Something went wrong');
            }

        });
    });

    $(document).on('click', ".mk_moveToBill", function () {
        var warehouseId = $(this).data("warehouseid");
        var transactionId = $(this).data("transactionid");
        var orderId = $(this).data("orderid");
        doGetAjaxRequestHandler(`${context}/om/moveToBill?warehouseId=${warehouseId}&orderId=${orderId}`, function (response) {
            var result = response.response || response;
            if (result.moved === true) {
                alert("Order moved successfully");
                loadTransactionDetail(transactionId, warehouseId, "transaction-detail-container");
                return;
            }
            if (result.needsInput) {
                var msg = "Order Qty: " + result.orderQty +
                    "\nNet Available (free stock): " + result.netAvailability +
                    "\nMax Available (includes reserved): " + result.maxAvailability +
                    "\n\nWarehouses:";
                for (var i = 0; i < result.warehouses.length; i++) {
                    var wh = result.warehouses[i];
                    msg += "\n  WH " + wh.warehouseId + " - Available: " + wh.availability + ", Reserved: " + wh.reserved + ", Net: " + wh.netAvailability;
                }
                msg += "\n\nEnter qty to move and warehouse ID (e.g. 5,3 for qty=5 to warehouse 3):";
                var input = prompt(msg);
                if (input) {
                    var parts = input.split(",");
                    var qty = parseInt(parts[0].trim());
                    var fWhId = parseInt(parts[1].trim());
                    if (isNaN(qty) || isNaN(fWhId)) {
                        alert("Invalid input");
                        return;
                    }
                    doGetAjaxRequestHandler(`${context}/om/moveToBillWithQty?orderId=${orderId}&qty=${qty}&fulfilmentWarehouseId=${fWhId}`, function () {
                        alert("Order moved successfully");
                        loadTransactionDetail(transactionId, warehouseId, "transaction-detail-container");
                    });
                }
            } else {
                alert(result.message || "Could not move order");
            }
        });
    });
    $(document).on('click', ".changeWarehouse-mk", function () {
        var itemId = $(this).data("itemid");
        var warehouseId = $(this).data("warehouseid");
        var orderId = $(this).data("orderid");
        console.log('warehouse', warehouseId);
        console.log('itemId', itemId);
        doGetAjaxRequestHandler(`${context}/om/formWarehouseByItemId/?warehouseId=${warehouseId}&itemId=${itemId}&orderId=${orderId}`, function (response) {
            console.log(response);
            if (response && response.response && Array.isArray(response.response)) {
                console.log("response2222 warehouse", response.response);
                if (response.response.length > 0) {
                    var selectOptions = '';
                    response.response.forEach(function (warehouse) {
                        selectOptions += `<option value="${warehouse.warehouseFrom}">${warehouse.warehouseFromName}</option>`;
                    });
                    // Populate the modal with the select dropdown
                    $('#changeWarehouseModal .modal-body .brand-mapping-warehouse-mk').html(`<select id="selectedFromBillingWarehouse" data-orderid="${orderId}" class="form-control">${selectOptions}</select>`);
                    $('.all-warehouse-map').attr("data-orderid", orderId); //setter
                    $('.change-warehouse-save-mk').css("display", "block");
                } else {
                    $('#changeWarehouseModal .modal-body').html(`No other warehouse found for change`);
                    $('.change-warehouse-save-mk').css("display", "none");
                }
            } else {
                console.log('error: invalid response structure');
            }
        });
    });


    $(document).on('click', ".order_accepted", function () {
        var transactionId = $("#selectedTransactionId").text();
        var providerId = $("select.mk_provider>:selected").data("providerid");
        let distance = "";
        let isSamePinCheck = $("#samePinCheck").val();
        console.log("distance - ", distance);
        console.log("isSamePinCheck - ", isSamePinCheck);
        if (isNaN(providerId)) {
            alert("Choose Provider");
            return;
        }
        let vehicleNumber = null;
        if (providerId == SELF_PICKUP) {
            vehicleNumber = $('.mk_vehicleNumber').val();
            if (vehicleNumber == "") {
                alert("Vehicle Number is required");
                return;
            }
        } else if (providerId == RUNNER) {
            if ($('.mk_rider>select').prop('selectedIndex') == 0) {
                alert("Choose Rider");
                return;
            }
            if (isSamePinCheck == "true") {
                distance = $(".mk_distanceValue").val();
                if (!distance) {
                    alert("Please Enter Approx Distance");
                    return;
                }
            }
            vehicleNumber = $('.mk_rider select').val();
        }
        console.log("distance after Check- ", distance);
        var warehouseId = $("#selectedWarehouseId").val();
        var orderBillingModels = []; // Array to store OrderBillingModel objects
        $("#wareHouseTransactionTable > tbody > tr").each(function (rowIndex) {
            if ($(this).hasClass('main-tr')) {
                var orderId = parseInt($(this).find(".orderId").text().trim());
                var fillQuantityInput = $(this).find(".filledQty");
                var fillQuantity = fillQuantityInput.length ? parseInt(fillQuantityInput.val().trim()) : 0; // Get fill quantity from input field if it exists
                var serialNumbers = [];

                var imeiInputAvailability = $(this).find(".imeis-to-grn");
                if (imeiInputAvailability.length) {
                    var imeiInput = ($(this).find(".imeis-to-grn")).tagsinput('items'); // Get selected serial numbers
                    if (imeiInput.length) {
                        imeiInput.forEach((imei) => {
                            serialNumbers.push(imei);
                        });
                    }
                }

                // Determine the quantity to bill based on serial numbers and fill quantity
                var quantityToBill;
                if (serialNumbers.length) {
                    quantityToBill = serialNumbers.length;
                } else {
                    quantityToBill = fillQuantity;
                }

                // Create OrderBillingModel object
                var orderBillingModel = {
                    orderId: orderId,
                    serialNumbersToBill: serialNumbers,
                    quantityToBill: quantityToBill,
                    logisticsProviderId: providerId,
                    vehicleNumber: vehicleNumber,
                    distance: distance
                };

                // Add OrderBillingModel object to the array
                orderBillingModels.push(orderBillingModel);
            }
        });

        // Convert orderBillingModels array to JSON string
        var requestBody = JSON.stringify(orderBillingModels);

        // Perform further actions with the requestBody, such as sending it in an AJAX request
        console.log('Request Body:', requestBody);

        doPostAjaxRequestWithJsonHandler(`${context}/om/addBillingDetailsForGrouppedOrders/?warehouseId=${warehouseId}&transactionId=${transactionId}`, requestBody, function (invoiceNumber) {
            if (invoiceNumber) {
                alert("bill generated successfully");
                setTimeout(function () {
                    window.open(`${context}/om/downloadInvoice/${invoiceNumber}`, "_blank");
                }, 3000,);
                loadAllTransaction(warehouseId, "main-content");
            } else {
                alert("something went wrong");
            }
        });

    });


});


function loadAllTransaction(warehouseId, domId) {
    doGetAjaxRequestHandler(context + "/om/transactions/?warehouseId=" + warehouseId + "&orderStatus=SUBMITTED_FOR_PROCESSING", function (response) {
        $('#' + domId).html(response);
        var transactionId = $("#firstTxnId").val();
        $("#selectedWarehouse").val(warehouseId);
        console.log("Transaction ID:", transactionId);

        var selectOptions = '';
        authorisedWarehouses.forEach(function (warehouse) {
            var selected = (warehouse.id == warehouseId) ? 'selected' : '';

            selectOptions += `<option value="${warehouse.id}" ${selected}>${warehouse.name}</option>`;
        });
        $('#authWarehousesList').html(`<select class="form-control" id="selectedWarehouse">${selectOptions}</select>`);

        loadTransactionDetail(transactionId, warehouseId, "transaction-detail-container");
    });
}

function loadTransactionDetail(transactionId, warehouseId, detailContainer) {
    var url = context + "/om/orderByTransaction/?transactionId=" + transactionId + "&warehouseId=" + warehouseId;
    doGetAjaxRequestHandler(url, function (response) {
        $('#' + detailContainer).html(response);
        $("#selectedTransactionId").text(transactionId);
        $("#selectedWarehouseId").val(warehouseId);

    });
}


function getAuthorisedWarehouseList(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) {
            console.log("responseeee warehouse", response);
            authorisedWarehouses = JSON.parse(response);

            inputOptions = [];
            authorisedWarehouses.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);
    }
}