Skip to content

Commit

Permalink
feat: [admin] added login flow
Browse files Browse the repository at this point in the history
  • Loading branch information
aabidsofi19 committed Mar 5, 2022
1 parent 42d5008 commit 37ebd17
Show file tree
Hide file tree
Showing 104 changed files with 3,553 additions and 2,317 deletions.
12 changes: 7 additions & 5 deletions apps/backend/Orders/schema.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from ast import Str
import base64
from mongoengine.errors import DoesNotExist

from shop.models import Variation
from shop.types import ProductType, VariationType
from django.core.paginator import Paginator
import graphene
Expand Down Expand Up @@ -80,11 +83,10 @@ def resolve_product(self, info):
return self.product

def resolve_variation(self, info):

for v in self.product.variations:

if str(v._id) == self.variation_id:
return v
try:
return self.product.get_variation(self.variation_id)
except DoesNotExist:
return Variation(price=0)


class Query(graphene.ObjectType):
Expand Down
148 changes: 81 additions & 67 deletions apps/backend/cart/cart.py
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
from decimal import Decimal
from telnetlib import DO
import uuid
import uuid
from bson.objectid import ObjectId
from django.conf import settings
from pathlib import Path
from mongoengine import DoesNotExist
from shop.models import Product
from abc import ABC,abstractmethod
from typing import List,Dict
from abc import ABC, abstractmethod
from typing import List, Dict

BASE_DIR = Path(__file__).resolve().parent.parent


class AbstractCart(ABC):

@abstractmethod
def add(self, product_id,variation_id,quantity=1, override_quantity=False):
def add(self, product_id, variation_id, quantity=1, override_quantity=False):
pass

@abstractmethod
def clear_cart(self):
pass

@abstractmethod
def total_items(self):
def total_items(self):
pass

@abstractmethod
def products(self) -> List[Dict]:
""" returns all the items in the cart """
"""returns all the items in the cart"""
pass

@abstractmethod
def remove(self, product_id,variation_id):
def remove(self, product_id, variation_id):
pass

@abstractmethod
Expand All @@ -52,99 +52,113 @@ def __init__(self, request):
# save an empty cart in the session
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart

def products(self):
"""
Iterate over the items in the cart and get the products
from the database.
"""
products=[]
for key,item in self.cart.items():
cart_obj= {}
cart_obj["quantity"]=item["quantity"]
keys=key.split(",")
product_id=keys[0]

try :
products = []
for key, item in self.cart.items():
cart_obj = {}
cart_obj["quantity"] = item["quantity"]
keys = key.split(",")
product_id = keys[0]

try:
product = Product.objects.get(id=product_id)
except DoesNotExist :
except DoesNotExist:
self.remove(key)
variation = None
for v in product.variations :

variation = None
for v in product.variations:
if str(v._id) == keys[1]:
variation =v
variation = v
break
cart_obj['product']=product
cart_obj['variation']=variation
cart_obj['price']=int(item['price'])
cart_obj["product"] = product
cart_obj["variation"] = variation
cart_obj["price"] = int(item["price"])
# cart_obj['totalPrice']=int(item['price'])* item['quantity']
products.append(cart_obj)
return products

def total_items(self):
return sum(item['quantity'] for item in self.cart.values())
return sum(item["quantity"] for item in self.cart.values())

def data(self):
return self.cart

