def home(request): """:synopsis: Permet de générer la page index du site si request = GET :param request: La requete du client de type GET :type request: djangoRequest :return: le template + le context -> générer au final la page html """ context = {"product": object, "basketCount": tools.basketCount(request), 'form': PriceRange()} # on recupere tous les produits product = Product.objects.filter(quantity__gte=1).order_by("date") pub = IndexPub.objects.all() context["indexPub"] = pub paginator = Paginator(product, 25) page = request.GET.get('page') try: context["product"] = paginator.get_page(page) except PageNotAnInteger: context["product"] = paginator.page(1) except EmptyPage: context["product"] = paginator.page(1) context = tools.mergeDict(context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) context = tools.mergeDict(context, tools.displayCategory()) request.session['emailNewsLetter'] = "" return render(request, 'index.html', context)
def view_product(request, id_product): """:synopsis: Permet de générer la page details produit si request = GET. Si request = POST permet de poster un avis sur la page produit details :param request: La requete du client de type GET ou POST :type request: djangoRequest :param id_product: L'id du produit a afficher sur la page :type id_product: int :return: le template + le context -> générer au final la page html """ context = {"product": get_object_or_404(Product, id=id_product), "image": Images.objects.filter(product_id=id_product), "reviews": ProductComment.objects.filter(product_id=id_product).order_by('-date'), "form": ReviewsForm(), "basketCount": tools.basketCount(request), 'basket': Basket()} context = tools.mergeDict(context, tools.displayCategory()) context = tools.mergeDict(context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" if request.method == "POST": form = ReviewsForm(request.POST) if form.is_valid(): # on insert le commentaire dans la bd review = ProductComment(name=form.cleaned_data['name'], email=form.cleaned_data['email'], comment=form.cleaned_data['comment'], product=Product.objects.get(pk=id_product), star=4) review.save() return render(request, 'view_details.html', context)
def view_search(request): """:synopsis: Permet de générer la page de resultat d'une recherche si request = GET. :param request: La requete du client de type GET :type request: djangoRequest :return: le template + le context -> générer au final la page html """ context = {'product': object(), 'form': PriceRange(), "basketCount": tools.basketCount(request)} context = tools.mergeDict(context, tools.displayCategory()) context = tools.mergeDict(context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" # on verifie que la form est valide form = Search(request.GET) print("ok est a search") if form.is_valid(): terms = form.cleaned_data['search'] context['terms'] = terms product = Product.objects.filter(name__icontains=terms, quantity__gte=1) context["productName"] = terms paginator = Paginator(product, 1) page = request.GET.get('page') try: context["product"] = paginator.get_page(page) except PageNotAnInteger: context["product"] = paginator.page(1) except EmptyPage: context["product"] = paginator.page(1) return render(request, 'view_search.html', context) else: redirect("index")
def index_price_range(request): """:synopsis: Permet de Trier les produits de l'index en fonction d'un prix min et max si request = GET :param request: La requete du client de type GET :type request: djangoRequest :return: le template + le context -> générer au final la page index.html avec les produits trier """ context = {"product": object(), "basketCount": tools.basketCount(request)} context = tools.mergeDict(context, tools.displayCategory()) # on verifie que la requete est de type get pub = IndexPub.objects.all() context["indexPub"] = pub if request.method == "GET": form = PriceRange(request.GET) context['form'] = form if form.is_valid(): product = Product.objects.filter(price__range=(form.cleaned_data['priceMin'], form.cleaned_data['priceMax']), quantity__gte=1) paginator = Paginator(product, 25) page = request.GET.get('page') try: context["product"] = paginator.get_page(page) except PageNotAnInteger: context["product"] = paginator.page(1) except EmptyPage: context["product"] = paginator.page(1) finally: get = dict(request.GET) context["getParam"] = "priceMin={0}&priceMax={1}".format(get["priceMin"][0], get["priceMax"][0]) context = tools.mergeDict(context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" return render(request, 'index.html', context)
def view_check_out(request, id_address): """:synopsis: Permet de générer la page Checkout(Page de Commande) si request = GET :param request: La requete du client de type GET :type request: djangoRequest :param id_address: l'id de l'addresse a afficher dans le formulaire de Commande :param id_address: int :return: le template + le context -> générer au final une page html avec le formulaire d'adresse rempli ou non """ context = { "basketCount": tools.basketCount(request), 'key': settings.STRIPE_PUBLISHABLE_KEY } context = tools.mergeDict(context, tools.checkOutProduct(request)) context = tools.mergeDict( context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" # on verifie qu'il y a bien des produits dans le panier if context["product"].count(): # on verifie si il existe des address if context["address"].count(): try: address = Address.objects.get(customer__user=request.user, id=id_address) context['CheckOut'] = CheckOut(organizer=address.__dict__) except Address.DoesNotExist: context['CheckOut'] = CheckOut() else: context['CheckOut'] = CheckOut() return render(request, 'checkout.html', context) else: return redirect("Basket")
def dashboard(request): """:synopsis: Permet de générer la page DashBoard si request = GET :param request: La requete du client de type GET :type request: djangoRequest :return: le template + le context -> générer au final une page html """ context = tools.mergeDict( { 'search': Search(), "basketCount": tools.basketCount(request) }, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" return render(request, 'dashboard.html', context)
def category_sorted(request, id_category, sorted_by): """:synopsis: Permet de Trier les produits de la page view Category en fonction d'une action passer en paramètre (request = GET) :param request: La requete du client de type GET :type request: djangoRequest :param id_category: L'id de la catégorie a afficher :type id_category: int :param sorted_by: Action a effectué sur le trie des produits :type sorted_by: str :return: le template + le context -> générer au final la page index.html avec les produits trier """ # on recupere tous les article lier a cette catégorie context = {"product": object(), 'id_category': id_category, 'form': PriceRange(), "basketCount": tools.basketCount(request)} sorted_values = {"priceASC": lambda: (Product.objects.filter(category_id=id_category, quantity__gte=1).order_by('price')), "priceDESC": lambda: (Product.objects.filter(category_id=id_category, quantity__gte=1).order_by('-price')), "date": lambda: (Product.objects.filter(category_id=id_category, quantity__gte=1).order_by('date')), "star": lambda: (Product.objects.filter(category=id_category, quantity__gte=1).annotate( review=Count('productcomment__comment')).order_by('-review')), "error": lambda: (Product.objects.filter(category_id=id_category, quantity__gte=1))} try: product = sorted_values[sorted_by]() except KeyError: product = sorted_values["error"]() paginator = Paginator(product, 25) page = request.GET.get('page') try: context["product"] = paginator.get_page(page) except PageNotAnInteger: context["product"] = paginator.page(1) except EmptyPage: context["product"] = paginator.page(1) context = tools.mergeDict(context, tools.displayCategory()) context = tools.mergeDict(context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" return render(request, 'view_category.html', context)
def view_my_order(request): """:synopsis: Permet de d'afficher la page pour visualisé information sur les Commandes du client :param request: La requete du client de type GET :type request: djangoRequest :return: Si requete GET le template + le context -> générer au final une page html """ context = tools.mergeDict( {"basketCount": tools.basketCount(request)}, {"emailNewsLetter": request.session.get('emailNewsLetter')}) order = Order.objects.filter(customer__user=request.user).order_by('-date') context = tools.mergeDict( context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" context["order"] = order context["orderProduct"] = {} for items in order: context["orderProduct"][str( items.id)] = OrderProduct.objects.filter(order=items) return render(request, 'order.html', context)
def view_basket(request): """:synopsis: Permet de générer la page Basket(Panier client) si request = GET :param request: La requete du client de type GET :type request: djangoRequest :return: le template + le context -> générer au final une page html """ context = {"basketCount": tools.basketCount(request)} product = Basket.objects.filter(customer__user=request.user) context["product"] = product # on calcule le prix total, le prix ht total_ttc = 0 for item in product: total_ttc += float(item.product.price * item.quantity) context["totalTTC"] = round(float(total_ttc), 2) context["tva"] = round(float(total_ttc * 0.2), 2) context["totalHT"] = round(float(total_ttc - context["tva"]), 2) context = tools.mergeDict( context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" return render(request, 'basket.html', context)
def contact(request): """:synopsis: Permet de générer la page contact si request = GET sinon permet d'enregistrer une demande de contact dans la base de données :param request: La requete du client de type POST ou GET :type request: djangoRequest :return: le template + le context -> générer au final une page html """ if request.method == "GET": form = ContactForm() context = {"form": form, "basketCount": tools.basketCount(request)} context = tools.mergeDict( context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" return render(request, 'contact/contact.html', context) else: # method POST form = ContactForm(request.POST) if form.is_valid(): form.save() return HttpResponse("ok sa marche")
def view_category(request, id_category): """:synopsis: Permet de générer la page pour afficher tous les produit contenu dans une catégorie si request = GET. :param request: La requete du client de type GET :type request: djangoRequest :param id_category: L'id de la catégorie a afficher :type id_category: int :return: le template + le context -> générer au final la page html """ # on recupere tous les article lier a cette catégorie product = Product.objects.filter(category_id=id_category, quantity__gte=1) paginator = Paginator(product, 25) page = request.GET.get('page') # get_list_or_404(Product, category_id=id_category) context = {"product": paginator.get_page(page), 'id_category': id_category, 'form': PriceRange(), "basketCount": tools.basketCount(request), 'categoryName': SubCategory.objects.get(id=id_category)} context = tools.mergeDict(context, tools.displayCategory()) context = tools.mergeDict(context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" return render(request, 'view_category.html', context)
def view_price_by_name(request, product_name): """:synopsis: Permet de Trier les produits de la page view Search en fonction d'un prix min et max si request = GET :param request: La requete du client de type GET :type request: djangoRequest :param product_name: le terms rechercher :type product_name: str :return: Le template + le context -> générer au final la page view_search.html avec les produits trier par prix """ context = {"product": object(), 'form': PriceRange(), 'productName': product_name, "basketCount": tools.basketCount(request)} context = tools.mergeDict(context, tools.displayCategory()) context = tools.mergeDict(context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" # on verifie que la requete est de type get if request.method == "GET": form = PriceRange(request.GET) if form.is_valid(): product = Product.objects.filter(price__range=(form.cleaned_data['priceMin'], form.cleaned_data['priceMax']), name__contains=product_name, quantity__gte=1) paginator = Paginator(product, 25) page = request.GET.get('page') try: context["product"] = paginator.get_page(page) except PageNotAnInteger: context["product"] = paginator.page(1) except EmptyPage: context["product"] = paginator.page(1) finally: get = dict(request.GET) get = "priceMin={0}&priceMax={1}".format(get["priceMin"][0], get["priceMax"][0]) context["getParam"] = get return render(request, 'view_search.html', context)
def view_payment(request): """:synopsis: Permet de générer la page Payment(Page de payment) si request = POST sinon redirige vers la page Checkout. :param request: La requete du client de type GET ou POST :type request: djangoRequest :return: si requete POST le template + le context -> générer au final une page html :return: si requete GET redirige vers la page de Checkout """ context = { "basketCount": tools.basketCount(request), 'key': settings.STRIPE_PUBLISHABLE_KEY } context = tools.mergeDict( context, {"emailNewsLetter": request.session.get('emailNewsLetter')}) request.session['emailNewsLetter'] = "" context = tools.mergeDict(context, tools.checkOutProduct(request)) if request.method == "POST": checkout = CheckOut(request.POST) context['CheckOut'] = checkout if checkout.is_valid(): # method = request.POST.get("card") context['disabled'] = "disabled" context["payment"] = """ <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{}" data-description="eBrocante" data-amount="{}" data-locale="auto" data-label="Payer ma commande" data-currency="eur" data-image='https://stripe.com/img/documentation/checkout/marketplace.png'></script> """.format(context["key"], tools.amount(context["totalTTC"])) return render(request, 'checkout.html', context) return render(request, 'checkout.html', context) else: return redirect("CheckOut", id_address=0)
def view_order_done(request): """:synopsis: Permet de générer la page de succes si le payement est passer sinon permet de recharger la page de payment si une erreur c'est produite. En cas de succes cette fonction creer une nouvelle Commande relié aux client dans la base de données, creer aussi une nouvelle Adresse relier au client si l'addresse du formulaire n'existe pas(request = POST). Redirige vers la Page de checkout (request = POST). :param request: La requete du client de type GET ou POST :type request: djangoRequest :return: si requete POST le template + le context -> générer au final une page html :return: si requete GET redirige vers la page de Checkout """ context = {'key': settings.STRIPE_PUBLISHABLE_KEY} # fonction qui gere la fin du payement et la creation de la commande if request.method == "POST": try: token = request.POST.get('stripeToken') checkout = CheckOut(request.POST) context['CheckOut'] = checkout if checkout.is_valid(): print("token = ", token) total_ttc = 0 product = Basket.objects.filter(customer__user=request.user) for item in product: total_ttc += float(item.product.price * item.quantity) context["totalTTC"] = round(float(total_ttc), 2) charge = stripe.Charge.create( amount=tools.amount(context["totalTTC"]), currency='eur', description='Customer Id : {}'.format( Customer.objects.get(user=request.user).id), source=token, ) try: address = Address.objects.get( customer__user=request.user, firstName=checkout.cleaned_data['firstName'], lastName=checkout.cleaned_data['lastName'], address=checkout.cleaned_data['address'], city=checkout.cleaned_data['city'], cp=checkout.cleaned_data['cp'], country=checkout.cleaned_data['country'], mobile=checkout.cleaned_data['mobilePhone']) except Address.DoesNotExist: # on creer une instance address = Address( customer=Customer.objects.get(user=request.user), firstName=checkout.cleaned_data['firstName'], lastName=checkout.cleaned_data['lastName'], address=checkout.cleaned_data['address'], city=checkout.cleaned_data['city'], cp=checkout.cleaned_data['cp'], country=checkout.cleaned_data['country'], mobile=checkout.cleaned_data['mobilePhone']) address.save() order = Order(customer=Customer.objects.get(user=request.user), address=address, status="En cours de Traitement", methodPayment='Cards') order.save() # on recupere le contenu du panier basket = Basket.objects.filter(customer__user=request.user) # on le parcour for item in basket: # on ajoute a la table OrderProduct les produit qui sont dans le panier du client OrderProduct(product=item.product, order=order, quantity=item.quantity).save() product = Product.objects.get(id=item.product.id) print("product quantity old = ", product.quantity) print("product quantity = ", (product.quantity - item.quantity)) # on supprime la quantité au produit product.quantity = (product.quantity - item.quantity) product.save() # on supprime le produit du panier du client item.delete() context = tools.mergeDict({"OrderId": order.id}, { "emailNewsLetter": request.session.get('emailNewsLetter') }) return render(request, "donePayment.html", context) else: # si le formulaire est pas valide on le renvoie context["basketCount"] = tools.basketCount(request) context = tools.mergeDict(context, tools.checkOutProduct(request)) return render(request, 'checkout.html', context) except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly pass except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API pass except stripe.error.AuthenticationError as e: # Authentication with Stripe's API failed # (maybe you changed API keys recently) pass except stripe.error.APIConnectionError as e: # Network communication with Stripe failed pass except stripe.error.StripeError as e: # Display a very generic error to the user, and maybe send # yourself an email pass except Exception as e: # Something else happened, completely unrelated to Stripe pass # si une erreur c'est produite return redirect("Payment") else: # si on a une requete de type get return redirect("Basket")