Ejemplo n.º 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)
Ejemplo n.º 2
0
def calc_trip():
    trip = request.json["viaje"]
    role = json.loads(request.json["role"])
    tumsa = Tumsa(dbhost=env_cfg["dbhost"], dbuser=db_user, dbpass=db_pass, dbname=env_cfg["dbname"])
    start_date = Utils.format_date(Utils.string_to_date(str(trip["start_date"]).split('.')[0], "%Y-%m-%dT%H:%M:%S"),"%Y-%m-%d")
    calcs = tumsa.calc_trip(trip["route"], start_date, role)
    return calcs
Ejemplo n.º 3
0
def fix_data(msg):
    print("Reading events")
    data = json.loads(msg)
    events = []
    for event in data["events"]:
        pEvent = dict()
        vehicle = get_vehicle(event["header"]["UnitId"])
        if vehicle:
            pEvent["Dominio"] = vehicle["Registration"]
            pEvent["NroSerie"] = vehicle["Description"]
            pEvent["Codigo"] = "1"
            pEvent["customer_name"] = get_name(vehicle["Description"])
            pEvent["Latitud"] = event["header"]["Latitude"]
            pEvent["Longitud"] = event["header"]["Longitude"]
            pEvent["Altitud"] = event["header"]["Odometer"]
            pEvent["Velocidad"] = event["header"]["Speed"]
            pEvent["FechaHoraEvento"] = Utils.format_date(
                Utils.utc_to_datetime(event["header"]["UtcTimestampSeconds"]),
                '%Y-%m-%dT%H:%M:%S')
            pEvent["FechaHoraRecepcion"] = Utils.format_date(
                Utils.string_to_date(data["date"], "%Y-%m-%d %H:%M:%S"),
                "%Y-%m-%dT%H:%M:%S")
            events.append(pEvent)
        else:
            logger.error("Vehicle not found: " + event["header"]["UnitId"],
                         extra={
                             'props': {
                                 "app": config["name"],
                                 "label": config["name"]
                             }
                         })
    logger.info("Sending document",
                extra={
                    'props': {
                        "raw": events,
                        "app": config["name"],
                        "label": config["name"]
                    }
                })
    if len(events) > 0:
        send(events)
Ejemplo n.º 4
0
 def header(self):
     self.set_font('Arial', 'B', 15)
     # Move to the right
     # Framed title
     self.cell(300, 10, 'MANZANILLO, COLIMA', 0, 0, 'C')
     # Line break
     self.ln(10)
     self.cell(300, 10, 'SISTEMA TUCA', 0, 0, 'C')
     self.ln(10)
     self.cell(300, 10, 'REPORTE DE CHECADAS', 0, 0, 'C')
     self.ln(10)
     self.cell(50, 10, "RUTA " + self._route, 0, 0, 'C')
     self.cell(155, 10, "No. Economico: " + self._vehicle, 0, 0, 'C')
     self.cell(
         100, 10, "Fecha: " + Utils.format_date(
             Utils.string_to_date(self._start_date, "%Y-%m-%d %H:%M:%S"),
             "%d/%m/%Y"), 0, 0, 'C')
     self.ln(15)
Ejemplo n.º 5
0
    def get_todays_trips(self, route=None):
        viajes = []
        try:
            base = Utils.format_date(
                Utils.datetime_zone(datetime.datetime.now(),
                                    "America/Mexico_City"), '%Y-%m-%d')
            start = base + " 00:00:00"
            end = base + " 23:59:59"
            conn = pg.connect(host=self.dbhost,
                              user=self.dbuser,
                              password=self.dbpass,
                              port="5432",
                              database=self.dbname)
            sql = "select * from departures where start_date>=%s and start_date<=%s "

            if route:
                sql = sql + " and route->>'nid' = '" + route + "'"
            sql = sql + " order by priority asc"
            cursor = conn.cursor()
            cursor.execute(sql, (start, end))
            data = cursor.fetchall()
            for row in data:
                viaje = {}
                viaje["nid"] = row[0]
                viaje["trip"] = row[1]
                viaje["route"] = row[2]
                viaje["rounds"] = int(row[3])
                viaje["total_time"] = int(row[4])
                viaje["vehicle"] = row[5]
                viaje["created"] = str(row[6])
                viaje["start_date"] = str(row[7])
                viaje["end_date"] = str(row[8])
                viaje["start_point"] = str(row[9])
                viaje["end_point"] = str(row[10])
                viaje["comments"] = str(row[11])
                viaje["delay"] = int(row[12])
                viaje["priority"] = int(row[13])
                viajes.append(viaje)
        except (Exception, pg.Error) as error:
            print(error)
        finally:
            return viajes
