Subversion Repositories SmartDukaan

Rev

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

var TEAM_ACTIVITY = ["COMMUNICATION_OUT", "COMMUNICATION_INTERNAL",
        "ESCALATED", "ASSIGNED", "CATEGORY_CHANGED"];

// Activity type constants for consistent usage
var ActivityType = {
        OPENED: "OPENED",
        COMMUNICATION_IN: "COMMUNICATION_IN",
        COMMUNICATION_OUT: "COMMUNICATION_OUT",
        COMMUNICATION_INTERNAL: "COMMUNICATION_INTERNAL",
        RESOLVED: "RESOLVED",
        RESOLVED_ACCEPTED: "RESOLVED_ACCEPTED",
        RESOLVED_REJECTED: "RESOLVED_REJECTED",
        ESCALATED: "ESCALATED",
        ASSIGNED: "ASSIGNED",
        CATEGORY_CHANGED: "CATEGORY_CHANGED"
};

// Helper function to normalize boolean values from various sources
function toBool(val) {
        return val === true || val === "true";
}

// Helper function to escape HTML and prevent XSS
function escapeHtml(text) {
        if (text == null) return '';
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
}

$(function() {

        $(document).on('click', ".create-ticket-category", function() {
                console.log("create ticket category clicked......");
                loadCreateCategory("main-content");
        });
        $(document).on('click', ".create-region", function() {
                loadCreateRegion("main-content");
        });
        $(document).on('click', "#manager-ticket-search-by-partner-name",
                function() {
                        if ($("#manager-ticket-content-area").length) {
                                refreshManagerTicketTable(0);
                        } else if ($("#partner-ticket-content-area").length) {
                                refreshPartnerTicketTable();
                        }
                });
        $(document).on('click', "#retailer-details-search-button-by-ticketId",
                function() {
                        var searchContent = $("#search-by-ticketId").val();
                        if (searchContent == "" || searchContent == undefined
                                || searchContent == null) {
                                alert("Input field can't be empty");
                                return false;
                        }
                        if ($("#manager-ticket-content-area").length) {
                                refreshManagerTicketTable(0);
                        } else if ($("#partner-ticket-content-area").length) {
                                refreshPartnerTicketTable();
                        }
                });
        $(document).on('click', "#assignee-ticket-search-by-partner-name",
                function() {
                        refreshMyTicketTable(0);
                });
        $(document).on('click', "#assignee-retailer-details-search-button-by-ticketId",
                function() {
                        var searchContent = $("#assignee-search-by-ticketId").val();
                        if (searchContent == "" || searchContent == undefined
                                || searchContent == null) {
                                alert("Input field can't be empty");
                                return false;
                        }
                        refreshMyTicketTable(0);
                });

        $(document).on('click', ".ticket-last-activity", function() {
                var ticketId = $(this).data('ticketid');
                var activity = $(this).data('activity');
                var partnerName = $(this).data('partnername') || '';
                console.log(ticketId);
                console.log(activity);
                var message = partnerName ? "Mark Ticket #" + ticketId + " - " + partnerName + " as resolved?" : "Are you sure!";
                if (confirm(message) == true) {
                        createLastActivity(ticketId, activity);
                }
        });

        $(document).on('change', "#region", function() {
                var regionId = $("#region").val();
                console.log(regionId);
                loadPartnerForRegion(regionId);
        });

        $(document).on('change', "#regionPosition", function() {
                var regionId = $("#regionPosition").val();
                console.log(regionId);
                loadPartnerForRegionId(regionId);
        });

        $(document).on('change', "#managersearchType", function() {
                var searchType = $("#managersearchType").val();
                console.log(searchType);
                var html;
                if (searchType == "PARTNER_NAME") {
                        $('.byPartnerName').css('display', 'inline-block');
                        $('.byTicketId').css('display', 'none');
                        $("#search-by-ticketId").val("");
                } else {
                        $('.byPartnerName').css('display', 'none');
                        $('.byTicketId').css('display', 'inline-block');
                        $('#manager-ticket-search-by-partner-name').data('id', "");
                }

        });
        $(document).on('change', "#assigneesearchType", function() {
                var searchType = $("#assigneesearchType").val();
                console.log(searchType);
                var html;
                if (searchType == "PARTNER_NAME") {
                        $('.assigneebyPartnerName').css('display', 'inline-block');
                        $('.assigneebyTicketId').css('display', 'none');
                        $("#assignee-search-by-ticketId").val("");
                } else {
                        $('.assigneebyPartnerName').css('display', 'none');
                        $('.assigneebyTicketId').css('display', 'inline-block');
                        $("#assignee-ticket-search-by-partner-name").data('id', '');
                }

        });

        $(document).on('click', ".change-ticket-auth-button",
                function() {
                        var ticketId = $("#ticketId").val();
                        var subCategory = $("#subCategory").val();
                        var authUserId = $("#authUserCategory").val();
                        var categoryId = $("#categoryAuth").val();

                        var escalationType = $("#escalationType").val();
                        console.log(ticketId);
                        if (subCategory == null || subCategory == ""
                                || subCategory == undefined) {
                                alert("Choose appropriate subCategory");
                                return false;
                        }
                        console.log(subCategory);
                        console.log(authUserId);

                        console.log(categoryId);

                        if (confirm("Are you sure you want to change ticket!") == true) {
                                changeTicket(ticketId, subCategory, authUserId,
                                        categoryId, escalationType);
                        }
                });

        $(document).on('click', ".change-ticket-button",
                function() {
                        var ticketId = $("#ticketId").val();
                        var subCategory = $("#subCategory").val();
                        var authUserId;
                        var categoryId = $("#category").val();

                        var escalationType = $("#escalationType").val();
                        console.log(ticketId);
                        if (subCategory == null || subCategory == ""
                                || subCategory == undefined) {
                                alert("Choose appropriate subCategory");
                                return false;
                        }

                        console.log(subCategory);

                        console.log(categoryId);
                        console.log(authUserId);
                        if (confirm("Are you sure you want to change ticket!") == true) {
                                changeTicket(ticketId, subCategory, authUserId,
                                        categoryId, escalationType);
                        }
                });

        $(document).on('click', ".change-partner-ticket-button",
                function () {
                        var ticketId = $("#ticketId").val();
                        var subCategory = $("#subCategory").val();
                        var authUserId;
                        var categoryId = $("#category").val();

                        var escalationType = $("#escalationType").val();
                        console.log(ticketId);
                        if (subCategory == null || subCategory == ""
                                || subCategory == undefined) {
                                alert("Choose appropriate subCategory");
                                return false;
                        }

                        console.log(subCategory);

                        console.log(categoryId);
                        console.log(authUserId);
                        if (confirm("Are you sure you want to change ticket!") == true) {
                                changeMyPartnerTicket(ticketId, subCategory, authUserId,
                                        categoryId, escalationType);
                        }
                });
        $(document).on('click', ".edit-ticket", function() {
                var ticketId = $(this).data('ticketid1');
                loadEditTicket(ticketId);
        });

        $(document).on('click', ".edit-ticket-partner", function () {
                var ticketId = $(this).data('ticketid1');
                loadMyPartnerEditTicket(ticketId);
        });

        $(document).on('click', ".manager-ticket", function() {
                loadManagerTicket("main-content", null, null);
        });
        $(document).on('click', ".access-management", function() {
                loadAccessManagement("main-content", null, null);
        });
        $(document).on('click', ".ticketType", function() {
                console.log("create Region");
                loadCreateRegion("main-content");
        });
        $(document).on('click', ".activities-link", function() {
                var ticketId = $(this).data('ticketid');
                var assignee = $(this).data('assignee');
                var internal = $(this).data('internal');
                var roleType = $(this).data('role');
                var isCrmUser = $(this).data('crm');
                var canAction = $(this).data('canaction');
                console.log(assignee);
                loadActivities(ticketId, assignee, internal, roleType, isCrmUser);
                // Hide modal footer (message input/submit) if user cannot take action
                if (canAction !== undefined && canAction.toString().trim() === 'false') {
                        $('#myModal .modal-footer').hide();
                } else {
                        $('#myModal .modal-footer').show();
                }
        });
        $(document).on('click', ".my-ticket", function() {
                loadMyTicket("main-content", null, null, null, null, null);
        });
        $(document).on('click', "#close-ticket", function() {
                var ticketId = $(this).data('ticketid');
                closeTicket(ticketId);
        });

        $(document).on('change', '.partners', function() {
                console.log("Hello");
        });
        var documentIds = [];
        var count = 0;

        $(document).on('click', ".submit-message-button",
                function() {
                        var message = $("#activityMessage").val();
                        var internal = $("#internalCommunication").prop("checked");
                        if (message == "" || message == null || message == undefined) {
                                alert("message field can't be empty");
                                return false;
                        }
                        var ticketId = $("#ticketIdforactivity").val();
                        var assignee = $("#assigneeUser").val();
                        var roleType = $("#role").val();
                        var isCrmUser = $("#crmUser").val();
                        count = 0;
                        console.log(message, ticketId, assignee);

                        createActivity(message, ticketId, assignee, internal, roleType, isCrmUser,
                                documentIds);
                });

        $(document).on('click', ".uploadFile", function() {
                $("#file1").trigger('click');
        });

        $(document).on('change', "input[name=file1]",
                function(evt) {
                        var output = [];
                        var fileBundle = [];
                        for (var i = 0, f; f = evt.target.files[i]; i++) {
                                count++;
                                console.log(count);
                                if (evt.target.files[i].size > 5000000) {
                                        alert("Size should be less than 5MB");
                                        return false;
                                }

                                if (count > "5") {
                                        alert("five files send at a time");
                                        var lilength = $('.fileList li').size();
                                        console.log(lilength);
                                        count = lilength;
                                        console.log(lilength)
                                        return false;
                                }

                                var file = evt.target.files[i];
                                fileBundle.push(file);
                                console.log(fileBundle);

                                var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\""
                                        + i + "\">Remove</a>";

                                output.push("<li><strong>", file.name,
                                        "</strong> - ", "&nbsp; &nbsp; ",
                                        removeLink, "</li> ");

                        }

                        for (var j = 0; j < fileBundle.length; j++) {
                                console.log(fileBundle[j])
                                var url = context + '/document-upload';
                                doAjaxUploadRequestHandler(
                                        url,
                                        'POST',
                                        fileBundle[j],
                                        function(response) {
                                                console.log(response);
                                                var documentId = response.response.document_id;
                                                console.log("documentId : "
                                                        + documentId);
                                                documentIds.push(documentId);

                                        });

                        }
                        console.log(documentIds);
                        $(".fileList").append(output.join(""));

                });

        $(document).on('click', ".removeFile", function(e) {
                e.preventDefault();
                console.log("Hello")
                var fileId = $(this).parent().children("a").data("fileid");
                for (var i = 0; i < documentIds.length; ++i) {
                        if (documentIds[i].id === fileId)
                                documentIds.splice(i, 1);
                }
                console.log(documentIds)
                $(this).parent().remove();
                var lilen = $('.fileList li').size();

                count = lilen;
                console.log(count)
                /*
                 * var lilength = $('.fileList li').size(); if (lilength == 1) {
                 * console.log(lilength) $(".fileList li").remove(); } else {
                 * console.log(lilength) $(".fileList li").eq(fileId).remove(); } var
                 * lilen = $('.fileList li').size();
                 * 
                 * count = lilen; console.log(count)
                 * 
                 * console.log(documentIds);
                 */

        });

        // AJAX pagination for My Ticket
        $(document).on('click', "#ticket-content-area .ticket-page-link", function(e) {
                e.preventDefault();
                refreshMyTicketTable($(this).data('page'));
        });
        $(document).on('change', "#ticket-content-area .ticket-page-size", function() {
                refreshMyTicketTable(0);
        });

        // AJAX pagination for Manager Ticket
        $(document).on('click', "#manager-ticket-content-area .manager-ticket-page-link", function(e) {
                e.preventDefault();
                refreshManagerTicketTable($(this).data('page'));
        });
        $(document).on('change', "#manager-ticket-content-area .manager-ticket-page-size", function() {
                refreshManagerTicketTable(0);
        });

        // AJAX pagination for Partner Ticket
        $(document).on('click', "#partner-ticket-content-area .partner-ticket-page-link", function(e) {
                e.preventDefault();
                refreshPartnerTicketTable();
        });

        // Search form handlers
        $(document).on('submit', "#ticket-search-form", function(e) {
                e.preventDefault();
                refreshMyTicketTable(0);
        });
        $(document).on('click', "#ticket-search-btn", function() {
                refreshMyTicketTable(0);
        });
        $(document).on('click', "#ticket-search-clear", function() {
                $("#ticket-search-input").val('');
                $(this).hide();
                refreshMyTicketTable(0);
        });

        $(document).on('submit', "#manager-ticket-search-form", function(e) {
                e.preventDefault();
                refreshManagerTicketTable(0);
        });
        $(document).on('click', "#manager-ticket-search-btn", function() {
                refreshManagerTicketTable(0);
        });
        $(document).on('click', "#manager-ticket-search-clear", function() {
                $("#manager-ticket-search-input").val('');
                $(this).hide();
                refreshManagerTicketTable(0);
        });
        $(document).on('click', "#positions-paginated .next",
                function() {
                        loadPaginatedNextItems('/cs/position-paginated', null,
                                'positions-paginated', 'position-table',
                                'position-details-container');
                        $(this).blur();
                });

        $(document).on('click', "#positions-paginated .previous",
                function() {
                        loadPaginatedPreviousItems('/cs/position-paginated', null,
                                'positions-paginated', 'position-table',
                                'position-details-container');
                        $(this).blur();
                });

        $(document).on('click', ".create-partner-region", function() {
                loadCreatePartnerRegion("main-content");
        });
        $(document).on('click', ".create-ticket", function() {
                loadCreateTicket("main-content");
        });

        $(document).on('click', ".my-partner-ticket", function () {
                loadMyPartnerTicket("main-content");
        });
        $(document).on('click', ".create-ticket-button",
                function() {
                        var categoryId = $('#category').val();
                        var subCategoryId = $('#subCategory').val();
                        var message = $('#message').val();

                        if (categoryId == "" || categoryId == null || categoryId == undefined) {
                                alert("Please select a category");
                                return false;
                        }
                        if (subCategoryId == "" || subCategoryId == null || subCategoryId == undefined) {
                                alert("Please select a subcategory");
                                return false;
                        }
                        if (message == "" || message == null || message == undefined || message.trim() == "") {
                                alert("Please describe your issue");
                                $('#message').focus();
                                return false;
                        }

                        if (confirm("Are you sure you want to create this ticket?")) {
                                var params = {
                                        "categoryId": categoryId,
                                        "subCategoryId": subCategoryId,
                                        "message": message
                                };
                                doPostAjaxRequestWithParamsHandler(
                                        context + "/cs/createTicket",
                                        params,
                                        function(response) {
                                                if (response == "true") {
                                                        alert("Ticket created successfully");
                                                        loadCreateTicket("main-content");
                                                } else {
                                                        alert("You have reached maximum number of unresolved tickets. Please accept resolution for resolved tickets to create new ones.");
                                                }
                                        });
                        }
                });
        $(document).on('click', ".create-position", function() {
                loadCreatePosition("main-content");
        });

        $(document).on('click', ".positionPartnerView", function() {
                $clickedElement = $(this);
                var positionId = $clickedElement.data("positionid");
                $tdElement = $(this).closest('td');
                doGetAjaxRequestHandler(context + "/cs/getPosition?positionId=" + positionId, function(response) {

                        $tdElement.html(response);
                        $tdElement.find('.partners').multiselect({
                                includeSelectAllOption: true,
                                multiple: true,
                                maxHeight: 200,
                                buttonWidth: '180px',
                                numberDisplayed: 1,
                                nonSelectedText: 'Partners',
                                nSelectedText: ' - Users Selected',
                                allSelectedText: 'All Users Selected',
                                enableFiltering: true,
                                enableCaseInsensitiveFiltering: true
                        });
                });
        });


        $(document).on('change', "#ticketStatus", function() {
                refreshMyTicketTable(0);
        });
        $(document).on('change', "#orderBy", function() {
                refreshMyTicketTable(0);
        });
        $(document).on('change', "#managerTicketStatus", function() {
                // Check if we're on manager ticket page or partner ticket page
                if ($("#manager-ticket-content-area").length) {
                        refreshManagerTicketTable(0);
                } else if ($("#partner-ticket-content-area").length) {
                        refreshPartnerTicketTable();
                }
        });
        $(document).on('change', "#managerTicketorderBy", function() {
                if ($("#manager-ticket-content-area").length) {
                        refreshManagerTicketTable(0);
                } else if ($("#partner-ticket-content-area").length) {
                        refreshPartnerTicketTable();
                }
        });
        $(document).on('change', "#category", function() {
                var categoryId = $("#category").val();
                //      $("#auth-user-for-category").hide();
                loadSubCategories(categoryId);
        });

        $(document).on('change', "#authUserCategory", function() {
                var authId = $("#authUserCategory").val();
                console.log(authId)
                loadCategories(authId);
        });

        $(document).on('change', "#categoryAuth", function() {
                var categoryId = $("#categoryAuth").val();
                var authId = $("#authUserCategory").val();

                console.log(categoryId)
                loadAuthSubCategories(categoryId, authId);
        });


        $(document).on('click', ".create-ticket-category-button", function () {
                console.log("create-ticket-category-button clicked......");

                var name = $("#categoryName").val();
                var description = $("#categorydescription").val();
                var categoryType = $("#categoryType").is(":checked") ? 1 : 0;

                console.log('cccccccccccccc', name, description, categoryType);

                if (name === "" || name === null || name === undefined) {
                        alert("Name field can't be empty");
                        return false;
                }

                if (description === "" || description === null || description === undefined) {
                        alert("Description field can't be empty");
                        return false;
                }

                if (confirm("Are you sure you want to create a ticket category?")) {
                        createCategory("main-content", name, description, categoryType);
                }
        });

        $(document).on('click', ".create-region-button",
                function() {
                        var name = $("#regionName").val();
                        var description = $("#regiondescription").val();
                        if (name == "" || name == null || name == undefined) {
                                alert("Name field can't be empty");
                                return false;
                        }
                        if (description == "" || description == null
                                || description == undefined) {
                                alert("Description field can't be empty");
                                return false;
                        }
                        if (confirm("Are you sure you want to create region!") == true) {
                                createRegion("main-content", name, description);
                        }
                });

        $(document).on('click', ".create-partner-region-button",
                function() {

                        var regionId = $("#region").val();
                        var fofoIds = $("#partner").val();
                        console.log(regionId, fofoIds);
                        if (regionId == "" || regionId == null
                                || regionId == undefined) {
                                alert("regionId field can't be empty");
                                return false;
                        }
                        if (fofoIds == "" || fofoIds == null
                                || fofoIds == undefined) {
                                alert("select appropriate partner");
                                return false;
                        }
                        if (confirm("Are you sure you want to create partner region!") == true) {
                                createPartnerRegion("main-content", regionId,
                                        fofoIds);
                        }
                });
        $(document).on('click', ".create-position-button",
                function() {

                        var authUser = $("#authUser").val();
                        var ticketCategoryPosition = $(
                                "#ticketCategoryPosition").val();
                        var escalationType = $("#escalationType").val();
                        var regionPosition = $("#regionPosition").val();


                        let ticketAssignee = $('#ticketAssignee').is(':checked');


                        console.log(ticketAssignee);
                        var fofoIds = $("#partner").val();
                        if (fofoIds.includes("0")) {
                                fofoIds = [0];
                                console.log(fofoIds);
                        } else {
                                console.log(fofoIds);
                        }
                        console.log(authUser, ticketCategoryPosition,
                                escalationType, regionPosition);
                        if (authUser == "" || authUser == null
                                || authUser == undefined) {
                                alert("select appropriate authUser");
                                return false;
                        }
                        if (ticketCategoryPosition == ""
                                || ticketCategoryPosition == null
                                || ticketCategoryPosition == undefined) {
                                alert("select appropriate category");
                                return false;
                        }
                        if (escalationType == "" || escalationType == null
                                || escalationType == undefined) {
                                alert("select appropriate escalationType");
                                return false;
                        }
                        if (regionPosition == "" || regionPosition == null
                                || regionPosition == undefined) {
                                alert("select appropriate Region");
                                return false;
                        }

                        if (confirm("Are you sure you want to create Position!") == true) {
                                createPosition("main-content", authUser,
                                        ticketCategoryPosition, escalationType,
                                        regionPosition, fofoIds,
                                        ticketAssignee
                                );
                        }

                });

        $(document).on('change', "#ticketCategory", function() {
                console.log("change ticket category clicked......");
                var ticketCategoryId = $(this).val();
                console.log(ticketCategoryId);
                loadticketSubCategoryById(ticketCategoryId);
        });
        $(document).on('click', ".create-ticket-sub-category", function() {
                console.log("create ticket category clicked......");
                loadCreateSubCategory("main-content");
        });

        $(document).on('click', ".create-ticket-sub-category-button",
                function() {
                        console
                                .log("create-ticket-category-button clicked......");
                        var name = $("#subcategoryName").val();
                        var description = $("#subcategorydescription").val();
                        var ticketCategoryId = $("#ticketCategory").val();
                        console.log(name, description);
                        if (name == "" || name == null || name == undefined) {
                                alert("Name field can't be empty");
                                return false;
                        }
                        if (description == "" || description == null
                                || description == undefined) {
                                alert("Description field can't be empty");
                                return false;
                        }
                        if (ticketCategoryId == "" || ticketCategoryId == null
                                || ticketCategoryId == undefined) {
                                alert("select appropriate category name");
                                return false;
                        }
                        if (confirm("Are you sure you want to create ticket category!") == true) {
                                createSubCategory("main-content", name,
                                        description, ticketCategoryId);
                        }
                });
        $(document).on('click', ".remove-position", function() {
                var positionId = $(this).data('positionid');
                if (confirm("Are you sure you want to remove position!") == true) {
                        removePosition(positionId);
                }
        });


        $(document).on('change', "#ticketAssign", function() {
                var positionId = $(this).data('positionid');
                if (confirm("Are you sure you want to change ticket Assignee !") == true) {
                        doPostAjaxRequestHandler(context + "/cs/changeTicketAssignee?positionId="
                                + positionId, function(response) {
                                        if (response == "true") {
                                                alert("change successfully");
                                                loadCreatePosition("main-content");
                                        }
                                });
                }
        });




        $(document).on('click', ".update-position",
                function() {
                        var positionId = $(this).data('positionid');
                        var regionId = $(this).data('regionid');
                        var row = $(this);
                        var selectedFofoIds = $(this).closest("tr").find(
                                '#partners').val();
                        if (selectedFofoIds.includes("0")) {
                                selectedFofoIds = [0];
                                console.log(selectedFofoIds);
                        } else {
                                console.log(selectedFofoIds);
                        }
                        if (confirm("Are you sure you want to update the partners!") == true) {
                                doPostAjaxRequestWithJsonHandler(context
                                        + "/cs/updatePartnerPosition?regionId="
                                        + regionId + "&positionId=" + positionId,
                                        JSON.stringify(selectedFofoIds), function(
                                                response) {
                                        if (response == "true") {
                                                alert("Update successfully");
                                                //loadCreatePosition("main-content");
                                        }
                                });
                        }

                });

});

