import os | |
import json | |
from pymongo import MongoClient | |
from dotenv import load_dotenv | |
from trip_utils import format_trip_summary | |
load_dotenv() | |
client = MongoClient(os.getenv("MONGODB_URI")) | |
db = client.get_database() | |
collection = db.get_collection("travelrecords") | |
def fetch_trips_by_location(city: str) -> str: | |
""" | |
Fetch all trip records to a given city across all users, using name fuzzy match | |
AND exact latitude/longitude match to ensure consistent location. | |
""" | |
reference = collection.find_one({ | |
"$or": [ | |
{"destinationName": {"$regex": city, "$options": "i"}}, | |
{"locationName": {"$regex": city, "$options": "i"}} | |
], | |
"latitude": {"$exists": True}, | |
"longitude": {"$exists": True} | |
}) | |
if not reference: | |
return json.dumps({ | |
"type": "text", | |
"message": f"No travel records found for {city}." | |
}) | |
lat = reference.get("latitude") | |
lon = reference.get("longitude") | |
records = list(collection.find({ | |
"latitude": lat, | |
"longitude": lon | |
})) | |
if not records: | |
return json.dumps({ | |
"type": "text", | |
"message": f"No travel records found for {city}." | |
}) | |
summaries = [format_trip_summary(rec) for rec in records] | |
result = "\n---\n".join(summaries) | |
return json.dumps({ | |
"type": "text", | |
"message": result | |
}) |