Subversion Repositories SmartDukaan

Rev

Rev 36789 | Rev 36868 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

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

    $(document).on('click', ".team-commitment", function () {
        loadTeamCommitment("main-content");
    });


    $(document).on('click', ".partner-health", function () {
        loadPartnerHealth("main-content");
    });

    $(document).on('click', ".lead-detail", function () {
        loadLeadDetail("main-content");
    });


    $(document).on('click', ".submitCommitment",
        function () {
            var startDateTime = getDatesFromPicker('input[name="commitmentDate"]').startDate;
            doGetAjaxRequestHandler(context + "/getTeamCommitment?date="
                + startDateTime, function (response) {
                $('.teamcommitmentcontainer').html(response);

            });
        });


    $(document).on('click', ".submitDateWiseLead", function () {

        var startDate = $("#startDate").val();
        var endDate = $("#endDate").val();
        var status = $("#statusFilter").val();
        var color = $("#colorFilter").val();

        if (color == null) {
            color = "";
        }

        if (startDate && endDate) {
            var start = new Date(startDate);
            var end = new Date(endDate);
            if (end < start) {
                alert("End date must be after start date");
                return;
            }
        }

        doGetAjaxRequestHandler(context + "/getOpenLead?leadStatus=" + status + "&color=" + color + "&startDate=" + startDate + "&endDate=" + endDate, function (response) {
            $('#' + 'main-content').html(response);
        });


    })
    ;$(document).on('click', ".downloadDateWiseLead", function () {

        var startDate = $("#startDate").val();
        var endDate = $("#endDate").val();
        var status = $("#statusFilter").val();
        var color = $("#colorFilter").val();

        if (color == null) {
            color = "";
        }

        if (startDate && endDate) {
            var start = new Date(startDate);
            var end = new Date(endDate);
            if (end < start) {
                alert("End date must be after start date");
                return;
            }
        }

        let endPoint = `${context}/downloadDateWiseLead?leadStatus=${status}&color=${color}&startDate=${startDate}&endDate=${endDate}`;
        window.location.href = endPoint;

    });


    $(document).on('click', ".visit-request-plan", function () {

        doGetAjaxRequestHandler(context + "/visitPlan", function (response) {
            $('#' + 'main-content').html(response);
        });

    });

    $(document).on('click', ".visitPlan", function () {

        let dateWisePlan = $("#dateVisitSearch").val();

        doGetAjaxRequestHandler(context + "/visit/getVisitPlan?date=" + dateWisePlan, function (response) {
            $('#' + 'main-content').html(response);
        });

    });

    $(document).on('click', ".lead-close", function () {
        loadClosedLead("main-content");
    });

    $(document).on('click', "#lead-close-paginated .next",
        function () {

            var searchText = $("#authUser").val();
            // var searchTxt=$("#scheme-search-text").val();
            console.log(searchText);
            if (typeof (searchText) == "undefined" || !searchText) {
                searchText = "";
            }

            if ((searchText)) {
                var params = {};
                params['searchTerm'] = searchText;
                loadPaginatedNextItems('/searchLeadPaginated', params,
                    'lead-close-paginated', 'close-lead-table',
                    'lead-close-container');
            } else {

                loadPaginatedNextItems('/getPaginatedClosedLeads', null,
                    'lead-close-paginated', 'close-lead-table',
                    'lead-close-container');
            }
            $(this).blur();
        });

    $(document).on('click', "#lead-close-paginated .previous",
        function () {
            var searchText = $("#authUser").val();
            // var searchTxt=$("#scheme-search-text").val();
            console.log(searchText);
            if (typeof (searchText) == "undefined" || !searchText) {
                searchText = "";
            }

            if ((searchText)) {
                var params = {};
                params['searchTerm'] = searchText;
                loadPaginatedPreviousItems('/searchLeadPaginated', params,
                    'lead-close-paginated', 'close-lead-table',
                    'lead-close-container');
            } else {
                loadPaginatedPreviousItems('/getPaginatedClosedLeads',
                    null, 'lead-close-paginated', 'close-lead-table',
                    'lead-close-container');
            }
            $(this).blur();
        });

    $(document).on('click', "#close-lead-search-button", function () {
        var searchText = $("#authUser").val();
        if (typeof (searchText) == "undefined" || !searchText) {
            searchText = "";
        }
        loadLeadSearchInfo(searchText);
    });

    $(document).on("keyup", "#authUser", function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode == 13) {
            $("#close-lead-search-button").click();
        }
    });
    $(document).on('click', ".view",
        function () {
            var id = $(this).data('requestid');
            console.log(id);
            doGetAjaxRequestHandler(context + "/getLeadActivity?leadId="
                + id, function (response) {

                console.log(response)

                $('#fetchLeadActivityData .modal-content').html(response);

            });
        });

    $(document).on('click', ".newLead", function () {
        $('#newEntryLeadModal').modal('show');
        $("#scheduleTime").hide();
    });

    $(document).on('click', ".show-lead", function () {
        var status = $("#statusFilter").val();
        doGetAjaxRequestHandler(context + "/getOpenLead?leadStatus=" + status, function (response) {
            $('#' + 'main-content').html(response);
        });
    });


    $(document).on('click', ".show-colowise-lead", function () {
        var status = $("#statusFilter").val();
        var color = $("#colorFilter").val();
        doGetAjaxRequestHandler(context + "/getOpenLead?leadStatus=" + status + "&color=" + color, function (response) {
            $('#' + 'main-content').html(response);
        });
    });

    $(document).on('click', "#uploadIvoryLead", function () {

        window.location.href = context + "/downloadIvoryLead";
    });

    $(document).on('click', ".submitLeadGenerate", function () {

        console.log("hello");
        if (confirm('Confirm upload ?')) {
            var fileSelector = $(this)[0];
            if (fileSelector != undefined) {
                var url = `${context}/csvFileAndSetLead`;
                console.log(url);
                var file = $(".fileLeadGenerate")[0].files[0];
                let fileInput = $(this);
                console.log("file" + file);
                console.log("fileInput" + fileInput);
                doAjaxUploadRequestHandler(
                    url,
                    'POST',
                    file, function (response) {

                        console.log("reponse" + response);

                        if (response == true) {
                            alert("successfully uploaded");


                        }
                    });

            }
        } else {
            // Do nothing!
        }
    });


    $(document).on('click', ".lead-request",
        function () {

            var firstName = $('input[name="firstName"]').val();
            var lastName = $('input[name="lastName"]').val();
            var mobile = $('input[name="mobile"]').val();
            var address = $('input[name="address"]').val();
            var status = $("#status").val();
            var city = $('input[name="city"]').val();
            var state = $("#state").val();
            var remark = $("#createRemark").val();
            var assignTo = $("#createAssignTo").val();
            var source = $("#leadSource").val();
            var communicationType = $("#communicationTye").val();

            var conversionprobability = $("#conversionprobabilit").val();


            var outletName = $('input[name="leadoutletName"]').val();
            var counterSize = $('input[name="leadcounterSize"]').val();
            var table = document.getElementById('brandtable');
            var brandValueJson = [];
            var leadBrands;

            console.log(conversionprobability)


            if (firstName === "" && lastName === "" && mobile === ""
                && address === "" && status === "" && city === ""
                && state === "" && remark === "" && source === "") {
                alert("Field can't be empty");
                return;
            }


            if (firstName === "") {
                alert("First Name is required");
                return;
            }
            if (lastName === "") {
                alert("Last Name is required");
                return;
            }
            if (mobile === "") {
                alert("Mobile is required");
                return;
            }
            if (status === "") {
                alert("Status is required");
                return;
            }
            if (address === "") {
                alert("address is required");
                return;
            }
            if (city === "") {
                alert("city is required");
                return;
            }

            if (state === "") {
                alert("state is required");
                return;
            }
            if (source === "") {
                alert("Source is required")
                return;
            }

            if (remark === "") {
                alert("Remark is required");
                return;
            }

            if (conversionprobability === "") {
                alert("Conversion Probability is required");
                return;
            }
            if (status == "followUp" || status == "pending" || status == "finalized") {
                if (outletName === "") {
                    alert("Outlet Name is required");
                    return;
                }

                if (counterSize === "") {
                    alert("Counter Size is required");
                    return;
                }

                if (localStorage.getItem("frontph") == "undefined" && localStorage.getItem("frontph") == null) {
                    alert("Front Document is required");
                    return;
                }

                if (localStorage.getItem("internalMarketh") == "undefined" || localStorage.getItem("internalMarketh") == null) {
                    alert("Front With Market Document is required");
                    return;
                }

                if (localStorage.getItem("leftShoth") == "undefined" || localStorage.getItem("leftShoth") == null) {
                    alert("Internal Left Shot Document is required");
                    return;
                }

                if (localStorage.getItem("leftWallh") == "undefined" || localStorage.getItem("leftWallh") == null) {
                    alert("Internal Left Wall Document is required");
                    return;
                }


                if (localStorage.getItem("rightWallh") == "undefined" || localStorage.getItem("rightWallh") == null) {
                    alert("Internal Right Wall Document is required");
                    return;
                }


                for (i = 1; i < table.rows.length; i++) {

                    var objCells = table.rows[i].cells;

                    leadBrands = {
                        brand: objCells[0].innerText,
                        value: objCells[1].getElementsByTagName('input')[0].value
                    }
                    brandValueJson.push(leadBrands);
                }


            }


            var leaddetailData = {}
            leaddetailData['firstName'] = firstName;
            leaddetailData['lastName'] = lastName
            leaddetailData['mobile'] = mobile
            leaddetailData['address'] = address
            leaddetailData['city'] = city
            leaddetailData['state'] = state
            leaddetailData['status'] = status
            leaddetailData['remark'] = remark
            leaddetailData['assignTo'] = assignTo
            leaddetailData['source'] = source
            leaddetailData['colorCheck'] = conversionprobability


            if (status == "followUp") {
                leaddetailData['schelduleTimestamp'] = getDatesFromPicker('#scheduleTime').startDate;

                leaddetailData['communicationType'] = communicationType
            }


            leaddetailData['outletName'] = outletName;

            leaddetailData['counterSize'] = counterSize;


            leaddetailData['leadBrands'] = brandValueJson;

            console.log(localStorage.getItem("frontp"));


            leaddetailData['frontp'] = localStorage
                .getItem("frontph");


            leaddetailData['frontWithMarket'] = localStorage
                .getItem("internalMarketh");


            leaddetailData['internalLongShot'] = localStorage
                .getItem("leftShoth");


            leaddetailData['internalLeftWall'] = localStorage
                .getItem("leftWallh");


            leaddetailData['internalRightWall'] = localStorage
                .getItem("rightWallh");

            console.log(leaddetailData);

            if (confirm("Are you sure you want to add lead!") == true) {
                doPostAjaxRequestWithJsonHandler(context + "/createLead",
                    JSON.stringify(leaddetailData), function (response) {
                        if (response == 'true') {
                            alert("successfully Add");
                            $('#newEntryLeadModal').modal('hide');
                            $('.modal-backdrop').remove();
                            loadLead("main-content");
                        } else {
                            alert(response);
                        }
                    });

                return false;
            }
        });
    window.leadId = null;
    var row = null;
    $(document).on('click', ".editLead", function () {
        $('#editLeadData').modal('show');

        $("#remark").val("");
        $("#assignTo").val("");
        $("#editStatus").val("");
        $("#reason").val("");
        $("#editCity").val("");
        $("#editState").val("");
        $("#editSource").val("");
        $("#editScheduleTime").hide();


        localStorage.removeItem("frontph");
        localStorage.removeItem("leftShoth");
        localStorage.removeItem("rightWallh");
        localStorage.removeItem("leftWallh");
        localStorage.removeItem("internalMarketh");

        row = $(this).closest("tr");
        leadId = $(this).data('leadid');

        doAjaxRequestHandler(
            context + "/getLeadDetailByLeadId?leadId=" + leadId,
            "GET",
            function (response) {

                var data = response.response;
                if (!data) return;
                console.log(data);
                $("#editCity").val(data.city);
                $("#editState").val(data.state);
                $("input[name='outletName']").val(data.outletName);
                $("input[name='counterSize']").val(data.counterSize);
            }
        );
    });


    $(document).on('click', ".lead-edit-request",
        function () {

            // Gate the assign/status submit on approved geo. Modal stays open so the
            // user can still work the other sub-forms (lead detail, etc.).
            var clickedBtn = $(this);
            // notInterested is a close-out — no geo / no beat / no assignee
            // needed. Skip the geo gate and submit straight through with just
            // the activity (status + reason + remark).
            var currentStatus = $('#editStatus').val();
            if (currentStatus === 'notInterested') {
                submitLeadEdit();
                return;
            }
            // Non-sales assignees (BGC / other internal hand-offs) don't need
            // geo or a beat-day — the lead just routes to their queue. Skip the
            // geo gate and submit straight through, same as the legacy flow.
            var assigneeId = parseInt($('#assignTo').val(), 10);
            var isSalesAssignee = !isNaN(assigneeId)
                && typeof salesUserIds !== 'undefined'
                && salesUserIds.indexOf(assigneeId) !== -1;
            if (!isSalesAssignee) {
                submitLeadEdit();
                return;
            }
            if (clickedBtn.data('geoChecking')) return;
            clickedBtn.data('geoChecking', true);
            doAjaxRequestHandler(
                context + "/lead-geo/check/" + leadId,
                "GET",
                function (response) {
                    clickedBtn.removeData('geoChecking');
                    var hasGeo = response && response.response && response.response.hasApprovedGeo;
                    if (!hasGeo) {
                        alert('Live geo-location for this lead has not been approved yet. Please approve the geo-location before assigning / updating status.');
                        return;
                    }
                    submitLeadEdit();
                }
            );
        });

    function submitLeadEdit() {

            console.log(row);
            var remark = $('input[name="remark"]').val();
            var assignTo = $("#assignTo").val();
            var editStatus = $("#editStatus").val();
            var city = $('input[name="editCity"]').val();
            var state = $("#editState").val();
            var reason = $("#reason").val();

            var startDate = $("#startDate").val();
            var endDate = $("#endDate").val();
            var leadStatus = $("#statusFilter").val();
            var color = $("#colorFilter").val();
            var communicationType = $("#communicationType").val();

            var conversionprobability = $("#conversionprobability").val();
            var editSource = $("#editSource").val();

            console.log(conversionprobability)


            console.log(startDate)
            console.log(leadStatus)

            console.log(color)
            console.log(reason)

            if (remark === "" && assignTo === "" && editStatus === "") {
                alert("All fields is required");
                return;
            }

        // For notInterested (close-out) the lead doesn't need an assignee
        // — it's just a status + reason + remark write. Only enforce
        // assignTo for the other statuses where scheduling matters.
        if (assignTo === "" && editStatus !== "notInterested") {
                alert("assignTo is required");
                return;
            }

            if (remark === "") {
                alert("Remark is required");
                return;
            }


            if (editStatus === "") {
                alert("status is required");
                return;
            }

            if (editStatus === "notInterested") {
                if (reason == null || reason === "") {
                    alert("Reason  is required");
                    return;
                }
            }
            var leadActivityData = {}
            leadActivityData['id'] = leadId;
            leadActivityData['remark'] = remark;
            leadActivityData['assignTo'] = assignTo
            leadActivityData['status'] = editStatus
            leadActivityData['reason'] = reason
            leadActivityData['colorCheck'] = (conversionprobability === "true" || conversionprobability === true)
            if (city && city.trim() !== "") {
                leadActivityData.city = city;
            }

            if (state && state.trim() !== "") {
                leadActivityData.state = state;
            }

            if (editSource && editSource.trim() !== "") {
                leadActivityData.source = editSource;
            }


            if (editStatus == "followUp") {
                leadActivityData['communicationType'] = communicationType
                var assigneeIdForBeat = parseInt(assignTo, 10);
                var isSalesAssigneeForBeat = !isNaN(assigneeIdForBeat)
                    && typeof salesUserIds !== 'undefined'
                    && salesUserIds.indexOf(assigneeIdForBeat) !== -1;
                var beatVal = $('#beatDate').val();
                // Beat-day gate only applies to sales assignees. Non-sales
                // (BGC / other) hand-offs are just routed to the user's queue
                // without a beat attachment — same as the legacy flow.
                if (isSalesAssigneeForBeat) {
                    if (!beatVal) {
                        var hasBadges = $('#beatBadges .beat-badge').length > 0;
                        if (!hasBadges) {
                            alert('No upcoming beat is available for this assignee. Cannot schedule the lead until they have a beat.');
                        } else {
                            alert('Please select a beat date for the assignee before submitting.');
                        }
                        return;
                    }
                    var beatDate = beatVal.split('|')[0];
                    leadActivityData['scheldule'] = beatDate + 'T12:00:00';
                    leadActivityData['beatSelection'] = beatVal;
                }
            }

            console.log(leadActivityData);
            if (confirm("Are you sure you want to add lead!") == true) {
                doPostAjaxRequestWithJsonHandler(context + "/editLead", JSON.stringify(leadActivityData), function (response) {
                    console.log(response);
                    $('#editLeadData').modal('hide');
                    $('.modal-backdrop').remove();
                    row.html(response);
                });
            }

    }


    $(document).on('click', ".show-partner-health",
        function () {

            var email = $("#authUserFilter").val();

            console.log(email)
            doGetAjaxRequestHandler(context + "/partnerHealth?email="
                + email, function (response) {
                console.log(response)
                $('#' + 'main-content').html(response);

            });
        });


    $(document).on('click', ".lead-detail-entry",
        function () {

            console.log("hello");
            var outletName = $('input[name="outletName"]').val();
            var counterSize = $('input[name="counterSize"]').val();
            var table = document.getElementById('editbrandtable');
            var brandValueJson = [];
            var leadBrands;

            if (outletName === "") {
                alert("Outlet Name is required");
                return;
            }

            if (counterSize === "") {
                alert("Counter Size is required");
                return;
            }

            if (localStorage.getItem("frontph") == "undefined" && localStorage.getItem("frontph") == null) {
                alert("Front Document is required");
                return;
            }

            if (localStorage.getItem("internalMarketh") == "undefined" || localStorage.getItem("internalMarketh") == null) {
                alert("Front With Market Document is required");
                return;
            }

            if (localStorage.getItem("leftShoth") == "undefined" || localStorage.getItem("leftShoth") == null) {
                alert("Internal Left Shot Document is required");
                return;
            }

            if (localStorage.getItem("leftWallh") == "undefined" || localStorage.getItem("leftWallh") == null) {
                alert("Internal Left Wall Document is required");
                return;
            }


            if (localStorage.getItem("rightWallh") == "undefined" || localStorage.getItem("rightWallh") == null) {
                alert("Internal Right Wall Document is required");
                return;
            }


            for (i = 1; i < table.rows.length; i++) {

                var objCells = table.rows[i].cells;

                leadBrands = {
                    brand: objCells[0].innerText,
                    value: objCells[1].getElementsByTagName('input')[0].value
                }
                brandValueJson.push(leadBrands);
            }


            var leadDetailObject = {};

            leadDetailObject['leadId'] = leadId;


            leadDetailObject['outletName'] = outletName;

            leadDetailObject['counterSize'] = counterSize;

            leadDetailObject['leadBrands'] = brandValueJson;


            console.log(localStorage.getItem("frontp"));


            leadDetailObject['frontp'] = localStorage
                .getItem("frontph");


            leadDetailObject['frontWithMarket'] = localStorage
                .getItem("internalMarketh");


            leadDetailObject['internalLongShot'] = localStorage
                .getItem("leftShoth");


            leadDetailObject['internalLeftWall'] = localStorage
                .getItem("leftWallh");


            leadDetailObject['internalRightWall'] = localStorage
                .getItem("rightWallh");

            console.log(leadDetailObject);

            if (confirm("Are you sure you want to add lead detail!") == true) {
                doPostAjaxRequestWithJsonHandler(context + "/leadDetail", JSON.stringify(leadDetailObject), function (response) {
                    console.log(response);
                    if (response == 'true') {
                        alert("Submit Successfully");
                    }

                });
            }

        });


    $(document).on('change', '.frontp',
        function () {

            if (confirm('Document has been selected, Do you want to upload ?')) {

                var documentId = uploadImage(this, "frontph");


            } else {

            }
        });

    $(document).on('change', '.internalMarket',
        function () {

            if (confirm('Document has been selected, Do you want to upload ?')) {

                var documentId = uploadImage(this, "internalMarketh");

            } else {

            }
        });

    $(document).on('change', '.leftShot',

        function () {
            if (confirm('Document has been selected, Do you want to upload ?')) {
                var documentId = uploadImage(this, "leftShoth");
            } else {

            }
        });

    $(document).on('change', '.leftWall',
        function () {
            if (confirm('Document has been selected, Do you want to upload ?')) {
                var documentId = uploadImage(this, "leftWallh");
            } else {

            }
        });

    $(document).on('change', '.rightWall',
        function () {
            if (confirm('Document has been selected, Do you want to upload ?')) {
                var documentId = uploadImage(this, "rightWallh");
            } else {
            }
        });


});

