From c0978a63e75f8d7261dc5c797c5eb41c9e2411fc Mon Sep 17 00:00:00 2001 From: Luiz Costa Date: Wed, 15 Nov 2023 10:31:58 +0000 Subject: [PATCH] get trip function --- fleet_management/traccar_api.py | 45 +++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/fleet_management/traccar_api.py b/fleet_management/traccar_api.py index 4aed0e9..b190c8c 100644 --- a/fleet_management/traccar_api.py +++ b/fleet_management/traccar_api.py @@ -1,7 +1,7 @@ from datetime import datetime import frappe import requests -from requests.auth import HTTPBasicAuth + def traccar_auth(ts): """authenticates on traccar server and returns cookies""" @@ -21,6 +21,7 @@ def traccar_auth(ts): else: frappe.throw(f"Authentication failed: {response.status_code}: {response.reason}
Dict ts: {ts.as_dict()}") + @frappe.whitelist() def get_devices(doc=None): """fetches all devices the user has access to and stores them in Tracker Doctype @@ -64,5 +65,45 @@ def get_devices(doc=None): def get_trips_for_device(device, start = None, end = None): """getches all trip for a device, stores them Trip Doctype and links them to the vehicle which is assigned to the device""" - pass + # get informations for authentication on traccar server + ts = frappe.get_last_doc('TraccarServer') + + # get all trips from traccar server + try: + trips = requests.get( + f"http://{ts.traccar_server}:{ts.traccar_port}/api/reports/trips", + cookies = traccar_auth(ts), + params = { + 'deviceId': device, + 'from': start, + 'to': end + } + ) + except: + frappe.throw("Could not fetch trips from traccar server") + + # Insert trips into Trip Doctype + for trip in trips.json(): + if not frappe.db.exists('Trip', trip['id']): + frappe.get_doc({ + 'doctype': 'Trip', + 'portal_id': trip['id'], + 'device_id': trip['deviceId'], + 'start': datetime.fromisoformat(trip['startTime']).strftime('%Y-%m-%d %H:%M:%S'), + 'end': datetime.fromisoformat(trip['endTime']).strftime('%Y-%m-%d %H:%M:%S'), + 'distance': trip['distance'], + 'average_speed': trip['averageSpeed'], + 'max_speed': trip['maxSpeed'], + 'spent_fuel': trip['spentFuel'], + 'start_address': trip['startAddress'], + 'end_address': trip['endAddress'], + 'duration': trip['duration'], + 'driver_unique_id': trip['driverUniqueId'], + 'vehicle': frappe.get_value('Tracker', trip['deviceId'], 'vehicle'), + }).insert() + + # update db frappe + frappe.db.commit() + +