From 2964079722641166ef2abf3231cb637d9c5fac75 Mon Sep 17 00:00:00 2001 From: Benjamin Ng <60500272+benymng@users.noreply.github.com> Date: Fri, 17 May 2024 03:11:19 -0400 Subject: [PATCH] Benymng/setup google geoncoding api (#130) --------- Co-authored-by: Shahan Neda --- backend/app/graphql/__init__.py | 1 + .../app/utilities/location_to_coordinates.py | 55 +++++++++++++++++-- frontend/src/components/auth/Join.tsx | 26 +++++++-- frontend/src/pages/Settings.tsx | 26 +++++++-- 4 files changed, 93 insertions(+), 15 deletions(-) diff --git a/backend/app/graphql/__init__.py b/backend/app/graphql/__init__.py index 9f784a59..b726ebe5 100644 --- a/backend/app/graphql/__init__.py +++ b/backend/app/graphql/__init__.py @@ -57,6 +57,7 @@ class RootMutation( def init_email_service(app): print("Initializing email service") if app.config["TESTING"]: + os.environ["ENV"] = "testing" print("Using mock email service in testings!") services["email_service"] = MockEmailService( logger=current_app.logger, diff --git a/backend/app/utilities/location_to_coordinates.py b/backend/app/utilities/location_to_coordinates.py index 9abdace0..ff5533dd 100644 --- a/backend/app/utilities/location_to_coordinates.py +++ b/backend/app/utilities/location_to_coordinates.py @@ -1,16 +1,60 @@ import os - import requests GEOCODE_API_URL = "https://geocode.maps.co/search" GEOCODE_API_KEY = os.getenv("GEOCODING_API_KEY") +BASE_URL = "https://maps.googleapis.com/maps/api/geocode/" +GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") + +USE_GOOGLE_API = os.getenv("USE_GOOGLE_API", "1") == "1" +# NOTE: It's important all the errors in this file have the "GEOCODING" string in them since the frontend uses that to determine if the error is a geocoding error def getGeocodeFromAddress(organization_address): - if "PYTEST_CURRENT_TEST" in os.environ: + if os.getenv("ENV") == "testing": print("MOCKING LATITUDE IN TESTING") return [-11.1, 11.1] + if USE_GOOGLE_API: + return getGeocodeFromAddressGoogle(organization_address) + else: + return getGeocodeFromAddressGeocode(organization_address) + + +def getGeocodeFromAddressGoogle(organization_address): + response = requests.get( + '{base_url}{output_format}?address={address}"&key={api_key}'.format( + output_format="json", + base_url=BASE_URL, + address=organization_address, + api_key=GOOGLE_API_KEY, + ) + ) + try: + if response.status_code != 200: + raise Exception("GEOCODING: Failed to get coordinates from Geocode API") + + response_json = response.json() + if ( + len(response_json) == 0 + or "results" not in response_json + or not response_json["results"] + ): + raise Exception("GEOCODING: Failed to get coordinates from Geocode API") + + return [ + float(response_json["results"][0]["geometry"]["location"]["lng"]), + float(response_json["results"][0]["geometry"]["location"]["lat"]), + ] + except Exception as e: + print("Failed when getting geoencoding from address!") + print("Response:", response_json) + print(f"Status code is: {response.status_code}") + print("e is: ", e) + raise Exception("GEOCODING: Failed to get coordinates from Geocode API") + + +def getGeocodeFromAddressGeocode(organization_address): response = requests.get( '{base_url}?q="{address}"&api_key={api_key}'.format( base_url=GEOCODE_API_URL, @@ -20,13 +64,14 @@ def getGeocodeFromAddress(organization_address): ) try: if response.status_code != 200: - raise Exception("Failed to get coordinates from Geocode API") + raise Exception("GEOCODING: Failed to get coordinates from Geocode API") response_json = response.json() if len(response_json) == 0: - raise Exception("Failed to get coordinates from Geocode API") + raise Exception("GEOCODING: Failed to get coordinates from Geocode API") return [float(response_json[0]["lon"]), float(response_json[0]["lat"])] except Exception as e: print("Failed when getting geoencoding from address!") print(f"Status code is: {response.status_code}") - raise e + print("e:", e) + raise Exception("GEOCODING: Failed to get coordinates from Geocode API") diff --git a/frontend/src/components/auth/Join.tsx b/frontend/src/components/auth/Join.tsx index 73993d98..a36d7390 100644 --- a/frontend/src/components/auth/Join.tsx +++ b/frontend/src/components/auth/Join.tsx @@ -471,11 +471,27 @@ const Join = (): React.ReactElement => { console.log(response); navigate(JOIN_SUCCESS_PAGE); } catch (e: unknown) { - toast({ - title: "Failed to create account. Please try again.", - status: "error", - isClosable: true, - }); + if ( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + e?.graphQLErrors && + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + String(e.graphQLErrors[0]?.message).includes("GEOCODING") + ) { + toast({ + title: + "Failed to located address, please try entering more information or a different address!", + status: "error", + isClosable: true, + }); + } else { + toast({ + title: "Failed to create account. Please try again.", + status: "error", + isClosable: true, + }); + } // eslint-disable-next-line no-console console.log(e); logPossibleGraphQLError(e as ApolloError); diff --git a/frontend/src/pages/Settings.tsx b/frontend/src/pages/Settings.tsx index fc94c851..df0f0011 100644 --- a/frontend/src/pages/Settings.tsx +++ b/frontend/src/pages/Settings.tsx @@ -727,11 +727,27 @@ const Settings = (): React.ReactElement => { logPossibleGraphQLError(e as ApolloError); setIsLoading(false); - toast({ - title: "Failed to save settings", - status: "error", - isClosable: true, - }); + if ( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + e?.graphQLErrors && + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + String(e.graphQLErrors[0]?.message).includes("GEOCODING") + ) { + toast({ + title: + "Failed to located address, please try entering more information or a different address!", + status: "error", + isClosable: true, + }); + } else { + toast({ + title: "Failed to create account. Please try again.", + status: "error", + isClosable: true, + }); + } } };