function uploadImage(fileSelector, attrName) {
    var documentId;
    if (fileSelector != undefined
        && fileSelector.files[0] != undefined) {
        var url = context
            + '/document-upload';

        console.log(url);
        var file = fileSelector.files[0];

        console.log(file)
        doAjaxUploadRequestHandler(
            url,
            'POST',
            file,
            function (response) {
                console.log(response)
                documentId = response.response.document_id;
                console
                    .log("documentId : "
                        + documentId);


                localStorage
                    .setItem(
                        attrName,
                        documentId);

            });
        return documentId;
    }

}


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

function loadClosedLead(domId, searchTerm) {
    doGetAjaxRequestHandler(context + "/getClosedLead", function (response) {
        $('#' + domId).html(response);
    })
}

function statusAction() {
    var val = $('#status').val();
    if (val == "followUp") {
        $("#scheduleTime").show();
    } else {
        $("#scheduleTime").hide();
    }

}


function editStatusAction() {
    var val = $('#editStatus').val();
    if (val == "followUp") {
        // Show communication type and schedule date
        $("#communicationTypeSection").show();
        $("#editScheduleTime").show();
        $("#beatDateSelection").hide();

        // Reset communication type only; preserve the assignee the user picked.
        $('#communicationType').val('');
        $('#assignTo option').show();

        // Check if lead has approved geolocation to decide VISIT option
        doAjaxRequestHandler(context + "/lead-geo/check/" + leadId, "GET", function (response) {
            var hasGeo = response.response.hasApprovedGeo;
            var commDropdown = $('#communicationType');
            commDropdown.empty();
            commDropdown.append('<option value="" disabled selected>Communication Type</option>');
            commDropdown.append('<option value="TELEPHONIC">TELEPHONIC</option>');
            if (hasGeo) {
                commDropdown.append('<option value="VISIT">VISIT</option>');
            }
        });
    } else {
        $("#communicationTypeSection").hide();
        $("#editScheduleTime").hide();
        $("#beatDateSelection").hide();
        $('#assignTo option').show();
    }

}