function loadCreateCategory(domId) {
        doGetAjaxRequestHandler(context + "/cs/createCategory", function(response) {
                $('#' + domId).html(response);
        });
}
function removePosition(positionId) {
        doDeleteAjaxRequestHandler(context + "/cs/removePosition?positionId="
                + positionId, function(response) {
                        if (response == "true") {
                                alert("Position removed successfully");
                                loadCreatePosition("main-content");
                        }
                });
}

function loadCreateRegion(domId) {
        doGetAjaxRequestHandler(context + "/cs/createRegion", function(response) {
                $('#' + domId).html(response);
        });
}
function loadMyTicket(domId, ticketStatus, sortOrder, ticketSearchType,
        searchTerm, searchValue) {

        if (ticketStatus == null && sortOrder == null) {
                doGetAjaxRequestHandler(context + "/cs/myticket", function(response) {
                        $('#' + domId).html(response);
                });
        } else if (ticketSearchType == null) {
                doGetAjaxRequestHandler(context + "/cs/myticket?ticketStatus="
                        + ticketStatus + "&orderby=" + sortOrder, function(response) {
                                $('#' + domId).html(response);
                        });
        } else {
                doGetAjaxRequestHandler(context + "/cs/myticket?ticketStatus="
                        + ticketStatus + "&orderby=" + sortOrder + "&ticketSearchType="
                        + ticketSearchType + "&searchTerm=" + searchTerm, function(
                                response) {
                        $('#' + domId).html(response);
                        if (ticketSearchType == "PARTNER_NAME") {
                                $('.assigneebyPartnerName').css('display', 'inline-block');
                                $('.assingeebyTicketId').css('display', 'none');
                                $("#typeaheadpartnernameforassignee").val(searchValue);
                                $("#assignee-partner-name-input").val(searchTerm);
                        } else {
                                $('.assigneebyPartnerName').css('display', 'none');
                                $('.assigneebyTicketId').css('display', 'inline-block');
                                $("#assignee-search-by-ticketId").val(searchTerm);
                        }
                });
        }
}

