Skip to content

Commit

Permalink
Send coordinates for event (#384)
Browse files Browse the repository at this point in the history
  • Loading branch information
adimar-aot authored Oct 3, 2024
1 parent 15f35e4 commit b2dff0d
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 23 deletions.
5 changes: 5 additions & 0 deletions python/common/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ class ErrorCode(BaseEnum):
"Contact DF application support for further investigation", False)


# Geocoding location related error

L01 = ErrorCodeDetails("L01", "Error in getting coordinates", ErrorCategory.CONNECTION, ErrorSeverity.MEDIUM,
"Contact DF application support for further investigation", False)


# Add more error codes as needed...

Expand Down
16 changes: 16 additions & 0 deletions python/common/form_middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

import logging
from python.common.models import City


def get_city_name(city_code, args) -> str:
application = args.get('app')
db = args.get('db')
with application.app_context():
city_data = db.session.query(City) \
.filter(City.objectCd == city_code) \
.all()
if len(city_data) == 0:
logging.error("city not found")
else:
return city_data[0].objectDsc
18 changes: 5 additions & 13 deletions python/common/ride_actions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
import logging.config
import requests
from python.common import form_middleware
from python.common.helper import date_time_to_local_tz_string, format_date_only, yes_no_string_to_bool
from python.common.config import Config
from python.common.enums import ErrorCode
Expand Down Expand Up @@ -233,7 +234,10 @@ def fill_common_payload_record(args, payloadRecord):
payloadRecord["timeReleased"] = args['event_data']['time_released']
payloadRecord["vehicleTypeDesc"] = get_vehicle_type(args)
payloadRecord["addressOfOffence"] = args['event_data']['intersection_or_address_of_offence']
payloadRecord["offenceCity"] = get_city_name(args['event_data']['offence_city'], args)
payloadRecord["offenceCity"] = form_middleware.get_city_name(args['event_data']['offence_city'], args)
if 'latitude' in args['event_data'] and 'longitude' in args['event_data']:
payloadRecord["latitude"] = args['event_data']['latitude']
payloadRecord["longitude"] = args['event_data']['longitude']

payloadRecord["officerDisplayName"] = args['user_data']['display_name']
payloadRecord["officerBadgeNumber"] = args['user_data']['badge_number']
Expand Down Expand Up @@ -328,18 +332,6 @@ def get_vehicle_type(args) -> str:
return vehicle_type_data[0].description
return None


def get_city_name(city_code, args) -> str:
application = args.get('app')
db = args.get('db')
with application.app_context():
city_data = db.session.query(City) \
.filter(City.objectCd == city_code) \
.all()
if len(city_data) == 0:
logging.error("city not found")
else:
return city_data[0].objectDsc

def get_impound_lot_operator(args) -> str:
if args['event_data']['impound_lot_operator']:
Expand Down
36 changes: 28 additions & 8 deletions python/form_handler/actions.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
import json
import csv
import pytz
import logging
import logging.config
from python.common import form_middleware
from python.form_handler.config import Config
from cerberus import Validator
import base64
from cerberus import errors
import logging
import json
from datetime import datetime
from minio import Minio
from minio.error import S3Error
from python.common.models import Event,FormStorageRefs,VIForm,TwentyFourHourForm,TwelveHourForm,IRPForm,User,AgencyCrossref,CityCrossRef,JurisdictionCrossRef,ImpoundReasonCodes,IloIdCrossRef,ImpoundLotOperator
from python.form_handler.geocoding_service import get_coordinates
from python.form_handler.icbc_service import submit_to_icbc
from python.form_handler.vips_service import create_vips_doc,create_vips_imp
from python.form_handler.payloads import vips_payload,vips_document_payload
from python.form_handler.message import encode_message
from python.form_handler.helper import method2_decrypt,decryptPdf_method1,convertDateTime,convertDateTimeWithSecs
from python.form_handler.helper import decryptPdf_method1,convertDateTime,convertDateTimeWithSecs
from python.common.error_middleware import record_error
from python.common.enums import ErrorCode

