Ahmad140 commited on
Commit
6766d93
·
verified ·
1 Parent(s): 8affac6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -90
app.py CHANGED
@@ -5,7 +5,7 @@ import requests
5
  import os
6
  import json
7
  from datetime import datetime
8
- from sentence_transformers import SentenceTransformer, util
9
  import uuid
10
  import re
11
 
@@ -14,7 +14,7 @@ app = Flask(__name__)
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 set karo.")
18
  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)
@@ -22,31 +22,24 @@ firebase_admin.initialize_app(cred, {'databaseURL': database_url})
22
  ref = db.reference('/')
23
  print("✅ Firebase connected")
24
 
25
- # ---------- Sentence-Transformer ----------
26
- print("🔄 Loading sentence-transformers...")
27
- embedding_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
28
  print("✅ Embedding model loaded")
29
 
30
  # ---------- Helper: Load extra services from Firebase ----------
31
  def get_extra_services():
32
  snap = ref.child("extra_services").get()
33
  if not snap:
34
- # Default services if empty
35
  default = {
36
  "live_chat": {"name": "live chat", "price": 20000, "timeline": 3, "display": "Live Chat (+PKR 20,000, +3 days)"},
37
  "booking_system": {"name": "booking system", "price": 35000, "timeline": 5, "display": "Booking System (+PKR 35,000, +5 days)"},
38
  "multi_language": {"name": "multi-language", "price": 25000, "timeline": 4, "display": "Multi-Language (+PKR 25,000, +4 days)"},
39
- "custom_backend": {"name": "custom backend", "price": 100000, "timeline": 15, "display": "Custom Backend (+PKR 1,00,000, +15 days)"},
40
- "seo_advanced": {"name": "seo advanced", "price": 30000, "timeline": 7, "display": "Advanced SEO (+PKR 30,000, +7 days)"},
41
- "maintenance_plan": {"name": "maintenance plan", "price": 15000, "timeline": 0, "display": "Maintenance Plan (+PKR 15,000/month)"}
42
  }
43
  ref.child("extra_services").set(default)
44
  return default
45
  return snap
46
 
47
- # ---------- User Sessions ----------
48
- user_sessions = {}
49
-
50
  # ---------- Pricing Helpers ----------
51
  BASE_PRICE = 50000
52
  BASE_PAGES = 5
@@ -61,12 +54,11 @@ def calculate_price_and_timeline(req):
61
  chatbot = req.get("chatbot", False)
62
  seo = req.get("seo", False)
63
  extra_features = req.get("extra_features", [])
64
-
65
  price = BASE_PRICE
66
  timeline = BASE_TIMELINE
67
  if pages > BASE_PAGES:
68
  price += (pages - BASE_PAGES) * EXTRA_PAGE_PRICE
69
- timeline += (pages - BASE_PAGES) * 1
70
  if domain:
71
  price += 5000
72
  timeline += 1
@@ -118,37 +110,38 @@ def update_project_status(project_id, status, decline_reason=None):
118
  def update_project_message(project_id, message):
119
  ref.child(f"projects/{project_id}").update({"admin_message": message, "updated_at": datetime.now().isoformat()})
120
 
121
- # ---------- Step Builder Logic (with dynamic extra services) ----------
 
 
122
  def is_start_project_request(text):
123
- keywords = ["website banwani", "build website", "new project", "website chahiye", "start project",
124
  "i want to build a website", "web project", "website banana hai", "naya project"]
125
  return any(k in text.lower() for k in keywords)
126
 
127
  def process_step_by_step(session_id, message):
128
  msg_lower = message.lower().strip()
129
-
130
  if session_id not in user_sessions:
131
  if is_start_project_request(message):
132
  user_sessions[session_id] = {"step": "asking_domain", "requirements": {}}
133
  return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
134
  return None
135
-
136
  session = user_sessions[session_id]
137
  step = session.get("step")
138
  req = session.get("requirements", {})
139
-
140
- if msg_lower in ["add more", "add something", "extra add", "kuch aur add karo"]:
141
  session["step"] = "asking_extra"
142
  extra_services = get_extra_services()