function loadLeadSearchInfo(search_text) {
    loadSearchLead("main-content", search_text);
}

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

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

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

function loadSearchLead(domId, search_text) {
    doGetAjaxRequestHandler(context + "/searchLeads?searchTerm=" + search_text,
        function (response) {
            $('#' + domId).html(response);
        });
}

$(document).on('click', ".arr-button-mk",
    function () {
        var startDate = $('.arr-start_date').val();
        doGetAjaxRequestHandler(context + "/rbmTodayArr?startDate=" + startDate, function (response) {
            $('#main-content').html(response);

        });
    });

$(document).on('click', ".rbm-today-arr",
    function () {
        doGetAjaxRequestHandler(context + "/rbmTodayArr", function (response) {
            $('#main-content').html(response);

        });
    });
$(document).on('click', '.reassign', function () {
    $('#bulkReassignFile').val(null);
    $('#bulkReassignFile').click();
});

$(document).on('change', '#bulkReassignFile', function () {

    if (!confirm("Confirm bulk reassign upload?")) {
        return;
    }

    var file = this.files[0];
    if (!file) {
        alert("No file selected");
        return;
    }

    doAjaxUploadRequestHandler(
        context + "/upload-assign-id",
        'POST',
        file,
        function (response) {
            alert("Bulk reassignment completed");
            loadLead("main-content");
        }
    );
});

