コード例 #1
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def customer_message_to_vendor(request):
    """Customer sending message to vendor"""
    customer = get_customer_from_request(request)
    if customer is None:
        return HttpResponse("Customer authentication failed", status=401)
    flow_id = request.POST.get("flow_id")
    if flow_id is None:
        return HttpResponse("Flow id is not given", status=400)
    try:
        flow = MessageFlowCustomer.objects.get(id=flow_id)
    except:
        return HttpResponse("Flow does not exist", status=400)
    if flow.customer != customer:
        return HttpResponse("Customer authentication failed", status=401)
    message_text = request.POST.get("message")
    if message_text is None:
        return HttpResponse("Message is not given", status=400)
    elif len(message_text) > 200:
        return HttpResponse("Message is too long (LIMIT=200 char)", status=400)
    message = MessageHistoryCustomer.objects.create(
            flow=flow,
            from_customer=True,
            message=message_text
        )
    message.save()
    flow.vendor_read = False
    flow.save()
    return HttpResponse("Message sent successfully!")
コード例 #2
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def get_messages_from_flow_customer(request):
    """GET requests for customer to get messages from message flow"""
    customer = get_customer_from_request(request)
    if customer is None:
        return HttpResponse("Customer authentication failed", status=401)
    flow_id = request.GET.get("flow_id")
    if flow_id is None:
        return HttpResponse("Flow id not given", status=400)
    try:
        flow = MessageFlowCustomer.objects.get(id=flow_id)
    except:
        return HttpResponse("Flow with id does not exist", status=400)
    if flow.customer!=customer:
        return HttpResponse("Customer authentication failed", status=401)
    messages = MessageHistoryCustomer.objects.filter(flow=flow).order_by("date_sent")
    data = []
    for message in messages:
        data.append({
            "sender": "self" if message.from_customer else "other",
            "customer": flow.customer.user.user.username,
            "vendor_name": flow.vendor.user.user.first_name,
            "message": message.message,
            "date_sent": message.date_sent,
        })
    flow.customer_read = True
    flow.save()
    return JsonResponse(data, safe=False)
コード例 #3
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def delete_product_from_shopping_list(request):
    """Delete product with id from the shopping list with given name"""
    customer = get_customer_from_request(request)
    if customer is None:
        return HttpResponse("Customer authentication failed", status=401)
    try:
        product_id = int(request.POST["product_id"])
    except (KeyError, ValueError):
        return HttpResponse("Product id (product_id) not given", status=400)
    try:
        name = request.POST["list_name"]
    except KeyError:
        return HttpResponse("List name not given", status=400)
    try:
        product_list = ProductLists.objects.get(name=name, customer=customer)
    except Exception:
        return HttpResponse("Customer doesn't have a list with given name", status=400)

    try:
        product = Product.objects.get(id=product_id)
    except Exception:
        return HttpResponse("There is no such product with given id", status=400)
    try:
        listing = ListedProducts.objects.filter(product_list=product_list, product=product)
        listing.delete()
    except Exception:
        return HttpResponse("Product with the id is not in the list", status=400)
    return HttpResponse("Product is deleted from the list successfully!")
コード例 #4
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def get_shopping_lists_of_customer(request):
    """Get shopping lists of the current customer"""
    customer = get_customer_from_request(request)
    if customer is None:
        return HttpResponse("Customer authentication failed", status=401)
    lists = [product_list.name for product_list in ProductLists.objects.filter(customer=customer)]
    return JsonResponse(lists, safe=False)
コード例 #5
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def get_products_from_shopping_list(request):
    """Get products from shopping list with given name"""
    customer = get_customer_from_request(request)
    if customer is None:
        return HttpResponse("Customer authentication failed", status=401)
    try:
        name = request.POST["list_name"]
    except KeyError:
        return HttpResponse("List name not given", status=400)
    try:
        product_list = ProductLists.objects.get(name=name, customer=customer)
    except Exception:
        return HttpResponse("Customer doesn't have a list with given name", status=400)
    list_products =[listing.product for listing in
                     ListedProducts.objects.filter(product_list=product_list)]
    products = []
    static_url = settings.TURSU_STATIC_URL
    for product in list_products:
        images = Image.objects.filter(product=product)
        if len(images) > 0:
            photo_url = f"{static_url}{images[0].photo}"
        else:
            photo_url = ""
        product_info ={"id": product.pk,
                       "name": product.name,
                       "photo_url": photo_url,
                       "vendor_name": product.vendor.user.user.first_name,
                       "category": product.category.name,
                       "rating": product.rating,
                       "stock": product.stock,
                       "price": product.price,
                       "brand": product.brand
                    }
        products.append(product_info)
    return JsonResponse(products, safe=False)
