Ejemplo n.º 1
0
def station_business_page(request, subdomain_name=None):
    if not subdomain_name:
        subdomain_name = get_station_domain(request)
    station = get_object_or_404(models.Station, subdomain_name=subdomain_name)
    passenger = Passenger.from_request(request)

    if not passenger:
        return auth_views.login(request, template_name="business_login.html")
#    only in django 1.3
#        return auth_views.login(request, template_name="business_login.html", extra_context={'station': station})
    elif not passenger.business:
        return HttpResponseForbidden("You are not a business")

    business = passenger.business
    cities = City.objects.filter(country=passenger.country)
    cities = filter(lambda city: is_in_hebrew(city.name), cities)
    cities = sorted(cities, key=lambda city: city.name)

    PENDING = models.PENDING
    ASSIGNED = models.ASSIGNED
    ACCEPTED = models.ACCEPTED
    ORDER_FAILED = models.FAILED # groups together FAILED, ERROR and TIMED_OUT
    ORDER_MAX_WAIT_TIME = models.ORDER_MAX_WAIT_TIME
    FAILED_MSG = _(order_tracker.STATUS_MESSAGES[models.FAILED])

    channel_key = get_channel_key(Passenger.from_request(request), request.session.session_key)
    passenger.cleanup_session_keys()
    passenger.session_keys.append(request.session.session_key)
    passenger.save()

    init_token = channel.create_channel(channel_key)
    init_tracker_history = [simplejson.dumps(msg) for msg in order_tracker.get_tracker_history(passenger)]

    return custom_render_to_response("station_page_business.html", locals(), context_instance=RequestContext(request))
Ejemplo n.º 2
0
def passenger_home(request):
    if not request.mobile and CURRENT_PASSENGER_KEY in request.session:
        del request.session[CURRENT_PASSENGER_KEY]

    hidden_fields = HIDDEN_FIELDS
    form = OrderForm()
    not_a_user, not_a_passenger = NOT_A_USER, NOT_A_PASSENGER
    waze_token = settings.WAZE_API_TOKEN
    telmap_user = settings.TELMAP_API_USER
    telmap_password = settings.TELMAP_API_PASSWORD
    telmap_languages = "he" if str(get_language_from_request(request)) == "he" else "en"
    country_code = settings.DEFAULT_COUNTRY_CODE
    service_cities = ", ".join(set([s.city.name for s in Station.objects.filter(show_on_list=True)]))
    passenger = Passenger.from_request(request)

    if not passenger and request.GET.get("show_login", False):
        show_login = True

    if passenger and passenger.business:
        PENDING = models.PENDING
        ASSIGNED = models.ASSIGNED
        ACCEPTED = models.ACCEPTED
        ORDER_FAILED = models.FAILED  # groups together FAILED, ERROR and TIMED_OUT
        ORDER_MAX_WAIT_TIME = models.ORDER_MAX_WAIT_TIME
        FAILED_MSG = _(order_tracker.STATUS_MESSAGES[models.FAILED])

        show_tracker = True
        channel_key = get_channel_key(Passenger.from_request(request), request.session.session_key)
        init_token = channel.create_channel(channel_key)
        init_tracker_history = [simplejson.dumps(msg) for msg in order_tracker.get_tracker_history(passenger)]

    return custom_render_to_response("passenger_home.html", locals(), context_instance=RequestContext(request))
Ejemplo n.º 3
0
def create_passenger():
    test_user = User.objects.get(username='******')
    passenger = Passenger()
    passenger.user = test_user
    passenger.country = Country.objects.filter(code="IL").get()
    passenger.save()

    return passenger
Ejemplo n.º 4
0
 def wrapper(request, **kwargs):
     passenger = Passenger.from_request(request)
     if passenger:
         kwargs["passenger"] = passenger
     else:
         return HttpResponseForbidden("You are not a passenger, please <a href='/passenger/logout/'>logout</a> and try again")
     return function(request, **kwargs)
Ejemplo n.º 5
0
def sync_app_state(request):
    earliest_pickup_time = ceil_datetime(trim_seconds(default_tz_now()) + datetime.timedelta(minutes=asap_interval()), minutes=booking_interval())
    latest_pickup_time = earliest_pickup_time + datetime.timedelta(hours=(24*14))
    dt_options = list(datetimeIterator(earliest_pickup_time, latest_pickup_time, delta=datetime.timedelta(minutes=booking_interval())))

    response = {
        "logged_in": request.user.is_authenticated(),
        "pickup_datetime_options": [to_js_date(opt) for opt in dt_options],
        "pickup_datetime_default_idx": 0,
        "asap_as_default": True,
        "booking_data": request.session.get(CURRENT_BOOKING_DATA_KEY)
    }

    passenger = Passenger.from_request(request)
    response["show_url"] = "" # change to cause child browser to open with passed url

    if passenger:
        response["authenticated"] = True
        response["passenger_picture_url"] = passenger.picture_url

        ongoing_order = get_ongoing_order(passenger)
        if ongoing_order:
            response["ongoing_order_id"] = ongoing_order.id

        future_orders = get_future_orders_for(passenger)
        response["future_orders_count"] = len(future_orders)

    trimed_response = response.copy()
    trimed_response['pickup_datetime_options'] = response['pickup_datetime_options'][:9] + ['...']
    logging.info("get_initial_status: %s" % trimed_response)

    return JSONResponse(response)
Ejemplo n.º 6
0
def update_profile_fb(request, passenger_id, next):
    """
    Callback after passenger approved us to get his data from fb
    """
    logging.info("update facebook profile for passenger[%s]" % passenger_id)

    from ordering.models import Passenger
    passenger = Passenger.by_id(passenger_id)
    if passenger and request.GET.get('code'):
        args = {
            'client_id': settings.FACEBOOK_APP_ID,
            # redirect_uri MUST match the one passed in step1 (redirecting to fb)
            'redirect_uri': "http://%s%s" % (DEFAULT_DOMAIN, reverse(update_profile_fb, args=[passenger.id, next])),
            'client_secret': settings.FACEBOOK_APP_SECRET,
            'code': request.GET['code'],
            }

        url = 'https://graph.facebook.com/oauth/access_token?' +\
              urllib.urlencode(args)

        try:
            response = cgi.parse_qs(urllib.urlopen(url).read())
            logging.info("FB query: %s" % url)
            logging.info("FB response: %s" % response)

            access_token = response['access_token'][0]

            facebook_session = FacebookSession(access_token=access_token)
            profile = facebook_session.query('me', fields=['id', 'email', 'first_name', 'last_name', 'picture'])
            passenger.picture_url = profile['picture']['data']['url']
            passenger.fb_id = profile['id']
            passenger.save()
            logging.info("passenger picture updated: %s" % passenger.picture_url)
        except Exception, e:
            pass
Ejemplo n.º 7
0
def is_email_available_for_user(request):
    passenger = Passenger.from_request(request)
    if passenger and passenger.user:
        if request.GET.get("email", None) == passenger.user.email:
            return JSONResponse(True)

    return is_email_available(request)
Ejemplo n.º 8
0
def view_passenger_orders(request, passenger_id):
    passenger = Passenger.by_id(passenger_id)
    user = passenger.user
    orders = sorted(passenger.orders.filter(type__in=[OrderType.SHARED, OrderType.PRIVATE], debug=False), key=lambda order: order.create_date, reverse=True)
    num_orders = len(orders)
    title = "View sharing order for passenger: %s [%s]" % (user.get_full_name(), user.email)

    return custom_render_to_response("staff_user_orders.html", locals(), context_instance=RequestContext(request))
Ejemplo n.º 9
0
def get_credentials_form(request):
    passenger = Passenger.from_request(request)
    if passenger and passenger.user:
        current_email = passenger.user.email
        context = locals()
        context.update({'FACEBOOK_APP_ID' : FACEBOOK_APP_ID})
        return render_to_response('credentials_form.html', context)
    else:
        return HttpResponseForbidden()
Ejemplo n.º 10
0
def get_credentials_form(request):
    passenger = Passenger.from_request(request)
    if passenger and passenger.user:
        current_email = passenger.user.email
        context = locals()
        context.update({'FACEBOOK_APP_ID': FACEBOOK_APP_ID})
        return render_to_response('credentials_form.html', context)
    else:
        return HttpResponseForbidden()
Ejemplo n.º 11
0
    def wrapper(request, **kwargs):
        passenger = Passenger.from_request(request)


        if not passenger:
            logging.info("passenger_required_no_redirect rejected request")
            return HttpResponseForbidden(NOT_A_PASSENGER)

        kwargs["passenger"] = passenger
        return function(request, **kwargs)
Ejemplo n.º 12
0
def create_passenger(user, country, phone, save=True):
    passenger = Passenger()
    passenger.user = user
    passenger.country = country
    passenger.phone = phone
    passenger.phone_verified = True

    if save:
        passenger.save()
        log_event(EventType.PASSENGER_REGISTERED, passenger=passenger)

    logging.info("welcome new passenger %s" % passenger)
    return passenger
Ejemplo n.º 13
0
def get_tracker_init(request):
    response = ''
    passenger = Passenger.from_request(request)
    if passenger:
        channel_key = get_channel_key(passenger, request.session.session_key)
        token = channel.create_channel(channel_key)
        tracker_history = order_tracker.get_tracker_history(passenger)

        response = {'tracker_history': tracker_history, 'token': token}

    return JSONResponse(response)
Ejemplo n.º 14
0
def get_tracker_init(request):
    response = ""
    passenger = Passenger.from_request(request)
    if passenger:
        channel_key = get_channel_key(passenger, request.session.session_key)
        token = channel.create_channel(channel_key)
        tracker_history = order_tracker.get_tracker_history(passenger)

        response = {"tracker_history": tracker_history, "token": token}

    return JSONResponse(response)
Ejemplo n.º 15
0
def resolve_address(request):
    # get parameters
    if not ADDRESS_PARAMETER in request.GET:
        return HttpResponseBadRequest("Missing address")

    address = request.GET[ADDRESS_PARAMETER]
    lon = request.GET.get("lon", None)
    lat = request.GET.get("lat", None)
    include_order_history = request.GET.get("include_order_history", True)
    fixed_address = fix_address(address, lon, lat)

    size = request.GET.get(MAX_SIZE_PARAMETER) or DEFAULT_RESULT_MAX_SIZE
    try:
        size = int(size)
    except:
        return HttpResponseBadRequest("Invalid value for max_size")

    geocoding_results = geocode(fixed_address,
                                max_size=size,
                                resolve_to_ids=True)
    history_results = []
    if include_order_history:
        passenger = Passenger.from_request(request)
        if passenger:
            history_results.extend([
                get_results_from_order(o, "from")
                for o in passenger.orders.filter(from_raw__icontains=address)
            ])
            history_results.extend([
                get_results_from_order(o, "to")
                for o in passenger.orders.filter(to_raw__icontains=address)
            ])
            history_results_by_name = {}
            for result in history_results:
                history_results_by_name[result["name"]] = result

            history_results = history_results_by_name.values()

            # remove duplicate results
            history_results_names = [
                result_name for result_name in history_results_by_name
            ]

            for result in geocoding_results:
                if result['name'] in history_results_names:
                    geocoding_results.remove(result)

    return JSONResponse({
        "geocode": geocoding_results[:size],
        "history": history_results[:size],
        "geocode_label": "map_suggestion",
        "history_label": "history_suggestion"
    })
Ejemplo n.º 16
0
def track_app_event(request):
    event_name = request.POST.get("name")
    logging.info("Track app event: %s" % event_name)

    passenger = Passenger.from_request(request)
    if event_name:
        if event_name == "APPLICATION_INSTALL":
            BIEvent.log(BIEventType.APP_INSTALL, request=request, passenger=passenger)
        elif event_name == "APPLICATION_OPEN":
            BIEvent.log(BIEventType.BOOKING_START, request=request, passenger=passenger)

    return HttpResponse("OK")
Ejemplo n.º 17
0
def is_user_authenticated(request):
    if request.user.is_authenticated():
        logging.info("User is authenticated: %s" % request.user.username)
        response_data = [True, request.user.username]
        passenger = Passenger.from_request(request)
        if passenger and (request.is_secure() or settings.DEV): # send token only over secure connection
            response_data.append(passenger.login_token)

        return JSONResponse(response_data)
    else:
        logging.info("User is not authenticated")
        return JSONResponse([False])
Ejemplo n.º 18
0
def passenger_home(request):
    if not request.mobile and CURRENT_PASSENGER_KEY in request.session:
        del request.session[CURRENT_PASSENGER_KEY]

    hidden_fields = HIDDEN_FIELDS
    form = OrderForm()
    not_a_user, not_a_passenger = NOT_A_USER, NOT_A_PASSENGER
    waze_token = settings.WAZE_API_TOKEN
    telmap_user = settings.TELMAP_API_USER
    telmap_password = settings.TELMAP_API_PASSWORD
    telmap_languages = 'he' if str(
        get_language_from_request(request)) == 'he' else 'en'
    country_code = settings.DEFAULT_COUNTRY_CODE
    service_cities = ", ".join(
        set([s.city.name for s in Station.objects.filter(show_on_list=True)]))
    passenger = Passenger.from_request(request)

    if not passenger and request.GET.get("show_login", False):
        show_login = True

    if passenger and passenger.business:
        PENDING = models.PENDING
        ASSIGNED = models.ASSIGNED
        ACCEPTED = models.ACCEPTED
        ORDER_FAILED = models.FAILED  # groups together FAILED, ERROR and TIMED_OUT
        ORDER_MAX_WAIT_TIME = models.ORDER_MAX_WAIT_TIME
        FAILED_MSG = _(order_tracker.STATUS_MESSAGES[models.FAILED])

        show_tracker = True
        channel_key = get_channel_key(Passenger.from_request(request),
                                      request.session.session_key)
        init_token = channel.create_channel(channel_key)
        init_tracker_history = [
            simplejson.dumps(msg)
            for msg in order_tracker.get_tracker_history(passenger)
        ]

    return custom_render_to_response("passenger_home.html",
                                     locals(),
                                     context_instance=RequestContext(request))
Ejemplo n.º 19
0
def booking_page(request, continued=False):
    lib_ng = True
    lib_map = True
    lib_geo = True

    if continued:
        continue_booking = simplejson.dumps(True)
    else:
        request.session[CURRENT_BOOKING_DATA_KEY] = None

    BIEvent.log(BIEventType.BOOKING_START, request=request, passenger=Passenger.from_request(request))

    return render_to_response("booking_page.html", locals(), RequestContext(request))
Ejemplo n.º 20
0
def create_passenger():
    test_user = User.objects.get(username='******')
    passenger = Passenger()
    passenger.user = test_user
    passenger.country = Country.objects.filter(code="IL").get()
    passenger.save()

    return passenger
Ejemplo n.º 21
0
def view_passenger_orders(request, passenger_id):
    passenger = Passenger.by_id(passenger_id)
    user = passenger.user
    orders = sorted(passenger.orders.filter(
        type__in=[OrderType.SHARED, OrderType.PRIVATE], debug=False),
                    key=lambda order: order.create_date,
                    reverse=True)
    num_orders = len(orders)
    title = "View sharing order for passenger: %s [%s]" % (
        user.get_full_name(), user.email)

    return custom_render_to_response("staff_user_orders.html",
                                     locals(),
                                     context_instance=RequestContext(request))
Ejemplo n.º 22
0
def create_passenger(user, country, phone, save=True):
    passenger = Passenger()
    passenger.user = user
    passenger.country = country
    passenger.phone = phone
    passenger.phone_verified = True

    if save:
        passenger.save()
        log_event(EventType.PASSENGER_REGISTERED, passenger=passenger)

    logging.info("welcome new passenger %s" % passenger)
    return passenger
Ejemplo n.º 23
0
def resolve_address(request):
    # get parameters
    if not ADDRESS_PARAMETER in request.GET:
        return HttpResponseBadRequest("Missing address")

    address = request.GET[ADDRESS_PARAMETER]
    lon = request.GET.get("lon", None)
    lat = request.GET.get("lat", None)
    include_order_history = request.GET.get("include_order_history", True)
    fixed_address = fix_address(address, lon, lat)

    size = request.GET.get(MAX_SIZE_PARAMETER) or DEFAULT_RESULT_MAX_SIZE
    try:
        size = int(size)
    except:
        return HttpResponseBadRequest("Invalid value for max_size")

    geocoding_results = geocode(fixed_address, max_size=size, resolve_to_ids=True)
    history_results = []
    if include_order_history:
        passenger = Passenger.from_request(request)
        if passenger:
            history_results.extend(
                [get_results_from_order(o, "from") for o in passenger.orders.filter(from_raw__icontains=address)]
            )
            history_results.extend(
                [get_results_from_order(o, "to") for o in passenger.orders.filter(to_raw__icontains=address)]
            )
            history_results_by_name = {}
            for result in history_results:
                history_results_by_name[result["name"]] = result

            history_results = history_results_by_name.values()

            # remove duplicate results
            history_results_names = [result_name for result_name in history_results_by_name]

            for result in geocoding_results:
                if result["name"] in history_results_names:
                    geocoding_results.remove(result)

    return JSONResponse(
        {
            "geocode": geocoding_results[:size],
            "history": history_results[:size],
            "geocode_label": "map_suggestion",
            "history_label": "history_suggestion",
        }
    )
Ejemplo n.º 24
0
def update_push_token(request):
    token = request.POST.get("push_token")
    old_token = request.POST.get("old_token")

    logging.info("update_push_token %s -> %s" % (old_token, token))
    passenger = Passenger.from_request(request)

    if passenger and passenger.push_token != token:
        if passenger.push_token:
            deregister_push_token(passenger)

        passenger.mobile_platform = get_mobile_platform(request.META.get("HTTP_USER_AGENT", ""))
        passenger.push_token = token
        passenger.save()

    return HttpResponse("OK")
Ejemplo n.º 25
0
def feedback(request):
    passenger = Passenger.from_request(request)
    if request.POST:
        form = FeedbackForm(data=request.POST, passenger=passenger)
        if form.is_valid():
            for name in Feedback.field_names():
                if form.cleaned_data[name]:
                    logging.info("saving feedback")
                    feedback = form.save()
                    feedback.passenger = passenger
                    feedback.save()
                    break

    else:
        form = FeedbackForm()
        
    return render_to_response('feedback_form.html', locals(), RequestContext(request))
Ejemplo n.º 26
0
def update_push_token(request):
    token = request.POST.get("push_token")
    old_token = request.POST.get("old_token")

    logging.info("update_push_token %s -> %s" % (old_token, token))
    passenger = Passenger.from_request(request)

    if passenger and passenger.push_token != token:
        if passenger.push_token:
            deregister_push_token(passenger)

        passenger.mobile_platform = get_mobile_platform(
            request.META.get('HTTP_USER_AGENT', ""))
        passenger.push_token = token
        passenger.save()

    return HttpResponse("OK")
Ejemplo n.º 27
0
def post_login_redirect(request):
    url = reverse("wb_home")

    passenger = Passenger.from_request(request)
    if not passenger:
        url = reverse(registration, kwargs={'step': 'phone'})

    elif not hasattr(passenger, "billing_info"):
        url = get_token_url(request)  # go to billing registration

    elif request.session.get(CURRENT_BOOKING_DATA_KEY):
        # continue booking process, mobile continues by closing child browser
        if request.mobile:
            url = reverse("wb_home")
        else:
            url = reverse("booking_continued")

    return HttpResponseRedirect(url)
Ejemplo n.º 28
0
def feedback(request):
    passenger = Passenger.from_request(request)
    if request.POST:
        form = FeedbackForm(data=request.POST, passenger=passenger)
        if form.is_valid():
            for name in Feedback.field_names():
                if form.cleaned_data[name]:
                    logging.info("saving feedback")
                    feedback = form.save()
                    feedback.passenger = passenger
                    feedback.save()
                    break

    else:
        form = FeedbackForm()

    return render_to_response('feedback_form.html', locals(),
                              RequestContext(request))
Ejemplo n.º 29
0
def post_login_redirect(request):
    url = reverse("wb_home")

    passenger = Passenger.from_request(request)
    if not passenger:
        url = reverse(registration, kwargs={'step': 'phone'})

    elif not hasattr(passenger, "billing_info"):
        url = get_token_url(request)  # go to billing registration

    elif request.session.get(CURRENT_BOOKING_DATA_KEY):
        # continue booking process, mobile continues by closing child browser
        if request.mobile:
            url = reverse("wb_home")
        else:
            url = reverse("booking_continued")

    return HttpResponseRedirect(url)
Ejemplo n.º 30
0
def update_profile_fb(request, passenger_id, next):
    """
    Callback after passenger approved us to get his data from fb
    """
    logging.info("update facebook profile for passenger[%s]" % passenger_id)

    from ordering.models import Passenger
    passenger = Passenger.by_id(passenger_id)
    if passenger and request.GET.get('code'):
        args = {
            'client_id':
            settings.FACEBOOK_APP_ID,
            # redirect_uri MUST match the one passed in step1 (redirecting to fb)
            'redirect_uri':
            "http://%s%s" %
            (DEFAULT_DOMAIN,
             reverse(update_profile_fb, args=[passenger.id, next])),
            'client_secret':
            settings.FACEBOOK_APP_SECRET,
            'code':
            request.GET['code'],
        }

        url = 'https://graph.facebook.com/oauth/access_token?' +\
              urllib.urlencode(args)

        try:
            response = cgi.parse_qs(urllib.urlopen(url).read())
            logging.info("FB query: %s" % url)
            logging.info("FB response: %s" % response)

            access_token = response['access_token'][0]

            facebook_session = FacebookSession(access_token=access_token)
            profile = facebook_session.query(
                'me',
                fields=['id', 'email', 'first_name', 'last_name', 'picture'])
            passenger.picture_url = profile['picture']['data']['url']
            passenger.fb_id = profile['id']
            passenger.save()
            logging.info("passenger picture updated: %s" %
                         passenger.picture_url)
        except Exception, e:
            pass
Ejemplo n.º 31
0
def transaction_ok(request):
    from analytics.models import BIEvent, BIEventType

    passenger = Passenger.from_request(request)
    if not passenger:
        logging.info("[transaction_ok] not a passenger")
        registration_url = reverse(mobile_registration_view if request.mobiel else web_registration_view)
        return HttpResponseRedirect(registration_url)

    #TODO: handle errors
    #TODO: makesure referrer is creditguard
    ga_track_event(request, "registration", "credit_card_validation", "approved")
    date_string = request.GET.get("cardExp")
    exp_date = date(year=int(date_string[2:]) + 2000, month=int(date_string[:2]), day=1)
    kwargs = {
        "passenger"			: passenger,
        "token"					: request.GET.get("cardToken"),
        "expiration_date"		: exp_date,
        "card_repr"				: request.GET.get("cardMask"),
        "personal_id"          : request.GET.get("personalId")
    }
    # clean up old billing info objects
    BillingInfo.objects.filter(passenger=passenger).delete()

    # save new billing info
    billing_info = BillingInfo(**kwargs)
    billing_info.save()

    BIEvent.log(BIEventType.BILLING_INFO_COMPLETE, passenger=passenger, request=request)

    if request.session.get(CURRENT_BOOKING_DATA_KEY): # continue booking process
        continue_booking_url = settings.CLOSE_CHILD_BROWSER_URI if request.mobile else reverse("booking_continued")
        logging.info("[transaction_ok] continue booking after billing registration --> %s" % continue_booking_url)
        return HttpResponseRedirect(continue_booking_url)
    else:
        account_url = reverse(mobile_account_view if request.mobile else web_account_view)
        return HttpResponseRedirect(account_url)
Ejemplo n.º 32
0
def station_page(request, subdomain_name):
    station = get_object_or_404(models.Station, subdomain_name=subdomain_name)

    ua = request.META.get("HTTP_USER_AGENT", "").lower()

    if station.market_app_url and ua.find("android") > -1:
        ga_hit_page(request)
        return HttpResponseRedirect(station.market_app_url)
    elif station.itunes_app_url and ua.find("iphone") > -1:
        ga_hit_page(request)
        return HttpResponseRedirect(station.itunes_app_url)

    passenger = Passenger.from_request(request)
    if passenger and passenger.business:
        return station_business_page(request, subdomain_name)

    if not request.mobile and CURRENT_PASSENGER_KEY in request.session:
        del request.session[CURRENT_PASSENGER_KEY]

    page_specific_class = "station_page"
    hidden_fields = HIDDEN_FIELDS
    form = OrderForm()
    not_a_user, not_a_passenger = NOT_A_USER, NOT_A_PASSENGER
    waze_token = settings.WAZE_API_TOKEN
    telmap_user = settings.TELMAP_API_USER
    telmap_password = settings.TELMAP_API_PASSWORD
    telmap_languages = 'he' if str(get_language_from_request(request)) == 'he' else 'en'
    country_code = settings.DEFAULT_COUNTRY_CODE
    station_full_name = _("%s Taxi station") % station.name
    website_link = station.get_station_page_link()
    pretty_website_link = website_link.replace("http://", "")
    station_logo = blob_to_image_tag(station.logo)

    if not passenger and request.GET.get("show_login", False):
        show_login = True

    return custom_render_to_response("station_page.html", locals(), context_instance=RequestContext(request))
Ejemplo n.º 33
0
def get_offers(request):
    return JSONResponse({
        'status': 'failed',
        'error': SERVICE_NOT_AVAILABLE_MSG
    })

    order_settings = OrderSettings.fromRequest(request)

    # TODO_WB: save the requested search params and associate with a push_token from request for later notifications of similar searches

    if not order_settings.private:
        candidate_rides = get_candidate_rides(order_settings)
        look_for_discounts = True
    else:
        candidate_rides = []
        look_for_discounts = False

    matching_rides = get_matching_rides(candidate_rides, order_settings)
    if not matching_rides:
        return JSONResponse({'error': u'מצטערים, הכתובת המבוקשת אינה באיזורי הכיסוי עדיין'})

    offers = []

    start_ride_algo_data = None

    for ride_data in matching_rides:
        ride_id = ride_data.ride_id
        ride = SharedRide.by_id(ride_id)

        # get price for offer according to tariff
        tariff = RuleSet.get_active_set(order_settings.pickup_dt)
        price = ride_data.order_price(NEW_ORDER_ID, tariff)
        price_alone = ride_data.order_price(NEW_ORDER_ID, tariff, sharing=False)

        if not price > 0:
            logging.warning("get_offers missing price for %s" % order_settings.pickup_dt)
            continue

        if ride_id == NEW_ORDER_ID:  # start a new ride
            start_ride_algo_data = ride_data
            offer = {
                "asap": order_settings.asap,
                "pickup_time": to_js_date(order_settings.pickup_dt),
                "price": price,
                "seats_left": MAX_SEATS,
                "new_ride": True,
                "comment": _(u"You will be updated when someone joins")  # TODO_WB: sharing chances
            }

        else:  # sharing offers
            time_sharing = ride_data.order_time(NEW_ORDER_ID)
            time_alone = ride_data.order_time(NEW_ORDER_ID, sharing=False)
            time_addition = int((time_sharing - time_alone) / 60)

            pickup_point = ride_data.order_pickup_point(NEW_ORDER_ID)
            ride_orders = ride.orders.all()
            pickup_time = compute_new_departure(ride, ride_data) + datetime.timedelta(seconds=pickup_point.offset)
            if pickup_time < default_tz_now() + datetime.timedelta(minutes=asap_interval()):
                logging.info("skipping offer because pickup_time is too soon: %s" % pickup_time)
                continue

            offer = {
                "ride_id": ride_id,
                "pickup_time": to_js_date(pickup_time),
                "passengers": [{'name': order.passenger.name, 'picture_url': order.passenger.picture_url} for order in ride_orders for seat in range(order.num_seats)],
                "seats_left": MAX_SEATS - sum([order.num_seats for order in ride_orders]),
                "price": price,
                "new_ride": False,
                "comment": _(u"Money saved: %(money_saved)s NIS or more – additional time: %(time_added)s min") % {'time_added': time_addition, 'money_saved': "%g" % (price_alone - price)}
            }

            # good enough offer found, no discounts
            if order_settings.pickup_dt - datetime.timedelta(minutes=30) < pickup_time < order_settings.pickup_dt + datetime.timedelta(minutes=30):
                look_for_discounts = False

        offers.append(offer)

    # add discounted offers if relevant

    ## override
    look_for_discounts = True
    ## override

    if look_for_discounts and start_ride_algo_data:
        offers += get_discounted_offers(request, order_settings, start_ride_algo_data)

    offers = sorted(offers, key=lambda  o: o["pickup_time"], reverse=False)

    deferred.defer(save_search_req_and_offers, Passenger.from_request(request), order_settings, offers)
    return JSONResponse({'offers': offers})
Ejemplo n.º 34
0
def is_token_valid(request):
    p = Passenger.from_request(request)
    is_valid = p is not None and p.login_token and p.login_token == request.POST.get("passenger_token")
    logging.info("is_token_valid: %s: %s" % (p, is_valid))
    return JSONResponse({'valid': is_valid})
Ejemplo n.º 35
0
def create_ride(address, comments, passenger_phone, first_name, last_name,
                start_time, finish_time, station_id, as_raw_output):
    from common.tz_support import set_default_tz_time
    from geo.coder import geocode

    if not address:
        return "Please choose a valid street address: street, house number and city"

    lat, lon, city, street, house_number = None, None, None, None, None
    results = geocode(address, lang_code="he")
    if results:
        result = results[0]
        if "street_address" in result["types"]:
            lat = result["geometry"]["location"]["lat"]
            lon = result["geometry"]["location"]["lng"]

            for component in result["address_components"]:
                if "street_number" in component["types"]:
                    house_number = component["short_name"]
                if "route" in component["types"]:
                    street = component["short_name"]
                if "locality" in component["types"]:
                    city_name = component["short_name"]
                    city = City.objects.get(name=city_name)

    if not all([lat, lon, city, street, house_number]):
        return "Please choose a valid street address: street, house number and city"

    user = User()
    user.first_name = first_name
    user.last_name = last_name

    passenger = Passenger()
    passenger.user = user
    passenger.phone = passenger_phone
    passenger.id = random.randrange(1, 999999)

    order = Order()
    order.id = random.randrange(1, 999999)
    order.from_raw = address
    order.from_city = city
    order.from_street_address = street
    order.from_house_number = house_number
    order.from_lat = lat
    order.from_lon = lon
    order.comments = comments
    order.depart_time = set_default_tz_time(
        datetime.datetime.strptime(
            start_time, "%Y-%m-%dT%H:%M:%S")) if start_time else None
    order.arrive_time = set_default_tz_time(
        datetime.datetime.strptime(
            finish_time, "%Y-%m-%dT%H:%M:%S")) if finish_time else None
    order.passenger = passenger

    station = Station()
    station.fleet_manager = isr_fm
    station.fleet_station_id = station_id or 8  # waybetter station operator id

    ride = FakeSharedRide([order])
    ride.id = random.randrange(1, 999999)
    ride.station = station
    ride.dn_fleet_manager_id = isr_fm.id
    ride.status = ASSIGNED

    DEV_WB_ONGOING_RIDES.append(ride)

    if as_raw_output:
        ex_order = ISR._create_external_order(order, station.fleet_station_id)
        reply = ISR._get_client().service.Insert_External_Order(
            ISR._get_login_token(), ex_order)
        return reply

    return "%s ride id=%s" % (fleet_manager.create_ride(ride), ride.id)
