from flask import Flask, render_template, request, jsonify, session from pymongo import MongoClient import random import string app = Flask(__name__) MONGO_URI_RO = 'mongodb://localhost:27017/hardware' app.secret_key = 'test' # mongoimport --db hardware --collection product_thinkmate --file db.json --jsonArray def init_mongo(): client = MongoClient(MONGO_URI_RO) return client['hardware'] @app.route('/', methods=['GET']) def home(): hardware = init_mongo() categories = list(hardware['product_thinkmate'].find({})) return render_template('base_website.html', categories=categories) @app.route('/index', methods=['POST']) def index(): hardware = init_mongo() categories = list(hardware['product_thinkmate'].find({})) return render_template('index.html', categories=categories) @app.route('/servers', methods=['POST']) def servers(): hardware = init_mongo() servers = list(hardware['product_thinkmate'].find({'type': 'server'})) return render_template('servers.html', servers=servers) @app.route('/servers/', methods=['POST']) def category(category): hardware = init_mongo() server_category = hardware['product_thinkmate'].find_one({'type': 'server', 'category': category}) server_details = server_category.get('server_details', '') server_highlights_detail = server_category.get('server_highlights_detail', '') products = server_category.get('products', '') details_list = [phrase.strip() for phrase in server_details.split('||')] return render_template('category.html', server_category=server_category, details_list=details_list, server_highlights_detail=server_highlights_detail, products=products) @app.route('/product//', methods=['POST']) def product(category, product_name): session.clear() product_id = request.args.get('product_id') hardware = init_mongo() category_data = hardware['product_thinkmate'].find_one({'category': category}) saved_selections = session.get('config_selections', {}).get(product_name, {}) product = None config_data = None if category_data and 'products' in category_data: for item in category_data['products']: if item.get('product_name') == product_name: product = item config_data = item.get('product_data', {}).get('config', [])[0] break return render_template('product.html', product=product, category_data=category_data, config_data=config_data, saved_selections=saved_selections) @app.route('/configurator///', methods=['POST']) def config(category, product_name, config_category): product_id = request.args.get('product_id') hardware = init_mongo() category_data = hardware['product_thinkmate'].find_one({'category': category}) saved_selections = session.get('config_selections', {}).get(product_name, {}) product = None config_data = None if category_data and 'products' in category_data: for item in category_data['products']: if item.get('product_name') == product_name: product = item config_data = item.get('product_data', {}).get('config', []) for config in config_data: if config.get('category', {}).get('name') == config_category: config_data = config break break return render_template('config.html', product=product, category_data=category_data, config_data=config_data, config_category=config_category, saved_selections=saved_selections) @app.route('/save_config_selection', methods=['POST']) def save_config_selection(): data = request.form product_name = data.get('product_name') category = data.get('category') max_quantity_str = data.get('max_quantity', None) try: max_quantity = int(max_quantity_str) if max_quantity_str and max_quantity_str.isdigit() else None except ValueError: max_quantity = None sub_category = data.get('sub_category') config_choice_type = data.get('config_choice_type') new_category_data = {"max_quantity": max_quantity} config_keys = [key for key in data.keys() if key.startswith('config-')] if config_choice_type != 'radio' and max_quantity and len(config_keys) > max_quantity: return jsonify({ 'message': f'Cannot select more than {max_quantity} options for {category}.', 'status': 'ko' }) if config_keys: if config_choice_type == 'radio': for key, value in data.items(): if key.startswith('config-'): new_category_data["selection"] = value break else: new_category_data["subcategories"] = {} for key, value in data.items(): if key.startswith('config-'): parts = key.split('-') subcategory = parts[3] if len(parts) >= 4 else category new_category_data["subcategories"].setdefault(subcategory, []).append(value) else: if config_choice_type == 'radio': new_category_data["selection"] = None else: new_category_data["subcategories"] = {sub_category or category: []} config_selections = session.get('config_selections', {}) config_selections.setdefault(product_name, {})[category] = new_category_data # Cleanup logic if config_choice_type != 'radio': subcats = config_selections[product_name][category].get("subcategories", {}) subcats = {k: v for k, v in subcats.items() if v} if not subcats: config_selections[product_name].pop(category, None) elif not config_selections[product_name][category].get("selection"): config_selections[product_name].pop(category, None) if not config_selections[product_name]: config_selections.pop(product_name) session['config_selections'] = config_selections return jsonify(config_selections.get(product_name, {})) @app.route('/show_order', methods=['POST']) def show_order(): config_selection = session.get('config_selections', {}) return render_template('order.html', config_selection=config_selection, no_order_message='No orders found in the session.') def sanitize_keys(data): if isinstance(data, dict): return {k.replace('.', '_'): sanitize_keys(v) for k, v in data.items()} elif isinstance(data, list): return [sanitize_keys(i) for i in data] return data @app.route('/confirm_order', methods=['POST']) def confirm_order(): order = sanitize_keys(session.get('config_selections', {})) hardware = init_mongo() if not order: return 'No orders found in the session.' if 'order' not in hardware.list_collection_names(): hardware.create_collection('order') order_id = ''.join(random.choices(string.ascii_letters + string.digits, k=5)) details = [] for product_name, categories in order.items(): for category_name, category_data in categories.items(): details.append({ "category": category_name, "selection": category_data.get("selection"), "subcategories": category_data.get("subcategories", {}) }) hardware['order'].insert_one({ 'order_id': order_id, 'product_name': product_name, 'details': details, 'status': 'confirmed' }) session.clear() return ' Order confirmed successfully!' if __name__ == '__main__': app.run(debug=True)