コード例 #6
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def edit_profile(request):
    """Edits user with given parameters when POST request is made."""
    customer = get_customer_from_request(request)
    vendor = get_vendor_from_request(request)
    if vendor is not None:
        if 'iban' in request.POST:
            vendor.iban = request.POST["iban"]
        if 'first_name' in request.POST:
            vendor.user.user.first_name = request.POST["first_name"]
        if 'password' in request.POST:
            vendor.user.user.set_password(request.POST["password"])
        vendor.user.user.save()
        vendor.user.save()
        vendor.save()

    elif customer is not None:
        if 'first_name' in request.POST:
            customer.user.user.first_name = request.POST["first_name"]
        if 'last_name' in request.POST:
            customer.user.user.last_name = request.POST["last_name"]
        if 'password' in request.POST:
            customer.user.user.set_password(request.POST["password"])
        customer.user.user.save()
        customer.user.save()
        customer.save()

    else:
        return Response("Authentication failed", status=401)

    return Response({}, status=status.HTTP_200_OK)
コード例 #7
0
def all(request):
    customer = get_customer_from_request(request)
    if (customer is None):
        return HttpResponse("Customer authentication failed", status=401)

    items = ShoppingCarts.objects.filter(Q(customer=customer))
    static_url = settings.TURSU_STATIC_URL
    cart = []

    for item in items:
        images = Image.objects.filter(product=item.product)
        if len(images) > 0:
            photo_url = f"{static_url}{images[0].photo}"
        else:
            photo_url = ""

        product_info = {
            "id": item.product.pk,
            "name": item.product.name,
            "photo_url": photo_url,
            "vendor_name": item.product.vendor.user.user.first_name,
            "category": item.product.category.name,
            "rating": item.product.rating,
            "stock": item.product.stock,
            "price": item.product.price,
            "brand": item.product.brand
        }

        cart_info = {"product": product_info, "quantity": item.quantity}
        cart.append(cart_info)

    return JsonResponse(cart, safe=False)
コード例 #8
0
def recommendation_pack(request):
    """Returns all recommendations types in JSON format"""
    customer = get_customer_from_request(request)
    if customer is not None:
        product_data = recommend_based_on_orders(customer)
        recommended = product_list_serializer(product_data)
    else:
        recommended = []

    product_data = bestseller_products()
    bestseller = product_list_serializer(product_data)

    product_data = top_rated_products()
    top_rated = product_list_serializer(product_data)

    product_data = newest_arrival_products()
    newest_arrival = product_list_serializer(product_data)

    recommendation = {
        'recommended': recommended,
        'bestseller': bestseller,
        'top_rated': top_rated,
        'newest_arrival': newest_arrival
    }
    return JsonResponse(recommendation, safe=False)
コード例 #9
0
def recommended_products(request):
    """Returns personally recommended products in JSON format"""
    customer = get_customer_from_request(request)
    if customer is not None:
        product_data = recommend_based_on_orders(customer)
        recommended = product_list_serializer(product_data)
    else:
        recommended = []
    return JsonResponse(recommended, safe=False)
