Ejemplo n.º 1
0
    def get(self, request, *args, **kwargs):
        context = dict()

        #Check if session is valid
        sessionValid = webshopUtils.checkSessionIdValidity(
            request=request,
            session_id_key=session_id_key,
            validPeriodInDays=self.hd2900RestaurantObject.restaurantModelData.
            session_valid_time)

        if sessionValid is False:
            context["pageRefresh"] = True
            return JsonResponse(context, status=200)

        #Check if all items still are available. This is to assure that the products are not sold out
        #Get all active products offered by the restaurant
        allActiveProducts = self.hd2900RestaurantObject.get_all_active_products(
        )
        sessionItems = CartItem.objects.filter(
            cart_id=request.session[session_id_key])
        number_of_products_ordered_beforeCheck = len(sessionItems)
        sessionItems = self.hd2900RestaurantObject.validateSessionOrderedProducts(
            allActiveProducts=allActiveProducts, sessionItems=sessionItems)

        if not sessionItems:
            context["pageRefresh"] = True
            return JsonResponse(context, status=200)

        number_of_products_ordered_afterCheck = len(sessionItems)

        if number_of_products_ordered_beforeCheck != number_of_products_ordered_afterCheck:
            context["pageRefresh"] = True
            return JsonResponse(context, status=200)

        #Get the total price
        context['totalPrice'] = webshopUtils.get_BasketTotalPrice(
            request.session[session_id_key])

        #Provide the item total price for each item to be updated into the table
        context['ordered_product_items_list'] = list()

        for item in sessionItems:
            tmp = dict()
            tmp['productSlug'] = item.product.slug
            #tmp['productPrice'] = item.product.price
            #tmp['orderedQuantity'] = item.quantity
            tmp['totalPrice_for_ordered_item'] = item.product.price * item.quantity
            context['ordered_product_items_list'].append(tmp)

        #If both restaurant offers delivery today and the total price is above the limit, the signal for delivery button is sent back
        deliveryPossible = self.hd2900RestaurantObject.isDeliveryPossible()
        if deliveryPossible and context[
                'totalPrice'] >= self.hd2900RestaurantObject.restaurantModelData.minimum_order_total_for_delivery:
            context['deliveryButtonActive'] = True
        else:
            context['deliveryButtonActive'] = False
            context[
                'minimum_totalPrice_for_delivery'] = self.hd2900RestaurantObject.restaurantModelData.minimum_order_total_for_delivery
        return JsonResponse(context, status=200)
Ejemplo n.º 2
0
    def get(self, request, *args, **kwargs):

        #Check if session is still valid
        sessionValid = webshopUtils.checkSessionIdValidity(
            request=request,
            session_id_key=session_id_key,
            validPeriodInDays=self.hd2900RestaurantObject.restaurantModelData.
            session_valid_time)
        if sessionValid is False:  #the session has expired and the user needs to start over
            return redirect('/hd2900_takeaway_webshop')

        #Check if delivery is still possible at this given date and time
        deliveryPossible = self.hd2900RestaurantObject.isDeliveryPossible()

        #Get all active products offered by the restaurant
        allActiveProducts = self.hd2900RestaurantObject.get_all_active_products(
        )

        #Check if the shopping cart items are still offered by the restaurant
        sessionItems = CartItem.objects.filter(
            cart_id=request.session[session_id_key])
        sessionItems = self.hd2900RestaurantObject.validateSessionOrderedProducts(
            allActiveProducts=allActiveProducts, sessionItems=sessionItems)

        #Check if total in sessionItems are above the limit for local delivery
        totalPrice = webshopUtils.get_BasketTotalPrice(
            request.session[session_id_key])

        if totalPrice < self.hd2900RestaurantObject.restaurantModelData.minimum_order_total_for_delivery:
            deliveryButtonActive = False
            totalPriceDeliveryMessage = "Minimum order for takeaway delivery : " + str(
                self.hd2900RestaurantObject.restaurantModelData.
                minimum_order_total_for_delivery) + ' kr'
        else:
            deliveryButtonActive = True
            totalPriceDeliveryMessage = ''

        #Check delivery status
        context = {
            'title': 'Hidden Dimsum takeaway checkout',
            'checkoutProducts': sessionItems,
            'totalPrice': totalPrice,
            'deliveryPossible':
            deliveryPossible,  #Relates to if it at all is possible to order delivery for today at the given time
            'deliveryButtonActive':
            deliveryButtonActive,  #checks if the total price is above the minimum limit for delivery
            'totalPriceDeliveryMessage': totalPriceDeliveryMessage
        }

        return render(
            request,
            template_name=
            'takeawayWebshop/takeawayWebshopPickupDeliveryCheckout.html',
            context=context)
