diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000000..1d5c207add --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,59 @@ +name: 'Lint Code' + +on: + push: + branches: [master, main] + pull_request: + branches: [master, main] + +jobs: + lint_python: + name: Lint Python Files + runs-on: ubuntu-latest + + steps: + + - name: Checkout Repository + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.12 + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 + + - name: Print working directory + run: pwd + + - name: Run Linter + run: | + pwd + # This command finds all Python files recursively and runs flake8 on them + find . -name "*.py" -exec flake8 {} + + echo "Linted all the python files successfully" + + lint_js: + name: Lint JavaScript Files + runs-on: ubuntu-latest + + steps: + - name: Checkout Repository + uses: actions/checkout@v3 + + - name: Install Node.js + uses: actions/setup-node@v3 + with: + node-version: 14 + + - name: Install JSHint + run: npm install jshint --global + + - name: Run Linter + run: | + # This command finds all JavaScript files recursively and runs JSHint on them + find ./server/database -name "*.js" -exec jshint {} + + echo "Linted all the js files successfully" diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000000..2b6f469f0c --- /dev/null +++ b/.jshintrc @@ -0,0 +1,3 @@ +{ + "esversion": 6 +} diff --git a/server/database/app.js b/server/database/app.js index 00f52b2008..f115b3a709 100644 --- a/server/database/app.js +++ b/server/database/app.js @@ -1,104 +1,110 @@ +/*jshint esversion: 8 */ // This line should already be at the top from previous fixes. + const express = require('express'); const mongoose = require('mongoose'); const fs = require('fs'); -const cors = require('cors') -const app = express() +const cors = require('cors'); // Corrected spacing +const app = express(); // Added semicolon const port = 3030; -app.use(cors()) -app.use(require('body-parser').urlencoded({ extended: false })); - -const reviews_data = JSON.parse(fs.readFileSync("reviews.json", 'utf8')); -const dealerships_data = JSON.parse(fs.readFileSync("dealerships.json", 'utf8')); +app.use(cors()); // Added semicolon +app.use(require('body-parser').urlencoded({ extended: false })); // Added semicolon -mongoose.connect("mongodb://mongo_db:27017/",{'dbName':'dealershipsDB'}); +const reviews_data = JSON.parse(fs.readFileSync("reviews.json", 'utf8')); // Added semicolon +const dealerships_data = JSON.parse(fs.readFileSync("dealerships.json", 'utf8')); // Added semicolon +mongoose.connect("mongodb://mongo_db:27017/", {'dbName': 'dealershipsDB'}); // Added semicolon and fixed spacing -const Reviews = require('./review'); +const Reviews = require('./review'); // Added semicolon -const Dealerships = require('./dealership'); +const Dealerships = require('./dealership'); // Added semicolon try { - Reviews.deleteMany({}).then(()=>{ - Reviews.insertMany(reviews_data['reviews']); - }); - Dealerships.deleteMany({}).then(()=>{ - Dealerships.insertMany(dealerships_data['dealerships']); - }); - + Reviews.deleteMany({}).then(() => { + Reviews.insertMany(reviews_data.reviews); // Fixed to dot notation: reviews_data['reviews'] -> reviews_data.reviews + }); + Dealerships.deleteMany({}).then(() => { + Dealerships.insertMany(dealerships_data.dealerships); // Fixed to dot notation: dealerships_data['dealerships'] -> dealerships_data.dealerships + }); + } catch (error) { - res.status(500).json({ error: 'Error fetching documents' }); + res.status(500).json({ error: 'Error fetching documents' }); } // Express route to home app.get('/', async (req, res) => { - res.send("Welcome to the Mongoose API") + res.send("Welcome to the Mongoose API"); // Added semicolon }); // Express route to fetch all reviews app.get('/fetchReviews', async (req, res) => { - try { - const documents = await Reviews.find(); - res.json(documents); - } catch (error) { - res.status(500).json({ error: 'Error fetching documents' }); - } + try { + const documents = await Reviews.find(); + res.json(documents); + } catch (error) { + res.status(500).json({ error: 'Error fetching documents' }); + } }); // Express route to fetch reviews by a particular dealer app.get('/fetchReviews/dealer/:id', async (req, res) => { - try { - const documents = await Reviews.find({dealership: req.params.id}); - res.json(documents); - } catch (error) { - res.status(500).json({ error: 'Error fetching documents' }); - } + try { + const documents = await Reviews.find({ dealership: req.params.id }); + res.json(documents); + } catch (error) { + res.status(500).json({ error: 'Error fetching documents' }); + } }); // Express route to fetch all dealerships app.get('/fetchDealers', async (req, res) => { -//Write your code here + try { + const documents = await Dealerships.find(); + res.json(documents); + } catch (error) { + res.status(500).json({ error: 'Error fetching documents' }); + } }); // Express route to fetch Dealers by a particular state app.get('/fetchDealers/:state', async (req, res) => { -//Write your code here + }); // Express route to fetch dealer by a particular id app.get('/fetchDealer/:id', async (req, res) => { -//Write your code here + //Write your code here }); //Express route to insert review app.post('/insert_review', express.raw({ type: '*/*' }), async (req, res) => { - data = JSON.parse(req.body); - const documents = await Reviews.find().sort( { id: -1 } ) - let new_id = documents[0]['id']+1 - - const review = new Reviews({ - "id": new_id, - "name": data['name'], - "dealership": data['dealership'], - "review": data['review'], - "purchase": data['purchase'], - "purchase_date": data['purchase_date'], - "car_make": data['car_make'], - "car_model": data['car_model'], - "car_year": data['car_year'], - }); - - try { - const savedReview = await review.save(); - res.json(savedReview); - } catch (error) { - console.log(error); - res.status(500).json({ error: 'Error inserting review' }); - } + data = JSON.parse(req.body); // Added semicolon + const documents = await Reviews.find().sort({ id: -1 }); // Added semicolon + let new_id = documents[0].id + 1; // Fixed to dot notation: documents[0]['id'] -> documents[0].id + + const review = new Reviews({ + "id": new_id, + "name": data.name, + "dealership": data.dealership, + "review": data.review, + "purchase": data.purchase, + "purchase_date": data.purchase_date, + "car_make": data.car_make, + "car_model": data.car_model, + "car_year": data.car_year + }); + + try { + const savedReview = await review.save(); + res.json(savedReview); + } catch (error) { + console.log(error); // Added semicolon + res.status(500).json({ error: 'Error inserting review' }); + } }); // Start the Express server app.listen(port, () => { - console.log(`Server is running on http://localhost:${port}`); + console.log(`Server is running on http://localhost:${port}`); }); diff --git a/server/djangoapp/.env b/server/djangoapp/.env index 01822e542a..91791e42bd 100644 --- a/server/djangoapp/.env +++ b/server/djangoapp/.env @@ -1,2 +1,3 @@ backend_url =your backend url -sentiment_analyzer_url=your code engine deployment url +sentiment_analyzer_url=https://sentianalyzer.1y32t94nuhbv.us-south.codeengine.appdomain.cloud/ +backend_url = https://brody8991-3030.theiadockernext-1-labs-prod-theiak8s-4-tor01.proxy.cognitiveclass.ai/ \ No newline at end of file diff --git a/server/djangoapp/admin.py b/server/djangoapp/admin.py index 433657fc64..8b53fb60b4 100644 --- a/server/djangoapp/admin.py +++ b/server/djangoapp/admin.py @@ -1,8 +1,10 @@ -# from django.contrib import admin -# from .models import related models +from django.contrib import admin +from .models import CarMake, CarModel # Register your models here. +admin.site.register(CarMake) +admin.site.register(CarModel) # CarModelInline class diff --git a/server/djangoapp/apps.py b/server/djangoapp/apps.py index 3800cc769c..ff2365a747 100644 --- a/server/djangoapp/apps.py +++ b/server/djangoapp/apps.py @@ -2,4 +2,4 @@ class DjangoappConfig(AppConfig): - name = 'djangoapp' + name = "djangoapp" diff --git a/server/djangoapp/microservices/app.py b/server/djangoapp/microservices/app.py index 9d967e6fd9..03fa076444 100644 --- a/server/djangoapp/microservices/app.py +++ b/server/djangoapp/microservices/app.py @@ -1,30 +1,31 @@ from flask import Flask from nltk.sentiment import SentimentIntensityAnalyzer import json + app = Flask("Sentiment Analyzer") sia = SentimentIntensityAnalyzer() -@app.get('/') +@app.get("/") def home(): return "Welcome to the Sentiment Analyzer. \ Use /analyze/text to get the sentiment" -@app.get('/analyze/') +@app.get("/analyze/") def analyze_sentiment(input_txt): scores = sia.polarity_scores(input_txt) print(scores) - pos = float(scores['pos']) - neg = float(scores['neg']) - neu = float(scores['neu']) + pos = float(scores["pos"]) + neg = float(scores["neg"]) + neu = float(scores["neu"]) res = "positive" print("pos neg nue ", pos, neg, neu) - if (neg > pos and neg > neu): + if neg > pos and neg > neu: res = "negative" - elif (neu > neg and neu > pos): + elif neu > neg and neu > pos: res = "neutral" res = json.dumps({"sentiment": res}) print(res) diff --git a/server/djangoapp/migrations/0001_initial.py b/server/djangoapp/migrations/0001_initial.py new file mode 100644 index 0000000000..f560c49aa0 --- /dev/null +++ b/server/djangoapp/migrations/0001_initial.py @@ -0,0 +1,82 @@ +# Generated by Django 5.2.4 on 2025-07-20 16:03 + +import django.core.validators +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [] + + operations = [ + migrations.CreateModel( + name="CarMake", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("name", models.CharField(max_length=100)), + ("description", models.TextField()), + ], + ), + migrations.CreateModel( + name="CarModel", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("dealer_id", models.IntegerField(null=True)), + ("name", models.CharField(max_length=100)), + ( + "type", + models.CharField( + choices=[ + ("SEDAN", "Sedan"), + ("SUV", "SUV"), + ("WAGON", "Wagon"), + ("TRUCK", "Truck"), + ("HATCHBACK", "Hatchback"), + ("COUPE", "Coupe"), + ("CONVERTIBLE", "Convertible"), + ("MINIVAN", "Minivan"), + ("PICKUP", "Pickup"), + ], + default="SUV", + max_length=15, + ), + ), + ( + "year", + models.IntegerField( + default=2023, + validators=[ + django.core.validators.MaxValueValidator(2023), + django.core.validators.MinValueValidator(2015), + ], + ), + ), + ( + "car_make", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to="djangoapp.carmake", + ), + ), + ], + ), + ] diff --git a/server/djangoapp/migrations/__init__.py b/server/djangoapp/migrations/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/server/djangoapp/models.py b/server/djangoapp/models.py index eb101a68c8..5b4d6a24d0 100644 --- a/server/djangoapp/models.py +++ b/server/djangoapp/models.py @@ -1,8 +1,8 @@ # Uncomment the following imports before adding the Model code -# from django.db import models -# from django.utils.timezone import now -# from django.core.validators import MaxValueValidator, MinValueValidator +from django.db import models + +from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. @@ -14,6 +14,14 @@ # - __str__ method to print a car make object +class CarMake(models.Model): + name = models.CharField(max_length=100) + description = models.TextField() + + def __str__(self): + return self.name + + # Create a Car Model model `class CarModel(models.Model):`: # - Many-To-One relationship to Car Make model (One Car Make has many # Car Models, using ForeignKey field) @@ -23,3 +31,32 @@ # - Year (IntegerField) with min value 2015 and max value 2023 # - Any other fields you would like to include in car model # - __str__ method to print a car make object +class CarModel(models.Model): + car_make = models.ForeignKey( + CarMake, on_delete=models.CASCADE + ) # Many-to-One relationship + dealer_id = models.IntegerField( + null=True + ) # Refers to a dealer created in Cloudant database + name = models.CharField(max_length=100) + CAR_TYPES = [ + ("SEDAN", "Sedan"), + ("SUV", "SUV"), + ("WAGON", "Wagon"), + ("TRUCK", "Truck"), + ("HATCHBACK", "Hatchback"), + ("COUPE", "Coupe"), + ("CONVERTIBLE", "Convertible"), + ("MINIVAN", "Minivan"), + ("PICKUP", "Pickup"), + # Add more choices as required + ] + type = models.CharField(max_length=15, choices=CAR_TYPES, default="SUV") + year = models.IntegerField( + default=2023, + validators=[ + MaxValueValidator(2023), + MinValueValidator(2015)]) + + def __str__(self): + return f"{self.car_make.name} - {self.name}" diff --git a/server/djangoapp/populate.py b/server/djangoapp/populate.py index 1927e09e18..0f5a55cda1 100644 --- a/server/djangoapp/populate.py +++ b/server/djangoapp/populate.py @@ -1,2 +1,109 @@ +from .models import CarMake, CarModel + + def initiate(): - print("Populate not implemented. Add data manually") + car_make_data = [ + {"name": "NISSAN", "description": "Great cars. Japanese technology"}, + {"name": "Mercedes", "description": "Great cars. German technology"}, + {"name": "Audi", "description": "Great cars. German technology"}, + {"name": "Kia", "description": "Great cars. Korean technology"}, + {"name": "Toyota", "description": "Great cars. Japanese technology"}, + ] + + car_make_instances = [] + for data in car_make_data: + car_make_instances.append( + CarMake.objects.create( + name=data["name"], + description=data["description"])) + + # Create CarModel instances with the corresponding CarMake instances + car_model_data = [ + { + "name": "Pathfinder", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[0], + }, + { + "name": "Qashqai", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[0], + }, + { + "name": "XTRAIL", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[0], + }, + { + "name": "A-Class", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[1], + }, + { + "name": "C-Class", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[1], + }, + { + "name": "E-Class", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[1], + }, + {"name": "A4", "type": "SUV", "year": 2023, + "car_make": car_make_instances[2]}, + {"name": "A5", "type": "SUV", "year": 2023, + "car_make": car_make_instances[2]}, + {"name": "A6", "type": "SUV", "year": 2023, + "car_make": car_make_instances[2]}, + { + "name": "Sorrento", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[3], + }, + { + "name": "Carnival", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[3], + }, + { + "name": "Cerato", + "type": "Sedan", + "year": 2023, + "car_make": car_make_instances[3], + }, + { + "name": "Corolla", + "type": "Sedan", + "year": 2023, + "car_make": car_make_instances[4], + }, + { + "name": "Camry", + "type": "Sedan", + "year": 2023, + "car_make": car_make_instances[4], + }, + { + "name": "Kluger", + "type": "SUV", + "year": 2023, + "car_make": car_make_instances[4], + }, + # Add more CarModel instances as needed + ] + + for data in car_model_data: + CarModel.objects.create( + name=data["name"], + car_make=data["car_make"], + type=data["type"], + year=data["year"], + ) diff --git a/server/djangoapp/restapis.py b/server/djangoapp/restapis.py index 90709d9e3b..cc05e40437 100644 --- a/server/djangoapp/restapis.py +++ b/server/djangoapp/restapis.py @@ -1,22 +1,61 @@ # Uncomment the imports below before you add the function code -# import requests +import requests import os from dotenv import load_dotenv load_dotenv() -backend_url = os.getenv( - 'backend_url', default="http://localhost:3030") +backend_url = os.getenv("backend_url", default="http://localhost:3030") sentiment_analyzer_url = os.getenv( - 'sentiment_analyzer_url', - default="http://localhost:5050/") + "sentiment_analyzer_url", default="http://localhost:5050/" +) + # def get_request(endpoint, **kwargs): # Add code for get requests to back end +def get_request(endpoint, **kwargs): + params = "" + if kwargs: + for key, value in kwargs.items(): + params = params + key + "=" + value + "&" + + request_url = backend_url + endpoint + "?" + params + + print("GET from {} ".format(request_url)) + try: + # Call get method of requests library with URL and parameters + response = requests.get(request_url) + return response.json() + except BaseException: + # If any error occurs + print("Network exception occurred") + # def analyze_review_sentiments(text): # request_url = sentiment_analyzer_url+"analyze/"+text # Add code for retrieving sentiments + +def analyze_review_sentiments(text): + request_url = sentiment_analyzer_url + "analyze/" + text + try: + # Call get method of requests library with URL and parameters + response = requests.get(request_url) + return response.json() + except Exception as err: + print(f"Unexpected {err=}, {type(err)=}") + print("Network exception occurred") + + # def post_review(data_dict): +def post_review(data_dict): + request_url = backend_url + "/insert_review" + try: + response = requests.post(request_url, json=data_dict) + print(response.json()) + return response.json() + except BaseException: + print("Network exception occurred") + + # Add code for posting review diff --git a/server/djangoapp/urls.py b/server/djangoapp/urls.py index 0edc274f90..ea4140b4d0 100644 --- a/server/djangoapp/urls.py +++ b/server/djangoapp/urls.py @@ -1,18 +1,32 @@ # Uncomment the imports before you add the code -# from django.urls import path +from django.urls import path from django.conf.urls.static import static from django.conf import settings -# from . import views +from . import views -app_name = 'djangoapp' +app_name = "djangoapp" urlpatterns = [ # # path for registration - # path for login # path(route='login', view=views.login_user, name='login'), - # path for dealer reviews view - + path(route="get_dealers", view=views.get_dealerships, name="get_dealers"), + path( + route="get_dealers/", + view=views.get_dealerships, + name="get_dealers_by_state", + ), + path( + route="dealer/", + view=views.get_dealer_details, + name="dealer_details", + ), + path( + route="reviews/dealer/", + view=views.get_dealer_reviews, + name="dealer_details", + ), + path(route="add_review", view=views.add_review, name="add_review"), # path for add a review view - + path(route="get_cars", view=views.get_cars, name="getcars"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/server/djangoapp/views.py b/server/djangoapp/views.py index b16409f419..18720883fe 100644 --- a/server/djangoapp/views.py +++ b/server/djangoapp/views.py @@ -1,19 +1,14 @@ # Uncomment the required imports before adding the code -# from django.shortcuts import render -# from django.http import HttpResponseRedirect, HttpResponse -# from django.contrib.auth.models import User -# from django.shortcuts import get_object_or_404, render, redirect -# from django.contrib.auth import logout -# from django.contrib import messages -# from datetime import datetime - from django.http import JsonResponse from django.contrib.auth import login, authenticate import logging import json from django.views.decorators.csrf import csrf_exempt -# from .populate import initiate + +from .populate import initiate +from .models import CarMake, CarModel +from .restapis import get_request, analyze_review_sentiments, post_review # Get an instance of a logger @@ -22,13 +17,14 @@ # Create your views here. + # Create a `login_request` view to handle sign in request @csrf_exempt def login_user(request): # Get username and password from request.POST dictionary data = json.loads(request.body) - username = data['userName'] - password = data['password'] + username = data["userName"] + password = data["password"] # Try to check if provide credential can be authenticated user = authenticate(username=username, password=password) data = {"userName": username} @@ -38,6 +34,7 @@ def login_user(request): data = {"userName": username, "status": "Authenticated"} return JsonResponse(data) + # Create a `logout_request` view to handle sign out request # def logout_request(request): # ... @@ -63,3 +60,64 @@ def login_user(request): # Create a `add_review` view to submit a review # def add_review(request): # ... + + +def get_cars(request): + count = CarMake.objects.filter().count() + print(count) + if count == 0: + initiate() + car_models = CarModel.objects.select_related("car_make") + cars = [] + for car_model in car_models: + cars.append({"CarModel": car_model.name, + "CarMake": car_model.car_make.name}) + return JsonResponse({"CarModels": cars}) + + +# Update the `get_dealerships` render list of dealerships all by default, +# particular state if state is passed +def get_dealerships(request, state="All"): + if state == "All": + endpoint = "/fetchDealers" + else: + endpoint = "/fetchDealers/" + state + dealerships = get_request(endpoint) + return JsonResponse({"status": 200, "dealers": dealerships}) + + +def get_dealer_details(request, dealer_id): + if dealer_id: + endpoint = "/fetchDealer/" + str(dealer_id) + dealership = get_request(endpoint) + return JsonResponse({"status": 200, "dealer": dealership}) + else: + return JsonResponse({"status": 400, "message": "Bad Request"}) + + +def get_dealer_reviews(request, dealer_id): + # if dealer id has been provided + if dealer_id: + endpoint = "/fetchReviews/dealer/" + str(dealer_id) + reviews = get_request(endpoint) + for review_detail in reviews: + sentiment_response = analyze_review_sentiments( + review_detail["review"]) + print(sentiment_response) + review_detail["sentiment"] = sentiment_response["sentiment"] + return JsonResponse({"status": 200, "reviews": reviews}) + else: + return JsonResponse({"status": 400, "message": "Bad Request"}) + + +def add_review(request): + if not request.user.is_anonymous: + data = json.loads(request.body) + try: + post_review(data) # No need to assign to 'response' if not used + return JsonResponse({"status": 200}) + except BaseException: + return JsonResponse( + {"status": 401, "message": "Error in posting review"}) + else: + return JsonResponse({"status": 403, "message": "Unauthorized"}) diff --git a/server/djangoproj/asgi.py b/server/djangoproj/asgi.py index c9336c553c..91b3a676de 100644 --- a/server/djangoproj/asgi.py +++ b/server/djangoproj/asgi.py @@ -11,6 +11,6 @@ from django.core.asgi import get_asgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproj.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproj.settings") application = get_asgi_application() diff --git a/server/djangoproj/settings.py b/server/djangoproj/settings.py index e0b1092a5c..d46d017952 100644 --- a/server/djangoproj/settings.py +++ b/server/djangoproj/settings.py @@ -22,87 +22,105 @@ # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! -SECRET_KEY =\ - 'django-insecure-ccow$tz_=9%dxu4(0%^(z%nx32#s@(zt9$ih@)5l54yny)wm-0' +SECRET_KEY = ( + "django-insecure-ccow$tz_=9%dxu4(0%^(z%nx32#s@(zt9$ih@)5l54yny)wm-0" +) -# SECURITY WARNING: don't run with debug turned on in production! +# SECURITY WARNING: don't run with debug on in production! DEBUG = True -ALLOWED_HOSTS = [] -CSRF_TRUSTED_ORIGINS = [] +ALLOWED_HOSTS = [ + "localhost", + ( # Fix Line 33: E501 line too long (splitting URL string) + "brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01" + ".proxy.cognitiveclass.ai" + ), +] +CSRF_TRUSTED_ORIGINS = [ + ( # Fix Line 37: E501 line too long (splitting URL string) + "https://brody8991-8000.theiadockernext-1-labs-prod-theiak8s-4-tor01" + ".proxy.cognitiveclass.ai" + ) +] REST_FRAMEWORK = { - 'DEFAULT_AUTHENTICATION_CLASSES': [], + "DEFAULT_AUTHENTICATION_CLASSES": [], } # Application definition INSTALLED_APPS = [ - 'djangoapp.apps.DjangoappConfig', - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', + "djangoapp.apps.DjangoappConfig", + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", ] MIDDLEWARE = [ - 'django.middleware.security.SecurityMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.common.CommonMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - 'django.middleware.clickjacking.XFrameOptionsMiddleware', + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", ] -ROOT_URLCONF = 'djangoproj.urls' +ROOT_URLCONF = "djangoproj.urls" TEMPLATES = [ { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], - 'APP_DIRS': True, - 'OPTIONS': { - 'context_processors': [ - 'django.template.context_processors.debug', - 'django.template.context_processors.request', - 'django.contrib.auth.context_processors.auth', - 'django.contrib.messages.context_processors.messages', + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [ + os.path.join(BASE_DIR, "frontend/static") + ], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", ], }, }, ] -WSGI_APPLICATION = 'djangoproj.wsgi.application' +WSGI_APPLICATION = "djangoproj.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': BASE_DIR / 'db.sqlite3', + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", } } AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': - 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + "NAME": ( + "django.contrib.auth.password_validation." + "UserAttributeSimilarityValidator" + ), # User similarity validator }, { - 'NAME': - 'django.contrib.auth.password_validation.MinimumLengthValidator', + "NAME": ( + "django.contrib.auth.password_validation.MinimumLengthValidator" + ), }, { - 'NAME': - 'django.contrib.auth.password_validation.CommonPasswordValidator', + "NAME": ( + "django.contrib.auth.password_validation.CommonPasswordValidator" + ), }, { - 'NAME': - 'django.contrib.auth.password_validation.NumericPasswordValidator', + "NAME": + "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] @@ -110,9 +128,9 @@ # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ -LANGUAGE_CODE = 'en-us' +LANGUAGE_CODE = "en-us" -TIME_ZONE = 'UTC' +TIME_ZONE = "UTC" USE_I18N = True @@ -124,15 +142,18 @@ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ -STATIC_URL = '/static/' -STATIC_ROOT = os.path.join(BASE_DIR, 'static') -MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') -MEDIA_URL = '/media/' +STATIC_URL = "/static/" +STATIC_ROOT = os.path.join(BASE_DIR, "static") +MEDIA_ROOT = os.path.join(STATIC_ROOT, "media") +MEDIA_URL = "/media/" # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field -DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' - -STATICFILES_DIRS = [] +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" +STATICFILES_DIRS = [ + os.path.join( # This was previously line 146, which was fixed + BASE_DIR, "frontend/static" + ) +] # Static files directory diff --git a/server/djangoproj/urls.py b/server/djangoproj/urls.py index 6808da9141..8d07a685a3 100644 --- a/server/djangoproj/urls.py +++ b/server/djangoproj/urls.py @@ -13,6 +13,7 @@ 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ + from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView @@ -20,7 +21,9 @@ from django.conf import settings urlpatterns = [ - path('admin/', admin.site.urls), - path('djangoapp/', include('djangoapp.urls')), - path('', TemplateView.as_view(template_name="Home.html")), + path("contact/", TemplateView.as_view(template_name="Contact.html")), + path("about/", TemplateView.as_view(template_name="About.html")), + path("admin/", admin.site.urls), + path("djangoapp/", include("djangoapp.urls")), + path("", TemplateView.as_view(template_name="Home.html")), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) diff --git a/server/djangoproj/wsgi.py b/server/djangoproj/wsgi.py index 171ab807e3..b0c3e2a268 100644 --- a/server/djangoproj/wsgi.py +++ b/server/djangoproj/wsgi.py @@ -11,6 +11,6 @@ from django.core.wsgi import get_wsgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproj.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproj.settings") application = get_wsgi_application() diff --git a/server/frontend/package-lock.json b/server/frontend/package-lock.json index 0797425307..bdb21fad35 100644 --- a/server/frontend/package-lock.json +++ b/server/frontend/package-lock.json @@ -16,6 +16,9 @@ "react-router-dom": "^6.19.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" + }, + "devDependencies": { + "@babel/plugin-proposal-private-property-in-object": "^7.21.11" } }, "node_modules/@aashutoshrathi/word-wrap": { @@ -646,9 +649,18 @@ } }, "node_modules/@babel/plugin-proposal-private-property-in-object": { - "version": "7.21.0-placeholder-for-preset-env.2", - "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", - "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "version": "7.21.11", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.11.tgz", + "integrity": "sha512-0QZ8qP/3RLDVBwBFoWAwCtgcDZJVwA5LUJRZU8x2YFfKNuFq161wK3cuGrALu5yiPu+vzwTAg/sMWVNeWeNyaw==", + "deprecated": "This proposal has been merged to the ECMAScript standard and thus this plugin is no longer maintained. Please use @babel/plugin-transform-private-property-in-object instead.", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-annotate-as-pure": "^7.18.6", + "@babel/helper-create-class-features-plugin": "^7.21.0", + "@babel/helper-plugin-utils": "^7.20.2", + "@babel/plugin-syntax-private-property-in-object": "^7.14.5" + }, "engines": { "node": ">=6.9.0" }, @@ -1891,6 +1903,18 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/preset-env/node_modules/@babel/plugin-proposal-private-property-in-object": { + "version": "7.21.0-placeholder-for-preset-env.2", + "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-private-property-in-object/-/plugin-proposal-private-property-in-object-7.21.0-placeholder-for-preset-env.2.tgz", + "integrity": "sha512-SOSkfJDddaM7mak6cPEpswyTRnuRltl429hMraQEglW+OkovnCzsiszTmsrlY//qLFjCpQDFRvjdm2wA5pPm9w==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, "node_modules/@babel/preset-env/node_modules/semver": { "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", diff --git a/server/frontend/src/App.js b/server/frontend/src/App.js index aceac6974d..631f265741 100644 --- a/server/frontend/src/App.js +++ b/server/frontend/src/App.js @@ -1,10 +1,37 @@ -import LoginPanel from "./components/Login/Login" +// src/App.js + import { Routes, Route } from "react-router-dom"; +// Corrected import for Login/LoginPanel - assuming LoginPanel is what you want to use for /login +import LoginPanel from "./components/Login/Login"; // This imports the default export from Login.js as LoginPanel +import Register from "./components/Register/Register"; +import Dealers from './components/Dealers/Dealers'; + +// **** THESE ARE THE MISSING IMPORTS THAT ARE CAUSING THE ESLINT ERRORS **** +// You need to import these components from their respective files. +// Adjust the paths based on where these component files actually live in your project. +// Common assumption: each component has its own folder within `src/components/` +import Home from './components/Home/Home'; // Assuming your Home component is in src/components/Home/Home.js +import Dealer from './components/Dealers/Dealer'; // Assuming your Dealer component is in src/components/Dealer/Dealer.js + // Assuming PostReview is in src/components/PostReview/PostReview.js +import Header from './components/Header/Header'; +import PostReview from "./components/Dealers/PostReview" function App() { return ( + + } /> + {/* If LoginPanel is the component for your login page, use it here: */} } /> + {/* If you have a separate component named 'Login' that is *not* LoginPanel, + then you would need to import 'Login' as well: import Login from './components/Login/LoginComponent'; + But typically, LoginPanel IS the Login component. + */} + } /> + } /> + } /> + } /> + ); } diff --git a/server/frontend/src/components/Dealers/Dealers.jsx b/server/frontend/src/components/Dealers/Dealers.jsx index db3410680c..e4fa7a749a 100644 --- a/server/frontend/src/components/Dealers/Dealers.jsx +++ b/server/frontend/src/components/Dealers/Dealers.jsx @@ -5,92 +5,120 @@ import Header from '../Header/Header'; import review_icon from "../assets/reviewicon.png" const Dealers = () => { - const [dealersList, setDealersList] = useState([]); - // let [state, setState] = useState("") - let [states, setStates] = useState([]) + const [dealersList, setDealersList] = useState([]); + const [states, setStates] = useState([]); + const [selectedState, setSelectedState] = useState('All'); // New state to manage the selected filter value - // let root_url = window.location.origin - let dealer_url ="/djangoapp/get_dealers"; - - let dealer_url_by_state = "/djangoapp/get_dealers/"; - - const filterDealers = async (state) => { - dealer_url_by_state = dealer_url_by_state+state; - const res = await fetch(dealer_url_by_state, { - method: "GET" - }); - const retobj = await res.json(); - if(retobj.status === 200) { - let state_dealers = Array.from(retobj.dealers) - setDealersList(state_dealers) - } - } + // Function to fetch dealerships based on the selected state + const fetchDealerships = async (stateParam) => { // Renamed parameter to avoid conflict with useState + let url = `/djangoapp/get_dealers`; + if (stateParam && stateParam !== 'All') { + url = `/djangoapp/get_dealers/${stateParam}`; // Correctly form URL for specific state + } + + try { + const res = await fetch(url, { + method: "GET" + }); + const retobj = await res.json(); + if (retobj.status === 200) { + setDealersList(Array.from(retobj.dealers)); + } else { + console.error("Failed to fetch dealerships:", retobj.message); + setDealersList([]); // Clear list on error + } + } catch (error) { + console.error("Network error fetching dealerships:", error); + setDealersList([]); // Clear list on network error + } + }; - const get_dealers = async ()=>{ - const res = await fetch(dealer_url, { - method: "GET" - }); - const retobj = await res.json(); - if(retobj.status === 200) { - let all_dealers = Array.from(retobj.dealers) - let states = []; - all_dealers.forEach((dealer)=>{ - states.push(dealer.state) + // Function to get all dealers and populate states dropdown initially + const get_all_dealers_and_states = async () => { + const res = await fetch("/djangoapp/get_dealers", { // Always fetch all initially to get states + method: "GET" }); + const retobj = await res.json(); + if (retobj.status === 200) { + let all_dealers = Array.from(retobj.dealers); + let uniqueStates = new Set(); + all_dealers.forEach((dealer) => { + uniqueStates.add(dealer.state); + }); + setStates(Array.from(uniqueStates)); // Set unique states for the dropdown + setDealersList(all_dealers); // Set the initial list of all dealers + } else { + console.error("Failed to fetch initial dealerships and states:", retobj.message); + } + }; - setStates(Array.from(new Set(states))) - setDealersList(all_dealers) - } - } - useEffect(() => { - get_dealers(); - },[]); + // Use useEffect to fetch initial data and then re-fetch when selectedState changes + useEffect(() => { + // On initial mount, get all dealers and populate states + get_all_dealers_and_states(); + }, []); // Empty dependency array: runs only once on component mount + // This useEffect watches for changes in selectedState and fetches dealers accordingly + useEffect(() => { + if (selectedState) { // Ensure selectedState is not null/undefined + fetchDealerships(selectedState); + } + }, [selectedState]); // Dependency array: re-run when selectedState changes -let isLoggedIn = sessionStorage.getItem("username") != null ? true : false; -return( -
-
+ const handleStateChange = (e) => { + setSelectedState(e.target.value); // Update the selectedState + }; - - - - - - - - - {isLoggedIn ? ( - - ):<> - } - - {dealersList.map(dealer => ( - - - - - - - - {isLoggedIn ? ( - - ):<> - } - - ))} -
IDDealer NameCityAddressZip - + let isLoggedIn = sessionStorage.getItem("username") != null ? true : false; +return ( +
+
-
Review Dealer
{dealer['id']}{dealer['full_name']}{dealer['city']}{dealer['address']}{dealer['zip']}{dealer['state']}Post Review
; -
-) + + + + + + + + + + {isLoggedIn ? ( + + ) : <> + } + + + + {dealersList.length === 0 ? ( + + ) : ( + dealersList.map(dealer => ( + {/* Add key for list items */} + + + + + + + {isLoggedIn ? ( + + ) : <> + } + + )) + )} + +
IDDealer NameCityAddressZip + + Review Dealer
Loading dealerships...
{dealer['id']}{dealer['full_name']}{dealer['city']}{dealer['address']}{dealer['zip']}{dealer['state']}Post Review
+ + ); } -export default Dealers +export default Dealers; \ No newline at end of file diff --git a/server/frontend/src/components/Home/Home.jsx b/server/frontend/src/components/Home/Home.jsx new file mode 100644 index 0000000000..35c3e4aac8 --- /dev/null +++ b/server/frontend/src/components/Home/Home.jsx @@ -0,0 +1,60 @@ +// /home/project/xrwvm-fullstack_developer_capstone/server/frontend/src/components/Home/Home.jsx + +import React from 'react'; +import { Link } from 'react-router-dom'; // Assuming you have react-router-dom installed for navigation + +function Home() { + const containerStyle = { + textAlign: 'center', + padding: '50px', + fontFamily: 'Arial, sans-serif', + }; + + const buttonContainerStyle = { + marginTop: '30px', + }; + + const buttonStyle = { + display: 'inline-block', + margin: '10px', + padding: '12px 25px', + fontSize: '18px', + fontWeight: 'bold', + color: '#fff', + backgroundColor: '#007bff', + border: 'none', + borderRadius: '5px', + cursor: 'pointer', + textDecoration: 'none', // For Link components + }; + + const buttonHoverStyle = { + backgroundColor: '#0056b3', // Darker blue on hover + }; + + return ( +
+

