Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified __pycache__/services.cpython-311.pyc
Binary file not shown.
146 changes: 137 additions & 9 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,63 @@
from datetime import timedelta
import os
from dotenv import load_dotenv
from flask_cors import CORS # Import CORS

load_dotenv()
app = Flask(__name__)
# Enable CORS with specific settings
CORS(app, resources={r"/*": {"origins": "*", "allow_headers": ["Content-Type", "Accept"], "methods": ["GET", "POST", "OPTIONS"]}})

# Handle OPTIONS requests explicitly
@app.route('/', defaults={'path': ''}, methods=['OPTIONS'])
@app.route('/<path:path>', methods=['OPTIONS'])
def handle_options(path):
response = make_response()
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Accept')
response.headers.add('Access-Control-Allow-Methods', 'GET,POST,OPTIONS')
return response

CORS(app)

# Fetch or create user by ID
@app.route('/users/fetch/<user_id>', methods=['POST'])
def fetch_user(user_id):
try:
# Check if user exists
user_doc = db.collection('users').document(user_id).get()

if user_doc.exists:
# User exists, return user data
user_data = user_doc.to_dict()
return jsonify({"success": True, "data": user_data, "existing": True})
else:
# User doesn't exist, create new user
data = request.get_json() or {}

# Check required fields for new user
if 'userEmail' not in data or 'userName' not in data:
return jsonify({"success": False, "error": "Missing required fields for new user: userEmail and userName"}), 400

# Create user document in Firestore
user_ref = db.collection('users').document(user_id)

# Set user data
user_data = {
"userId": user_id,
"userEmail": data['userEmail'],
"userName": data['userName'],
"numRecipe": 0,
"streak": 0
# Add other default fields as needed
}

user_ref.set(user_data)

return jsonify({"success": True, "data": user_data, "existing": False}), 201
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500

@app.route('/extract-text', methods=['POST'])
def extract_text_endpoint():
if 'file' not in request.files:
Expand Down Expand Up @@ -113,6 +164,20 @@ def create_recipe():
if not data or 'dishName' not in data or 'ingredients' not in data or 'recipeSteps' not in data or 'userId' not in data:
return jsonify({"success": False, "error": "Missing required fields: dishName, ingredients, recipeSteps, and userId"}), 400

# Validate route field if provided
route = data.get('route', 'original') # Default to 'original' if not provided
valid_routes = ['original', 'local', 'sustainable']
if route not in valid_routes:
return jsonify({"success": False, "error": f"Invalid route value. Must be one of: {', '.join(valid_routes)}"}), 400

user_id = data['userId']
# Check if user exists
user_ref = db.collection('users').document(user_id)
user_doc = user_ref.get()

if not user_doc.exists:
return jsonify({"success": False, "error": f"User with ID {user_id} does not exist. Please create the user first."}), 404

# Create recipe document in Firestore
recipe_ref = db.collection('recipes').document()

Expand All @@ -122,6 +187,7 @@ def create_recipe():
"ingredients": data['ingredients'],
"recipeSteps": data['recipeSteps'],
"userId": data['userId'],
"route": route, # Add the route field
}

# Add timestamp in Firestore but don't include in response
Expand All @@ -130,13 +196,9 @@ def create_recipe():
recipe_ref.set(firestore_data)

# Update user's recipe count
user_ref = db.collection('users').document(data['userId'])
user_doc = user_ref.get()

if user_doc.exists:
user_data = user_doc.to_dict()
current_count = user_data.get('numRecipe', 0)
user_ref.update({"numRecipe": current_count + 1})
user_data = user_doc.to_dict()
current_count = user_data.get('numRecipe', 0)
user_ref.update({"numRecipe": current_count + 1})

return jsonify({"success": True, "data": recipe_data, "id": recipe_ref.id}), 201
except Exception as e:
Expand All @@ -147,10 +209,14 @@ def create_recipe():
def get_recipes_by_user(user_id):
try:
# Query recipes collection where userId matches
recipes_query = db.collection('recipes').where('userId', '==', user_id).stream()
recipes_query = db.collection('recipes').where('userId', '==', user_id)


# Execute query
recipes_results = recipes_query.stream()

recipes = []
for doc in recipes_query:
for doc in recipes_results:
recipe_data = doc.to_dict()
recipe_data['id'] = doc.id
recipes.append(recipe_data)
Expand All @@ -159,5 +225,67 @@ def get_recipes_by_user(user_id):
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500

# Get a user's most common recipe route
@app.route('/users/<user_id>/most-common-route', methods=['GET'])
def get_most_common_route(user_id):
try:
# Check if user exists
user_doc = db.collection('users').document(user_id).get()

if not user_doc.exists:
return jsonify({"success": False, "error": f"User with ID {user_id} does not exist"}), 404

# Query recipes collection where userId matches
recipes_query = db.collection('recipes').where('userId', '==', user_id).stream()

# Count occurrences of each route
route_counts = {
'original': 0,
'local': 0,
'sustainable': 0
}

total_recipes = 0
for doc in recipes_query:
recipe_data = doc.to_dict()
route = recipe_data.get('route', 'original')
if route in route_counts:
route_counts[route] += 1
total_recipes += 1

if total_recipes == 0:
# No recipes found, default to 'original'
most_common_route = 'original'
most_common_count = 0
else:
# Find the route with the highest count
most_common_route = 'original' # Default in case of tie
most_common_count = 0

for route, count in route_counts.items():
if count > most_common_count:
most_common_route = route
most_common_count = count

# Calculate percentage if there are recipes
percentage = (most_common_count / total_recipes * 100) if total_recipes > 0 else 0

return jsonify({
"success": True,
"data": {
"userId": user_id,
"mostCommonRoute": most_common_route,
"count": most_common_count,
"totalRecipes": total_recipes,
"percentage": round(percentage, 2),
"routeCounts": route_counts
}
})

except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500



if __name__ == "__main__":
app.run(debug=True)
Loading