Ejemplo n.º 3
0
    def get(self, request, *args, **kwargs):
        session_id = request.session[session_id_key]

        #Display the total cost together with bag fee
        sessionItems = CartItem.objects.filter(cart_id=session_id)

        #Decide if delivery is still possible
        pickupPossible = self.hd2900RestaurantObject.isPickupPossible()

        if pickupPossible is False:
            #Redirect the user to pickup
            context = dict()
            context['message'] = "Sorry takeaway is closed for today."
            return render(request,
                          template_name="takeawayWebshop/takeawayClosed.html",
                          context=context)

        #Generate time list for collecting pickup
        pickupTimeList = self.hd2900RestaurantObject.get_pickupTimeList()

        context = dict()
        #Get the total price and add on top of it the bag fee
        context['title'] = 'Takeaway pickup checkout'
        context['orderProducts'] = sessionItems
        context[
            'bagFee'] = self.hd2900RestaurantObject.restaurantModelData.bagFee
        context['grandTotal'] = webshopUtils.get_BasketTotalPrice(
            request.session[session_id_key]) + context['bagFee']
        context['customerPickupForm'] = customerPickupForm(
            pickupTimeList=pickupTimeList, auto_id=True)

        #Get the restaurant name and address to inform the user where to pick up
        context[
            'restaurantName'] = self.hd2900RestaurantObject.restaurantModelData.name
        context[
            'restaurantAddress'] = self.hd2900RestaurantObject.restaurantModelData.address
        return render(request,
                      template_name="takeawayWebshop/checkoutPickup.html",
                      context=context)
Ejemplo n.º 4
0
    def get(self, request, *args, **kwargs):
        #Display the total cost together with delivery fee and bag fee
        sessionItems = CartItem.objects.filter(
            cart_id=request.session[session_id_key])

        #Decide if delivery is still possible
        deliveryPossible = self.hd2900RestaurantObject.isDeliveryPossible()

        if deliveryPossible is False:
            #Redirect the user to pickup
            context = dict()
            context['message'] = "Sorry takeaway delivery is closed for today."
            return render(request,
                          template_name="takeawayWebshop/takeawayClosed.html",
                          context=context)

        #Generate time list for receiving delivery package
        deliveryTimeList = self.hd2900RestaurantObject.get_deliveryTimeList()

        context = dict()
        #Get the total price and add on top of it the bag fee and delivery cost
        context['title'] = 'Local delivery checkout'
        context['orderProducts'] = sessionItems
        context[
            'deliveryCost'] = self.hd2900RestaurantObject.restaurantModelData.delivery_fee
        context[
            'bagFee'] = self.hd2900RestaurantObject.restaurantModelData.bagFee
        context['grandTotal'] = webshopUtils.get_BasketTotalPrice(
            request.session[session_id_key]
        ) + context['deliveryCost'] + context['bagFee']
        checkoutLocalDeliveryForm = customerLocalDeliveryForm(
            deliveryTimeList=deliveryTimeList, auto_id=True)
        context['customerDeliveryForm'] = checkoutLocalDeliveryForm

        return render(
            request,
            template_name="takeawayWebshop/checkoutLocalDelivery.html",
            context=context)
