Skip to content

Programming Challenge 2023 (Submission) #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 92 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
**/node_modules
/.pnp
.pnp.js

Expand All @@ -21,3 +21,94 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Created by https://www.gitignore.io

### OSX ###
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear on external disk
.Spotlight-V100
.Trashes

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk


### Python ###
# Byte-compiled / optimized / DLL files
**/__init__.py
**/__pycache__/
*.py[cod]

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.cache
nosetests.xml
coverage.xml

# Translations
*.mo
*.pot

# Sphinx documentation
docs/_build/

# PyBuilder
target/


### Django ###
*.log
*.pot
*.pyc
__pycache__/
local_settings.py

.env
db.sqlite3
3 changes: 3 additions & 0 deletions API/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions API/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'API'
11 changes: 11 additions & 0 deletions API/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import uuid
from django.db import models

def generateOrderID():
return str(uuid.uuid4()).split('-')[-1].upper()

# Create your models here.
class User(models.Model):
ID = models.AutoField(primary_key = True)
userName = models.CharField(max_length = 255, blank = False)
createdAt = models.DateTimeField(auto_now_add = True)
3 changes: 3 additions & 0 deletions API/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
11 changes: 11 additions & 0 deletions API/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from django.urls import path
from .views import authUser, getStoreStats, fetchProducts, addToCart, getCartCount, getCart

urlpatterns = [
path('authUser', authUser),
path('getStoreStats', getStoreStats),
path('fetchProducts', fetchProducts),
path('addToCart', addToCart),
path('getCartCount', getCartCount),
path('getCart', getCart),
]
85 changes: 85 additions & 0 deletions API/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import requests
from django.urls import reverse
from django.shortcuts import render
from rest_framework import generics
from django.contrib import messages
from django.shortcuts import redirect
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponseRedirect

cartDict = {}
# Create your views here.
def fetchSpecificProduct(productID):
productsData = requests.get(f'https://fakestoreapi.com/products/{productID}').json()
return productsData

@api_view(['POST'])
def authUser(request):
userName = dict(request.POST.items()).get('name')
request.session['userName'] = userName
authResponse = HttpResponseRedirect('http://127.0.0.1:8000/')
authResponse.set_cookie('userName', userName)
return authResponse

@api_view(['GET'])
def getStoreStats(request):
productsList = requests.get('https://fakestoreapi.com/products').json()
categoriesList = requests.get('https://fakestoreapi.com/products/categories').json()
prodList = [tempProd['rating']['rate'] for tempProd in productsList]
prodRatings = [tempProd['rating']['count'] for tempProd in productsList]

return Response({"productsAvailable": len(productsList), "categoriesAvailable": len(categoriesList), "avgReviews": float(round(sum(prodList)/len(prodList), 2)), "prodRatings": sum(prodRatings)})

@api_view(['GET'])
def fetchProducts(request):
productsList = requests.get('https://fakestoreapi.com/products').json()
return Response(productsList)

@api_view(['GET'])
def addToCart(request):
cartItems = 0
productID = int(request.GET.get("prodID"))
if request.session.get('userName') == None or request.session.get('userName') =='':
return JsonResponse({'success': False, 'message': '"Please login prior to adding new products to cart!"'})
else:
userID = request.session['userName']
userCartData = cartDict.get(userID, {})
userCartData[productID] = userCartData.get(productID, 0) + 1
cartDict[userID] = userCartData
for tempProd in cartDict.get(request.session['userName']):
cartItems+= cartDict.get(request.session['userName']).get(tempProd)

return JsonResponse({'success': True, 'message': 'Product added to cart successfully!', 'cartItems': cartItems})

@api_view(['GET'])
def getCartCount(request):
cartItems = 0
if request.session.get('userName') == None:
return JsonResponse({'success': False, 'message': '"Please login prior to fetching cart items!"'})
else:
try:
for tempProd in cartDict.get(request.session['userName']):
cartItems+= cartDict.get(request.session['userName']).get(tempProd)

return JsonResponse({'success': True, 'cartItems': cartItems})
except Exception:
return JsonResponse({'success': True, 'cartItems': 0})

@api_view(['GET'])
def getCart(request):
mainResponse, productsList = {}, []
if cartDict.get(request.session.get('userName')) == None:
return JsonResponse({'productsList': [], 'subTotal': 0.00, 'tax': 0.00, 'totalAmt': 0.00})
else:
for tempProductID in cartDict.get(request.session.get('userName')):
tempResponse, tempProductsData = {}, requests.get(f'https://fakestoreapi.com/products/{tempProductID}').json()
tempResponse['title'], tempResponse['image'], tempResponse['price'], tempResponse['quantity'], tempResponse['subtotal'] = tempProductsData['title'], tempProductsData['image'], tempProductsData['price'], cartDict.get(request.session.get('userName')).get(tempProductID), tempProductsData['price'] * cartDict.get(request.session.get('userName')).get(tempProductID)
productsList.append(tempResponse)

mainResponse['productsList'] = productsList
mainResponse['subTotal'] = sum([tempProduct['subtotal'] for tempProduct in productsList])
mainResponse['tax'] = round(mainResponse['subTotal'] * 0.075, 2)
mainResponse['totalAmt'] = mainResponse['subTotal'] + mainResponse['tax']
return JsonResponse(mainResponse)
3 changes: 3 additions & 0 deletions FrontEnd/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions FrontEnd/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class FrontendConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'FrontEnd'
14 changes: 14 additions & 0 deletions FrontEnd/babel.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "10"
}
}
],
"@babel/preset-react"
],
"plugins": ["@babel/plugin-proposal-class-properties"]
}
3 changes: 3 additions & 0 deletions FrontEnd/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
Loading