from flask import request, jsonify, current_app from flask_login import login_required, current_user from app import db from app.models import Restaurant, RestaurantImage from app.utils import upload_file_to_gcs from . import main @main.route('/', methods=['GET']) def index(): return jsonify({'status': 'OK'}) @main.route('/restaurants', methods=['GET']) def get_restaurants(): # Basic search implementation # In real app, use PostGIS or similar for geo-search lat = request.args.get('lat', type=float) lng = request.args.get('lng', type=float) query = Restaurant.query.filter_by(status='approved') # Very basic "nearby" filter (bounding box would be better) if lat and lng: # This is not accurate but a placeholder query = query.filter(Restaurant.latitude.between(lat-0.1, lat+0.1)) query = query.filter(Restaurant.longitude.between(lng-0.1, lng+0.1)) restaurants = query.all() results = [] for r in restaurants: results.append({ 'id': r.id, 'name': r.name, 'address': r.address, 'min_price': r.min_price, 'max_price': r.max_price, 'images': [i.image_url for i in r.images], 'user_rating': r.user_rating }) return jsonify(results) @main.route('/restaurants', methods=['POST']) @login_required def create_restaurant(): # Handle multipart/form-data for images data = request.form # Check probation if current_user.is_probation: status = 'pending' else: status = 'approved' restaurant = Restaurant( name=data['name'], address=data['address'], latitude=data.get('latitude'), longitude=data.get('longitude'), google_place_id=data.get('google_place_id'), min_price=data.get('min_price'), max_price=data.get('max_price'), single_price=data.get('single_price') == 'true', drink_included=data.get('drink_included') == 'true', options_count=data.get('options_count'), user_rating=data.get('user_rating'), user_description=data.get('user_description'), status=status, user_id=current_user.id ) db.session.add(restaurant) db.session.commit() # Handle images images = request.files.getlist('images') bucket_name = current_app.config.get('GCS_BUCKET_NAME') for img in images[:5]: # Limit to 5 if img and bucket_name: try: url = upload_file_to_gcs(img, bucket_name) img_obj = RestaurantImage(image_url=url, restaurant_id=restaurant.id) db.session.add(img_obj) except Exception as e: print(f"Error uploading image: {e}") db.session.commit() return jsonify({'message': 'Restaurant created', 'id': restaurant.id, 'status': status}), 201 @main.route('/restaurants/', methods=['GET']) def get_restaurant(id): r = Restaurant.query.get_or_404(id) return jsonify({ 'id': r.id, 'name': r.name, 'address': r.address, 'min_price': r.min_price, 'max_price': r.max_price, 'single_price': r.single_price, 'drink_included': r.drink_included, 'options_count': r.options_count, 'user_rating': r.user_rating, 'user_description': r.user_description, 'images': [i.image_url for i in r.images], 'author': r.author.username })