function loadCreatePartnerRegion(domId) {
        doGetAjaxRequestHandler(context + "/cs/createPartnerRegion", function(
                response) {
                $('#' + domId).html(response);
        });
}
function loadCreatePosition(domId) {
        doGetAjaxRequestHandler(context + "/cs/createPosition", function(response) {
                $('#' + domId).html(response);
        });
}
function loadSubCategories(categoryId) {
        doGetAjaxRequestHandler(context
                + "/cs/getSubCategoriesByCategoryId?categoryId=" + categoryId,
                function(response) {
                        $('#' + "create-ticket-sub-categories").html(response);
                });
}

function loadCategories(authId) {
        doGetAjaxRequestHandler(context
                + "/cs/getCategoriesByAuthId?authId=" + authId,
                function(response) {
                        $('#' + "create-tickets-categories-for-auth").html(response);
                });
}

function loadAuthSubCategories(categoryId, authId) {
        doGetAjaxRequestHandler(context
                + "/cs/getSubCategoriesByCategoryId?categoryId=" + categoryId,
                function(response) {
                        $('#' + "create-ticket-sub-categories-for-auth").html(response);
                });


        doGetAjaxRequestHandler(context
                + "/cs/getEscalationTypeByCategoryId?categoryId=" + categoryId + "&authId=" + authId,
                function(response) {
                        $('#' + "create-ticket-escalationType-for-auth").html(response);
                });


}

