Skip to content

Commit

Permalink
A lot has been done!
Browse files Browse the repository at this point in the history
Added htmls for dealer_details and add_review. Updated views, restapis and url files
  • Loading branch information
gokhanduzel committed Dec 14, 2023
1 parent 81b7cf2 commit 6f8d55f
Show file tree
Hide file tree
Showing 7 changed files with 222 additions and 25 deletions.
3 changes: 2 additions & 1 deletion functions/reviews.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from cloudant.client import Cloudant
from cloudant.query import Query
from flask import Flask, jsonify, request
from flask import Flask, jsonify, request, abort
import atexit

#Add your Cloudant service credentials here
Expand Down Expand Up @@ -56,6 +56,7 @@ def post_review():

# Extract review data from the request JSON
review_data = request.json
print(review_data)

# Validate that the required fields are present in the review data
required_fields = ['id', 'name', 'dealership', 'review', 'purchase', 'purchase_date', 'car_make', 'car_model', 'car_year']
Expand Down
Binary file modified server/db.sqlite3
Binary file not shown.
46 changes: 42 additions & 4 deletions server/djangoapp/restapis.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,26 @@ def get_request(url, api_key=None, **kwargs):

# Create a `post_request` to make HTTP POST requests
# e.g., response = requests.post(url, params=kwargs, json=payload)
def post_request(url, json_payload, **kwargs):
print("POST to {} ".format(url))
response = requests.post(
url,
params=kwargs,
data=json.dumps(json_payload),
headers={'Content-Type': 'application/json'},
)

status_code = response.status_code
print("With status {} ".format(status_code))
print("Response text: ", response.text)

try:
json_data = json.loads(response.text)
return json_data
except json.JSONDecodeError:
print("Error decoding JSON response")
return None



# Create a get_dealers_from_cf method to get dealers from a cloud function
Expand Down Expand Up @@ -70,23 +90,41 @@ def get_dealers_from_cf(url, **kwargs):

return results

# def get_dealer_by_id_from_cf(url, dealerId):
def get_dealer_by_id_from_cf(url, dealer_id):
json_result = get_request(url, id=dealer_id)
if json_result:
print(json_result,'dealer_get')
dealer = json_result[0]

dealer_obj = CarDealer(
address=dealer["address"],
city=dealer["city"],
full_name=dealer["full_name"],
id=dealer["id"],
lat=dealer["lat"],
long=dealer["long"],
short_name=dealer["short_name"],
st=dealer["st"],
zip=dealer["zip"]
)
return dealer_obj


