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/blueprints/reports/views.py
import logging as log
import traceback
from flask import (
    Blueprint,
    flash,
    make_response,
    render_template,
    request, redirect, url_for, current_app, jsonify)
from flask_login import login_required, current_user
from functools import wraps
from flask_babel import gettext as _
from sqlalchemy import text, func, and_
from buyercall.extensions import db
from contextlib import closing
from io import StringIO
import csv
from datetime import date
from buyercall.lib.util_datetime import format_date_to_excel
from buyercall.blueprints.reports.models import Report, ReportUserTie
from buyercall.lib.flask_mailplus import _try_renderer_template

reports = Blueprint('reports', __name__, template_folder='templates')


def access_required(report_name):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if current_user is None:
                return redirect(url_for('login', next=request.url))
            links = [link for link in current_user.reports if link.report.name == report_name]
            if len(links) == 0:
                return 'No access to report', 403
            return f(*args, **kwargs)
        return decorated_function
    return decorator


@reports.route('/reports', methods=['GET'])
@login_required
def all_reports():
    reports_list = list(link.report.name for link in current_user.reports)

    if len(reports_list) == 0:
        flash(_('No report were found. Please contact support.'), 'danger')
        return redirect(url_for('user.settings'))

    try:
        daily_report = Report.query.filter(Report.name == 'Daily Leads Report').first()
    except Exception as e:
        log.error("The report does not exist {}".format(traceback.format_exc()))
        flash(_('The report does not exist.'), 'danger')

    try:
        form = ReportUserTie.query.\
            filter(ReportUserTie.user_id == current_user.id, daily_report.id == ReportUserTie.report_id).first()
    except Exception as e:
        log.error("The report does not exist {}".format(traceback.format_exc()))

    return render_template('all_reports.jinja2', reports_list=reports_list, form=form)


# TODO: create report access decorator
@reports.route('/reports/listofinterest/csv', methods=['GET'])
@login_required
@access_required(report_name='List of Interest')
def list_of_interest_csv():
    header = [
        '#', 'id', 'firstname', 'lastname', 'email', 'customer_phonenumber', 'cu_phone', 'question', 'duration (sec)',
        'starttime', 'endtime', 'created_on', 'call_type', 'status', 'progress_status',
        'recording_url', 'notes', 'agent_firstname', 'agent_lastname', 'widget_friendly_name',
        'inbound_friendly_name'
    ]

    params = {'partnership_account_id': current_user.partnership_account_id}

    query = text("""SELECT result.id
        ,result.firstname
        ,result.lastname
        ,result.phonenumber
        ,result.email
        ,result.my_phone
        ,result.question
        ,result.duration
        ,result.starttime
        ,result.endtime
        ,result.created_on
        ,result.call_type
        ,result.STATUS
        ,result.progress_status
        ,result.recording_url
        ,result.notes
        ,"agents.firstname"
        ,"agents.lastname"
        ,"widgets.name"
        ,"phonenumbers.friendly_name"
    FROM (
        SELECT leads.id
            ,leads.firstname
            ,leads.lastname
            ,leads.phonenumber
            ,leads.email
            ,leads.my_phone
            ,leads.question
            ,leads.duration
            ,leads.starttime
            ,leads.endtime
            ,leads.created_on
            ,leads.call_type
            ,leads.STATUS
            ,leads.progress_status
            ,leads.recording_url
            ,leads.notes
            ,agents.firstname as "agents.firstname"
            ,agents.lastname as "agents.lastname"
            ,widgets.NAME as "widgets.name"
            ,phonenumbers.friendly_name as "phonenumbers.friendly_name"
            ,ROW_NUMBER() OVER (
                PARTITION BY leads.phonenumber ORDER BY leads.id ASC
                ) AS rk
        FROM leads
        LEFT OUTER JOIN agents ON (leads.agent_id = agents.id)
        LEFT OUTER JOIN widgets ON (leads.widget_guid = widgets.guid)
        LEFT OUTER JOIN phonenumbers ON (leads.inbound_id = phonenumbers.id)
        WHERE leads.partnership_account_id = :partnership_account_id
            AND leads.phonenumber NOT IN (
                SELECT leads.phonenumber
                FROM leads
                INNER JOIN widgets ON leads.widget_guid = widgets.guid
                WHERE widgets.NAME LIKE '%Application%'
                )
        ) result
        WHERE rk = 1;""")

    connection = db.engine.connect()
    leads = connection.execute(query, params)

    # Build the CSV
    row_no = 0
    with closing(StringIO()) as out:
        writer = csv.writer(out)
        writer.writerow(header)
        for lead in leads:
            row_no += 1
            csv_row = [
                row_no, lead.id, lead.firstname, lead.lastname, lead.email,
                lead.phonenumber, lead.my_phone, lead.question, lead.duration,
                format_date_to_excel(lead.starttime), format_date_to_excel(lead.endtime),
                format_date_to_excel(lead.created_on), lead.call_type, lead.status, lead.progress_status,
                lead.recording_url, lead.notes,
                lead['agents.firstname'], lead['agents.lastname'],
                lead['widgets.name'],
                lead['phonenumbers.friendly_name']
            ]
            writer.writerow(csv_row)

        filename = 'Buyercall Report - List of Interest - {}.csv'.format(
            date.today().strftime('%Y-%m-%d')
        )

        resp = make_response(out.getvalue())
        resp.headers['Content-Type'] = 'text/csv'
        resp.headers['Content-Disposition'] = \
            'attachment; filename="{}"'.format(filename)
        return resp


