def _create_airport_ride_request(args, user_id): """ Creates an airport ride request with arguments received by REST API endpoint :param args: argument dict returned by .parse_args() from a reqparse object :param user_id: user id :return: RideRequest object """ builder = AirportRideRequestBuilder() ride_request: AirportRideRequest = builder \ .set_with_form_and_user_id(args, user_id) \ .build_airport_ride_request() \ .export_as_class(AirportRideRequest) location = Location.get( doc_id=any_to_doc_id(ride_request.airport_location) ) if ride_request.target.to_event: # TODO: fix user_location = Location.get( doc_id=any_to_doc_id(ride_request.origin_ref) ) else: raise ValueError("to_event is False ") # Do Validation Tasks before saving rideRequest # 1. Check that rideRequest is not submitted by the same user # for the flight on the same day already # TODO: move to transactional logic for better atomicity if utils.check_duplicate(ride_request.user_id, ride_request.event_ref): raise service_errors.RequestAlreadyExistsError # Starts database operations to (save rideRequest and update user's eventSchedule) transaction = db.transaction() # Transactional business logic for adding rideRequest utils.add_ride_request(transaction, ride_request, location, user_id) # Save write result transaction.commit() return ride_request
def from_location(self, value): if value != '' and value is not None: if "/" in value: self.ride_host.from_location = Location.get( doc_ref_str=value) else: self.ride_host.from_location = Location.get(doc_id=value)
def to_location(self, value): if value != '' and value is not None: if "/" in value: self.rider_booking.to_location = Location.get( doc_ref_str=value) else: self.rider_booking.to_location = Location.get(doc_id=value)
def generate_test_data(self, airport_code="LAX", start_string="2018-12-07T08:00:00.000", num_days=3, event_category="airport"): """ Generate data needed by the test :param airport_code: :param start_string: :param num_days: :param event_category: :return: """ c = scripts.populate_locations.PopulateLocationCommand( airport_code=airport_code) refs = c.execute() self.refs_to_delete.extend(refs) c = scripts.populate_airport_events.PopulateEventCommand( start_string=start_string, num_days=num_days, event_category=event_category) refs = c.execute() self.refs_to_delete.extend(refs) d = store.getUserLocationDict() location = Location.from_dict(d, doc_id=store.getMockKeys()["originId"]) location.save() location_ref = location.doc_ref # LocationGenericDao().set(location, location_ref) self.refs_to_delete.append(location_ref)
def run_orbit_group(ride_requests: dict): """ Create an orbit and group ride requests into the orbit. :param ride_requests: ride requests to place in the same orbit. :return: ride requests that could not be joined """ assert len(ride_requests) != 0 event_refs: set = {r.event_ref for rid, r in ride_requests.items()} assert len(event_refs) == 1 event_ref = event_refs.pop() orbit = Orbit.from_dict({ "orbitCategory": "airportRide", "eventRef": event_ref, "userTicketPairs": { }, "chatroomRef": None, "costEstimate": 987654321, "status": 1 }) orbit_ref = OrbitDao().create(orbit) orbit.set_firestore_ref(orbit_ref) event = EventDao().get(event_ref) location_ref: DocumentReference = event.location_ref location = Location.get(doc_id=location_ref.id) ride_request_refs = [r.get_firestore_ref() for rid, r in ride_requests.items()] transaction = db.transaction() # TODO: implement and call validate_entities_not_changed not_joined = _add_to_group(transaction, orbit_ref, ride_request_refs, event_ref, location_ref) return not_joined
def to_tuple_point(self, to_event = True): """ Returns a tuple (actually a list) representation of the ride request as a point for grouping algorithm. :return: """ assert to_event is True # Time-related to_event_target: ToEventTarget = self.target earliest = to_event_target.arrive_at_event_time['earliest'] latest = to_event_target.arrive_at_event_time['latest'] # Tag to identify ride request ref = self.get_firestore_ref() # Location-related pickup_location_ref = None if self.target.to_event: pickup_location_ref = self.origin_ref else: raise ValueError("Pickup address of to_event=False is not supported. ") location = Location.get(doc_id=any_to_doc_id(pickup_location_ref.id)) coordinates = location.coordinates latitude = coordinates["latitude"] longitude = coordinates["longitude"] # Form tuple () t = [earliest, latest, latitude, longitude, ref] return t
def setUp(self): self.refs_to_delete = list() event_dict = getEventDict(use_firestore_ref=True, to_earliest=1545033600, to_latest=1545119999, from_earliest=1545033600, from_latest=1545119999) self.event = Event.from_dict(event_dict) main.app.testing = True self.app = main.app.test_client() self.userId = "testuid1" self.c = scripts.SetUpTestDatabase() self.c.clear_before() self.c.generate_test_data(start_string="2018-12-17T08:00:00.000", num_days=5) # Populate location location_ref = event_dict["locationRef"] location_d = getLocationDict(location_category="social") location = Location.from_dict(location_d) LocationGenericDao().set(location, location_ref) self.refs_to_delete.append(location_ref) event_ref: firestore.DocumentReference = EventDao().create(self.event) self.event.set_firestore_ref(event_ref) self.refs_to_delete.append(event_ref) self.event_id = event_ref.id
def get_location_ref_by_id(location_id: str) -> DocumentReference: """ This method return the location_ref by location_id. :param location_id: :return: """ return Location.get_ref_by_id(location_id)
def test_view_websocket(): from gravitate.main import app mediator = UserLocationWsMediator(view_model_cls=UserLocationWebsocket, namespace="/sublocations") print(Location.get_schema_obj().fields) io = flask_socketio.SocketIO(app=app) io.on_namespace(mediator) client = io.test_client(app=app, namespace='/sublocations') assert client.is_connected(namespace='/sublocations') _ = client.emit('create_draft', { "user_id": "test_user_id1", "latitude": 32.879707, "longitude": -117.241254 }, namespace='/sublocations') res = client.get_received(namespace="/sublocations") assert res[-1] == { 'name': 'draft_created', 'args': [{ 'latitude': 32.879707, 'longitude': -117.241254, 'address': 'Muir Ln, San Diego, CA 92161, USA' }], 'namespace': '/sublocations' }
def get_with_transaction(transaction: Transaction, locationRef: DocumentReference) -> Type[Location]: """ Description Note that this cannot take place if transaction already received write operations. "If a transaction is used and it already has write operations added, this method cannot be used (i.e. read-after-write is not allowed)." :type self: :param self: :type transaction:Transaction: :param transaction:Transaction: :type locationRef:DocumentReference: :param locationRef:DocumentReference: :raises: :rtype: """ try: snapshot: DocumentSnapshot = locationRef.get( transaction=transaction) snapshotDict: dict = snapshot.to_dict() location = Location.from_dict(snapshotDict) location.set_firestore_ref(locationRef) return location except google.cloud.exceptions.NotFound: raise Exception('No such document! ' + str(locationRef.id))
def _get_dropoff_address(self): dropoff_location_ref = None if not self.target.to_event: dropoff_location_ref = self.destination_ref else: raise ValueError("Pickup address of to_event=True is not supported. ") location = Location.get(dropoff_location_ref) return location.address
def location(self): """ Note that this method is non-transactional. We are assuming that Location objects are immutable and ready before the transaction. :return: """ location_ref = self.location_ref location = Location.get(doc_id=location_ref.id) return location
def get(self, locationRef: DocumentReference): if isinstance(locationRef, str): locationRef = str_to_ref(locationRef) snapshot: DocumentSnapshot = locationRef.get() snapshotDict: dict = snapshot.to_dict() location = Location.from_dict(snapshotDict) location.set_firestore_ref(locationRef) return location return locationResult
def testGet(self): l = model.getLocation() l.save() doc_id = l.doc_id self.to_delete.append(l.doc_ref) location = Location.get(doc_id=doc_id) self.assertIsNotNone(location) print(location.to_dict())
def testGetUserLocation(self): location = LocationFactory.from_pickup_address("Tenaya Hall, San Diego, CA 92161") location.save() ref = location.doc_ref self.to_delete.append(ref) location = Location.get(doc_id=location.doc_id) d = location.to_dict() self.assertDictContainsSubset({ 'obj_type': "UserLocation", 'coordinates': {'latitude': 32.8794203, 'longitude': -117.2428555}, 'address': 'Tenaya Hall, San Diego, CA 92161', }, d)
def test_location_factory(self): location = Location.from_pickup_address( 'Tenaya Hall, San Diego, CA 92161') location_dict = { 'locationCategory': "user", 'coordinates': { 'latitude': 32.8794203, 'longitude': -117.2428555 }, 'address': 'Tenaya Hall, San Diego, CA 92161', } self.assertDictEqual(location.to_dict(), location_dict)
def testPickupAddress(self): location = Location.from_pickup_address( "Tenaya Hall, San Diego, CA 92161") d = location.to_dict() self.assertEqual( d, { 'locationCategory': "user", 'coordinates': { 'latitude': 32.8794203, 'longitude': -117.2428555 }, 'address': 'Tenaya Hall, San Diego, CA 92161', })
def testGetUserLocation(self): location = Location.from_pickup_address( "Tenaya Hall, San Diego, CA 92161") ref = LocationGenericDao().insert_new(location) self.to_delete.append(ref) location = LocationGenericDao().get(ref) d = location.to_dict() self.assertEqual( d, { 'locationCategory': "user", 'coordinates': { 'latitude': 32.8794203, 'longitude': -117.2428555 }, 'address': 'Tenaya Hall, San Diego, CA 92161', })
def setUp(self): self._to_delete = list() campusLocation = Location.from_code("UCSB", "campus") ref = LocationGenericDao().insert_new(campusLocation) campusLocation.set_firestore_ref(ref) self._to_delete.append(ref) self.event_dict = { "eventCategory": "campus", "campusCode": "UCSB", "isClosed": False, "targets": [{ 'eventCategory': 'campus', 'toEvent': True, 'arriveAtEventTime': { 'earliest': 1545033600, 'latest': 1545119999 } }, { 'eventCategory': 'campus', 'toEvent': False, 'leaveEventTime': { 'earliest': 1545033600, 'latest': 1545119999 } }], "localDateString": "2018-12-17", "pricing": 123456789, "parkingInfo": { "parkingAvailable": False, "parkingPrice": 0, "parkingLocation": "none" }, "description": "UCSB on 2018-12-17", "name": "UCSB", "locationRef": "/locations/testlocationid1", "participants": [] }
def _get_pickup_address(self): """ Note that this method is non-transactional. We are assuming that Location objects are immutable and ready before the transaction. :return: """ pickup_location_ref = None if self.target.to_event: pickup_location_ref = self.origin_ref else: raise ValueError("Pickup address of to_event=False is not supported. ") # if self._transaction is not None: # location = LocationGenericDao().get_with_transaction(self._transaction, pickup_location_ref) # return location.address # else: location = Location.get(doc_id=any_to_doc_id(pickup_location_ref)) return location.address
def setUp(self): main.app.testing = True self.app = main.app.test_client() self.userIds = ["testuid1", "testuid2"] self.refs_to_delete = list() location_dict = store.getLocationDict(location_category="social") location = Location.from_dict(location_dict) location_ref = LocationGenericDao().insert_new(location) self.refs_to_delete.append(location_ref) event_dict = store.getEventDict(event_category="social") event_dict["locationRef"] = location_ref event = Event.from_dict(event_dict) event_ref = EventDao().create(event) self.refs_to_delete.append(event_ref) event_id = event_ref.id self.d = store.EventRideRequestFormDictFactory().create( event_id=event_id) self.ride_request_ids_to_delete = list()
def doWorkUc(campusCode="UCSB"): campusLocation = Location.from_code("UCSB", "campus") ref = LocationGenericDao().insert_new(campusLocation) campusLocation.set_firestore_ref(ref)
def exportToLocation(self): return Location.from_dict(self.locationDict)
def _get_location(transaction: Transaction = None, location_id: str = None) -> Type[Location]: return Location.get(doc_id=location_id, transaction=transaction)
def doWorkUc(campusCode="UCSB"): campusLocation = Location.from_code("UCSB", "campus") campusLocation.save() ref = campusLocation.doc_ref campusLocation.set_firestore_ref(ref)
def setUp(self): self.arr = [[12000000, 12005000, 32.8802438, -117.2426505, 'A'], [12000000, 12005000, 32.8796722, -117.2414153, 'B'], [12000000, 12005000, 32.8687404, -117.2306258, 'C'], [12005000, 12006000, 32.8805864, -117.2318744, 'D'], [12007000, 12009000, 32.83228020000001, -117.1480747, 'E'], [12009001, 12009900, 32.8255484, -117.1543703, 'F'], [11000000, 11009000, 32.8248571, -117.1559327, 'G']] arr = self.arr rideRequests = list() configs = list() configs_other = [[12000000, 12005000, 'A'], [12000000, 12005000, 'B'], [12000000, 12005000, 'C'], [12005000, 12006000, 'D'], [12007000, 12009000, 'E'], [12009001, 12009900, 'F'], [11000000, 11009000, 'G']] addresses = [ # These are ucsd addresed "9500 Gilman Dr, La Jolla, CA 92093", "Muir Ln, San Diego, CA 92161", "8825 Villa La Jolla Dr, La Jolla, CA 92037", # Whole foods "3390 Voigt Dr, San Diego, CA 92121", # Canyonview Aquatic Center # These are Kearny Mesa Addressed "8199 Clairemont Mesa Blvd Suite H, San Diego, CA 92111", # Camellia "4681 Convoy St, San Diego, CA 92111", # Tajima Japanese Restaurant "4646 Convoy St, San Diego, CA 92111" # Tasty Noodle House ] locations_ds = [ {'locationCategory': 'user', 'coordinates': {'latitude': 32.8802438, 'longitude': -117.2426505}, 'address': '9500 Gilman Dr, La Jolla, CA 92093'}, {'locationCategory': 'user', 'coordinates': {'latitude': 32.8796722, 'longitude': -117.2414153}, 'address': 'Muir Ln, San Diego, CA 92161'}, {'locationCategory': 'user', 'coordinates': {'latitude': 32.8687404, 'longitude': -117.2306258}, 'address': '8825 Villa La Jolla Dr, La Jolla, CA 92037'}, {'locationCategory': 'user', 'coordinates': {'latitude': 32.8805864, 'longitude': -117.2318744}, 'address': '3390 Voigt Dr, San Diego, CA 92121'}, {'locationCategory': 'user', 'coordinates': {'latitude': 32.83228020000001, 'longitude': -117.1480747}, 'address': '8199 Clairemont Mesa Blvd Suite H, San Diego, CA 92111'}, {'locationCategory': 'user', 'coordinates': {'latitude': 32.8255484, 'longitude': -117.1543703}, 'address': '4681 Convoy St, San Diego, CA 92111'}, {'locationCategory': 'user', 'coordinates': {'latitude': 32.8248571, 'longitude': -117.1559327}, 'address': '4646 Convoy St, San Diego, CA 92111'}, ] for i in range(len(configs_other)): earliest, latest, firestoreRef = configs_other[i] address = addresses[i] location_d = locations_ds[i] ride_request = test.store.model.getMockRideRequest( earliest=earliest, latest=latest, firestoreRef=firestoreRef, returnDict=False) # Generate Test Locations location = Location.from_dict(location_d) ref = LocationGenericDao().insert_new(location) ride_request.origin_ref = ref rideRequests.append(ride_request) self.ride_requests = rideRequests
def getLocation(): locationDict = getLocationDict() location = Location.from_dict(locationDict) location.set_firestore_ref(mock1["locationFirestoreRef"]) return location