コード例 #10
0
def get_orders(request):
    """Get the list of all orders"""
    customer = get_customer_from_request(request)
    if (customer is None):
        return HttpResponse("Customer authentication failed", status=401)

    items = Order.objects.filter(Q(customer=customer)).order_by('created')
    static_url = settings.TURSU_STATIC_URL
    orders = []
    group = []
    index = 0
    for index in range(len(items)):
        if index > 0 and items[index - 1].created != items[index].created:
            orders.append(group)
            group = []
        item = items[index]
        images = Image.objects.filter(product=item.product)
        if len(images) > 0:
            photo_url = f"{static_url}{images[0].photo}"
        else:
            photo_url = ""

        product_info = {
            "id": item.product.pk,
            "name": item.product.name,
            "photo_url": photo_url,
            "vendor_name": item.product.vendor.user.user.first_name,
            "category": item.product.category.name,
            "rating": item.product.rating,
            "stock": item.product.stock,
            "price": item.product.price,
            "brand": item.product.brand
        }

        order_info = {
            "product": product_info,
            "quantity": item.quantity,
            "id": item.pk,
            "status": item.status,
            "cargoID": item.cargoID,
            "estimatedArrivalDate": item.estimatedArrivalDate,
            "arrivalDate": item.arrivalDate
        }
        group.append(order_info)

    if len(group) > 0:
        orders.append(group)

    orders.sort(key=lambda x: x[0].get('id'))
    orders.reverse()
    return JsonResponse(orders, safe=False)
コード例 #11
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def get_customer_flows(request):
    """GET requests to get MessageFlows of Customer requestsing"""
    customer = get_customer_from_request(request)
    if customer is None:
        return HttpResponse("Customer authentication failed", status=401)
    flows = MessageFlowCustomer.objects.filter(customer=customer)
    info = []
    for flow in flows:
        info.append({
            "id": flow.pk,
            "notify": True if not flow.customer_read else False,
            "vendor_name": flow.vendor.user.user.first_name,
        })
    return JsonResponse(info,safe=False)
コード例 #12
0
def delete(request):
    customer = get_customer_from_request(request)
    if (customer is None):
        return HttpResponse("Customer authentication failed", status=401)

    try:
        product_id = int(request.POST["product_id"])
    except (KeyError, ValueError):
        return HttpResponse("Product id (product_id) not given or invalid",
                            status=400)

    product = Product.objects.filter(Q(id=product_id))
    ShoppingCarts.objects.filter(Q(product=product_id,
                                   customer=customer)).delete()
    return HttpResponse("success")
コード例 #13
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def delete_shopping_list(request):
    """Delete shopping list with given name"""
    customer = get_customer_from_request(request)
    if customer is None:
        return HttpResponse("Customer authentication failed", status=401)
    try:
        name = request.POST["list_name"]
    except KeyError:
        return HttpResponse("List name not given", status=400)
    try:
        product_list = ProductLists.objects.get(name=name, customer=customer)
        product_list.delete()
    except Exception:
        return HttpResponse("Can't delete list because it doesn't exist", status=400)
    return HttpResponse("List successfully deleted")
コード例 #14
0
def index(request):
    customer = get_customer_from_request(request)
    if (customer is None):
        return HttpResponse("Customer authentication failed", status=401)

    orders = Order.objects.filter(Q(customer=customer))
    my_orders = []
    for order in orders:
        comment = Comment.objects.filter(Q(order=order))
        if len(comment) == 0:
            comment = ""
        else:
            comment = comment[0].text

        order_info = {
            "id": order.id,
            "vendor": order.vendor.user.user.first_name,
            "product": order.product.pk,
            "status": order.status,
            "cargoID": order.cargoID,
            "orderDate": order.orderDate,
            "estimatedArrivalDate": order.estimatedArrivalDate,
            "arrivalDate": order.arrivalDate,
            "quantity": order.quantity,
            "comment": comment
        }
        my_orders.append(order_info)
    my_orders.sort(key=lambda x: x.get('id'))
    my_orders.reverse()

    lists = [
        product_list.name
        for product_list in ProductLists.objects.filter(customer=customer)
    ]

    customer_info = {
        "username": customer.user.user.username,
        "email": customer.user.user.email,
        "first_name": customer.user.user.first_name,
        "last_name": customer.user.user.last_name,
        "money_spent": customer.money_spent,
        "orders": my_orders,
        "lists": lists
    }

    return JsonResponse(customer_info, safe=False)