143
- extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for k, v in extra_services.items()])
144
- return f"✨ **Add extra features or services**\n\nAvailable:\n{extra_list}\n\nType the name of the feature you want (e.g., 'live chat') or type **done** to finish."
145
-
146
  if step == "asking_domain":
147
  req["domain"] = "yes" in msg_lower or "han" in msg_lower
148
  session["step"] = "asking_pages"
149
  session["requirements"] = req
150
- return "📄 **How many pages do you need?** (Minimum 5, extra pages +PKR 5,000 each)\n\nType a number like: **5**, **10**, **15**"
151
-
152
  elif step == "asking_pages":
153
  try:
154
  pages = int(re.search(r'\d+', msg_lower).group())
@@ -157,31 +150,31 @@ def process_step_by_step(session_id, message):
157
  req["pages"] = 5
158
  session["step"] = "asking_ecommerce"
159
  session["requirements"] = req
160
- return "🛒 **Do you need e‑commerce functionality?** (Shopping cart, payment gateway)\n\nReply: **Yes** or **No**"
161
-
162
  elif step == "asking_ecommerce":
163
  req["ecommerce"] = "yes" in msg_lower or "han" in msg_lower
164
  session["step"] = "asking_chatbot"
165
  session["requirements"] = req
166
- return "🤖 **Do you want an AI chatbot on your website?**\n\nReply: **Yes** or **No**"
167
-
168
  elif step == "asking_chatbot":
169
  req["chatbot"] = "yes" in msg_lower or "han" in msg_lower
170
  session["step"] = "asking_seo"
171
  session["requirements"] = req
172
- return "🔍 **Do you need SEO optimization?** (To rank on Google)\n\nReply: **Yes** or **No**"
173
-
174
  elif step == "asking_seo":
175
  req["seo"] = "yes" in msg_lower or "han" in msg_lower
176
  session["step"] = "asking_extra"
177
  session["requirements"] = req
178
  extra_services = get_extra_services()
179
- extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for k, v in extra_services.items()])
180
- return f"✨ **Any extra features or services?**\n\nAvailable:\n{extra_list}\n\nType the name of the feature (e.g., 'live chat') or **none** / **done** to finish."
181
-
182
  elif step == "asking_extra":
183
  extra_services = get_extra_services()
184
- if msg_lower in ["none", "done", "no", "nahi"]:
185
  price, timeline = calculate_price_and_timeline(req)
186
  session["step"] = "confirm"
187
  session["requirements"] = req
@@ -189,22 +182,21 @@ def process_step_by_step(session_id, message):
189
  extra_display = ", ".join(extra_names) if extra_names else "None"
190
  return f"""📋 **Your Project Proposal**
191
 
192
- ✅ **Requirements Summary:**
193
  • Domain: {'Yes' if req.get('domain') else 'No'}
194
  • Pages: {req.get('pages', 5)}
195
- • E-commerce: {'Yes' if req.get('ecommerce') else 'No'}
196
- • AI Chatbot: {'Yes' if req.get('chatbot') else 'No'}
197
  • SEO: {'Yes' if req.get('seo') else 'No'}
198
- • Extra features: {extra_display}
199
 
200
  💰 **Total Cost:** PKR {price:,}
201
- ⏱️ **Estimated Timeline:** {timeline} working days
202
 
203
- ❓ **Do you agree with this proposal?** (Reply: **Confirm** or **Cancel**)
204
 
205
- ⚠️ *If you disagree or want to add more, type 'add more'*"""
206
  else:
207
- # Match feature by name (case-insensitive)
208
  matched_key = None
209
  for key, val in extra_services.items():
210
  if val.get("name", "").lower() in msg_lower or msg_lower in val.get("name", "").lower():
@@ -216,55 +208,78 @@ def process_step_by_step(session_id, message):
216
  extra_list.append(matched_key)
217
  req["extra_features"] = extra_list
218
  session["requirements"] = req
219
- return f"✅ Added **{extra_services[matched_key]['name']}** to your project.\n\nAny other extras? Type the name or **done** to finish."
220
  else:
221
- return f"ℹ️ **{extra_services[matched_key]['name']}** is already added. Type another feature name or **done**."
222
  else:
