Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,17 @@
|
|
| 1 |
from flask import Flask, request, jsonify, send_from_directory
|
| 2 |
import firebase_admin
|
| 3 |
from firebase_admin import credentials, db
|
|
|
|
| 4 |
import os
|
| 5 |
import json
|
| 6 |
-
import re
|
| 7 |
-
import uuid
|
| 8 |
-
import random
|
| 9 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
app = Flask(__name__)
|
| 12 |
|
| 13 |
-
# ---------- Firebase
|
| 14 |
firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
|
| 15 |
if not firebase_service_account_json:
|
| 16 |
raise ValueError("FIREBASE_SERVICE_ACCOUNT secret missing")
|
|
@@ -18,297 +19,480 @@ service_account_info = json.loads(firebase_service_account_json)
|
|
| 18 |
database_url = "https://chat-bot-80c6e-default-rtdb.firebaseio.com/"
|
| 19 |
cred = credentials.Certificate(service_account_info)
|
| 20 |
firebase_admin.initialize_app(cred, {'databaseURL': database_url})
|
| 21 |
-
ref =
|
| 22 |
-
print("✅ Firebase connected
|
| 23 |
-
|
| 24 |
-
# ---------- Immutable Service Catalog ----------
|
| 25 |
-
SERVICES = {
|
| 26 |
-
"base_platforms": {
|
| 27 |
-
"micro_saas": {"name": "Micro-SaaS Platform (Single Function Portal)", "price": 4500, "timeline": 21},
|
| 28 |
-
"corporate_hub": {"name": "Corporate Hub & Business Enterprise Platform", "price": 3200, "timeline": 14},
|
| 29 |
-
"ecommerce_engine": {"name": "Hyper-Scale E-Commerce Engine (Multi-vendor / Global checkout)", "price": 6800, "timeline": 30},
|
| 30 |
-
"custom_webapp": {"name": "Custom Web Application / High-Fidelity Portal", "price": 8500, "timeline": 45}
|
| 31 |
-
},
|
| 32 |
-
"ui_ux": {
|
| 33 |
-
"standard_ui": {"name": "Standard clean-grid UI Layout", "price": 0, "timeline": 0},
|
| 34 |
-
"premium_ui": {"name": "Premium Modern UI Upgrade (WebGL, Lottie, Parallax, Motion Assets)", "price": 1800, "timeline": 7},
|
| 35 |
-
"dark_mode_accessibility": {"name": "Dark Mode Custom Adaptor & WCAG Accessibility Engine", "price": 650, "timeline": 3}
|
| 36 |
-
},
|
| 37 |
-
"database_inventory": {
|
| 38 |
-
"baseline_db": {"name": "Baseline Database Integration (User Profiles / Cloud Storage)", "price": 0, "timeline": 0},
|
| 39 |
-
"inventory_management": {"name": "Advanced Real-Time Inventory Management Engine (SKU, barcodes, low-stock signals)", "price": 2200, "timeline": 10},
|
| 40 |
-
"logistics_bridge": {"name": "Multi-Warehouse Global Logistics / Supplier Bridge API", "price": 3500, "timeline": 14}
|
| 41 |
-
},
|
| 42 |
-
"pages": {
|
| 43 |
-
"base_pages": 5,
|
| 44 |
-
"extra_page_price": 150,
|
| 45 |
-
"extra_page_timeline": 1
|
| 46 |
-
},
|
| 47 |
-
"domains_infra": {
|
| 48 |
-
"standard_dns": {"name": "Standard DNS & Shared Cloud Package", "price": 0, "timeline": 0},
|
| 49 |
-
"premium_domain": {"name": "Premium Dedicated Domain + Multi-Region AWS/GCP Auto-Scaling Shell", "price": 950, "timeline": 2},
|
| 50 |
-
"security_shield": {"name": "Military-Grade Security Shield (DDoS Mitigation, Encryption, Pentest Vault)", "price": 1400, "timeline": 4}
|
| 51 |
-
}
|
| 52 |
-
}
|
| 53 |
-
|
| 54 |
-
# ---------- Step Definitions ----------
|
| 55 |
-
STEPS = [
|
| 56 |
-
("industry", "📌 Please provide your industry, core business goal, and any specific platform requirements."),
|
| 57 |
-
("base_platform", "🏗️ Choose your core platform:\n1. Micro-SaaS Portal ($4,500, 21 days)\n2. Corporate Hub ($3,200, 14 days)\n3. E-Commerce Engine ($6,800, 30 days)\n4. Custom Web App ($8,500, 45 days)"),
|
| 58 |
-
("ui_ux", "🎨 Design level:\n- Standard UI (included)\n- Premium Modern UI (+$1,800, +7 days)\n- Dark Mode Accessibility (+$650, +3 days)"),
|
| 59 |
-
("database_inventory", "🗄️ Database & Inventory:\n- Baseline (included)\n- Real-Time Inventory (+$2,200, +10 days)\n- Logistics Bridge (+$3,500, +14 days)"),
|
| 60 |
-
("extra_pages", "📄 Base includes 5 pages. How many additional pages do you need? (Each +$150, +1 day per 3 pages)"),
|
| 61 |
-
("domain_infra", "🌐 Domain & Infrastructure (you can select multiple, e.g., 'Premium + Security'):\n- Standard DNS (included)\n- Premium Domain + Auto-Scaling (+$950, +2 days)\n- Security Shield (+$1,400, +4 days)"),
|
| 62 |
-
("mobile", "📞 Please provide your corporate/personal contact mobile number."),
|
| 63 |
-
("email", "✉️ Please provide your verified primary email address."),
|
| 64 |
-
("confirm", "✅ Do you confirm this proposal? (Reply: Confirm / Yes / Agree)")
|
| 65 |
-
]
|
| 66 |
-
|
| 67 |
-
# ---------- Session Management ----------
|
| 68 |
-
user_sessions = {}
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
"
|
| 80 |
-
"
|
|
|
|
|
|
|
| 81 |
}
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
def create_project(session_id, requirements
|
| 117 |
-
project_id =
|
|
|
|
| 118 |
project_data = {
|
| 119 |
"project_id": project_id,
|
| 120 |
"session_id": session_id,
|
| 121 |
"requirements": requirements,
|
| 122 |
-
"
|
| 123 |
-
"
|
| 124 |
-
"
|
| 125 |
-
"total_timeline": total_timeline,
|
| 126 |
-
"status": "Pending",
|
| 127 |
"admin_message": "",
|
| 128 |
"created_at": datetime.now().isoformat(),
|
| 129 |
"updated_at": datetime.now().isoformat()
|
| 130 |
}
|
| 131 |
ref.child(f"projects/{project_id}").set(project_data)
|
| 132 |
-
return project_id
|
| 133 |
-
|
| 134 |
-
# ---------- Main Conversation Handler ----------
|
| 135 |
-
def process_message(session_id, user_message):
|
| 136 |
-
# Check for project tracking ID
|
| 137 |
-
if re.match(r'PROJ-2026-\d{4}', user_message.strip().upper()):
|
| 138 |
-
pid = user_message.strip().upper()
|
| 139 |
-
proj = ref.child(f"projects/{pid}").get()
|
| 140 |
-
if proj:
|
| 141 |
-
status = proj.get("status", "Unknown")
|
| 142 |
-
admin_msg = proj.get("admin_message", "")
|
| 143 |
-
extra = f"\n📝 Admin note: {admin_msg}" if admin_msg else ""
|
| 144 |
-
return f"🔍 **Project Tracking Record**\nID: {pid}\nStatus: {status}{extra}"
|
| 145 |
-
else:
|
| 146 |
-
return f"❌ Project ID `{pid}` not found."
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
if session_id in user_sessions:
|
| 151 |
-
del user_sessions[session_id]
|
| 152 |
-
return start_new_session(session_id)
|
| 153 |
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
if session_id not in user_sessions:
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
session = user_sessions[session_id]
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
# All steps completed – waiting for confirmation
|
| 162 |
-
if "confirm" in user_message.lower() or "yes" in user_message.lower() or "agree" in user_message.lower():
|
| 163 |
-
total_price, total_timeline = calculate_total_price_and_timeline(session)
|
| 164 |
-
project_id = create_project(
|
| 165 |
-
session_id,
|
| 166 |
-
session["requirements"],
|
| 167 |
-
session["contact"],
|
| 168 |
-
session["quote"],
|
| 169 |
-
total_price,
|
| 170 |
-
total_timeline
|
| 171 |
-
)
|
| 172 |
-
del user_sessions[session_id]
|
| 173 |
-
return f"""✅ **Project registration successful.**
|
| 174 |
-
Your tracking record is logged under ID: `{project_id}`.
|
| 175 |
-
You can input this ID at any time to retrieve real‑time updates.
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
if
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
else:
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
else:
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
session["
|
| 214 |
-
|
| 215 |
-
session["
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
else:
|
| 217 |
-
session["
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
session["quote"]["domain_infra"] = ["premium_domain", "security_shield"]
|
| 227 |
-
elif "premium" in answer.lower():
|
| 228 |
-
session["quote"]["domain_infra"] = "premium_domain"
|
| 229 |
-
elif "security" in answer.lower() or "shield" in answer.lower():
|
| 230 |
-
session["quote"]["domain_infra"] = "security_shield"
|
| 231 |
else:
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
else:
|
| 237 |
-
return "
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
else:
|
| 242 |
-
return "
|
| 243 |
-
|
| 244 |
-
# Move to next step
|
| 245 |
-
session["step_idx"] += 1
|
| 246 |
-
if session["step_idx"] >= len(STEPS):
|
| 247 |
-
# All data collected – generate proposal
|
| 248 |
-
total_price, total_timeline = calculate_total_price_and_timeline(session)
|
| 249 |
-
contact = session["contact"]
|
| 250 |
-
quote = session["quote"]
|
| 251 |
-
proposal = f"""📋 **PROJECT IDENTIFICATION STAGE: PROPOSAL SUMMARY**
|
| 252 |
-
|
| 253 |
-
**CLIENT METRICS**
|
| 254 |
-
📞 Mobile: {contact.get('mobile', 'N/A')}
|
| 255 |
-
✉️ Email: {contact.get('email', 'N/A')}
|
| 256 |
-
|
| 257 |
-
**SELECTED QUOTES & ITEMIZATION**
|
| 258 |
-
"""
|
| 259 |
-
bp = quote.get("base_platform")
|
| 260 |
-
if bp:
|
| 261 |
-
proposal += f"- {SERVICES['base_platforms'][bp]['name']}: ${SERVICES['base_platforms'][bp]['price']}\n"
|
| 262 |
-
ui = quote.get("ui_ux")
|
| 263 |
-
if ui:
|
| 264 |
-
proposal += f"- {SERVICES['ui_ux'][ui]['name']}: ${SERVICES['ui_ux'][ui]['price']}\n"
|
| 265 |
-
di = quote.get("database_inventory")
|
| 266 |
-
if di:
|
| 267 |
-
proposal += f"- {SERVICES['database_inventory'][di]['name']}: ${SERVICES['database_inventory'][di]['price']}\n"
|
| 268 |
-
extra = quote.get("extra_pages", 0)
|
| 269 |
-
if extra:
|
| 270 |
-
proposal += f"- Additional pages ({extra} pages): ${extra * SERVICES['pages']['extra_page_price']}\n"
|
| 271 |
-
infra = quote.get("domain_infra")
|
| 272 |
-
if infra:
|
| 273 |
-
if isinstance(infra, list):
|
| 274 |
-
for item in infra:
|
| 275 |
-
proposal += f"- {SERVICES['domains_infra'][item]['name']}: ${SERVICES['domains_infra'][item]['price']}\n"
|
| 276 |
-
else:
|
| 277 |
-
proposal += f"- {SERVICES['domains_infra'][infra]['name']}: ${SERVICES['domains_infra'][infra]['price']}\n"
|
| 278 |
-
proposal += f"\n**TOTAL FINANCIAL INVOICE**: ${total_price}\n"
|
| 279 |
-
proposal += f"**TOTAL DEVELOPMENT TIMELINE**: {total_timeline} business days\n\n"
|
| 280 |
-
proposal += "❓ **Do you explicitly confirm and agree with this technical proposal to initialize database logging?** (Reply: Confirm / Agree / Yes)"
|
| 281 |
-
return proposal
|
| 282 |
-
|
| 283 |
-
# Return next question
|
| 284 |
-
next_step_key, next_question = STEPS[session["step_idx"]]
|
| 285 |
-
if next_step_key == "extra_pages":
|
| 286 |
-
current_price, _ = calculate_total_price_and_timeline(session)
|
| 287 |
-
return f"{next_question}\n\n*Current live invoice: ${current_price}*"
|
| 288 |
-
return next_question
|
| 289 |
-
|
| 290 |
-
# ---------- Flask Routes ----------
|
| 291 |
-
@app.route('/api/chat', methods=['POST'])
|
| 292 |
-
def chat():
|
| 293 |
-
data = request.json
|
| 294 |
-
message = data.get('message', '')
|
| 295 |
-
session_id = data.get('session_id', str(uuid.uuid4()))
|
| 296 |
-
if not message:
|
| 297 |
-
return jsonify({"reply": "Please say something."})
|
| 298 |
-
reply = process_message(session_id, message)
|
| 299 |
-
# Save chat history
|
| 300 |
-
ref.child(f"chats/{session_id}/messages").push().set({
|
| 301 |
-
"role": "user", "content": message, "timestamp": datetime.now().isoformat()
|
| 302 |
-
})
|
| 303 |
-
ref.child(f"chats/{session_id}/messages").push().set({
|
| 304 |
-
"role": "assistant", "content": reply, "timestamp": datetime.now().isoformat()
|
| 305 |
-
})
|
| 306 |
-
return jsonify({"reply": reply, "session_id": session_id})
|
| 307 |
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
|
|
|
|
|
|
|
|
|
|
| 312 |
@app.route('/api/projects', methods=['GET'])
|
| 313 |
def get_projects():
|
| 314 |
snap = ref.child("projects").get()
|
|
@@ -318,18 +502,86 @@ def get_projects():
|
|
| 318 |
def update_status(project_id):
|
| 319 |
data = request.json
|
| 320 |
status = data.get('status')
|
| 321 |
-
|
|
|
|
| 322 |
return jsonify({"error": "Invalid status"}), 400
|
| 323 |
-
|
| 324 |
return jsonify({"message": "Status updated"})
|
| 325 |
|
| 326 |
@app.route('/api/project/<project_id>/message', methods=['PUT'])
|
| 327 |
def update_message(project_id):
|
| 328 |
data = request.json
|
| 329 |
msg = data.get('message', '')
|
| 330 |
-
|
| 331 |
return jsonify({"message": "Message updated"})
|
| 332 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
if __name__ == '__main__':
|
| 334 |
port = int(os.environ.get('PORT', 7860))
|
| 335 |
app.run(host='0.0.0.0', port=port)
|
|
|
|
| 1 |
from flask import Flask, request, jsonify, send_from_directory
|
| 2 |
import firebase_admin
|
| 3 |
from firebase_admin import credentials, db
|
| 4 |
+
import requests
|
| 5 |
import os
|
| 6 |
import json
|
|
|
|
|
|
|
|
|
|
| 7 |
from datetime import datetime
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
import uuid
|
| 10 |
+
import re
|
| 11 |
|
| 12 |
app = Flask(__name__)
|
| 13 |
|
| 14 |
+
# ---------- Firebase ----------
|
| 15 |
firebase_service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT")
|
| 16 |
if not firebase_service_account_json:
|
| 17 |
raise ValueError("FIREBASE_SERVICE_ACCOUNT secret missing")
|
|
|
|
| 19 |
database_url = "https://chat-bot-80c6e-default-rtdb.firebaseio.com/"
|
| 20 |
cred = credentials.Certificate(service_account_info)
|
| 21 |
firebase_admin.initialize_app(cred, {'databaseURL': database_url})
|
| 22 |
+
ref = db.reference('/')
|
| 23 |
+
print("✅ Firebase connected")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
# ---------- Sentence-Transformer (for intent, not needed for validation) ----------
|
| 26 |
+
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 27 |
+
print("✅ Embedding model loaded")
|
| 28 |
+
|
| 29 |
+
# ---------- Helper: Load extra services from Firebase ----------
|
| 30 |
+
def get_extra_services():
|
| 31 |
+
snap = ref.child("extra_services").get()
|
| 32 |
+
if not snap:
|
| 33 |
+
default = {
|
| 34 |
+
"live_chat": {"name": "live chat", "price": 20000, "timeline": 3, "display": "Live Chat (+PKR 20,000, +3 days)"},
|
| 35 |
+
"booking_system": {"name": "booking system", "price": 35000, "timeline": 5, "display": "Booking System (+PKR 35,000, +5 days)"},
|
| 36 |
+
"multi_language": {"name": "multi-language", "price": 25000, "timeline": 4, "display": "Multi-Language (+PKR 25,000, +4 days)"},
|
| 37 |
+
"custom_backend": {"name": "custom backend", "price": 100000, "timeline": 15, "display": "Custom Backend (+PKR 1,00,000, +15 days)"}
|
| 38 |
}
|
| 39 |
+
ref.child("extra_services").set(default)
|
| 40 |
+
return default
|
| 41 |
+
return snap
|
| 42 |
+
|
| 43 |
+
# ---------- Pricing Helpers ----------
|
| 44 |
+
BASE_PRICE = 50000
|
| 45 |
+
BASE_PAGES = 5
|
| 46 |
+
EXTRA_PAGE_PRICE = 5000
|
| 47 |
+
BASE_TIMELINE = 10
|
| 48 |
+
|
| 49 |
+
def calculate_price_and_timeline(req):
|
| 50 |
+
extra_services = get_extra_services()
|
| 51 |
+
pages = req.get("pages", 5)
|
| 52 |
+
domain = req.get("domain", False)
|
| 53 |
+
ecommerce = req.get("ecommerce", False)
|
| 54 |
+
chatbot = req.get("chatbot", False)
|
| 55 |
+
seo = req.get("seo", False)
|
| 56 |
+
extra_features = req.get("extra_features", [])
|
| 57 |
+
inventory = req.get("inventory", "").lower() == "yes"
|
| 58 |
+
database = req.get("data", "").lower() == "yes"
|
| 59 |
+
|
| 60 |
+
price = BASE_PRICE
|
| 61 |
+
timeline = BASE_TIMELINE
|
| 62 |
+
if pages > BASE_PAGES:
|
| 63 |
+
price += (pages - BASE_PAGES) * EXTRA_PAGE_PRICE
|
| 64 |
+
timeline += (pages - BASE_PAGES)
|
| 65 |
+
if domain:
|
| 66 |
+
price += 5000
|
| 67 |
+
timeline += 1
|
| 68 |
+
if ecommerce:
|
| 69 |
+
price += 50000
|
| 70 |
+
timeline += 10
|
| 71 |
+
if chatbot:
|
| 72 |
+
price += 30000
|
| 73 |
+
timeline += 5
|
| 74 |
+
if seo:
|
| 75 |
+
price += 25000
|
| 76 |
+
timeline += 5
|
| 77 |
+
for feat in extra_features:
|
| 78 |
+
if feat in extra_services:
|
| 79 |
+
info = extra_services[feat]
|
| 80 |
+
price += info.get("price", 0)
|
| 81 |
+
timeline += info.get("timeline", 0)
|
| 82 |
+
if inventory:
|
| 83 |
+
price += 30000
|
| 84 |
+
timeline += 5
|
| 85 |
+
if database:
|
| 86 |
+
price += 40000
|
| 87 |
+
timeline += 8
|
| 88 |
+
return price, timeline
|
| 89 |
+
|
| 90 |
+
def generate_project_id():
|
| 91 |
+
return f"PROJ-{int(datetime.now().timestamp())}-{uuid.uuid4().hex[:6].upper()}"
|
| 92 |
|
| 93 |
+
def create_project(session_id, requirements):
|
| 94 |
+
project_id = generate_project_id()
|
| 95 |
+
price, timeline = calculate_price_and_timeline(requirements)
|
| 96 |
project_data = {
|
| 97 |
"project_id": project_id,
|
| 98 |
"session_id": session_id,
|
| 99 |
"requirements": requirements,
|
| 100 |
+
"calculated_price": price,
|
| 101 |
+
"calculated_timeline": timeline,
|
| 102 |
+
"status": "pending",
|
|
|
|
|
|
|
| 103 |
"admin_message": "",
|
| 104 |
"created_at": datetime.now().isoformat(),
|
| 105 |
"updated_at": datetime.now().isoformat()
|
| 106 |
}
|
| 107 |
ref.child(f"projects/{project_id}").set(project_data)
|
| 108 |
+
return project_id, price, timeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
def get_project(project_id):
|
| 111 |
+
return ref.child(f"projects/{project_id}").get()
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
def update_project_status(project_id, status, decline_reason=None):
|
| 114 |
+
data = {"status": status, "updated_at": datetime.now().isoformat()}
|
| 115 |
+
if decline_reason:
|
| 116 |
+
data["admin_message"] = decline_reason
|
| 117 |
+
ref.child(f"projects/{project_id}").update(data)
|
| 118 |
+
|
| 119 |
+
def update_project_message(project_id, message):
|
| 120 |
+
ref.child(f"projects/{project_id}").update({"admin_message": message, "updated_at": datetime.now().isoformat()})
|
| 121 |
+
|
| 122 |
+
# ---------- AI Helpers for Dynamic Deep Questions ----------
|
| 123 |
+
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
| 124 |
+
OPENROUTER_MODEL = "google/gemini-2.0-flash-lite-preview-02-05"
|
| 125 |
+
|
| 126 |
+
def call_ai(prompt):
|
| 127 |
+
"""Call OpenRouter (Gemini) or fallback to a simple rule if key missing."""
|
| 128 |
+
if OPENROUTER_API_KEY:
|
| 129 |
+
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 130 |
+
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"}
|
| 131 |
+
payload = {
|
| 132 |
+
"model": OPENROUTER_MODEL,
|
| 133 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 134 |
+
"temperature": 0.7,
|
| 135 |
+
"max_tokens": 200
|
| 136 |
+
}
|
| 137 |
+
try:
|
| 138 |
+
resp = requests.post(url, json=payload, headers=headers, timeout=10)
|
| 139 |
+
resp.raise_for_status()
|
| 140 |
+
return resp.json()["choices"][0]["message"]["content"].strip()
|
| 141 |
+
except Exception as e:
|
| 142 |
+
print(f"OpenRouter error: {e}")
|
| 143 |
+
# Fallback: return a generic deep question
|
| 144 |
+
return "Could you please provide more details about your target audience or business goals?"
|
| 145 |
+
|
| 146 |
+
# ---------- Step Builder with Validation ----------
|
| 147 |
+
user_sessions = {}
|
| 148 |
+
|
| 149 |
+
def is_start_project_request(text):
|
| 150 |
+
keywords = ["website banwani", "build website", "new project", "website chahiye", "start project",
|
| 151 |
+
"i want to build a website", "web project", "website banana hai", "naya project"]
|
| 152 |
+
return any(k in text.lower() for k in keywords)
|
| 153 |
+
|
| 154 |
+
def process_step_by_step(session_id, message):
|
| 155 |
+
msg_lower = message.lower().strip()
|
| 156 |
+
# Start new session
|
| 157 |
if session_id not in user_sessions:
|
| 158 |
+
if is_start_project_request(message):
|
| 159 |
+
user_sessions[session_id] = {
|
| 160 |
+
"step": "asking_domain",
|
| 161 |
+
"requirements": {},
|
| 162 |
+
"deep_answers": {},
|
| 163 |
+
"deep_index": 0,
|
| 164 |
+
"max_deep_rounds": 3,
|
| 165 |
+
"deep_questions": [] # will be filled on the fly
|
| 166 |
+
}
|
| 167 |
+
return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
|
| 168 |
+
return None
|
| 169 |
|
| 170 |
session = user_sessions[session_id]
|
| 171 |
+
step = session.get("step")
|
| 172 |
+
req = session.get("requirements", {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
+
# ---------- Helper to validate answers ----------
|
| 175 |
+
def is_valid_domain_answer(ans):
|
| 176 |
+
return ans.lower() in ["yes", "no", "han", "nahi"]
|
| 177 |
+
|
| 178 |
+
def is_valid_pages_answer(ans):
|
| 179 |
+
try:
|
| 180 |
+
pages = int(ans)
|
| 181 |
+
return pages >= 1
|
| 182 |
+
except:
|
| 183 |
+
return False
|
| 184 |
+
|
| 185 |
+
def is_valid_yes_no(ans):
|
| 186 |
+
return ans.lower() in ["yes", "no", "han", "nahi"]
|
| 187 |
+
|
| 188 |
+
def is_valid_extra_feature_name(ans):
|
| 189 |
+
if ans.lower() in ["none", "done", "no"]:
|
| 190 |
+
return True
|
| 191 |
+
extra_services = get_extra_services()
|
| 192 |
+
for val in extra_services.values():
|
| 193 |
+
if val.get("name", "").lower() in ans.lower() or ans.lower() in val.get("name", "").lower():
|
| 194 |
+
return True
|
| 195 |
+
return False
|
| 196 |
+
|
| 197 |
+
def is_valid_purpose(ans):
|
| 198 |
+
return len(ans.strip()) > 0 # any non-empty
|
| 199 |
+
|
| 200 |
+
def is_valid_theme(ans):
|
| 201 |
+
return len(ans.strip()) > 0
|
| 202 |
+
|
| 203 |
+
def is_valid_content(ans):
|
| 204 |
+
return True # any answer is fine
|
| 205 |
+
|
| 206 |
+
def is_valid_inventory(ans):
|
| 207 |
+
return ans.lower() in ["yes", "no", "han", "nahi", "skip", "none"]
|
| 208 |
+
|
| 209 |
+
def is_valid_database(ans):
|
| 210 |
+
return ans.lower() in ["yes", "no", "han", "nahi", "skip", "none"]
|
| 211 |
+
|
| 212 |
+
def is_valid_mobile(ans):
|
| 213 |
+
return re.search(r'\d{10,15}', ans) is not None
|
| 214 |
+
|
| 215 |
+
def is_valid_email(ans):
|
| 216 |
+
return "@" in ans and "." in ans
|
| 217 |
+
|
| 218 |
+
# ---------- Handle "add more" command ----------
|
| 219 |
+
if msg_lower in ["add more", "add something", "extra add"]:
|
| 220 |
+
session["step"] = "asking_extra"
|
| 221 |
+
extra_services = get_extra_services()
|
| 222 |
+
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 223 |
+
return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
|
| 224 |
+
|
| 225 |
+
# ---------- Step handlers with validation ----------
|
| 226 |
+
if step == "asking_domain":
|
| 227 |
+
if not is_valid_domain_answer(message):
|
| 228 |
+
return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🌐 Do you need a domain name?"
|
| 229 |
+
req["domain"] = "yes" in msg_lower or "han" in msg_lower
|
| 230 |
+
session["step"] = "asking_pages"
|
| 231 |
+
session["requirements"] = req
|
| 232 |
+
return "📄 **How many pages?** (min 5, extra +PKR 5,000 each)\n\nType a number: **5**, **10**, **15**"
|
| 233 |
+
|
| 234 |
+
elif step == "asking_pages":
|
| 235 |
+
if not is_valid_pages_answer(message):
|
| 236 |
+
return "❌ Invalid number. Please enter a valid number of pages (minimum 1).\n\n📄 How many pages?"
|
| 237 |
+
pages = int(re.search(r'\d+', msg_lower).group())
|
| 238 |
+
req["pages"] = max(pages, 5)
|
| 239 |
+
session["step"] = "asking_ecommerce"
|
| 240 |
+
session["requirements"] = req
|
| 241 |
+
return "🛒 **Need e‑commerce?** (payment gateway, cart)\n\nReply: **Yes** or **No**"
|
| 242 |
+
|
| 243 |
+
elif step == "asking_ecommerce":
|
| 244 |
+
if not is_valid_yes_no(message):
|
| 245 |
+
return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🛒 Need e‑commerce?"
|
| 246 |
+
req["ecommerce"] = "yes" in msg_lower or "han" in msg_lower
|
| 247 |
+
session["step"] = "asking_chatbot"
|
| 248 |
+
session["requirements"] = req
|
| 249 |
+
return "🤖 **AI chatbot on your website?**\n\nReply: **Yes** or **No**"
|
| 250 |
+
|
| 251 |
+
elif step == "asking_chatbot":
|
| 252 |
+
if not is_valid_yes_no(message):
|
| 253 |
+
return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🤖 AI chatbot on your website?"
|
| 254 |
+
req["chatbot"] = "yes" in msg_lower or "han" in msg_lower
|
| 255 |
+
session["step"] = "asking_seo"
|
| 256 |
+
session["requirements"] = req
|
| 257 |
+
return "🔍 **SEO optimization?** (rank on Google)\n\nReply: **Yes** or **No**"
|
| 258 |
+
|
| 259 |
+
elif step == "asking_seo":
|
| 260 |
+
if not is_valid_yes_no(message):
|
| 261 |
+
return "❌ Invalid answer. Please reply **Yes** or **No**.\n\n🔍 SEO optimization?"
|
| 262 |
+
req["seo"] = "yes" in msg_lower or "han" in msg_lower
|
| 263 |
+
session["step"] = "asking_extra"
|
| 264 |
+
session["requirements"] = req
|
| 265 |
+
extra_services = get_extra_services()
|
| 266 |
+
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 267 |
+
return f"✨ **Extra features?**\n\nAvailable:\n{extra_list}\n\nType name (e.g., 'live chat') or **done**."
|
| 268 |
+
|
| 269 |
+
elif step == "asking_extra":
|
| 270 |
+
extra_services = get_extra_services()
|
| 271 |
+
if msg_lower in ["none", "done", "no"]:
|
| 272 |
+
# Move to dynamic deep questioning
|
| 273 |
+
session["step"] = "asking_deep"
|
| 274 |
+
session["deep_index"] = 0
|
| 275 |
+
# Generate first deep question using AI
|
| 276 |
+
prompt = f"""You are an expert project estimator. Based on the following client requirements, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Ask about design, content, audience, integrations, or any missing critical detail. Keep your question concise (one sentence).
|
| 277 |
+
|
| 278 |
+
Current requirements:
|
| 279 |
+
{json.dumps(req, indent=2)}
|
| 280 |
+
|
| 281 |
+
Generated question:"""
|
| 282 |
+
first_q = call_ai(prompt)
|
| 283 |
+
session["deep_questions"] = [first_q] # will be extended dynamically
|
| 284 |
+
return first_q
|
| 285 |
else:
|
| 286 |
+
if not is_valid_extra_feature_name(message):
|
| 287 |
+
available = ', '.join([v['name'] for v in extra_services.values()])
|
| 288 |
+
return f"❌ Sorry, **'{message}'** is not offered. Available: {available}\n\nType a valid name or **done**."
|
| 289 |
+
matched_key = None
|
| 290 |
+
for key, val in extra_services.items():
|
| 291 |
+
if val.get("name", "").lower() in msg_lower or msg_lower in val.get("name", "").lower():
|
| 292 |
+
matched_key = key
|
| 293 |
+
break
|
| 294 |
+
if matched_key:
|
| 295 |
+
extra_list = req.get("extra_features", [])
|
| 296 |
+
if matched_key not in extra_list:
|
| 297 |
+
extra_list.append(matched_key)
|
| 298 |
+
req["extra_features"] = extra_list
|
| 299 |
+
session["requirements"] = req
|
| 300 |
+
return f"✅ Added **{extra_services[matched_key]['name']}**.\n\nAny other extras? Type name or **done**."
|
| 301 |
+
else:
|
| 302 |
+
return f"ℹ️ Already added. Type another name or **done**."
|
| 303 |
+
else:
|
| 304 |
+
return f"❌ Sorry, **'{message}'** is not offered. Available: {', '.join([v['name'] for v in extra_services.values()])}\n\nType a valid name or **done**."
|
| 305 |
+
|
| 306 |
+
elif step == "asking_deep":
|
| 307 |
+
# Save the answer to the current deep question
|
| 308 |
+
idx = session.get("deep_index", 0)
|
| 309 |
+
if idx >= session.get("max_deep_rounds", 3):
|
| 310 |
+
# No more deep questions, move to additional info
|
| 311 |
+
session["step"] = "asking_additional"
|
| 312 |
+
session["additional_index"] = 0
|
| 313 |
+
session["additional_questions"] = [
|
| 314 |
+
{"key": "purpose", "question": "📌 **What is the main purpose of the website?** (e.g., e-commerce store, portfolio, blog, corporate) – Type **skip** to leave blank."},
|
| 315 |
+
{"key": "theme", "question": "🎨 **Any specific theme or design preference?** (e.g., modern, minimal, colorful, dark) – Type **skip** or describe."},
|
| 316 |
+
{"key": "content", "question": "📝 **Do you have ready content (text/images)?** Or need us to create? (Type **skip** if not needed now.)"},
|
| 317 |
+
{"key": "inventory", "question": "📦 **Do you need inventory management?** (For products, stock tracking) – Yes/No or **skip**."},
|
| 318 |
+
{"key": "data", "question": "🗄️ **Do you need database integration?** (e.g., user accounts, data storage) – Yes/No or **skip**."}
|
| 319 |
+
]
|
| 320 |
+
return session["additional_questions"][0]["question"]
|
| 321 |
else:
|
| 322 |
+
# Store the answer
|
| 323 |
+
if "deep_answers" not in session:
|
| 324 |
+
session["deep_answers"] = {}
|
| 325 |
+
session["deep_answers"][f"deep_{idx}"] = message
|
| 326 |
+
session["deep_index"] = idx + 1
|
| 327 |
+
# Generate next deep question if still within rounds
|
| 328 |
+
if session["deep_index"] < session.get("max_deep_rounds", 3):
|
| 329 |
+
prompt = f"""You are an expert project estimator. Based on the following client requirements and previous answers, ask the NEXT most important, specific, and open‑ended question to clarify the project details. Do not repeat what has already been answered. Keep your question concise (one sentence).
|
| 330 |
+
|
| 331 |
+
Current requirements:
|
| 332 |
+
{json.dumps(req, indent=2)}
|
| 333 |
+
|
| 334 |
+
Previous deep answers:
|
| 335 |
+
{json.dumps(session.get("deep_answers", {}), indent=2)}
|
| 336 |
+
|
| 337 |
+
Generated question:"""
|
| 338 |
+
next_q = call_ai(prompt)
|
| 339 |
+
return next_q
|
| 340 |
+
else:
|
| 341 |
+
# Move to additional info step
|
| 342 |
+
session["step"] = "asking_additional"
|
| 343 |
+
session["additional_index"] = 0
|
| 344 |
+
session["additional_questions"] = [
|
| 345 |
+
{"key": "purpose", "question": "📌 **What is the main purpose of the website?** (e.g., e-commerce store, portfolio, blog, corporate) – Type **skip** to leave blank."},
|
| 346 |
+
{"key": "theme", "question": "🎨 **Any specific theme or design preference?** (e.g., modern, minimal, colorful, dark) – Type **skip** or describe."},
|
| 347 |
+
{"key": "content", "question": "📝 **Do you have ready content (text/images)?** Or need us to create? (Type **skip** if not needed now.)"},
|
| 348 |
+
{"key": "inventory", "question": "📦 **Do you need inventory management?** (For products, stock tracking) – Yes/No or **skip**."},
|
| 349 |
+
{"key": "data", "question": "🗄️ **Do you need database integration?** (e.g., user accounts, data storage) – Yes/No or **skip**."}
|
| 350 |
+
]
|
| 351 |
+
return session["additional_questions"][0]["question"]
|
| 352 |
+
|
| 353 |
+
elif step == "asking_additional":
|
| 354 |
+
idx = session.get("additional_index", 0)
|
| 355 |
+
qlist = session.get("additional_questions", [])
|
| 356 |
+
if idx < len(qlist):
|
| 357 |
+
current_q = qlist[idx]
|
| 358 |
+
key = current_q["key"]
|
| 359 |
+
# For optional questions, accept any answer (including skip)
|
| 360 |
+
if msg_lower in ["skip", "none", "no"]:
|
| 361 |
+
session["additional_answers"][key] = ""
|
| 362 |
+
else:
|
| 363 |
+
session["additional_answers"][key] = message
|
| 364 |
+
session["additional_index"] = idx + 1
|
| 365 |
+
if idx + 1 < len(qlist):
|
| 366 |
+
return qlist[idx+1]["question"]
|
| 367 |
+
else:
|
| 368 |
+
# All additional questions done, move to contact
|
| 369 |
+
session["step"] = "asking_contact"
|
| 370 |
+
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 371 |
else:
|
| 372 |
+
session["step"] = "asking_contact"
|
| 373 |
+
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 374 |
+
|
| 375 |
+
elif step == "asking_contact":
|
| 376 |
+
if "mobile" not in session:
|
| 377 |
+
if not is_valid_mobile(message):
|
| 378 |
+
return "❌ Invalid mobile number. Please enter a valid phone number (10-15 digits).\n\n📞 Please provide your mobile number:"
|
| 379 |
+
session["mobile"] = message
|
| 380 |
+
return "✉️ **Please provide your email address** (e.g., name@example.com) – We'll send the quote and updates."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 381 |
else:
|
| 382 |
+
if not is_valid_email(message):
|
| 383 |
+
return "❌ Invalid email address. Please enter a valid email (e.g., name@example.com).\n\n✉️ Please provide your email address:"
|
| 384 |
+
session["email"] = message
|
| 385 |
+
req["mobile"] = session.get("mobile", "")
|
| 386 |
+
req["email"] = session.get("email", "")
|
| 387 |
+
# Merge additional and deep answers
|
| 388 |
+
req["additional_answers"] = session.get("additional_answers", {})
|
| 389 |
+
req["deep_answers"] = session.get("deep_answers", {})
|
| 390 |
+
session["requirements"] = req
|
| 391 |
+
session["step"] = "confirm"
|
| 392 |
+
price, timeline = calculate_price_and_timeline(req)
|
| 393 |
+
extra_services = get_extra_services()
|
| 394 |
+
extra_names = [extra_services.get(f, {}).get("name", f) for f in req.get("extra_features", [])]
|
| 395 |
+
extra_display = ", ".join(extra_names) if extra_names else "None"
|
| 396 |
+
add_answers = session.get("additional_answers", {})
|
| 397 |
+
add_text = ""
|
| 398 |
+
if any(add_answers.values()):
|
| 399 |
+
add_text = "\n\n📌 **Additional Info:**\n"
|
| 400 |
+
if add_answers.get("purpose"):
|
| 401 |
+
add_text += f"• Purpose: {add_answers['purpose']}\n"
|
| 402 |
+
if add_answers.get("theme"):
|
| 403 |
+
add_text += f"• Theme: {add_answers['theme']}\n"
|
| 404 |
+
if add_answers.get("content"):
|
| 405 |
+
add_text += f"• Content: {add_answers['content']}\n"
|
| 406 |
+
if add_answers.get("inventory"):
|
| 407 |
+
add_text += f"• Inventory Management: {add_answers['inventory']}\n"
|
| 408 |
+
if add_answers.get("data"):
|
| 409 |
+
add_text += f"• Database Integration: {add_answers['data']}\n"
|
| 410 |
+
deep_answers = session.get("deep_answers", {})
|
| 411 |
+
deep_text = ""
|
| 412 |
+
if deep_answers:
|
| 413 |
+
deep_text = "\n\n📌 **Deep Dive Responses:**\n"
|
| 414 |
+
for key, val in deep_answers.items():
|
| 415 |
+
deep_text += f"• {key}: {val}\n"
|
| 416 |
+
contact_text = f"\n\n📞 **Contact Details:**\n• Mobile: {req.get('mobile', '')}\n• Email: {req.get('email', '')}"
|
| 417 |
+
return f"""📋 **Your Project Proposal**
|
| 418 |
+
|
| 419 |
+
✅ **Summary:**
|
| 420 |
+
• Domain: {'Yes' if req.get('domain') else 'No'}
|
| 421 |
+
• Pages: {req.get('pages', 5)}
|
| 422 |
+
• E‑commerce: {'Yes' if req.get('ecommerce') else 'No'}
|
| 423 |
+
• Chatbot: {'Yes' if req.get('chatbot') else 'No'}
|
| 424 |
+
• SEO: {'Yes' if req.get('seo') else 'No'}
|
| 425 |
+
• Extras: {extra_display}{add_text}{deep_text}{contact_text}
|
| 426 |
+
|
| 427 |
+
💰 **Total Cost:** PKR {price:,}
|
| 428 |
+
⏱️ **Timeline:** {timeline} working days
|
| 429 |
+
|
| 430 |
+
❓ **Agree?** (Reply: **Confirm** or **Cancel**)
|
| 431 |
+
|
| 432 |
+
⚠️ *To add more extras, type 'add more'*"""
|
| 433 |
+
|
| 434 |
+
elif step == "confirm":
|
| 435 |
+
if "confirm" in msg_lower or "agree" in msg_lower:
|
| 436 |
+
project_id, price, timeline = create_project(session_id, req)
|
| 437 |
+
del user_sessions[session_id]
|
| 438 |
+
return f"""✅ **Project Confirmed!**
|
| 439 |
+
|
| 440 |
+
**Project ID:** `{project_id}`
|
| 441 |
+
**Total Cost:** PKR {price:,}
|
| 442 |
+
**Timeline:** {timeline} days
|
| 443 |
+
|
| 444 |
+
Use `status {project_id}` anytime.
|
| 445 |
+
We'll contact you within 24 hours. 🚀"""
|
| 446 |
+
elif "cancel" in msg_lower:
|
| 447 |
+
del user_sessions[session_id]
|
| 448 |
+
return "❌ Cancelled. Start again with 'I want to build a website'.\n📞 For special requests, contact admin: +92 300 1234567"
|
| 449 |
+
elif "add more" in msg_lower:
|
| 450 |
+
session["step"] = "asking_extra"
|
| 451 |
+
extra_services = get_extra_services()
|
| 452 |
+
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 453 |
+
return f"✨ **Add more extras**\n\nAvailable:\n{extra_list}\n\nType name or **done**."
|
| 454 |
else:
|
| 455 |
+
return "Please reply **Confirm**, **Cancel**, or **add more**."
|
| 456 |
+
|
| 457 |
+
return None
|
| 458 |
+
|
| 459 |
+
# ---------- Package details (fallback for existing features) ----------
|
| 460 |
+
def package_details(query):
|
| 461 |
+
q = query.lower()
|
| 462 |
+
if "basic" in q:
|
| 463 |
+
return "**Basic Website** – PKR 50,000 (7-10 days)\n✅ 5 pages, responsive, basic SEO, contact form, social links."
|
| 464 |
+
if "standard" in q:
|
| 465 |
+
return "**Standard Website** – PKR 1,20,000 (15-20 days)\n✅ 10 pages, CMS, advanced SEO, blog, chatbot, 1 month support."
|
| 466 |
+
if "premium" in q:
|
| 467 |
+
return "**Premium Website** – PKR 2,50,000 (25-30 days)\n✅ Unlimited pages, e‑commerce, payment gateway, user accounts, custom animations, 6 months support."
|
| 468 |
+
return None
|
| 469 |
+
|
| 470 |
+
# ---------- Main response handler ----------
|
| 471 |
+
def get_final_response(user_message, session_id):
|
| 472 |
+
step_resp = process_step_by_step(session_id, user_message)
|
| 473 |
+
if step_resp:
|
| 474 |
+
return step_resp
|
| 475 |
+
|
| 476 |
+
status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower())
|
| 477 |
+
if status_match:
|
| 478 |
+
pid = status_match.group(1).upper()
|
| 479 |
+
proj = get_project(pid)
|
| 480 |
+
if proj:
|
| 481 |
+
status = proj.get("status", "pending")
|
| 482 |
+
emoji = {"pending":"⏳", "in-progress":"🔄", "completed":"✅", "declined":"❌"}.get(status, "❓")
|
| 483 |
+
msg = proj.get("admin_message", "")
|
| 484 |
+
extra = f"\n📝 **Admin note:** {msg}" if msg else ""
|
| 485 |
+
return f"📦 **Project {pid}**\nStatus: {emoji} {status.upper()}{extra}\nTotal: PKR {proj.get('calculated_price',0):,}\nTimeline: {proj.get('calculated_timeline',0)} days"
|
| 486 |
else:
|
| 487 |
+
return f"❌ Project ID `{pid}` not found."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
|
| 489 |
+
pkg = package_details(user_message)
|
| 490 |
+
if pkg:
|
| 491 |
+
return pkg
|
| 492 |
|
| 493 |
+
return "- How can I help? Services: website design, e‑commerce, SEO, chatbots.\n- **To start a project, say 'I want to build a website'**"
|
| 494 |
+
|
| 495 |
+
# ---------- Admin API routes (unchanged) ----------
|
| 496 |
@app.route('/api/projects', methods=['GET'])
|
| 497 |
def get_projects():
|
| 498 |
snap = ref.child("projects").get()
|
|
|
|
| 502 |
def update_status(project_id):
|
| 503 |
data = request.json
|
| 504 |
status = data.get('status')
|
| 505 |
+
reason = data.get('reason', '')
|
| 506 |
+
if status not in ['pending', 'in-progress', 'completed', 'declined']:
|
| 507 |
return jsonify({"error": "Invalid status"}), 400
|
| 508 |
+
update_project_status(project_id, status, reason)
|
| 509 |
return jsonify({"message": "Status updated"})
|
| 510 |
|
| 511 |
@app.route('/api/project/<project_id>/message', methods=['PUT'])
|
| 512 |
def update_message(project_id):
|
| 513 |
data = request.json
|
| 514 |
msg = data.get('message', '')
|
| 515 |
+
update_project_message(project_id, msg)
|
| 516 |
return jsonify({"message": "Message updated"})
|
| 517 |
|
| 518 |
+
@app.route('/api/services', methods=['GET'])
|
| 519 |
+
def get_services():
|
| 520 |
+
services = get_extra_services()
|
| 521 |
+
return jsonify({"services": services})
|
| 522 |
+
|
| 523 |
+
@app.route('/api/services', methods=['POST'])
|
| 524 |
+
def add_service():
|
| 525 |
+
data = request.json
|
| 526 |
+
key = data.get('key')
|
| 527 |
+
name = data.get('name')
|
| 528 |
+
price = int(data.get('price', 0))
|
| 529 |
+
timeline = int(data.get('timeline', 0))
|
| 530 |
+
if not key or not name:
|
| 531 |
+
return jsonify({"error": "Missing key or name"}), 400
|
| 532 |
+
service = {
|
| 533 |
+
"name": name,
|
| 534 |
+
"price": price,
|
| 535 |
+
"timeline": timeline,
|
| 536 |
+
"display": f"{name} (+PKR {price:,}, +{timeline} days)"
|
| 537 |
+
}
|
| 538 |
+
ref.child(f"extra_services/{key}").set(service)
|
| 539 |
+
return jsonify({"message": "Service added"})
|
| 540 |
+
|
| 541 |
+
@app.route('/api/services/<key>', methods=['PUT'])
|
| 542 |
+
def update_service(key):
|
| 543 |
+
data = request.json
|
| 544 |
+
name = data.get('name')
|
| 545 |
+
price = int(data.get('price', 0))
|
| 546 |
+
timeline = int(data.get('timeline', 0))
|
| 547 |
+
if not name:
|
| 548 |
+
return jsonify({"error": "Missing name"}), 400
|
| 549 |
+
service = {
|
| 550 |
+
"name": name,
|
| 551 |
+
"price": price,
|
| 552 |
+
"timeline": timeline,
|
| 553 |
+
"display": f"{name} (+PKR {price:,}, +{timeline} days)"
|
| 554 |
+
}
|
| 555 |
+
ref.child(f"extra_services/{key}").update(service)
|
| 556 |
+
return jsonify({"message": "Service updated"})
|
| 557 |
+
|
| 558 |
+
@app.route('/api/services/<key>', methods=['DELETE'])
|
| 559 |
+
def delete_service(key):
|
| 560 |
+
ref.child(f"extra_services/{key}").delete()
|
| 561 |
+
return jsonify({"message": "Service deleted"})
|
| 562 |
+
|
| 563 |
+
# ---------- Main chat endpoint ----------
|
| 564 |
+
@app.route('/api/chat', methods=['POST'])
|
| 565 |
+
def chat():
|
| 566 |
+
data = request.json
|
| 567 |
+
message = data.get('message', '')
|
| 568 |
+
session_id = data.get('session_id', str(uuid.uuid4()))
|
| 569 |
+
if not message:
|
| 570 |
+
return jsonify({"reply": "Please say something."})
|
| 571 |
+
reply = get_final_response(message, session_id)
|
| 572 |
+
# Save chat history
|
| 573 |
+
ref.child(f"chats/{session_id}/messages").push().set({
|
| 574 |
+
"role": "user", "content": message, "timestamp": datetime.now().isoformat()
|
| 575 |
+
})
|
| 576 |
+
ref.child(f"chats/{session_id}/messages").push().set({
|
| 577 |
+
"role": "assistant", "content": reply, "timestamp": datetime.now().isoformat()
|
| 578 |
+
})
|
| 579 |
+
return jsonify({"reply": reply, "session_id": session_id})
|
| 580 |
+
|
| 581 |
+
@app.route('/')
|
| 582 |
+
def index():
|
| 583 |
+
return send_from_directory('.', 'index.html')
|
| 584 |
+
|
| 585 |
if __name__ == '__main__':
|
| 586 |
port = int(os.environ.get('PORT', 7860))
|
| 587 |
app.run(host='0.0.0.0', port=port)
|