from flask import Flask, render_template, request, redirect, url_for, flash, jsonify, session import sqlite3 import os from datetime import datetime from werkzeug.security import check_password_hash, generate_password_hash from werkzeug.utils import secure_filename app = Flask(__name__) app.secret_key = "fruit_veg_secret_key" # Create directories def create_directories(): if not os.path.exists('static/images'): os.makedirs('static/images') # Create directories at startup create_directories() # Database initialization def init_db(): conn = sqlite3.connect('fruitsveggies.db') cursor = conn.cursor() # Create admin users table cursor.execute(''' CREATE TABLE IF NOT EXISTS admin_users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE, password TEXT NOT NULL ) ''') cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, email TEXT NOT NULL UNIQUE, phone TEXT NOT NULL UNIQUE, password TEXT NOT NULL ) ''') cursor.execute(''' PRAGMA table_info(users) ''') columns = [column[1] for column in cursor.fetchall()] if 'address' not in columns: cursor.execute(''' ALTER TABLE users ADD COLUMN address TEXT ''') # Check if admin user exists, if not create a default one cursor.execute("SELECT COUNT(*) FROM admin_users") count = cursor.fetchone()[0] if count == 0: # Create default admin user: username 'admin', password 'admin123' hashed_password = generate_password_hash('admin123') cursor.execute("INSERT INTO admin_users (username, password) VALUES (?, ?)", ('admin', hashed_password)) # Create products table cursor.execute(''' CREATE TABLE IF NOT EXISTS products ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, description TEXT NOT NULL, price REAL NOT NULL, image TEXT NOT NULL, category TEXT NOT NULL ) ''') # Create orders table cursor.execute(''' CREATE TABLE IF NOT EXISTS orders ( id INTEGER PRIMARY KEY AUTOINCREMENT, customer_name TEXT NOT NULL, mobile TEXT NOT NULL, address TEXT NOT NULL, payment_method TEXT NOT NULL, order_date TIMESTAMP NOT NULL, product_id INTEGER NOT NULL, quantity INTEGER NOT NULL, FOREIGN KEY (product_id) REFERENCES products (id) ) ''') # Check if products already exist to avoid duplicates cursor.execute("SELECT COUNT(*) FROM products") count = cursor.fetchone()[0] if count == 0: # Vegetables data vegetables = [ ('Carrot', 'Fresh organic carrots rich in vitamin A', 1.99, 'carrot.jpg', 'vegetable'), ('Broccoli', 'Nutritious green broccoli florets', 2.49, 'broccoli.jpg', 'vegetable'), ('Spinach', 'Leafy green spinach packed with iron', 1.79, 'spinach.jpg', 'vegetable'), ('Potato', 'Russet potatoes perfect for baking or mashing', 0.99, 'potato.jpg', 'vegetable'), ('Tomato', 'Ripe red tomatoes grown locally', 1.49, 'tomato.jpg', 'vegetable'), ('Cucumber', 'Crisp cucumbers perfect for salads', 1.29, 'cucumber.jpg', 'vegetable'), ('Bell Pepper', 'Sweet bell peppers in various colors', 1.89, 'bell_pepper.jpg', 'vegetable'), ('Onion', 'Yellow onions for cooking and flavoring', 0.89, 'onion.jpg', 'vegetable'), ('Zucchini', 'Fresh green zucchini for grilling or sautéing', 1.59, 'zucchini.jpg', 'vegetable'), ('Eggplant', 'Large purple eggplants for roasting', 2.29, 'eggplant.jpg', 'vegetable') ] # Fruits data fruits = [ ('Apple', 'Crisp sweet apples from local orchards', 1.29, 'apple.jpg', 'fruit'), ('Banana', 'Ripe yellow bananas rich in potassium', 0.59, 'banana.jpg', 'fruit'), ('Orange', 'Juicy oranges packed with vitamin C', 0.99, 'orange.jpg', 'fruit'), ('Strawberry', 'Sweet red strawberries, locally grown', 3.99, 'strawberry.jpg', 'fruit'), ('Grapes', 'Seedless green grapes in bunches', 2.99, 'grapes.jpg', 'fruit'), ('Watermelon', 'Sweet and refreshing watermelon slices', 4.99, 'watermelon.jpg', 'fruit'), ('Pineapple', 'Tropical sweet pineapple', 3.49, 'pineapple.jpg', 'fruit'), ('Mango', 'Sweet and fragrant mangoes', 1.99, 'mango.jpg', 'fruit'), ('Blueberry', 'Antioxidant-rich blueberries', 4.49, 'blueberry.jpg', 'fruit'), ('Kiwi', 'Tangy green kiwi fruit rich in vitamin C', 0.79, 'kiwi.jpg', 'fruit') ] # Insert vegetables and fruits into products table cursor.executemany("INSERT INTO products (name, description, price, image, category) VALUES (?, ?, ?, ?, ?)", vegetables + fruits) conn.commit() conn.close() # Initialize database on startup init_db() # Routes @app.route('/') def home(): conn = sqlite3.connect('fruitsveggies.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() # Get categories for filter cursor.execute("SELECT DISTINCT category FROM products") categories = [dict(row) for row in cursor.fetchall()] # Get all products (or filtered by category if provided) category = request.args.get('category', None) if category: cursor.execute("SELECT * FROM products WHERE category = ?", (category,)) else: cursor.execute("SELECT * FROM products") products = [dict(row) for row in cursor.fetchall()] conn.close() return render_template('index.html', products=products, categories=categories, selected_category=category) @app.route('/product/') def product_detail(product_id): conn = sqlite3.connect('fruitsveggies.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,)) product = dict(cursor.fetchone()) conn.close() return render_template('product_detail.html', product=product) @app.route('/place_order', methods=['POST']) def place_order(): if request.method == 'POST': try: name = request.form['name'] mobile = request.form['mobile'] address = request.form['address'] payment_method = request.form['payment_method'] product_id = request.form['product_id'] quantity = request.form['quantity'] conn = sqlite3.connect('fruitsveggies.db') cursor = conn.cursor() # Insert the order cursor.execute( "INSERT INTO orders (customer_name, mobile, address, payment_method, order_date, product_id, quantity) VALUES (?, ?, ?, ?, ?, ?, ?)", (name, mobile, address, payment_method, datetime.now(), product_id, quantity) ) conn.commit() conn.close() return redirect(url_for('order_success')) except Exception as e: flash(f"Error placing order: {str(e)}") return redirect(url_for('product_detail', product_id=product_id)) # Admin routes @app.route('/admin', methods=['GET', 'POST']) def admin_login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] conn = sqlite3.connect('fruitsveggies.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute("SELECT * FROM admin_users WHERE username = ?", (username,)) user = cursor.fetchone() conn.close() if user and check_password_hash(user['password'], password): session['admin_logged_in'] = True session['admin_username'] = username return redirect(url_for('admin_dashboard')) else: flash('Invalid credentials') return render_template('admin/login.html') @app.route('/admin/logout') def admin_logout(): session.pop('admin_logged_in', None) session.pop('admin_username', None) return redirect(url_for('admin_login')) def admin_required(f): def decorated_function(*args, **kwargs): if not session.get('admin_logged_in'): return redirect(url_for('admin_login')) return f(*args, **kwargs) decorated_function.__name__ = f.__name__ return decorated_function @app.route('/admin/dashboard') @admin_required def admin_dashboard(): return render_template('admin/dashboard.html') @app.route('/admin/products') @admin_required def admin_products(): conn = sqlite3.connect('fruitsveggies.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute("SELECT * FROM products ORDER BY category, name") products = [dict(row) for row in cursor.fetchall()] conn.close() return render_template('admin/products.html', products=products) @app.route('/admin/add_product', methods=['GET', 'POST']) @admin_required def add_product(): if request.method == 'POST': name = request.form['name'] description = request.form['description'] price = float(request.form['price']) category = request.form['category'] # Handle image upload image = request.files['image'] if image and image.filename: filename = secure_filename(image.filename) image.save(os.path.join('static/images', filename)) else: filename = 'default.jpg' # Default image if none provided conn = sqlite3.connect('fruitsveggies.db') cursor = conn.cursor() cursor.execute( "INSERT INTO products (name, description, price, image, category) VALUES (?, ?, ?, ?, ?)", (name, description, price, filename, category) ) conn.commit() conn.close() flash('Product added successfully') return redirect(url_for('admin_products')) return render_template('admin/add_product.html') @app.route('/admin/edit_product/', methods=['GET', 'POST']) @admin_required def edit_product(product_id): conn = sqlite3.connect('fruitsveggies.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() if request.method == 'POST': name = request.form['name'] description = request.form['description'] price = float(request.form['price']) category = request.form['category'] # Handle image upload image = request.files['image'] if image and image.filename: filename = secure_filename(image.filename) image.save(os.path.join('static/images', filename)) # Update product with new image cursor.execute( "UPDATE products SET name = ?, description = ?, price = ?, image = ?, category = ? WHERE id = ?", (name, description, price, filename, category, product_id) ) else: # Update product without changing image cursor.execute( "UPDATE products SET name = ?, description = ?, price = ?, category = ? WHERE id = ?", (name, description, price, category, product_id) ) conn.commit() flash('Product updated successfully') return redirect(url_for('admin_products')) # Get product for editing cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,)) product = dict(cursor.fetchone()) conn.close() return render_template('admin/edit_product.html', product=product) @app.route('/admin/delete_product/', methods=['POST']) @admin_required def delete_product(product_id): conn = sqlite3.connect('fruitsveggies.db') cursor = conn.cursor() # First get the image filename to delete it from the filesystem cursor.execute("SELECT image FROM products WHERE id = ?", (product_id,)) image = cursor.fetchone()[0] # Delete the product cursor.execute("DELETE FROM products WHERE id = ?", (product_id,)) conn.commit() conn.close() # Delete the image file if it exists and is not a default if image != 'default.jpg': image_path = os.path.join('static/images', image) if os.path.exists(image_path): os.remove(image_path) flash('Product deleted successfully') return redirect(url_for('admin_products')) @app.route('/admin/orders') @admin_required def admin_orders(): conn = sqlite3.connect('fruitsveggies.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute(''' SELECT o.id, o.customer_name, o.mobile, o.address, o.payment_method, o.order_date, o.quantity, p.name AS product_name, p.category, p.price FROM orders o JOIN products p ON o.product_id = p.id ORDER BY o.order_date DESC ''') orders = [] for row in cursor.fetchall(): order = dict(row) # Parse the order_date string into a datetime object order_date_str = order['order_date'] try: # Attempt to parse with microseconds order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S.%f') except ValueError: # Fallback to parsing without microseconds order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S') order['order_date'] = order_date orders.append(order) conn.close() return render_template('admin/orders.html', orders=orders) @app.route('/order_success') def order_success(): return render_template('order_success.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': phone = request.form['phone'] password = request.form['password'] conn = sqlite3.connect('fruitsveggies.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute("SELECT * FROM users WHERE phone = ?", (phone,)) user = cursor.fetchone() conn.close() if user and check_password_hash(user['password'], password): session['user_logged_in'] = True session['user_id'] = user['id'] session['user_name'] = user['name'] flash('Login successful!') return redirect(url_for('home')) else: flash('Invalid phone number or password') return render_template('login.html') @app.route('/signup', methods=['GET', 'POST']) def signup(): if request.method == 'POST': name = request.form['name'] email = request.form['email'] phone = request.form['phone'] password = request.form['password'] confirm_password = request.form['confirm_password'] # Validate passwords match if password != confirm_password: flash('Passwords do not match') return render_template('signup.html') # Hash the password hashed_password = generate_password_hash(password) conn = sqlite3.connect('fruitsveggies.db') cursor = conn.cursor() try: cursor.execute( "INSERT INTO users (name, email, phone, password) VALUES (?, ?, ?, ?)", (name, email, phone, hashed_password) ) conn.commit() flash('Account created successfully! Please login.') return redirect(url_for('login')) except sqlite3.IntegrityError: flash('Email or phone number already exists') finally: conn.close() return render_template('signup.html') @app.route('/logout') def logout(): session.pop('user_logged_in', None) session.pop('user_id', None) session.pop('user_name', None) flash('You have been logged out') return redirect(url_for('home')) @app.route('/profile') def profile(): # Check if user is logged in if not session.get('user_logged_in'): flash('Please login to view your profile') return redirect(url_for('login')) user_id = session.get('user_id') conn = sqlite3.connect('fruitsveggies.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() # Get user info cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) user = dict(cursor.fetchone()) # Get user orders cursor.execute(''' SELECT o.id, o.order_date, o.quantity, p.name AS product_name, p.price FROM orders o JOIN products p ON o.product_id = p.id WHERE o.customer_name = ? ORDER BY o.order_date DESC ''', (user['name'],)) orders = [] for row in cursor.fetchall(): order = dict(row) # Parse the order_date string into a datetime object order_date_str = order['order_date'] try: # Attempt to parse with microseconds order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S.%f') except ValueError: # Fallback to parsing without microseconds order_date = datetime.strptime(order_date_str, '%Y-%m-%d %H:%M:%S') order['order_date'] = order_date orders.append(order) conn.close() return render_template('profile.html', user=user, orders=orders) @app.route('/edit_profile', methods=['GET', 'POST']) def edit_profile(): # Check if user is logged in if not session.get('user_logged_in'): flash('Please login to edit your profile') return redirect(url_for('login')) user_id = session.get('user_id') conn = sqlite3.connect('fruitsveggies.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() # Get user info cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) user = dict(cursor.fetchone()) if request.method == 'POST': name = request.form['name'] email = request.form['email'] phone = request.form['phone'] address = request.form['address'] current_password = request.form['current_password'] new_password = request.form['new_password'] confirm_password = request.form['confirm_password'] # Verify current password if not check_password_hash(user['password'], current_password): flash('Current password is incorrect') return render_template('edit_profile.html', user=user) try: # If new password is provided, update it if new_password: if new_password != confirm_password: flash('New passwords do not match') return render_template('edit_profile.html', user=user) hashed_password = generate_password_hash(new_password) cursor.execute( "UPDATE users SET name = ?, email = ?, phone = ?, address = ?, password = ? WHERE id = ?", (name, email, phone, address, hashed_password, user_id) ) else: # Otherwise just update other fields cursor.execute( "UPDATE users SET name = ?, email = ?, phone = ?, address = ? WHERE id = ?", (name, email, phone, address, user_id) ) conn.commit() session['user_name'] = name # Update session user name flash('Profile updated successfully') return redirect(url_for('profile')) except sqlite3.IntegrityError: flash('Email or phone number already in use') finally: conn.close() conn.close() return render_template('edit_profile.html', user=user) @app.route('/about') def about(): return render_template('about.html') @app.route('/contact') def contact(): return render_template('contact.html') if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)