Ahmad140 commited on
Commit
e22db78
·
verified ·
1 Parent(s): 165d1c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -233
app.py CHANGED
@@ -21,7 +21,7 @@ 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},
@@ -42,7 +42,7 @@ SERVICES = {
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},
@@ -51,81 +51,74 @@ SERVICES = {
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,
@@ -138,199 +131,161 @@ def create_project(session_id, req, contact, quote, total_price, total_timeline)
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'])
@@ -341,7 +296,7 @@ def chat():
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,7 +309,6 @@ def chat():
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()
 
21
  ref = firebase_admin.db.reference('/')
22
  print("✅ Firebase connected (Aetheria Nexus Core v9.4)")
23
 
24
+ # ---------- Immutable Service Catalog ----------
25
  SERVICES = {
26
  "base_platforms": {
27
  "micro_saas": {"name": "Micro-SaaS Platform (Single Function Portal)", "price": 4500, "timeline": 21},
 
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},
 
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
+ def start_new_session(session_id):
71
+ user_sessions[session_id] = {
72
+ "step_idx": 0,
73
+ "requirements": {},
74
+ "contact": {},
75
+ "quote": {
76
+ "base_platform": None,
77
+ "ui_ux": None,
78
+ "database_inventory": None,
79
+ "extra_pages": 0,
80
+ "domain_infra": None
 
 
 
 
81
  }
82
+ }
83
+ return STEPS[0][1]
84
 
85
+ def calculate_total_price_and_timeline(session):
86
+ quote = session["quote"]
87
  total_price = 0
88
  total_timeline = 0
 
89
  bp = quote.get("base_platform")
90
+ if bp:
91
  total_price += SERVICES["base_platforms"][bp]["price"]
92
  total_timeline += SERVICES["base_platforms"][bp]["timeline"]
 
93
  ui = quote.get("ui_ux")
94
+ if ui:
95
  total_price += SERVICES["ui_ux"][ui]["price"]
96
  total_timeline += SERVICES["ui_ux"][ui]["timeline"]
 
97
  di = quote.get("database_inventory")
98
+ if di:
99
  total_price += SERVICES["database_inventory"][di]["price"]
100
  total_timeline += SERVICES["database_inventory"][di]["timeline"]
101
+ extra = quote.get("extra_pages", 0)
102
+ if extra:
103
+ total_price += extra * SERVICES["pages"]["extra_page_price"]
104
+ total_timeline += (extra // 3) * SERVICES["pages"]["extra_page_timeline"]
 
 
105
  infra = quote.get("domain_infra")
106
+ if infra:
107
+ if isinstance(infra, list):
108
+ for item in infra:
109
+ total_price += SERVICES["domains_infra"][item]["price"]
110
+ total_timeline += SERVICES["domains_infra"][item]["timeline"]
111
+ else:
112
+ total_price += SERVICES["domains_infra"][infra]["price"]
113
+ total_timeline += SERVICES["domains_infra"][infra]["timeline"]
114
  return total_price, total_timeline
115
 
116
+ def create_project(session_id, requirements, contact, quote, total_price, total_timeline):
117
+ project_id = f"PROJ-2026-{random.randint(1000, 9999)}"
 
 
 
 
118
  project_data = {
119
  "project_id": project_id,
120
  "session_id": session_id,
121
+ "requirements": requirements,
122
  "contact": contact,
123
  "quote": quote,
124
  "total_price": total_price,
 
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
+ # Start new project if user says so
149
+ if any(phrase in user_message.lower() for phrase in ["want to build a website", "new project", "start project"]):
150
+ if session_id in user_sessions:
151
+ del user_sessions[session_id]
152
+ return start_new_session(session_id)
153
+
154
+ # If no session exists, start one
155
+ if session_id not in user_sessions:
156
+ return start_new_session(session_id)
157
 
158
+ session = user_sessions[session_id]
159
+ step_idx = session["step_idx"]
160
+ if step_idx >= len(STEPS):
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
+ Is there any secondary asset or requirement you wish to inject?"""
178
+ elif "no" in user_message.lower() or "cancel" in user_message.lower():
179
+ del user_sessions[session_id]
180
+ return "❌ Manual structural negotiation triggered. Contact admin: +1-800-NEXUS-CORE / admin@aetherianexus.internal"
181
  else:
182
+ return "Please confirm with **Confirm**, **Yes**, or **Agree**. If you disagree, reply **No**."
183
 
184
+ current_step_key, current_question = STEPS[step_idx]
185
+ answer = user_message.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
187
+ # Process and store the answer
188
+ if current_step_key == "industry":
189
+ session["requirements"]["industry_notes"] = answer
190
+ elif current_step_key == "base_platform":
191
+ choice = answer.lower()
192
+ if "micro" in choice or "1" in choice:
193
+ session["quote"]["base_platform"] = "micro_saas"
194
+ elif "corporate" in choice or "2" in choice:
195
+ session["quote"]["base_platform"] = "corporate_hub"
196
+ elif "ecommerce" in choice or "e-com" in choice or "3" in choice:
197
+ session["quote"]["base_platform"] = "ecommerce_engine"
198
+ elif "custom" in choice or "4" in choice:
199
+ session["quote"]["base_platform"] = "custom_webapp"
200
+ else:
201
+ return "Invalid selection. Please type the number or name (1‑4)."
202
+ elif current_step_key == "ui_ux":
203
+ choice = answer.lower()
204
+ if "premium" in choice or "modern" in choice:
205
+ session["quote"]["ui_ux"] = "premium_ui"
206
+ elif "dark" in choice or "accessibility" in choice:
207
+ session["quote"]["ui_ux"] = "dark_mode_accessibility"
208
+ else:
209
+ session["quote"]["ui_ux"] = "standard_ui"
210
+ elif current_step_key == "database_inventory":
211
+ choice = answer.lower()
212
+ if "inventory" in choice or "real-time" in choice:
213
+ session["quote"]["database_inventory"] = "inventory_management"
214
+ elif "logistics" in choice or "bridge" in choice:
215
+ session["quote"]["database_inventory"] = "logistics_bridge"
216
+ else:
217
+ session["quote"]["database_inventory"] = "baseline_db"
218
+ elif current_step_key == "extra_pages":
219
+ try:
220
+ extra = int(re.search(r'\d+', answer).group())
221
+ session["quote"]["extra_pages"] = max(0, extra)
222
+ except:
223
+ session["quote"]["extra_pages"] = 0
224
+ elif current_step_key == "domain_infra":
225
+ if "premium" in answer.lower() and "security" in answer.lower():
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
+ session["quote"]["domain_infra"] = "standard_dns"
233
+ elif current_step_key == "mobile":
234
+ if re.search(r'\d{10,15}', answer):
235
+ session["contact"]["mobile"] = answer
236
+ else:
237
+ return "Invalid mobile number. Please provide a valid phone number (10‑15 digits)."
238
+ elif current_step_key == "email":
239
+ if "@" in answer and "." in answer:
240
+ session["contact"]["email"] = answer
241
+ else:
242
+ return "Invalid email address. Please provide a valid email."
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'])
 
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
  })
 
309
  def index():
310
  return send_from_directory('.', 'index.html')
311
 
 
312
  @app.route('/api/projects', methods=['GET'])
313
  def get_projects():
314
  snap = ref.child("projects").get()