コード例 #15
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def create_shopping_list(request):
    """Create shopping list with given name"""
    customer = get_customer_from_request(request)
    if customer is None:
        return HttpResponse("Customer authentication failed", status=401)
    try:
        name = request.POST["list_name"]
    except KeyError:
        return HttpResponse("List name not given", status=400)
    try:
        product_list = ProductLists.objects.get(name=name, customer=customer)
        return HttpResponse("List with name already exists", status=400)
    except Exception:
        pass
    product_list = ProductLists.objects.create(name=name, customer=customer)
    product_list.save()
    return HttpResponse("List created successfully")
コード例 #16
0
def add(request):
    customer = get_customer_from_request(request)
    if (customer is None):
        return HttpResponse("Customer authentication failed", status=401)

    try:
        product_id = int(request.POST["product_id"])
    except (KeyError, ValueError):
        return HttpResponse("Product id (product_id) not given or invalid",
                            status=400)

    quantity = request.POST.get('quantity')
    if (not quantity):
        quantity = 1
    else:
        try:
            quantity = int(quantity)
        except (KeyError, ValueError):
            return HttpResponse("Given quantity is not an integer", status=400)

    product = Product.objects.filter(Q(id=product_id))
    if len(product) == 0:
        return HttpResponse('There is no such product.', status=400)
    else:
        product = product[0]

    try:
        items = ShoppingCarts.objects.filter(
            Q(product=product_id, customer=customer))
        if len(items) == 0:
            item = ShoppingCarts.objects.create(product=product,
                                                customer=customer,
                                                quantity=quantity)
            item.save()
        else:
            items[0].quantity = quantity
            items[0].save()
    except Exception:
        return HttpResponse(
            "Product can not be added to the shopping cart of current user",
            status=400)

    return HttpResponse("success")
コード例 #17
0
ファイル: views.py プロジェクト: umutgun17/bounswe2020group1
def create_flow_customer_vendor(request):
    """Customer creating message flow to message vendor"""
    customer = get_customer_from_request(request)
    if customer is None:
        return HttpResponse("Customer authentication failed", status=401)
    vendor_name = request.POST.get("vendor_name")
    if vendor_name is None:
        return HttpResponse("Vendor name is not given", status=400)
    try:
        vendor = Vendor.objects.get(user__user__first_name=vendor_name)
    except:
        return HttpResponse("Vendor does not exist", status=400)
    #orders = Order.objects.filter(customer=customer, vendor=vendor)
    #if len(orders) == 0:
    #    return HttpResponse("You can't message vendors that you haven't ordered from", status=400)
    flow, _ = MessageFlowCustomer.objects.get_or_create(
            customer=customer,
            vendor=vendor
        )
    flow.save()
    return HttpResponse("Flow created successfully")
コード例 #18
0
def decrease(request):
    customer = get_customer_from_request(request)
    if (customer is None):
        return HttpResponse("Customer authentication failed", status=401)
    try:
        product_id = int(request.POST["product_id"])
        product = Product.objects.filter(Q(id=product_id))[0]
    except Exception:
        return HttpResponse("Product id (product_id) not given or invalid",
                            status=400)

    items = ShoppingCarts.objects.filter(
        Q(product=product_id, customer=customer))
    if len(items) == 0:
        return HttpResponse("success")
    else:
        items[0].quantity = items[0].quantity - 1
        items[0].save()
        if items[0].quantity == 0:
            items[0].delete()
    return HttpResponse("success")
コード例 #19
0
def create_orders(request):
    """Crete order from cart."""
    customer = get_customer_from_request(request)
    if (customer is None):
        return HttpResponse("Customer authentication failed", status=401)
    items = ShoppingCarts.objects.filter(Q(customer=customer))
    created_ = datetime.datetime.now(tz=timezone.utc)
    invalid_list = []
    for item in items:
        product = item.product
        quantity = item.quantity
        if product.stock < quantity:
            invalid_list.append(str(product.name))
    if (len(invalid_list) > 0):
        return JsonResponse({"invalid": invalid_list}, safe=False)

    for item in items:
        product = item.product
        vendor = item.product.vendor
        quantity = item.quantity
        order = Order.objects.create(
            product=product,
            vendor=vendor,
            customer=customer,
            quantity=quantity,
            estimatedArrivalDate=datetime.date.today(),
            arrivalDate=datetime.date.today(),
            created=created_)
        product.stock -= quantity
        customer.money_spent += quantity * product.price
        product.save()
        order.save()
        notif.insert_order_status_change(vendor.user, product.name, order.id,
                                         "new")

    ShoppingCarts.objects.filter(Q(customer=customer)).delete()

    return JsonResponse({}, safe=False)