223
- return f"❌ Sorry, **'{message}'** is not a service we provide. Our available extras: {', '.join([v['name'] for v in extra_services.values()])}\n\nType a valid feature name or **done**."
224
-
225
  elif step == "confirm":
226
  if "confirm" in msg_lower or "agree" in msg_lower:
227
  project_id, price, timeline = create_project(session_id, req)
228
  del user_sessions[session_id]
229
  return f"""✅ **Project Confirmed!**
230
 
231
- Your Project ID: `{project_id}`
232
-
233
- 📌 **Use this ID to check your project status anytime.**
234
- Type: `status {project_id}`
235
 
236
- 💰 Total Cost: PKR {price:,}
237
- ⱏ️ Timeline: {timeline} working days
238
-
239
- Our team will contact you within 24 hours.
240
- Thank you for choosing Elite Visuals! 🚀"""
241
  elif "cancel" in msg_lower:
242
  del user_sessions[session_id]
243
- return "❌ Project cancelled. If you change your mind, just say **'I want to build a website'** again.\n\n📞 For special requests, contact admin: +92 300 1234567"
244
  elif "add more" in msg_lower:
245
  session["step"] = "asking_extra"
246
  extra_services = get_extra_services()
247
- extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for k, v in extra_services.items()])
248
- return f"✨ **Add more extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
249
  else:
250
- return "Please reply **Confirm** to proceed, **Cancel** to cancel, or **add more** to add extra features."
251
-
252
  return None
253
 
254
- # ---------- Existing Intent & Response (shortened for brevity, same as before) ----------
255
- # ... (keep the rest of your existing functions: classify_intent, get_response_and_data, etc.)
256
- # I'll include the minimal needed for completion, but you should keep your full existing code.
257
- # For brevity, I'm showing only new/changed parts. In final deployment, merge with your previous code.
 
 
 
 
 
 
258
 
259
- # ====== Placeholder for existing code (classify_intent, get_response_and_data, call_openrouter, etc.) ======
260
- # You already have these functions; keep them unchanged. I'll not duplicate them here.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
 
262
- # ---------- API Routes (including admin endpoints) ----------
263
- @app.route('/api/chat', methods=['POST'])
264
- def chat():
265
- # same as before – uses get_final_response which includes step builder
266
- pass # actual implementation you already have
 
 
267
 
 
268
  @app.route('/api/projects', methods=['GET'])
269
  def get_projects():
270
  snap = ref.child("projects").get()
@@ -283,8 +298,8 @@ def update_status(project_id):
283
  @app.route('/api/project/<project_id>/message', methods=['PUT'])
284
  def update_message(project_id):
285
  data = request.json
286
- message = data.get('message', '')
287
- update_project_message(project_id, message)
288
  return jsonify({"message": "Message updated"})
289
 
290
  @app.route('/api/services', methods=['GET'])
@@ -297,41 +312,59 @@ def add_service():
297
  data = request.json
298
  key = data.get('key')
299
  name = data.get('name')
300
- price = data.get('price')
301
- timeline = data.get('timeline')
302
  if not key or not name:
303
  return jsonify({"error": "Missing key or name"}), 400
304
- new_service = {
305
  "name": name,
306
- "price": int(price) if price else 0,
307
- "timeline": int(timeline) if timeline else 0,
308
- "display": f"{name} (+PKR {int(price):,}, +{int(timeline)} days)"
309
  }
310
- ref.child(f"extra_services/{key}").set(new_service)
311
- return jsonify({"message": "Service added", "service": new_service})
312
 
313
  @app.route('/api/services/<key>', methods=['PUT'])
314
  def update_service(key):
315
  data = request.json
316
  name = data.get('name')
317
- price = data.get('price')
318
- timeline = data.get('timeline')
319
  if not name:
320
  return jsonify({"error": "Missing name"}), 400
321
- updated = {
322
  "name": name,
323
- "price": int(price) if price else 0,
324
- "timeline": int(timeline) if timeline else 0,
325
- "display": f"{name} (+PKR {int(price):,}, +{int(timeline)} days)"
326
  }
327
- ref.child(f"extra_services/{key}").update(updated)
328
- return jsonify({"message": "Service updated", "service": updated})
329
 
330
  @app.route('/api/services/<key>', methods=['DELETE'])
