コード例 #1
0
ファイル: tasks.py プロジェクト: ntxuva/mopa-utils
        report.type = xstr(_request['service_name'])
        report.status = xstr(_request['service_notice'])
        report.status_notes = xstr(_request.get('status_notes', ''))

        Uow.add(report)
        try:
            Uow.commit()
        except IntegrityError:
            Uow.rollback()
        except Exception, ex:
            Uow.rollback()
            current_app.logger.error("Error While Inserting Report in DB\n" + traceback.format_exc())

    # Report by State
    # ---------------
    estados_report_rows = Report.get_summary_report(start_date, end_date, old_start_date, old_end_date)

    # calculate totals for states
    total_occurencies = 0
    total_pct = 0
    total_tempo_medio_resolucao = 0
    total_variacao = 0

    for estado in estados_report_rows:
        total_occurencies += estado["no_occorencias"]
        total_pct += estado["pct_do_total"]
        total_tempo_medio_resolucao += estado["tempo_medio_resolucao"]
        total_variacao += estado.get("variacao") if estado.get("variacao") else 0

    estados_report_rows.append({
        'type': 'TOTAL',
コード例 #2
0
ファイル: tasks.py プロジェクト: ntxuva/mopa-utils
def send_weekly_report(today=None):
    """Task to run weekly for report"""

    today = date.today() if today is None else datetime.strptime(today, '%Y-%m-%d')
    start_date = today + timedelta(days=-7)
    end_date = today

    old_start_date = start_date + timedelta(days=-7)
    old_end_date = start_date

    # Get requests
    default = ''
    requests_list = []

    for _request in get_requests(start_date, end_date, True):
        location = Location.i().guess_location(_request)

        del _request['zipcode']
        del _request['lat']
        del _request['long']

        district = location['district']
        neighbourhood = location['neighbourhood']
        location_name = location['location_name']

        report = Report()
        report.id = xstr(_request['service_request_id'])
        report.district = district
        report.neighbourhood = neighbourhood
        report.location_name = location_name
        report.nature = xstr(_request['service_name'])
        report.requested_datetime = (xstr(_request['requested_datetime'])[0:10] + " " + xstr(_request['requested_datetime'])[11:19])
        report.updated_datetime = (xstr(_request['updated_datetime'])[0:10] + " " + xstr(_request['updated_datetime'])[11:19])
        report.type = xstr(_request['service_name'])
        report.status = xstr(_request['service_notice'])
        report.status_notes = xstr(_request.get('status_notes', ''))

        Uow.add(report)
        try:
            Uow.commit()
        except IntegrityError:
            Uow.rollback()
        except Exception, ex:
            Uow.rollback()
            current_app.logger.error("Error While Inserting Report in DB\n" + traceback.format_exc())
コード例 #3
0
ファイル: tasks.py プロジェクト: ntxuva/mopa-utils
def send_weekly_report(today=None):
    """Task to run weekly for report"""

    today = date.today() if today is None else datetime.strptime(
        today, '%Y-%m-%d')
    start_date = today + timedelta(days=-7)
    end_date = today

    old_start_date = start_date + timedelta(days=-7)
    old_end_date = start_date

    for _request in get_requests(start_date, end_date, True):
        location = Location.i().guess_location(_request)

        del _request['zipcode']
        del _request['lat']
        del _request['long']

        district = location['district']
        neighbourhood = location['neighbourhood']
        location_name = location['location_name']

        report = Report()
        report.id = xstr(_request['service_request_id'])
        report.district = district
        report.neighbourhood = neighbourhood
        report.location_name = location_name
        report.nature = xstr(_request['service_name'])
        report.requested_datetime = (
            xstr(_request['requested_datetime'])[0:10] + " " +
            xstr(_request['requested_datetime'])[11:19])
        report.updated_datetime = (xstr(_request['updated_datetime'])[0:10] +
                                   " " +
                                   xstr(_request['updated_datetime'])[11:19])
        report.type = xstr(_request['service_name'])
        report.status = xstr(_request['service_notice'])
        report.status_notes = xstr(_request.get('status_notes', ''))

        Uow.add(report)
        try:
            Uow.commit()
        except IntegrityError:
            Uow.rollback()
        except Exception as ex:
            Uow.rollback()
            current_app.logger.error("Error While Inserting Report in DB\n" +
                                     traceback.format_exc())

    # Report by State
    # ---------------
    estados_report_rows = Report.get_summary_report(start_date, end_date,
                                                    old_start_date,
                                                    old_end_date)

    # calculate totals for states
    total_occurrences = 0
    total_pct = 0
    total_tempo_medio_resolucao = 0
    total_variacao = 0

    for estado in estados_report_rows:
        total_occurrences += estado["no_occorencias"]
        total_pct += estado["pct_do_total"]
        total_tempo_medio_resolucao += estado["tempo_medio_resolucao"]
        total_variacao += estado.get("variacao") if estado.get(
            "variacao") else 0

    estados_report_rows.append({
        'type': 'TOTAL',
        'no_occorencias': total_occurrences,
        'pct_do_total': total_pct,
        'tempo_medio_resolucao': total_tempo_medio_resolucao,
        'variacao': total_variacao
    })

    # Report by District
    # ------------------
    district_rows = Report.get_summary_by_district_report(
        start_date, end_date, old_start_date, old_end_date)

    # Calculate totals per district
    district_totals = {}
    district_names = []
    districts = {}

    for row in district_rows:
        district_names.append(row["district"])

    district_names = list(set(district_names))  # remove duplicates

    for row in district_rows:
        if not district_totals.get(row["district"]):
            district_totals[row["district"]] = {
                "no_occorencias": 0,
                "pct_do_total": 0,
                "tempo_medio_resolucao": 0,
                "variacao": 0
            }

        district_totals[
            row["district"]]["no_occorencias"] += row["no_occorencias"]
        district_totals[row["district"]]["pct_do_total"] += row["pct_do_total"]
        district_totals[row["district"]]["tempo_medio_resolucao"] += row[
            "tempo_medio_resolucao"]
        district_totals[row["district"]]["variacao"] += row.get("variacao", 0)

    for district in district_names:
        districts[district] = {
            "name": district,
            "totals": district_totals[district],
            "rows": []
        }

        for row in district_rows:
            if row["district"] == district:
                districts[district]["rows"].append(row)

    # Tiago Report
    # ------------
    t_report_rows = Report.get_by_problem(start_date, end_date)
    t_neighbourhood_names = []
    t_neighbourhoods = {}
    problem_types = [
        u"Tchova não passou", u"Contentor está cheio", u"Amontoado de lixo",
        u"Lixo fora do contentor", u"Lixo na vala de drenagem",
        u"Camião não passou", u"Contentor a Arder", u"Entulho na rua",
        u"Ramos no chão"
    ]

    problem_images = map(lambda x: remove_accents(x).lower().replace(' ', '_'),
                         problem_types)

    for row in t_report_rows:
        t_neighbourhood_names.append(row["bairro"])

    t_neighbourhood_names = list(set(t_neighbourhood_names))

    for neighbourhood in t_neighbourhood_names:
        t_neighbourhoods[neighbourhood] = {"name": neighbourhood, "rows": []}

        for row in t_report_rows:
            if row["bairro"] == neighbourhood:
                t_neighbourhoods[neighbourhood]["rows"].append({
                    "problema":
                    row.get("problema", "-"),
                    "registado":
                    row.get("registado", 0),
                    "em_processo":
                    row.get("em_processo", 0),
                    "resolvido":
                    row.get("resolvido", 0),
                    "invalido":
                    row.get("invalido", 0),
                    "total":
                    row.get("total", 0)
                })

    for neighbourhood in t_neighbourhood_names:
        neighbourhood_problems = []

        for row in t_neighbourhoods[neighbourhood]["rows"]:
            neighbourhood_problems.append(row["problema"])

        for problem_type in problem_types:
            if problem_type not in neighbourhood_problems:
                t_neighbourhoods[neighbourhood]["rows"].append({
                    "problema": problem_type,
                    "registado": 0,
                    "em_processo": 0,
                    "resolvido": 0,
                    "invalido": 0,
                    "total": 0
                })

        t_neighbourhoods[neighbourhood]["rows"] = sorted(
            t_neighbourhoods[neighbourhood]["rows"],
            key=lambda i: (-1 * i['total']))

    for neighbourhood in t_neighbourhood_names:
        if t_neighbourhoods[neighbourhood]["rows"][0]["total"] > 0:
            t_neighbourhoods[neighbourhood][
                "most_frequent_problem"] = t_neighbourhoods[neighbourhood][
                    "rows"][0]["problema"]
        else:
            t_neighbourhoods[neighbourhood]["most_frequent_problem"] = None

        t_neighbourhoods[neighbourhood]["rows"] = sorted(
            t_neighbourhoods[neighbourhood]["rows"],
            key=lambda i: (-1 * i['resolvido']))

        if t_neighbourhoods[neighbourhood]["rows"][0]["resolvido"] > 0:
            t_neighbourhoods[neighbourhood][
                "most_solved_problem"] = t_neighbourhoods[neighbourhood][
                    "rows"][0]["problema"]
        else:
            t_neighbourhoods[neighbourhood]["most_solved_problem"] = None

        t_neighbourhoods[neighbourhood]["rows"] = sorted(
            t_neighbourhoods[neighbourhood]["rows"],
            key=lambda i: (-1 * i['total']))

    for neighbourhood in t_neighbourhood_names:
        t_neighbourhoods[neighbourhood][
            "worst_critical_points"] = Report.get_worst_critical_points(
                neighbourhood, start_date, end_date)

    # Generate PDF
    context = {
        'today': today.strftime('%d-%m-%Y'),
        'sumario': {
            'estados': estados_report_rows,
            'district_names': district_names,
            'districts': districts
        },
        'details': {
            'neighbourhood_names': t_neighbourhood_names,
            'neighbourhoods': t_neighbourhoods
        },
        'icons': dict(zip(problem_types, problem_images)),
        'static': os.path.join(config.BASE_DIR, 'templates') + '/'
    }
    report_file_name = 'relatorio-semanal-' + today.strftime(
        '%Y_%m_%d') + '.pdf'
    generate_pdf('weekly_report.html', context, report_file_name)

    # Send mail
    html = '''
<html>
    <head></head>
    <body>
    <p>Sauda&ccedil;&otilde;es!<br/><br/>
        Segue em anexo o relat&oacute;rio MOPA<br/><br/>
        Cumprimentos,<br/>
        <em>Enviado automaticamente</em>
    </p>
    </body>
</html>
            '''
    send_mail('[MOPA] Relatorio Semanal - ' + today.strftime('%Y-%m-%d'),
              html_message=html,
              to=config.WEEKLY_REPORT_TO,
              cc=config.DAILY_REPORT_CC,
              sender=(config.EMAIL_DEFAULT_NAME, config.EMAIL_DEFAULT_SENDER),
              attachments=[config.REPORTS_DIR + '/' + report_file_name])

    return "Ok", 200