Exemple #1
0
class lastPickupDeliveryOrderTime(View):
    def __init__(self):
        #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
        self.hd2900RestaurantObject = RestaurantUtils(
            restaurantName=restaurantName)

    def get(self, request, *args, **kwargs):
        '''
        Provides timer count down information to the front end to inform customers the followings:
        1) If restaurant is open today for pick up
        2) If restaurant is open today for delivery
        3) At what time pickup will be closed for order 
        4) At what time delivery will be closed for order
        '''
        response = dict()
        deliveryPossible = self.hd2900RestaurantObject.isDeliveryPossible()
        if deliveryPossible:
            response['deliveryClosed'] = False

        if deliveryPossible is False:
            response['deliveryClosed'] = True

        pickupPossible = self.hd2900RestaurantObject.isPickupPossible()

        if pickupPossible:
            response['pickupClosed'] = False

        if pickupPossible is False:
            response['pickupClosed'] = True

        #Get last datetime string for ordering delivery
        lastDeliveryOrderTime = self.hd2900RestaurantObject.get_latestDeliveryOrderTime(
        )
        response['lastDeliveryOrderTime'] = [
            lastDeliveryOrderTime.year, lastDeliveryOrderTime.month - 1,
            lastDeliveryOrderTime.day, lastDeliveryOrderTime.hour,
            lastDeliveryOrderTime.minute, lastDeliveryOrderTime.second
        ]

        #Get the last datetime string for ordering pickup
        lastPickupOrderTime = self.hd2900RestaurantObject.get_latestPickupOrderTime(
        )
        response['lastPickupOrderTime'] = [
            lastPickupOrderTime.year, lastPickupOrderTime.month - 1,
            lastPickupOrderTime.day, lastPickupOrderTime.hour,
            lastPickupOrderTime.minute, lastPickupOrderTime.second
        ]

        return JsonResponse(response, status=200)
Exemple #2
0
class PickUpForm(View):
    def __init__(self):
        #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
        self.hd2900RestaurantObject = RestaurantUtils(
            restaurantName=restaurantName)

    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)
Exemple #3
0
class DeliveryForm(View):
    def __init__(self):
        #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
        self.hd2900RestaurantObject = RestaurantUtils(
            restaurantName=restaurantName)

    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)
Exemple #4
0
 def __init__(self):
     #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
     self.hd2900RestaurantObject = RestaurantUtils(
         restaurantName=restaurantName)
Exemple #5
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)
Exemple #6
0
 def __init__(self):
     #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
     self.hd2900RestaurantObject = RestaurantUtils(
         restaurantName=restaurantName)
     self.deliveryStatus = self.hd2900RestaurantObject.isDeliveryOpenToday()
Exemple #7
0
class TakeawayCheckout(View):
    def __init__(self):
        #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
        self.hd2900RestaurantObject = RestaurantUtils(
            restaurantName=restaurantName)
        self.deliveryStatus = self.hd2900RestaurantObject.isDeliveryOpenToday()

    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)
Exemple #8
0
class totalPriceDeliveryPossible(View):
    def __init__(self):
        #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
        self.hd2900RestaurantObject = RestaurantUtils(
            restaurantName=restaurantName)
        self.deliveryStatus = self.hd2900RestaurantObject.isDeliveryOpenToday()

    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)
Exemple #9
0
 def __init__(self):
     #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
     self.hd2900RestaurantObject = RestaurantUtils(
         restaurantName=restaurantName)
     self.emailSignUp = newsLetterForm()
Exemple #10
0
class hd2900_webshop_Main(View):
    def __init__(self):
        #Get model webshopRestaurant data for hd2900 restaurant for location id for this restaurant
        self.hd2900RestaurantObject = RestaurantUtils(
            restaurantName=restaurantName)
        self.emailSignUp = newsLetterForm()

    def get(self, request, *args, **kwargs):
        #Inform visitor the delivery status today
        deliveryStatus = self.hd2900RestaurantObject.isDeliveryOpenToday()

        if deliveryStatus:
            takeawayStatusMsg = "We offer local delivery today"
        else:
            takeawayStatusMsg = "Order online and pickup at Hidden Dimsum 2900. Local delivery not available today"

        #Check if visitor has a cookie
        sessionValid = webshopUtils.checkSessionIdValidity(
            request=request,
            session_id_key=session_id_key,
            validPeriodInDays=self.hd2900RestaurantObject.restaurantModelData.
            session_valid_time)

        allActiveProducts = self.hd2900RestaurantObject.get_all_active_products(
        )
        if sessionValid:
            sessionItems = CartItem.objects.filter(
                cart_id=request.session[session_id_key])
            #Assure that the products in the session cart is still valid otherwise they should be removed. This
            #validation is made to assure that the products in the cart is still offered by the restaurant
            sessionItems = self.hd2900RestaurantObject.validateSessionOrderedProducts(
                allActiveProducts=allActiveProducts, sessionItems=sessionItems)
            #Merge sessionItems with all active products and add the quantity
            productToDisplay = self.hd2900RestaurantObject.generateProductsForView(
                allActiveProducts=allActiveProducts, sessionItems=sessionItems)
            totalItemsInBasket = webshopUtils.get_totalBasketItemQuantity(
                request.session[session_id_key])
        else:
            productToDisplay = self.hd2900RestaurantObject.generateProductsForView(
                allActiveProducts=allActiveProducts, sessionItems=[])
            totalItemsInBasket = 0

        context = {
            'title':
            restaurantName + ' online takeaway',
            'deliveryStatus':
            deliveryStatus,
            'deliveryStartTime':
            self.hd2900RestaurantObject.get_deliveryOpenTime().strftime(
                '%H:%M'),
            'deliveryEndTime':
            self.hd2900RestaurantObject.get_deliveryEndtime().strftime(
                '%H:%M'),
            'products':
            productToDisplay,
            'totalItemsInBasket':
            totalItemsInBasket,
            'deliveryRadius':
            self.hd2900RestaurantObject.restaurantModelData.delivery_radius,
            'deliveryFee':
            self.hd2900RestaurantObject.restaurantModelData.delivery_fee,
            'minimumOrderForDelivery':
            self.hd2900RestaurantObject.restaurantModelData.
            minimum_order_total_for_delivery,
            'emailSignUpForm':
            self.emailSignUp,
            'facebookLink ':
            'https://www.facebook.com/pages/category/Dim-Sum-Restaurant/Hidden-Dimsum-2900-100653481855726/',
            'instagramLink':
            'https://www.instagram.com/hiddendimsum2900/',
            'youtubeLink':
            'https://www.youtube.com/channel/UC-ryuXvGrMK2WQHBDui2lxw',
            'shopTitle':
            'Hidden Dimsum 2900',
            'addressStreet':
            'Strandvejen 163, 2900 Hellerup',
            'addressPhone':
            'Phone : 40 38 88 84',
            'addressCVR':
            'CVR : 38908901'
        }
        return render(request,
                      template_name="takeawayWebshop/takeawayWebshopMain.html",
                      context=context)