331
  def delete_service(key):
332
  ref.child(f"extra_services/{key}").delete()
333
  return jsonify({"message": "Service deleted"})
334
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
335
  @app.route('/')
336
  def index():
337
  return send_from_directory('.', 'index.html')
 
5
  import os
6
  import json
7
  from datetime import datetime
8
+ from sentence_transformers import SentenceTransformer
9
  import uuid
10
  import re
11
 
 
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")
18
  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)
 
22
  ref = db.reference('/')
23
  print("✅ Firebase connected")
24
 
25
+ # ---------- Sentence-Transformer (for intent, not strictly needed now) ----------
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
 
54
  chatbot = req.get("chatbot", False)
55
  seo = req.get("seo", False)
56
  extra_features = req.get("extra_features", [])
 
57
  price = BASE_PRICE
58
  timeline = BASE_TIMELINE
59
  if pages > BASE_PAGES:
60
  price += (pages - BASE_PAGES) * EXTRA_PAGE_PRICE
61
+ timeline += (pages - BASE_PAGES)
62
  if domain:
63
  price += 5000
64
  timeline += 1
 
110
  def update_project_message(project_id, message):
111
  ref.child(f"projects/{project_id}").update({"admin_message": message, "updated_at": datetime.now().isoformat()})
112
 
113
+ # ---------- User Sessions for Step Builder ----------
114
+ user_sessions = {}
115
+
116
  def is_start_project_request(text):
117
+ keywords = ["website banwani", "build website", "new project", "website chahiye", "start project",
118
  "i want to build a website", "web project", "website banana hai", "naya project"]
119
  return any(k in text.lower() for k in keywords)
120
 
121
  def process_step_by_step(session_id, message):
122
  msg_lower = message.lower().strip()
 
123
  if session_id not in user_sessions:
124
  if is_start_project_request(message):
125
  user_sessions[session_id] = {"step": "asking_domain", "requirements": {}}
126
  return "🌐 **Do you need a domain name?** (e.g., www.yourbusiness.com)\n\nReply: **Yes** or **No**"
127
  return None
128
+
129
  session = user_sessions[session_id]
130
  step = session.get("step")
131
  req = session.get("requirements", {})
132
+
133
+ if msg_lower in ["add more", "add something", "extra add"]:
134
  session["step"] = "asking_extra"
135
  extra_services = get_extra_services()
136
+ extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
137
+ return f"✨ **Add extra features**\n\nAvailable:\n{extra_list}\n\nType the name or **done**."
138
+
139
  if step == "asking_domain":
140
  req["domain"] = "yes" in msg_lower or "han" in msg_lower
141
  session["step"] = "asking_pages"
142
  session["requirements"] = req
143
+ return "📄 **How many pages?** (min 5, extra +PKR 5,000 each)\n\nType a number: **5**, **10**, **15**"
144
+
145
  elif step == "asking_pages":
146
  try:
147
  pages = int(re.search(r'\d+', msg_lower).group())
 
150
  req["pages"] = 5
151
  session["step"] = "asking_ecommerce"
152
  session["requirements"] = req
153
+ return "🛒 **Need e‑commerce?** (payment gateway, cart)\n\nReply: **Yes** or **No**"
154
+
155
  elif step == "asking_ecommerce":
156
  req["ecommerce"] = "yes" in msg_lower or "han" in msg_lower
157
  session["step"] = "asking_chatbot"
158
  session["requirements"] = req
159
+ return "🤖 **AI chatbot on your website?**\n\nReply: **Yes** or **No**"
160
+
161
  elif step == "asking_chatbot":
162
  req["chatbot"] = "yes" in msg_lower or "han" in msg_lower
163
  session["step"] = "asking_seo"
164
  session["requirements"] = req
165
+ return "🔍 **SEO optimization?** (rank on Google)\n\nReply: **Yes** or **No**"
166
+
167
  elif step == "asking_seo":
168
  req["seo"] = "yes" in msg_lower or "han" in msg_lower
169
  session["step"] = "asking_extra"
170
  session["requirements"] = req
171
  extra_services = get_extra_services()
