troubleshooting Question

Where is this text coming from?

Avatar of Bruce Gust
Bruce GustFlag for United States of America asked on
Node.jsJavaScript
3 Comments1 Solution73 ViewsLast Modified:
I'm working on an app that's using DateRangePicker...

There's been more than one third party contractor involved and I say that because of the way the formatting changes from page to page. My task is to institute some uniformity and I'm stuck.

Here's the dilemma:

The Dashboard:DateRangePicker

screenshot of dashboard
The twig file that goes along the Dashboard looks like this (this is just the relevant part):

 <div class="row filter-widget">
                <div class="col"><h4>Most Active</h4></div>
                <div class="col right-padding">
                    <form class="form-inline float-right" action="/dashboard/activitychart" data-chart-target="activityChart">                       
                        <div style="cursor: pointer;" class="form-control text-muted date-range" data-saved="{{dashboard_settings.most_active.range}}" onclick="dateRangeSelect('index3')">
                            <div style="margin-top: 3px;">
                                <i class="fa fa-calendar"></i>&nbsp;
                                <span style="padding-right: 30px;"></span> <i class="fa fa-caret-down"></i>
                            </div>                
                        </div>
                        <input type="text" style="display:none;"  placeholder="Date Range" name="date" required />

Open in new window


There's a JS file that goes along with this page. I have it here in its entirety ,but I'm looking at line #34.

var colors = [
    '#002878',
    '#0098aa',
    '#41ad49',
    '#002878',
    '#0098aa',
    '#41ad49',
    '#002878',
    '#0098aa',
    '#41ad49',
    '#002878',
    '#0098aa',
    '#41ad49',
    '#002878',
    '#0098aa',
    '#41ad49'
];