Ejemplo n.º 6
0
def dailyreport2():
    tumsa = Tumsa(dbhost=env_cfg["dbhost"], dbuser=db_user, dbpass=db_pass, dbname=env_cfg["dbname"], UTC=UTC)
    today = Utils.format_date(Utils.datetime_zone(datetime.now(), "America/Mexico_City"), '%Y-%m-%d')

    route = request.json["route"]
    token = request.json["token"]
    viajes = []
    delay = 1
    m = MZone()
    m.set_token(token)

    user = m.current_user()
    perfil = json.loads(user["phoneHome"])["perfil"]
    vehicles = [v['id'] for v in m.get_vehicles()]
    trips = tumsa.get_day_trips(today, route)
    print(trips)
    if perfil != "admin":
        viajes = list(filter(lambda d: d['vehicle']["id"] in vehicles, trips))
    else:
        viajes = trips

    viajes = sorted(viajes, key=lambda i: i['priority'])
    pages = len(viajes)
    if pages > 0:
        pdf = HTML2PDF()
        for viaje in viajes:
            pdf = tumsa.get_pdf_report(pdf, viaje, token, pages=pages)
    else:
        pdf = PDFEmpty()
        pdf.add_page(orientation='L')
        pdf.ln(10)
        pdf.set_font('Arial', '', 25)
        pdf.cell(300, 50, "NO HAY VIAJES EN ESTE REPORTE", 0, 0, 'C')


    pdf.output('reporteDiario.pdf')
    pdf2 = open('reporteDiario.pdf')
    response = Response(pdf2.read(), mimetype="application/pdf",
                        headers={"Content-disposition": "attachment; filename=reporteDiario.pdf"})
    pdf2.close()
    os.remove('reporteDiario.pdf')
    return response
Ejemplo n.º 7
0
 def report_position(self, report):
     mzone = MZone(self.mzone_user, self.mzone_pass, self.mzone_secret,
                   "mz-a3tek")
     position = mzone.get_last_position(str(report["vehicle_Id"]))
     if position is not None:
         token = b64.b64encode("circulocorp:" + self.token)
         headers = {
             "Authorization": "Bearer %s" % token,
             "Content-Type": "application/json"
         }
         resp = {}
         if not report["folio"]:
             data = {
                 'fl':
                 0,
                 'ln':
                 position["longitude"],
                 'lt':
                 position["latitude"],
                 'vl':
                 position["speed"],
                 'rm':
                 position["vehicle"]["odometer"],
                 'pl':
                 report["placa"],
                 'vn':
                 report["vin"],
                 'mr':
                 report["marca"],
                 'md':
                 report["modelo"],
                 'an':
                 report["unidadyear"],
                 'cl':
                 report["color"],
                 'fc':
                 Utils.format_date(
                     Utils.datetime_zone(
                         Utils.string_to_date(position["utcTimestamp"],
                                              "%Y-%m-%dT%H:%M:%SZ"),
                         "America/Mexico_City"), "%Y-%m-%d %H:%M:%S")
             }
             resp = requests.post(self.endpoint + "api/reporte",
                                  data=json.dumps(data),
                                  headers=headers,
                                  verify=False)
             print(resp.text)
         else:
             data = {
                 'fl':
                 report["folio"],
                 'ln':
                 position["longitude"],
                 'lt':
                 position["latitude"],
                 'fc':
                 Utils.format_date(
                     Utils.datetime_zone(
                         Utils.string_to_date(position["utcTimestamp"],
                                              "%Y-%m-%dT%H:%M:%SZ"),
                         "America/Mexico_City"), "%Y-%m-%d %H:%M:%S")
             }
             resp = requests.post(self.endpoint + "api/reporte",
                                  data=json.dumps(data),
                                  headers=headers,
                                  verify=False)
         self._update_folio(report, resp.json())
         self._generate_historic(report, position, resp.json())
Ejemplo n.º 8
0
def start(account):
    logger.info(
        "Searching notifications for " + account["user"],
        extra={'props': {
            "app": config["name"],
            "label": config["name"]
        }})
    yesterday = Utils.format_date(datetime.now() - timedelta(hours=12),
                                  "%Y-%m-%dT%H:%M:%S")
    m = MZone(account["user"], account["password"], mzone_secret, "mz-a3tek",
              "https://live.mzoneweb.net/mzone61.api/")
    m.gettoken()
    if m.check_token():
        notifis = m.get_notifications(
            extra="readUtcTimestamp eq null and utcTimestamp gt " + yesterday +
            "Z")["value"]
        if len(notifis) > 0:
            logger.info("Reading notifications",
                        extra={
                            'props': {
                                "notifications": notifis,
                                "app": config["name"],
                                "label": config["name"]
                            }
                        })
        else:
            logger.info("No notifications found for " + account["user"],
                        extra={
                            'props': {
                                "app": config["name"],
                                "label": config["name"]
                            }
                        })
        templates = []
        messages = []
        addresses = []
        for noti in notifis:
            if noti["notificationTemplate_Id"] not in templates:
                templates.append(noti["notificationTemplate_Id"])
            message = dict()
            message["template"] = noti["notificationTemplate_Id"]
            message["text"] = noti["message"]
            message["id"] = noti["id"]
            messages.append(message)

        for temple in templates:
            address = dict()
            address["phones"] = get_subscriptions(temple, m)
            address["template"] = temple
            addresses.append(address)

        build_message(messages, addresses, m, account)
    else:
        logger.error("Cant connect to MZone using " + account["user"],
                     extra={
                         'props': {
                             "account": account["user"],
                             "app": config["name"],
                             "label": config["name"]
                         }
                     })
