Add quote bridge and quote handoff flow

This commit is contained in:
2026-06-29 18:41:45 -05:00
parent be1475dd8e
commit a329168765
17 changed files with 1707 additions and 509 deletions
+4 -24
View File
@@ -1,29 +1,9 @@
# Required Code Changes for Conditional Navigation
# Conditional Navigation and Filtering Status
## Overview
To support conditional material/color questions and dynamic navigation, the following changes are needed in your application code.
## Purpose
---
## 1. JavaScript Changes (`js/script.js`)
### Current State
- Loads `questions.json` statically
- Has hardcoded conditional for `q-material-conditional`
- No product data loading
### Required Changes
#### A. Load Multiple Data Files
```javascript
// At the top of script.js - modify loadQuestionData() to load both files
let questionData = {};
let productData = [];
let accessoryData = [];
let bitwiseData = {};
let accumulatedBitValue = 0;
function init() {
This document records what was originally proposed for conditional question flow,
what is already implemented, and what still remains.
// Load all data files
Promise.all([
fetch('data/navigation.json').then(r => r.json()),
+88 -155
View File
@@ -1,184 +1,117 @@
# 🎉 Flask Web Application Successfully Created!
# Product Finder Project
Your HTML/JavaScript quiz has been converted to a Python Flask web application.
## What This Project Is
## ✅ What Was Created
This repository contains a Flask-based Product Finder application used to guide users
through product selection and provide product detail, accessory, search, and admin
workflows.
### Core Application Files
- **app.py** - Main Flask application with routes
- **wsgi.py** - Production WSGI entry point
- **config.py** - Configuration management
- **requirements.txt** - Python dependencies
The current application is no longer a simple Flask conversion of a static quiz.
It now includes:
- modular blueprints
- login and session management
- location-aware access
- product management APIs
- shareable quiz URLs
- layered image preview support
- an optional SQLite backend
### Templates & Static Files
- **templates/** - HTML files (index.html, index2.html, 404.html)
- **css/** - Stylesheets (styles.css)
- **js/** - JavaScript files (script.js)
- **images/** - Product images folder
## Fastest Way To Run It
### Documentation & Utilities
- **README.md** - Complete documentation
- **QUICKSTART.md** - Quick start guide
- **run.bat** - Windows startup script
- **.gitignore** - Git ignore file
- **.env.example** - Environment template
From the repository root:
## 🚀 Quick Start
### Option 1: Using Batch File (Windows)
Double-click `run.bat` to install dependencies and start the server.
### Option 2: Manual Start
```bash
# Install dependencies
pip install -r requirements.txt
# Run the application
python app.py
cd app
../.venv/bin/python app.py
```
### Access Your Application
Open in browser: **http://localhost:8080/quiz**
Then open:
- `http://127.0.0.1:8080/`
- `http://127.0.0.1:8080/quiz/`
## 🌐 Current Status
## Recommended VS Code Tasks
✅ Flask is currently running on: http://localhost:8080
✅ Quiz page: http://localhost:8080/quiz
✅ Debug mode: Enabled (auto-reloads on file changes)
Use the built-in tasks from the repository root:
## 📁 Project Structure
- `Start Flask Server`
- `Process All Data`
- `Update Data Files from CSV`
- `Generate Bitwise Data`
```
project/
├── app.py ← Main Flask app (START HERE)
├── wsgi.py ← For production deployment
├── config.py ← Settings & configuration
├── requirements.txt ← Python packages needed
├── run.bat ← Windows startup script
├── templates/ ← HTML files (Flask requires this folder)
│ ├── index.html ← Main landing page
│ ├── index2.html ← Quiz page
│ └── 404.html ← Error page
├── css/ ← Stylesheets
│ └── styles.css ← Main CSS file
├── js/ ← JavaScript files
│ └── script.js ← Quiz logic and data
└── images/ ← Product images (add your images here)
```
`Process All Data` runs the two data-generation steps in sequence.
## 🎯 Key Features
## Main Application Areas
**Dynamic Routing** - Flask handles all page requests
**Static File Serving** - CSS, JS, and images properly served
**Error Handling** - Custom 404 page
**API Endpoints** - Ready for future backend features
**Production Ready** - WSGI config included
**All Original Features** - Quiz, forms, conditional logic, memory storage
### Authentication
- login page
- logout
- session info endpoint
- location selection for multi-location users
## 🔧 Customization
### Product Finder
- guided quiz flow at `/quiz/`
- advanced search page
- product list page
- product manager page
- direct product links at `/quiz/product/<product_code>`
### Change Port
Edit `app.py`, line with `app.run()`:
```python
app.run(debug=True, host='0.0.0.0', port=YOUR_PORT)
```
### Images and Previews
- flat product images
- layered image previews
- Canvas API fallback routes for hierarchical image lookup
- layer transforms for mirrored door/hardware previews where configured
### Add New Routes
In `app.py`:
```python
@app.route('/your-page')
def your_page():
return render_template('your-page.html')
```
### Data Layer
- JSON is the default runtime backend
- SQLite support exists behind a config flag
- frontend quiz data is driven by JSON files in `app/data/`
### Update Quiz Questions
Edit `js/script.js` - modify the `questionData` object
## Important Files
### Change Styling
Edit `css/styles.css`
- `app/app.py` - application entry point
- `app/blueprints/auth.py` - authentication/session logic
- `app/blueprints/users.py` - user management routes
- `app/blueprints/products.py` - quiz pages, product APIs, admin pages
- `app/blueprints/canvas.py` - Canvas API image routes
- `app/static/js/script.js` - quiz flow, URL state, search, previews
- `app/data/navigation.json` - quiz navigation structure
- `app/data/products.json` - product catalog data
- `app/data/accessories.json` - accessory data
- `app/data/product_bitwise.json` - bitwise lookup data
## 📦 Deployment Options
## Current Known Status
### 1. Web Panels (cPanel, Plesk)
- Upload all files
- Install requirements: `pip install -r requirements.txt`
- Point to `wsgi.py`
Implemented:
- modular Flask app structure
- login/session flow
- location-aware permissions
- user management
- product CRUD/search APIs
- quiz result filtering
- shareable URL state
- product deep links
- Canvas API image fallback system
### 2. Cloud Platforms
- **Heroku**: Add `Procfile` and push to Git
- **PythonAnywhere**: Upload and configure WSGI
- **AWS/Azure**: Use with Gunicorn
Still incomplete:
- fully generic conditional question skipping based on navigation metadata
- automated tests
- decision on whether SQLite should become the default backend
### 3. Docker
See README.md for Dockerfile example
## If You Are Updating Product Data
### 4. Production Server
```bash
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8080 wsgi:app
```
1. Update the source CSV used by the data-generation scripts.
2. Run `Process All Data`.
3. Restart the Flask server if needed.
4. Verify quiz results and product detail views.
## 🐛 Troubleshooting
## If You Are Picking Up Development
### Port Already in Use
Change port in app.py or kill the process:
```bash
# Windows
netstat -ano | findstr :8080
taskkill /PID <PID> /F
```
Start with these files:
### Templates Not Found
Make sure HTML files are in `templates/` folder
1. `app/app.py`
2. `app/blueprints/products.py`
3. `app/static/js/script.js`
4. `app/data/navigation.json`
5. `app/config.py`
### Static Files Not Loading
Check that `css/` and `js/` folders exist in root directory
### Module Not Found
```bash
pip install -r requirements.txt
```
## 📚 Next Steps
1. **Test the application** - Visit http://localhost:8080/quiz
2. **Add your product images** - Place images in `images/` folder
3. **Customize the quiz** - Edit `js/script.js`
4. **Update styling** - Modify `css/styles.css`
5. **Deploy** - Follow README.md deployment guide
## 🔒 Security Notes for Production
Before deploying to production:
- [ ] Set `DEBUG = False` in config.py
- [ ] Change `SECRET_KEY` to a strong random value
- [ ] Use environment variables for sensitive data
- [ ] Set up HTTPS/SSL
- [ ] Use a production WSGI server (Gunicorn, uWSGI)
- [ ] Configure proper logging
- [ ] Set up database backups (if using a database)
## 💡 Tips
- Flask auto-reloads when you edit files (in debug mode)
- Press `Ctrl+C` to stop the server
- Check terminal for error messages
- Use browser DevTools to debug JavaScript
- All original quiz functionality is preserved
## 📞 Need Help?
- Check **README.md** for detailed documentation
- Check **QUICKSTART.md** for simple instructions
- Review Flask logs in terminal for errors
- Test API endpoints using browser or Postman
---
**Your Flask app is ready to use! 🎊**
Visit: http://localhost:8080/quiz
Those files define the main routing, quiz behavior, and backend mode.
+70 -206
View File
@@ -1,230 +1,94 @@
# Implementation Summary - URL State Management
# URL State Management
## 🎯 What You Get
## Current Status
Your application will support **shareable URLs** that preserve:
- ✅ User's navigation progress (bitwise value)
- ✅ Current question position
- ✅ Direct product links
- ✅ Browser refresh without data loss
- ✅ Browser back/forward buttons
- ✅ Copy/share functionality
URL state management is implemented in the current frontend.
## 🔗 URL Examples
The quiz now supports:
- Shareable URLs for in-progress quiz state
- Direct links to product detail views
- Browser refresh without losing the current route context
- Browser back/forward support
- Share buttons on results and product-detail views
```
# Initial state (no params)
https://yoursite.com/
## Current URL Parameters
# After selecting Door + Storm Door + Aluminum
https://yoursite.com/?b=16401&q=q-dimensions
↑ ↑
| Current question
Accumulated bit value (Door + Aluminum + Storm Door)
- `b` - accumulated bitwise state for the user selections
- `q` - current question key or `results`
- `p` - product code for direct product-detail views
# Viewing specific product
https://yoursite.com/?p=BGIST&b=16401
Product code
Examples:
# Bit value 16401 decodes to:
# Bit 0 (1) = Door
# Bit 4 (16) = Aluminum
# Bit 14 (16384) = Storm Door subtype
# Total: 1 + 16 + 16384 = 16401
```text
/quiz/?b=16401&q=results
/quiz/?p=404&b=16401
/quiz/product/404
```
## 📋 Implementation Checklist
## What Is Implemented
### Phase 1: Core URL Functionality (Essential)
- [ ] Add bitwise data loading to `init()` function
- [ ] Add `accumulatedBitValue` variable
- [ ] Add `BIT_DEFINITIONS` constants
- [ ] Implement `updateURL()` function
- [ ] Implement `updateBitValue()` function
- [ ] Update `handleAnswer()` to call `updateBitValue()`
- [ ] Implement `initFromURL()` function
- [ ] Implement `restoreStateFromBitValue()` function
- [ ] Update `startOver()` to clear URL
### Core State Handling
- `accumulatedBitValue` is tracked in the frontend
- `BIT_DEFINITIONS` constants are present in `script.js`
- `product_bitwise.json` is loaded during startup
- `updateBitValue()` updates the accumulated bitmask from answer filters
- `updateURL()` writes `b` and `q` params without reloading the page
- `initFromURL()` restores the app from query params or direct product routes
- `restoreStateFromBitValue()` rebuilds the key quiz selections from the bitmask
- `startOver()` clears the URL state
### Phase 2: Product Deep Linking (Recommended)
- [ ] Implement `showProductByCode()` function
- [ ] Update `showProductDetail()` to update URL
- [ ] Make product cards clickable
- [ ] Add URL params when viewing products
### Product Deep Linking
- Product cards open detail views through `showProductByCode()`
- Product detail views push the selected product code into the URL
- Direct query-string product links are supported with `?p=<code>`
- Direct Flask routes are supported with `/quiz/product/<product_code>`
### Phase 3: Share Functionality (Nice to Have)
- [ ] Implement `shareCurrentPage()` function
- [ ] Add `showNotification()` helper
- [ ] Add "Share" buttons to UI
- [ ] Add CSS for notification animations
### Share and Navigation Support
- `shareCurrentPage()` copies the current URL to the clipboard when supported
- A notification helper is shown after successful copy
- Share buttons exist on results and product detail screens
- A `popstate` listener handles browser back/forward navigation
### Phase 4: Browser Navigation (Polish)
- [ ] Add `popstate` event listener
- [ ] Test browser back button
- [ ] Test browser forward button
- [ ] Test refresh behavior
## Implementation Notes
## 🚀 Quick Start
The current implementation restores the primary quiz state used by filtering:
- base type
- subtype
- material
- color
### Step 1: Add Global Variables
Add to top of `js/script.js`:
```javascript
let accumulatedBitValue = 0;
let bitwiseData = {};
That is enough to reopen result sets and product-detail pages consistently.
const BIT_DEFINITIONS = {
'base_door': 0, 'base_window': 1,
'material_aluminum': 4, 'material_vinyl': 5,
'color_black': 6, 'color_white': 7, 'color_bronze': 8,
'color_tan': 9, 'color_mill': 10, 'color_sandstone': 11,
'subtype_patio_door': 12, 'subtype_primary_window': 13,
'subtype_storm_door': 14, 'subtype_storm_window': 15
};
```
Dimension data is still primarily driven by the current session flow rather than fully
reconstructed from the URL alone.
### Step 2: Load Bitwise Data
Update `init()` to load `product_bitwise.json`:
```javascript
Promise.all([
fetch('data/navigation.json').then(r => r.json()),
fetch('data/products.json').then(r => r.json()),
fetch('data/accessories.json').then(r => r.json()),
fetch('data/product_bitwise.json').then(r => r.json()) // ADD THIS
])
.then(([questions, products, accessories, bitwise]) => {
// ... existing code ...
// Index bitwise data
bitwiseData = {};
bitwise.forEach(item => {
bitwiseData[item.PROD_CODE] = item.BIT_VALUE;
});
// Check for URL state
initFromURL();
});
```
## Validation Checklist
### Step 3: Add URL Functions
Copy these three key functions from [URL_STATE_MANAGEMENT.md](URL_STATE_MANAGEMENT.md):
1. `updateURL()` - Updates browser URL
2. `updateBitValue()` - Calculates bit value from selection
3. `initFromURL()` - Restores state from URL on load
- [x] Bitwise data loads at startup
- [x] URLs update as quiz answers are selected
- [x] Results pages can be shared with `b` and `q`
- [x] Product pages can be shared with `p`
- [x] Browser refresh restores route context
- [x] Browser back button is handled in code
- [x] Browser forward button is handled in code
- [ ] Full manual regression testing across all quiz paths
### Step 4: Update handleAnswer
Add one line to `handleAnswer()`:
```javascript
function handleAnswer(currentKey, answerValue, answerIndex) {
// ... existing code ...
updateBitValue(answerObject); // ADD THIS LINE
const nextKey = resolveNextQuestion(currentKey, answerValue, answerObject);
history.push(nextKey);
updateURL(nextKey); // ADD THIS LINE
loadContent(nextKey);
}
```
## Known Limits
### Step 5: Test
1. Run your app
2. Navigate through questions
3. Check URL updates after each selection
4. Copy URL and paste in new tab
5. Should restore to same state ✅
- URL restoration is designed around the current bitwise filter model, not a complete
replay of every form interaction.
- Conditional question metadata exists in the navigation data, but the frontend does
not yet use a fully generic conditional-resolution engine.
## 📖 Documentation Files
## Related Files
All details are in these files:
- **[URL_STATE_MANAGEMENT.md](URL_STATE_MANAGEMENT.md)** - Complete implementation guide
- **[REQUIRED_CODE_CHANGES.md](REQUIRED_CODE_CHANGES.md)** - Updated with URL features
- **[BITWISE_USAGE_GUIDE.md](BITWISE_USAGE_GUIDE.md)** - How bitwise system works
- `app/static/js/script.js`
- `app/data/product_bitwise.json`
- `information/BITWISE_USAGE_GUIDE.md`
- `information/REQUIRED_CODE_CHANGES.md`
## 🔧 Key Functions Reference
## Recommended Next Steps
| Function | Purpose | When Called |
|----------|---------|-------------|
| `initFromURL()` | Read URL params on page load | Once at startup |
| `updateURL()` | Write current state to URL | After each answer |
| `updateBitValue()` | Add selection to bit value | After each answer |
| `restoreStateFromBitValue()` | Decode bit value to selections | On page load from URL |
| `shareCurrentPage()` | Copy URL to clipboard | User clicks "Share" |
## 🎨 URL Format Design
### Why Bitwise?
- **Compact**: `?b=16401` vs `?door=true&aluminum=true&storm=true`
- **Fast**: Single integer comparison
- **Flexible**: Easy to add new attributes
- **Shareable**: Short URLs
- **Reversible**: Can decode back to selections
### Parameters Chosen
- `b` = bit value (short, recognizable)
- `q` = question (short, clear purpose)
- `p` = product (short, clear purpose)
### Alternative Considered
Could use hash fragments instead:
```
https://yoursite.com/#/door/storm-door/aluminum
```
But query params are better for:
- Server-side rendering
- Analytics tracking
- SEO (if products are indexed)
## ⚠️ Important Notes
1. **Bit Definitions Must Match**: The `BIT_DEFINITIONS` in JavaScript must match the Python script
2. **URL Length Limits**: URLs have practical limits (~2000 chars), but bit values are small
3. **No Sensitive Data**: Don't put sensitive info in URL (it's visible and loggable)
4. **Test Thoroughly**: Test all navigation paths and browser actions
## 🐛 Troubleshooting
### URL Not Updating
- Check `updateURL()` is called after `handleAnswer()`
- Check browser console for errors
- Verify `accumulatedBitValue` is being set
### State Not Restoring
- Check `initFromURL()` is called in `init()`
- Verify URL has `b` and `q` parameters
- Check `restoreStateFromBitValue()` logic
### Wrong Bit Values
- Verify `BIT_DEFINITIONS` matches `generate_bitwise_helper.py`
- Check `bitwise_legend.json` for correct bit positions
- Use browser console: `console.log(accumulatedBitValue)`
### Share Button Not Working
- Check clipboard API support: `navigator.clipboard`
- Fallback to `prompt()` for older browsers
- Test in HTTPS (clipboard API requires secure context)
## 📈 Benefits Summary
| Feature | User Benefit | Business Benefit |
|---------|-------------|------------------|
| Shareable URLs | Share configurations | Viral marketing |
| Bookmarks | Save favorites | Return visitors |
| Refresh-safe | No data loss | Better UX |
| Deep linking | Direct to product | SEO indexing |
| Browser nav | Back/forward works | Expected behavior |
| Short URLs | Easy to share | More sharing |
## 🎯 Next Steps
1. ✅ Implement Phase 1 (core URL functionality)
2. ✅ Test basic URL state restoration
3. ✅ Add Phase 2 (product deep linking)
4. ✅ Add Phase 3 (share buttons)
5. ✅ Add Phase 4 (browser navigation)
6. ✅ Test all scenarios thoroughly
7. ✅ Add analytics tracking (optional)
Good luck! 🚀
1. Manually test refresh and back/forward behavior on all major quiz branches.
2. Extend restoration if dimension-specific deep linking becomes a requirement.
3. Finish generic conditional navigation so URL restoration and question skipping use the same rules.