Esempio n. 1
0
def getDistanceAndPrice(request):
    if request.method == "POST":
        user_form = DistancePriceForm(request.POST)
        if user_form.is_valid():
            srccity = user_form.cleaned_data['srccity']
            srcaddress = user_form.cleaned_data['srcaddress']
            srcpostalcode = user_form.cleaned_data['srcpostalcode']
            dstcity = user_form.cleaned_data['dstcity']
            dstaddress = user_form.cleaned_data['dstaddress']
            dstpostalcode = user_form.cleaned_data['dstpostalcode']
            size = user_form.cleaned_data['size']
            maps = geomaps.GMaps()
            origin = srcaddress + ', ' + srccity + ', ' + srcpostalcode
            destination = dstaddress + ', ' + dstcity + ', ' + dstpostalcode
            maps.set_geo_args(dict(origin=origin, destination=destination))
            distance = maps.get_total_distance()
            # For price
            price = pricing.WebPricing()
            reward = price.get_price(distance, size=size)
            resultdict = {}
            resultdict['distance'] = distance
            resultdict['price'] = reward
            return HttpResponse(json.dumps(resultdict),
                                content_type="application/json")
        if user_form.errors:
            logger.debug("Form has errors, %s ", user_form.errors)
            resultdict['status'] = 500
            resultdict['message'] = "Internal Server Error"
            return HttpResponse(json.dumps(resultdict),
                                content_type="application/json")
