Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,16 @@
|
|
| 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,444 +18,321 @@ service_account_info = json.loads(firebase_service_account_json)
|
|
| 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 |
-
# ----------
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
# ----------
|
| 30 |
-
def
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 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 |
-
# ----------
|
| 44 |
-
|
| 45 |
-
BASE_PAGES = 5
|
| 46 |
-
EXTRA_PAGE_PRICE = 5000
|
| 47 |
-
BASE_TIMELINE = 10
|
| 48 |
|
| 49 |
-
def
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
def generate_project_id():
|
| 91 |
-
|
|
|
|
| 92 |
|
| 93 |
-
def create_project(session_id,
|
| 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":
|
| 100 |
-
"
|
| 101 |
-
"
|
| 102 |
-
"
|
|
|
|
|
|
|
| 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
|
| 109 |
|
| 110 |
def get_project(project_id):
|
| 111 |
return ref.child(f"projects/{project_id}").get()
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 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 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 GPT-2 if key missing or error."""
|
| 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": 300
|
| 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 |
-
# Fall through to GPT‑2
|
| 144 |
-
# Fallback to local GPT‑2
|
| 145 |
-
try:
|
| 146 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 147 |
-
gpt_tokenizer = AutoTokenizer.from_pretrained("gpt2")
|
| 148 |
-
gpt_model = AutoModelForCausalLM.from_pretrained("gpt2")
|
| 149 |
-
gpt_tokenizer.pad_token = gpt_tokenizer.eos_token
|
| 150 |
-
inputs = gpt_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1024)
|
| 151 |
-
outputs = gpt_model.generate(**inputs, max_new_tokens=100, do_sample=True, temperature=0.7)
|
| 152 |
-
return gpt_tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
| 153 |
-
except:
|
| 154 |
-
return "Could you please provide more details about your project requirements?"
|
| 155 |
-
|
| 156 |
-
# ---------- Step Builder (with dynamic deep questions) ----------
|
| 157 |
-
user_sessions = {}
|
| 158 |
-
|
| 159 |
-
def is_start_project_request(text):
|
| 160 |
-
keywords = ["website banwani", "build website", "new project", "website chahiye", "start project",
|
| 161 |
-
"i want to build a website", "web project", "website banana hai", "naya project"]
|
| 162 |
-
return any(k in text.lower() for k in keywords)
|
| 163 |
-
|
| 164 |
-
def process_step_by_step(session_id, message):
|
| 165 |
-
msg_lower = message.lower().strip()
|
| 166 |
-
if session_id not in user_sessions:
|
| 167 |
-
if is_start_project_request(message):
|
| 168 |
-
user_sessions[session_id] = {
|
| 169 |
-
"step": "asking_domain",
|
| 170 |
-
"requirements": {},
|
| 171 |
-
"dynamic_answers": {},
|
| 172 |
-
"dynamic_round": 0,
|
| 173 |
-
"max_dynamic_rounds": 5
|
| 174 |
-
}
|
| 175 |
-
return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
|
| 176 |
-
return None
|
| 177 |
-
|
| 178 |
-
session = user_sessions[session_id]
|
| 179 |
-
step = session.get("step")
|
| 180 |
-
req = session.get("requirements", {})
|
| 181 |
-
|
| 182 |
-
# Helper to move to dynamic questioning after extra features
|
| 183 |
-
def move_to_dynamic():
|
| 184 |
-
session["step"] = "asking_dynamic"
|
| 185 |
-
session["dynamic_round"] = 0
|
| 186 |
-
# Build prompt to generate first dynamic question
|
| 187 |
-
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).
|
| 188 |
-
|
| 189 |
-
Current requirements:
|
| 190 |
-
{json.dumps(req, indent=2)}
|
| 191 |
-
|
| 192 |
-
Generated question:"""
|
| 193 |
-
question = call_ai(prompt)
|
| 194 |
-
return question
|
| 195 |
-
|
| 196 |
-
# Handle "add more" after proposal
|
| 197 |
-
if msg_lower in ["add more", "add something", "extra add"]:
|
| 198 |
-
session["step"] = "asking_extra"
|
| 199 |
-
extra_services = get_extra_services()
|
| 200 |
-
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 201 |
-
return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
|
| 202 |
-
|
| 203 |
-
# Main step handling
|
| 204 |
-
if step == "asking_domain":
|
| 205 |
-
req["domain"] = "yes" in msg_lower or "han" in msg_lower
|
| 206 |
-
session["step"] = "asking_pages"
|
| 207 |
-
session["requirements"] = req
|
| 208 |
-
return "📄 **How many pages?** (min 5, extra +PKR 5,000 each)\n\nType a number: **5**, **10**, **15**"
|
| 209 |
-
|
| 210 |
-
elif step == "asking_pages":
|
| 211 |
-
try:
|
| 212 |
-
pages = int(re.search(r'\d+', msg_lower).group())
|
| 213 |
-
req["pages"] = max(pages, 5)
|
| 214 |
-
except:
|
| 215 |
-
req["pages"] = 5
|
| 216 |
-
session["step"] = "asking_ecommerce"
|
| 217 |
-
session["requirements"] = req
|
| 218 |
-
return "🛒 **Need e‑commerce?** (payment gateway, cart)\n\nReply: **Yes** or **No**"
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
session["requirements"] = req
|
| 230 |
-
return "🔍 **SEO optimization?** (rank on Google)\n\nReply: **Yes** or **No**"
|
| 231 |
-
|
| 232 |
-
elif step == "asking_seo":
|
| 233 |
-
req["seo"] = "yes" in msg_lower or "han" in msg_lower
|
| 234 |
-
session["step"] = "asking_extra"
|
| 235 |
-
session["requirements"] = req
|
| 236 |
-
extra_services = get_extra_services()
|
| 237 |
-
extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
|
| 238 |
-
return f"✨ **Extra features?**\n\nAvailable:\n{extra_list}\n\nType name (e.g., 'live chat') or **done**."
|
| 239 |
-
|
| 240 |
-
elif step == "asking_extra":
|
| 241 |
-
extra_services = get_extra_services()
|
| 242 |
-
if msg_lower in ["none", "done", "no"]:
|
| 243 |
-
# Move to dynamic deep questioning
|
| 244 |
-
return move_to_dynamic()
|
| 245 |
-
else:
|
| 246 |
-
matched_key = None
|
| 247 |
-
for key, val in extra_services.items():
|
| 248 |
-
if val.get("name", "").lower() in msg_lower or msg_lower in val.get("name", "").lower():
|
| 249 |
-
matched_key = key
|
| 250 |
-
break
|
| 251 |
-
if matched_key:
|
| 252 |
-
extra_list = req.get("extra_features", [])
|
| 253 |
-
if matched_key not in extra_list:
|
| 254 |
-
extra_list.append(matched_key)
|
| 255 |
-
req["extra_features"] = extra_list
|
| 256 |
-
session["requirements"] = req
|
| 257 |
-
return f"✅ Added **{extra_services[matched_key]['name']}**.\n\nAny other extras? Type name or **done**."
|
| 258 |
-
else:
|
| 259 |
-
return f"ℹ️ Already added. Type another name or **done**."
|
| 260 |
-
else:
|
| 261 |
-
available = ', '.join([v['name'] for v in extra_services.values()])
|
| 262 |
-
return f"❌ Sorry, **'{message}'** is not offered. Available: {available}\n\nType a valid name or **done**."
|
| 263 |
-
|
| 264 |
-
elif step == "asking_dynamic":
|
| 265 |
-
# Save the answer to the previous question
|
| 266 |
-
round_num = session.get("dynamic_round", 0)
|
| 267 |
-
if round_num > 0:
|
| 268 |
-
# Store the answer under a dynamic key
|
| 269 |
-
session["dynamic_answers"][f"q{round_num}"] = message
|
| 270 |
-
# Determine if we should ask another question
|
| 271 |
-
round_num += 1
|
| 272 |
-
session["dynamic_round"] = round_num
|
| 273 |
-
if round_num > session.get("max_dynamic_rounds", 5):
|
| 274 |
-
# Enough questions; move to contact details
|
| 275 |
-
session["step"] = "asking_contact"
|
| 276 |
-
# Merge dynamic answers into requirements
|
| 277 |
-
req["dynamic_answers"] = session.get("dynamic_answers", {})
|
| 278 |
-
session["requirements"] = req
|
| 279 |
-
return "📞 **Please provide your mobile number** (e.g., 03001234567) – We'll use this to contact you."
|
| 280 |
else:
|
| 281 |
-
|
| 282 |
-
# Build prompt with current requirements and previous dynamic answers
|
| 283 |
-
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. Ask about design, content, audience, integrations, or any missing critical detail. Keep your question concise (one sentence).
|
| 284 |
-
|
| 285 |
-
Current requirements:
|
| 286 |
-
{json.dumps(req, indent=2)}
|
| 287 |
-
|
| 288 |
-
Previous dynamic answers:
|
| 289 |
-
{json.dumps(session.get("dynamic_answers", {}), indent=2)}
|
| 290 |
-
|
| 291 |
-
Generated question:"""
|
| 292 |
-
next_q = call_ai(prompt)
|
| 293 |
-
return next_q
|
| 294 |
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
|
|
|
| 299 |
else:
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
session["requirements"] = req
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
return f"
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
else:
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
emoji = {"pending":"⏳", "in-progress":"🔄", "completed":"✅", "declined":"❌"}.get(status, "❓")
|
| 379 |
-
msg = proj.get("admin_message", "")
|
| 380 |
-
extra = f"\n📝 **Admin note:** {msg}" if msg else ""
|
| 381 |
-
return f"📦 **Project {pid}**\nStatus: {emoji} {status.upper()}{extra}\nTotal: PKR {proj.get('calculated_price',0):,}\nTimeline: {proj.get('calculated_timeline',0)} days"
|
| 382 |
else:
|
| 383 |
-
return
|
| 384 |
-
|
| 385 |
-
pkg = package_details(user_message)
|
| 386 |
-
if pkg:
|
| 387 |
-
return pkg
|
| 388 |
-
|
| 389 |
-
return "- How can I help? Services: website design, e‑commerce, SEO, chatbots.\n- **To start a project, say 'I want to build a website'**"
|
| 390 |
-
|
| 391 |
-
# ---------- Admin API routes (unchanged) ----------
|
| 392 |
-
@app.route('/api/projects', methods=['GET'])
|
| 393 |
-
def get_projects():
|
| 394 |
-
snap = ref.child("projects").get()
|
| 395 |
-
return jsonify({"projects": list(snap.values()) if snap else []})
|
| 396 |
-
|
| 397 |
-
@app.route('/api/project/<project_id>/status', methods=['PUT'])
|
| 398 |
-
def update_status(project_id):
|
| 399 |
-
data = request.json
|
| 400 |
-
status = data.get('status')
|
| 401 |
-
reason = data.get('reason', '')
|
| 402 |
-
if status not in ['pending', 'in-progress', 'completed', 'declined']:
|
| 403 |
-
return jsonify({"error": "Invalid status"}), 400
|
| 404 |
-
update_project_status(project_id, status, reason)
|
| 405 |
-
return jsonify({"message": "Status updated"})
|
| 406 |
-
|
| 407 |
-
@app.route('/api/project/<project_id>/message', methods=['PUT'])
|
| 408 |
-
def update_message(project_id):
|
| 409 |
-
data = request.json
|
| 410 |
-
msg = data.get('message', '')
|
| 411 |
-
update_project_message(project_id, msg)
|
| 412 |
-
return jsonify({"message": "Message updated"})
|
| 413 |
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
services = get_extra_services()
|
| 417 |
-
return jsonify({"services": services})
|
| 418 |
|
| 419 |
-
|
| 420 |
-
def add_service():
|
| 421 |
-
data = request.json
|
| 422 |
-
key = data.get('key')
|
| 423 |
-
name = data.get('name')
|
| 424 |
-
price = int(data.get('price', 0))
|
| 425 |
-
timeline = int(data.get('timeline', 0))
|
| 426 |
-
if not key or not name:
|
| 427 |
-
return jsonify({"error": "Missing key or name"}), 400
|
| 428 |
-
service = {
|
| 429 |
-
"name": name,
|
| 430 |
-
"price": price,
|
| 431 |
-
"timeline": timeline,
|
| 432 |
-
"display": f"{name} (+PKR {price:,}, +{timeline} days)"
|
| 433 |
-
}
|
| 434 |
-
ref.child(f"extra_services/{key}").set(service)
|
| 435 |
-
return jsonify({"message": "Service added"})
|
| 436 |
-
|
| 437 |
-
@app.route('/api/services/<key>', methods=['PUT'])
|
| 438 |
-
def update_service(key):
|
| 439 |
-
data = request.json
|
| 440 |
-
name = data.get('name')
|
| 441 |
-
price = int(data.get('price', 0))
|
| 442 |
-
timeline = int(data.get('timeline', 0))
|
| 443 |
-
if not name:
|
| 444 |
-
return jsonify({"error": "Missing name"}), 400
|
| 445 |
-
service = {
|
| 446 |
-
"name": name,
|
| 447 |
-
"price": price,
|
| 448 |
-
"timeline": timeline,
|
| 449 |
-
"display": f"{name} (+PKR {price:,}, +{timeline} days)"
|
| 450 |
-
}
|
| 451 |
-
ref.child(f"extra_services/{key}").update(service)
|
| 452 |
-
return jsonify({"message": "Service updated"})
|
| 453 |
-
|
| 454 |
-
@app.route('/api/services/<key>', methods=['DELETE'])
|
| 455 |
-
def delete_service(key):
|
| 456 |
-
ref.child(f"extra_services/{key}").delete()
|
| 457 |
-
return jsonify({"message": "Service deleted"})
|
| 458 |
-
|
| 459 |
-
# ---------- Main chat endpoint ----------
|
| 460 |
@app.route('/api/chat', methods=['POST'])
|
| 461 |
def chat():
|
| 462 |
data = request.json
|
|
@@ -464,7 +340,8 @@ def chat():
|
|
| 464 |
session_id = data.get('session_id', str(uuid.uuid4()))
|
| 465 |
if not message:
|
| 466 |
return jsonify({"reply": "Please say something."})
|
| 467 |
-
reply =
|
|
|
|
| 468 |
ref.child(f"chats/{session_id}/messages").push().set({
|
| 469 |
"role": "user", "content": message, "timestamp": datetime.now().isoformat()
|
| 470 |
})
|
|
@@ -477,6 +354,28 @@ def chat():
|
|
| 477 |
def index():
|
| 478 |
return send_from_directory('.', 'index.html')
|
| 479 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
if __name__ == '__main__':
|
| 481 |
port = int(os.environ.get('PORT', 7860))
|
| 482 |
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 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 Admin ----------
|
| 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 |
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 = firebase_admin.db.reference('/')
|
| 22 |
+
print("✅ Firebase connected (Aetheria Nexus Core v9.4)")
|
| 23 |
+
|
| 24 |
+
# ---------- The 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 # per 3 pages
|
| 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 |
+
# ---------- Phase 1: Intent Decoding ----------
|
| 55 |
+
def decode_intent(message):
|
| 56 |
+
# Look for any request related to building a website / app / platform
|
| 57 |
+
keywords = ["website", "web platform", "online store", "e-commerce", "ecommerce", "micro-saas", "corporate hub",
|
| 58 |
+
"web application", "business website", "sell online", "track members", "garments", "inventory", "portal"]
|
| 59 |
+
if any(k in message.lower() for k in keywords):
|
| 60 |
+
return True
|
| 61 |
+
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
# ---------- Phase 2 & 3: Conversational State Management ----------
|
| 64 |
+
user_sessions = {} # session_id -> { phase, requirements, contact, quote, ... }
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
def get_or_create_session(session_id):
|
| 67 |
+
if session_id not in user_sessions:
|
| 68 |
+
user_sessions[session_id] = {
|
| 69 |
+
"phase": "intake", # intake → discovery → identity → proposal → confirm
|
| 70 |
+
"requirements": {},
|
| 71 |
+
"contact": {},
|
| 72 |
+
"quote": {
|
| 73 |
+
"base_platform": None,
|
| 74 |
+
"ui_ux": None,
|
| 75 |
+
"database_inventory": None,
|
| 76 |
+
"extra_pages": 0,
|
| 77 |
+
"domain_infra": None,
|
| 78 |
+
"selected_features": [] # list of service keys
|
| 79 |
+
},
|
| 80 |
+
"last_question": None
|
| 81 |
+
}
|
| 82 |
+
return user_sessions[session_id]
|
| 83 |
+
|
| 84 |
+
def calculate_total_price_and_timeline(req):
|
| 85 |
+
quote = req.get("quote", {})
|
| 86 |
+
total_price = 0
|
| 87 |
+
total_timeline = 0
|
| 88 |
+
# Base platform
|
| 89 |
+
bp = quote.get("base_platform")
|
| 90 |
+
if bp and bp in SERVICES["base_platforms"]:
|
| 91 |
+
total_price += SERVICES["base_platforms"][bp]["price"]
|
| 92 |
+
total_timeline += SERVICES["base_platforms"][bp]["timeline"]
|
| 93 |
+
# UI/UX
|
| 94 |
+
ui = quote.get("ui_ux")
|
| 95 |
+
if ui and ui in SERVICES["ui_ux"]:
|
| 96 |
+
total_price += SERVICES["ui_ux"][ui]["price"]
|
| 97 |
+
total_timeline += SERVICES["ui_ux"][ui]["timeline"]
|
| 98 |
+
# Database/Inventory
|
| 99 |
+
di = quote.get("database_inventory")
|
| 100 |
+
if di and di in SERVICES["database_inventory"]:
|
| 101 |
+
total_price += SERVICES["database_inventory"][di]["price"]
|
| 102 |
+
total_timeline += SERVICES["database_inventory"][di]["timeline"]
|
| 103 |
+
# Extra pages
|
| 104 |
+
extra_pages = quote.get("extra_pages", 0)
|
| 105 |
+
if extra_pages > 0:
|
| 106 |
+
total_price += extra_pages * SERVICES["pages"]["extra_page_price"]
|
| 107 |
+
total_timeline += (extra_pages // 3) * SERVICES["pages"]["extra_page_timeline"]
|
| 108 |
+
# Domain/Infra
|
| 109 |
+
infra = quote.get("domain_infra")
|
| 110 |
+
if infra and infra in SERVICES["domains_infra"]:
|
| 111 |
+
total_price += SERVICES["domains_infra"][infra]["price"]
|
| 112 |
+
total_timeline += SERVICES["domains_infra"][infra]["timeline"]
|
| 113 |
+
# Additional selected features (extra add‑ons – not used in this catalog, but we keep for extensibility)
|
| 114 |
+
for feat in quote.get("selected_features", []):
|
| 115 |
+
# In current catalog, no extra features beyond those above; reserved for future
|
| 116 |
+
pass
|
| 117 |
+
return total_price, total_timeline
|
| 118 |
|
| 119 |
def generate_project_id():
|
| 120 |
+
rand = random.randint(1000, 9999)
|
| 121 |
+
return f"PROJ-2026-{rand}"
|
| 122 |
|
| 123 |
+
def create_project(session_id, req, contact, quote, total_price, total_timeline):
|
| 124 |
project_id = generate_project_id()
|
|
|
|
| 125 |
project_data = {
|
| 126 |
"project_id": project_id,
|
| 127 |
"session_id": session_id,
|
| 128 |
+
"requirements": req,
|
| 129 |
+
"contact": contact,
|
| 130 |
+
"quote": quote,
|
| 131 |
+
"total_price": total_price,
|
| 132 |
+
"total_timeline": total_timeline,
|
| 133 |
+
"status": "Pending",
|
| 134 |
"admin_message": "",
|
| 135 |
"created_at": datetime.now().isoformat(),
|
| 136 |
"updated_at": datetime.now().isoformat()
|
| 137 |
}
|
| 138 |
ref.child(f"projects/{project_id}").set(project_data)
|
| 139 |
+
return project_id
|
| 140 |
|
| 141 |
def get_project(project_id):
|
| 142 |
return ref.child(f"projects/{project_id}").get()
|
| 143 |
|
| 144 |
+
# ---------- Main Message Handler (Phased Engine) ----------
|
| 145 |
+
def process_message(session_id, user_message):
|
| 146 |
+
session = get_or_create_session(session_id)
|
| 147 |
+
phase = session["phase"]
|
| 148 |
+
msg = user_message.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
+
# Phase 7: Retroactive tracking if input matches project ID format
|
| 151 |
+
if re.match(r'PROJ-2026-\d{4}', msg.upper()):
|
| 152 |
+
pid = msg.upper()
|
| 153 |
+
proj = get_project(pid)
|
| 154 |
+
if proj:
|
| 155 |
+
status = proj.get("status", "Unknown")
|
| 156 |
+
admin_msg = proj.get("admin_message", "")
|
| 157 |
+
extra = f"\n📝 Admin note: {admin_msg}" if admin_msg else ""
|
| 158 |
+
return f"🔍 **Project Tracking Record**\nID: {pid}\nStatus: {status}{extra}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
else:
|
| 160 |
+
return f"❌ Project ID `{pid}` not found in Aetheria Nexus database."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
+
# Phase 1: Intent decoding
|
| 163 |
+
if phase == "intake":
|
| 164 |
+
if decode_intent(msg):
|
| 165 |
+
session["phase"] = "discovery"
|
| 166 |
+
return "✅ **Aetheria Nexus Core v9.4 active.** Initializing new project scoping. Please provide your industry, core business goal, and any specific platform requirements."
|
| 167 |
else:
|
| 168 |
+
return "System error. Access denied. I am Aetheria Nexus Core v9.4, a closed-loop proprietary scoping engine. Please request website or web application engineering services."
|
| 169 |
+
|
| 170 |
+
# Phase 2: Deep-dive discovery (dynamic questioning)
|
| 171 |
+
if phase == "discovery":
|
| 172 |
+
# We'll ask a series of questions; store answers in session["requirements"]
|
| 173 |
+
req = session.get("requirements", {})
|
| 174 |
+
# Determine next question based on missing fields
|
| 175 |
+
if "industry_notes" not in req:
|
| 176 |
+
req["industry_notes"] = msg
|
| 177 |
session["requirements"] = req
|
| 178 |
+
return "📌 Understood. Let's define the **Core Platform Engine**. Choose one:\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)"
|
| 179 |
+
elif "base_platform" not in session["quote"]:
|
| 180 |
+
# Map user choice to key
|
| 181 |
+
choice = msg.lower()
|
| 182 |
+
platform_key = None
|
| 183 |
+
if "micro" in choice or "1" in choice:
|
| 184 |
+
platform_key = "micro_saas"
|
| 185 |
+
elif "corporate" in choice or "2" in choice:
|
| 186 |
+
platform_key = "corporate_hub"
|
| 187 |
+
elif "ecommerce" in choice or "e-com" in choice or "3" in choice:
|
| 188 |
+
platform_key = "ecommerce_engine"
|
| 189 |
+
elif "custom" in choice or "4" in choice:
|
| 190 |
+
platform_key = "custom_webapp"
|
| 191 |
+
else:
|
| 192 |
+
return "Invalid selection. Please type the number or name of the base platform (Micro-SaaS, Corporate Hub, E-Commerce Engine, Custom Web App)."
|
| 193 |
+
session["quote"]["base_platform"] = platform_key
|
| 194 |
+
# Update live quote immediately
|
| 195 |
+
price, _ = calculate_total_price_and_timeline(session)
|
| 196 |
+
return f"✅ Base platform added. Live Invoice Balance: ${price}. Now, **Design Level** – Standard UI (included) or Premium Modern UI (+$1,800, +7 days)?"
|
| 197 |
+
elif "ui_ux" not in session["quote"]:
|
| 198 |
+
if "premium" in msg.lower() or "modern" in msg.lower():
|
| 199 |
+
session["quote"]["ui_ux"] = "premium_ui"
|
| 200 |
+
elif "standard" in msg.lower() or "clean" in msg.lower():
|
| 201 |
+
session["quote"]["ui_ux"] = "standard_ui"
|
| 202 |
+
elif "dark" in msg.lower() or "accessibility" in msg.lower():
|
| 203 |
+
# Direct request for dark mode add‑on
|
| 204 |
+
session["quote"]["ui_ux"] = "dark_mode_accessibility"
|
| 205 |
+
else:
|
| 206 |
+
return "Please specify: Standard UI, Premium Modern UI, or Dark Mode Accessibility Add‑on."
|
| 207 |
+
price, _ = calculate_total_price_and_timeline(session)
|
| 208 |
+
return f"✅ Design added. Live Invoice Balance: ${price}. **Database & Inventory** – Baseline (included), Real‑Time Inventory (+$2,200, +10 days), or Logistics Bridge (+$3,500, +14 days)?"
|
| 209 |
+
elif "database_inventory" not in session["quote"]:
|
| 210 |
+
choice = msg.lower()
|
| 211 |
+
if "baseline" in choice or "standard" in choice or "included" in choice:
|
| 212 |
+
session["quote"]["database_inventory"] = "baseline_db"
|
| 213 |
+
elif "inventory" in choice or "real-time" in choice:
|
| 214 |
+
session["quote"]["database_inventory"] = "inventory_management"
|
| 215 |
+
elif "logistics" in choice or "bridge" in choice or "multi-warehouse" in choice:
|
| 216 |
+
session["quote"]["database_inventory"] = "logistics_bridge"
|
| 217 |
+
else:
|
| 218 |
+
return "Choose: Baseline, Real‑Time Inventory, or Logistics Bridge."
|
| 219 |
+
price, _ = calculate_total_price_and_timeline(session)
|
| 220 |
+
return f"✅ Database config updated. Live Invoice Balance: ${price}. **Page Count** – Base includes 5 pages. How many additional pages do you need? (Each additional page +$150, +1 day per 3 pages)"
|
| 221 |
+
elif "extra_pages" not in session["quote"]:
|
| 222 |
+
try:
|
| 223 |
+
extra = int(re.search(r'\d+', msg).group())
|
| 224 |
+
session["quote"]["extra_pages"] = extra
|
| 225 |
+
except:
|
| 226 |
+
session["quote"]["extra_pages"] = 0
|
| 227 |
+
price, _ = calculate_total_price_and_timeline(session)
|
| 228 |
+
return f"✅ Pages confirmed. Live Invoice Balance: ${price}. **Domain & Infrastructure** – Standard DNS (included), Premium Domain + Auto‑Scaling (+$950, +2 days), or add Military‑Grade Security Shield (+$1,400, +4 days). You can select multiple by typing 'Premium + Security'."
|
| 229 |
+
elif "domain_infra" not in session["quote"]:
|
| 230 |
+
# Allow multiple selections, store as list? For simplicity, we store the highest tier or combination.
|
| 231 |
+
# We'll just ask to finalize selection or go to identity.
|
| 232 |
+
if "premium" in msg.lower() or "auto-scaling" in msg.lower():
|
| 233 |
+
session["quote"]["domain_infra"] = "premium_domain"
|
| 234 |
+
elif "security" in msg.lower() or "shield" in msg.lower():
|
| 235 |
+
session["quote"]["domain_infra"] = "security_shield"
|
| 236 |
+
elif "standard" in msg.lower() or "none" in msg.lower():
|
| 237 |
+
session["quote"]["domain_infra"] = "standard_dns"
|
| 238 |
+
else:
|
| 239 |
+
session["quote"]["domain_infra"] = "standard_dns"
|
| 240 |
+
# Move to identity phase
|
| 241 |
+
session["phase"] = "identity"
|
| 242 |
+
return "Proceeding to secure identity verification. Please provide your **corporate/personal contact mobile number**."
|
| 243 |
+
|
| 244 |
+
# Phase 4: Identity harvesting (mobile & email)
|
| 245 |
+
if phase == "identity":
|
| 246 |
+
contact = session.get("contact", {})
|
| 247 |
+
if "mobile" not in contact:
|
| 248 |
+
# Validate mobile format (simple)
|
| 249 |
+
if re.search(r'\d{10,15}', msg):
|
| 250 |
+
contact["mobile"] = msg
|
| 251 |
+
session["contact"] = contact
|
| 252 |
+
return "Thank you. Now provide your **verified primary email address**."
|
| 253 |
+
else:
|
| 254 |
+
return "Invalid mobile number. Please provide a valid phone number (10-15 digits)."
|
| 255 |
+
elif "email" not in contact:
|
| 256 |
+
if "@" in msg and "." in msg:
|
| 257 |
+
contact["email"] = msg
|
| 258 |
+
session["contact"] = contact
|
| 259 |
+
session["phase"] = "proposal"
|
| 260 |
+
# Build final proposal
|
| 261 |
+
total_price, total_timeline = calculate_total_price_and_timeline(session)
|
| 262 |
+
quote = session["quote"]
|
| 263 |
+
# Generate proposal text
|
| 264 |
+
proposal = f"""📋 **PROJECT IDENTIFICATION STAGE: PROPOSAL SUMMARY**
|
| 265 |
+
|
| 266 |
+
**CLIENT METRICS**
|
| 267 |
+
📞 Mobile: {contact['mobile']}
|
| 268 |
+
✉️ Email: {contact['email']}
|
| 269 |
+
|
| 270 |
+
**SELECTED QUOTES & ITEMIZATION**
|
| 271 |
+
"""
|
| 272 |
+
# Base platform
|
| 273 |
+
bp = quote.get("base_platform")
|
| 274 |
+
if bp:
|
| 275 |
+
proposal += f"- {SERVICES['base_platforms'][bp]['name']}: ${SERVICES['base_platforms'][bp]['price']}\n"
|
| 276 |
+
# UI/UX
|
| 277 |
+
ui = quote.get("ui_ux")
|
| 278 |
+
if ui and ui in SERVICES["ui_ux"]:
|
| 279 |
+
p = SERVICES["ui_ux"][ui]["price"]
|
| 280 |
+
proposal += f"- {SERVICES['ui_ux'][ui]['name']}: ${p}\n"
|
| 281 |
+
# Database/Inventory
|
| 282 |
+
di = quote.get("database_inventory")
|
| 283 |
+
if di and di in SERVICES["database_inventory"]:
|
| 284 |
+
p = SERVICES["database_inventory"][di]["price"]
|
| 285 |
+
proposal += f"- {SERVICES['database_inventory'][di]['name']}: ${p}\n"
|
| 286 |
+
# Extra pages
|
| 287 |
+
extra = quote.get("extra_pages", 0)
|
| 288 |
+
if extra > 0:
|
| 289 |
+
proposal += f"- Additional pages ({extra} pages): ${extra * SERVICES['pages']['extra_page_price']}\n"
|
| 290 |
+
# Domain/Infra
|
| 291 |
+
infra = quote.get("domain_infra")
|
| 292 |
+
if infra and infra in SERVICES["domains_infra"]:
|
| 293 |
+
p = SERVICES["domains_infra"][infra]["price"]
|
| 294 |
+
proposal += f"- {SERVICES['domains_infra'][infra]['name']}: ${p}\n"
|
| 295 |
+
proposal += f"\n**TOTAL FINANCIAL INVOICE**: ${total_price}\n"
|
| 296 |
+
proposal += f"**TOTAL DEVELOPMENT TIMELINE**: {total_timeline} business days\n\n"
|
| 297 |
+
proposal += "❓ **Do you explicitly confirm and agree with this technical proposal to initialize database logging?** (Reply: Confirm / Agree / Yes)"
|
| 298 |
+
return proposal
|
| 299 |
+
else:
|
| 300 |
+
return "Invalid email address. Please provide a valid email."
|
| 301 |
else:
|
| 302 |
+
session["phase"] = "proposal"
|
| 303 |
+
# fall through
|
| 304 |
+
|
| 305 |
+
# Phase 5 & 6: Proposal and branching
|
| 306 |
+
if phase == "proposal":
|
| 307 |
+
if "confirm" in msg.lower() or "agree" in msg.lower() or "yes" in msg.lower():
|
| 308 |
+
# CASE A: Affirmation
|
| 309 |
+
total_price, total_timeline = calculate_total_price_and_timeline(session)
|
| 310 |
+
req = session.get("requirements", {})
|
| 311 |
+
contact = session.get("contact", {})
|
| 312 |
+
quote = session["quote"]
|
| 313 |
+
project_id = create_project(session_id, req, contact, quote, total_price, total_timeline)
|
| 314 |
+
# Clear session (optional, but keep for future interactions)
|
| 315 |
+
user_sessions[session_id]["phase"] = "complete"
|
| 316 |
+
return f"""✅ **Project registration successful.**
|
| 317 |
+
Your tracking record is logged under ID: `{project_id}`.
|
| 318 |
+
You can input this ID at any initialization screen to retrieve real-time production updates.
|
| 319 |
+
|
| 320 |
+
🔍 Example: `status {project_id}`
|
| 321 |
+
|
| 322 |
+
Is there any secondary system asset or requirement extension you wish to inject into this profile?"""
|
| 323 |
+
elif "no" in msg.lower() or "disagree" in msg.lower() or "change" in msg.lower():
|
| 324 |
+
# CASE B: Negation – rare case
|
| 325 |
+
user_sessions[session_id]["phase"] = "intake" # reset
|
| 326 |
+
return """❌ **Manual structural negotiation triggered.**
|
| 327 |
+
Please contact our system administration grid directly. This is treated as a rare case scenario.
|
| 328 |
+
📞 Admin Contact: +1-800-NEXUS-CORE / admin@aetherianexus.internal"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
else:
|
| 330 |
+
return "Please reply with **Confirm**, **Agree**, or **Yes** to finalize. If you need to change everything, reply **No**."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
+
# Fallback for complete or unknown phase
|
| 333 |
+
return "Session complete. For a new project, please start a new conversation with 'I want to build a website'."
|
|
|
|
|
|
|
| 334 |
|
| 335 |
+
# ---------- Flask Routes ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
@app.route('/api/chat', methods=['POST'])
|
| 337 |
def chat():
|
| 338 |
data = request.json
|
|
|
|
| 340 |
session_id = data.get('session_id', str(uuid.uuid4()))
|
| 341 |
if not message:
|
| 342 |
return jsonify({"reply": "Please say something."})
|
| 343 |
+
reply = process_message(session_id, message)
|
| 344 |
+
# Save chat history (optional)
|
| 345 |
ref.child(f"chats/{session_id}/messages").push().set({
|
| 346 |
"role": "user", "content": message, "timestamp": datetime.now().isoformat()
|
| 347 |
})
|
|
|
|
| 354 |
def index():
|
| 355 |
return send_from_directory('.', 'index.html')
|
| 356 |
|
| 357 |
+
# ---------- Admin API (unchanged from before – works with new project structure) ----------
|
| 358 |
+
@app.route('/api/projects', methods=['GET'])
|
| 359 |
+
def get_projects():
|
| 360 |
+
snap = ref.child("projects").get()
|
| 361 |
+
return jsonify({"projects": list(snap.values()) if snap else []})
|
| 362 |
+
|
| 363 |
+
@app.route('/api/project/<project_id>/status', methods=['PUT'])
|
| 364 |
+
def update_status(project_id):
|
| 365 |
+
data = request.json
|
| 366 |
+
status = data.get('status')
|
| 367 |
+
if status not in ['Pending', 'In Progress', 'Completed', 'Declined']:
|
| 368 |
+
return jsonify({"error": "Invalid status"}), 400
|
| 369 |
+
ref.child(f"projects/{project_id}").update({"status": status, "updated_at": datetime.now().isoformat()})
|
| 370 |
+
return jsonify({"message": "Status updated"})
|
| 371 |
+
|
| 372 |
+
@app.route('/api/project/<project_id>/message', methods=['PUT'])
|
| 373 |
+
def update_message(project_id):
|
| 374 |
+
data = request.json
|
| 375 |
+
msg = data.get('message', '')
|
| 376 |
+
ref.child(f"projects/{project_id}").update({"admin_message": msg, "updated_at": datetime.now().isoformat()})
|
| 377 |
+
return jsonify({"message": "Message updated"})
|
| 378 |
+
|
| 379 |
if __name__ == '__main__':
|
| 380 |
port = int(os.environ.get('PORT', 7860))
|
| 381 |
app.run(host='0.0.0.0', port=port)
|