Example #1
0
def main():
    tumsa = Tumsa(dbhost="127.0.0.1",
                  dbuser="******",
                  dbpass="******",
                  dbname="tumsadev")
    start_date = Utils.format_date(
        Utils.string_to_date("2020-10-04 06:33:00", "%Y-%m-%d %H:%M:%S") -
        timedelta(hours=5) - timedelta(minutes=40), "%Y-%m-%dT%H:%M:%S") + "Z"
    end_date = Utils.format_date(
        Utils.string_to_date("2020-10-04 18:21:00", "%Y-%m-%d %H:%M:%S") +
        timedelta(hours=5) + timedelta(minutes=40), "%Y-%m-%dT%H:%M:%S") + "Z"

    m = MZone()
    token = {
        "access_token":
        "eyJhbGciOiJSUzI1NiIsImtpZCI6IkVGMUUxMkVFOTQ1NTdBNDg5MzlCMUJBNjJFQUUxQzFBN0ZDNTY2MkQiLCJ0eXAiOiJKV1QiLCJ4NXQiOiI3eDRTN3BSVmVraVRteHVtTHE0Y0duX0ZaaTAifQ.eyJuYmYiOjE2MDE5NDkxOTksImV4cCI6MTYwMTk1Mjc5OSwiaXNzIjoiaHR0cHM6Ly9sb2dpbi5tem9uZXdlYi5uZXQiLCJhdWQiOlsiaHR0cHM6Ly9sb2dpbi5tem9uZXdlYi5uZXQvcmVzb3VyY2VzIiwibXo2LWFwaSJdLCJjbGllbnRfaWQiOiJtei1hM3RlayIsInN1YiI6IjUzYTkwNjMwLTk4OTctNGNkNS05MjJiLTM1NTZhYjI5M2UzOSIsImF1dGhfdGltZSI6MTYwMTk0OTE5OSwiaWRwIjoibG9jYWwiLCJtel91c2VybmFtZSI6IlRVTVNBLUFQSSIsIm16X3VzZXJncm91cF9pZCI6IjAwMDAwMDAwLTAwMDAtMDAwMC0wMDAwLTAwMDAwMDAwMDAwMCIsIm16X3NoYXJkX2NvZGUiOiJBM1RFSyIsInNjb3BlIjpbIm16X3VzZXJuYW1lIiwib3BlbmlkIiwibXo2LWFwaS5hbGwiXSwiYW1yIjpbInB3ZCJdfQ.ZHTW-sLBNFmwqUz-eSFCvleQcoXpjbFCfGJ7Yw4-vYfUV9n4WsBootTKTDeD1usHfEQRy2SGAJPdeLVVYUP27zshmY66IirUxUHAdi7i1DAcHteMlzt4lXQ9NYbRktHOdDmAoNeZm6PE8dhfIws1_NA2YjFZOd9B8EeRi7yLcoi-4wglyZ8Z3INL7tMjruSvlqtXdWnElcGaNqkpaEGtR1AJHlUjPlUldXOKocX0KRK2ZscV22xYH94Vd0MuOWFkIei9uyHprTFP2C7Xsz9-2ZSYXC12OMbbUedhVAcJeo1I0DKO60u0fc6ZeT9w41iMH-oX0S7Ilg-dJCoKlaPxlIlumD4BzTqEvZDq_72WZFHAD_QAJn5WAI3s8ta0Y7u91V1QhOvOYA0GrVXSM0MVs8b3HHHMjXQCR74cH56tLbOwxhkFUVI5UPNGbqaTvm3HKq1CusoBlpgmVvNDJomkE6n6cFop78cmFHqETNjD-UpDLJBB0n_0mQf78pi1V2h32fz5Dr5N80qCjqBX6aa89PCeCQDCD59b_nOyadzDFppaBIlfhGViXqw_YMqllvAb84sopaRkk_7vMN1AOAfCZUI16wIB-O7p3NJLoFq-7R22xT9xs5PtGy0KsFVSzmTFCzdUyrPDlehz31FmpPImJ7TnmzISyhDgJo4e8Xvgod4",
        "expires_in": 3600,
        "token_type": "Bearer",
        "valid_until": "2020-10-05 21:53:19.472393"
    }
    m.set_token(token)
    v = m.get_vehicles()
    fences = m.get_geofences(
        extra=
        "vehicle_Id eq b1772001-3173-467d-9b6c-5f97a05a4b9a and entryUtcTimestamp gt "
        + start_date + " and entryUtcTimestamp lt " + end_date,
        orderby="entryUtcTimestamp asc")
    for f in fences:
        print(f)