Expand Down Expand Up @@ -1369,4 +1364,29 @@ def record_event_error(**args):
except Exception as e:
# If recording the error itself fails, log it
logging.error(f"Failed to record error: {str(e)}")
return True, args


def get_event_coordinates(**args)->tuple:
logging.debug("inside get_event_coordinates()")
try:
address = args['event_data']['intersection_or_address_of_offence']
city = form_middleware.get_city_name(args['event_data']['offence_city'], args)

geocoding_status, latitude, longitude = get_coordinates(address, city)
args['event_data']['latitude'] = latitude
args['event_data']['longitude'] = longitude

except Exception as e:
logging.error(f'Error getting coordinates: {e}')
args['error'] = {
'error_code': ErrorCode.L01,
'error_details': e,
'event_type': args['message']['event_type'],
'func': get_event_coordinates,
'event_id': args['message']['event_id']
}
record_event_error(**args)

# Always return True to continue processing even if not able to get coordinates
return True, args
3 changes: 3 additions & 0 deletions python/form_handler/business.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ def process_incoming_form() -> dict:
# {"try": actions.add_to_retry_queue, "fail": []},
# {"try": actions.update_event_status_hold, "fail": []},
# ]},
{"try": actions.get_event_coordinates, "fail": []},
{"try": ride_actions.vi_event, "fail": [
{"try": actions.record_event_error, "fail": []},
]},
Expand Down Expand Up @@ -140,6 +141,7 @@ def process_incoming_form() -> dict:
{"try": actions.record_event_error, "fail": []},
{"try": actions.update_event_status_hold, "fail": []},
]},
{"try": actions.get_event_coordinates, "fail": []},
{"try": ride_actions.twenty_four_hours_event, "fail": [
{"try": actions.record_event_error, "fail": []},
]},
Expand Down Expand Up @@ -187,6 +189,7 @@ def process_incoming_form() -> dict:
{"try": actions.add_to_retry_queue, "fail": []},
{"try": actions.update_event_status_hold, "fail": []},
]},
{"try": actions.get_event_coordinates, "fail": []},
{"try": ride_actions.twelve_hours_event, "fail": [
{"try": actions.record_event_error, "fail": []},
]},
Expand Down
5 changes: 3 additions & 2 deletions python/form_handler/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,9 @@ class Config():

VIPS_DPS_EMAIL = os.getenv('VIPS_DPS_EMAIL', 'do-not-reply-rsi@gov.bc.ca')



# Geocoding service details
GEOCODING_API_URL = os.getenv('GEOCODING_API_URL', 'http://localhost:8000')
GEOCODING_API_KEY = os.getenv('GEOCODING_API_KEY', 'TEST')

LOGGING = {
'version': 1,
Expand Down
25 changes: 25 additions & 0 deletions python/form_handler/geocoding_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import logging
import requests
from python.form_handler.config import Config

geocoding_url = Config.GEOCODING_API_URL
geocoding_key = Config.GEOCODING_API_KEY


def get_coordinates(address: str, city: str)-> tuple:
logging.debug(f'Getting coordinates for address: {address} and city: {city}')

url = f'{geocoding_url}/coordinates?address={address}&city={city}'
logging.debug(f'Geocoding API URL: {url}')
response = requests.get(url, headers={'api-key': geocoding_key})
if response.status_code == 200:
get_coordinates_response = response.json()
if get_coordinates_response['province'] != 'BC':
logging.warning(f'Coordinates found for address: {address} and city: {city} but not in BC')
return False, None, None
return True, get_coordinates_response['latitude'], get_coordinates_response['longitude']
elif response.status_code == 404:
logging.warning(f'No coordinates found for address: {address} and city: {city}')
return False, None, None
else:
raise Exception(f'Error getting coordinates for address: {address} and city: {city} -> Status: {response.status_code} Response: {response.text}')

0 comments on commit b2dff0d

Please sign in to comment.