Esempio n. 2
0
    def post(self, request, format=None):
        """
        Creates a new shipment from the provided data
        ---
        request_serializer: serializers.NewQuestDataValidationSerializer
        response_serializer: serializers.NewQuestSerializer
        """

        user = request.user
        if user.is_shipper:
            return Response(status=status.HTTP_403_FORBIDDEN)

        ##Validate if all the data is available###
        serializer = serializers.NewQuestDataValidationSerializer(
            data=request.DATA)
        if serializer.is_valid():
            data = request.DATA
            ##Calculate distance and price
            pickupdict = {}
            dropoffdict = {}
            from libs import geomaps, pricing
            maps = geomaps.GMaps()
            price = pricing.WebPricing(user)
            size = data['size']
            pickupdict['city'] = data['srccity']
            pickupdict['address'] = data['srcaddress']
            pickupdict['address_2'] = data['srcaddress_2']
            pickupdict['postalcode'] = data['srcpostalcode']
            pickupdict['name'] = data['srcname']
            pickupdict['phone'] = data['srcphone']
            dropoffdict['city'] = data['dstcity']
            dropoffdict['address'] = data['dstaddress']
            dropoffdict['address_2'] = data['dstaddress_2']
            dropoffdict['postalcode'] = data['dstpostalcode']
            dropoffdict['name'] = data['dstname']
            dropoffdict['phone'] = data['dstphone']
            origin = pickupdict['address'] + ', ' + pickupdict[
                'city'] + ', ' + pickupdict['postalcode']
            destination = dropoffdict['address'] + ', ' + dropoffdict[
                'city'] + ', ' + dropoffdict['postalcode']
            maps.set_geo_args(dict(origin=origin, destination=destination))
            distance = maps.get_total_distance()
            map_image = maps.fetch_static_map()
            reward = price.get_price(distance, shipment_mode=size)
            questrs = user.id
            data['reward'] = reward
            data['distance'] = distance
            data['map_image'] = map_image
            data['questrs'] = questrs
            data['pickup'] = json.dumps(pickupdict)
            data['dropoff'] = json.dumps(dropoffdict)
            serializer = serializers.NewQuestSerializer(data=data)
            if serializer.is_valid():
                logging.warn(serializer.data)
                serializer.save()
                responsedata = dict(data=serializer.data, success=True)
                return Response(responsedata, status=status.HTTP_201_CREATED)
        responsedata = dict(errors=serializer.errors, success=False)
        return Response(responsedata, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 3
0
def newquest(request):
    """creates new quest and sends notification to shippers"""
    user = request.user
    if user.is_shipper:
        return redirect('home')

    if request.method == "POST":
        # logging.warn(request.POST)
        user_form = QuestCreationForm(request.POST)
        if user_form.is_valid():
            title = user_form.cleaned_data['title']
            size = user_form.cleaned_data['size']
            description = user_form.cleaned_data['description']
            srccity = user_form.cleaned_data['srccity']
            srcaddress = user_form.cleaned_data['srcaddress']
            srcaddress_2 = user_form.cleaned_data['srcaddress_2']
            srcpostalcode = user_form.cleaned_data['srcpostalcode']
            srcname = user_form.cleaned_data['srcname']
            srcphone = user_form.cleaned_data['srcphone']
            dstcity = user_form.cleaned_data['dstcity']
            dstaddress = user_form.cleaned_data['dstaddress']
            dstaddress_2 = user_form.cleaned_data['dstaddress_2']
            dstpostalcode = user_form.cleaned_data['dstpostalcode']
            dstname = user_form.cleaned_data['dstname']
            dstphone = user_form.cleaned_data['dstphone']
            # For distance
            maps = geomaps.GMaps()
            origin = srcaddress + ', ' + srccity + ', ' + srcpostalcode
            destination = dstaddress + ', ' + dstcity + ', ' + dstpostalcode
            maps.set_geo_args(dict(origin=origin, destination=destination))
            distance = maps.get_total_distance()
            map_image = maps.fetch_static_map()
            logger.warn(map_image)
            if distance is None or map_image is None:
                request.session['alert_message'] = dict(
                    type="Danger",
                    message=
                    "An error occured while creating your shipment, please try again in a while!"
                )
                message = "Error occured while creating quest"
                warnlog = dict(message=message)
                logger.warn(warnlog)
                return redirect('home')
            # For price
            price = pricing.WebPricing()
            reward = price.get_price(distance, size=size)
            stripereward = reward * 100
            stripekey = os.environ['STRIPE_KEY']
            pagetitle = "Confirm your Quest"
            return render(request, 'confirmquest.html', locals())
        if user_form.errors:
            logger.debug("Form has errors, %s ", user_form.errors)
            return render(request, 'newquest.html', locals())

    user_form = QuestCreationForm()
    pagetitle = "Create your Quest"
    return render(request, 'newquest.html', locals())
Esempio n. 4
0
 def checkProximity(self, address_1, address_2):
     proximity = settings.QUESTR_PROXIMITY
     maps = geomaps.GMaps()
     maps.set_geo_args(dict(origin=address_1, destination=address_2))
     distance = maps.get_total_distance()
     if int(distance) <= proximity:
         proximity = True
         return dict(in_proximity=proximity, distance=distance)
     else:
         proximity = False
         return dict(in_proximity=proximity, distance=distance)
Esempio n. 5
0
    def post(self, request, format=None):
        """
        Returns with price after receiving shipment information
        ---
        request_serializer: serializers.PriceCalcSerializer
        response_serializer: serializers.PriceCalcSerializer
        """

        user = request.user
        if user.is_shipper:
            return Response(status=status.HTTP_403_FORBIDDEN)

        ##Validate if all the data is available###
        serializer = serializers.PriceCalcSerializer(data=request.DATA)
        if serializer.is_valid():
            data = request.DATA
            ##Calculate distance and price
            pickupdict = {}
            dropoffdict = {}
            from libs import geomaps, pricing
            maps = geomaps.GMaps()
            price = pricing.WebPricing()
            size = data['size']
            pickupdict['city'] = data['srccity']
            pickupdict['address'] = data['srcaddress']
            pickupdict['postalcode'] = data['srcpostalcode']
            dropoffdict['city'] = data['dstcity']
            dropoffdict['address'] = data['dstaddress']
            dropoffdict['postalcode'] = data['dstpostalcode']
            origin = pickupdict['address'] + ', ' + pickupdict[
                'city'] + ', ' + pickupdict['postalcode']
            destination = dropoffdict['address'] + ', ' + dropoffdict[
                'city'] + ', ' + dropoffdict['postalcode']
            maps.set_geo_args(dict(origin=origin, destination=destination))
            distance = maps.get_total_distance()
            fee = price.get_price(distance, size=size)
            responsedata = dict(fee=fee)
            return Response(responsedata, status=status.HTTP_200_OK)
        responsedata = dict(errors=serializer.errors, success=False)
        return Response(responsedata, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 6
0
def confirmquest(request):
    """creates new quest and sends notification to shippers"""
    user = request.user
    if user.is_shipper:
        return redirect('home')

    if request.method == "POST":
        user_form = QuestConfirmForm(request.POST, request.FILES)
        if user_form.is_valid():
            pickupdict = {}
            dropoffdict = {}
            size = user_form.cleaned_data['size']
            srccity = user_form.cleaned_data['srccity']
            srcaddress = user_form.cleaned_data['srcaddress']
            srcaddress_2 = user_form.cleaned_data['srcaddress_2']
            srcpostalcode = user_form.cleaned_data['srcpostalcode']
            srcname = user_form.cleaned_data['srcname']
            srcphone = user_form.cleaned_data['srcphone']
            dstcity = user_form.cleaned_data['dstcity']
            dstaddress = user_form.cleaned_data['dstaddress']
            dstaddress_2 = user_form.cleaned_data['dstaddress_2']
            dstpostalcode = user_form.cleaned_data['dstpostalcode']
            dstname = user_form.cleaned_data['dstname']
            dstphone = user_form.cleaned_data['dstphone']
            ## categorizing source and destination info
            pickupdict['city'] = srccity
            pickupdict['address'] = srcaddress
            pickupdict['address_2'] = srcaddress_2
            pickupdict['postalcode'] = srcpostalcode
            pickupdict['name'] = srcname
            pickupdict['phone'] = srcphone
            dropoffdict['city'] = dstcity
            dropoffdict['address'] = dstaddress
            dropoffdict['address_2'] = dstaddress_2
            dropoffdict['postalcode'] = dstpostalcode
            dropoffdict['name'] = dstname
            dropoffdict['phone'] = dstphone
            # Pickup Time
            # pickup_time = user_form.cleaned_data['pickup_time'].lower()
            # Recalculate distance and price to prevent any arbitrary false attempt.
            # For distance
            maps = geomaps.GMaps()
            origin = srcaddress + ', ' + srccity + ', ' + srcpostalcode
            destination = dstaddress + ', ' + dstcity + ', ' + dstpostalcode
            maps.set_geo_args(dict(origin=origin, destination=destination))
            distance = maps.get_total_distance()
            map_image = maps.fetch_static_map()
            # For price
            price = pricing.WebPricing()
            reward = price.get_price(distance, size=size)
            quest_data = user_form.save(commit=False)
            ##Submit dict to the field
            quest_data.pickup = json.dumps(pickupdict)
            quest_data.dropoff = json.dumps(dropoffdict)
            quest_data.questrs_id = request.user.id
            quest_data.reward = reward
            quest_data.item_images = user_form.cleaned_data['item_images']
            quest_data.map_image = map_image
            # pickup_time = user_form.cleaned_data['pickup_time']
            # if pickup_time == 'now':
            #     pickup_time = quest_handler.get_pickup_time()
            # elif pickup_time == 'not_now':
            #     pickup_when = user_form.cleaned_data['pickup_when']
            #     time = user_form.cleaned_data['not_now_pickup_time']
            #     pickup_time = quest_handler.get_pickup_time(pickup_time, pickup_when, time)
            #     if (pickup_time - timezone.now().astimezone(pytz.timezone(settings.TIME_ZONE))).total_seconds() < 0:
            #         request.session['alert_message'] = dict(type="warning",message="Pickup time cannot be before current time!")
            #         return redirect('home')
            #     # If the p
            #     if (pickup_time - timezone.now().astimezone(pytz.timezone(settings.TIME_ZONE))).total_seconds() < 3600:
            #         pickup_time = quest_handler.get_pickup_time()
            # else:
            #     pickup_time = quest_handler.get_pickup_time()
            # quest_data.pickup_time = pickup_time
            try:
                chargeme = stripeutils.PayStripe()
                result = chargeme.charge(request.POST['stripeToken'],
                                         int(reward * 100))
                if result['status'] == "pass":
                    quest_data.save()
                    # quest_handler.update_resized_image(quest_data.id)
                    eventmanager = quest_handler.QuestEventManager()
                    extrainfo = dict(detail="quest created")
                    eventmanager.setevent(quest_data, 1, extrainfo)
                    message = "Quest {0} has been created by user {1}".format(
                        quest_data.id, user)
                    request.session['alert_message'] = dict(
                        type="Success", message="Your quest has been created!")
                    logger.warn(message)
                    init_courier_selection.apply_async(
                        (quest_data.id, ), eta=quest_handler.get_pickup_time())
                    return redirect('home')
                else:
                    request.session['alert_message'] = dict(
                        type="Danger",
                        message=
                        "An error occured while creating your shipment, please try again in a while!"
                    )
                    message = "Error occured while creating quest"
                    warnlog = dict(message=message, exception=e)
                    logger.warn(warnlog)
                    return redirect('home')
            except Exception, e:
                ##Inform admin of an error
                request.session['alert_message'] = dict(
                    type="Danger",
                    message=
                    "An error occured while creating your shipment, please try again in a while!"
                )
                message = "Error occured while creating quest"
                warnlog = dict(message=message, exception=e)
                logger.warn(warnlog)
                return redirect('home')

        if user_form.errors:
            logger.debug("Form has errors, %s ", user_form.errors)