function createCategory(domId, name, description, categoryType) {
        var params = {
                "name": name,
                "description": description,
                "categoryType": categoryType,
        };

        doPostAjaxRequestWithParamsHandler(context + "/cs/createCategory", params, function (response) {
                alert("Category created successfully");
                loadCreateCategory(domId);
        });
}

function changeTicket(ticketId, subCategoryId, authUserId, categoryId, escalationType) {
        var params = {
                "ticketId": ticketId,
                "subCategoryId": subCategoryId,
                "authUserId": authUserId,
                "categoryId": categoryId,
                "escalationType": escalationType
        }
        doPostAjaxRequestWithParamsHandler(context + "/cs/edit-ticket", params,
                function(response) {
                        if (response == "true") {
                                $('#theModal').modal('hide');
                                $('body').removeClass('modal-open');
                                $('.modal-backdrop').remove();
                                alert("Ticket changed successfully");
                                if ($("#manager-ticket-content-area").length) {
                                        refreshManagerTicketTable(0);
                                } else if ($("#ticket-content-area").length) {
                                        refreshMyTicketTable(0);
                                } else {
                                        loadManagerTicket("main-content", null, null, null, null, null);
                                }
                        }
                });
}

function changeMyPartnerTicket(ticketId, subCategoryId, authUserId, categoryId, escalationType) {
        var params = {
                "ticketId": ticketId,
                "subCategoryId": subCategoryId,
                "authUserId": authUserId,
                "categoryId": categoryId,
                "escalationType": escalationType
        }
        doPostAjaxRequestWithParamsHandler(context + "/cs/edit-partner-ticket", params,
                function (response) {
                        if (response == "true") {
                                $('#theModal2').modal('hide');
                                $('body').removeClass('modal-open');
                                $('.modal-backdrop').remove();
                                alert("Ticket changed successfully");
                                if ($("#partner-ticket-content-area").length) {
                                        refreshPartnerTicketTable();
                                } else {
                                        loadMyPartnerTicket("main-content");
                                }
                        }
                });
}