172
+ extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
173
+ return f"✨ **Extra features?**\n\nAvailable:\n{extra_list}\n\nType name (e.g., 'live chat') or **done**."
174
+
175
  elif step == "asking_extra":
176
  extra_services = get_extra_services()
177
+ if msg_lower in ["none", "done", "no"]:
178
  price, timeline = calculate_price_and_timeline(req)
179
  session["step"] = "confirm"
180
  session["requirements"] = req
 
182
  extra_display = ", ".join(extra_names) if extra_names else "None"
183
  return f"""📋 **Your Project Proposal**
184
 
185
+ ✅ **Summary:**
186
  • Domain: {'Yes' if req.get('domain') else 'No'}
187
  • Pages: {req.get('pages', 5)}
188
+ • E‑commerce: {'Yes' if req.get('ecommerce') else 'No'}
189
+ • Chatbot: {'Yes' if req.get('chatbot') else 'No'}
190
  • SEO: {'Yes' if req.get('seo') else 'No'}
191
+ • Extras: {extra_display}
192
 
193
  💰 **Total Cost:** PKR {price:,}
194
+ ⏱️ **Timeline:** {timeline} working days
195
 
196
+ ❓ **Agree?** (Reply: **Confirm** or **Cancel**)
197
 
198
+ ⚠️ *To add more, type 'add more'*"""
199
  else:
 
200
  matched_key = None
201
  for key, val in extra_services.items():
202
  if val.get("name", "").lower() in msg_lower or msg_lower in val.get("name", "").lower():
 
208
  extra_list.append(matched_key)
209
  req["extra_features"] = extra_list
210
  session["requirements"] = req
211
+ return f"✅ Added **{extra_services[matched_key]['name']}**.\n\nAny other extras? Type name or **done**."
212
  else:
213
+ return f"ℹ️ Already added. Type another name or **done**."
214
  else:
215
+ return f"❌ Sorry, **'{message}'** is not offered. Available: {', '.join([v['name'] for v in extra_services.values()])}\n\nType a valid name or **done**."
216
+
217
  elif step == "confirm":
218
  if "confirm" in msg_lower or "agree" in msg_lower:
219
  project_id, price, timeline = create_project(session_id, req)
220
  del user_sessions[session_id]
221
  return f"""✅ **Project Confirmed!**
222
 
223
+ **Project ID:** `{project_id}`
224
+ **Total Cost:** PKR {price:,}
225
+ **Timeline:** {timeline} days
 
226
 
227
+ Use `status {project_id}` anytime.
228
+ We'll contact you soon. 🚀"""
 
 
 
229
  elif "cancel" in msg_lower:
230
  del user_sessions[session_id]
231
+ return "❌ Cancelled. Start again with 'I want to build a website'."
232
  elif "add more" in msg_lower:
233
  session["step"] = "asking_extra"
234
  extra_services = get_extra_services()
235
+ extra_list = "\n".join([f"{v['name']}: +PKR {v['price']:,}, +{v['timeline']} days" for v in extra_services.values()])
236
+ return f"✨ **Add more extras**\n\nAvailable:\n{extra_list}\n\nType name or **done**."
237
  else:
238
+ return "Please reply **Confirm**, **Cancel**, or **add more**."
239
+
240
  return None
241
 
242
+ # ---------- Package details (fallback for existing features) ----------
243
+ def package_details(query):
244
+ q = query.lower()
245
+ if "basic" in q:
246
+ return "**Basic Website** – PKR 50,000 (7-10 days)\n✅ 5 pages, responsive, basic SEO, contact form, social links."
247
+ if "standard" in q:
248
+ return "**Standard Website** – PKR 1,20,000 (15-20 days)\n✅ 10 pages, CMS, advanced SEO, blog, chatbot, 1 month support."
249
+ if "premium" in q:
250
+ return "**Premium Website** – PKR 2,50,000 (25-30 days)\n✅ Unlimited pages, e‑commerce, payment gateway, user accounts, custom animations, 6 months support."
251
+ return None
252
 