Example #2
0
    def get_pdf_report(self, pdf=None, viaje=None, token=None, pages=1):

        if pdf == None:
            pdf = HTML2PDF()

        m = MZone()
        start_date = Utils.format_date(
            Utils.string_to_date(viaje["start_date"], "%Y-%m-%d %H:%M:%S") -
            timedelta(hours=self.UTC) - timedelta(minutes=40),
            "%Y-%m-%dT%H:%M:%S") + "Z"
        end_date = Utils.format_date(
            Utils.string_to_date(viaje["end_date"], "%Y-%m-%d %H:%M:%S") +
            timedelta(hours=self.UTC) + timedelta(minutes=40),
            "%Y-%m-%dT%H:%M:%S") + "Z"

        m.set_token(token)
        delay = int(viaje["delay"])
        pdf.set_data(route=viaje["route"]["name"],
                     vehicle=viaje["vehicle"]["description"],
                     start_date=viaje["start_date"],
                     tolerancia=delay,
                     total_pages=pages)
        pdf.add_page(orientation='L')
        epw = pdf.w - 2 * pdf.l_margin

        fences = m.get_geofences(extra="vehicle_Id eq " +
                                 viaje["vehicle"]["id"] +
                                 " and entryUtcTimestamp gt " + start_date +
                                 " and entryUtcTimestamp lt " + end_date,
                                 orderby="entryUtcTimestamp asc")

        df = pd.DataFrame(fences)
        all = [[] for i in range(0, viaje["rounds"])]
        head = []

        for he in viaje["route"]["points"]["places"]:
            head.append(he["description"])

        trips = []
        if "trip" in viaje["trip"]:
            trips = viaje["trip"]["trip"]
        else:
            trips = viaje["trip"]

        for place in trips:
            calc = {}
            calc["place_Id"] = place["id"]
            calc["description"] = place["description"]
            calc["estimated"] = place["hour"]
            calc["real"] = ""
            calc["real_hour"] = ""
            calc["delay"] = 0
            calc["check"] = 0
            calc["estimated_hour"] = ""
            calc["color"] = "black"
            if place["hour"] != "":
                fence = []
                calc["estimated_hour"] = Utils.format_date(
                    Utils.string_to_date(place["hour"], "%Y-%m-%d %H:%M:%S"),
                    "%H:%M")
                start_date = Utils.format_date(
                    Utils.string_to_date(place["hour"], "%Y-%m-%d %H:%M:%S") +
                    timedelta(hours=self.UTC) - timedelta(minutes=15),
                    "%Y-%m-%dT%H:%M:%S") + "Z"
                end_date = Utils.format_date(
                    Utils.string_to_date(place["hour"], "%Y-%m-%d %H:%M:%S") +
                    timedelta(hours=self.UTC) + timedelta(minutes=15),
                    "%Y-%m-%dT%H:%M:%S") + "Z"

                if "place_Id" in df:
                    row = df[df["place_Id"] == calc["place_Id"]]
                    row2 = row[row["entryUtcTimestamp"] >= start_date]
                    fence = row2[
                        row2["entryUtcTimestamp"] <= end_date].to_dict(
                            orient='records')

                if len(fence) > 0:
                    real = Utils.string_to_date(
                        fence[0]["entryUtcTimestamp"],
                        "%Y-%m-%dT%H:%M:%SZ") - timedelta(hours=self.UTC)
                    estimated = Utils.string_to_date(calc["estimated"],
                                                     "%Y-%m-%d %H:%M:%S")
                    calc["real"] = Utils.format_date(real, "%Y-%m-%d %H:%M:%S")
                    calc["real_hour"] = Utils.format_date(real, "%H:%M")
                    real_hour = Utils.string_to_date(
                        Utils.format_date(real, "%Y-%m-%d %H:%M") + ":00",
                        "%Y-%m-%d %H:%M:%S")

                    diff = int((estimated - real_hour).total_seconds() / 60)

                    if real_hour < (estimated - timedelta(minutes=delay)):
                        calc["delay"] = abs(diff - delay)
                        calc["color"] = "blue"
                    else:
                        if real_hour > (estimated + timedelta(minutes=delay)):
                            calc["delay"] = abs(diff + delay)
                            calc["color"] = "red"
                        else:
                            calc["delay"] = diff
                            calc["color"] = "black"

                    calc["check"] = 1
            all[int(place["round"]) - 1].append(calc)

        col_width = epw / (len(head) + 2)
        pdf.set_font('Arial', 'B', 8)

        th = pdf.font_size
        pdf.set_fill_color(234, 230, 230)
        for data in head:
            pdf.cell(col_width, 2 * th, data, border=1, fill=True, align='C')

        head.append("ADNTO")
        head.append("RTRSO")
        col_width_f = 12
        pdf.cell(col_width_f, 2 * th, "ADNTO", border=1, fill=True, align='C')
        pdf.cell(col_width_f, 2 * th, "RTRSO", border=1, fill=True, align='C')

        pdf.set_font('Arial', '', 9)
        pdf.ln(2 * th)
        th = pdf.font_size

        total_adelanto = 0
        total_retraso = 0

        for vuelta in all:
            atraso = 0
            adelanto = 0
            pos = -1
            for point in vuelta:
                pdf.cell(col_width,
                         2 * th,
                         point["estimated_hour"],
                         border='LRT',
                         align='C')

            pdf.cell(col_width_f, 2 * th, '', border='R', align='C')
            pdf.cell(col_width_f, 2 * th, '', border='R', align='C')
            pdf.ln(2 * th)
            for point in vuelta:
                pos += 1
                if point["color"] == "red":
                    if pos != len(vuelta) - 1:
                        atraso = atraso + int(point["delay"])
                elif point["color"] == "blue":
                    pdf.set_text_color(0, 0, 255)
                    if pos != len(vuelta) - 1:
                        adelanto = adelanto + int(point["delay"])
                else:
                    pdf.set_text_color(0, 0, 0)

                if point["check"] == 1:
                    pdf.set_text_color(0, 0, 0)
                    if point["color"] == "red":
                        pdf.set_text_color(255, 0, 0)
                    elif point["color"] == "blue":
                        pdf.set_text_color(0, 0, 255)
                    pdf.cell(col_width,
                             2 * th,
                             "" + point["real_hour"] + "(" +
                             str(point["delay"]) + ")",
                             border='LRB',
                             align='C')
                else:
                    pdf.set_text_color(0, 0, 0)
                    pdf.cell(col_width,
                             2 * th,
                             "S/CHK",
                             border='LRB',
                             align='C')

            total_adelanto = total_adelanto + adelanto
            total_retraso = total_retraso + atraso
            pdf.set_text_color(0, 0, 255)
            pdf.cell(col_width_f,
                     2 * th,
                     str(adelanto),
                     border='BR',
                     align='C')
            pdf.set_text_color(255, 0, 0)
            pdf.cell(col_width_f, 2 * th, str(atraso), border='BR', align='C')
            pdf.set_text_color(0, 0, 0)
            pdf.ln(2 * th)

        pdf.set_text_color(0, 0, 0)
        for i in head[:-2]:
            pdf.cell(col_width, 2 * th, " - ", border=1, fill=True, align='C')
        pdf.set_text_color(0, 0, 255)
        pdf.cell(col_width_f,
                 2 * th,
                 str(total_adelanto),
                 border=1,
                 fill=True,
                 align='C')
        pdf.set_text_color(255, 0, 0)
        pdf.cell(col_width_f,
                 2 * th,
                 str(total_retraso),
                 border=1,
                 fill=True,
                 align='C')

        pdf.ln(10)
        pdf.ln(10)
        pdf.set_text_color(0, 0, 0)
        # pdf.cell(50, 10, 'COMENTARIOS: ', 0, 0, 'L')
        pdf.ln(10)
        pdf.set_font('Arial', '', 15)
        if not viaje["comments"] or len(
                viaje["comments"]) < 1 or viaje["comments"] == "None":
            viaje["comments"] = ""
        pdf.cell(200, 10, viaje["comments"], 0, 0, 'L')
        return pdf