Ejemplo n.º 5
0
    def get(self, request, *args, **kwargs):
        logging.info('Get call received from PaymentComplete view class')
        #Get all user information and the ordered products and display it to the user
        session_id = request.session[session_id_key]

        #Check if the session is valid. This is to prevent people from keeping refreshing the payment complete
        #website and trigger sending the same messages to the restaurant multiple times
        sessionValid = webshopUtils.checkSessionIdValidity(
            request=request,
            session_id_key=session_id_key,
            validPeriodInDays=self.hd2900RestaurantObject.restaurantModelData.
            session_valid_time)
        logging.debug(
            f'Payment complete session validity check returned {sessionValid}')
        if sessionValid is False:
            logging.debug(
                f'Payment complete view session valid is false and redirect client to hd2900_takeaway_webshop'
            )
            return redirect('hd2900_takeaway_webshop')

        #Prevent client from reaching this site by circumventing the payment, a check will be made to verify that
        #payment actually is received

        order = webshopUtils.get_order(session_id=session_id)
        if not order:
            logging.debug(
                'Payment complete view order cannot be found and client redirect to hd2900_takeaway_webshop'
            )
            return redirect('hd2900_takeaway_webshop')

        if order.webhookPaymentStatus is False:
            logging.debug(
                'Payment complete view order.webhookPaymentStatus is false and client redirected to hd2900_takeaway_webshop'
            )
            return redirect('hd2900_takeaway_webshop')

        #Get all the products that the customer has ordered
        sessionItems = CartItem.objects.filter(
            cart_id=request.session[session_id_key])

        #Calculate the total cost
        if order.delivery:
            totalPrice = webshopUtils.get_BasketTotalPrice(
                request.session[session_id_key]
            ) + self.hd2900RestaurantObject.restaurantModelData.delivery_fee + self.hd2900RestaurantObject.restaurantModelData.bagFee
        else:
            totalPrice = webshopUtils.get_BasketTotalPrice(
                request.session[session_id_key]
            ) + self.hd2900RestaurantObject.restaurantModelData.bagFee

        #Create a coppy of sessionItems as session deletion will be called next
        sessionItems = copy.copy(sessionItems)

        #Delete session
        webshopUtils.delete_session(session_id=session_id)
        logging.info(
            'Payment complete view. Client session deleted from back end and at this point order should be sent to the restaurant and confirmed to client'
        )

        context = dict()
        context['title'] = 'Payment Complete'
        context['orderCreationTime'] = order.orderCreationDateTime.strftime(
            '%d-%m-%Y %H:%M')
        context['order'] = order
        context[
            'restaurantObject'] = self.hd2900RestaurantObject.restaurantModelData
        context['orderedProducts'] = sessionItems
        context['grandTotal'] = totalPrice
        context['emailSignUpForm'] = newsLetterForm()
        context[
            'shopTitle'] = self.hd2900RestaurantObject.restaurantModelData.name
        context[
            'addressStreet'] = self.hd2900RestaurantObject.restaurantModelData.address
        context[
            'addressPhone'] = self.hd2900RestaurantObject.restaurantModelData.phone
        context[
            'addressEmail'] = self.hd2900RestaurantObject.restaurantModelData.email
        context[
            'addressCVR'] = 'CVR : ' + self.hd2900RestaurantObject.restaurantModelData.cvr
        context[
            'instagramLink'] = 'https://www.instagram.com/hiddendimsum2900/?hl=da'
        context[
            'youtubeLink'] = 'https://www.youtube.com/channel/UC-ryuXvGrMK2WQHBDui2lxw'
        context['facebookLink'] = 'https://www.facebook.com/hiddendimsum/'

        return render(
            request,
            template_name="takeawayWebshop/webshopPaymentComplete.html",
            context=context)
Ejemplo n.º 6
0
def paymentNotificationWebhook(request):
    logging.info('Incoming webhook received from NETS')

    #Assure that header contains Source key
    if 'Source' not in request.headers:
        return HttpResponse(status=500)

    #Assure the value of source is NETS_webhook_paymentChargeCreated
    if request.headers['Source'] != 'NETS_webhook_paymentChargeCreated':
        return HttpResponse(status=500)

    #check if header has Authorization key
    if 'Authorization' not in request.headers:
        return HttpResponse(status=500)

    authorization = request.headers['Authorization']

    #Check that authorization is string
    if isinstance(authorization, str) is False:
        return HttpResponse(status=500)

    #check if key Sessionid key is in the request.headers
    if 'Sessionid' not in request.headers:
        return HttpResponse(status=500)

    #Assure that the sessionid is a string
    if isinstance(request.headers['Sessionid'], str) is False:
        return HttpResponse(status=500)

    sessionId = request.headers['Sessionid']

    #check for the event type
    body = request.body.decode('utf8')
    body = json.loads(body)

    #Assure that body has event key
    if 'event' not in body:
        return HttpResponse(status=500)

    #If body event value is payment.charge.created.v2 then return status 200 followed by update database
    if body['event'] == 'payment.charge.created.v2':
        status = webshopUtils.retrieve_order_with_sessionid_authToken(
            session_id=sessionId, authToken=authorization, paymentStatus=True)

        logging.info(
            f'status of changing payment status in Django model based on the incoming webhook {status}'
        )

        if status:
            logging.info(
                'Incoming webhook validated and NETS got status 200 for webhook received. Sending order to restaurant'
            )

            order = webshopUtils.get_order(session_id=sessionId)
            #set date time field for payment received in order
            order.webhookDateTimePaymentReceived = datetime.datetime.now()
            order.save()

            hd2900RestaurantObject = RestaurantUtils(
                restaurantName=restaurantName)

            if order.delivery:
                totalPrice = webshopUtils.get_BasketTotalPrice(
                    sessionId
                ) + hd2900RestaurantObject.restaurantModelData.delivery_fee + hd2900RestaurantObject.restaurantModelData.bagFee
            else:
                totalPrice = webshopUtils.get_BasketTotalPrice(
                    sessionId
                ) + hd2900RestaurantObject.restaurantModelData.bagFee

            OrderDB = webshopUtils.OrderDatabase()
            #OrderDB._create_database()
            #OrderDB._create_tables()

            #Get all session items from the session id
            sessionItems = CartItem.objects.filter(cart_id=sessionId)

            #Log the order in mysql data base
            OrderDB.createNewOrder(session_id=sessionId,
                                   order=order,
                                   totalPrice=totalPrice,
                                   sessionItems=sessionItems)

            #Create the receipt for the customer as a pdf byte like object
            OrderDB = webshopUtils.OrderDatabase()
            orderData = OrderDB.getOrder(session_id=sessionId)

            receipt = GenerateForm()
            pdfByteLikeObj = receipt.takeaway_HD2900Receipt_template(
                logoPath=str(settings.BASE_DIR) +
                '/static/media/hd2900LogoReceipt.png',
                restaurantModel=hd2900RestaurantObject.restaurantModelData,
                orderData=orderData)

            emailObject = Send_Order_Email()

            #Send notification to customer
            emailObject.send_confirmation_to_customer(
                orderdata=orderData,
                restaurantModelData=hd2900RestaurantObject.restaurantModelData,
                pdfByteLikeObj=pdfByteLikeObj)

            #Send email notification to restaurant
            emailObject.send_order_to_restaurant(
                orderdata=orderData,
                restaurantModelData=hd2900RestaurantObject.restaurantModelData,
                pdfByteLikeObj=pdfByteLikeObj)

            #Send an sms notification to restaurant
            # smsObject = SendSMS()
            # smsObject.send_order_sms_to_restaurant(
            #     orderdata = orderData,
            #     restaurantData= hd2900RestaurantObject.restaurantModelData)

            #Change notify status in database
            OrderDB = webshopUtils.OrderDatabase()
            OrderDB.update_notifcation_to_true(session_id=sessionId)
            logging.info('Order sent to restaurant and customer notified')

            #Send the order to restaurant
            notifyRestaurantThread = threading.Thread(
                target=notifyRestaurant.sendOrderToRestaurant,
                args=(sessionId, ))
            notifyRestaurantThread.start()
            #status_code, postBody = notifyRestaurant.sendOrderToRestaurant(session_id=sessionId)
            logging.debug('here is the returned status code ')
            #logging.debug(status_code)
            logging.debug('here is the postBody')
            #logging.debug(postBody)
            logging.debug('here is the order Data')
            logging.debug(orderData)
            return HttpResponse(status=200)
        else:
            return HttpResponse(status=500)
