diff --git a/app/models/recipe.py b/app/models/recipe.py index b35a921..667073f 100644 --- a/app/models/recipe.py +++ b/app/models/recipe.py @@ -2,7 +2,6 @@ from datetime import datetime import uuid from sqlalchemy.dialects.postgresql import UUID -from sqlalchemy import inspect class Recipe(db.Model): @@ -22,14 +21,13 @@ class Recipe(db.Model): user_id = db.Column(UUID(as_uuid=True), db.ForeignKey( 'user.id'), nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow) - updated_at = db.Column( - db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) + updated_at = db.Column(db.DateTime, default=datetime.utcnow) category = db.relationship('Category', backref='recipes', lazy=True) - comments = db.relationship('Comment', backref='recipe', lazy=True) + comments = db.relationship('Comment', backref='recipe', cascade='all, delete-orphan', lazy=True) ingredients = db.relationship( - 'Ingredient', backref='recipe', lazy='dynamic') + 'Ingredient', backref='recipe', cascade='all, delete-orphan', lazy='dynamic') instructions = db.relationship( - 'Instruction', backref='recipes', lazy='dynamic') + 'Instruction', backref='recipes', cascade='all, delete-orphan', lazy='dynamic') def __repr__(self): return f'' @@ -37,4 +35,5 @@ def __repr__(self): def increment_view_count(self): """Increment the view count without updating the updated_at timestamp.""" self.view_count += 1 + db.session.commit() # No commit or onupdate manipulation here diff --git a/app/routes/recipe_routes.py b/app/routes/recipe_routes.py index 9d664ff..df7bf8e 100644 --- a/app/routes/recipe_routes.py +++ b/app/routes/recipe_routes.py @@ -1,6 +1,6 @@ from flask import Blueprint, request, url_for, render_template, flash, redirect from app import db -from app.services.recipe_service import get_all_recipes, get_recipe_by_id, create_recipe, get_most_viewed_recipes, update_recipe, delete_recipe, get_recipe_with_details +from app.services.recipe_service import get_all_recipes, get_recipe_by_id, create_recipe, get_most_viewed_recipes, update_recipe, delete_recipe, get_recipe_with_details, get_quick_and_easy_recipe from app.services.validation_service import validate_recipe_data from app.services.category_service import CategoryService from app.services.image_service import upload_image_to_s3, delete_image_from_s3 @@ -66,6 +66,8 @@ def list_recipes(): page = int(request.args.get('page', 1)) per_page = int(request.args.get('per_page', 9)) paginated_recipes = get_all_recipes(page, per_page) + most_viewed_recipes = get_most_viewed_recipes(limit=3) + quick_recipes = get_quick_and_easy_recipe(limit=3) # Fetch user details for each recipe for recipe in paginated_recipes['items']: @@ -76,6 +78,8 @@ def list_recipes(): total_pages=paginated_recipes['total_pages'], current_page=paginated_recipes['current_page'], per_page=per_page, + most_viewed=most_viewed_recipes, + quick_recipes=quick_recipes, title='Recipes | SpiceShare Inc.') @@ -89,11 +93,14 @@ def view_recipe(recipe_id): comment.user = db.session.query(User).filter_by(id=comment.user_id).first() # Get the user who made the comment if recipe: - recipe.increment_view_count() # Increment view count without committing + if current_user.is_authenticated: + if current_user.id != recipe.user_id: + recipe.increment_view_count() # Increment view count if the viewer is not the author + else: + # If anonymous, increment view count + recipe.increment_view_count() recipe.user = db.session.query(User).filter_by(id=recipe.user_id).first() - - # Commit all changes here - db.session.commit() # Commit after all changes are made + return render_template('recipes/readPages/recipe_detail.html', recipe=recipe, ingredients=ingredients, instructions=instructions, comments=comments, title=f'{recipe.title} - SpiceShare Inc.') else: flash("Recipe not found.", "error") @@ -166,11 +173,11 @@ def remove_recipe(recipe_id): if delete_image_from_s3(recipe.image_url): flash("Image deleted", 'success') else: - flash("Failed to delet Image", 'info') + flash("Failed to delete Image", 'info') delete_recipe(recipe) flash("Recipe deleted successfully!", 'info') - return redirect(url_for('recipe_routes.recipe_list')) + return redirect(url_for('recipe_routes.list_recipes')) except Exception as e: flash( diff --git a/app/routes/user_routes.py b/app/routes/user_routes.py index 5a324d6..bb7e16f 100644 --- a/app/routes/user_routes.py +++ b/app/routes/user_routes.py @@ -76,7 +76,6 @@ def edit_user(user_id): user = get_user_by_id(str(user_id)) if current_user.id != user.id: - print(current_user.id) flash('You are not authorized to edit this profile', 'error') return redirect(url_for('user_routes.user_profile', user_id=current_user.id)) diff --git a/app/services/pagination_service.py b/app/services/pagination_service.py index 612cc82..3624f74 100644 --- a/app/services/pagination_service.py +++ b/app/services/pagination_service.py @@ -12,15 +12,17 @@ def paginate(items, page, per_page): dict: A dictionary containing paginated items and pagination info. """ + # Ensure page is at least 1 if page < 1: - raise ValueError("Page number must be 1 or greater.") + page = 1 total_items = len(items) total_pages = ceil(total_items / per_page) + # Adjust page if it exceeds total pages if page > total_pages: - raise ValueError("Page number exceeds total pages") - + page = total_pages + start = (page - 1) * per_page end = start + per_page paginated_items = items[start:end] diff --git a/app/services/recipe_service.py b/app/services/recipe_service.py index e25d023..88e34cc 100644 --- a/app/services/recipe_service.py +++ b/app/services/recipe_service.py @@ -6,6 +6,7 @@ from app.models.instruction import Instruction from app import db import random +from datetime import datetime from app.services.pagination_service import paginate @@ -141,6 +142,9 @@ def update_recipe(recipe, data, ingredients, instructions, image_url): # Remove any extra instructions not submitted in the form for extra_idx in range(len(instructions) + 1, len(existing_instructions) + 1): db.session.delete(existing_instructions[extra_idx]) + + # Manually updating the `updated_at` field 'cos of view_count + recipe.updated_at = datetime.utcnow() db.session.commit() @@ -191,3 +195,10 @@ def get_recipes_by_user(user_id, page=1, per_page=9): """Fetch recipes created by a specific user with pagination.""" recipes = Recipe.query.filter_by(user_id=user_id).all() return paginate(recipes, page, per_page) + +def get_quick_and_easy_recipe(limit=5): + """Fetch quick and easy recipes based on prep and cook time.""" + return Recipe.query.filter( + (Recipe.prep_time + Recipe.cook_time) <= 30 # Total time should be 30 minutes or less + ).order_by(Recipe.updated_at.desc()).limit(limit).all() +