Welcome to Best Cars Dealership!

+

Your one-stop solution for finding the best car deals and managing your dealership network.

+ +
+ {/* Login Button */} + e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor} onMouseOut={(e) => e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor}> + Login + + + {/* Register Button */} + e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor} onMouseOut={(e) => e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor}> + Register + + + {/* Dealers Button */} + e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor} onMouseOut={(e) => e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor}> + View Dealerships + +
+
+ ); +} + +export default Home; \ No newline at end of file diff --git a/server/frontend/src/components/Register/Register.jsx b/server/frontend/src/components/Register/Register.jsx new file mode 100644 index 0000000000..d7981a606e --- /dev/null +++ b/server/frontend/src/components/Register/Register.jsx @@ -0,0 +1,101 @@ +import React, { useState } from "react"; +import "./Register.css"; +import user_icon from "../assets/person.png" +import email_icon from "../assets/email.png" +import password_icon from "../assets/password.png" +import close_icon from "../assets/close.png" + +const Register = () => { +// State variables for form inputs + const [userName, setUserName] = useState(""); + const [password, setPassword] = useState(""); + const [email, setEmail] = useState(""); + const [firstName, setFirstName] = useState(""); + const [lastName, setlastName] = useState(""); + +// Redirect to home + const gohome = ()=> { + window.location.href = window.location.origin; + } + +// Handle form submission + const register = async (e) => { + e.preventDefault(); + + let register_url = window.location.origin+"/djangoapp/register"; + +// Send POST request to register endpoint + const res = await fetch(register_url, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + "userName": userName, + "password": password, + "firstName":firstName, + "lastName":lastName, + "email":email + }), + }); + + const json = await res.json(); + if (json.status) { + // Save username in session and reload home + sessionStorage.setItem('username', json.userName); + window.location.href = window.location.origin; + } + else if (json.error === "Already Registered") { + alert("The user with same username is already registered"); + window.location.href = window.location.origin; + } +}; + + return( +
+ + +
+
+
+ Username + setUserName(e.target.value)}/> +
+
+ First Name + setFirstName(e.target.value)}/> +
+ +
+ Last Name + setlastName(e.target.value)}/> +
+ +
+ Email + setEmail(e.target.value)}/> +
+ +
+ password + setPassword(e.target.value)}/> +
+ +
+
+ +
+
+
+ ) +} + +export default Register; \ No newline at end of file diff --git a/server/frontend/static/About.html b/server/frontend/static/About.html index 484efd960f..8e23c85877 100644 --- a/server/frontend/static/About.html +++ b/server/frontend/static/About.html @@ -1,68 +1,70 @@ - +      +   
- - -
- -
-
- Card image -
-