コード例 #20
0
def cancel_order(request):
    """Sets and order as cancelled"""
    vendor = get_vendor_from_request(request)
    customer = get_customer_from_request(request)
    if (vendor is None and customer is None):
        return HttpResponse("Authentication failed", status=401)
    try:
        order_id = request.POST["order_id"]
    except:
        return HttpResponse("Missing arguments", status=400)

    order = Order.objects.filter(id=order_id).first()
    if order == None:
        return HttpResponse("Invalid order_id", status=400)

    if order.customer == customer or order.vendor == vendor:
        if order.status == "cancelled":
            return HttpResponse("Order is already cancelled", status=400)
        order.status = "cancelled"
        order.product.stock += order.quantity
        order.customer.money_spent -= order.quantity * order.product.price
    else:
        return HttpResponse("Order doesn't belong to given user", status=400)

    order.product.save()
    order.save()
    order.customer.save()

    # add notification
    if vendor is None:
        notif.insert_order_status_change(order.vendor.user, order.product.name,
                                         order.id, "cancelled")
    if customer is None:
        notif.insert_order_status_change(order.customer.user,
                                         order.product.name, order.id,
                                         "cancelled")

    return JsonResponse({}, safe=False)
コード例 #21
0
def set_delivered(request):
    """Sets and order as delivered."""
    customer = get_customer_from_request(request)
    if (customer is None):
        return HttpResponse("Customer authentication failed", status=401)
    try:
        order_id = request.POST["order_id"]
    except:
        return HttpResponse("Missing arguments", status=400)

    order = Order.objects.filter(id=order_id).first()
    if order == None:
        return HttpResponse("Invalid order_id", status=400)

    order.status = "delivered"
    order.arrivalDate = datetime.date.today()
    order.save()

    # add notification for vendor
    notif.insert_order_status_change(order.vendor.user, order.product.name,
                                     order.id, "delivered")

    return JsonResponse({}, safe=False)
コード例 #22
0
def add(request):
    customer = get_customer_from_request(request)
    if (customer is None):
        return HttpResponse("Customer authentication failed", status=401)

    try:
        product_id = int(request.POST.get('product_id'))
    except (KeyError, ValueError, TypeError):
        return HttpResponse("Product id (product_id) not given or invalid",
                            status=400)

    try:
        text = request.POST.get('text')
    except (KeyError, ValueError):
        return HttpResponse("Comment not given or invalid", status=400)

    try:
        product_rating = int(request.POST.get('product_rating'))
    except (KeyError, ValueError, TypeError):
        return HttpResponse("Product rating not given or invalid", status=400)

    try:
        vendor_rating = int(request.POST.get('vendor_rating'))
    except (KeyError, ValueError):
        return HttpResponse("Vendor rating not given or invalid", status=400)

    product = Product.objects.filter(Q(id=product_id))
    if len(product) == 0:
        return HttpResponse('There is no such product.', status=400)
    else:
        product = product[0]

    order = Order.objects.filter(
        Q(customer=customer, product=product, comment_added=False))
    if len(order) == 0:
        return HttpResponse(
            'The customer did not buy the product or comment already added.',
            status=401)
    else:
        order = order[0]
        try:
            comment = Comment.objects.create(order=order,
                                             product=product,
                                             customer=customer,
                                             text=text,
                                             rating=product_rating)
            comment.save()
            product.rating = ((product.rating * product.number_of_raters) +
                              product_rating) / (product.number_of_raters + 1)
            product.number_of_raters = product.number_of_raters + 1
            product.save()
            vendor = order.vendor
            rated_orders = Order.objects.filter(
                Q(vendor=vendor, comment_added=True))
            num_of_raters = len(rated_orders)
            vendor.rating = ((vendor.rating * num_of_raters) +
                             vendor_rating) / (num_of_raters + 1)
            order.comment_added = True
            vendor.save()
            order.save()
        except Exception:
            return HttpResponse("Comment cannot be added.", status=400)

    return HttpResponse("success")