Example #3
0
def trip_report():
    pdf = HTML2PDF()
    try:
        m = MZone()
        token = request.json["token"]
        tumsa = Tumsa(dbhost=env_cfg["dbhost"], dbuser=db_user, dbpass=db_pass, dbname=env_cfg["dbname"])
        viaje = tumsa.get_viaje(request.json["viaje"])[0]
        delay = int(viaje["delay"])
        start_date = Utils.format_date(Utils.string_to_date(viaje["start_date"], "%Y-%m-%d %H:%M:%S")
                                       - timedelta(hours=UTC) - timedelta(minutes=40) , "%Y-%m-%dT%H:%M:%S")+"Z"
        end_date = Utils.format_date(Utils.string_to_date(viaje["end_date"], "%Y-%m-%d %H:%M:%S")
                                     + timedelta(hours=UTC) + timedelta(minutes=40), "%Y-%m-%dT%H:%M:%S")+"Z"

        m.set_token(token)
        pdf.set_data(route=viaje["route"]["name"], vehicle=viaje["vehicle"]["description"], start_date=viaje["start_date"],
                     tolerancia=delay, total_pages=1)
        pdf.add_page(orientation='L')
        epw = pdf.w - 2 * pdf.l_margin

        print("vehicle_Id eq "+viaje["vehicle"]["id"]+" and entryUtcTimestamp gt "+
              start_date+" and entryUtcTimestamp lt "+end_date)

        fences = m.get_geofences(extra="vehicle_Id eq "+viaje["vehicle"]["id"]+" and entryUtcTimestamp gt "+start_date+
                                       " and entryUtcTimestamp lt "+end_date, orderby="entryUtcTimestamp asc")

        df = pd.DataFrame(fences)
        all = [[] for i in range(0, viaje["rounds"])]
        head = []

        for he in viaje["route"]["points"]["places"]:
            head.append(he["description"])

        trips = []
        if "trip" in viaje["trip"]:
            trips = viaje["trip"]["trip"]
        else:
            trips = viaje["trip"]

        for place in trips:
            calc = {}
            calc["place_Id"] = place["id"]
            calc["description"] = place["description"]
            calc["estimated"] = place["hour"]
            calc["real"] = ""
            calc["real_hour"] = ""
            calc["delay"] = 0
            calc["check"] = 0
            calc["estimated_hour"] = ""
            calc["color"] = "black"
            if place["hour"] != "":
                fence = []
                calc["estimated_hour"] = Utils.format_date(Utils.string_to_date(place["hour"], "%Y-%m-%d %H:%M:%S"), "%H:%M")
                start_date = Utils.format_date(Utils.string_to_date(place["hour"], "%Y-%m-%d %H:%M:%S")
                                               + timedelta(hours=UTC) - timedelta(minutes=30), "%Y-%m-%dT%H:%M:%S") + "Z"
                end_date = Utils.format_date(Utils.string_to_date(place["hour"], "%Y-%m-%d %H:%M:%S")
                                             + timedelta(hours=UTC) + timedelta(minutes=30), "%Y-%m-%dT%H:%M:%S") + "Z"

                if "place_Id" in df:
                    row = df[df["place_Id"] == calc["place_Id"]]
                    row2 = row[row["entryUtcTimestamp"] >= start_date]
                    fence = row2[row2["entryUtcTimestamp"] <= end_date].to_dict(orient='records')

                if len(fence) > 0:
                    real = Utils.string_to_date(fence[0]["entryUtcTimestamp"], "%Y-%m-%dT%H:%M:%SZ") - timedelta(hours=UTC)
                    estimated = Utils.string_to_date(calc["estimated"], "%Y-%m-%d %H:%M:%S")
                    calc["real"] = Utils.format_date(real, "%Y-%m-%d %H:%M:%S")
                    calc["real_hour"] = Utils.format_date(real, "%H:%M")
                    real_hour = Utils.string_to_date(Utils.format_date(real, "%Y-%m-%d %H:%M") + ":00",
                                                     "%Y-%m-%d %H:%M:%S")

                    diff = int((estimated - real_hour).total_seconds() / 60)

                    if real_hour < (estimated - timedelta(minutes=delay)):
                        calc["delay"] = abs(diff - delay)
                        calc["color"] = "blue"
                    else:
                        if real_hour > (estimated + timedelta(minutes=delay)):
                            calc["delay"] = abs(diff + delay)
                            calc["color"] = "red"
                        else:
                            calc["delay"] = diff
                            calc["color"] = "black"

                    calc["check"] = 1
            all[int(place["round"])-1].append(calc)


        col_width = epw / (len(head) + 1)
        pdf.set_font('Arial', 'B', 8)

        th = pdf.font_size
        pdf.set_fill_color(234, 230, 230)
        for data in head:
            pdf.cell(col_width, 2 * th, data, border=1, fill=True, align='C')

        head.append("ADNTO")
        head.append("RTRSO")
        col_width_f = 12
        pdf.cell(col_width_f, 2 * th, "ADNTO", border=1, fill=True, align='C')
        pdf.cell(col_width_f, 2 * th, "RTRSO", border=1, fill=True, align='C')

        pdf.set_font('Arial', '', 7)
        pdf.ln(2 * th)
        th = pdf.font_size

        total_adelanto = 0
        total_retraso = 0
        for vuelta in all:
            atraso = 0
            adelanto = 0
            pos = -1
            for point in vuelta:
                pos += 1
                if point["color"] == "red":
                    if pos != len(vuelta) - 1:
                        atraso = atraso + int(point["delay"])
                elif point["color"] == "blue":
                    pdf.set_text_color(0, 0, 255)
                    if pos != len(vuelta) - 1:
                        adelanto = adelanto + int(point["delay"])
                else:
                    pdf.set_text_color(0, 0, 0)

                if point["check"] == 1:
                    pdf.set_text_color(0, 0, 0)
                    pdf.cell(col_width/2, 2*th, point["estimated_hour"], border=1, align='C')
                    if point["color"] == "red":
                        pdf.set_text_color(255, 0, 0)
                    elif point["color"] == "blue":
                        pdf.set_text_color(0, 0, 255)
                    pdf.cell(col_width/2, 2*th, " "+point["real_hour"] + "(" + str(point["delay"]) + ")", border=1, align='C')
                else:
                    pdf.cell(col_width/2, 2 * th, point["estimated_hour"], border=1, align='C')
                    pdf.cell(col_width/2, 2 * th, "S/CHK", border=1, align='C')
            total_adelanto = total_adelanto + adelanto
            total_retraso = total_retraso + atraso
            pdf.set_text_color(0, 0, 255)
            pdf.cell(col_width_f, 2 * th, str(adelanto), border=1, align='C')
            pdf.set_text_color(255, 0, 0)
            pdf.cell(col_width_f, 2 * th, str(atraso), border=1, align='C')
            pdf.ln(2 * th)

        pdf.set_text_color(0, 0, 0)
        for i in head[:-2]:
            pdf.cell(col_width, 2 * th, " - ", border=1, fill=True, align='C')
        pdf.set_text_color(0, 0, 255)
        pdf.cell(col_width_f, 2 * th, str(total_adelanto), border=1, fill=True, align='C')
        pdf.set_text_color(255, 0, 0)
        pdf.cell(col_width_f, 2 * th, str(total_retraso), border=1, fill=True, align='C')

        pdf.ln(10)
        pdf.ln(10)
        pdf.set_text_color(0, 0, 0)
       # pdf.cell(50, 10, 'COMENTARIOS: ', 0, 0, 'L')
        pdf.ln(10)
        pdf.set_font('Arial', '', 15)
        if not viaje["comments"] or len(viaje["comments"]) < 1 or viaje["comments"] == "None":
            viaje["comments"] = ""
        pdf.cell(200, 10, viaje["comments"], 0, 0, 'L')
        pdf.output('out.pdf')
    except Exception as e:
        print("Problem here creating the pdf")
        print(e)
        pdf.output('out.pdf')
    finally:
        pdf2 = open("out.pdf")
        response = Response(pdf2.read(), mimetype="application/pdf", headers={"Content-disposition": "attachment; filename=report.pdf"})
        pdf2.close()
        os.remove("out.pdf")
    return response