function createRegion(domId, name, description) {
        var params = {
                "name": name,
                "description": description
        }
        doPostAjaxRequestWithParamsHandler(context + "/cs/createRegion", params,
                function(response) {
                        if (response == "true") {
                                alert("Region created successfully");
                                loadCreateRegion(domId);
                        }
                });
}
function loadCreateSubCategory(domId) {
        doGetAjaxRequestHandler(context + "/cs/createSubCategory", function(
                response) {
                $('#' + domId).html(response);
        });
}
function loadManagerTicket(domId, ticketStatus, sortOrder, ticketSearchType,
        searchTerm, searchValue) {
        if (ticketStatus == null && sortOrder == null) {
                doGetAjaxRequestHandler(context + "/cs/managerTicket", function(
                        response) {
                        $('#' + domId).html(response);
                });
        } else if (ticketSearchType == null) {
                doGetAjaxRequestHandler(context + "/cs/managerTicket?ticketStatus="
                        + ticketStatus + "&orderby=" + sortOrder, function(response) {
                                $('#' + domId).html(response);
                        });
        } else {
                doGetAjaxRequestHandler(context + "/cs/managerTicket?ticketStatus="
                        + ticketStatus + "&orderby=" + sortOrder + "&ticketSearchType="
                        + ticketSearchType + "&searchTerm=" + searchTerm, function(
                                response) {
                        $('#' + domId).html(response);
                        if (ticketSearchType == "PARTNER_NAME") {
                                $('.byPartnerName').css('display', 'inline-block');
                                $('.byTicketId').css('display', 'none');
                                $("#typeaheadpartnername").val(searchValue);
                                $("#partner-name-input").val(searchTerm);
                        } else {
                                $('.byPartnerName').css('display', 'none');
                                $('.byTicketId').css('display', 'inline-block');
                                $("#search-by-ticketId").val(searchTerm);
                        }
                });
        }
}
function loadCreateTicket(domId) {
        doGetAjaxRequestHandler(context + "/cs/createTicket", function(response) {
                $('#' + domId).html(response);
        });
}