$(document).ready(function () {
    waterBubblecircleProgressBar();
    circleProgressBar();
    let chart_types = [
        { type: "radar", label: "Radar chart" },
        { type: "horizontalBar", label: "Horizontal bar chart" },
        { type: "polarArea", label: "Polar area chart" },
        { type: "pie", label: "Pie chart" },
        { type: "line", label: "Line chart" },
        { type: "bar", label: "Bar chart" },
        { type: "doughnut", label: "Doughnut chart" },
        { type: "funnel", label: "Funnel Chart" }
    ];
    var start = moment().subtract(29, 'days');
    var end = moment();
    $('.date-range span').html('Last 30 Days');
    // Info: https://www.sisense.com/blog/calculate-mtd-qtd-ytd/
    let date_ranges = {
        'Today': [moment(), moment()],
        'Past Week': [moment().subtract(6, 'days'), moment()],
        'Month To Date (MTD)': [moment().startOf('month'), moment()], // ? From beginning of the Month until day of Today
        'Quarter To Date (QTD)': [moment().startOf('quarter'), moment()], // ? From beginning of the Quarter until day of Today// Current Quarter: moment().startOf('quarter'), 1st Quarter: moment().startOf('year').startOf('quarter')
        'Year To Date (YTD)': [moment().startOf('year'), moment()], // - YTD ? From beginning of the Year until day of Today
        'Custom Range': 'custom'
        //'Yesterday': [moment().subtract(1, 'days'), moment()],
        //'Last 7 Days': [moment().subtract(6, 'days'), moment()],
        //'Last 30 Days': [moment().subtract(29, 'days'), moment()],
        //'Last 60 Days': [moment().subtract(59, 'days'), moment()],
        //'Last 90 Days': [moment().subtract(89, 'days'), moment()],
        //'This Month': [moment().startOf('month'), moment().endOf('month')],
        //'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
        //'Last 1 Year': [moment().subtract(1, 'year'), moment()],
        //'Last 2 Years': [moment().subtract(2, 'year'), moment()],
        //'Last 3 Years': [moment().subtract(3, 'year'), moment()],
        //'All': [moment().subtract(20, 'year'), moment().add(10, 'years')]
    };
    $.get('/dashboard/userslist', {}, (rows) => {       
        if (rows.error) { CAMS.alert('Error', rows.error, 'error'); }
        let users = rows.members;
        let smTeam = [];
        let sm = users.filter(x => x.role === 'Sales Manager');
        if (sm.length > 0) { sm[0].users.forEach((smu) => { if (smu.team) { smu.team.forEach((smt) => { smTeam.push(smt._id); }); } }); }

        $('.filter-widget').each(function () {
            let $this = $(this);
            let $chartType = $this.find('.chart-type');//$this.attr('data-chart-target');
            chart_types.forEach((item) => {
                let defaultSelected = "";                
                if ($chartType.attr('data-default') == item.type) {
                    defaultSelected = "selected";
                }                
                $chartType.append('<option value="' + item.type + '" ' + defaultSelected + '>' + item.label + '</option>');
            });
            if ($chartType.attr('data-saved')) {
                $chartType.find('option[value="' + $chartType.attr('data-saved') + '"]').attr('selected', 'selected');
            }

            $chartType.on('change', function () {
                $this.find('form').submit();
            });
            $this.find('.user-select').on('change', function () {
                $this.find('form').submit();
            });
            
            users.forEach((items) => {
                if (items.role == 'Sales Manager') {
                    items.users.forEach((user) => {
                        let managerOptn = '<option value="' + user._id + '" ' + ($this.find('.user-select').attr('data-me') === user._id ? 'selected="selected"' : '') + ' data-avatar="' + user.avatar + '" data-role="' + user.role + '" style="display:none;">' + user.name + '</option>';
                        if (user.team) {
                            if (user.team.length > 0) {
                                let optn = '';
                                user.team.forEach((team) => {
                                    optn = optn + '<option value="' + team._id + '" ' + ($this.find('.user-select').attr('data-me') === team._id ? 'selected="selected"' : '') + ' data-avatar="' + team.avatar + '" data-role="' + team.role + '">' + team.name + '</option>';
                                });                                
                                $this.find('.user-select').append('<optgroup title="' + user.name + '" label="' + user.name + '">' + managerOptn + optn + '</optgroup>');
                            } else {
                                $this.find('.user-select').append('<optgroup title="' + user.name + '" label="' + user.name + '">' + managerOptn +'</optgroup>');
                                //$this.find('.user-select').append('<option value="' + user._id + '" ' + ($this.find('.user-select').attr('data-me') === user._id ? 'selected="selected"' : '') + ' data-avatar="' + user.avatar + '" data-role="' + user.role + '">' + user.name + '</option>');//.trigger('change');
                            }
                        } else {
                            //$this.find('.user-select').append('<option value="' + user._id + '" ' + ($this.find('.user-select').attr('data-me') === user._id ? 'selected="selected"' : '') + ' data-avatar="' + user.avatar + '" data-role="' + user.role + '">' + user.name + '</option>');//.trigger('change');
                        }
                    });                                        
                } else {
                    let optn = '';
                    items.users.forEach((user) => {
                        if (smTeam.indexOf(user._id) === -1) {
                            optn = optn + '<option value="' + user._id + '" ' + ($this.find('.user-select').attr('data-me') === user._id ? 'selected="selected"' : '') + ' data-avatar="' + user.avatar + '" data-role="' + user.role + '">' + user.name + '</option>';//.trigger('change');
                        }                        
                    });
                    $this.find('.user-select').append('<optgroup title="MISCELLANEOUS" label="MISCELLANEOUS">' + optn + '</optgroup>');
                }
                
            });
            let _saved_users = $this.find('.user-select').attr('data-saved') ? $this.find('.user-select').attr('data-saved').split(',') : [];
            _saved_users.forEach((_id) => {
                if($this.find('.user-select').find('option[value="' + _id + '"]')) { $this.find('.user-select').find('option[value="' + _id + '"]').attr('selected','selected'); } 
            });
            //$this.find('.user-select').select2MultiCheckboxes({
            //    placeholder: "Choose multiple elements"
            //});
            //$this.find('.user-select').multiselect({
            //    templates: {
            //        maxHeight: true,
            //        li: '<li><a href="javascript:void(0);"><label class="pl-2"></label></a></li>'
            //    }
            //});
            $this.find('.user-select').multipleSelect({
                multiple: true, multipleWidth: 62,
                filter: true, width: '100%', 
                openOnHover: false, 
                textTemplate: function ($el) {
                    let avatar = $el.attr('data-avatar') === "undefined" ? 'https://ui-avatars.com/api/?name=' + $el.html() + '&background=' + getRandomColor() + '&size=200&color=000000' : $el.attr('data-avatar');
                    return (typeof $el.attr('data-avatar') != 'undefined' ? '<img src="' + avatar + '" style="width:26px;" class="img-thumbnail rounded" title="' + $el.html() + '"/>' : '') + $el.html();
                }
            });
            
            if ($this.find('.date-range').attr('data-saved')) {
                $this.find('.date-range span').html($this.find('.date-range').attr('data-saved'));
                let savedRange = date_ranges[$this.find('.date-range').attr('data-saved')];
                if (savedRange) {
                    start = savedRange[0];
                    end = savedRange[1];
                }
            }
            
            $this.find('input[name="date"]').val(moment().startOf('month').format('L') + ' - ' + moment().format('L'));
            let dtConfig = {
                endDate: end,//moment(),
                startDate: start,//moment().startOf('month'),
                minDate: moment().subtract(25, 'years'),
                maxDate: moment().add(25, 'years'),
                periods: [''], // to hide periods
                period: 'day',
                ranges: date_ranges,
                parentElement: $this.closest('.card'),
                anchorElement: $this,
                callback: function (startDate, endDate, period) {
                    let label = startDate.format('L') + ' - ' + endDate.format('L');
                    $this.find('input[name="date"]').val(label);
                    $(this).val(label);
                        if (period == 'day') {
                            label = $this.closest('.card').find('.daterangepicker').find('ul.ranges li.active').text();
                        }
                        else {
                            label = $this.closest('.card').find('.daterangepicker').find('ul.periods li.active').text();
                        }
                        $this.find('.date-range span').html(label);
                        $this.find('.date-range').val(startDate.format('L') + ' - ' + endDate.format('L'));

                    $this.find('.user-select').find('option').removeAttr('selected');
                    $this.find('.user-select').val($this.find('.user-select').attr('data-me'));
                    $this.find('form').submit();
                    return false;
                }
            };
            $this.find('.date-range').daterangepicker(dtConfig);
         
            //Restore defaults
            $this.find('.restore-default').on('click', function () {
                //$this.find('.date-range span').html('Last 30 Days');
                ////$this.find(".date-range").data('daterangepicker');
                //dRange.setStartDate(date_ranges['Last 30 Days'][0]);
                //dRange.setEndDate(date_ranges['Last 30 Days'][1]);
                //$chartType.val($chartType.attr('data-default'));
                //$this.find('form').submit();
            });

            //Form Submit
            $this.find('form').on('submit', function (e) {
                e.preventDefault();                
                let action = $(this).attr('action');
                let targetChartId = $(this).attr('data-chart-target');
                if (typeof action != 'undefined') {
                    let dRange = $this.find('input[name="date"]').val();//.data('daterangepicker');
                    dRange = dRange ? dRange.split('-') : dRange;
                    let sDate = dRange ? dRange[0].trim() : '';
                    let eDate = dRange ? dRange[1].trim() : '';                    
                   
                    let data = {
                        date: [sDate, eDate],
                        user: $this.find('.user-select').val()
                    };
                    data.user = $.unique(data.user);
                    $.post(action, data, function (res) {
                        if (res.error) {
                           // CAMS.alert('Error', res.error, 'error');
                        }
                        saveSettings();
                        if (typeof targetChartId != 'undefined') {
                            if (targetChartId == 'activityStream') {
                                bindTimeLine(targetChartId, res);
                            }
                            else if (targetChartId == 'upcomingTasks') {
                                bindUpcomingTasks(targetChartId, res.data);
                            }else {
                                createChart(targetChartId, $chartType.val(), res.data);
                            }

                        } else {
                            //Other bind
                        }
                    }, 'json').fail(function () {
                        CAMS.alert('Error', 'We encountered an error while trying to process your request. Please refresh the page try again.', 'error');
                    });
                } else {
                    CAMS.alert("Undefined form action.");
                }
            });
            $this.find('form').submit();
        });
        let owned_saved = $('#owned-by').attr('data-saved').split(',');
        users.forEach((items) => {
                if (items.role == 'Sales Manager') {
                    items.users.forEach((user) => {
                        let managerOptn = '<option value="' + user._id + '" data-avatar="' + user.avatar + '" data-role="' + user.role + '" style="display:none;" ' + (owned_saved.indexOf(user._id)>=0?'selected="selected"':'') + '>' + user.name + '</option>';
                        if (user.team) {
                            if (user.team.length > 0) {
                                let optn = '';                                
                                user.team.forEach((team) => {
                                    optn = optn + '<option value="' + team._id + '" data-avatar="' + team.avatar + '" data-role="' + team.role + '" ' + owned_saved.indexOf(team._id)>=0?'selected="selected"':'' + ' >' + team.name + '</option>';
                                });
                                $("#owned-by").append('<optgroup title="' + user.name + '" label="' + user.name + '">' + managerOptn + optn + '</optgroup>');
                            } else {
                                $("#owned-by").append('<optgroup title="' + user.name + '" label="' + user.name + '">' + managerOptn +'</optgroup>');
                                //$this.find('.user-select').append('<option value="' + user._id + '" ' + ($this.find('.user-select').attr('data-me') === user._id ? 'selected="selected"' : '') + ' data-avatar="' + user.avatar + '" data-role="' + user.role + '">' + user.name + '</option>');//.trigger('change');
                            }
                        } else {
                            //$this.find('.user-select').append('<option value="' + user._id + '" ' + ($this.find('.user-select').attr('data-me') === user._id ? 'selected="selected"' : '') + ' data-avatar="' + user.avatar + '" data-role="' + user.role + '">' + user.name + '</option>');//.trigger('change');
                        }
                    });                                        
                } else {
                    let optn = '';
                    items.users.forEach((user) => {
                        if (smTeam.indexOf(user._id) === -1) {
                            optn = optn + '<option value="' + user._id + '" data-avatar="' + user.avatar + '" data-role="' + user.role + '" ' + (owned_saved.indexOf(user._id)>=0?'selected="selected"':'') + '>' + user.name + '</option>';
                        }                        
                    });
                    $("#owned-by").append('<optgroup title="MISCELLANEOUS" label="MISCELLANEOUS">' + optn + '</optgroup>');
                }
                
            });
        //users.forEach((user) => {
        //    $("#owned-by").append('<option value="' + user._id + '" ' + ' data-avatar="' + user.avatar + '">' + user.name + '</option>');//.trigger('change');
        //});
        $("#owned-by").multipleSelect({
            formatSelectAll: function () {return 'All leads/proposals'},
            formatAllSelected: function () {return 'All leads/proposals'},
            multiple: true, multipleWidth: 100,
            filter: true, width: '30%', openOnHover: true,
            textTemplate: function ($el) {
                let avatar = $el.attr('data-avatar') === "undefined" ? 'https://ui-avatars.com/api/?name=' + $el.html() + '&background=' + getRandomColor() + '&size=200&color=000000' : $el.attr('data-avatar');
                return (typeof $el.attr('data-avatar') != 'undefined' ? '<img src="' + avatar + '" style="width:32px;" class="img-thumbnail rounded" title="' + $el.html() + '"/>' : '') + $el.html();
            }
        });
    });
         
    $('[data-toggle="tooltip"]').tooltip();
    function getSettings() {
        try {
            let dashboard_settings = {
                first_widget: {
                    user: $("#owned-by").val().length>0 ? $("#owned-by").val() : ($("#owned-by").attr('data-saved') ? $("#owned-by").attr('data-saved').split(',') : []),
                    range: $('#time-range').val() ? $('#time-range').val() : $('#time-range').attr('data-saved')
                },
                most_active: {
                    range: $('form[data-chart-target="activityChart"]').find('div.date-range').text().trim(),
                    chart_type: $('form[data-chart-target="activityChart"]').find('select.chart-type').val(),
                    user: $('form[data-chart-target="activityChart"]').find('.user-select').val()
                },
                upcoming_tasks: { user: $('form[data-chart-target="upcomingTasks"]').find('.user-select').val() },
                activity_stream: {
                    range: $('form[data-chart-target="activityStream"]').find('div.date-range').text().trim(),
                    user: $('form[data-chart-target="activityStream"]').find('.user-select').val()
                },
                proposal_won: {
                    range: $('form[data-chart-target="winTotalChart"]').find('div.date-range').text().trim(),
                    chart_type: $('form[data-chart-target="winTotalChart"]').find('select.chart-type').val(),
                    user: $('form[data-chart-target="winTotalChart"]').find('.user-select').val()
                },
                won_percentage: {
                    range: $('form[data-chart-target="winPercentChart"]').find('div.date-range').text().trim(),
                    chart_type: $('form[data-chart-target="winPercentChart"]').find('select.chart-type').val(),
                    user: $('form[data-chart-target="winPercentChart"]').find('.user-select').val()
                },
                shortest_sales_cycle: {
                    range: $('form[data-chart-target="salesCycleChart"]').find('div.date-range').text().trim(),
                    chart_type: $('form[data-chart-target="salesCycleChart"]').find('select.chart-type').val(),
                    user: $('form[data-chart-target="salesCycleChart"]').find('.user-select').val()
                }
            };
            return dashboard_settings;
        } catch (e) {
            console.log(e);
        }
    }

    function saveSettings() {
        $.post('/dashboard/settings/save', getSettings(), function (res) {
            if (res.error) {
                CAMS.alert('Error', res.error, 'error');
            }
        }, 'json').fail(function () {
            CAMS.alert('Error', 'We encountered an error while trying to process your request. Please refresh the page try again.', 'error');
        });
    }


    //var charts = {};

    $('.btn-add-company').on('click', function () {
        $(window).trigger('company-form-show', ['new']);
    });
    //$('#chart-type').on('change', function () {
    //    setTimeout(function () {
    //        for (var cId in chartData) {
    //            charts[cId] = createChart($('#' + cId), chartData[cId]);
    //        }
    //    }, 500);
    //});
    let dtConfig_metrics = {
        endDate: end,//moment(),
        startDate: start,//moment().startOf('month'),
        minDate: moment().subtract(25, 'years'),
        maxDate: moment().add(25, 'years'),
        periods: [''], // to hide periods
        period: 'day',
        ranges: {
            'This Year': [moment().startOf('year'), moment().startOf('year')],
            'Previous Year': [moment().subtract(1, 'year'), moment().subtract(1, 'year')],
            'This Month': [moment().startOf('month'), moment().startOf('month')],
            'Previous Month': [moment().subtract(1, 'month'), moment().subtract(1, 'month')],             
            'Custom Range': 'custom'
        },
        parentElement: $('.dashboard-filter-top'),
        anchorElement: $('.dashboard-metrics'),
        callback: function (startDate, endDate, period) {
            let label = startDate.format('L') + ' - ' + endDate.format('L');            
            $(this).val(label);
            if (period === 'day') {
                label = $('.dashboard-metrics').find('.daterangepicker').find('ul.ranges li.active').text();
            }
            else {
                label = $('.dashboard-metrics').find('.daterangepicker').find('ul.periods li.active').text();
            }
            $('.time-range span').html(label);
            $('#time-range').val(label);
            if (label === 'Custom Range') {
                $('#time-range').val(startDate.format('L') + ' - ' + endDate.format('L'));
            }
            $('#dashboard-metrics').submit();
            return false;
        }
    };
    $(".time-range").daterangepicker(dtConfig_metrics);    
    $('#owned-by').on('change', function () {
        $('#dashboard-metrics').submit();       
    });
    $('#dashboard-metrics').on('submit', function (e) {
        e.preventDefault();        
        $('.dashboard-metrics-loading').show();
        $(".activity-top-title").html('');
        let tempa = {};
        $('#owned-by').find('option:selected').each(function () {
            tempa[$(this).attr('data-avatar')] = { name: $(this).text(), avatar: $(this).attr('data-avatar'), role: $(this).attr('data-role') };
        });
        let cu = 0, actTitle = "", showMore = '<a href="javascript:void(0);" class="huser">...[+]</a>';
        $.each(tempa, function (k, v) {
            //$(".activity-top-title").append('<a href="javascript:void(0);" class="user-info" data-toggle="tooltip" data-user-id="' + k + '" title="' + v.name + '(' + v.role + ')"><img src="' + v.avatar + '" width="32px" class="rounded-circle"/></a>&nbsp;|&nbsp;');
            cu = cu + 1;
            //            $(".activity-top-title").append('<span class="' + (cu <= 4 ? 'suser' : 'huser') + '"  style="display:' + (cu <= 4 ? 'block' : 'none') + '"><a href="javascript:void(0);" class="user-info" data-toggle="tooltip" data-user-id="' + k + '" title="' + v.name + '(' + v.role + ')">' + v.name + '</a>&nbsp;|&nbsp;</span>');
            actTitle = actTitle + '<span class="' + (cu <= 4 ? 'suser' : 'huser') + '"  style="' + (cu <= 4 ? '' : 'display:none') + '"><a href="javascript:void(0);" class="user-info" data-toggle="tooltip" data-user-id="' + k + '" title="' + v.name + '(' + v.role + ')">' + v.name + '</a>&nbsp;|&nbsp;</span>';
        });
        $(".activity-top-title").html(actTitle + (cu > 4 ? showMore : ''));
        $(".activity-top-title").find('a.huser').on('click', function () { $(".activity-top-title").find('.huser').show('slow'); $(this).hide(); });
        var filters = { owner: $('#owned-by').val(), _range: $('#time-range').val() };
        if (filters.owner.length > 0 && filters._range.length > 0) {
            saveSettings();
            $.post('/dashboard/filter', filters, function (resp) {
                $('.dashboard-metrics-loading').hide();
                if (resp.error) {
                    return CAMS.alert('Error', resp.msg, 'error');
                }

                var $el, stat;

                // update the total numbers
                //for (var i in resp) {
                //    if (i == 'stats') {
                //        continue;
                //    }

                //    $el = $('.totals-' + i);

                //    if ($el.hasClass('money')) {
                //        $el.html(formatValue(resp.data[i], 'money'));
                //    } else if ($el.hasClass('percent')) {
                //        $el.html(formatValue(resp.data[i], 'percent'));
                //    } else {
                //        $el.html(formatValue(resp.data[i], 'int'));
                //    }
                //}

                // update the stats
                resp.stages.forEach((stage) => {
                    //stat = resp.data.stats[stage];
                    if (stage.key == 'target') {
                        $('.stats-' + stage.key + '-count').text(stage.companies ? stage.companies : '0');
                    } else if (stage.key == 'contact') {
                        $('.stats-' + stage.key + '-count').text(stage.companies ? stage.companies : '0');
                    } else {
                        $('.stats-' + stage.key + '-value').text(stage.value ? number_format(stage.value, 0) : '0');
                        $('.stats-' + stage.key + '-count').text(stage.proposals ? stage.proposals : '0');
                    }
                });
                $('.employers-engaged').text(resp.employersEngaged);
                $('.total-employers').text(resp.totalEmployers);
                $('.market-engagment').attr('data-percent', resp.marketEngagement);
                $('.totals-winPercent').text(resp.winPercent + '%');
                $('.totals-avgWonAmt').text('$' + number_format(resp.avgWonAmt, 1));
                waterBubblecircleProgressBar();
                circleProgressBar();
            }, 'json').fail(function () {
                CAMS.alert('Error', 'An unexpected error was encountered while trying to process your request. Please try again.', 'error');
            });
        }        
    });
    function formatValue(val, formatAs) {
        if (typeof val == 'string') {
            if (val === '' || val == 'Unknown') {
                return 'Unknown';
            }

            val = parseFloat(val);
        }

        switch (formatAs) {
            case 'money':
                return '$' + number_format(val, 2);
                break;

            case 'percent':
                return val.toFixed(1) + '%';
                break;

            case 'proposals':
                val = parseInt(val);
                if (val == 1) {
                    return 1 + ' Proposal';
                } else {
                    return val + ' Proposals';
                }
                break;

            default:
                // int
                return number_format(val, 0);
                break;
        }
    }

    //// simulate an ajax delay
    //setTimeout(function(){
    //  for (var cId in chartData) {
    //    charts[ cId ] = createChart($('#' + cId), chartData[ cId ]);
    //  }
    //}, 500);

    //function createChart($chart, data) {
    //  var labels = [],
    //      dataset = [],
    //      html = '';

    //  for (var i in data) {
    //    html += '<tr><td>' + data[i].userName + '</td><td>' + data[i].total + '</td></tr>';

    //    labels.push( data[i].userName );
    //    dataset.push( data[i].total );
    //  }

    //  var opts = {
    //      type: $('#chart-type option:selected').val(),//'radar',//'bubble',//'horizontalBar',//'polarArea',//'pie',//'radar',//'line',//'bar',//'doughnut',
    //    data: {
    //      labels: labels,
    //      datasets: [{
    //        data: dataset,
    //        backgroundColor: colors
    //      }]
    //    },
    //    options: {
    //      maintainAspectRatio: false,
    //        legend: {
    //            display: false
    //      }
    //    }
    //    };
    //    if ($chart.attr('id') == 'salesCycleChart') {
    //        opts.type = 'line';
    //    }
    //    if ($chart.attr('id') == 'winTotalChart') {
    //        opts.type = 'bar';
    //    }
    //    if ($chart.attr('id') == 'activityChart') {
    //        opts.type = 'horizontalBar';
    //    }
    //    var myChart = new Chart($chart, opts);
    //    myChart.destroy();
    //    myChart = new Chart($chart, opts);
    //    return myChart;
    //  }
    var charts = []; // global
    function createChart(id, type, data) {
        var labels = [],
            dataset = [],
            html = '', dtrows = [];
        let targetTable = id + 'Table';
        //let dtChart = $('#' + targetTable).DataTable({

        //    "dom": "<'row'<'col-sm-12 col-md-12 text-right'p>><'clear'>",
        //    "order": [[1, "desc"]], bRetrieve: true,
        //    "bLengthChange": false,
        //    "bInfo": false,
        //    lengthMenu: [
        //        [5, 10, 25, 50, -1],
        //        ['5', '10', '25', '50', 'Show all']
        //    ],
        //    //"pagingType": "full_numbers",
        //    "pagingType": "customPagination",
        //    "language": {
        //        search: '', searchPlaceholder: "search",
        //        "info": "_START_ to _END_ of _TOTAL_ ",
        //        "paginate": {
        //            "first": "<i class='fas fa-step-backward fa-lg'></i>",
        //            "last": "<i class='fas fa-step-forward fa-lg'></i>",
        //            "next": "<i class='fas fa-caret-right fa-lg'></i>",
        //            "previous": "<i class='fas fa-caret-left fa-lg'></i>"
        //        }
        //    }
        //});
        //dtChart.clear();
        ////var info = dtChart.page.info();
        ////if (typeof info != 'undefined') {
        ////    $('.paginate_button.next').before($('<span>', {
        ////        'text': info.start + ' to ' + info.end + ' of ' + info.pages,
        ////        class: 'cdatatableDetails'
        ////    }));
        ////}        
        for (var i in data) {
            let spans = "";
            if (typeof data[i].activities != 'undefined') {
                data[i].activities.forEach((activity) => {
                    spans = spans + ("<a href='javascript:void(0);' title='" + activity.count + " " + activity.type + "s' data-toggle='tooltip'><i class='fa " + activity.icon + "'></i> " + activity.count + "</a>&nbsp;");
                });
            }
            if (targetTable == 'salesCycleChartTable') {
                //dtChart.row.add([
                //    '<a href="javascript:void(0);"class="user-info" data-user-id="' + data[i]._id + '" data-route="companies">' + data[i].userName + '</a>',
                //    data[i].total + ' Days']).draw(false);
                html += '<tr><td><a href="javascript:void(0);"class="user-info" data-user-id="' + data[i]._id + '" data-route="companies">' + data[i].userName + '</a></td><td>' + data[i].total + ' Days</td></tr>';
            }
            else if (targetTable == 'activityChartTable') {
                //dtChart.row.add([
                //    '<a href="javascript:void(0);"class="user-info" data-user-id="' + data[i]._id + '" data-route="companies">' + data[i].userName + '</a>',
                //    data[i].total,
                //    '<div class="user-icons-activity">' + spans + '</div>'
                //]).draw(false);
                html += '<tr><td><a href="javascript:void(0);"class="user-info" data-user-id="' + data[i]._id + '" data-route="companies">' + data[i].userName + '</a>' +
                    '<td>'+data[i].total+'</td>'+
                    '</td><td><div class="user-icons-activity">' + spans + '</div></td>' +
                    '</tr>';
            }
            else if (targetTable == 'winTotalChartTable') {
                //dtChart.row.add([
                //    '<a href="javascript:void(0);"class="user-info" data-user-id="' + data[i]._id + '" data-route="companies">' + data[i].userName + '</a>',
                //    data[i].total]).draw(false);
                html += '<tr><td><a href="javascript:void(0);"class="user-info" data-user-id="' + data[i]._id + '" data-route="companies">' + data[i].userName + '</a></td><td>' + data[i].total + '</td></tr>';
            }
            else if (targetTable == 'winPercentChartTable') {
                //dtChart.row.add([
                //    '<a href="javascript:void(0);"class="user-info" data-user-id="' + data[i]._id + '" data-route="companies">' + data[i].userName + '</a>',
                //    data[i].total + ' %']).draw(false);
                html += '<tr><td><a href="javascript:void(0);"class="user-info" data-user-id="' + data[i]._id + '" data-route="companies">' + data[i].userName + '</a></td><td>' + data[i].total + ' %</td></tr>';
            }


            let userLabel = data[i].userName;
            labels.push(userLabel);
            dataset.push(data[i].total);
        }
        //if (targetTable != 'activityChartTable') {
        //    $('#' + targetTable).find('tbody').html(html);
        //}
        $('#' + targetTable).find('tbody').html(html);

        $('[data-toggle="tooltip"]').tooltip();
        var config = {
            type: type,//'radar',//'bubble',//'horizontalBar',//'polarArea',//'pie',//'radar',//'line',//'bar',//'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: dataset,
                    backgroundColor: colors
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                legend: {
                    display: false
                }
            }

        };
        if (id == 'funnelChart') {
            let funnelData = $('#funnelChartData').val();
            if (typeof funnelData != 'undefined') {
                let Jsondata = JSON.parse(funnelData);
                if (typeof Jsondata != 'undefined') {
                    config.tooltips = {
                        enabled: true,
                        mode: 'single',
                        callbacks: {
                            label: function (tooltipItems, data) {
                                let _totals = '';
                                if (tooltipItems.xLabel == 'Companies') { _totals = Jsondata.companies.total; }
                                if (tooltipItems.xLabel == 'Proposals') { _totals = Jsondata.proposal.total; }
                                if (tooltipItems.xLabel == 'Won') { _totals = Jsondata.won.total; }
                                return _totals + ' ' + tooltipItems.xLabel;
                            }
                        }
                    };
                }
            }
        }
        if (typeof charts[id] == "undefined") // see if passed id exists
        {
            // doesn't, so create it
            charts[id] = new (function () {
                this.ctx = $("#" + id); // canvas el
                this.chart = new Chart(this.ctx, config);
            })();
            console.log('created chart ' + charts[id].chart.canvas.id);
        }
        else {
            charts[id].chart.destroy(); // "destroy" the "old chart"
            charts[id].chart = new Chart(charts[id].ctx, config); // create the chart with same id and el
            console.log('replaced chart ' + charts[id].chart.canvas.id);
        }
        // just to see all instances
        Chart.helpers.each(Chart.instances, function (instance) {
            console.log('found instance ' + instance.chart.canvas.id);
        });

    }

    let funnelData = $('#funnelChartData').val();
    if (typeof funnelData != 'undefined') {
        let Jsondata = JSON.parse(funnelData);
        if (typeof Jsondata != 'undefined') {
            let data = [
                { userName: 'Companies', total: Jsondata.companies.width },
                { userName: 'Proposals', total: Jsondata.proposals.width },
                { userName: 'Won', total: Jsondata.won.width }
            ];
            createChart('funnelChart', 'bar', data);
        }

    }
    function bindUpcomingTasks(targetElement, data) {
        $('#' + targetElement).html('Processing...');
        if (typeof data != 'undefined') {
            if (data.length > 0) {
                let html = '';
                let filters = {};
                data.reverse().forEach((activity) => {
                    let ktype = activity.type + '|' + activity.icon;
                    filters[ktype] = typeof filters[ktype] == 'undefined' ? 0 : filters[ktype];
                    filters[ktype] = filters[ktype] + 1;
                    let activityIcon = '<i class="fa ' + activity.icon + '" aria-hidden="true"></i>';
                    let activityAvatar = typeof activity.owner.avatar != 'undefined' ? activity.owner.avatar : 'https://ui-avatars.com/api/?name=' + activity.owner.name + '&background=33b5e5&size=64&color=000000';
                    let avatarLink = '<a href="javascript:void(0);" class="user-info" data-user-id="' + activity.owner._id + '" title="' + activity.owner.name + '" data-toggle="tooltip">' +
                        '<img src="' + activityAvatar + '" alt="' + activity.owner.name + '" class="rounded-circle" style="width:16px;"/> ' + activity.owner.name +
                        '</a>';
                    let companyLink = '<a href="javascript:void(0);" class="open-company-details" data-company-id="' + activity.company._id + '" data-route="companies" title="Company" data-toggle="tooltip">' + activity.company.name + '</a>';
                    let proposalLink = '';
                    if (typeof activity.proposal != 'undefined') {
                        proposalLink = '<a href="javascript:void(0);" class="open-proposal-details" data-proposal-id="' + activity.proposal._id + '" data-route="companies">Proposal</a>';
                    }
                    let activityMeta = '';
                    for (var key in activity.meta) {
                        let val = activity.meta[key];
                        activityMeta = activityMeta + '<div class="box-item"><strong>' + key + '</strong>:<span>' + val + '</span></div>';
                    }
                    let taskTitle = '<div class="left-view-time"> <span> ' + activity.prettyDate + '</span> <span>10 Tasks</span></div>';
                    let taskDate = activity.type == 'event' ? '<small title="' + (activity.meta.dates.start.readableDate + ' - ' + activity.meta.dates.end.readableDate) + '" data-toggle="tooltip">' + (activity.meta.dates.start.readableDate + ' - ' + activity.meta.dates.end.readableDate) + '</small>' : '<small title="' + activity.meta.dates.readableDate + '" data-toggle="tooltip">' + activity.meta.dates.prettyDate + '</small>';
                    let taskDetails = activity.type == 'event' ? '<p class="mb-1">' + activity.meta.subject +
                        (activity.meta.location.length > 0 ? '</br/>location: ' + activity.meta.location : '') +
                        (activity.meta.participants.length > 0 ? '</br/>participants: ' + activity.meta.participants : '') +
                        (activity.meta.details.length > 0 ? '</br/>details: ' + activity.meta.details : '') +
                        '</p>' : '<p class="desc">' + activity.meta.notes + '</p>';
                    html = html + '<li class="sl-item animated list-group-item zoomIn li-' + activity.type + '">' +
                        '<div class="row">' +
                        '<div class="sl-left bg-success"> '+ activityIcon +' </div>' +
                        '<div class="col">' +
                        '<div class="d-flex w-100 justify-content-between">' +
                        '<h5 class="mb-1 text-uppercase">' + activity.type + '</h5>' +
                        taskDate +
                        '</div>' +
                        '<small>related to ' + companyLink + (proposalLink.length > 0 ? ',' + proposalLink : '') + '  ' + avatarLink + '</small>' +
                        taskDetails +
                        '</div>' +
                        '</div>' +
                        '</li>';
                });
                let chkfilters = '', totals = 0;
                $.each(filters, function (k, v) {
                    let ktype = k.split('|');
                    totals = totals + v;
                    chkfilters = chkfilters + '<div class="col"><div class="custom-control custom-checkbox">' +
                        '<input type="checkbox" value="' + ktype[0] + '" checked="checked" id="filter-' + ktype[0] + '" class="custom-control-input filter-type"/> ' +
                        '<label class="custom-control-label text-capitalize" for="filter-' + ktype[0] + '"><i class="fa ' + ktype[1] + '"></i> ' + v + ' ' + ktype[0] + '</label>' +
                        '</div></div>';
                });
                $('.tasks-total').html(totals + ' Total ');
                //chkfilters = chkfilters + '<div class="col text-right mr-2">' + totals + ' Total</div>';

                $('#' + targetElement).html('<div class="row">' + chkfilters + '</div><ul class="list-group steamline">' + html + '</ul>');
                $('#' + targetElement).find('.filter-type').on('change', function () {
                    $('#' + targetElement).find('.list-group-item').hide();
                    $('#' + targetElement).find('.filter-type').each(function () {
                        if ($(this).is(':checked') == true) {
                            $('#' + targetElement).find('.li-' + $(this).val()).show('slow');
                        }
                    });

                });
            } else {
                $('#' + targetElement).html('No upcoming tasks found.');
            }
            $('[data-toggle="tooltip"]').tooltip();
        } else {
            $('#' + targetElement).html('No upcoming tasks found.');
        }
    }
    function bindTimeLine(targetElement, data) {
        $('#' + targetElement).html('Processing...');
        if (typeof data != 'undefined') {
            if (data.length > 0) {
                let html = '';
                data.forEach((row) => {
                    let timelineMonth = '<div class="timeline-month" title="' + row._id + '">' +
                        '<div class="timeline-time-view" >' +
                        '<div class="timeline-time-view-inner" title="' + row._id + '">' +
                        '<div class="left-view-time"> <span> ' + row.prettyDate + '</span> <span>' + row.activities.length + ' Entries</span></div> ' +
                        '</div>' +

                        '</div>' +
                        '</div>'
                        //'<div style="height:78px;"></div>'
                        ;
                    let timelineSection = '', timelineIndex = 0;
                    row.activities.forEach((activity) => {
                        let activityMeta = '';
                        timelineIndex = row._id+'-'+( timelineIndex + 1);
                        for (var key in activity.meta) {
                            let val = activity.meta[key];
                            activityMeta = activityMeta + '<div class="box-item"><strong>' + key + '</strong>:<span>' + val + '</span></div>';
                        }
                        let relatedToLink = '';
                        if (typeof activity.proposal != 'undefined') {
                            relatedToLink = '<div class="box-item"><strong>Related to</strong>:' +
                                '<a href="javascript:void(0);" class="open-proposal-details" data-proposal-id="' + activity.proposal._id + '" data-route="companies">Proposal</a>' +
                                '</div>';
                        }
                        let activityAvatar = typeof activity.user.avatar != 'undefined' ? (activity.user.avatar.length == 0 ? 'https://ui-avatars.com/api/?name=' + activity.user.name + '&background=33b5e5&size=64&color=000000' : activity.user.avatar) : 'https://ui-avatars.com/api/?name=' + activity.user.name + '&background=33b5e5&size=64&color=000000';
                        timelineSection = timelineSection +
                            '<div class="timeline-section animated zoomIn">' +
                            //'<span class="stright-line-timeline"></span>'+
                            '<div class="row">' +
                            '<div class="col">' +
                            '<div class="timeline-box">' +
                            '<div class="box-title">' +
                            '<i class="fa ' + activity.icon + '" aria-hidden="true"></i>' +
                            '<a href="javascript:void(0);" class="user-info" data-user-id="' + activity.user._id + '"><img src="' + activityAvatar + '" alt="' + activity.user.name + '" class="rounded" style="width:32px;"/><i>' + activity.user.name + '</i></a>' +
                            '<strong> <a href="javascript:void(0);" data-toggle="collapse" data-target="#timeline-' + timelineIndex + '">' + activity.type + '</a> </strong> <span title="' + activity.date + '" data-format="Y-m-d H: i A" data-toggle="tooltip" data-time="' + activity.date + '">' + activity.prettyDate + '</span>' +
                            '<a href="javascript:void(0);" class="float-right" data-toggle="collapse" data-target="#timeline-' + timelineIndex + '"><i class="fas fa-angle-double-down"></i></a>' +
                            '</div>' +


                            '<div class="box-content collapse" id="timeline-' + timelineIndex + '">' +
                            '<div class="box-item">' +
                            '<strong>Related to</strong>: <a href="javascript:void(0);" class="open-company-details" data-company-id="' + (activity.company ? activity.company._id : '') + '" data-route="companies" title="Company" data-toggle="tooltip"><img class="company-img" src="/assets/images/company-icon.png"> ' + (activity.company ? activity.company.name : '') + '</a>' +
                            '</div>' +
                            '<a class="btn btn-sm btn-default float-right" data-toggle="collapse" href="#actd-' + activity._id + '" role="button" aria-expanded="false" aria-controls="actd-' + activity._id + '">Details</a>' +
                            '<div class="collapse" id="actd-' + activity._id + '">' +
                            activityMeta +
                            '</div>' +
                            relatedToLink +
                            '<div class="clearfix clear-fix"></div>' +
                            '</div>' +



                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '<label class="left-date-row text-right" title="' + activity.date + '"><small>' + activity.readableDate + '<br/>' + activity.prettyDate + '</small></label>' +
                            '</div>'
                            ;
                    });
                    html = html + timelineMonth + timelineSection;
                });
                $('#' + targetElement).html(html);
            } else {
                $('#' + targetElement).html('No activity found.');
            }
            $('[data-toggle="tooltip"]').tooltip();
        } else {
            $('#' + targetElement).html('No activity found.');
        }
    }
    function getRandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
    function waterBubblecircleProgressBar() {
        $(document).find('.waterbubble-circleProgress').each(function () {
            $(this).html('');
            var can = $('<canvas/>', { 'class': 'radHuh', 'name': 'myCanvas' }).prop({ width: 200, height: 200 });
            $(this).append(can);
            var c = can[0].getContext('2d');

            let txtPercent = $(this).attr('data-percent');
            let txtColor = $(this).attr('data-color');
            let colorCode = txtColor == 'success' ? '#01c951' : txtColor == 'warning' ? '#fb3' : txtColor == 'danger' ? '#ff3547' : txtColor == 'primary' ? '#002878' : '#002878';
            let percent = (parseFloat(txtPercent) / 100).toFixed(2);
            let config = {
                // bubble size
                radius: 80,
                // border width
                lineWidth: 2,
                // data to present
                data: parseFloat(percent),//0.12,
                // color of the water bubble
                waterColor: colorCode,
                // text color
               // textColor: '#002878',
                // custom font family
                font: '',
                // show wave
                wave: true,
                // custom text displayed inside the water bubble
                txt: txtPercent + '%',
                // enable water fill animation
                animation: true
            };
            $(this).find('canvas').waterbubble(config);
        });

    }
    function circleProgressBar() {
        $(document).find('.circleProgress').each(function () {
            $(this).html('');
            var can = $('<canvas/>', { 'class': 'radHuh', 'name': 'myCanvas' }).prop({ width: 200, height: 200 });
            $(this).append(can);
            var c = can[0].getContext('2d');
            var spanProcent = $('<span/>', { 'class': 'procent' });
            $(this).append(spanProcent);
            var spanText = $(this).attr('data-text');
            var spanTag = $('<span/>', { 'class': 'circle-progress-text' }).text(spanText);
            $(this).append(spanTag);

            let percent = parseFloat($(this).attr('data-percent')).toFixed();
            let txtPercent = $(this).attr('data-percent');
            let txtColor = $(this).attr('data-color');
            let colorCode = txtColor == 'success' ? '#01c951' : txtColor == 'warning' ? '#fb3' : txtColor == 'danger' ? '#ff3547' : txtColor == 'primary' ? '#002878' : '#002878';
            var posX = can[0].width / 2,
                posY = can[0].height / 2,
                fps = 1000 / 200,
                procent = 0,
                oneProcent = 360 / 100,
                result = oneProcent * percent;//26.5;

            c.lineCap = 'round';
            arcMove();

            function arcMove() {
                var deegres = 0;
                var acrInterval = setInterval(function () {
                    deegres += 1;
                    c.clearRect(0, 0, can[0].width, can[0].height);
                    procent = deegres / oneProcent;

                    spanProcent[0].innerHTML = txtPercent;//procent.toFixed(1);

                    c.beginPath();
                    c.arc(posX, posY, 70, (Math.PI / 180) * 270, (Math.PI / 180) * (270 + 360));
                    c.strokeStyle = '#efefef';
                    c.lineWidth = '10';
                    c.stroke();

                    c.beginPath();
                    c.strokeStyle = colorCode;//'#01c951';
                    c.lineWidth = '10';
                    c.arc(posX, posY, 70, (Math.PI / 180) * 270, (Math.PI / 180) * (270 + deegres));
                    c.stroke();
                    if (deegres >= result) clearInterval(acrInterval);
                }, fps);

            }
        })

    }
});

jQuery(document).ready(function () {
    jQuery('.scrollbar-macosx').scrollbar();
});
/*
$(document).ready(function(){
    $(".date-range").click(function(){
      $(".calender-row").addClass("calenderup");
    });
  });*/
function dateRangeSelect(id) {
    $(".calender-row").removeClass("calenderup");
    $("#" + id).addClass("calenderup");
};

Open in new window


I'm thinking "$('.date-range span').html('Last 30 Days')" is what's producing, "Last 30 Days" on the twig file. But when I attempt to alter the text, nothing changes on the screen.

What am I missing?

I'm wondering if there's not something with DateRangePicker that I'm not aware of, but in any case, I wanted some other eyes on it.

Where's "Last 30 Days" coming from?
ASKER CERTIFIED SOLUTION
Bruce Gust
PHP Developer

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 3 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros