Ejemplo n.º 1
0
def business_registration(request):
    if request.method == "POST":
        form = BusinessRegistrationForm(request.POST)
        if form.is_valid():
            business = form.save()
            log_event(EventType.BUSINESS_REGISTERED, passenger=business.passenger)

            # send a welcoming email to the business
            business.send_welcome_email(form.cleaned_data["password"])
            response = {"business_created": True}

        else:  # form invalid
            errors = [{e: form.errors.get(e)} for e in form.errors.keys()]
            response = {"errors": errors}

        return JSONResponse(response)

    else:  # GET
        interest_id = request.GET.get("from_interest_id", None)
        if interest_id:
            interest = BusinessInterest.objects.get(id=int(interest_id))
            data = {"email": interest.email, "contact_person": interest.contact_person, "phone": interest.phone}

            if interest.from_station:
                data.update({"from_station": interest.from_station.id})
                from_station_name = interest.from_station.name

            form = BusinessRegistrationForm(initial=data)

        else:
            form = BusinessRegistrationForm()

        return custom_render_to_response(
            "business_registration.html", locals(), context_instance=RequestContext(request)
        )
Ejemplo n.º 2
0
def assign_order(order):
    """
    Assign the order to a workstation and return the assignment.
    """
    passenger = order.passenger
    work_station = choose_workstation(order)
    if not work_station:
        raise NoWorkStationFoundError("Could not find a valid station")

    # create an OrderAssignment
    assignment = OrderAssignment(order=order, station=work_station.station, work_station=work_station)
    assignment.pickup_address_in_ws_lang = translate_address_for_ws(work_station, order, 'from')
    assignment.dropoff_address_in_ws_lang = translate_address_for_ws(work_station, order, 'to')

    assignment.save()

    work_station.last_assignment_date = assignment.create_date
    work_station.save()
    work_station.station.last_assignment_date = assignment.create_date
    work_station.station.save()

    try:
        order.change_status(new_status=models.ASSIGNED)
        log_event(EventType.ORDER_ASSIGNED,
                  passenger=passenger,
                  order=order,
                  order_assignment=assignment,
                  station=work_station.station,
                  work_station=work_station)
        # emit the signal only if the order was successfully marked as ASSIGNED
        orderassignment_created_signal.send(sender="orderassignment_created_signal", obj=assignment)
    except UpdateStatusError:
        logging.error("Cannot assign order: %d" % order.id)

    return assignment
Ejemplo n.º 3
0
def log_connection_events(sender, signal_type, obj, **kwargs):
    from common.tz_support import utc_now
    from django.core.urlresolvers import reverse
    from google.appengine.api.taskqueue import taskqueue
    from analytics.models import AnalyticsEvent
    from common.util import  log_event, EventType, notify_by_email
    from ordering.signals import   SignalType
    from ordering.station_connection_manager import ALERT_DELTA, handle_dead_workstations

    last_event_qs = AnalyticsEvent.objects.filter(work_station=obj, type__in=[EventType.WORKSTATION_UP, EventType.WORKSTATION_DOWN]).order_by('-create_date')[:1]
    station = obj.station

    if signal_type == SignalType.WORKSTATION_ONLINE:
        if last_event_qs:
            # send workstation reconnect mail
            last_event = last_event_qs[0]
            if last_event.type == EventType.WORKSTATION_DOWN and (utc_now() - last_event.create_date) >= ALERT_DELTA and station.show_on_list:
                msg = u"Workstation is up again:\n\tid = %d station = %s" % (obj.id, obj.dn_station_name)
                notify_by_email(u"Workstation Reconnected", msg=msg)
        elif station.show_on_list:
            # send "new workstation" mail
            msg = u"A new workstation just connected: id = %d station = %s" % (obj.id, obj.dn_station_name)
            notify_by_email(u"New Workstation", msg=msg)

        log_event(EventType.WORKSTATION_UP, station=station, work_station=obj)

    elif signal_type == SignalType.WORKSTATION_OFFLINE:
        log_event(EventType.WORKSTATION_DOWN, station=station, work_station=obj)

        if station.show_on_list:
            # add task to check if workstation is still dead after ALERT_DELTA
            task = taskqueue.Task(url=reverse(handle_dead_workstations),
                                  countdown=ALERT_DELTA.seconds + 1,
                                  params={"workstation_id": obj.id})
            taskqueue.Queue('log-events').add(task)
Ejemplo n.º 4
0
def rate_order(request, order_id, passenger):
    order = get_object_or_404(Order, id=order_id)
    if order.passenger != passenger:
        return HttpResponseForbidden(_("You can't rate this order"))
    rating = int(request.POST["rating"])
    if rating > 0:
        order.passenger_rating = rating
    else:
        order.passenger_rating = None
    order.save()
    log_event(EventType.ORDER_RATED,
              order=order,
              rating=rating,
              passenger=passenger,
              station=order.station)
    # update async the station rating
    task = taskqueue.Task(url=reverse(update_station_rating),
                          countdown=10,
                          params={
                              "rating":
                              rating,
                              "station_id":
                              order.station_id if order.station else ""
                          })

    q = taskqueue.Queue('update-station-rating')
    q.add(task)
    return HttpResponse("OK")
Ejemplo n.º 5
0
def book_order(request):
    """
    Book an order: send it to the dispatcher to get an order assignment,
    then pass the assignment to the station manager.
    """
    order_id = int(request.POST["order_id"])
    logging.info("book_order_task: %d" % order_id)
    order = get_object_or_404(Order, id=order_id)
    passenger = order.passenger

    # if this is the first order of this passenger, connect him with the station that originated the order
    if order.originating_station and passenger.orders.count() == 1:
        logging.info("assigning passenger %s to station %s" % (passenger, order.originating_station))
        passenger.originating_station = order.originating_station
        if not passenger.default_station:
            passenger.default_station = order.originating_station

        passenger.save()

    sorry_msg = ugettext_noop("We're sorry, but we could not find a taxi for you") # use dummy ugettext for makemessages)

    # check if dispatching should stop and return an answer to the user
    if (utc_now() - order.create_date).seconds > ORDER_HANDLE_TIMEOUT:
        try:
            order.change_status(new_status=TIMED_OUT)
            send_msg_to_passenger(passenger, translate_to_lang(sorry_msg, order.language_code))
            logging.warning("order time out: %d" % order_id)
            response = HttpResponse(ORDER_TIMEOUT)
        except UpdateStatusError:
            logging.error("book_order failed: cannot set order [%d] status to %s" % (order.id, "TIME_OUT"))
    else:
        try:
            # choose an assignment for the order and push it to the relevant workstation
            order_assignment = dispatcher.assign_order(order)
            push_order(order_assignment)
            enqueue_redispatch_orders(order_assignment, ORDER_TEASER_TIMEOUT, redispatch_pending_orders)
            response = HttpResponse(ORDER_HANDLED)

        except NoWorkStationFoundError:
            try:
                order.change_status(new_status=FAILED)
                send_msg_to_passenger(passenger, translate_to_lang(sorry_msg, order.language_code)) # use dummy ugettext for makemessages

                log_event(EventType.ORDER_FAILED, order=order, passenger=order.passenger)
                logging.warning("no matching workstation found for: %d" % order_id)
                response = HttpResponse(NO_MATCHING_WORKSTATIONS_FOUND)
            except UpdateStatusError:
                logging.error("book_order failed: cannot set order [%d] status to %s" % (order.id, "FAILED"))

        except Exception, e:
            try:
                order.change_status(new_status=ERROR)
                send_msg_to_passenger(passenger, translate_to_lang(ugettext_noop("We're sorry, but we have encountered an error while handling your request")
                             , order.language_code)) # use dummy ugettext for makemessages
                log_event(EventType.ORDER_ERROR, order=order, passenger=order.passenger)
                logging.error("book_order: OrderError: %d" % order_id)
                raise # handle exception in decorator 
            except UpdateStatusError:
                logging.error("book_order failed: cannot set order [%d] status to %s" % (order.id, "ERROR"))
Ejemplo n.º 6
0
def update_order_status(order_id, work_station, new_status, pickup_time=None):
    """
    raises UpdateOrderError
    """
    try:
        order_assignment = OrderAssignment.objects.get(order=order_id, work_station=work_station, status=ASSIGNED)
    except OrderAssignment.DoesNotExist:
        logging.error("No ASSIGNED assignment for order %d in work station %d" % (order_id, work_station.id))
        raise UpdateOrderError()

    result = {'order_id': order_id}

    if order_assignment.is_stale():
        try:
            order_assignment.change_status(ASSIGNED, IGNORED)
            result["order_status"] = "stale"
            return result
        except UpdateStatusError:
            logging.error("update_order_status failed [%d]: cannot mark assignment as %s" % (order_id, "IGNORED"))

    if new_status == station_controller.ACCEPT and pickup_time:
        try:
            order_assignment.change_status(ASSIGNED, ACCEPTED)
            accept_order(order_assignment.order, pickup_time, order_assignment.station)
            log_event(EventType.ORDER_ACCEPTED,
                      passenger=order_assignment.order.passenger,
                      order=order_assignment.order,
                      order_assignment=order_assignment,
                      station=work_station.station,
                      work_station=work_station)
            order_assignment.order.notify()
            result["pickup_message"] = _("Message sent, pickup in %s minutes") % pickup_time
            result["pickup_address"] = order_assignment.pickup_address_in_ws_lang
            result["dropoff_address"] = order_assignment.dropoff_address_in_ws_lang
            return result

        except UpdateStatusError:
            logging.error("update_order_status failed [%d]: cannot mark assignment as %s" % (order_id, "ACCEPTED"))

    elif new_status == station_controller.REJECT:
        try:
            order_assignment.change_status(ASSIGNED, REJECTED)
            log_event(EventType.ORDER_REJECTED,
                      passenger=order_assignment.order.passenger,
                      order=order_assignment.order,
                      order_assignment=order_assignment,
                      station=work_station.station,
                      work_station=work_station)
            book_order_async(order_assignment.order, order_assignment)
            return result

        except UpdateStatusError:
            logging.error("update_order_status failed [%d]: cannot mark assignment as %s" % (order_id, "REJECTED"))

    else:
        raise UpdateOrderError("Invalid status")
Ejemplo n.º 7
0
    def create(self, request, *args, **kwargs):
        api_user = kwargs["api_user"]
        request_data = request.data.get("request")
        if not request_data:
            return rc.BAD_REQUEST

        language_code = request_data.get("language_code")
        translation.activate(language_code)

        passenger = None
        phone_number = request_data.get("phone_number")
        login_token = request_data.get("login_token")

        try:
            if login_token: #TODO_WB: merge needed to make this work
                passenger = Passenger.objects.get(login_token=login_token)
            elif phone_number and not api_user.phone_validation_required:
                passenger = Passenger.objects.get(phone=phone_number) 
        except Passenger.DoesNotExist:
            pass

        if not passenger:
            return rc.NOT_FOUND #TODO_WB: is this the right response

        order_data = {}
        for address_type in ('from', 'to'):
            for att, val in request_data[address_type].items():
                order_data[address_type + "_" + att] = val or ""

            if not is_valid_address(order_data, address_type):
                res = rc.BAD_REQUEST
                res.write(" %s\n" % ErrorCodes.INVALID_ADDRESS)
                return res

            order_data[address_type + "_country"] = Country.get_id_by_code(order_data[address_type + "_country"])
            order_data[address_type + "_city"] = City.get_id_by_name_and_country(order_data[address_type + "_city"], order_data[address_type + "_country"], add_if_not_found=True)

        order_form = OrderForm(data=order_data, passenger=passenger)
        if order_form.is_valid():

            order = order_form.save()
            order.api_user = api_user
            order.passenger = passenger
            order.language_code = language_code
            order.save()
            book_order_async(order)
            log_event(EventType.ORDER_BOOKED, order=order)
            return rc.CREATED
        else:
            response = rc.BAD_REQUEST
            response.write(" %s\n" % order_form.errors.as_text())
            return response
Ejemplo n.º 8
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.º 9
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.º 10
0
    def clean(self):
        to_country = self.cleaned_data.get('to_country')
        from_country = self.cleaned_data.get('from_country')
        from_lon = self.cleaned_data.get('from_lon')
        from_lat = self.cleaned_data.get('from_lat')
        to_lon = self.cleaned_data.get('to_lon')
        to_lat = self.cleaned_data.get('to_lat')
        from_city = self.cleaned_data.get('from_city')
        to_city = self.cleaned_data.get('to_city')

        if self.passenger and self.passenger.is_banned:
            raise forms.ValidationError(_("Your account has been suspended. Please contact [email protected]"))

        if to_country and from_country != to_country:
            log_event(EventType.CROSS_COUNTRY_ORDER_FAILURE, passenger=self.passenger, country=to_country)
            raise forms.ValidationError(_("To and From countries do not match"), code=ErrorCodes.COUNTRIES_DONT_MATCH)

        stations_count = Station.objects.filter(country=from_country).count()
        if not stations_count:
            log_event(EventType.NO_SERVICE_IN_COUNTRY, passenger=self.passenger, country=from_country)
            raise forms.ValidationError(_("Currently, there is no service in the country"),
                                        code=ErrorCodes.NO_SERVICE_IN_COUNTRY)

        # orders with originating station are confined to this station
        if self.cleaned_data["originating_station"]:
            self.cleaned_data["confining_station"] = self.cleaned_data["originating_station"]
        # otherwise check if there is a nearby station
        else:
            # TODO_WB: move this check to the DB?
            close_enough_station_found = False
            stations = Station.objects.filter(country=from_country)

            user = self.passenger.user if self.passenger else None
            if user and user.is_staff:
                pass
            else:
                stations = stations.filter(show_on_list=True)

            for station in stations:
                if station.is_in_valid_distance(from_lon=from_lon, from_lat=from_lat, to_lon=to_lon, to_lat=to_lat):
                    close_enough_station_found = True
                    break

            if not close_enough_station_found:
                log_event(EventType.NO_SERVICE_IN_CITY, passenger=self.passenger, city=from_city, lat=from_lat,
                          lon=from_lon)
                if to_city and from_city != to_city:
                    log_event(EventType.NO_SERVICE_IN_CITY, passenger=self.passenger, city=to_city, lat=to_lat, lon=to_lon)

                raise forms.ValidationError(
                    _(
                        "Service is not available in %(city)s yet.\nPlease try again soon.\nTHANKS!\nWAYbetter team :)") %
                    {'city': from_city.name}, code=ErrorCodes.NO_SERVICE_IN_CITY)

        return self.cleaned_data
Ejemplo n.º 11
0
def log_connection_events(sender, signal_type, obj, **kwargs):
    from common.tz_support import utc_now
    from django.core.urlresolvers import reverse
    from google.appengine.api.taskqueue import taskqueue
    from analytics.models import AnalyticsEvent
    from common.util import log_event, EventType, notify_by_email
    from ordering.signals import SignalType
    from ordering.station_connection_manager import ALERT_DELTA, handle_dead_workstations

    last_event_qs = AnalyticsEvent.objects.filter(
        work_station=obj,
        type__in=[EventType.WORKSTATION_UP,
                  EventType.WORKSTATION_DOWN]).order_by('-create_date')[:1]
    station = obj.station

    if signal_type == SignalType.WORKSTATION_ONLINE:
        if last_event_qs:
            # send workstation reconnect mail
            last_event = last_event_qs[0]
            if last_event.type == EventType.WORKSTATION_DOWN and (
                    utc_now() - last_event.create_date
            ) >= ALERT_DELTA and station.show_on_list:
                msg = u"Workstation is up again:\n\tid = %d station = %s" % (
                    obj.id, obj.dn_station_name)
                notify_by_email(u"Workstation Reconnected", msg=msg)
        elif station.show_on_list:
            # send "new workstation" mail
            msg = u"A new workstation just connected: id = %d station = %s" % (
                obj.id, obj.dn_station_name)
            notify_by_email(u"New Workstation", msg=msg)

        log_event(EventType.WORKSTATION_UP, station=station, work_station=obj)

    elif signal_type == SignalType.WORKSTATION_OFFLINE:
        log_event(EventType.WORKSTATION_DOWN,
                  station=station,
                  work_station=obj)

        if station.show_on_list:
            # add task to check if workstation is still dead after ALERT_DELTA
            task = taskqueue.Task(url=reverse(handle_dead_workstations),
                                  countdown=ALERT_DELTA.seconds + 1,
                                  params={"workstation_id": obj.id})
            taskqueue.Queue('log-events').add(task)
Ejemplo n.º 12
0
def rate_order(request, order_id, passenger):
    order = get_object_or_404(Order, id=order_id)
    if order.passenger != passenger:
        return HttpResponseForbidden(_("You can't rate this order"))
    rating = int(request.POST["rating"])
    if rating > 0:
        order.passenger_rating = rating
    else:
        order.passenger_rating = None
    order.save()
    log_event(EventType.ORDER_RATED, order=order, rating=rating, passenger=passenger, station=order.station)
    # update async the station rating
    task = taskqueue.Task(url=reverse(update_station_rating),
                          countdown=10,
                          params={"rating": rating, "station_id": order.station_id if order.station else ""})

    q = taskqueue.Queue('update-station-rating')
    q.add(task)
    return HttpResponse("OK")
Ejemplo n.º 13
0
def redispatch_ignored_orders(request, order_assignment):
    """
    If assigning time is up mark the assignment as IGNORED and book the order again.
    """
    logging.info("redispatch_ignored orders: %d" % order_assignment.id)

    try:
        order_assignment.change_status(ASSIGNED, IGNORED)
        log_event(EventType.ORDER_IGNORED,
                  passenger=order_assignment.order.passenger,
                  order=order_assignment.order,
                  order_assignment=order_assignment,
                  station=order_assignment.station,
                  work_station=order_assignment.work_station)
        book_order_async(order_assignment.order, order_assignment)
    except UpdateStatusError:
        logging.warning("redispatch_ignored_orders failed: cannot mark assignment [%d] as %s" % (order_assignment.id, "IGNORED"))

    return HttpResponse(OK)
Ejemplo n.º 14
0
def redispatch_pending_orders(request, order_assignment):
    """
    If teaser time is up mark the assignment as NOT_TAKEN and book the order again.
    """
    logging.info("redispatch_pending_orders: %d" % order_assignment.id)

    try:
        order_assignment.change_status(PENDING, NOT_TAKEN)
        log_event(EventType.ORDER_NOT_TAKEN,
                  passenger=order_assignment.order.passenger,
                  order=order_assignment.order,
                  order_assignment=order_assignment,
                  station=order_assignment.station,
                  work_station=order_assignment.work_station)
        book_order_async(order_assignment.order, order_assignment)
    except UpdateStatusError:
        logging.warning("redispatch_pending_orders failed: cannot mark assignment [%d] as %s" % (order_assignment.id, "NOT_TAKEN"))

    return HttpResponse(OK)
Ejemplo n.º 15
0
def business_registration(request):
    if request.method == 'POST':
        form = BusinessRegistrationForm(request.POST)
        if form.is_valid():
            business = form.save()
            log_event(EventType.BUSINESS_REGISTERED,
                      passenger=business.passenger)

            # send a welcoming email to the business
            business.send_welcome_email(form.cleaned_data["password"])
            response = {"business_created": True}

        else:  # form invalid
            errors = [{e: form.errors.get(e)} for e in form.errors.keys()]
            response = {"errors": errors}

        return JSONResponse(response)

    else:  # GET
        interest_id = request.GET.get('from_interest_id', None)
        if interest_id:
            interest = BusinessInterest.objects.get(id=int(interest_id))
            data = {
                "email": interest.email,
                "contact_person": interest.contact_person,
                "phone": interest.phone
            }

            if interest.from_station:
                data.update({"from_station": interest.from_station.id})
                from_station_name = interest.from_station.name

            form = BusinessRegistrationForm(initial=data)

        else:
            form = BusinessRegistrationForm()

        return custom_render_to_response(
            "business_registration.html",
            locals(),
            context_instance=RequestContext(request))
Ejemplo n.º 16
0
def redispatch_ignored_orders(request, order_assignment):
    """
    If assigning time is up mark the assignment as IGNORED and book the order again.
    """
    logging.info("redispatch_ignored orders: %d" % order_assignment.id)

    try:
        order_assignment.change_status(ASSIGNED, IGNORED)
        log_event(EventType.ORDER_IGNORED,
                  passenger=order_assignment.order.passenger,
                  order=order_assignment.order,
                  order_assignment=order_assignment,
                  station=order_assignment.station,
                  work_station=order_assignment.work_station)
        book_order_async(order_assignment.order, order_assignment)
    except UpdateStatusError:
        logging.warning(
            "redispatch_ignored_orders failed: cannot mark assignment [%d] as %s"
            % (order_assignment.id, "IGNORED"))

    return HttpResponse(OK)
Ejemplo n.º 17
0
def redispatch_pending_orders(request, order_assignment):
    """
    If teaser time is up mark the assignment as NOT_TAKEN and book the order again.
    """
    logging.info("redispatch_pending_orders: %d" % order_assignment.id)

    try:
        order_assignment.change_status(PENDING, NOT_TAKEN)
        log_event(EventType.ORDER_NOT_TAKEN,
                  passenger=order_assignment.order.passenger,
                  order=order_assignment.order,
                  order_assignment=order_assignment,
                  station=order_assignment.station,
                  work_station=order_assignment.work_station)
        book_order_async(order_assignment.order, order_assignment)
    except UpdateStatusError:
        logging.warning(
            "redispatch_pending_orders failed: cannot mark assignment [%d] as %s"
            % (order_assignment.id, "NOT_TAKEN"))

    return HttpResponse(OK)
Ejemplo n.º 18
0
                order.confining_station = stations[0]
            else:
                return error_response(_("Could not send order to specified station"))

        order.save()
        order_created_signal.send(sender="order_created_signal", obj=order)

        if passenger.phone != settings.APPLE_TESTER_PHONE_NUMBER:
            order_manager.book_order_async(order)
        else:  # assign order to test station so the user will see it in his history
            order.station = Station.by_id(1713061)
            order.pickup_time = 5
            order.save()
            order.change_status(old_status=PENDING, new_status=ACCEPTED)

        log_event(EventType.ORDER_BOOKED, order=order)

        book_order_message = _("An SMS with ride details will arrive shortly...")
        if order.originating_station_id:
            book_order_message = (
                _("%s is looking for a free taxi. An SMS with ride details will arrive shortly...")
                % order.originating_station.name
            )

        book_order_result = {
            "status": "booked",
            "message": book_order_message,
            "order_id": order.id,
            "tracker_msg": simplejson.dumps(order_tracker.get_tracker_msg_for_order(order)),
            "show_registration": 0 if order.passenger.user else 1,  # signal the show registration dialog
        }
Ejemplo n.º 19
0
def book_order(request):
    """
    Book an order: send it to the dispatcher to get an order assignment,
    then pass the assignment to the station manager.
    """
    order_id = int(request.POST["order_id"])
    logging.info("book_order_task: %d" % order_id)
    order = get_object_or_404(Order, id=order_id)
    passenger = order.passenger

    # if this is the first order of this passenger, connect him with the station that originated the order
    if order.originating_station and passenger.orders.count() == 1:
        logging.info("assigning passenger %s to station %s" %
                     (passenger, order.originating_station))
        passenger.originating_station = order.originating_station
        if not passenger.default_station:
            passenger.default_station = order.originating_station

        passenger.save()

    sorry_msg = ugettext_noop(
        "We're sorry, but we could not find a taxi for you"
    )  # use dummy ugettext for makemessages)

    # check if dispatching should stop and return an answer to the user
    if (utc_now() - order.create_date).seconds > ORDER_HANDLE_TIMEOUT:
        try:
            order.change_status(new_status=TIMED_OUT)
            send_msg_to_passenger(
                passenger, translate_to_lang(sorry_msg, order.language_code))
            logging.warning("order time out: %d" % order_id)
            response = HttpResponse(ORDER_TIMEOUT)
        except UpdateStatusError:
            logging.error(
                "book_order failed: cannot set order [%d] status to %s" %
                (order.id, "TIME_OUT"))
    else:
        try:
            # choose an assignment for the order and push it to the relevant workstation
            order_assignment = dispatcher.assign_order(order)
            push_order(order_assignment)
            enqueue_redispatch_orders(order_assignment, ORDER_TEASER_TIMEOUT,
                                      redispatch_pending_orders)
            response = HttpResponse(ORDER_HANDLED)

        except NoWorkStationFoundError:
            try:
                order.change_status(new_status=FAILED)
                send_msg_to_passenger(passenger,
                                      translate_to_lang(
                                          sorry_msg, order.language_code)
                                      )  # use dummy ugettext for makemessages

                log_event(EventType.ORDER_FAILED,
                          order=order,
                          passenger=order.passenger)
                logging.warning("no matching workstation found for: %d" %
                                order_id)
                response = HttpResponse(NO_MATCHING_WORKSTATIONS_FOUND)
            except UpdateStatusError:
                logging.error(
                    "book_order failed: cannot set order [%d] status to %s" %
                    (order.id, "FAILED"))

        except Exception, e:
            try:
                order.change_status(new_status=ERROR)
                send_msg_to_passenger(
                    passenger,
                    translate_to_lang(
                        ugettext_noop(
                            "We're sorry, but we have encountered an error while handling your request"
                        ), order.language_code
                    ))  # use dummy ugettext for makemessages
                log_event(EventType.ORDER_ERROR,
                          order=order,
                          passenger=order.passenger)
                logging.error("book_order: OrderError: %d" % order_id)
                raise  # handle exception in decorator
            except UpdateStatusError:
                logging.error(
                    "book_order failed: cannot set order [%d] status to %s" %
                    (order.id, "ERROR"))