# Create a get_dealer_reviews_from_cf method to get reviews by dealer id from a cloud function
# def get_dealer_by_id_from_cf(url, dealerId):
# - Call get_request() with specified arguments
# - Parse JSON results into a DealerView object list
def get_dealer_reviews_from_cf(url, dealer_id):
results = []
# Call get_request with a URL parameter
json_result = get_request(url, api_key=None, id=dealer_id)
print("IT IS IN GET DEALER REVIEWS FROM CF")
json_result = get_request(url, api_key=None, dealer_id=dealer_id)
if isinstance(json_result, list):
reviews = json_result
# Print or log the reviews for debugging
print(reviews)
# For each dealer object
for review in reviews:
# Get its content in `doc` object
# Get its content
review_obj = DealerReview(
dealership=review.get("dealership", ""),
name=review.get("name", ""),
Expand Down
47 changes: 44 additions & 3 deletions server/djangoapp/templates/djangoapp/add_review.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,48 @@
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>

</head>
<body>
<!--Add review form here -->
</body>
<body>

<div class="col-md">
<h3 class="mb-5 mt-3">Add Review for <strong> {{dealer.full_name}} </strong> </h3>
</div>

<form class="d-flex flex-column justify-content-center w-50" action = "{% url 'djangoapp:add_review' dealer.id %}" method="post">
{% csrf_token %}
<div class="col-auto">
<H5>Your Name:</H5><br>
{% csrf_token %}
<input class="form-control" id="name" name="name" size="30" required></textarea><br>
<div class="form-group">
<h5>Enter your review here:</h5>
<textarea class="form-control my-2" id="content" name="content" rows="2" required></textarea>
</div>
<div class = "form-check mt-5">
<input class="form-check-input" type="checkbox" name="purchasecheck" id="purchasecheck">
<label class="form-check-label">Has purchased car from {{dealer.full_name}} ?<label> <span style="color: gray; font-weight: 300; padding-left: 5px;">(select purchased car information below if checked)</span>
</div>
<div class="form-group">
<h5 class="my-2">Select your car (Model-Make-Year):</h5>
<select name="car" id="car" class="form-select my-2 mx-2" required>
{% for car in cars %}
<option selected value={{car.id}}>{{car.name}}-{{car.car_make.name}}-{{ car.year|date:"Y" }}</option>
{% endfor %}
</select>
</div>
<div class="form-group" data-provide="datepicker">
<label for="purchasedate">Select your purchase date:</label>
<input class="date-own form-control my-2" type="date" name="purchasedate" id="purchasedate">
</div>
<button type="submit" class="btn btn-primary my-3 align-items-center">Submit Review</button>

</div>

</form>

</body>
<script type="text/javascript">
$('.date-own').datepicker({
format: 'mm/dd/yyyy'
});
</script>
</html>
81 changes: 77 additions & 4 deletions server/djangoapp/templates/djangoapp/dealer_details.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,85 @@
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>

<body>
<body>
<!--NAVBAR-->
<nav class="navbar navbar-expand-sm navbar-dark bg-dark">
<a class="navbar-brand" href="#">Best Cars</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample04" aria-controls="navbarsExample04" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>

<!--Add a nav bar here -->
<div class="collapse navbar-collapse" id="navbarsExample04">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="about/">About Us <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="contact/">Contact Us <span class="sr-only">(current)</span></a>
</li>
</ul>
{% if user.is_authenticated %}
<li class="my-2 my-md-0">
<a class="btn btn-link" href="/djangoapp/add_review/{{ dealer.id }}/">Add Review</a>
<a class="btn btn-link" href="#">{{ user.first_name }}({{ user.username }})</a>
<a class="btn btn-link" href="logout/">Logout</a>
</li>
{% else %}
<form class="form-inline my-2 my-md-0" action="{% url 'djangoapp:login' %}" method="post">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control-sm" placeholder="Username" name="username" >
<input type="password" class="form-control-sm" placeholder="Password" name="psw" >
<button class="btn-sm btn-primary" type="submit">Login</button>
<a class="btn-sm btn-link" href="registration/">Sign Up</a>
</div>
</form>
{% endif %}
</div>
</nav>
<!-- Add reviews as cards -->
<div class="col-md mb-5 mt-3">
<h3> Reviews for <strong> {{ dealer.full_name }} </strong> </h3>
</div>

<!-- Add reviews as cards -->
<div class="col-md">
{% if reviews_list %}
<div class="card-columns">
{% for review in reviews_list %}
<div class="card text-dark bg-light mb-3 text-left">
{% if review.sentiment == "positive" %}
<img class="card-img-left" src="{{MEDIA_URL}}/emoji/positive.png"/>
{% elif review.sentiment == "neutral" %}
<img class="card-img-left" src="{{MEDIA_URL}}/emoji/neutral.png"/>
{% elif review.sentiment == "negative" %}
<img class="card-img-left" src="{{MEDIA_URL}}/emoji/negative.png"/>
{% else %}
<img class="card-img-left" src="{{MEDIA_URL}}/emoji/neutral.png"/>
{% endif %}

</body>
<div class="card-body bg-light">
{% if review.purchase %}
<h5 class="card-title">{{review.car_make}}</h5>
<h5 class="card-title">{{review.car_model}}</h5>
<h5 class="card-title">{{review.purchase_date}}</h5>
{% else %}
<h5 class="card-title">Reviewer did not buy any car</h5>
{% endif %}
<label class="card-title">{{review.review}}</label>
</div>
</div>
{% endfor %}
</div>
{% else %}
<div class="card-columns">
<div class="card">
<div class="card-body bg-light">
<h5 class="card-title">No reviews yet</h5>
</div>
</div>
</div>
{% endif %}
</div>
</body>

</html>
4 changes: 2 additions & 2 deletions server/djangoapp/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
path(route='', view=views.get_dealerships, name='index'),

# path for dealer reviews view
path(route='dealer/<int:dealer_id>/', view=views.get_dealer_details, name='dealer_details')
path(route='dealer/<int:dealer_id>/', view=views.get_dealer_details, name='dealer_details'),

# path for add a review view

path(route='add_review/<int:dealer_id>/', view=views.add_review, name='add_review')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
66 changes: 55 additions & 11 deletions server/djangoapp/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render, redirect
from .models import CarMake, CarModel, CarDealer, DealerReview
from .restapis import get_dealers_from_cf, get_request, get_dealer_reviews_from_cf
from .restapis import get_dealers_from_cf, get_request, get_dealer_reviews_from_cf, get_dealer_by_id_from_cf, post_request
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from datetime import datetime
Expand Down Expand Up @@ -97,6 +97,7 @@ def get_dealerships(request):
url = "https://gduzel-3001.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai/dealerships/get"
# Get dealers from the URL
dealerships = get_dealers_from_cf(url)
# append the dealership list to context
context["dealership_list"] = dealerships
# Concat all dealer's short name
dealer_names = ' '.join([dealer.short_name for dealer in dealerships])
Expand All @@ -106,20 +107,63 @@ def get_dealerships(request):

# Create a `get_dealer_details` view to render the reviews of a dealer
def get_dealer_details(request, dealer_id):
context={}
if request.method == "GET":
url = "https://gduzel-5001.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai/api/get_reviews"
url_reviews = "https://gduzel-5001.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai/api/get_reviews"
url_dealership = "https://gduzel-3001.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai/dealerships/get"
# Get reviews from the URL
reviews = get_dealer_reviews_from_cf(url, dealer_id)
# Concat all review's name
review_names = ' '.join([review.name for review in reviews])
# Return a list of dealer short name
print(review_names)
return HttpResponse(review_names)
reviews = get_dealer_reviews_from_cf(url_reviews, dealer_id)
# Get dealership by id from the URL
dealer = get_dealer_by_id_from_cf(url_dealership, dealer_id)
# append the reviews list to context
context["reviews_list"] = reviews
# append the dealer to context
context["dealer"] = dealer


return render(request, 'djangoapp/dealer_details.html', context)




# Create a `add_review` view to submit a review
# def add_review(request, dealer_id):
# ...
def add_review(request, dealer_id):
context = {}
if request.method == "GET":
url = "https://gduzel-3001.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai/dealerships/get"
dealer = get_dealer_by_id_from_cf(url, dealer_id)
print(dealer)
cars = CarModel.objects.filter(dealer_id=dealer_id)
context["dealer"] = dealer
context["cars"] = cars
return render(request, 'djangoapp/add_review.html', context)

if request.method == "POST":
if request.user.is_authenticated:
url = "https://gduzel-5001.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai/api/post_review"
username = request.user.username
if 'purchasecheck' in request.POST:
was_purchased = True
else:
was_purchased = False

cars = CarModel.objects.filter(dealer_id=dealer_id)
print(cars,"CARS")
for car in cars:
print(car,"car")
if car.id == int(request.POST['car']):
review_car = car
review = {}
review["id"] = dealer_id
review["name"] = request.POST['name']
review["dealership"] = dealer_id
review["review"] = request.POST['content']
review["purchase"] = was_purchased
review["purchase_date"] = request.POST['purchasedate']
review["car_make"] = review_car.car_make.name
review["car_model"] = review_car.name
review["car_year"] = review_car.year.strftime("%Y")
json_payload = {}
json_payload["review"] = review
response = post_request(url, json_payload, dealer_id=dealer_id)
return redirect("djangoapp:dealer_details", dealer_id=dealer_id)

0 comments on commit 6f8d55f

Please sign in to comment.