// ==================== GEO LOCATION HANDLERS ====================

// Communication type change: filter assignTo based on type
$(document).on('change', '#communicationType', function () {
    var val = $(this).val();
    var assignDropdown = $('#assignTo');

    // Reset beat + restore manual date input
    $('#beatDate').val('');
    $('#beatBadges').empty();
    $("#beatDateSelection").hide();
    $("#editScheduleTime").show();

    if (val == 'VISIT') {
        // Filter assignTo to sales users only (no BGC)
        if (typeof salesUserIds !== 'undefined') {
            assignDropdown.find('option').each(function () {
                var optVal = parseInt($(this).val());
                if (optVal && salesUserIds.indexOf(optVal) === -1) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
        }
    } else {
        // TELEPHONIC — show all users
        assignDropdown.find('option').show();
    }
    // Both VISIT and TELEPHONIC offer beat-day slots when an assignee is set
    // (TELEPHONIC just uses the beat date as the call slot; backend won't
    // attach a LeadRoute for it). Non-sales assignees simply get an empty list.
    if (val && assignDropdown.val()) {
        fetchBeatDates();
    }
});

// Fetch beats when assignTo changes (works for both VISIT and TELEPHONIC)
$(document).on('change', '#assignTo', function () {
    var commType = $('#communicationType').val();
    var salesAuthId = $('#assignTo').val();
    if (commType && salesAuthId && leadId) {
        fetchBeatDates();
    } else if (!commType) {
        $("#beatDateSelection").hide();
    }
});

function fetchBeatDates() {
    var salesAuthId = $('#assignTo').val();
    if (!salesAuthId || !leadId) return;

    // Beat slots only make sense for sales assignees. BGC / other internal
    // hand-offs skip the entire beat panel (and the visit-request CTA that
    // sits inside it). Mirrors the server-side carve-out in /editLead.
    var assigneeIntId = parseInt(salesAuthId, 10);
    var isSalesAssigneeFetch = !isNaN(assigneeIntId)
        && typeof salesUserIds !== 'undefined'
        && salesUserIds.indexOf(assigneeIntId) !== -1;
    if (!isSalesAssigneeFetch) {
        $('#beatBadges').empty();
        $('#beatDate').val('');
        $('#beatDateSelection').hide();
        return;
    }

    var badgesDiv = $('#beatBadges');
    badgesDiv.html('<span style="color:#999; font-size:12px;">Loading beats...</span>');
    $("#beatDateSelection").show();
    $('#beatDate').val('');

    var url = context + "/lead-geo/beat-dates?leadId=" + leadId + "&salesAuthId=" + salesAuthId;

    $.ajax({
        url: url,
        method: 'GET',
        success: function (response) {
            var data = response.response || response;
            badgesDiv.empty();

            // Stores within radius of the lead — show count + top 3 inline.
            var radius = (data && data.radiusKm) ? data.radiusKm : 30;
            var stores = (data && data.nearestStores) || [];
            if (stores.length > 0) {
                var preview = stores.slice(0, 3).map(function (s) {
                    return '<strong>' + s.code + ' - ' + s.name + '</strong> (' + s.distanceKm + ' km)';
                }).join(', ');
                var more = stores.length > 3 ? ' +' + (stores.length - 3) + ' more' : '';
                badgesDiv.append('<div style="font-size:12px; color:#333; margin-bottom:6px;">' +
                    stores.length + ' partner store(s) within ' + radius + ' km of this lead: ' +
                    preview + more + '</div>');
            }

            // All upcoming beat-dates for the assignee that touch any nearby store.
            if (data && data.beats && data.beats.length > 0) {
                badgesDiv.append('<div style="font-weight:bold; font-size:11px; color:#666; margin-bottom:4px;">Available Slots (near this lead):</div>');
                var beats = data.beats;
                for (var i = 0; i < beats.length; i++) {
                    var beat = beats[i];
                    var nearTxt = beat.nearStore ? ' &middot; near ' + beat.nearStore : '';
                    var badge = $('<span class="beat-badge" style="' +
                        'display:inline-block; background:#337ab7; color:#fff; padding:6px 12px; ' +
                        'margin:4px 6px 4px 0; border-radius:16px; cursor:pointer; font-size:12px; ' +
                        'border:2px solid #337ab7; transition:all 0.2s;">' +
                        beat.planDate + ' &middot; ' + beat.beatName + ' (' + beat.stops + ' stops)' + nearTxt +
                        '</span>');
                    badge.data('value', beat.planDate + '|' + beat.beatName + '|' + beat.planGroupId);
                    badgesDiv.append(badge);
                }
            } else {
                // No beat-days available for this assignee. Surface a CTA so the
                // user can fire a visit request to the assignee's hierarchy instead
                // of being stuck. The pre-existing 'beats > 0' branch above is
                // untouched — this only fires for the empty-beats case.
                var nearestId = (stores.length > 0 && stores[0].storeId) ? stores[0].storeId : '';
                badgesDiv.append(
                    '<div style="background:#fff8e1; border:1px solid #f0e0a0; border-radius:6px; padding:8px 10px; margin-top:4px;">'
                    + '<div style="font-size:12px; color:#7c5a00; margin-bottom:6px;">'
                    + 'No upcoming beat is available for this assignee.'
                    + '</div>'
                    + '<div style="display:flex; gap:8px; align-items:center;">'
                    + '<label style="font-size:11px; color:#666; margin:0;">Preferred date (optional):</label>'
                    + '<input type="date" id="vrPreferredDate" class="input-sm" style="font-size:12px; padding:3px 6px;">'
                    + '<button type="button" id="vrSendBtn" class="btn btn-warning btn-sm" '
                    + 'data-nearest="' + nearestId + '" style="font-size:12px;">Send Visit Request</button>'
                    + '</div>'
                    + '<div style="font-size:11px; color:#888; margin-top:6px;">'
                    + 'The request goes to the assignee\'s reporting head (and up). Once they approve and pick a beat-day, the lead lands on that beat.'
                    + '</div>'
                    + '</div>');
            }
        },
        error: function () {
            badgesDiv.html('<span style="color:#d9534f; font-size:12px;">Error loading beats</span>');
        }
    });
}

// Send Visit Request when no beats are available for the chosen assignee.
// Posts to /visitRequest/create. Existing beat-pick + Submit flow is unchanged.
$(document).on('click', '#vrSendBtn', function () {
    var $btn = $(this);
    var assigneeAuthId = parseInt($('#assignTo').val());
    var commType = $('#communicationType').val() || null;
    var nearestStoreId = parseInt($btn.data('nearest'));
    var preferred = $('#vrPreferredDate').val() || null;
    if (!leadId || !assigneeAuthId) {
        alert('Pick an assignee first.');
        return;
    }
    $btn.prop('disabled', true).text('Sending...');
    var payload = {
        leadId: leadId,
        assigneeAuthId: assigneeAuthId,
        communicationType: commType,
        reason: 'No upcoming beats for assignee'
    };
    if (!isNaN(nearestStoreId) && nearestStoreId > 0) payload.nearestStoreId = nearestStoreId;
    if (preferred) payload.requestedDate = preferred;

    doPostAjaxRequestWithJsonHandler(context + '/visitRequest/create', JSON.stringify(payload),
        function (response) {
            $btn.prop('disabled', false).text('Send Visit Request');
            var data = (response && response.response) || response || {};
            if (data && data.id) {
                alert('Visit request sent. The assignee\'s manager has been notified.');
                $('#editLeadData').modal('hide');
                $('.modal-backdrop').remove();
            } else {
                var msg = (data && data.message) || (data && data.error) || 'Could not send request.';
                alert(msg);
            }
        });
});

// Click on beat badge to select it. A picked beat becomes the schedule
// source — the manual date input is hidden (not needed when scheduling by beat).
$(document).on('click', '.beat-badge', function () {
    $('.beat-badge').css({'background': '#337ab7', 'border-color': '#337ab7'});
    $(this).css({'background': '#1a5276', 'border-color': '#f39c12', 'border-width': '2px'});
    $('#beatDate').val($(this).data('value'));
    $("#editScheduleTime").hide();
});

// Generate Geo Link for lead
$(document).on('click', '.generateGeoLink', function (e) {
    e.stopPropagation();
    var lid = $(this).data('leadid');
    doAjaxRequestHandler(context + "/lead-geo/generate-link?leadId=" + lid, "GET", function (response) {
        var url = response.response;
        if (navigator.clipboard) {
            navigator.clipboard.writeText(url).then(function () {
                alert("Link copied to clipboard:\n" + url);
            });
        } else {
            prompt("Share this link with the prospect:", url);
        }
    });
});

// Geo Review navigation
$(document).on('click', '.geo-review', function () {
    doGetAjaxRequestHandler(context + "/lead-geo/pending-reviews", function (response) {
        $('#main-content').html(response);
    });
});

// Visit Approvals navigation
$(document).on('click', '.visit-approvals', function () {
    doGetAjaxRequestHandler(context + "/visit-approvals", function (response) {
        $('#main-content').html(response);
    });
});

// Beat Day View — load inline into dashboard
$(document).on('click', '.beat-plan-dayview', function (e) {
    e.preventDefault();
    doGetAjaxRequestHandler(context + '/beatPlan/dayView', function (response) {
        $('#main-content').html(response);
    });
});

// Base Location manager — load inline into dashboard
$(document).on('click', '.base-location', function (e) {
    e.preventDefault();
    doGetAjaxRequestHandler(context + '/beatPlan/baseLocationPage', function (response) {
        $('#main-content').html(response);
    });
});

// Deferred Partners — load inline into dashboard
$(document).on('click', '.beat-plan-deferred', function (e) {
    e.preventDefault();
    doGetAjaxRequestHandler(context + '/beatPlan/deferredView', function (response) {
        $('#main-content').html(response);
    });
});

// Approve geolocation from lead table
$(document).on('click', '.approve-geo', function (e) {
    e.stopPropagation();
    var lid = $(this).data('leadid');
    if (!confirm('Approve geolocation for Lead #' + lid + '?')) return;

    var btn = $(this);
    var cell = btn.closest('td');

    doPostAjaxRequestWithParamsHandler(
        context + '/lead-geo/review',
        {leadId: lid, status: 'APPROVED', remark: ''},
        function (response) {
            cell.html('<span class="label label-success">Verified</span>');
        }
    );
});

// Reject geolocation from lead table
$(document).on('click', '.reject-geo', function (e) {
    e.stopPropagation();
    var lid = $(this).data('leadid');
    var reason = prompt('Reason for rejection:');
    if (reason === null) return;

    var btn = $(this);
    var cell = btn.closest('td');

    doPostAjaxRequestWithParamsHandler(
        context + '/lead-geo/review',
        {leadId: lid, status: 'REJECTED', remark: reason},
        function (response) {
            cell.html('<button class="btn btn-xs btn-warning generateGeoLink" data-leadid="' + lid + '">Rejected - Resend</button>');
        }
    );
});