Ejemplo n.º 9
0
def fix_data(msg):
    print("Reading events")
    root = {}
    registro = dict()
    movil = []
    data = json.loads(msg)
    goods = []
    bads = []
    for event in data["events"]:
        mov = dict()
        obj = event["header"]
        vehicle = get_vehicle(obj["UnitId"])
        if vehicle is not None and "provider" in vehicle:
            mov["proveedor"] = "TELCEL-GVT"
            mov["nombremovil"] = ""
            mov["patente"] = vehicle["Registration"]
            mov["ignicion"] = "1"
            mov["GPSLinea"] = "1"
            mov["LOGGPS"] = "0"
            mov["puerta1"] = "0"
            mov["evento"] = "1"
            mov["latitud"] = format(float(event["header"]["Latitude"]), '.6f')
            mov["longitud"] = format(float(event["header"]["Longitude"]),
                                     '.6f')
            mov["direccion"] = event["header"]["Direction"]
            mov["velocidad"] = event["header"]["Speed"]
            mov["fecha"] = Utils.format_date(
                Utils.datetime_zone(
                    Utils.utc_to_datetime(
                        event["header"]["UtcTimestampSeconds"]),
                    "America/Mexico_City"), '%d-%m-%Y %H:%M:%S')
            if mov["latitud"] == 0 or mov["longitud"] == 0:
                logger.error("Wrong Lat and Long",
                             extra={
                                 'props': {
                                     "raw": mov,
                                     "app": config["name"],
                                     "label": config["name"]
                                 }
                             })
                bad = dict()
                bad["vehicle"] = vehicle["_id"]
                bad["unit"] = obj["UnitId"]
                bad["problem"] = "Latitud=" + str(
                    mov["latitud"]) + ", Longitud=" + str(mov["longitud"])
                bads.append(bad)
            else:
                movil.append(mov)
                good = dict()
                good["vehicle"] = vehicle["_id"]
                goods.append(good)
        else:
            bad = dict()
            bad["problem"] = "Vehiculo no registrado o sin proveedor"
            bad["unit"] = obj["UnitId"]
            logger.error("Vehiculo no registrado o sin proveedor",
                         extra={
                             'props': {
                                 "raw": bad,
                                 "app": config["name"],
                                 "label": config["name"]
                             }
                         })
    registro["movil"] = movil
    root["registro"] = registro
    send(root)
Ejemplo n.º 10
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
Ejemplo n.º 11
0
    def calc_trip(self, route, day, role):
        calc = {}
        calc["start_date"] = Utils.string_to_date(day + " " + role["hour"],
                                                  "%Y-%m-%d %H:%M:%S")
        calc["start_point"] = role["start_point"]
        calc["end_point"] = role["end_point"]
        calc["trip"] = []
        calc["total_time"] = 0
        time = 0
        started = 0
        for i in range(int(role["rounds"])):
            for place in route["points"]["places"]:
                place2 = {}
                place2["id"] = place["id"]
                place2["description"] = place["description"]
                start = calc["start_date"]
                if calc["start_point"] != place2["id"] and started == 0:
                    place2["time"] = 0
                    place2["hour"] = ""
                else:
                    if "lastComment" in place and len(
                            json.loads(place["lastComment"])) > 0:
                        found = 0
                        for cond in json.loads(place["lastComment"]):
                            dt2 = Utils.format_date(
                                start +
                                timedelta(minutes=(time + int(place["time"]))),
                                "%H:%M")
                            if cond["k"] == route["name"] and (i + 1) == int(
                                    cond["v"]) and dt2 == cond["t1"]:
                                place2["condition"] = cond
                                oldtime = start + timedelta(
                                    minutes=(time + int(place["time"])))
                                ntime = Utils.string_to_date(
                                    Utils.format_date(start, "%Y-%m-%d") +
                                    " " + cond["t2"] + ":00",
                                    "%Y-%m-%d %H:%M:%S")
                                ftime = (ntime - oldtime).seconds
                                if oldtime > ntime:
                                    ftime = (oldtime - ntime).seconds
                                    time = time - int(ftime / 60) + int(
                                        place["time"])
                                else:
                                    time = time + int(ftime / 60) + int(
                                        place["time"])
                                found = 1
                                break
                        if found == 0:
                            time = time + int(place["time"])
                    else:
                        time = time + int(place["time"])
                    if started == 0:
                        time = 0
                    started = 1
                    place2["time"] = time
                    place2["hour"] = Utils.format_date(
                        start + timedelta(minutes=time), "%Y-%m-%d %H:%M:%S")
                place2["round"] = i + 1
                calc["trip"].append(place2)
            time = time + int(route["time_rounds"])

        calc["total_time"] = time
        calc["end_date"] = calc["start_date"] + timedelta(minutes=time)
        calc["start_point"] = route["points"]["places"][0]["id"]
        calc["end_point"] = route["points"]["places"][-1]["id"]

        return calc
Ejemplo n.º 12
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