@reports.route('/reports/daily_report', methods=['GET', 'POST'])
def daily_report():
    try:
        daily_report = Report.query.filter(Report.name == 'Daily Leads Report').first()
    except Exception as e:
        log.error("Cannot add or call lead: {}".format(traceback.format_exc()))
        flash(_('The report does not exist.'), 'danger')

    form = ReportUserTie.query. \
        filter(ReportUserTie.user_id == current_user.id, daily_report.id == ReportUserTie.report_id).first()

    form.emails = {'emails': request.form.get('recipient_emails', '')}
    try:
        db.session.commit()
        flash(_('The email address(es) has been added successfully.'), 'success')
        return redirect(url_for('reports.all_reports'))
    except Exception as e:
        log.error(traceback.format_exc())
        db.session.rollback()
        flash(_("Error saving form information."), 'danger')

    return render_template('_daily_report_modal.jinja2')


def send_daily_report(pa_id, report_id, user_id):
    """
            Return total daily reports .

            :return: Result of updating the records
            """
    from flask_babel import gettext as _
    from buyercall.blueprints.widgets.models import split_emails
    from buyercall.blueprints.partnership.models import Partnership, PartnershipAccount
    from buyercall.blueprints.leads.models import Lead
    from buyercall.blueprints.contacts.models import Contact
    from buyercall.blueprints.form_leads.models import FormLead, FormLeadField, ExternalForm
    from buyercall.blueprints.sms.models import Message
    from buyercall.blueprints.agents.models import Agent
    from buyercall.blueprints.phonenumbers.models import Phone
    from buyercall.app import create_app
    import pendulum
    # Create a context for the database connection.
    app = current_app or create_app()
    db.app = app

    # A small function to determine color of the value differences used in report
    def color_indicator(value):
        if value < 0:
            color = '#FF0000'
        elif value == 0:
            color = '#000'
        else:
            color = '#008000'
        return color

    with app.app_context():

        # Retrieve partnership and partnership account to get account name and logo
        partner_account = PartnershipAccount.query.filter(
            PartnershipAccount.id == pa_id).first()
        partner = Partnership.query.filter(Partnership.id == partner_account.partnership_id).first()

        # RETURN ALL CALL DATA FOR YESTERDAY FOR SPECIFIC ACCOUNT
        # calls = Lead.query. \
        #    filter(Lead.partnership_account_id == report.partnership_accounts_id,
        #           func.DATE(Lead.created_on) == yesterday_date) \
        #    .all()

        # Determine the times used in reporting
        # The daily report gets send out at 00:00 EST each day
        # This means we need to retrieve yesterday's data in the reports
        yesterday = pendulum.yesterday().to_date_string()
        day_before_yesterday = pendulum.today().subtract(days=2).to_date_string()
        current_week = pendulum.yesterday().week_of_year
        previous_week = pendulum.yesterday().week_of_year - 1
        current_month = pendulum.yesterday().month
        previous_month = pendulum.yesterday().month - 1
        current_year = pendulum.yesterday().year
        last_year = pendulum.yesterday().year - 1

        limit_lead_count_date = pendulum.yesterday().subtract(days=70).to_date_string()

        # Retrieve all leads from the db for a specific partnership account
        leads = Contact.query \
            .filter(and_(Contact.partnership_account_id == pa_id,
                         Contact.created_on > limit_lead_count_date)).all()

        # The total unique leads for yesterday and day before for an account
        day_leads = 0
        day_before_leads = 0
        week_leads = 0
        week_before_leads = 0
        month_leads = 0
        month_before_leads = 0
        last_year_month_before_leads = 0
        day_call_leads = 0
        day_before_call_leads = 0
        day_form_leads = 0
        day_before_form_leads = 0
        day_message_leads = 0
        day_before_message_leads = 0
        day_completed_leads = 0
        day_missed_leads = 0
        day_not_assigned_leads = 0
        day_assigned_leads = 0
        day_completed_calls = 0
        day_missed_calls = 0
        day_inbound_calls = 0
        day_outbound_calls = 0
        day_inbound_msg = 0
        day_outbound_msg = 0
        day_partial_form = 0
        day_full_form = 0

        # Retrieve agent data
        agents = Agent.query.filter(Agent.partnership_account_id == pa_id).all()
        agent_list = list()
        agent_leads_exist = 'No'
        for a in agents:
            lead_count = 0
            out_call_count = 0
            for l in a.contact_leads:
                contact_lead_date_transform = l.created_on.strftime("%Y-%m-%dT%H:%M:%SZ")
                contact_lead_date = pendulum.parse(contact_lead_date_transform).to_date_string()
                if contact_lead_date == yesterday:
                    lead_count = lead_count + 1
                    agent_leads_exist = 'Yes'
            for c in a.outbound_calls:
                out_call_lead_date_transform = c.created_on.strftime("%Y-%m-%dT%H:%M:%SZ")
                out_call_lead_date = pendulum.parse(out_call_lead_date_transform).to_date_string()
                if out_call_lead_date == yesterday and c.call_type == 'outbound':
                    out_call_count = out_call_count + 1
                    agent_leads_exist = 'Yes'
            a_keys = ['agent', 'lead_count', 'outbound_calls']
            a_values = [a.full_name, lead_count, out_call_count]
            agent_dict = dict(zip(a_keys, a_values))
            agent_list.append(agent_dict)

        # Retrieve phone number details
        phonenumbers = Phone.query\
            .filter(and_(Phone.partnership_account_id == pa_id,
                         Phone.is_deactivated.is_(False))).all()
        pn_list = list()
        pn_leads_exist = 'No'
        for p in phonenumbers:
            in_calls = 0
            out_calls = 0
            in_msgs = 0
            out_msgs = 0
            for pc in p.leads:
                call_date_transform = pc.created_on.strftime("%Y-%m-%dT%H:%M:%SZ")
                call_date = pendulum.parse(call_date_transform).to_date_string()
                if call_date == yesterday and pc.call_type == 'inbound':
                    in_calls = in_calls + 1
                    pn_leads_exist = 'Yes'
                elif call_date == yesterday and pc.call_type == 'outbound':
                    out_calls = out_calls + 1
                    pn_leads_exist = 'Yes'
            for pm in p.messages:
                msg_date_transform = pm.created_on.strftime("%Y-%m-%dT%H:%M:%SZ")
                msg_date = pendulum.parse(msg_date_transform).to_date_string()
                if msg_date == yesterday and pm.direction == 'inbound':
                    in_msgs = in_msgs + 1
                    pn_leads_exist = 'Yes'
                elif msg_date == yesterday and pm.direction == 'outbound':
                    out_msgs = out_msgs + 1
                    pn_leads_exist = 'Yes'
            p_keys = ['phone_number', 'in_calls', 'out_calls', 'in_msgs', 'out_msgs']
            p_values = [p.friendly_name, in_calls, out_calls, in_msgs, out_msgs]
            pn_dict = dict(zip(p_keys, p_values))
            pn_list.append(pn_dict)

        # Retrieve phone number details
        forms = ExternalForm.query \
            .filter(ExternalForm.partnership_account_id == pa_id).all()
        form_list = list()
        form_leads_exist = 'No'
        for f in forms:
            form_lead_count = 0
            for fl in f.leads:
                form_lead_date_transform = fl.created_on.strftime("%Y-%m-%dT%H:%M:%SZ")
                form_lead_date = pendulum.parse(form_lead_date_transform).to_date_string()
                if form_lead_date == yesterday:
                    form_lead_count = form_lead_count + 1
                    form_leads_exist = 'Yes'
            f_keys = ['form', 'form_lead_count']
            f_values = [f.display_name, form_lead_count]
            form_dict = dict(zip(f_keys, f_values))
            form_list.append(form_dict)

        """
        header = [
            'No', 'First Name', 'Last Name', 'Caller Id', 'Phonenumber_1', 'Phonenumber_2', 'Email',
            'Address_1', 'Address_2', 'City', 'State', 'Zip', 'Country',
            'Do Not Call', 'SMS Unsubscribe',
            'Agent Assigned',
            'Status',
            'Same Day Response',
            'Total Phone Calls',
            'Total Messages',
            'Total Form Submissions'
        ]
        report_csv = StringIO()
        csvwriter = csv.writer(report_csv)
        csvwriter.writerow(header)
        row_no = 1
        """

        # Contain statuses and lead count assigned to each status
        statuses = list()
        status_list = list()
        # Reiterate over the leads and determine the totals of leads for specific time periods
        # The reiteration will update the lead totals above
        for lead in leads:
            lead_date_transform = lead.created_on.strftime("%Y-%m-%dT%H:%M:%SZ")
            lead_date = pendulum.parse(lead_date_transform).to_date_string()

            lead_week = pendulum.parse(lead_date).week_of_year

            lead_month = pendulum.parse(lead_date).month

            lead_year = pendulum.parse(lead_date).year

            if lead_date == yesterday and lead_year == current_year:
                day_leads = day_leads + 1
                # Identify the unique leads originated from phone calls
                call = Lead.query.filter(Lead.contact_id == lead.id).order_by(Lead.created_on.asc()).first()
                # Identify the unique leads originated from form submits
                form = FormLead.query\
                    .filter(FormLead.contact_id == lead.id).order_by(FormLead.created_on.asc()).first()
                # Identify the unique leads originated from form submits
                message = Message.query\
                    .filter(Message.contact_id == lead.id).order_by(Message.created_on.asc()).first()
                # Determine how the lead originated (form, call or message) and which happened first
                if call and message and form:
                    if call.created_on < message.created_on and call.created_on < form.created_on:
                        day_call_leads = day_call_leads + 1
                    elif message.created_on < call.created_on and message.created_on < form.created_on:
                        day_message_leads = day_message_leads + 1
                    elif form.created_on < call.created_on and form.created_on < message.created_on:
                        day_form_leads = day_form_leads + 1
                elif call and message:
                    if call.created_on < message.created_on:
                        day_call_leads = day_call_leads + 1
                    elif message.created_on < call.created_on:
                        day_message_leads = day_message_leads + 1
                elif call and form:
                    if call.created_on < form.created_on:
                        day_call_leads = day_call_leads + 1
                    elif form.created_on < call.created_on:
                        day_form_leads = day_form_leads + 1
                elif message and form:
                    if message.created_on < form.created_on:
                        day_message_leads = day_message_leads + 1
                    elif form.created_on < message.created_on:
                        day_form_leads = day_form_leads + 1
                elif call:
                    day_call_leads = day_call_leads + 1
                elif message:
                    day_message_leads = day_message_leads + 1
                elif form:
                    day_form_leads = day_form_leads + 1

                # Calculate successful conversations on the same day
                # Requires at least one completed call or a send and receive text message
                # Identify the unique leads originated from phone calls
                completed_call = Lead.query.\
                    filter(and_(Lead.contact_id == lead.id, Lead.status == 'completed')).\
                    filter(func.DATE(Lead.created_on) == yesterday).first()
                # Identify the unique leads originated from messages
                messages = Message.query\
                    .filter(Message.contact_id == lead.id)\
                    .filter(func.DATE(Message.created_on) == yesterday).all()
                if completed_call:
                    day_completed_leads = day_completed_leads + 1
                    same_day = 'yes'
                elif messages:
                    complete_msg_chat = 0
                    for m in messages:
                        if m.status == 'received':
                            complete_msg_chat = complete_msg_chat + 1
                            print(m)
                        if m.status == 'sent':
                            complete_msg_chat = complete_msg_chat + 1
                            print(m)
                    if complete_msg_chat == 2:
                        day_completed_leads = day_completed_leads + 1
                        same_day = 'yes'
                    else:
                        day_missed_leads = day_missed_leads + 1
                        same_day = 'no'
                else:
                    day_missed_leads = day_missed_leads + 1
                    same_day = 'no'

                # Calculate the assigned and unassigned leads
                if lead.agent_assigned in ['None', 'no', 'select', 'null', 'NULL', 'not selected', '']:
                    day_not_assigned_leads = day_not_assigned_leads + 1
                else:
                    day_assigned_leads = day_assigned_leads + 1

                """
                # Add lead rows to the CSV file
                same_day_response = same_day
                csv_row = [
                    row_no,
                    lead.firstname,
                    lead.lastname,
                    lead.caller_id,
                    lead.phonenumber_1,
                    lead.phonenumber_2,
                    lead.email,
                    lead.address_1,
                    lead.address_2,
                    lead.city,
                    lead.state,
                    lead.zip,
                    lead.country,
                    lead.is_do_not_call,
                    lead.is_unsubscribe,
                    lead.agent_assigned,
                    lead.status,
                    same_day_response,
                    lead.sms_count,
                    lead.phone_count,
                    lead.form_count
                ]
                csvwriter.writerow([x for x in csv_row])
                row_no = row_no + 1
                """

                # Determine status counts for leads
                status_lead_count = 0
                if lead.status not in statuses:
                    status_lead_count = Contact.query\
                        .filter(and_(Contact.status == lead.status,
                                     Contact.partnership_account_id == pa_id))\
                        .filter(func.DATE(Contact.created_on) == yesterday).count()

                    statuses.append(lead.status)
                    s_keys = ['status', 'lead_count']
                    s_values = [lead.status, status_lead_count]
                    status_dict = dict(zip(s_keys, s_values))
                    status_list.append(status_dict)

            if lead_date == day_before_yesterday and lead_year == current_year:
                day_before_leads = day_before_leads + 1
                # Identify the unique leads originated from phone calls
                call = Lead.query.filter(Lead.contact_id == lead.id).first()
                # Identify the unique leads originated from form submits
                form = FormLead.query.filter(FormLead.contact_id == lead.id).first()
                # Identify the unique leads originated from form submits
                message = Message.query.filter(Message.contact_id == lead.id).first()
                # Determine how the lead originated (form, call or message) and which happened first
                if call and message and form:
                    if call.created_on < message.created_on and call.created_on < form.created_on:
                        day_before_call_leads = day_before_call_leads + 1
                    elif message.created_on < call.created_on and message.created_on < form.created_on:
                        day_before_message_leads = day_before_message_leads + 1
                    elif form.created_on < call.created_on and form.created_on < message.created_on:
                        day_before_form_leads = day_before_form_leads + 1
                elif call and message:
                    if call.created_on < message.created_on:
                        day_before_call_leads = day_before_call_leads + 1
                    elif message.created_on < call.created_on:
                        day_before_message_leads = day_before_message_leads + 1
                elif call and form:
                    if call.created_on < form.created_on:
                        day_before_call_leads = day_before_call_leads + 1
                    elif form.created_on < call.created_on:
                        day_before_form_leads = day_before_form_leads + 1
                elif message and form:
                    if message.created_on < form.created_on:
                        day_before_message_leads = day_before_message_leads + 1
                    elif form.created_on < message.created_on:
                        day_before_form_leads = day_before_form_leads + 1
                elif call:
                    day_before_call_leads = day_before_call_leads + 1
                elif message:
                    day_before_message_leads = day_before_message_leads + 1
                elif form:
                    day_before_form_leads = day_before_form_leads + 1

            if lead_week == current_week and lead_year == current_year:
                week_leads = week_leads + 1

            if lead_week == previous_week and lead_year == current_year:
                week_before_leads = week_before_leads + 1

            if lead_month == current_month and lead_year == current_year:
                month_leads = month_leads + 1

            if lead_month == previous_month and lead_year == current_year:
                month_before_leads = month_before_leads + 1

            if lead_month == 12 and lead_year == last_year:
                last_year_month_before_leads = last_year_month_before_leads + 1

            # Calculate total calls for yesterday
            day_all_calls = Lead.query. \
                filter(Lead.contact_id == lead.id). \
                filter(func.DATE(Lead.created_on) == yesterday).all()
            for c in day_all_calls:
                if c.status == 'completed' or c.status == 'in-progress':
                    day_completed_calls = day_completed_calls + 1
                elif c.status == 'missed' or 'ringing':
                    day_missed_calls = day_missed_calls + 1

                if c.call_type == 'inbound':
                    day_inbound_calls = day_inbound_calls + 1

                elif c.call_type == 'outbound':
                    day_outbound_calls = day_outbound_calls + 1

            # Calculate total messages for yesterday
            day_all_messages = Message.query. \
                filter(Message.contact_id == lead.id). \
                filter(func.DATE(Message.created_on) == yesterday).all()
            for m in day_all_messages:
                if m.status == 'received':
                    day_inbound_msg = day_inbound_msg + 1
                elif m.status == 'sent':
                    day_outbound_msg = day_outbound_msg + 1

            # Calculate difference between full and partial form submit
            day_all_forms = FormLead.query. \
                filter(FormLead.contact_id == lead.id). \
                filter(func.DATE(FormLead.created_on) == yesterday).all()

            for f in day_all_forms:
                form_field = FormLeadField.query.filter(
                    and_(FormLeadField.lead_id == f.id,
                         FormLeadField.field_id == 'privacypolicyfield')).first()
                if form_field and form_field.field_value != '':
                    day_full_form = day_full_form + 1
                else:
                    day_partial_form = day_partial_form + 1

        # Calculate the difference between leads in % value
        if day_before_leads > 0:
            day_leads_diff = round(
                (float(day_leads) - float(day_before_leads)) / float(
                    day_before_leads) * 100, 2)
        else:
            day_leads_diff = 0

        if week_before_leads > 0:
            week_leads_diff = round(
                (float(week_leads) - float(week_before_leads)) / float(
                    week_before_leads) * 100, 2)
        else:
            week_leads_diff = 0

        if last_year_month_before_leads > 0:
            last_year_month_leads_diff = round(
                (float(month_leads) - float(last_year_month_before_leads)) / float(
                    last_year_month_before_leads) * 100, 2)
        else:
            last_year_month_leads_diff = 0

        if month_before_leads > 0:
            month_leads_diff = round(
                (float(month_leads) - float(month_before_leads)) / float(
                    month_before_leads) * 100, 2)
        else:
            month_leads_diff = 0

        # Calculate the difference for lead types
        if day_before_call_leads > 0:
            day_calls_diff = round(
                (float(day_call_leads) - float(day_before_call_leads)) / float(
                    day_before_call_leads) * 100, 2)
        else:
            day_calls_diff = 0

        if day_before_message_leads > 0:
            day_messages_diff = round(
                (float(day_message_leads) - float(day_before_message_leads)) / float(
                    day_before_message_leads) * 100, 2)
        else:
            day_messages_diff = 0

        if day_before_form_leads > 0:
            day_forms_diff = round(
                (float(day_form_leads) - float(day_before_form_leads)) / float(
                    day_before_form_leads) * 100, 2)
        else:
            day_forms_diff = 0

        # Assign a color to the percentage difference between time periods based on positive and negative
        day_diff_style = color_indicator(day_leads_diff)
        week_diff_style = color_indicator(week_leads_diff)
        month_diff_style = color_indicator(month_leads_diff)
        day_calls_diff_style = color_indicator(day_calls_diff)
        day_messages_diff_style = color_indicator(day_messages_diff)
        day_forms_diff_style = color_indicator(day_forms_diff)

        # Add a + plus sign to the % difference if it's positive. The negative value already has a minus
        if day_leads_diff > 0:
            day_leads_diff = '+' + str(day_leads_diff)

        if week_leads_diff > 0:
            week_leads_diff = '+' + str(week_leads_diff)

        if month_leads_diff > 0:
            month_leads_diff = '+' + str(month_leads_diff)

        if day_calls_diff > 0:
            day_calls_diff = '+' + str(day_calls_diff)

        if day_messages_diff > 0:
            day_messages_diff = '+' + str(day_messages_diff)

        if day_forms_diff > 0:
            day_forms_diff = '+' + str(day_forms_diff)

        # Create a dict from the list of leads returned above
        ctx = {'leads': leads}
        ctx['agents'] = agent_list
        ctx['agent_leads_exist'] = agent_leads_exist
        ctx['status'] = status_list
        ctx['phonenumbers'] = pn_list
        ctx['pn_leads_exist'] = pn_leads_exist
        ctx['forms'] = form_list
        ctx['form_leads_exist'] =form_leads_exist
        ctx['current_date'] = yesterday
        # Declare the total unique leads for current time period
        ctx['current_month'] = current_month
        ctx['day_leads'] = day_leads
        ctx['week_leads'] = week_leads
        ctx['month_leads'] = month_leads
        ctx['day_call_leads'] = day_call_leads
        ctx['day_message_leads'] = day_message_leads
        ctx['day_form_leads'] = day_form_leads
        ctx['day_completed_leads'] = day_completed_leads
        ctx['day_missed_leads'] = day_missed_leads
        ctx['day_not_assigned_leads'] = day_not_assigned_leads
        ctx['day_assigned_leads'] = day_assigned_leads
        ctx['day_completed_calls'] = day_completed_calls
        ctx['day_missed_calls'] = day_missed_calls
        ctx['day_inbound_calls'] = day_inbound_calls
        ctx['day_outbound_calls'] = day_outbound_calls
        ctx['day_inbound_msg'] = day_inbound_msg
        ctx['day_outbound_msg'] = day_outbound_msg
        ctx['day_partial_form'] = day_partial_form
        ctx['day_full_form'] = day_full_form
        # Declare the total unique leads for previous time period
        ctx['day_before_leads'] = day_before_leads
        ctx['week_before_leads'] = week_before_leads
        ctx['month_before_leads'] = month_before_leads
        ctx['last_year_month_before_leads'] = last_year_month_before_leads
        ctx['day_before_call_leads'] = day_before_call_leads
        ctx['day_before_message_leads'] = day_before_message_leads
        ctx['day_before_form_leads'] = day_before_form_leads
        # Declare the % difference calculation between time periods
        ctx['day_leads_diff'] = day_leads_diff
        ctx['week_leads_diff'] = week_leads_diff
        ctx['month_leads_diff'] = month_leads_diff
        ctx['last_year_month_leads_diff'] = last_year_month_leads_diff
        ctx['day_calls_diff'] = day_calls_diff
        ctx['day_messages_diff'] = day_messages_diff
        ctx['day_forms_diff'] = day_forms_diff
        # Declare the color to indicate neg or pos number in report
        ctx['day_diff_style'] = day_diff_style
        ctx['week_diff_style'] = week_diff_style
        ctx['month_diff_style'] = month_diff_style
        ctx['day_calls_diff_style'] = day_calls_diff_style
        ctx['day_messages_diff_style'] = day_messages_diff_style
        ctx['day_forms_diff_style'] = day_forms_diff_style

        # SPECIFY COMPANY NAME AND LOGO
        ctx['partner_logo'] = partner.logo
        ctx['company'] = partner.name
        ctx['account_name'] = partner_account.name
        from buyercall.blueprints.reports.models import ReportUserTie
        report = ReportUserTie.query.filter(and_(ReportUserTie.partnership_accounts_id == pa_id,
                                                 ReportUserTie.report_id == report_id,
                                                 ReportUserTie.user_id == user_id)).first()
        if 'emails' in report.emails:
            # Check what emails there are
            splited_em = split_emails(report.emails['emails'])
            log.info("The split emails are: {}".format(splited_em))

            # SPLIT THE STRING OF EMAIL ADDRESSES AND ADD , OR ; FOR FORMATTING AND ADD IT TO EMAIL LIST
            emails = list()
            emails.extend(split_emails(report.emails['emails']))

            template = 'mail/daily_leads'
            html = _try_renderer_template(template, ext='html', **ctx)
            try:
                from buyercall.lib.util_ses_email import send_ses_email
                send_ses_email(recipients=emails,
                               p_id=partner.id,
                               subject='Daily Lead Report',
                               html=html)
            except Exception as e:
                log.error(traceback.format_exc())
        return


