HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/buyercall_forms/buyercall/buyercall/assets/components/sms/sms_dashboard.js
var utils = require('../utils');
var moment = require('moment');
var LeadCallView = require('../lead-call');

const SMS_CSV_URL = `//${appConfig.server_url}/sms/csv`;
const SMS_CALL_DETAILS = `//${appConfig.server_url}/sms/filteroptions`;

var sms = {

    tableApi: null,

    fromDate: null,

    ogFromDate: null,

    toDate: null,

    ogToDate: null,

    frDirectionObject: null,
    nwDirectionObject: null,

    frLeadSourceObject: null,
    nwLeadSourceObject: null,

    frCallStatusObject: null,
    nwCallStatusObject: null,

    frTypeObject: null,
    nwTypeObject: null,


    searchUrl: "",

    btnReset: false,

    gloIsPartnerRole: false,

    init: function() {
        var loThat = this;

        // Determine if user is super user and the role they have
        if ($('#superUserType').length == 1) {
            const roles = ['partner', 'limitsysadmin']
            if (roles.includes($('#superUserType').val())) {
                loThat.gloIsPartnerRole = true
            }
        }

        //Define start and end date
        this.ogFromDate = moment().subtract(1, "month");
        this.ogToDate = moment();
        this.fromDate = this.ogFromDate;
        this.toDate = this.ogToDate;

        //Load content and events
        loThat.loadTable(loThat.setTableUrl());
        loThat.loadDropDownFilterOptions();
        loThat.loadDatePickers();
        loThat.setEvents();
        loThat.setTableUrl();
        loThat.loadStyles();
    },

    getFilter: function(paFilter) {
        var loThat = this,
            evalObject = null;

        if (paFilter === "call_source") {
            evalObject = loThat.frLeadSourceObject;
        } else
        if (paFilter === "call_status") {
            evalObject = loThat.frCallStatusObject;
        } else
        if (paFilter === "direction") {
            evalObject = loThat.frDirectionObject;
        } else
        if (paFilter === "type") {
            evalObject = loThat.frTypeObject;
        }

        if (evalObject === null || evalObject === undefined || evalObject.id === undefined) {
            return "null";
        }
        else {
            return evalObject.id;
        }
    },

    getFromDateFilter: function() {
        var loThat = this;

        return loThat.fromDate.format("MMDDYYYY");
    },

    getToDateFilter: function() {
        var loThat = this;

        return loThat.toDate.format("MMDDYYYY");
    },

    loadTable: function(paLeadUrl) {
        spinnerAdded();
        var loThat = this;
        var loButtons = [];

        if (!loThat.gloIsPartnerRole) {
            loButtons = [{
                text: "Download csv",
                className: "btn-primary btn btn-csv-dl",
                action: function (e, dt, node, config) {
                    var searchOptions = {
                        search: dt.ajax.params().search,
                        df: loThat.getFromDateFilter(),
                        dt: loThat.getToDateFilter(),
                        tp: loThat.getFilter("type"),
                        so: loThat.getFilter("call_source"),
                        st: loThat.getFilter("call_status"),
                        dn: loThat.getFilter("direction")
                    },
                    queryString = $.param(searchOptions),
                    url = `${SMS_CSV_URL}?${queryString}`;
                    window.open(url);
                }
            }]
        } else {
            loButtons = [{
                text: "Restricted",
                className: "btn-primary btn disabled"
            }]
        }

        App.datatables();

        loThat.tableApi = $("#leads-datatable").DataTable({
            buttons: loButtons,
            dom: "<'row'<'col-sm-3 col-md-3 col-lg-2'B><'col-sm-2 col-lg-2'l><'col-xs-12 col-sm-7 col-md-7 col-lg-8 datatables-padding text-right'f>>" +
                 "<'row'<'col-sm-12't>>" +
                 "<'row'<'col-sm-5'i><'col-sm-7'rp>>",
            columns: [
                {
                    data: null,
                    render: function (data, type, row, meta) {
                        return loThat.tableApi.page.info().start + meta.row + 1;
                    },
                    searchable: false,
                    orderable: false
                },    // No
                {
                    data: 1,
                    className: "text-center",
                    render: function (text) {
                        if (text.length > 0) {
                            text = text.toUpperCase();
                        }

                        return text;
                    }
                }, // Type
                {
                    data: 2,
                    render: utils.formatNumber
                }, // From
                {
                    data: 3,
                    render: utils.formatNumber
                }, // To
                {
                    width: "25%",
                    data: 4,
                    render: function (message) {
                        if (message === 'Restricted') {
                            return 'Restricted';
                        } else {
                            return message;
                        }
                    }
                }, // Message
                {
                    data: 5,
                    searchable: false,
                    render: function (date) {
                        return `<time datetime='${date}'>${moment(new Date(date)).fromNow()}</time>`;
                    }
                },  // Date
                {
                    data: 6
                },  // Direction
                {
                    data: 7
                },  // Lead Source
                {
                    data: 8,
                    className: "text-center",
                    render: function (text) {
                        if (text.length > 0) {
                            text = text.toUpperCase();
                        }

                        var classes = {
                            "SENT": "label-success",
                            "RECIEVED": "label-primary",
                            "RECEIVED": "label-primary",
                        };
                        if (!(text in classes)) {
                            text = "UKNOWN";
                        }

                        return `<span class="label ${classes[text]}" title="">${text}</span>`;
                    }
                }, // Status
                {
                    data: 9,
                    render: function (data, visible, row) {
                        if (row[9].length && row[11].length) {
                            contactName = row[9] + ' ' + row[11];
                        } else if (row[9].length && !row[11].length)  {
                            contactName = row[9]
                        } else {
                            contactName = ''
                        }
                        var loLeadName = contactName,
                            loContactId = row[10];

                        return '<a href="/contacts/edit/' + loContactId +'" title="Contact Details" data-toggle="tooltip">' + loLeadName + '</a>';
                    }


                }, // Lead
                {
                    data: "0",
                    searchable: false,
                    orderable: false,
                    className: "text-center",
                    render: function (id, data, row) {
                       var contact_id = row[10];
                       if (loThat.gloIsPartnerRole) {
                            return '<a href="#" class="btn btn-secondary" aria-expanded="true" disabled> Restricted </a>';
                       } else {
                           return '<div class="dropdown">' +
                                '<a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="true" > Actions ' +
                                    '<b class="caret"></b>' +
                                '</a>' +
                                '<ul class="sms-action-menu dropdown-menu">' +
                                    '<li><a href="/sms/edit/' + id +'" title="Edit details">Edit</a></li>' +
                                    '<li><a href="" class="btn-lead-call" data-lead-id="' + contact_id +'" title="Call" data-toggle="modal" data-target="#myModal">Call</a></li>'  +
                                    '<li><a href="" class="btn-lead-sms" data-sms-id="' + contact_id +'" title="SMS">SMS</a></li>' +
                                '</ul>' +
                            '</div>';
                       }
                    }
                }
            ],
            "initComplete": function( settings, json ) {
                var input = $('.dataTables_filter input').unbind(),
                    self = this.api(),
                    $searchButton = $('<a>')
                               .text('search')
                               .click(function() {
                                  self.search(input.val()).draw();
                                  spinnerAdded();
                               }),
                    $clearButton = $('<a>')
                               .text('clear')
                               .click(function() {
                                  input.val('');
                                  $searchButton.click();
                               })

                    $(document).keypress(function (event) {
                        if (event.which == 13) {
                            $searchButton.click();
                        }
                    });
                if (!$(".tbl-search-btn").length) {
                    $('.dataTables_filter').append($searchButton, $clearButton);
                    $("#leads-datatable_filter a").addClass("btn btn-primary btn-default tbl-search-btn");
                    $("#leads-datatable_filter span i").remove();
                }
                if (loThat.objectEmpty(json.graphTotal) && loThat.objectEmpty(json.graphInbound) && loThat.objectEmpty(json.graphOutbound) && loThat.objectEmpty(json.graphPoints)) {
                    $(".feedback-section").hide();
                    $("#leadLineChart").html("");
                } else {
                    $(".feedback-section").show();
                }

                /*$(".btn-lead-call").off().on("click", function(e) {
                    var id = this.getAttribute("data-lead-id");
                    new LeadCallView({
                            leadCall: true,
                            callId: id
                         }).render();
                    e.preventDefault();
                });

                $(".btn-lead-sms").off().on("click", function(e) {
                    var leadId = this.getAttribute("data-sms-id");
                    $("#smsModalData").val(leadId);
                    e.preventDefault();
                    $("#mySms").modal();
                });*/
              }   ,
            "drawCallback": function() {
                $(".btn-lead-call").off().on("click", function(e) {
                    var id = this.getAttribute("data-lead-id");
                    new LeadCallView({
                        leadCall: true,
                        callId: id
                    }).render();
                    e.preventDefault();
                });

                $(".btn-lead-sms").off().on("click", function(e) {
                    var leadId = this.getAttribute("data-sms-id");
                    $("#smsModalData").val(leadId);
                    e.preventDefault();
                    $("#mySms").modal();
                });

                spinnerRemoved();
            },
            "order": [[ 5, "desc" ]],
            "language": {
                "lengthMenu": 'Display <select class="form-control dataTables-records-length-select">'+
                '<option value="30"> 30</option>'+
                '<option value="40"> 40</option>'+
                '<option value="50"> 50</option>'+
                '<option value="100"> 100</option>'+
                '</select> records'
            },
            "pageLength": 50,
            "processing": false,
            "serverSide": true,
            "ajax": paLeadUrl
        });

        loThat.loadStyles();
        loThat.tableApi.on("xhr", function(e, settings, json) {
            if (json !== undefined && json !== null) {
                var graphTotal = json.graphTotal;
                var graphInbound = json.graphInbound;
                var graphOutbound = json.graphOutbound;

                loThat.refreshGraph(graphTotal, graphInbound, graphOutbound, json.graphPoints);
                loThat.loadSideBarTexts(
                    json.messages,
                    json.unique_messages,
                    json.inbound_messages,
                    json.inbound_percentage,
                    json.outbound_messages,
                    json.outbound_percentage
                );
            }
        });
    },

    loadDropDownFilterOptions: function() {
        var loThat = this;

        $.ajax({
           url: `${SMS_CALL_DETAILS}`,
           type: "GET",
           dataType: "json",
           success: function(response) {
                loThat.populateDropDowns('cbSource', response.source_data, 'call_source');
                loThat.populateDropDowns("cbStatus", response.status_data, "call_status");
           }
        });
    },

    loadDatePickers: function() {
        var loThat = this;

        $("#date-from").datetimepicker({
            format: "MM/DD/YYYY",
            icons: {
                time: "fa fa-clock-o",
                date: "fa fa-calendar",
                up: "fa fa-chevron-up",
                down: "fa fa-chevron-down",
                previous: "fa fa-chevron-left",
                next: "fa fa-chevron-right",
                today: "fa fa-screenshot",
                clear: "fa fa-trash",
                close: "fa fa-remove",
                inline: true
            },
            defaultDate: loThat.fromDate
         });

        $("#date-to").datetimepicker({
            format: "MM/DD/YYYY",
            icons: {
                time: "fa fa-clock-o",
                date: "fa fa-calendar",
                up: "fa fa-chevron-up",
                down: "fa fa-chevron-down",
                previous: "fa fa-chevron-left",
                next: "fa fa-chevron-right",
                today: "fa fa-screenshot",
                clear: "fa fa-trash",
                close: "fa fa-remove",
                inline: true
            },
            defaultDate: loThat.toDate
         });
    },

    //General UI events for selecting the filters etc
    setEvents: function() {
        var loThat = this;
        var loCurrentDate = moment();

        $("#date-from").on("dp.change", function(ev) {
            if (ev.date !== null && ev.date !== undefined) {
                loThat.fromDate = ev.date;
                if (loThat.btnReset === false) {
                    loThat.tableApi.destroy();
                    loThat.loadTable(loThat.setTableUrl());
                }
            }
        });

        $("#date-to").on("dp.change", function(ev) {
            if (ev.date !== null && ev.date !== undefined) {
                loThat.toDate = ev.date;
                if (loThat.btnReset === false) {
                    loThat.tableApi.destroy();
                    loThat.loadTable(loThat.setTableUrl());
                }
            }
        });

        $(".btn-short-today").on("click", function(ev) {
            loThat.btnReset = false
            $("#date-from").data("DateTimePicker").date(loCurrentDate);
            $("#date-to").data("DateTimePicker").date(loCurrentDate);
            loThat.btnReset = true
        });

        $(".btn-short-week").on("click", function(ev) {
            loThat.btnReset = false
            $("#date-from").data("DateTimePicker").date(moment().subtract(7,"d"));
            $("#date-to").data("DateTimePicker").date(loCurrentDate);
            loThat.btnReset = true
        });

        $(".btn-short-month").on("click", function(ev) {
            $("#date-from").data("DateTimePicker").date(loThat.getFirstDayOfMonth());
            $("#date-to").data("DateTimePicker").date(loThat.getLastDayOfMonth());
        });

        $(".btn-short-year").on("click", function(ev) {
            loThat.btnReset = false
            $("#date-from").data("DateTimePicker").date(loThat.getFirstDayOfYear());
            $("#date-to").data("DateTimePicker").date(loThat.getLastDayOfYear());
            loThat.btnReset = true
        });

        $(".btn-additional-filters").on("click", function(ev) {
            $("#myLeadFilterModal").modal("show");
        });

        $("#btnApply").on("click", function(ev) {
            //Set new filters

            if (loThat.nwLeadSourceObject !== null) {
                loThat.frLeadSourceObject = loThat.nwLeadSourceObject;
            }

            if (loThat.nwCallStatusObject !== null) {
                loThat.frCallStatusObject = loThat.nwCallStatusObject;
            }

            if (loThat.nwTypeObject !== null) {
                loThat.frTypeObject = loThat.nwTypeObject;
            }

            if (loThat.nwDirectionObject !== null) {
                loThat.frDirectionObject = loThat.nwDirectionObject;
            }

            $("#myLeadFilterModal").modal("hide");

            //Apply new filters
            loThat.reloadTable();
        });

        $("#btnCancel").on("click", function(ev) {
            if (loThat.nwLeadSourceObject !== undefined && loThat.nwLeadSourceObject !== null) {
                if (loThat.frLeadSourceObject !== undefined && loThat.frLeadSourceObject !== null) {
                    $("#cbSource").val(loThat.frLeadSourceObject.name);
                } else {
                    $("#cbSource").val("---");
                }
            }

            if (loThat.nwCallStatusObject !== undefined && loThat.nwCallStatusObject !== null) {
                if (loThat.frCallStatusObject !== undefined && loThat.frCallStatusObject !== null) {
                    $("#cbStatus").val(loThat.frCallStatusObject.name);
                } else {
                    $("#cbStatus").val("---");
                }
            }

            if (loThat.nwTypeObject !== undefined && loThat.nwTypeObject !== null) {
                if (loThat.frTypeObject !== undefined && loThat.frTypeObject !== null) {
                    $("#cbType").val(loThat.frTypeObject.name);
                } else {
                    $("#cbType").val("---");
                }
            }

            if (loThat.nwDirectionObject !== undefined && loThat.nwDirectionObject !== null) {
                if (loThat.frDirectionObject !== undefined && loThat.frDirectionObject !== null) {
                    $("#cbDirection").val(loThat.frDirectionObject.name);
                } else {
                    $("#cbDirection").val("---");
                }
            }

            loThat.nwDirectionObject = null;
            loThat.nwLeadSourceObject = null;
            loThat.nwCallStatusObject = null;
            loThat.nwTypeObject = null;
        });

        $("#btnResetFilters").on("click", function(ev) {
            loThat.btnReset = true;
            // Reset date filters
            $("#date-from").data("DateTimePicker").date(loThat.ogFromDate);
            $("#date-to").data("DateTimePicker").date(loThat.ogToDate);

            loThat.frDirectionObject = null;
            loThat.nwDirectionObject = null;

            loThat.frLeadSourceObject = null;
            loThat.nwLeadSourceObject = null;

            loThat.frCallStatusObject = null;
            loThat.nwCallStatusObject = null;

            loThat.frTypeObject = null;
            loThat.nwTypeObject = null;

            $("#cbDirection, #cbSource, #cbStatus, #cbType").val("---");

            loThat.reloadTable();
        });
        $("#date-from").on("click", function(ev) {
            if (loThat.btnReset === true) {
                loThat.btnReset = false;
            }
        });
        $("#date-to").on("click", function(ev) {
            if (loThat.btnReset === true) {
                loThat.btnReset = false;
            }
        });
        $("#cbType").on("change", function(ev) {
            var loItem = $("#cbType option:selected" );

            loThat.nwTypeObject = {
                id: (loItem.attr("id") == -1) ? null : loItem.attr("id"),
                name: loItem.text()
            };
        });

        $("#cbDirection").on("change", function(ev) {
            var loItem = $("#cbDirection option:selected" );

            loThat.nwDirectionObject = {
                id: (loItem.attr("id") == -1) ? null : loItem.attr("id"),
                name: loItem.text()
            };
        });
    },

    loadStyles: function() {
         $("#leads-datatable_filter label").addClass("form-group");
         $("#leads-datatable_length label").addClass("form-group");
         $(".dataTables_filter input").attr("placeholder", "Search Records");
    },

    loadSideBarTexts: function(paMessages, paUniqueMessages, paInMessages, paInPercent, paOutMessages, paOutPercent) {
        $(".total-messages").html(paMessages + "<graph> " + paUniqueMessages + " unique messages</graph>");
        $(".inbound-messages").html(paInMessages + "<graph> "+ paInPercent +"% of all messages </graph>");
        $(".outbound-messages").html(paOutMessages + "<graph> "+ paOutPercent +"% of all messages </graph>");
    },

    refreshGraph: function(paTotal, paInbound, paOutbound, paLabels) {
        var loWidth = window.innerWidth,
            loGraphHeight =  400,
            loRightBuffer = 40,
            loChartOffset = 60,
            loLabelOffset = 2,
            loXOffset = -10,
            loYOffset = 10,
            loFullWidth = false;

        if (loWidth < 640) {
            loRightBuffer = 5;
            loChartOffset = 12;
            loLabelOffset = 6;
            loXOffset = 0;
            loYOffset = 0;
            $(".graph-section").css("padding-left", 0).css("padding-right", 0);
            $(".graph-chart-content").css("padding-left", 0).css("padding-right", 0);
        }

        if (paLabels.length > 1) {
            loFullWidth = true;
        }

        var loChart = new Chartist.Line("#leadLineChart", {
            // Our labels and three data series
            labels:  paLabels,
            series: [
                paTotal,
                paInbound,
                paOutbound
            ]}, {
                fullWidth: loFullWidth,
                chartPadding: {
                    right: loRightBuffer
                },
                // We are setting a few options for our chart and override the defaults
                // Set hight of the chart
                height: loGraphHeight,
                // Don't draw the line chart points
                showPoint: true,
                // Disable line smoothing
                lineSmooth: false,
                // X-Axis specific configuration
                axisX: {
                    labelOffset: {
                      x: loXOffset,
                      y: loYOffset
                    },
                    // We can disable the grid for this axis
                    showGrid: true,
                    // and also don't show the label
                    showLabel: true,
                    labelInterpolationFnc: function skipLabels(value, index, labels) {
                      if (labels.length > 15) {
                        return index % loLabelOffset  === 0 ? value : null;
                      } else {
                        return value;
                      }
                    }
                },
                // Y-Axis specific configuration
                axisY: {
                    // Lets offset the chart a bit from the labels
                    low: 0,
                    offset: loChartOffset,
                    // The label interpolation function enables you to modify the values
                    // used for the labels on each axis. Here we are converting the
                    // values into million pound.
                    labelInterpolationFnc: function(value) {
                      return value;
                    },
                    onlyInteger: true
                }
            });
    },

    reloadTable: function() {
        var loThat = this;

        loThat.tableApi.destroy();
        //loThat.tableApi.fnDestroy();
        loThat.loadTable(loThat.setTableUrl());
    },

    populateDropDowns: function(paControl, paDict, paShortName) {
        var loThat = this;
        var loHtml = "";

        loHtml = loHtml + '<option id="' + -1 +'" class="'+paShortName+' ">---</option>';

        for (var lpItem in paDict) {
            if (paDict.hasOwnProperty(lpItem)) {
                loHtml = loHtml + '<option class="'+paShortName+'" id="'+ lpItem +'">'+ paDict[lpItem] +'</option>';
            }
        }

        if (paShortName === "call_source") {
            $("#" + paControl).html(loHtml).on("change", function(ev) {
                var loItem = $(this).children(":selected");

                loThat.nwLeadSourceObject = {
                    id: (loItem.attr("id") == -1) ? null : loItem.attr("id"),
                    name: loItem.val()
                };
            });
        }

        if (paShortName === "call_status") {
            $("#" + paControl).html(loHtml).on("change", function(ev) {
                var loItem = $(this).children(":selected");

                loThat.nwCallStatusObject = {
                    id: (loItem.attr("id") == -1) ? null : loItem.attr("id"),
                    name: loItem.val()
                };
            });
        }
    },

    setTableUrl: function() {
        var loThat = this,
            loUrl = "/sms/data",
            df = "?df=",
            dt = "dt=",
            dn = "dn=",
            so = "so=",
            st = "st=",
            tp = "tp=";

        df += loThat.fromDate.format("MMDDYYYY") + "&";
        dt += loThat.toDate.format("MMDDYYYY") + "&";
        dn += loThat.getFilter("direction") + "&";
        so += loThat.getFilter("call_source") + "&";
        st += loThat.getFilter("call_status") + "&";
        tp += loThat.getFilter("type");

        loUrl += df + dt + dn + so + st + tp;
        loThat.searchUrl = loUrl;

        return loUrl;
    },

    objectEmpty: function(paObject) {
        if (paObject === null || paObject === undefined || paObject.length == 0)
            return true;
        else
            return false;
    },

    getFirstDayOfMonth: function() {
        var loDate = new Date(),
            loYear = loDate.getFullYear(),
            loMonth = loDate.getMonth();

        return moment(new Date(loYear, loMonth, 1));
    },

    getLastDayOfMonth: function() {
        var loDate = new Date(),
            loYear = loDate.getFullYear(),
            loMonth = loDate.getMonth();

        return moment(new Date(loYear, loMonth + 1, 0));
    },

    getFirstDayOfYear: function() {
        var loThisYear = (new Date()).getFullYear();
        var loStart = new Date("1/1/" + loThisYear);

        return moment(loStart.valueOf());
    },

    getLastDayOfYear: function() {
        var loThisYear = (new Date()).getFullYear();
        var loEnd = new Date("12/31/" + loThisYear);

        return moment(loEnd.valueOf());
    }
};

// function used to add spinner loader
function spinnerAdded() {
    document.getElementById("loaderContainer").style.display = "block";
    document.getElementById("loader").style.display = "block";
    document.getElementById("postLoader").style.display = "none";
}//end add spinner loader function
// function used to remove spinner loader
function spinnerRemoved() {
    document.getElementById("loaderContainer").style.display = "none";
    document.getElementById("loader").style.display = "none";
    document.getElementById("postLoader").style.display = "block";
}//end remove spinner loader function

$(document).ready(function() {
    sms.init();
});