def trip_create(request, pk): users = User.objects.get(id=pk) if request.method == "POST": check_in_date = parse_date(request.POST.get("startdate")) check_out_date = parse_date(request.POST.get("enddate")) check_in_time = parse_time(request.POST.get("starttime")) check_out_time = parse_time(request.POST.get("endtime")) duration_of_trip = request.POST.get("duration") amount_paid = request.POST.get("amount") destination = request.POST.get("destination") residence_address = request.POST.get("addr") trip_status = request.POST.get("tripstatus") car_type = request.POST.get("cartype") guest = request.POST.get("guests") trip = Trip(check_in_date=check_in_date, check_out_date=check_out_date, check_in_time=check_in_time, check_out_time=check_out_time, duration_of_trip=duration_of_trip, amount_paid=amount_paid, destination=destination, residence_address=residence_address, trip_status=trip_status, car_type=car_type, user=users, guest=guest) trip.save() return redirect("app:show_status", pk=users.pk) else: return render(request, "trip/trip_create.html")
class TestTrip(TestCase): """ In this class, the tests defined are the Trip, TripApproval and TripPOET models. The tests here are: 1. Trip cannot begin in the past. 2. Trip cannot begin on a later date than it ends. 3. Integrity errors are raised on fields that should be compulsory. """ def setUp(self): user = user_model.objects.create_user( username='******', password='******' ) self.traveler = TravelerProfile.objects.get(user_account=user) mock_file = mock.MagicMock(spec=File) mock_file.name = ('Test.docx') start_date = date.today() end_date = start_date + timedelta(days=10) self.trip = Trip( trip_name="Test Trip Name", traveler=self.traveler, type_of_travel="Domestic", category_of_travel= "Business", reason_for_travel= "This is a test trip", start_date=start_date, end_date=end_date, is_mission_critical=True, scope_of_work = mock_file, ) self.trip.save() def test_cannot_begin_in_the_past(self): """ Ensure that trip cannot begin before today. """ today = timezone.now().date self.assertTrue(today() >= self.trip.start_date) def test_trip_cannot_end_before_start(self): """ Test that start date is before end date. """ trip = self.trip self.assertTrue(trip.end_date >= trip.start_date)
def save(request): form = CreateTripForm(request.POST) if form.is_valid(): user = request.user #trip = Trip(name=request.POST.get('name'), slug=slugify(request.POST.get('name')), created_by=user ,start_date=request.POST.get('start_date'), num_days=request.POST.get('num_days')) trip = Trip(name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), created_by=user ,start_date=form.cleaned_data['start_date'], end_date=form.cleaned_data['end_date']) trip.save() trip_participant = TripParticipants(trip=trip, participant=user, role=TripParticipants.CREATOR) trip_participant.save() template = "trip/trip_summary.html" html = render_to_string(template, {'trip_info': trip }) response = simplejson.dumps({'success':'True', 'html': html}) else: html = form.errors.as_ul() response = simplejson.dumps({'success':'False', 'html': html}) return HttpResponse(response, content_type='application/javascript; charset=utf-8')
def save(request): form = CreateTripForm(request.POST) if form.is_valid(): user = request.user #trip = Trip(name=request.POST.get('name'), slug=slugify(request.POST.get('name')), created_by=user ,start_date=request.POST.get('start_date'), num_days=request.POST.get('num_days')) trip = Trip(name=form.cleaned_data['name'], slug=slugify(form.cleaned_data['name']), created_by=user ,destination=form.cleaned_data['destination'],start_date=form.cleaned_data['start_date'], end_date=form.cleaned_data['end_date']) trip.save() trip_participant = TripParticipants(trip=trip, participant=user, role=TripParticipants.CREATOR) trip_participant.save() template = "trip/trip_summary.html" html = render_to_string(template, {'trip_info': trip }) response = simplejson.dumps({'success':'True', 'html': html}) else: html = form.errors.as_ul() response = simplejson.dumps({'success':'False', 'html': html}) return HttpResponse(response, content_type='application/javascript; charset=utf-8')
def setUp(self): user = user_model.objects.create_user( username='******', password='******' ) self.traveler = TravelerProfile.objects.get(user_account=user) mock_file = mock.MagicMock(spec=File) mock_file.name = ('Test.docx') start_date = date.today() end_date = start_date + timedelta(days=10) self.trip = Trip( trip_name="Test Trip Name", traveler=self.traveler, type_of_travel="Domestic", category_of_travel= "Business", reason_for_travel= "This is a test trip", start_date=start_date, end_date=end_date, is_mission_critical=True, scope_of_work = mock_file, ) self.trip.save()
def get(cls, request, trip_id): trip = get_object_or_404(Trip, id=trip_id) if request.user == trip.car_provider: if trip.status != trip.WAITING_STATUS: return HttpResponse('Trip status is not waiting', status=409) return cls.show_trip_requests(request, trip) elif trip in Trip.get_accessible_trips_for(request.user): if trip.status != trip.WAITING_STATUS: return HttpResponse('Trip status is not waiting', status=409) return cls.show_create_request_form(request) else: return HttpResponse('You have not access to this trip', status=401)
def accept_trip_request(trip, trip_request_id): if trip.capacity <= trip.passengers.count(): raise Trip.TripIsFullException() trip_request = get_object_or_404(TripRequest, id=trip_request_id, trip=trip) trip_request.status = TripRequest.ACCEPTED_STATUS trip_request.save() Companionship.objects.create( member=trip_request.containing_set.applicant, trip=trip, source=trip_request.source, destination=trip_request.destination) trip_request.containing_set.close()
def join_a_trip_automatically(self): trips = Trip.get_accessible_trips_for(self.user).filter( people_can_join_automatically=True, status=Trip.WAITING_STATUS) source, destination = self.cleaned_data['source'], self.cleaned_data[ 'destination'] trips = sorted(trips, key=lambda trip: (get_trip_score(trip, source, destination))) trips = filter(lambda trip: self.__is_ok_to_join(trip), trips) for trip in trips: if self.__join_if_trip_is_not_full(trip): return trip return None
def post(self, request, trip_id): trip = get_object_or_404(Trip, id=trip_id) if request.user == trip.car_provider or trip.passengers.filter( id=request.user.id).exists(): return HttpResponse('You are already partaking this trip', status=403) if trip not in Trip.get_accessible_trips_for(request.user): return HttpResponse('You have not access to this trip', status=403) if trip.status != trip.WAITING_STATUS: return HttpResponse('Trip status is not waiting', status=409) source = extract_source(request.POST) destination = extract_destination(request.POST) form = TripRequestForm(user=request.user, trip=trip, data=request.POST) if form.is_valid() and TripForm.is_point_valid( source) and TripForm.is_point_valid(destination): trip_request = TripRequestManager.create_trip_request( form, source, destination) if trip.people_can_join_automatically: try: self.accept_trip_request(trip, trip_request.id) log.info("Request {} accepted automatically.".format( trip_request.id)) except Trip.TripIsFullException(): log.info( "Failed to automatically join trip #{} due to capacity limit." .format(trip.id)) return redirect(reverse('trip:trip', kwargs={'pk': trip_id})) log.warning( "Failed to create request to trip {} due to form validation errors." .format(trip.id), extra={'user': request.user}) return render(request, 'join_trip.html', {'form': form})
def do_search(cls, request): data = request.GET source = extract_source(data) destination = extract_destination(data) trips = Trip.get_accessible_trips_for(request.user) if data['start_time'] != "-1": trips = cls.filter_by_dates(data['start_time'], data['end_time'], trips) trips = sorted( trips, key=lambda trip: (get_trip_score(trip, source=source, destination=destination))) trips = filter( lambda trip: get_trip_score(trip, source, destination) != np.inf, trips) return render(request, "trips_viewer.html", {"trips": trips})
def get_available_trips_view(request): trips = Trip.get_accessible_trips_for(request.user).exclude( Q(status=Trip.DONE_STATUS) | Q(status=Trip.CANCELED_STATUS)) return render(request, 'trip_manager.html', {'trips': trips})
def post(self, request): # Create Trip API # Recieves destination, start_date, end_date, adults, infants, estimate_budget_start, estimate_budget_end, # user_id and events(json array) as parameter try: response = 200 message = '' data = request.data if not data["destination"] or data["destination"] is None: response = 400 message = "Destination is missing" elif not data["start_date"] or data["start_date"] is None: response = 400 message = "Trip start date is missing" elif not data["end_date"] or data["end_date"] is None: response = 400 message = "Trip end date is missing" elif not data["adults"] or data["adults"] is None: response = 400 message = "Adults number is missing" elif not data["infants"] or data["infants"] is None: response = 400 message = "Infants number is missing" elif not data["estimate_budget_start"] or data[ "estimate_budget_start"] is None: response = 400 message = "Estimated budget start limit is missing" elif not data["estimate_budget_end"] or data[ "estimate_budget_end"] is None: response = 400 message = "Estimated budget end limit is missing" elif not data["user_id"] or data["user_id"] is None: response = 400 message = "User ID is missing" if response == 400: return Response( {'response': { 'status': response, 'data': message, }}, status=response) user = User.nodes.get_or_none(uid=data["user_id"]) trip = Trip(destination=data["destination"], start_date=datetime.strptime(data["start_date"], '%Y-%m-%d').date(), end_date=datetime.strptime(data["end_date"], '%Y-%m-%d').date(), adults=data["adults"], infants=data["infants"], estimated_budget_start=data["estimate_budget_start"], estimated_budget_end=data["estimate_budget_end"], events=data["events"]).save() # Create trip.user.connect(user) return Response( { 'response': { 'status': response, 'data': { 'id': trip.id, 'trip_data': trip.serialize, } } }, status=response) except Exception as e: return Response( { 'response': { 'status': 500, 'data': { 'message': "Something went wrong. Try again later", } } }, status=500)