from flask import Blueprint, render_template, request, redirect, url_for, flash from models import Product, Node user_bp = Blueprint('user', __name__) @user_bp.route('/') def home(): products = Product.query.all() return render_template('home.html', products=products) @user_bp.route('/product/') def product_detail(product_id): product = Product.query.get_or_404(product_id) # If the product has a root node, redirect directly to the decision tree if product.root_node: return redirect(url_for('user.decision_node', product_id=product.id, node_id=product.root_node_id)) # Otherwise, show the product detail page with a message flash("This product doesn't have a decision tree yet.", "warning") return render_template('product_detail.html', product=product) # New route for starting the decision tree @user_bp.route('/product//start') def start_decision_tree(product_id): product = Product.query.get_or_404(product_id) if not product.root_node: flash("This product doesn't have a decision tree yet.", "warning") return redirect(url_for('user.product_detail', product_id=product_id)) return redirect(url_for('user.decision_node', product_id=product_id, node_id=product.root_node_id)) @user_bp.route('/product//node/') def decision_node(product_id, node_id): product = Product.query.get_or_404(product_id) node = Node.query.get_or_404(node_id) # Verify that this node belongs to the product's decision tree if not is_node_in_product_tree(product, node): flash("This node does not belong to the selected product.", "danger") return redirect(url_for('user.product_detail', product_id=product_id)) return render_template('decision_tree.html', product=product, current_node=node) # Backward compatibility route - redirects old URLs to new format @user_bp.route('/node/') def legacy_node_redirect(node_id): node = Node.query.get_or_404(node_id) # Find which product this node belongs to for product in Product.query.all(): if is_node_in_product_tree(product, node): return redirect(url_for('user.decision_node', product_id=product.id, node_id=node.id)) # If we can't find the product, redirect to home flash("Could not determine which product this node belongs to.", "warning") return redirect(url_for('user.home')) # Helper function to check if a node belongs to a product's decision tree def is_node_in_product_tree(product, node): if not product.root_node: return False # Check if this is the root node if product.root_node_id == node.id: return True # Otherwise, traverse the tree return is_node_in_tree(product.root_node, node.id) # Helper function to check if a node is in a tree def is_node_in_tree(root, node_id): if not root: return False if root.id == node_id: return True # Check yes branch if root.yes_node_id and is_node_in_tree(root.yes_node, node_id): return True # Check no branch if root.no_node_id and is_node_in_tree(root.no_node, node_id): return True return False