diff --git a/backend/product.py b/backend/product.py index 17422de2991a663bdbd3e1ed4f74d1e5a2604b13..421f475c0f7bc1d0aa283c33c6be61cdb75ee333 100644 --- a/backend/product.py +++ b/backend/product.py @@ -60,6 +60,64 @@ def get_products(product_id): cursor.close() conn.close() +@product_bp.route('/products/category/<string:category_name>', methods=['GET']) +def get_products_by_category(category_name): + conn = db_connection() + cursor = conn.cursor(dictionary=True) + try: + cursor.execute(""" + SELECT p.*, b.Name as BrandName, c.Name as CategoryName + FROM Product p + JOIN Category c ON p.CategoryID = c.CategoryID + JOIN Brand b ON p.BrandID = b.BrandID + WHERE c.Name = %s""", (category_name,)) + products = cursor.fetchall() + return jsonify(products), 200 + except Exception as e: + print(e) + return jsonify({'error': 'Database connection failed'}), 500 + finally: + cursor.close() + conn.close() + +# New route for searching products by name or brand +@product_bp.route('/products/search', methods=['GET']) +def search_products(): + search_query = request.args.get('query', default="", type=str).strip() + selected_brand = request.args.get('brand', default="All Brands", type=str).strip() + + if not search_query and selected_brand == "All Brands": + return jsonify({'message': 'No search criteria provided'}), 400 + + conn = db_connection() + if not conn: + return jsonify({'error': 'Database connection failed'}), 500 + + cursor = conn.cursor(dictionary=True) + try: + sql_query = """ + SELECT p.*, b.Name AS BrandName, c.Name AS CategoryName + FROM Product p + JOIN Brand b ON p.BrandID = b.BrandID + JOIN Category c ON p.CategoryID = c.CategoryID + WHERE (p.Name LIKE %s OR b.Name LIKE %s) + """ + sql_params = ['%' + search_query + '%', '%' + search_query + '%'] + + # Filter by selected brand if not 'All Brands' + if selected_brand != "All Brands": + sql_query += " AND b.Name = %s" + sql_params.append(selected_brand) + + cursor.execute(sql_query, sql_params) + products = cursor.fetchall() + return jsonify(products), 200 + except Exception as e: + return jsonify({'error': 'Error processing your request', 'details': str(e)}), 500 + finally: + cursor.close() + conn.close() + @product_bp.route('/products/<int:product_id>', methods=['PUT']) def update_product(product_id): data = request.json