WMGZON/controllers/web/product.py

188 lines
5.3 KiB
Python
Raw Normal View History

"""
Product related endpoints. Included contexts for principles such as
categories and image processing.
"""
from flask import render_template, session, flash, request, redirect, Blueprint
from models.products.product import Product
from controllers.database.product import ProductController
from controllers.database.category import CategoryController
2024-01-19 12:37:51 +00:00
from controllers.database.user import UserController
from datetime import datetime
from utils.file_utils import allowed_file
2024-01-22 17:35:49 +00:00
from utils.user_utils import is_role
import os
import uuid
import pathlib
blueprint = Blueprint("products", __name__, url_prefix="/products")
2024-01-21 22:06:06 +00:00
@blueprint.context_processor
def category_list():
""" Places a list of all categories in the products context """
database = CategoryController()
categories = database.read_all()
return dict(categories=categories)
2024-01-21 22:06:06 +00:00
@blueprint.route('/')
def index():
""" The front product page """
# Returning an empty category acts the same
# as a generic home page
return category("")
2024-01-21 22:06:06 +00:00
@blueprint.route('/<string:category>')
def category(category: str):
""" Loads a given categories page """
database = ProductController()
2024-01-21 22:06:06 +00:00
# Check to see if there is a custome search term
search_term = request.args.get("search", type=str)
2024-01-21 22:22:29 +00:00
if search_term is not None:
products = database.read_all(category, search_term)
else:
products = database.read_all(category)
# No Products visible
2024-01-21 22:22:29 +00:00
if products is None:
flash(f"No Products available. Try expanding your search criteria.")
2024-01-21 22:06:06 +00:00
return render_template(
'index.html',
content="content.html",
products=products,
category=category
)
2024-01-21 22:06:06 +00:00
@blueprint.route('/<int:id>')
def id(id: int):
""" Loads a given product based on ID """
db = ProductController()
product = db.read_id(id)
# Check that a valid product was returned
if product is None:
flash(f"No Product available with id {id}")
return redirect("/")
print(product.name)
return render_template(
'index.html',
content='product.html',
product=product
)
2024-01-19 12:37:51 +00:00
@blueprint.route('/add')
def display_add_product():
""" Launches the page to add a new product to the site """
2024-01-19 12:37:51 +00:00
user_id = session.get('user_id')
2024-01-21 22:06:06 +00:00
2024-01-22 17:35:49 +00:00
# User needs to be logged in as a seller to view this page
if not is_role("Seller"):
flash("You must be logged in as a seller to view this page!")
2024-01-23 13:30:18 +00:00
return redirect("/")
2024-01-19 12:37:51 +00:00
return render_template('index.html', content='new_product.html')
@blueprint.post('/add')
def add_product():
""" Server site processing to handle a request to add a
new product to the site
"""
user_id = session.get('user_id')
2024-01-21 22:06:06 +00:00
2024-01-22 17:35:49 +00:00
# User needs to be logged in as a seller to view this page
if not is_role("Seller"):
flash("You must be logged in as a seller to view this page!")
2024-01-23 13:30:18 +00:00
return redirect("/")
file = request.files.get('image')
2024-01-21 22:06:06 +00:00
# Ensure that the correct file type is uploaded
2024-01-21 22:22:29 +00:00
if file is None or not allowed_file(file.filename):
flash("Invalid File Uploaded")
return redirect("/add")
# Create the product object and push to database
filename = str(uuid.uuid4()) + pathlib.Path(file.filename).suffix
file.save(os.path.join('static/assets/img/products/', filename))
product = Product(
request.form.get('name'),
filename,
request.form.get('description'),
request.form.get('cost'),
request.form.get('category'),
user_id,
datetime.now(),
request.form.get('quantity')
)
db = ProductController()
db.create(product)
return redirect('/products/ownproducts')
2024-01-22 17:35:49 +00:00
@blueprint.post('/update/<int:id>')
def update_product(id: int):
""" Processes a request to update a product in place on the site """
# Ensure that the product belongs to the current user
user_id = session.get('user_id')
# User needs to be logged in as a seller to view this page
if not is_role("Seller"):
flash("You must be logged in as a seller to view this page!")
return redirect("/")
db = ProductController()
product = db.read_id(id)
if product.sellerID != user_id:
flash("This product does not belong to you!")
return redirect("/ownproducts")
# Update product details
product.name = request.form.get('name')
product.description = request.form.get('description')
product.category = request.form.get('category')
product.image = request.form.get('image')
product.cost = request.form.get('cost')
product.quantityAvailable = request.form.get('quantity')
db.update(product)
flash("Product successfully updated")
return redirect(f"/{product.id}")
2024-01-22 17:35:49 +00:00
@blueprint.route('/ownproducts')
def display_own_products():
""" Display products owned by the currently logged in seller """
user_id = session.get('user_id')
# User must be logged in as seller to view page
if not is_role("Seller"):
flash("You must be logged in as a seller to view this page!")
2024-01-23 13:30:18 +00:00
return redirect("/")
db = ProductController()
products = db.read_user(user_id)
if products is None:
flash("You don't currently have any products for sale.")
return render_template(
'index.html',
content='content.html',
products=products
)