function loadMyPartnerTicket(domId) {
        doGetAjaxRequestHandler(context + "/cs/myPartyTicketTicket", function (response) {
                $('#' + domId).html(response);
        });
}
function loadticketSubCategoryById(ticketCategoryId) {
        doGetAjaxRequestHandler(context
                + "/cs/getSubCategoryByCategoryId?ticketCategoryId="
                + ticketCategoryId, function(response) {
                console.log('response', response);
                        $(".ticket-sub-category-container").html(response);
                });
}
function createPartnerRegion(domId, regionId, fofoIds) {
        doPostAjaxRequestWithJsonHandler(context
                + "/cs/createPartnerRegion?regionId=" + regionId, JSON
                        .stringify(fofoIds), function(response) {
                                if (response == "true") {
                                        alert("added region to partner successfully");
                                        loadCreatePartnerRegion(domId);
                                }
                        });
}
function createSubCategory(domId, name, description, categoryId) {
        var params = {
                "categoryId": categoryId,
                "name": name,
                "description": description
        }
        doPostAjaxRequestWithParamsHandler(context + "/cs/createSubCategory",
                params, function(response) {
                        alert("Sub Category created successfully");
                        loadCreateSubCategory(domId);
                });
}
function createLastActivity(ticketId, activity) {
        var params = {
                "ticketId": ticketId,
                "lastactivity": activity
        }
        doPostAjaxRequestWithParamsHandler(context + "/cs/create-last-activity",
                params, function(response) {
                        if (response == "true") {
                                alert("successfully mark last activity");
                                if ($("#ticket-content-area").length) {
                                        refreshMyTicketTable(0);
                                } else if ($("#manager-ticket-content-area").length) {
                                        refreshManagerTicketTable(0);
                                } else if ($("#partner-ticket-content-area").length) {
                                        refreshPartnerTicketTable();
                                } else {
                                        loadMyTicket("main-content", null, null);
                                }
                        }
                });
}

function createPosition(domId, authUserId, categoryId, escalationType,
        regionId, fofoIds, ticketAssignee) {

        var createPositionModel = {};
        createPositionModel['authUserId'] = authUserId;
        createPositionModel['categoryId'] = categoryId
        createPositionModel['escalationType'] = escalationType;
        createPositionModel['regionId'] = regionId,

                createPositionModel['ticketAssigned'] = ticketAssignee,
                createPositionModel['fofoIds'] = fofoIds

        console.log(createPositionModel);
        doPostAjaxRequestWithJsonHandler(context + "/cs/createPosition", JSON
                .stringify(createPositionModel), function(response) {
                        if (response == "true") {
                                alert("Position created successfully");
                                loadCreatePosition(domId);
                        }
                });
}
function createActivity(message, ticketId, assigneeId, internal, roleType, isCrmUser,
        documentIds) {

        var params = {
                "message": message,
                "ticketId": ticketId,
                "assigneeId": assigneeId,
                "internal": internal,
                "documentIds": documentIds,
        }
        if (documentIds.includes("0")) {
                documentIds = [0];
                console.log(documentIds);
        } else {
                console.log(documentIds);
        }
        console.log(JSON.stringify(documentIds))
        doPostAjaxRequestWithJsonHandler(context + "/cs/createActivity?message="
                + message + "&ticketId=" + ticketId + "&assigneeId=" + assigneeId
                + "&internal=" + internal, JSON.stringify(documentIds), function(
                        response) {
                response = JSON.parse(response);

                documentIds.splice(0, documentIds.length);

                console.log(documentIds)
                $(".fileList li").remove();
                var assigneeName = response.firstName;
                loadActivities(ticketId, assigneeName, internal, roleType, isCrmUser)
        });
}
function loadEditTicket(ticketId) {
        doGetAjaxRequestHandler(context + "/cs/edit-ticket?ticketId=" + ticketId,
                function(response) {
                        $("#theModal .modal-content").html(response);
                        $("#theModal").modal('show');
                });
}