Person1

-

Person1 Title

-

Some text that explains the person1 in about 2 short sentences

-

person1@example.com

-
-
+  +   
+      +     
+     
+        Card image +       
+         

John Doe

+         

General Manager

+         

John has over 20 years of experience in the automotive industry and is dedicated to customer satisfaction. He leads our team with a passion for cars and a commitment to excellence.

+         

john.doe@example.com

+       
+     
-
- Card image -
-

Person2

-

Person2 Title

-

Some text that explains the person2 in about 2 short sentences

-

person2@example.com

-
-
+     
+        Card image +       
+         

Jane Smith

+         

Sales Director

+         

Jane excels at helping customers find their perfect vehicle. Her extensive knowledge of our inventory and friendly approach make the car-buying process a breeze.

+         

jane.smith@example.com

+       
+     
-
- Card image -
-

Person3

-

Person3 Title

-

Some text that explains the person3 in about 2 short sentences

-

person3@example.com

-
-
-
-
-
- +     
+        Card image +       
+         

Peter Jones

+         

Finance Manager

+         

Peter works tirelessly to secure the best financing options for our clients. He ensures a smooth and transparent process, making your dream car more affordable.

+         

peter.jones@example.com

+       
+     
+   
+   
+    +    - + \ No newline at end of file diff --git a/server/frontend/static/Contact.html b/server/frontend/static/Contact.html new file mode 100644 index 0000000000..612ea989a8 --- /dev/null +++ b/server/frontend/static/Contact.html @@ -0,0 +1,60 @@ + + +    Contact Us +    +    + + +   
+        +        +       
+            +           
+               
+                    Customer Service Icon +               
+               
+                   

Contact Customer Service

+                    support@bestcars.com +                   
+                   

Contact our National Advertising team

+                    NationalSales@bestcars.com +                   
+                   

Contact our Public Relations team

+                    PR@bestcars.com +                   
+                   

Contact the bestcars.com offices

+                   

312-611-1111

+                   
+                    Become a bestcars.com car dealer +                   
+                    Visit growwithbestcars.com +               
+           
+       
+   
+ + \ No newline at end of file diff --git a/server/frontend/static/Home.html b/server/frontend/static/Home.html index fb0c3fb617..31db8f326a 100644 --- a/server/frontend/static/Home.html +++ b/server/frontend/static/Home.html @@ -1,64 +1,84 @@ - - - -
- ... - ...
- + \ No newline at end of file diff --git a/server/manage.py b/server/manage.py index af7e44b832..4d9551ce86 100755 --- a/server/manage.py +++ b/server/manage.py @@ -6,7 +6,7 @@ def main(): """Run administrative tasks.""" - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproj.settings') + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoproj.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: @@ -18,5 +18,5 @@ def main(): execute_from_command_line(sys.argv) -if __name__ == '__main__': +if __name__ == "__main__": main()