def get_total_price(self):
#print(self.cart)
return sum(
int(item['price']) * int(item['quantity']) for item
in self.cart.values()
# print(self.cart)
return sum(
int(item["price"]) * int(item["quantity"]) for item in self.cart.values()
)

def clear_cart(self):
del self.session[settings.CART_SESSION_ID]
self.save()


def add(self, product_id,variation_id,quantity=1, override_quantity=False,):

def add(
self,
product_id,
variation_id,
quantity=1,
override_quantity=False,
):

"""
Add a product to the cart or update its quantity.
"""

if quantity <= 0:
raise ValueError('Cannot add zero or negative quantities!')

product_id = (product_id)
product=Product.objects(id=product_id,)

for v in product[0].variations:

if str(v._id)==str(variation_id):
#print('hi')
variation = v
price=variation.price

key =f"{product_id},{variation_id}"
raise ValueError("Cannot add zero or negative quantities!")

product_id = product_id

try:
product = Product.objects.get(
id=product_id,
)
variation = product.get_variation(variation_id)

except DoesNotExist:

return

print("variation", variation)
price = variation.price

key = f"{product_id},{variation_id}"

if key not in self.cart:
self.cart[key] = {'quantity': 0,'price': str(price)}
self.cart[key] = {"quantity": 0, "price": str(price)}
if override_quantity:
self.cart[key]['price']=str(price)
self.cart[key]['quantity'] = quantity
self.cart[key]["price"] = str(price)
self.cart[key]["quantity"] = quantity
else:
self.cart[key]['price']=str(price)
self.cart[key]['quantity'] += quantity
self.cart[key]["price"] = str(price)
self.cart[key]["quantity"] += quantity
self.save()

def save(self):
# mark the session as "modified" to make sure it gets saved
# mark the session as "modified" to make sure it gets saved
self.session.modified = True

def remove(self, product_id,variation_id):
key =f"{product_id},{variation_id}"
def remove(self, product_id, variation_id):

key = f"{product_id},{variation_id}"

if key in self.cart:
del self.cart[key]
self.save()

def add_from_db(self,db_cart):
def add_from_db(self, db_cart):
items = db_cart.products()
for item in items :
self.add(str(item.product.id),str(item.variation._id),item.quantity,override_quantity=True)
self.save()
for item in items:
self.add(
str(item.product.id),
str(item.variation._id),
item.quantity,
override_quantity=True,
)
self.save()
10 changes: 9 additions & 1 deletion apps/backend/filters/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,21 @@ class SortOptions(graphene.Enum):
class FilterInput(graphene.InputObjectType):
categories = graphene.List(graphene.String, required=False)
gender = graphene.String(required=False)
status = graphene.String(required=False)
status = graphene.String(required=False, default_value="active")
sub_categories = graphene.List(graphene.String, required=False)
brands = graphene.List(graphene.String, required=False)
variant_filters = graphene.List(VariantsFilterInput, required=False)
tags = graphene.List(graphene.String, required=False)
sort_by = graphene.Field(SortOptions)

@classmethod
def default(cls):
meta = cls._meta
fields = meta.fields
default_fields = {name: field.default_value for name, field in fields.items()}
container = meta.container
return container(**default_fields)


##### custom filter to use in model #######

Expand Down
4 changes: 2 additions & 2 deletions apps/backend/shop/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ class Product(Document):

created_at = DateTimeField(default=datetime.now)
name = StringField(max_length=100, required=True)
brand = ReferenceField(Brand, required=True)
category = ReferenceField(Category, required=True)
brand = ReferenceField(Brand, required=True, reverse_delete_rule=NULLIFY)
category = ReferenceField(Category, required=True, reverse_delete_rule=NULLIFY)
# sub_category= ReferenceField(SubCategory)
description = StringField(required=True, max_length=2000)
variations = ListField(EmbeddedDocumentField(Variation))
Expand Down
29 changes: 23 additions & 6 deletions apps/backend/shop/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
from .models import Product, Category, Variant, Brand
from filters.schema import FilterInput
from .types import ProductsType, VariantType, ProductType, CategoryType, BrandType
from Orders.models import Order


class Query(ObjectType):

Products = graphene.Field(
ProductsType,
filter=FilterInput(),
filter=FilterInput(default_value=FilterInput.default()),
pageNb=graphene.Int(default_value=1, required=False),
)
product = graphene.Field(ProductType, id=graphene.String())
Expand All @@ -23,12 +24,12 @@ def resolve_product(self, info, id, **kwargs):
# print(product)
return product

def resolve_Products(self, info, filter={}, pageNb=1, **kwargs):
def resolve_Products(self, info, filter, pageNb=1, **kwargs):
# print("fetching products")
# print("pagenb :- ",pageNb)

if not info.context.user.is_superuser:
filter["status"] = "active"
filter.status = "active"

limit = 30
offset = (pageNb - 1) * limit
Expand Down Expand Up @@ -158,13 +159,16 @@ def mutate(self, info, input):

class updateBrand(graphene.Mutation):
class Arguments:
id = graphene.String(required=True)
input = BrandInput(required=True)

brand = graphene.Field(BrandType)

def mutate(self, info, input):
brand = Brand.objects(id=input.get("id")).first()
def mutate(self, info, id, input):
brand = Brand.objects(id=id).first()
brand.update(**input)
brand.save()
brand.reload()
return updateBrand(brand=brand)


Expand Down Expand Up @@ -206,14 +210,23 @@ class Arguments:

def mutate(self, info, id, input):
category = Category.objects(id=id).first()
clean_input = clean_category_input(input)
if category:
category.update(**{k: v for k, v in input.items() if v is not None})
category.update(**clean_input)
category.save()
category.reload()
return updateCategory(category=category)
else:
return updateCategory(category=None)


def clean_category_input(input):
copy = {k: v for k, v in input.items() if v is not None}
if copy.get("brands"):
copy["brands"] = {bson.ObjectId(id) for id in copy["brands"]}
return copy


class deleteCategory(graphene.Mutation):
class Arguments:
id = graphene.String(required=True)
Expand Down Expand Up @@ -296,6 +309,10 @@ class Arguments:
id = graphene.String()

def mutate(root, info, id):

orders_for_product = Order.objects.filter(product_id=id)
if orders_for_product:
raise Exception("Orders for this product exist")
product = Product.objects(id=id).first()
product.delete()
return deleteProduct(product=product)
Expand Down
15 changes: 15 additions & 0 deletions apps/backend/shop/types.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from graphene_mongo import MongoengineObjectType
import graphene
from shop.models import *
from mongoengine.errors import DoesNotExist


class BrandType(MongoengineObjectType):
Expand Down Expand Up @@ -35,6 +36,20 @@ class ProductType(MongoengineObjectType):
class Meta:
model = Product

def resolve_brand(self, info):
try:
brand = self.brand
return brand
except DoesNotExist:
return Brand(name="Doesnt Exist", logo="")

def resolve_category(self, info):
try:
category = self.category
return category
except DoesNotExist:
return Category(name="", image="")


class ProductsType(graphene.ObjectType):
products = graphene.List(ProductType)
Expand Down
Loading

0 comments on commit 37ebd17

Please sign in to comment.