function loadMyPartnerEditTicket(ticketId) {
        doGetAjaxRequestHandler(context + "/cs/edit-partner-ticket?ticketId=" + ticketId,
                function (response) {
                        $("#theModal2 .modal-content").html(response);
                        $("#theModal2").modal('show');
                });
}
function loadPartnerForRegion(regionId) {
        doGetAjaxRequestHandler(context + "/cs/getPartners?regionId=" + regionId,
                function(response) {
                        $("#partner-region-container").html(response);
                });
}

function loadPartnerForRegionId(regionId) {
        doGetAjaxRequestHandler(context + "/cs/getPartnersByRegion?regionId="
                + regionId, function(response) {
                        $("#partner-subregion-container").html(response);
                });
}

function loadAccessManagement(domId) {
        doGetAjaxRequestHandler(context + "/admin/access-management", function(
                response) {
                $('#' + domId).html(response);
        });
}

function loadActivities(ticketId, assignee, internal, roleType, isCrmUser) {

        // Set current ticket ID for read tracking
        if (typeof TicketManager !== 'undefined') {
                TicketManager.setCurrentTicketId(ticketId);
        }

        // Show loading spinner
        $(".activity-container .modal-body").html('<div class="text-center" style="padding:20px;"><i class="fa fa-spinner fa-spin fa-2x"></i><br>Loading...</div>');
        $("#activityMessage").val("");
        $("#ticketIdforactivity").val(ticketId);
        $("#role").val(roleType);
        $("#crmUser").val(isCrmUser);
        $(".activity-container .modal-title").html(
                "Activity history for Ticket Id " + ticketId)
        console.log(ticketId);
        doGetAjaxRequestHandler(
                context + "/cs/getActivities?ticketId=" + ticketId,
                function(response) {
                        $(".activity-container .modal-body").empty(); // Clear loading spinner
                        response = JSON.parse(response);
                        console.log(response);

                        for (var i = 0; i < response.length; i++) {
                                console.log(response[i].activityAttachment.length);
                                var activityAttachment = []
                                var attachments = "";
                                if (response[i].activityAttachment.length > 0) {
                                        for (var j = 0; j < response[i].activityAttachment.length; j++) {
                                                var docName = escapeHtml(response[i].activityAttachment[j].documentName);
                                                var assigneeAttachment = "<a href=\"javascript:void(0)\" style=\"color:#337ab7;float:right;\"onclick=\"downloadDocument("
                                                        + response[i].activityAttachment[j].documentId
                                                        + ",\`"
                                                        + docName
                                                        + "\`)\">"
                                                        + docName
                                                        + "&nbsp;<i class=\"fa fa-download\"></i>"
                                                        + "</a>"
                                                activityAttachment.push(assigneeAttachment);
                                        }
                                        attachments = activityAttachment.join("");
                                        console.log(attachments);
                                }

                                var activityType = response[i].type;
                                var escapedMessage = escapeHtml(response[i].message);
                                var formattedTime = moment(response[i].createTimestamp).format('DD/MM/YYYY, h:mm:ss a');

                                if (activityType == ActivityType.OPENED || activityType == ActivityType.COMMUNICATION_IN) {

                                        var partnerMessage = "<div class=\"incoming_msg\">"
                                                + "<div class=\"received_msg\">"
                                                + "<div class=\"received_withd_msg\">" + "<p>"
                                                + escapedMessage + "</p><div>"
                                                + `${attachments}`
                                                + "</div> <span class=\"time_date\"> "
                                                + formattedTime
                                                + "</span></div>" + "</div>" + "</div>";
                                        $(".activity-container .modal-body").append(
                                                partnerMessage);

                                } else if (activityType == ActivityType.COMMUNICATION_OUT) {
                                        var senderName = escapeHtml(response[i].name ? response[i].name : "Support");
                                        var assigneeMessage = "<div class=\"outgoing_msg\">"
                                                + "<div class=\"sent_msg\">"
                                                + "<span style=color:green>"
                                                + "~"
                                                + senderName + "<p>"
                                                + escapedMessage + "</span> </p><div>"
                                                + `${attachments}`
                                                + "</div> <span class=\"time_date\">"
                                                + formattedTime
                                                + "</span> </div>" + "</div>";
                                        $(".activity-container .modal-body").append(
                                                assigneeMessage);

                                } else if (response[i].name && activityType == ActivityType.COMMUNICATION_INTERNAL) {
                                        var senderName = escapeHtml(response[i].name);
                                        var assigneeMessage = "<div class=\"outgoing_msg\">"
                                                + "<div class=\"sent_msg\">"
                                                + "<span style=color:green>"
                                                + "~"
                                                + senderName
                                                + "<p style=\"color: white;background: #b75454;\">"
                                                + escapedMessage + "</span> </p> <div>"
                                                + `${attachments}`
                                                + "</div> <span class=\"time_date\">"
                                                + formattedTime
                                                + "</span> </div>" + "</div>";
                                        $(".activity-container .modal-body").append(
                                                assigneeMessage);

                                } else {
                                        var typeLabel = activityType == "ESCALATED" ? "Escalated"
                                                : activityType == "ESCALATED_FINAL" ? "Final Escalation"
                                                : activityType == "ASSIGNED" ? "Assigned"
                                                : activityType == "CATEGORY_CHANGED" ? "Category Changed"
                                                : activityType;

                                        // Show message for ASSIGNED/ESCALATED activities if available
                                        var activityMessage = "";
                                        if ((activityType == "ASSIGNED" || activityType == "ESCALATED" || activityType == "ESCALATED_FINAL") && escapedMessage && escapedMessage.trim() !== "") {
                                                activityMessage = "<div style=\"font-size:12px;color:#555;margin-top:3px;\">" + escapedMessage + "</div>";
                                        }

                                        var systemMessage = "<div class=\"system-activity\">"
                                                + "<span>" + escapeHtml(typeLabel) + " &middot; " + formattedTime + "</span>"
                                                + activityMessage
                                                + "</div>";
                                        $(".activity-container .modal-body").append(
                                                systemMessage);

                                }

                        }
                        // Only show internal checkbox to CRM users (they can choose internal/external)
                        // Non-CRM users always send internal, so hide the checkbox
                        if (toBool(roleType) && toBool(isCrmUser)) {
                                $('.internalCheckBox').css('display', 'block');
                                $('#internalCommunication').prop('checked', toBool(internal));
                        } else {
                                $('.internalCheckBox').css('display', 'none');
                                // Non-CRM users always send internal
                                $('#internalCommunication').prop('checked', true);
                        }
                });
}