Ejemplo n.º 36
0
    phone_formatted = _("Not Entered")
    bi_formatted = _("Not Entered")

    if request.method == "POST":
        new_email = request.POST.get("email", "").strip() or None
        new_first_name, new_last_name = get_name_parts(
            request.POST.get("fullname") or None)
        try:
            user = update_user_details(user,
                                       first_name=new_first_name,
                                       last_name=new_last_name,
                                       email=new_email)
        except UpdateUserError, e:
            error = e.message

    passenger = Passenger.from_request(request)
    if passenger:
        phone_formatted = passenger.phone
        profile_picture_url = passenger.picture_url
        if hasattr(passenger, "billing_info"):
            bi = passenger.billing_info
            card_formatted = "%s%s" % ("**** " * 4, bi.card_repr[-4:])
            exp_formatted = bi.expiration_date.strftime("%m/%y")
            bi_formatted = "%s %s: %s" % (card_formatted, _("Exp"),
                                          exp_formatted)

    user_data = [
        {
            'name': "fullname",
            'label': _("Full Name"),
            'value': user.get_full_name
Ejemplo n.º 37
0
@login_required
def user_profile(request):
    page_specific_class = "user_profile"
    user = request.user
    phone_formatted = _("Not Entered")
    bi_formatted = _("Not Entered")

    if request.method == "POST":
        new_email = request.POST.get("email", "").strip() or None
        new_first_name, new_last_name = get_name_parts(request.POST.get("fullname") or None)
        try:
            user = update_user_details(user, first_name=new_first_name, last_name=new_last_name, email=new_email)
        except UpdateUserError, e:
            error = e.message

    passenger = Passenger.from_request(request)
    if passenger:
        phone_formatted = passenger.phone
        profile_picture_url = passenger.picture_url
        if hasattr(passenger, "billing_info"):
            bi = passenger.billing_info
            card_formatted = "%s%s" % ("**** " * 4, bi.card_repr[-4:])
            exp_formatted = bi.expiration_date.strftime("%m/%y")
            bi_formatted = "%s %s: %s" % (card_formatted, _("Exp"), exp_formatted)

    user_data = [
            {'name': "fullname", 'label': _("Full Name"), 'value': user.get_full_name},
            {'name': "email", 'label': _("Email Address"), 'value': user.email},
            {'name': "mobile", 'label': _("Mobile Phone"), 'value': phone_formatted},
            {'name': "billing", 'label': _("Billing Info"), 'value': bi_formatted},
    ]
Ejemplo n.º 38
0
def create_ride(address, comments, passenger_phone, first_name, last_name, start_time, finish_time, station_id, as_raw_output):
    from common.tz_support import set_default_tz_time
    from geo.coder import geocode

    if not address:
        return "Please choose a valid street address: street, house number and city"

    lat, lon, city, street, house_number = None, None, None, None, None
    results = geocode(address, lang_code="he")
    if results:
        result = results[0]
        if "street_address" in result["types"]:
            lat = result["geometry"]["location"]["lat"]
            lon = result["geometry"]["location"]["lng"]

            for component in result["address_components"]:
                if "street_number" in component["types"]:
                    house_number = component["short_name"]
                if "route" in component["types"]:
                    street = component["short_name"]
                if "locality" in component["types"]:
                    city_name = component["short_name"]
                    city = City.objects.get(name=city_name)

    if not all([lat, lon, city, street, house_number]):
        return "Please choose a valid street address: street, house number and city"

    user = User()
    user.first_name = first_name
    user.last_name = last_name

    passenger = Passenger()
    passenger.user = user
    passenger.phone = passenger_phone
    passenger.id = random.randrange(1, 999999)

    order = Order()
    order.id = random.randrange(1, 999999)
    order.from_raw = address
    order.from_city = city
    order.from_street_address = street
    order.from_house_number = house_number
    order.from_lat = lat
    order.from_lon = lon
    order.comments = comments
    order.depart_time = set_default_tz_time(datetime.datetime.strptime(start_time, "%Y-%m-%dT%H:%M:%S")) if start_time else None
    order.arrive_time = set_default_tz_time(datetime.datetime.strptime(finish_time, "%Y-%m-%dT%H:%M:%S")) if finish_time else None
    order.passenger = passenger

    station = Station()
    station.fleet_manager = isr_fm
    station.fleet_station_id = station_id or 8 # waybetter station operator id

    ride = FakeSharedRide([order])
    ride.id = random.randrange(1, 999999)
    ride.station = station
    ride.dn_fleet_manager_id = isr_fm.id
    ride.status = ASSIGNED

    DEV_WB_ONGOING_RIDES.append(ride)

    if as_raw_output:
        ex_order = ISR._create_external_order(order, station.fleet_station_id)
        reply = ISR._get_client().service.Insert_External_Order(ISR._get_login_token(), ex_order)
        return reply

    return "%s ride id=%s" % (fleet_manager.create_ride(ride), ride.id)
Ejemplo n.º 39
0
def book_ride(request):
    return JSONResponse({
        'status': 'failed',
        'error': SERVICE_NOT_AVAILABLE_MSG
    })

    passenger = Passenger.from_request(request)
    request_data = simplejson.loads(request.POST.get('data'))
    logging.info(u"book ride: %s\n%s" % (passenger, unicode(simplejson.dumps(request_data), "unicode-escape")))

    result = {
        'status': '',
        'order_id': None,
        'redirect': '',
        'error': '',
        'pickup_dt': None
    }

    if passenger and passenger.user and hasattr(passenger, "billing_info"): # we have logged-in passenger with billing_info - let's proceed
        order_settings = OrderSettings.fromRequest(request)
        ride_id = request_data.get("ride_id")

        new_ride = (ride_id == NEW_ORDER_ID)
        discounted_ride = (ride_id and str(ride_id).startswith(DISCOUNTED_OFFER_PREFIX))

        join_ride = not (new_ride or discounted_ride)
        ride_to_join = SharedRide.by_id(ride_id) if join_ride else None

        order = None
        if ride_to_join:  # check it is indeed a valid candidate
            if is_valid_candidate(ride_to_join, order_settings):
                order = create_order(order_settings, passenger, ride=ride_to_join)
            else:
                logging.warning("tried booking an invalid ride candidate")
                result['error'] = _("Sorry, but this ride has been closed for booking")

        else:  # new or discounted ride, check pickup time isn't before ASAP (minus a couple seconds to allow booking to exactly ASAP)
            if order_settings.pickup_dt <= default_tz_now() + datetime.timedelta(minutes=asap_interval()) - datetime.timedelta(seconds=10):
                logging.warning("tried booking to expired pickup time %s" % order_settings.pickup_dt)
                result['error'] = _("Please choose a later pickup time")
            else:
                if discounted_ride:
                    cached_discount_data = memcache.get(ride_id, namespace=DISCOUNTED_OFFERS_NS)
                    discount_data = DiscountData.load(cached_discount_data)
                    logging.info("[book_ride] discount_data = %s" % discount_data)
                    order = create_order(order_settings, passenger, discount_data=discount_data)
                else:
                    order = create_order(order_settings, passenger)


        if order:
            result['status'] = 'success'
            result['order_id'] = order.id
            result['pickup_formatted'] = order.from_raw
            result['pickup_dt'] = to_js_date(order.depart_time)
            result["price"] = order.get_billing_amount()

            ride_orders = [order] + ( list(ride_to_join.orders.all()) if ride_to_join else [] )
            result["passengers"] = [{'name': o.passenger.name, 'picture_url': o.passenger.picture_url, 'is_you': o==order} for o in ride_orders for seat in range(o.num_seats)]
            result["seats_left"] = MAX_SEATS - sum([o.num_seats for o in ride_orders])

            deferred.defer(join_offer_and_order, order, request_data)

        else:
            result['status'] = 'failed'

    else:  # not authorized for booking, save current booking state in session
        set_current_booking_data(request)

        if passenger and not hasattr(passenger, "billing_info"):
            result['status'] = 'billing_failed'
            result['redirect'] = get_token_url(request) # go to billing
        else:
            result['status'] = 'auth_failed'

    logging.info("book ride result: %s" % result)
    return JSONResponse(result)