253
+ # ---------- Main response handler ----------
254
+ def get_final_response(user_message, session_id):
255
+ # 1. Step builder
256
+ step_resp = process_step_by_step(session_id, user_message)
257
+ if step_resp:
258
+ return step_resp
259
+
260
+ # 2. Project status query
261
+ status_match = re.search(r'status\s+([A-Z0-9\-]+)', user_message.lower())
262
+ if status_match:
263
+ pid = status_match.group(1).upper()
264
+ proj = get_project(pid)
265
+ if proj:
266
+ status = proj.get("status", "pending")
267
+ emoji = {"pending":"⏳", "in-progress":"🔄", "completed":"✅", "declined":"❌"}.get(status, "❓")
268
+ msg = proj.get("admin_message", "")
269
+ extra = f"\n📝 **Admin note:** {msg}" if msg else ""
270
+ return f"📦 **Project {pid}**\nStatus: {emoji} {status.upper()}{extra}\nTotal: PKR {proj.get('calculated_price',0):,}\nTimeline: {proj.get('calculated_timeline',0)} days"
271
+ else:
272
+ return f"❌ Project ID `{pid}` not found."
273
 
274
+ # 3. Package inquiry
275
+ pkg = package_details(user_message)
276
+ if pkg:
277
+ return pkg
278
+
279
+ # 4. Simple fallback
280
+ return "- How can I help? Services: website design, e‑commerce, SEO, chatbots.\n- **To start a project, say 'I want to build a website'**"
281
 
282
+ # ---------- Admin API routes ----------
283
  @app.route('/api/projects', methods=['GET'])
284
  def get_projects():
285
  snap = ref.child("projects").get()
 
298
  @app.route('/api/project/<project_id>/message', methods=['PUT'])
299
  def update_message(project_id):
300
  data = request.json
301
+ msg = data.get('message', '')
302
+ update_project_message(project_id, msg)
303
  return jsonify({"message": "Message updated"})
304
 
305
  @app.route('/api/services', methods=['GET'])
 
312
  data = request.json
313
  key = data.get('key')
314
  name = data.get('name')
315
+ price = int(data.get('price', 0))
316
+ timeline = int(data.get('timeline', 0))
317
  if not key or not name:
318
  return jsonify({"error": "Missing key or name"}), 400
319
+ service = {
320
  "name": name,
321
+ "price": price,
322
+ "timeline": timeline,
323
+ "display": f"{name} (+PKR {price:,}, +{timeline} days)"
324
  }
325
+ ref.child(f"extra_services/{key}").set(service)
326
+ return jsonify({"message": "Service added"})
327
 
328
  @app.route('/api/services/<key>', methods=['PUT'])
329
  def update_service(key):
330
  data = request.json
331
  name = data.get('name')
332
+ price = int(data.get('price', 0))
333
+ timeline = int(data.get('timeline', 0))
334
  if not name:
335
  return jsonify({"error": "Missing name"}), 400
336
+ service = {
337
  "name": name,
338
+ "price": price,
339
+ "timeline": timeline,
340
+ "display": f"{name} (+PKR {price:,}, +{timeline} days)"
341
  }
342
+ ref.child(f"extra_services/{key}").update(service)
343
+ return jsonify({"message": "Service updated"})
344
 
345
  @app.route('/api/services/<key>', methods=['DELETE'])
346
  def delete_service(key):
347
  ref.child(f"extra_services/{key}").delete()
348
  return jsonify({"message": "Service deleted"})
349
 
350
+ # ---------- Main chat endpoint ----------
351
+ @app.route('/api/chat', methods=['POST'])
352
+ def chat():
353
+ data = request.json
354
+ message = data.get('message', '')
355
+ session_id = data.get('session_id', str(uuid.uuid4()))
356
+ if not message:
357
+ return jsonify({"reply": "Please say something."})
358
+ reply = get_final_response(message, session_id)
359
+ # Save chat history (optional but kept)
360
+ ref.child(f"chats/{session_id}/messages").push().set({
361
+ "role": "user", "content": message, "timestamp": datetime.now().isoformat()
362
+ })
363
+ ref.child(f"chats/{session_id}/messages").push().set({
364
+ "role": "assistant", "content": reply, "timestamp": datetime.now().isoformat()
365
+ })
366
+ return jsonify({"reply": reply, "session_id": session_id})
367
+
368
  @app.route('/')
369
  def index():
370
  return send_from_directory('.', 'index.html')