function downloadDocument(documentId, documentName) {
        console.log(documentName)
        doAjaxGetDownload(context + "/download?documentId=" + documentId,
                documentName);
}

// AJAX refresh functions for ticket tables (SPA-style, no full page reload)

function refreshMyTicketTable(page) {
        var ticketStatus = $("#ticketStatus").val() || "OPENED";
        var orderBy = $("#orderBy").val() || "DESCENDING";
        var search = $("#ticket-search-input").val() || "";
        var pageSize = $("#ticket-content-area .ticket-page-size").val() || "25";

        var searchType = $("#assigneesearchType").val();
        var searchTerm = "";
        if (searchType == "PARTNER_NAME") {
                searchTerm = $("#assignee-partner-name-input").val() || "";
        } else if (searchType == "TICKET_ID") {
                searchTerm = $("#assignee-search-by-ticketId").val() || "";
        }

        var url = context + "/cs/myticket-content?ticketStatus=" + encodeURIComponent(ticketStatus)
                + "&orderby=" + encodeURIComponent(orderBy)
                + "&page=" + (page || 0)
                + "&pageSize=" + pageSize
                + "&search=" + encodeURIComponent(search);

        if (searchType && searchType != "") {
                url += "&ticketSearchType=" + encodeURIComponent(searchType) + "&searchTerm=" + encodeURIComponent(searchTerm);
        }

        // Show/hide clear button
        if (search && search != "") {
                $("#ticket-search-clear").show();
        } else {
                $("#ticket-search-clear").hide();
        }

        doGetAjaxRequestHandler(url, function(response) {
                $('#ticket-content-area').html(response);
        });
}

function refreshManagerTicketTable(page) {
        var ticketStatus = $("#managerTicketStatus").val() || "OPENED";
        var orderBy = $("#managerTicketorderBy").val() || "DESCENDING";
        var search = $("#manager-ticket-search-input").val() || "";
        var pageSize = $("#manager-ticket-content-area .manager-ticket-page-size").val() || "25";

        var searchType = $("#managersearchType").val();
        var searchTerm = "";
        if (searchType == "PARTNER_NAME") {
                searchTerm = $("#partner-name-input").val() || "";
        } else if (searchType == "TICKET_ID") {
                searchTerm = $("#search-by-ticketId").val() || "";
        }

        var url = context + "/cs/managerTicket-content?ticketStatus=" + encodeURIComponent(ticketStatus)
                + "&orderby=" + encodeURIComponent(orderBy)
                + "&page=" + (page || 0)
                + "&pageSize=" + pageSize
                + "&search=" + encodeURIComponent(search);

        if (searchType && searchType != "") {
                url += "&ticketSearchType=" + encodeURIComponent(searchType) + "&searchTerm=" + encodeURIComponent(searchTerm);
        }

        // Show/hide clear button
        if (search && search != "") {
                $("#manager-ticket-search-clear").show();
        } else {
                $("#manager-ticket-search-clear").hide();
        }

        doGetAjaxRequestHandler(url, function(response) {
                $('#manager-ticket-content-area').html(response);
        });
}

function refreshPartnerTicketTable() {
        var ticketStatus = $("#managerTicketStatus").val() || "OPENED";
        var orderBy = $("#managerTicketorderBy").val() || "DESCENDING";

        var searchType = $("#managersearchType").val();
        var searchTerm = "";
        if (searchType == "PARTNER_NAME") {
                searchTerm = $("#partner-name-input").val() || "";
        } else if (searchType == "TICKET_ID") {
                searchTerm = $("#search-by-ticketId").val() || "";
        }

        var url = context + "/cs/myPartyTicket-content?ticketStatus=" + encodeURIComponent(ticketStatus)
                + "&orderby=" + encodeURIComponent(orderBy);

        if (searchType && searchType != "") {
                url += "&ticketSearchType=" + encodeURIComponent(searchType) + "&searchTerm=" + encodeURIComponent(searchTerm);
        }

        doGetAjaxRequestHandler(url, function(response) {
                $('#partner-ticket-content-area').html(response);
        });
}