Ejemplo n.º 7
0
    def post(self, request, *args, **kwargs):
        session_id = request.session[session_id_key]

        #Decide first if form comes from pickup form or delivery form
        if 'deliveryForm' in request.POST:
            deliveryType = 'delivery'

        if 'pickupForm' in request.POST:
            deliveryType = 'pickup'

        #Calculate the total order price dependent on if it is pickup or delivery
        if deliveryType == 'delivery':
            totalPrice = webshopUtils.get_BasketTotalPrice(
                request.session[session_id_key]
            ) + self.hd2900RestaurantObject.restaurantModelData.delivery_fee + self.hd2900RestaurantObject.restaurantModelData.bagFee

        if deliveryType == 'pickup':
            totalPrice = webshopUtils.get_BasketTotalPrice(
                session_id
            ) + self.hd2900RestaurantObject.restaurantModelData.bagFee

        #Insert the order into the model together with the payment id and authentication token for NETS webhook
        webshopUtils.create_or_update_Order(session_id=session_id,
                                            request=request,
                                            deliveryType=deliveryType)

        #Obtain the reference for the order
        reference = webshopUtils.get_order_reference(session_id=session_id)

        #Get the payment id from NETS
        payment = NETS()

        #Generate an unique token for payment notification webhook
        authToken = payment.genAuthToken()

        #Get the customer name to better identify the customer should there be problem in payment
        customerName = request.POST['customerName']

        #Generate payment id
        NETS_serverResponse = payment.get_paymentId(
            platform=platform,
            reference=reference,  #In format Order_[deliveryType]_xx
            name='Hidden Dimsum 2900 Takeaway',
            paymentReference=reference + '_' + customerName + '_' + session_id,
            session_id=session_id,
            unitPrice=int(totalPrice) * 100,
            authToken=authToken)

        if NETS_serverResponse.status_code == 201:
            paymentId = NETS_serverResponse.json()['paymentId']
        else:  #for some reasons we failed obtaining the payment id from NETS. Redirect customer to error page
            #Redirect customer to error page informing the type of error and contact Hidden Dimsum
            pass

        #Update the paymentId, webhook authentication into the order
        order = Order.objects.filter(session_id=session_id)
        order = order[0]
        order.webhookPaymentNotificationAuthKey = authToken
        order.paymentId = paymentId
        order.save()

        return redirect('localDeliveryPayment')