""" The user controller to manage all of the stats related endpoints in the web app """ from flask import Blueprint from flask import render_template, request, flash, session, redirect from controllers.database.stats import StatsController from controllers.database.product import ProductController from controllers.database.category import CategoryController from controllers.web.product import is_role from datetime import datetime import random # Blueprint to append user endpoints to blueprint = Blueprint("stats", __name__, url_prefix='/stats') @blueprint.route('/') def index(): """ Main page to view all of the statistics for the site """ db = StatsController() data = db.read() test = list(map(lambda d: d.productID, data)) return render_template("index.html", content="stats.html", data=test) @blueprint.route('/products/') def view_product_stats(id: int): """ Page to view statistics for a given product """ # Check user is seller if not is_role("Seller"): flash("You must be logged in as a seller to view this page!", "error") return redirect("/") db = ProductController() product = db.read_id(id) # Check user owns this product if product is None or product.sellerID is not session.get("user_id"): flash("This product does not belong to you!", "error") return redirect("/products/ownproducts") db = StatsController() prev_days: int = request.args.get('prev_days', 7, int) data = db.read_days(id, prev_days) # Recent Views product_view_frequency_data = dict(map( lambda k, v: (k, random.randint(70, 100)), # lambda k, v: (k, len(v)), data.keys(), data.values() )) # Total Views total_views = db.read_product_views(id) # Ranking in category ranking = db.read_ranking(id) # Category name db = CategoryController() category = db.read(product.category).name data = { "age": datetime.now() - product.postedDate, "ranking": ranking, "category": category, "views": { "total": total_views, "headings": list(reversed(product_view_frequency_data.keys())), "data": list(reversed(product_view_frequency_data.values())) }, "stocklevel": product.quantityAvailable } return render_template( "index.html", content="stats.html", data=data )