Ejemplo n.º 20
0
def update_order_status(order_id, work_station, new_status, pickup_time=None):
    """
    raises UpdateOrderError
    """
    try:
        order_assignment = OrderAssignment.objects.get(
            order=order_id, work_station=work_station, status=ASSIGNED)
    except OrderAssignment.DoesNotExist:
        logging.error(
            "No ASSIGNED assignment for order %d in work station %d" %
            (order_id, work_station.id))
        raise UpdateOrderError()

    result = {'order_id': order_id}

    if order_assignment.is_stale():
        try:
            order_assignment.change_status(ASSIGNED, IGNORED)
            result["order_status"] = "stale"
            return result
        except UpdateStatusError:
            logging.error(
                "update_order_status failed [%d]: cannot mark assignment as %s"
                % (order_id, "IGNORED"))

    if new_status == station_controller.ACCEPT and pickup_time:
        try:
            order_assignment.change_status(ASSIGNED, ACCEPTED)
            accept_order(order_assignment.order, pickup_time,
                         order_assignment.station)
            log_event(EventType.ORDER_ACCEPTED,
                      passenger=order_assignment.order.passenger,
                      order=order_assignment.order,
                      order_assignment=order_assignment,
                      station=work_station.station,
                      work_station=work_station)
            order_assignment.order.notify()
            result["pickup_message"] = _(
                "Message sent, pickup in %s minutes") % pickup_time
            result[
                "pickup_address"] = order_assignment.pickup_address_in_ws_lang
            result[
                "dropoff_address"] = order_assignment.dropoff_address_in_ws_lang
            return result

        except UpdateStatusError:
            logging.error(
                "update_order_status failed [%d]: cannot mark assignment as %s"
                % (order_id, "ACCEPTED"))

    elif new_status == station_controller.REJECT:
        try:
            order_assignment.change_status(ASSIGNED, REJECTED)
            log_event(EventType.ORDER_REJECTED,
                      passenger=order_assignment.order.passenger,
                      order=order_assignment.order,
                      order_assignment=order_assignment,
                      station=work_station.station,
                      work_station=work_station)
            book_order_async(order_assignment.order, order_assignment)
            return result

        except UpdateStatusError:
            logging.error(
                "update_order_status failed [%d]: cannot mark assignment as %s"
                % (order_id, "REJECTED"))

    else:
        raise UpdateOrderError("Invalid status")
Ejemplo n.º 21
0
            else:
                return error_response(
                    _("Could not send order to specified station"))

        order.save()
        order_created_signal.send(sender="order_created_signal", obj=order)

        if passenger.phone != settings.APPLE_TESTER_PHONE_NUMBER:
            order_manager.book_order_async(order)
        else:  # assign order to test station so the user will see it in his history
            order.station = Station.by_id(1713061)
            order.pickup_time = 5
            order.save()
            order.change_status(old_status=PENDING, new_status=ACCEPTED)

        log_event(EventType.ORDER_BOOKED, order=order)

        book_order_message = _(
            'An SMS with ride details will arrive shortly...')
        if order.originating_station_id:
            book_order_message = _(
                "%s is looking for a free taxi. An SMS with ride details will arrive shortly..."
            ) % order.originating_station.name

        book_order_result = {
            "status":
            "booked",
            "message":
            book_order_message,
            "order_id":
            order.id,