@reports.route('/reports/credit_service_provider_report/pdf/<int:user_id>', methods=['GET'])
@login_required
@access_required(report_name='Partner Channel Account Report')
def credit_service_provider_accounts_report(user_id):
    if user_id:
        from .tasks import generate_credit_service_provider_report_pdf
        result = generate_credit_service_provider_report_pdf.delay(user_id)
        return {"result_id": result.id}
    else:
        flash(_('Unable to detect the your account. Please contact support.'), 'danger')
        return redirect(url_for('reports.all_reports'))


@reports.route('/reports/credit_service_provider_report/pdf/result/<_id>', methods=['GET'])
def credit_service_provider_accounts_report_task_result(_id):
    from buyercall.app import create_celery_app
    celery = create_celery_app(current_app)
    task_result = celery.AsyncResult(_id)
    task_result_value = task_result.result if task_result.ready() else None
    task_result_output = {
        "task_id": _id,
        "task_status": task_result.status,
        "ready": task_result.ready(),
        "successful": task_result.successful(),
        "value": task_result_value
    }
    return jsonify(task_result_output), 200


@reports.route('/reports/open_pdf/result/', methods=['POST', 'GET'])
def open_credit_service_provider_report_pdf():
    if request.data:
        args =request.data
    else:
        args = request.args or request.json
    from flask_weasyprint import HTML, render_pdf
    return render_pdf(HTML(string=args))