muhammadhasnain100 Cursor commited on
Commit
c5cf697
·
1 Parent(s): 9129ffb

Add FastAPI routes, admin panel, RAG CSV merge, React frontend

Browse files

- Split users/query/chat history routes; JWT auth and admin APIs
- FAISS merge-from-CSV upload via admin; kb_uploads storage
- Vite/React UI: chat, auth, admin user management and KB upload
- MongoDB URI from MONGODB_URI env; gitignore secrets and artifacts

Co-authored-by: Cursor <cursoragent@cursor.com>

Files changed (50) hide show
  1. .gitignore +9 -0
  2. app.py +33 -82
  3. chatbot.py +399 -39
  4. database.py +16 -0
  5. dependencies.py +16 -0
  6. frontend/.gitignore +24 -0
  7. frontend/README.md +16 -0
  8. frontend/eslint.config.js +21 -0
  9. frontend/index.html +13 -0
  10. frontend/package-lock.json +0 -0
  11. frontend/package.json +32 -0
  12. frontend/public/comsats-logo.png +0 -0
  13. frontend/public/favicon.svg +1 -0
  14. frontend/public/icons.svg +24 -0
  15. frontend/src/App.jsx +40 -0
  16. frontend/src/api/admin.js +46 -0
  17. frontend/src/api/adminHttp.js +148 -0
  18. frontend/src/api/auth.js +39 -0
  19. frontend/src/api/chat.js +47 -0
  20. frontend/src/api/http.js +96 -0
  21. frontend/src/assets/hero.png +0 -0
  22. frontend/src/assets/react.svg +1 -0
  23. frontend/src/assets/vite.svg +1 -0
  24. frontend/src/auth/RequireAdminAuth.jsx +11 -0
  25. frontend/src/auth/RequireAuth.jsx +13 -0
  26. frontend/src/auth/adminStorage.js +32 -0
  27. frontend/src/auth/storage.js +39 -0
  28. frontend/src/components/ComsatsLogo.jsx +22 -0
  29. frontend/src/components/chat/ChatMain.jsx +528 -0
  30. frontend/src/components/chat/ChatSidebar.jsx +192 -0
  31. frontend/src/components/chat/CollapsedSidebarRail.jsx +81 -0
  32. frontend/src/components/chat/MessageRoleSticker.jsx +48 -0
  33. frontend/src/components/chat/ProfileModal.jsx +133 -0
  34. frontend/src/index.css +28 -0
  35. frontend/src/main.jsx +10 -0
  36. frontend/src/pages/AdminLogin.jsx +146 -0
  37. frontend/src/pages/AdminPanel.jsx +324 -0
  38. frontend/src/pages/AdminRegister.jsx +161 -0
  39. frontend/src/pages/AuthLayout.jsx +59 -0
  40. frontend/src/pages/ChatPage.jsx +517 -0
  41. frontend/src/pages/Login.jsx +151 -0
  42. frontend/src/pages/Signup.jsx +165 -0
  43. frontend/vite.config.js +19 -0
  44. requirements.txt +10 -2
  45. routes/__init__.py +3 -0
  46. routes/admin.py +239 -0
  47. routes/chathistory.py +72 -0
  48. routes/query.py +33 -0
  49. routes/users.py +149 -0
  50. security.py +168 -0
.gitignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .env
4
+ .venv/
5
+ venv/
6
+ kb_uploads/
7
+
8
+ frontend/node_modules/
9
+ frontend/dist/
app.py CHANGED
@@ -1,99 +1,50 @@
1
- import uuid
2
- from fastapi import FastAPI, HTTPException
3
- from pydantic import BaseModel
4
- from pymongo import MongoClient
5
- import urllib.parse
6
- import os
7
  from langchain_groq import ChatGroq
8
  from langchain_community.embeddings import HuggingFaceBgeEmbeddings
 
9
  from chatbot import Comsatsbot
10
- # FastAPI app setup
11
- app = FastAPI()
 
 
 
 
12
 
13
  model_name = "BAAI/bge-small-en"
14
  model_kwargs = {"device": "cpu"}
15
  encode_kwargs = {"normalize_embeddings": True}
16
  hf = HuggingFaceBgeEmbeddings(
17
- model_name=model_name, model_kwargs=model_kwargs, encode_kwargs=encode_kwargs
 
 
18
  )
19
 
20
  api_keys = [
21
- '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',
22
- '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',
23
- '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',
24
- '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',
25
  ]
26
 
27
- llm = ChatGroq(temperature=0, groq_api_key=api_keys[2], model_name="llama3-70b-8192")
28
-
29
- # MongoDB setup
30
- username = 'hasnainnaseer987'
31
- password = 'Hasnain'
32
- encoded_username = urllib.parse.quote_plus(username)
33
- encoded_password = urllib.parse.quote_plus(password)
34
- MONGODB_ATLAS_CLUSTER_URI = f'mongodb+srv://{encoded_username}:{encoded_password}@cluster0.jdfp3.mongodb.net/'
35
- client = MongoClient(MONGODB_ATLAS_CLUSTER_URI)
36
- db = client.get_database('chat_db') # Assume this is your database
37
- chats_collection = db.get_collection('chats') # Collection to store chats
38
- paths = ['FYP Supervisor Feedback.csv', 'urdu_data.csv', 'english_data.csv']
39
-
40
- chatbot = Comsatsbot(hf, llm, api_keys, chats_collection, paths)
41
-
42
- # Endpoint for creating a new chat ID
43
- @app.post("/get_new_chat")
44
- def create_new_chat():
45
- try:
46
- chat_id = str(uuid.uuid4())
47
- message = chatbot.new_chat(chat_id)
48
- return {"chat_id": chat_id, "message": "Successfully created new chat."}
49
- except KeyError:
50
- raise HTTPException(status_code=404, detail="Chat ID already exist try again plz...")
51
- except Exception as e:
52
- raise HTTPException(status_code=500, detail=str(e))
53
-
54
-
55
- # Request model for response endpoint
56
- class ChatRequest(BaseModel):
57
- chat_id: str
58
- question: str
59
-
60
- # Endpoint for retrieving chat history by chat ID
61
- @app.get("/get_chat/{chat_id}")
62
- def get_chat(chat_id: str):
63
- try:
64
- history = chatbot.load_chat(chat_id)
65
- return {"chat_id": chat_id, "history": history}
66
- except KeyError:
67
- raise HTTPException(status_code=404, detail="Chat ID not found")
68
- except Exception as e:
69
- raise HTTPException(status_code=500, detail=str(e))
70
-
71
-
72
- # Endpoint for deleting a chat by chat ID
73
- @app.delete("/delete_chat/{chat_id}")
74
- def delete_chat(chat_id: str):
75
- try:
76
- message = chatbot.delete_chat(chat_id)
77
- return {"message": f"Chat with ID {chat_id} has been deleted successfully."}
78
- except KeyError:
79
- raise HTTPException(status_code=404, detail="Chat ID not found")
80
- except Exception as e:
81
- raise HTTPException(status_code=500, detail=str(e))
82
-
83
-
84
- # Endpoint for getting a response based on chat ID and question
85
- @app.post("/response")
86
- def response(request: ChatRequest):
87
- chat_id = request.chat_id
88
- question = request.question
89
 
90
- try:
91
- answer = chatbot.response(question, chat_id)
92
- return {"answer": answer}
93
 
94
- except KeyError:
95
- raise HTTPException(status_code=404, detail="Chat ID not found")
96
 
97
- except Exception as e:
98
- raise HTTPException(status_code=500, detail="GPU error, try after some time...")
 
99
 
 
 
 
 
 
1
+ from fastapi import FastAPI
 
 
 
 
 
2
  from langchain_groq import ChatGroq
3
  from langchain_community.embeddings import HuggingFaceBgeEmbeddings
4
+
5
  from chatbot import Comsatsbot
6
+ from database import admins_collection, chats_collection, users_collection
7
+ from routes import admin, chathistory, query, users
8
+
9
+ app = FastAPI(
10
+ swagger_ui_parameters={"persistAuthorization": True},
11
+ )
12
 
13
  model_name = "BAAI/bge-small-en"
14
  model_kwargs = {"device": "cpu"}
15
  encode_kwargs = {"normalize_embeddings": True}
16
  hf = HuggingFaceBgeEmbeddings(
17
+ model_name=model_name,
18
+ model_kwargs=model_kwargs,
19
+ encode_kwargs=encode_kwargs,
20
  )
21
 
22
  api_keys = [
23
+ "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",
24
+ "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",
25
+ "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",
26
+ "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",
27
  ]
28
 
29
+ gemini_api_keys = [
30
+ "AIzaSyD6dGpppzVq4--EdI3aCAWtgSyHygV_VnA",
31
+ "AIzaSyAhkeFXxdqY8SGdE7_8doyFfwIABzVwoF4",
32
+ ]
33
+ llm = ChatGroq(
34
+ temperature=0,
35
+ groq_api_key=api_keys[2],
36
+ model_name="llama3-70b-8192",
37
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ paths = ["FYP Supervisor Feedback.csv", "urdu_data.csv", "english_data.csv"]
 
 
40
 
41
+ chatbot = Comsatsbot(hf, llm, api_keys, chats_collection, paths, gemini_api_keys)
 
42
 
43
+ app.state.chatbot = chatbot
44
+ app.state.users_collection = users_collection
45
+ app.state.admins_collection = admins_collection
46
 
47
+ app.include_router(admin.router)
48
+ app.include_router(users.router)
49
+ app.include_router(query.router)
50
+ app.include_router(chathistory.router)
chatbot.py CHANGED
@@ -1,29 +1,193 @@
 
1
  import os
 
 
 
 
 
2
  from groq import Groq
3
  from langchain.memory import ConversationTokenBufferMemory
4
- from langdetect import detect
5
- from deep_translator import GoogleTranslator
6
  from langchain_community.document_loaders.csv_loader import CSVLoader
7
  from langchain_community.vectorstores import FAISS
8
- import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  class Comsatsbot:
11
- def __init__(self, hf, llm, api_keys, chats_collection, paths, index_path='faiss_kb'):
 
 
 
 
 
 
 
 
 
 
12
  self.llm = llm
13
  self.api_keys = api_keys
14
  self.client = None
15
- self.models = ["llama3-groq-70b-8192-tool-use-preview", "llama-3.1-70b-versatile", "llama3-70b-8192"]
16
-
17
-
 
 
18
  # Initialize memory buffer and MongoDB connection
19
  self.memory = ConversationTokenBufferMemory(llm=self.llm, max_token_limit=3000)
20
  self.chats_collection = chats_collection
21
  self.index_path = index_path
 
 
22
  self.hf = hf
23
  self.faiss_index = None
24
  self.faiss_retriever = None
25
  self.paths = paths
26
  self.initialize_faiss_index()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  def load_data(self, paths):
29
  documents = []
@@ -35,14 +199,68 @@ class Comsatsbot:
35
 
36
  def initialize_faiss_index(self):
37
  if os.path.exists(self.index_path):
38
- self.faiss_index = FAISS.load_local(self.index_path, self.hf, allow_dangerous_deserialization=True)
39
- self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
 
 
 
 
 
 
 
 
40
  else:
41
  documents = self.load_data(self.paths)
42
  self.faiss_index = FAISS.from_documents(documents, self.hf)
43
  self.faiss_index.save_local(self.index_path)
44
  self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  def retrieve_answer(self, query):
47
  if self.faiss_retriever:
48
  return self.faiss_retriever.invoke(query)
@@ -50,39 +268,122 @@ class Comsatsbot:
50
  print("FAISS retriever is not initialized. Please create or load an index.")
51
  return None
52
 
53
- def create_chat_record(self, chat_id):
 
 
 
 
 
 
 
54
  self.chats_collection.insert_one({
55
  "_id": chat_id,
56
- "history": []
 
 
57
  })
58
 
59
  def update_chat(self, chat_id, question, answer):
 
60
  self.chats_collection.update_one(
61
  {"_id": chat_id},
62
- {"$push": {"history": {"question": question, "answer": answer}}}
 
 
 
63
  )
64
 
65
- def load_chat(self, chat_id):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  chat_record = self.chats_collection.find_one({"_id": chat_id})
67
- if not chat_record:
68
- raise KeyError(f"Chat ID {chat_id} does not exist.")
69
- return chat_record.get('history', [])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- def new_chat(self, chat_id):
72
- # Check if chat ID already exists
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  if self.chats_collection.find_one({"_id": chat_id}):
74
  raise KeyError(f"Chat ID {chat_id} exist already.")
75
 
76
- # Create a new chat record if it doesn't exist
77
- self.create_chat_record(chat_id)
78
  return "success"
79
 
80
- def delete_chat(self, chat_id):
81
- # Check if the chat ID exists
82
- if not self.chats_collection.find_one({"_id": chat_id}):
83
- raise KeyError(f"Chat ID {chat_id} does not exist.")
84
-
85
- # Delete the chat if it exists
86
  self.chats_collection.delete_one({"_id": chat_id})
87
  return "success"
88
 
@@ -152,32 +453,91 @@ class Comsatsbot:
152
  continue
153
 
154
  return "Sorry, unable to provide an answer at this time."
 
 
 
 
 
 
 
 
 
155
 
 
156
 
 
 
 
157
 
158
- def response(self, question, chat_id):
159
- chat_history = self.load_chat(chat_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
  # Load the previous conversation into memory
162
  for entry in chat_history:
163
  self.memory.save_context({"input": entry["question"]}, {"output": entry["answer"]})
164
 
165
  language = detect(question)
166
- if language == 'ur':
167
- question_translation = GoogleTranslator(source='ur', target='en').translate(question)
168
- context = self.faiss_retriever.invoke(question_translation)
169
- else:
170
- context = self.faiss_retriever.invoke(question)
171
 
172
- all_content = ''
173
- for document in context:
174
- page_content = document.page_content
175
- all_content += page_content + '\n' # Add a line break between contents for readability
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
- answer = self.generate_response(question, self.memory.load_memory_variables({})['history'], all_content, language)
 
 
 
 
 
 
 
 
 
178
 
179
  self.update_chat(chat_id, question, answer)
180
- return answer
181
 
182
 
183
 
 
1
+ import json
2
  import os
3
+ import threading
4
+ import time
5
+ import uuid
6
+ from datetime import datetime, timezone
7
+
8
  from groq import Groq
9
  from langchain.memory import ConversationTokenBufferMemory
 
 
10
  from langchain_community.document_loaders.csv_loader import CSVLoader
11
  from langchain_community.vectorstores import FAISS
12
+ from langdetect import detect
13
+ from deep_translator import GoogleTranslator
14
+ from pydantic import BaseModel, Field, ValidationError
15
+ from typing import Annotated
16
+
17
+ # Groq structured outputs: https://console.groq.com/docs/structured-outputs
18
+ FOLLOWUP_JSON_SCHEMA = {
19
+ "type": "object",
20
+ "properties": {
21
+ "suggested_questions": {
22
+ "type": "array",
23
+ "description": (
24
+ "Natural follow-up questions the student might ask next about COMSATS "
25
+ "or clarifying the last answer (1 to 4 questions)."
26
+ ),
27
+ "items": {"type": "string"},
28
+ "minItems": 1,
29
+ "maxItems": 4,
30
+ }
31
+ },
32
+ "required": ["suggested_questions"],
33
+ "additionalProperties": False,
34
+ }
35
+
36
+
37
+ class FollowUpQuestionsPayload(BaseModel):
38
+ """Validated shape returned by generate_followup_questions."""
39
+
40
+ suggested_questions: Annotated[list[str], Field(min_length=1, max_length=4)]
41
+
42
 
43
  class Comsatsbot:
44
+ def __init__(
45
+ self,
46
+ hf,
47
+ llm,
48
+ api_keys,
49
+ chats_collection,
50
+ paths,
51
+ gemini_api_keys,
52
+ index_path='faiss_kb',
53
+ kb_upload_dir='kb_uploads',
54
+ ):
55
  self.llm = llm
56
  self.api_keys = api_keys
57
  self.client = None
58
+ self.models = ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "openai/gpt-oss-20b", "meta-llama/llama-4-scout-17b-16e-instruct", "meta-llama/llama-prompt-guard-2-22m", "qwen/qwen3-32b"]
59
+ self.groq_json_models = ["meta-llama/llama-4-scout-17b-16e-instruct", "openai/gpt-oss-20b", "openai/gpt-oss-safeguard-20b", "openai/gpt-oss-120b"]
60
+ self.gemini_api_keys = gemini_api_keys
61
+ self.gemini_client = None
62
+ self.gemini_models = ["gemini-2.5-flash-lite", "gemini-3.1-flash-lite-preview", "gemini-3.1-flash-live-preview", "gemini-2.5-flash"]
63
  # Initialize memory buffer and MongoDB connection
64
  self.memory = ConversationTokenBufferMemory(llm=self.llm, max_token_limit=3000)
65
  self.chats_collection = chats_collection
66
  self.index_path = index_path
67
+ self.kb_upload_dir = kb_upload_dir
68
+ self._faiss_lock = threading.Lock()
69
  self.hf = hf
70
  self.faiss_index = None
71
  self.faiss_retriever = None
72
  self.paths = paths
73
  self.initialize_faiss_index()
74
+
75
+
76
+ @staticmethod
77
+ def _followup_history_snippet(chat_history: list, max_turns: int = 4) -> str:
78
+ if not chat_history:
79
+ return "(no prior turns in this conversation)"
80
+ tail = chat_history[-max_turns:]
81
+ lines = []
82
+ for h in tail:
83
+ q = (h.get("question") or "").strip()
84
+ a = (h.get("answer") or "").strip()
85
+ if q:
86
+ lines.append(f"Earlier Q: {q[:320]}")
87
+ if a:
88
+ lines.append(f"Earlier A: {a[:400]}")
89
+ return "\n".join(lines) if lines else "(no prior turns)"
90
+
91
+ @staticmethod
92
+ def _build_followup_user_prompt(
93
+ question: str,
94
+ answer: str,
95
+ history_snippet: str,
96
+ language_label: str,
97
+ ) -> str:
98
+ return f"""You generate suggested follow-up questions for a COMSATS University Attock campus chatbot.
99
+
100
+ Context:
101
+ - Latest student question: {question}
102
+ - Latest assistant answer: {answer}
103
+ - Recent conversation (may be truncated):
104
+ {history_snippet}
105
+
106
+ Requirements:
107
+ 1. Produce exactly ONE JSON object with a single key "suggested_questions" whose value is an array of strings.
108
+ 2. The array MUST contain between 1 and 4 questions inclusive (prefer 3–4 when the topic allows; use only 1–2 if the answer was very narrow or unknown).
109
+ 3. Each question must be short (aim under 120 characters), clear, and something the same student might reasonably ask next.
110
+ 4. Questions must stay relevant to COMSATS (programs, admissions, campus, fees, departments, links already mentioned) or logically deepen/clarify the last answer.
111
+ 5. Write every suggested question in **{language_label}** (same language family as the student's latest question).
112
+ 6. Do not repeat the student's latest question verbatim; do not add numbering prefixes like "1." inside the strings.
113
+ 7. Do not include markdown, explanations, or keys other than "suggested_questions".
114
+
115
+ Return only valid JSON."""
116
+
117
+ def _parse_followup_json(self, content: str | None) -> list[str] | None:
118
+ if not content or not content.strip():
119
+ return None
120
+ try:
121
+ data = json.loads(content)
122
+ except json.JSONDecodeError:
123
+ return None
124
+ if not isinstance(data, dict):
125
+ return None
126
+ raw = data.get("suggested_questions")
127
+ if not isinstance(raw, list):
128
+ return None
129
+ cleaned = [
130
+ str(x).strip()
131
+ for x in raw
132
+ if isinstance(x, (str, int, float)) and str(x).strip()
133
+ ]
134
+ if not cleaned:
135
+ return None
136
+ cleaned = cleaned[:4]
137
+ try:
138
+ validated = FollowUpQuestionsPayload.model_validate(
139
+ {"suggested_questions": cleaned}
140
+ )
141
+ return validated.suggested_questions
142
+ except ValidationError:
143
+ if len(cleaned) >= 1:
144
+ return cleaned[:4]
145
+ return None
146
+
147
+ def generate_followup_questions(
148
+ self,
149
+ question: str,
150
+ answer: str,
151
+ history_snippet: str,
152
+ language_label: str,
153
+ ) -> list[str] | None:
154
+ system_schema = (
155
+ "You output only JSON matching the schema: an object with "
156
+ '"suggested_questions": string array (1–4 items). No prose.'
157
+ )
158
+ user_prompt = self._build_followup_user_prompt(
159
+ question, answer, history_snippet, language_label
160
+ )
161
+
162
+ # Use only self.groq_json_models for suggestions — never self.models (RAG answer pool).
163
+ for api_key in self.api_keys:
164
+ client = Groq(api_key=api_key)
165
+ for model_id in self.groq_json_models:
166
+ try:
167
+ resp = client.chat.completions.create(
168
+ model=model_id,
169
+ messages=[
170
+ {"role": "system", "content": system_schema},
171
+ {"role": "user", "content": user_prompt},
172
+ ],
173
+ temperature=0.2,
174
+ response_format={
175
+ "type": "json_schema",
176
+ "json_schema": {
177
+ "name": "follow_up_questions",
178
+ "strict": True,
179
+ "schema": FOLLOWUP_JSON_SCHEMA,
180
+ },
181
+ },
182
+ )
183
+ content = resp.choices[0].message.content
184
+ parsed = self._parse_followup_json(content)
185
+ if parsed:
186
+ return parsed
187
+ except Exception:
188
+ time.sleep(0.4)
189
+ continue
190
+ return None
191
 
192
  def load_data(self, paths):
193
  documents = []
 
199
 
200
  def initialize_faiss_index(self):
201
  if os.path.exists(self.index_path):
202
+ try:
203
+ self.faiss_index = FAISS.load_local(
204
+ self.index_path, self.hf, allow_dangerous_deserialization=True
205
+ )
206
+ self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
207
+ except Exception:
208
+ documents = self.load_data(self.paths)
209
+ self.faiss_index = FAISS.from_documents(documents, self.hf)
210
+ self.faiss_index.save_local(self.index_path)
211
+ self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
212
  else:
213
  documents = self.load_data(self.paths)
214
  self.faiss_index = FAISS.from_documents(documents, self.hf)
215
  self.faiss_index.save_local(self.index_path)
216
  self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
217
 
218
+ def update_faiss_index(self, path: str) -> dict:
219
+ """Embed CSV rows and merge into the live FAISS index; persist and refresh retriever."""
220
+ if not os.path.isfile(path):
221
+ raise ValueError(f"CSV not found: {path}")
222
+ with self._faiss_lock:
223
+ if self.faiss_index is None:
224
+ raise RuntimeError(
225
+ "FAISS index is not loaded. Fix faiss_kb or bundled CSVs and restart."
226
+ )
227
+ documents = self.load_data([path])
228
+ if not documents:
229
+ raise ValueError("CSV contained no rows.")
230
+ rows = len(documents)
231
+ new_vs = FAISS.from_documents(documents, self.hf)
232
+ self.faiss_index.merge_from(new_vs)
233
+ self.faiss_index.save_local(self.index_path)
234
+ self.faiss_retriever = self.faiss_index.as_retriever(search_kwargs={"k": 5})
235
+ return {"rows_merged": rows, "mode": "merge"}
236
+
237
+ def merge_kb_csv_bytes(self, original_filename: str, data: bytes) -> dict:
238
+ """Save uploaded CSV under kb_upload_dir and merge into FAISS via update_faiss_index."""
239
+ if not data or not data.strip():
240
+ raise ValueError("Empty file.")
241
+ os.makedirs(self.kb_upload_dir, exist_ok=True)
242
+ safe = os.path.basename(original_filename or "upload.csv").strip() or "upload.csv"
243
+ safe = safe.replace('..', '').replace('/', '_').replace('\\', '_')
244
+ if not safe.lower().endswith('.csv'):
245
+ safe = f'{safe}.csv'
246
+ dest_name = f'{uuid.uuid4().hex}_{safe}'
247
+ dest_path = os.path.join(os.path.abspath(self.kb_upload_dir), dest_name)
248
+ with open(dest_path, 'wb') as f:
249
+ f.write(data)
250
+ stats = self.update_faiss_index(dest_path)
251
+ stats['saved_as'] = dest_name
252
+ return stats
253
+
254
+ def list_kb_upload_filenames(self) -> list[str]:
255
+ root = os.path.abspath(self.kb_upload_dir)
256
+ if not os.path.isdir(root):
257
+ return []
258
+ return sorted(
259
+ n
260
+ for n in os.listdir(root)
261
+ if n.lower().endswith('.csv') and os.path.isfile(os.path.join(root, n))
262
+ )
263
+
264
  def retrieve_answer(self, query):
265
  if self.faiss_retriever:
266
  return self.faiss_retriever.invoke(query)
 
268
  print("FAISS retriever is not initialized. Please create or load an index.")
269
  return None
270
 
271
+ def _assert_chat_owned(self, chat_record, user_id):
272
+ if not chat_record:
273
+ raise KeyError("Chat ID not found.")
274
+ if chat_record.get("user_id") != user_id:
275
+ raise KeyError("Chat ID not found.")
276
+
277
+ def create_chat_record(self, chat_id, user_id):
278
+ now = datetime.now(timezone.utc)
279
  self.chats_collection.insert_one({
280
  "_id": chat_id,
281
+ "user_id": user_id,
282
+ "history": [],
283
+ "updated_at": now,
284
  })
285
 
286
  def update_chat(self, chat_id, question, answer):
287
+ now = datetime.now(timezone.utc)
288
  self.chats_collection.update_one(
289
  {"_id": chat_id},
290
+ {
291
+ "$push": {"history": {"question": question, "answer": answer}},
292
+ "$set": {"updated_at": now},
293
+ },
294
  )
295
 
296
+ def list_chats(self, user_id, skip: int = 0, limit: int = 30):
297
+ cursor = self.chats_collection.find({"user_id": user_id})
298
+ items = []
299
+ for doc in cursor:
300
+ history = doc.get("history") or []
301
+ if history:
302
+ preview = (history[-1].get("question") or "")[:100]
303
+ else:
304
+ preview = "New conversation"
305
+ ua = doc.get("updated_at")
306
+ items.append({
307
+ "chat_id": doc["_id"],
308
+ "preview": preview.strip() or "New conversation",
309
+ "updated_at": ua.isoformat() if hasattr(ua, "isoformat") else None,
310
+ "message_count": len(history),
311
+ })
312
+
313
+ def sort_key(entry):
314
+ ts = entry["updated_at"] or ""
315
+ return ts
316
+
317
+ items.sort(key=sort_key, reverse=True)
318
+ total = len(items)
319
+ slice_items = items[skip : skip + limit]
320
+ return {
321
+ "chats": slice_items,
322
+ "total": total,
323
+ "skip": skip,
324
+ "limit": limit,
325
+ "has_more": skip + len(slice_items) < total,
326
+ }
327
+
328
+ def load_chat(self, chat_id, user_id):
329
  chat_record = self.chats_collection.find_one({"_id": chat_id})
330
+ self._assert_chat_owned(chat_record, user_id)
331
+ return chat_record.get("history", [])
332
+
333
+ def load_chat_history_page(
334
+ self,
335
+ chat_id,
336
+ user_id,
337
+ before_index: int | None,
338
+ limit: int,
339
+ ):
340
+ chat_record = self.chats_collection.find_one({"_id": chat_id})
341
+ self._assert_chat_owned(chat_record, user_id)
342
+ full = chat_record.get("history") or []
343
+ n = len(full)
344
+ limit = max(1, min(limit, 100))
345
+
346
+ if before_index is not None and before_index <= 0:
347
+ return {
348
+ "history": [],
349
+ "total_pairs": n,
350
+ "has_older": False,
351
+ "next_before_index": 0,
352
+ "range_start": 0,
353
+ "range_end_exclusive": 0,
354
+ }
355
 
356
+ if before_index is None:
357
+ start = max(0, n - limit)
358
+ slice_ = full[start:n]
359
+ has_older = start > 0
360
+ next_before = start
361
+ else:
362
+ end = before_index
363
+ start = max(0, end - limit)
364
+ slice_ = full[start:end]
365
+ has_older = start > 0
366
+ next_before = start
367
+
368
+ return {
369
+ "history": slice_,
370
+ "total_pairs": n,
371
+ "has_older": has_older,
372
+ "next_before_index": next_before,
373
+ "range_start": start,
374
+ "range_end_exclusive": start + len(slice_),
375
+ }
376
+
377
+ def new_chat(self, chat_id, user_id):
378
  if self.chats_collection.find_one({"_id": chat_id}):
379
  raise KeyError(f"Chat ID {chat_id} exist already.")
380
 
381
+ self.create_chat_record(chat_id, user_id)
 
382
  return "success"
383
 
384
+ def delete_chat(self, chat_id, user_id):
385
+ chat_record = self.chats_collection.find_one({"_id": chat_id})
386
+ self._assert_chat_owned(chat_record, user_id)
 
 
 
387
  self.chats_collection.delete_one({"_id": chat_id})
388
  return "success"
389
 
 
453
  continue
454
 
455
  return "Sorry, unable to provide an answer at this time."
456
+
457
+ def generate_web_response(self, question, history, detected_language):
458
+ from google import genai
459
+ from google.genai import types
460
+
461
+ lang = "Urdu" if detected_language == "ur" else "English"
462
+ prompt = f"""You are the COMSATS University Attock campus assistant.
463
+ Use Google Search when needed. Answer only COMSATS-related questions (admissions, programs, campus, fees).
464
+ Respond in {lang}.
465
 
466
+ Question: {question}
467
 
468
+ Prior conversation (may be truncated):
469
+ {history}
470
+ """
471
 
472
+ grounding_tool = types.Tool(google_search=types.GoogleSearch())
473
+ config = types.GenerateContentConfig(tools=[grounding_tool])
474
+
475
+ for api_key in self.gemini_api_keys:
476
+ try:
477
+ self.gemini_client = genai.Client(api_key=api_key)
478
+ except Exception:
479
+ time.sleep(0.3)
480
+ continue
481
+ for model_name in self.gemini_models:
482
+ try:
483
+ response = self.gemini_client.models.generate_content(
484
+ model=model_name,
485
+ contents=prompt,
486
+ config=config,
487
+ )
488
+ text = getattr(response, "text", None) or ""
489
+ if text.strip():
490
+ return text
491
+ except Exception:
492
+ time.sleep(0.3)
493
+ continue
494
+ return "Sorry, web search is unavailable right now."
495
+
496
+ def response(self, question, chat_id, user_id, allow_augmentation: bool = False, use_web_search: bool = False):
497
+ chat_history = self.load_chat(chat_id, user_id)
498
 
499
  # Load the previous conversation into memory
500
  for entry in chat_history:
501
  self.memory.save_context({"input": entry["question"]}, {"output": entry["answer"]})
502
 
503
  language = detect(question)
504
+ history_str = self.memory.load_memory_variables({})["history"]
 
 
 
 
505
 
506
+ if use_web_search:
507
+ answer = self.generate_web_response(question, history_str, language)
508
+ else:
509
+ if not self.faiss_retriever:
510
+ answer = (
511
+ "Knowledge base search is unavailable right now. "
512
+ "Please try again later or use web search if enabled."
513
+ )
514
+ elif language == 'ur':
515
+ question_translation = GoogleTranslator(source='ur', target='en').translate(question)
516
+ context = self.faiss_retriever.invoke(question_translation)
517
+ all_content = ''
518
+ for document in context:
519
+ all_content += document.page_content + '\n'
520
+ answer = self.generate_response(question, history_str, all_content, language)
521
+ else:
522
+ context = self.faiss_retriever.invoke(question)
523
+ all_content = ''
524
+ for document in context:
525
+ all_content += document.page_content + '\n'
526
+ answer = self.generate_response(question, history_str, all_content, language)
527
 
528
+ suggested_questions: list[str] | None = None
529
+ if allow_augmentation:
530
+ lang_label = "Urdu" if language == 'ur' else "English"
531
+ snippet = self._followup_history_snippet(chat_history)
532
+ suggested_questions = self.generate_followup_questions(
533
+ question,
534
+ answer,
535
+ snippet,
536
+ lang_label,
537
+ )
538
 
539
  self.update_chat(chat_id, question, answer)
540
+ return answer, suggested_questions
541
 
542
 
543
 
database.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from pymongo import MongoClient
4
+
5
+ MONGODB_URI = os.getenv("MONGODB_URI", "").strip()
6
+ if not MONGODB_URI:
7
+ raise RuntimeError(
8
+ "Set the MONGODB_URI environment variable to your MongoDB connection string "
9
+ "(e.g. mongodb+srv://user:pass@cluster.../?appName=Cluster0). Use a local `.env` or export in your shell."
10
+ )
11
+
12
+ client = MongoClient(MONGODB_URI)
13
+ db = client.get_database("chat_db")
14
+ chats_collection = db.get_collection("chats")
15
+ users_collection = db.get_collection("users")
16
+ admins_collection = db.get_collection("admins")
dependencies.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Annotated
2
+
3
+ from fastapi import Depends, Request
4
+
5
+ from chatbot import Comsatsbot
6
+ from security import get_current_admin_id, get_current_user_id
7
+
8
+
9
+ def get_chatbot(request: Request) -> Comsatsbot:
10
+ return request.app.state.chatbot
11
+
12
+
13
+ ChatbotDep = Annotated[Comsatsbot, Depends(get_chatbot)]
14
+
15
+ CurrentUserIdDep = Annotated[str, Depends(get_current_user_id)]
16
+ CurrentAdminIdDep = Annotated[str, Depends(get_current_admin_id)]
frontend/.gitignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Logs
2
+ logs
3
+ *.log
4
+ npm-debug.log*
5
+ yarn-debug.log*
6
+ yarn-error.log*
7
+ pnpm-debug.log*
8
+ lerna-debug.log*
9
+
10
+ node_modules
11
+ dist
12
+ dist-ssr
13
+ *.local
14
+
15
+ # Editor directories and files
16
+ .vscode/*
17
+ !.vscode/extensions.json
18
+ .idea
19
+ .DS_Store
20
+ *.suo
21
+ *.ntvs*
22
+ *.njsproj
23
+ *.sln
24
+ *.sw?
frontend/README.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # React + Vite
2
+
3
+ This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
4
+
5
+ Currently, two official plugins are available:
6
+
7
+ - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
8
+ - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
9
+
10
+ ## React Compiler
11
+
12
+ The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
13
+
14
+ ## Expanding the ESLint configuration
15
+
16
+ If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
frontend/eslint.config.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import js from '@eslint/js'
2
+ import globals from 'globals'
3
+ import reactHooks from 'eslint-plugin-react-hooks'
4
+ import reactRefresh from 'eslint-plugin-react-refresh'
5
+ import { defineConfig, globalIgnores } from 'eslint/config'
6
+
7
+ export default defineConfig([
8
+ globalIgnores(['dist']),
9
+ {
10
+ files: ['**/*.{js,jsx}'],
11
+ extends: [
12
+ js.configs.recommended,
13
+ reactHooks.configs.flat.recommended,
14
+ reactRefresh.configs.vite,
15
+ ],
16
+ languageOptions: {
17
+ globals: globals.browser,
18
+ parserOptions: { ecmaFeatures: { jsx: true } },
19
+ },
20
+ },
21
+ ])
frontend/index.html ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <link rel="icon" type="image/png" href="/comsats-logo.png" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>COMSATS Chatbot</title>
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script type="module" src="/src/main.jsx"></script>
12
+ </body>
13
+ </html>
frontend/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
frontend/package.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "frontend",
3
+ "private": true,
4
+ "version": "0.0.0",
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "vite build",
9
+ "lint": "eslint .",
10
+ "preview": "vite preview"
11
+ },
12
+ "dependencies": {
13
+ "react": "^19.2.5",
14
+ "react-dom": "^19.2.5",
15
+ "react-markdown": "^10.1.0",
16
+ "react-router-dom": "^7.14.2",
17
+ "remark-gfm": "^4.0.1"
18
+ },
19
+ "devDependencies": {
20
+ "@eslint/js": "^10.0.1",
21
+ "@tailwindcss/vite": "^4.2.4",
22
+ "@types/react": "^19.2.14",
23
+ "@types/react-dom": "^19.2.3",
24
+ "@vitejs/plugin-react": "^6.0.1",
25
+ "eslint": "^10.2.1",
26
+ "eslint-plugin-react-hooks": "^7.1.1",
27
+ "eslint-plugin-react-refresh": "^0.5.2",
28
+ "globals": "^17.5.0",
29
+ "tailwindcss": "^4.2.4",
30
+ "vite": "^8.0.10"
31
+ }
32
+ }
frontend/public/comsats-logo.png ADDED
frontend/public/favicon.svg ADDED
frontend/public/icons.svg ADDED
frontend/src/App.jsx ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom'
2
+ import RequireAdminAuth from './auth/RequireAdminAuth'
3
+ import RequireAuth from './auth/RequireAuth'
4
+ import AdminLogin from './pages/AdminLogin'
5
+ import AdminPanel from './pages/AdminPanel'
6
+ import AdminRegister from './pages/AdminRegister'
7
+ import ChatPage from './pages/ChatPage'
8
+ import Login from './pages/Login'
9
+ import Signup from './pages/Signup'
10
+
11
+ export default function App() {
12
+ return (
13
+ <BrowserRouter>
14
+ <Routes>
15
+ <Route path="/" element={<Navigate to="/login" replace />} />
16
+ <Route path="/login" element={<Login />} />
17
+ <Route path="/signup" element={<Signup />} />
18
+ <Route path="/admin/login" element={<AdminLogin />} />
19
+ <Route path="/admin/register" element={<AdminRegister />} />
20
+ <Route
21
+ path="/admin"
22
+ element={
23
+ <RequireAdminAuth>
24
+ <AdminPanel />
25
+ </RequireAdminAuth>
26
+ }
27
+ />
28
+ <Route path="/home" element={<Navigate to="/chat" replace />} />
29
+ <Route
30
+ path="/chat"
31
+ element={
32
+ <RequireAuth>
33
+ <ChatPage />
34
+ </RequireAuth>
35
+ }
36
+ />
37
+ </Routes>
38
+ </BrowserRouter>
39
+ )
40
+ }
frontend/src/api/admin.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { apiAdminJson, apiAdminUpload } from './adminHttp'
2
+ import { apiJson } from './http'
3
+
4
+ export function adminLogin(email, password) {
5
+ return apiJson('/admin/login', {
6
+ method: 'POST',
7
+ body: JSON.stringify({ email, password }),
8
+ auth: false,
9
+ })
10
+ }
11
+
12
+ export function adminRegister({ email, password, full_name, bootstrapSecret }) {
13
+ const headers = {}
14
+ if (bootstrapSecret?.trim()) {
15
+ headers['X-Admin-Bootstrap-Secret'] = bootstrapSecret.trim()
16
+ }
17
+ const body = { email, password }
18
+ if (full_name?.trim()) body.full_name = full_name.trim()
19
+ return apiJson('/admin/register', {
20
+ method: 'POST',
21
+ headers,
22
+ body: JSON.stringify(body),
23
+ auth: false,
24
+ })
25
+ }
26
+
27
+ export function listUsersAdmin(page = 1, page_size = 20) {
28
+ const q = new URLSearchParams({ page: String(page), page_size: String(page_size) })
29
+ return apiAdminJson(`/admin/users?${q}`, { auth: true })
30
+ }
31
+
32
+ export function deleteUserAdmin(userId) {
33
+ return apiAdminJson(`/admin/users/${encodeURIComponent(userId)}`, {
34
+ method: 'DELETE',
35
+ auth: true,
36
+ })
37
+ }
38
+
39
+ export function getKbStatus() {
40
+ return apiAdminJson('/admin/knowledge-base/status', { auth: true })
41
+ }
42
+
43
+ /** Merge one CSV into FAISS via admin endpoint (uses FormData factory for refresh retry). */
44
+ export function mergeKbCsvUpload(formDataFactory) {
45
+ return apiAdminUpload('/admin/knowledge-base/upload', formDataFactory, { auth: true })
46
+ }
frontend/src/api/adminHttp.js ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ clearAdminSession,
3
+ getAdminAccessToken,
4
+ getAdminRefreshToken,
5
+ getStoredAdmin,
6
+ setAdminSession,
7
+ } from '../auth/adminStorage'
8
+
9
+ async function readDetail(res) {
10
+ try {
11
+ const data = await res.json()
12
+ const d = data.detail
13
+ if (typeof d === 'string') return d
14
+ if (Array.isArray(d))
15
+ return d.map((e) => e.msg || JSON.stringify(e)).join(' ')
16
+ return data.message || res.statusText
17
+ } catch {
18
+ return res.statusText || 'Request failed'
19
+ }
20
+ }
21
+
22
+ async function postAdminRefresh() {
23
+ const rt = getAdminRefreshToken()
24
+ if (!rt) return null
25
+ const res = await fetch('/admin/refresh', {
26
+ method: 'POST',
27
+ headers: { 'Content-Type': 'application/json' },
28
+ body: JSON.stringify({ refresh_token: rt }),
29
+ })
30
+ if (!res.ok) return null
31
+ const text = await res.text()
32
+ return text ? JSON.parse(text) : null
33
+ }
34
+
35
+ function redirectToAdminLogin() {
36
+ clearAdminSession()
37
+ if (typeof window !== 'undefined') {
38
+ window.location.assign('/admin/login')
39
+ }
40
+ }
41
+
42
+ export async function apiAdminJson(path, options = {}) {
43
+ const { auth = false, ...fetchOpts } = options
44
+
45
+ function buildHeaders() {
46
+ const h = {
47
+ 'Content-Type': 'application/json',
48
+ ...(fetchOpts.headers || {}),
49
+ }
50
+ if (auth) {
51
+ const access = getAdminAccessToken()
52
+ if (access) {
53
+ h.Authorization = `Bearer ${access}`
54
+ }
55
+ }
56
+ return h
57
+ }
58
+
59
+ let res = await fetch(path, {
60
+ ...fetchOpts,
61
+ headers: buildHeaders(),
62
+ })
63
+
64
+ if (res.status === 401 && auth) {
65
+ const data = await postAdminRefresh()
66
+ if (data?.access_token && data?.refresh_token) {
67
+ setAdminSession({
68
+ access_token: data.access_token,
69
+ refresh_token: data.refresh_token,
70
+ admin: getStoredAdmin(),
71
+ })
72
+ res = await fetch(path, {
73
+ ...fetchOpts,
74
+ headers: buildHeaders(),
75
+ })
76
+ } else {
77
+ redirectToAdminLogin()
78
+ throw new Error('Session expired')
79
+ }
80
+ }
81
+
82
+ if (!res.ok) {
83
+ if (res.status === 401 && auth) {
84
+ redirectToAdminLogin()
85
+ }
86
+ throw new Error(await readDetail(res))
87
+ }
88
+
89
+ if (res.status === 204) return null
90
+ const text = await res.text()
91
+ return text ? JSON.parse(text) : null
92
+ }
93
+
94
+ /**
95
+ * Multipart POST; pass a factory so body can be recreated after token refresh.
96
+ * @param {string} path
97
+ * @param {() => FormData} formDataFactory
98
+ * @param {{ auth?: boolean }} options
99
+ */
100
+ export async function apiAdminUpload(path, formDataFactory, options = {}) {
101
+ const { auth = false } = options
102
+
103
+ function authHeaders() {
104
+ const h = {}
105
+ if (auth) {
106
+ const access = getAdminAccessToken()
107
+ if (access) {
108
+ h.Authorization = `Bearer ${access}`
109
+ }
110
+ }
111
+ return h
112
+ }
113
+
114
+ let res = await fetch(path, {
115
+ method: 'POST',
116
+ headers: authHeaders(),
117
+ body: formDataFactory(),
118
+ })
119
+
120
+ if (res.status === 401 && auth) {
121
+ const data = await postAdminRefresh()
122
+ if (data?.access_token && data?.refresh_token) {
123
+ setAdminSession({
124
+ access_token: data.access_token,
125
+ refresh_token: data.refresh_token,
126
+ admin: getStoredAdmin(),
127
+ })
128
+ res = await fetch(path, {
129
+ method: 'POST',
130
+ headers: authHeaders(),
131
+ body: formDataFactory(),
132
+ })
133
+ } else {
134
+ redirectToAdminLogin()
135
+ throw new Error('Session expired')
136
+ }
137
+ }
138
+
139
+ if (!res.ok) {
140
+ if (res.status === 401 && auth) {
141
+ redirectToAdminLogin()
142
+ }
143
+ throw new Error(await readDetail(res))
144
+ }
145
+
146
+ const text = await res.text()
147
+ return text ? JSON.parse(text) : null
148
+ }
frontend/src/api/auth.js ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { apiJson } from './http'
2
+
3
+ export function login(email, password) {
4
+ return apiJson('/users/login', {
5
+ method: 'POST',
6
+ body: JSON.stringify({ email, password }),
7
+ auth: false,
8
+ })
9
+ }
10
+
11
+ export function signup({ email, password, full_name }) {
12
+ const body = { email, password }
13
+ if (full_name?.trim()) body.full_name = full_name.trim()
14
+ return apiJson('/users', {
15
+ method: 'POST',
16
+ body: JSON.stringify(body),
17
+ auth: false,
18
+ })
19
+ }
20
+
21
+ export function refreshTokens(refresh_token) {
22
+ return apiJson('/users/refresh', {
23
+ method: 'POST',
24
+ body: JSON.stringify({ refresh_token }),
25
+ auth: false,
26
+ })
27
+ }
28
+
29
+ export function getProfile() {
30
+ return apiJson('/users/me', { auth: true })
31
+ }
32
+
33
+ export function updateProfile(body) {
34
+ return apiJson('/users/me', {
35
+ method: 'PATCH',
36
+ body: JSON.stringify(body),
37
+ auth: true,
38
+ })
39
+ }
frontend/src/api/chat.js ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { apiJson } from './http'
2
+
3
+ export function listChats({ skip = 0, limit = 30 } = {}) {
4
+ const q = new URLSearchParams({
5
+ skip: String(skip),
6
+ limit: String(limit),
7
+ })
8
+ return apiJson(`/list_chats?${q}`, { auth: true })
9
+ }
10
+
11
+ export function createChat() {
12
+ return apiJson('/get_new_chat', { method: 'POST', auth: true })
13
+ }
14
+
15
+ /** Latest page: omit beforeIndex. Older: pass next_before_index from prior response. */
16
+ export function fetchChatPage(chatId, { beforeIndex = null, limit = 20 } = {}) {
17
+ const q = new URLSearchParams({ limit: String(limit) })
18
+ if (beforeIndex != null) q.set('before_index', String(beforeIndex))
19
+ return apiJson(`/get_chat/${encodeURIComponent(chatId)}?${q}`, { auth: true })
20
+ }
21
+
22
+ export function removeChat(chatId) {
23
+ return apiJson(`/delete_chat/${encodeURIComponent(chatId)}`, {
24
+ method: 'DELETE',
25
+ auth: true,
26
+ })
27
+ }
28
+
29
+ export function sendMessage(
30
+ chatId,
31
+ question,
32
+ {
33
+ allowAugmentation = true,
34
+ useWebSearch = false,
35
+ } = {},
36
+ ) {
37
+ return apiJson('/response', {
38
+ method: 'POST',
39
+ body: JSON.stringify({
40
+ chat_id: chatId,
41
+ question,
42
+ allow_augmentation: allowAugmentation,
43
+ use_web_search: useWebSearch,
44
+ }),
45
+ auth: true,
46
+ })
47
+ }
frontend/src/api/http.js ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ clearSession,
3
+ getAccessToken,
4
+ getRefreshToken,
5
+ getStoredUser,
6
+ setSession,
7
+ } from '../auth/storage'
8
+
9
+ async function readDetail(res) {
10
+ try {
11
+ const data = await res.json()
12
+ const d = data.detail
13
+ if (typeof d === 'string') return d
14
+ if (Array.isArray(d))
15
+ return d.map((e) => e.msg || JSON.stringify(e)).join(' ')
16
+ return data.message || res.statusText
17
+ } catch {
18
+ return res.statusText || 'Request failed'
19
+ }
20
+ }
21
+
22
+ async function postRefresh() {
23
+ const rt = getRefreshToken()
24
+ if (!rt) return null
25
+ const res = await fetch('/users/refresh', {
26
+ method: 'POST',
27
+ headers: { 'Content-Type': 'application/json' },
28
+ body: JSON.stringify({ refresh_token: rt }),
29
+ })
30
+ if (!res.ok) return null
31
+ const text = await res.text()
32
+ return text ? JSON.parse(text) : null
33
+ }
34
+
35
+ function redirectToLogin() {
36
+ clearSession()
37
+ if (typeof window !== 'undefined') {
38
+ window.location.assign('/login')
39
+ }
40
+ }
41
+
42
+ /**
43
+ * @param {string} path
44
+ * @param {RequestInit & { auth?: boolean }} options - set auth: true to send Bearer and refresh on 401
45
+ */
46
+ export async function apiJson(path, options = {}) {
47
+ const { auth = false, ...fetchOpts } = options
48
+
49
+ function buildHeaders() {
50
+ const h = {
51
+ 'Content-Type': 'application/json',
52
+ ...(fetchOpts.headers || {}),
53
+ }
54
+ if (auth) {
55
+ const access = getAccessToken()
56
+ if (access) {
57
+ h.Authorization = `Bearer ${access}`
58
+ }
59
+ }
60
+ return h
61
+ }
62
+
63
+ let res = await fetch(path, {
64
+ ...fetchOpts,
65
+ headers: buildHeaders(),
66
+ })
67
+
68
+ if (res.status === 401 && auth) {
69
+ const data = await postRefresh()
70
+ if (data?.access_token && data?.refresh_token) {
71
+ setSession({
72
+ access_token: data.access_token,
73
+ refresh_token: data.refresh_token,
74
+ user: getStoredUser(),
75
+ })
76
+ res = await fetch(path, {
77
+ ...fetchOpts,
78
+ headers: buildHeaders(),
79
+ })
80
+ } else {
81
+ redirectToLogin()
82
+ throw new Error('Session expired')
83
+ }
84
+ }
85
+
86
+ if (!res.ok) {
87
+ if (res.status === 401 && auth) {
88
+ redirectToLogin()
89
+ }
90
+ throw new Error(await readDetail(res))
91
+ }
92
+
93
+ if (res.status === 204) return null
94
+ const text = await res.text()
95
+ return text ? JSON.parse(text) : null
96
+ }
frontend/src/assets/hero.png ADDED
frontend/src/assets/react.svg ADDED
frontend/src/assets/vite.svg ADDED
frontend/src/auth/RequireAdminAuth.jsx ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Navigate, useLocation } from 'react-router-dom'
2
+ import { getAdminAccessToken } from './adminStorage'
3
+
4
+ export default function RequireAdminAuth({ children }) {
5
+ const location = useLocation()
6
+ const token = getAdminAccessToken()
7
+ if (!token) {
8
+ return <Navigate to="/admin/login" replace state={{ from: location.pathname }} />
9
+ }
10
+ return children
11
+ }
frontend/src/auth/RequireAuth.jsx ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Navigate, useLocation } from 'react-router-dom'
2
+ import { getAccessToken } from './storage'
3
+
4
+ export default function RequireAuth({ children }) {
5
+ const location = useLocation()
6
+ const token = getAccessToken()
7
+
8
+ if (!token) {
9
+ return <Navigate to="/login" replace state={{ from: location.pathname }} />
10
+ }
11
+
12
+ return children
13
+ }
frontend/src/auth/adminStorage.js ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const ACCESS = 'comsats_admin_access_token'
2
+ const REFRESH = 'comsats_admin_refresh_token'
3
+ const ADMIN = 'comsats_admin_profile'
4
+
5
+ export function setAdminSession({ access_token, refresh_token, admin }) {
6
+ if (access_token) localStorage.setItem(ACCESS, access_token)
7
+ if (refresh_token) localStorage.setItem(REFRESH, refresh_token)
8
+ if (admin) localStorage.setItem(ADMIN, JSON.stringify(admin))
9
+ }
10
+
11
+ export function getAdminAccessToken() {
12
+ return localStorage.getItem(ACCESS)
13
+ }
14
+
15
+ export function getAdminRefreshToken() {
16
+ return localStorage.getItem(REFRESH)
17
+ }
18
+
19
+ export function getStoredAdmin() {
20
+ try {
21
+ const raw = localStorage.getItem(ADMIN)
22
+ return raw ? JSON.parse(raw) : null
23
+ } catch {
24
+ return null
25
+ }
26
+ }
27
+
28
+ export function clearAdminSession() {
29
+ localStorage.removeItem(ACCESS)
30
+ localStorage.removeItem(REFRESH)
31
+ localStorage.removeItem(ADMIN)
32
+ }
frontend/src/auth/storage.js ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const ACCESS = 'comsats_access_token'
2
+ const REFRESH = 'comsats_refresh_token'
3
+ const USER = 'comsats_user'
4
+
5
+ export function setSession({ access_token, refresh_token, user }) {
6
+ if (access_token) localStorage.setItem(ACCESS, access_token)
7
+ if (refresh_token) localStorage.setItem(REFRESH, refresh_token)
8
+ if (user) localStorage.setItem(USER, JSON.stringify(user))
9
+ }
10
+
11
+ export function getAccessToken() {
12
+ return localStorage.getItem(ACCESS)
13
+ }
14
+
15
+ export function getRefreshToken() {
16
+ return localStorage.getItem(REFRESH)
17
+ }
18
+
19
+ export function getStoredUser() {
20
+ try {
21
+ const raw = localStorage.getItem(USER)
22
+ return raw ? JSON.parse(raw) : null
23
+ } catch {
24
+ return null
25
+ }
26
+ }
27
+
28
+ export function clearSession() {
29
+ localStorage.removeItem(ACCESS)
30
+ localStorage.removeItem(REFRESH)
31
+ localStorage.removeItem(USER)
32
+ }
33
+
34
+ /** Merge into stored user without touching tokens */
35
+ export function patchStoredUser(updates) {
36
+ const u = getStoredUser()
37
+ if (!u) return
38
+ localStorage.setItem(USER, JSON.stringify({ ...u, ...updates }))
39
+ }
frontend/src/components/ComsatsLogo.jsx ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Official COMSATS seal — colors align with @theme (--color-comsats-purple / --color-comsats-blue).
3
+ * White circular frame keeps any non-transparent PNG edges clean on gradients.
4
+ */
5
+ export default function ComsatsLogo({
6
+ className = 'h-24 w-24 md:h-28 md:w-28',
7
+ alt = 'COMSATS University Islamabad',
8
+ }) {
9
+ return (
10
+ <div
11
+ className={`shrink-0 rounded-full bg-white p-2 shadow-lg shadow-comsats-purple/20 ring-2 ring-comsats-blue/30 ${className}`}
12
+ >
13
+ <img
14
+ src="/comsats-logo.png"
15
+ alt={alt}
16
+ className="h-full w-full rounded-full object-contain"
17
+ decoding="async"
18
+ draggable={false}
19
+ />
20
+ </div>
21
+ )
22
+ }
frontend/src/components/chat/ChatMain.jsx ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { forwardRef, useEffect, useRef, useState } from 'react'
2
+ import ReactMarkdown from 'react-markdown'
3
+ import remarkGfm from 'remark-gfm'
4
+ import ComsatsLogo from '../ComsatsLogo'
5
+ import { MessageRoleSticker } from './MessageRoleSticker'
6
+
7
+ function AssistantAvatarIcon({ className = '' }) {
8
+ return (
9
+ <svg
10
+ className={className}
11
+ viewBox="0 0 24 24"
12
+ fill="none"
13
+ stroke="currentColor"
14
+ strokeWidth="2"
15
+ aria-hidden
16
+ >
17
+ <path
18
+ strokeLinecap="round"
19
+ strokeLinejoin="round"
20
+ d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
21
+ />
22
+ </svg>
23
+ )
24
+ }
25
+
26
+ function SendIcon({ className = '' }) {
27
+ return (
28
+ <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
29
+ <path d="M3.478 2.404a.75.75 0 00-.926.941l2.432 7.905H13.5a.75.75 0 010 1.5H4.984l-2.432 7.905a.75.75 0 00.926.94 60.519 60.519 0 0018.445-8.986.75.75 0 000-1.218A60.517 60.517 0 003.478 2.404z" />
30
+ </svg>
31
+ )
32
+ }
33
+
34
+ function DotsVerticalIcon({ className = '' }) {
35
+ return (
36
+ <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
37
+ <circle cx="12" cy="6" r="1.75" />
38
+ <circle cx="12" cy="12" r="1.75" />
39
+ <circle cx="12" cy="18" r="1.75" />
40
+ </svg>
41
+ )
42
+ }
43
+
44
+ function CheckMiniIcon({ className = '' }) {
45
+ return (
46
+ <svg className={className} viewBox="0 0 20 20" fill="currentColor" aria-hidden>
47
+ <path
48
+ fillRule="evenodd"
49
+ d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z"
50
+ clipRule="evenodd"
51
+ />
52
+ </svg>
53
+ )
54
+ }
55
+
56
+ function SparklesIcon({ className = '' }) {
57
+ return (
58
+ <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden>
59
+ <path d="M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456z" />
60
+ </svg>
61
+ )
62
+ }
63
+
64
+ function MarkdownText({ content, tone = 'assistant' }) {
65
+ const linkClass =
66
+ tone === 'user'
67
+ ? 'underline decoration-white/60 hover:decoration-white'
68
+ : 'font-medium text-comsats-blue underline decoration-comsats-blue/25 underline-offset-2 hover:text-comsats-purple'
69
+
70
+ const codeBg =
71
+ tone === 'user' ? 'bg-white/20 text-white' : 'bg-slate-100 text-slate-900 ring-1 ring-slate-200/80'
72
+
73
+ const codeBlockBg =
74
+ tone === 'user' ? 'bg-black/25 text-white' : 'bg-slate-50 text-slate-900 ring-1 ring-slate-200/90'
75
+
76
+ return (
77
+ <ReactMarkdown
78
+ remarkPlugins={[remarkGfm]}
79
+ components={{
80
+ p: ({ children }) => (
81
+ <p className="m-0 whitespace-pre-wrap text-[15px] leading-[1.65] [&:not(:first-child)]:mt-3">
82
+ {children}
83
+ </p>
84
+ ),
85
+ ul: ({ children }) => <ul className="my-3 list-disc space-y-1.5 pl-5 text-[15px] leading-relaxed">{children}</ul>,
86
+ ol: ({ children }) => <ol className="my-3 list-decimal space-y-1.5 pl-5 text-[15px] leading-relaxed">{children}</ol>,
87
+ li: ({ children }) => <li className="leading-relaxed">{children}</li>,
88
+ a: ({ href, children }) => (
89
+ <a href={href} target="_blank" rel="noopener noreferrer" className={linkClass}>
90
+ {children}
91
+ </a>
92
+ ),
93
+ strong: ({ children }) => (
94
+ <strong
95
+ className={
96
+ tone === 'user' ? 'font-semibold text-white' : 'font-semibold text-slate-900'
97
+ }
98
+ >
99
+ {children}
100
+ </strong>
101
+ ),
102
+ code: ({ inline, children }) =>
103
+ inline ? (
104
+ <code className={`rounded-md px-1.5 py-0.5 text-[0.88em] ${codeBg}`}>{children}</code>
105
+ ) : (
106
+ <code className={`block overflow-x-auto rounded-xl p-4 text-[13px] leading-relaxed ${codeBlockBg}`}>
107
+ {children}
108
+ </code>
109
+ ),
110
+ }}
111
+ >
112
+ {content ?? ''}
113
+ </ReactMarkdown>
114
+ )
115
+ }
116
+
117
+ const EMPTY_THREAD_STARTERS = [
118
+ 'What programs are offered at COMSATS Attock?',
119
+ 'How do I apply for admissions?',
120
+ 'Tell me about campus facilities and fees.',
121
+ ]
122
+
123
+ const ChatMain = forwardRef(function ChatMain(
124
+ {
125
+ chatId,
126
+ chatTitle = 'Conversation',
127
+ turns,
128
+ loadingChat,
129
+ loadingOlder,
130
+ hasOlder,
131
+ onLoadOlder,
132
+ sending,
133
+ tailBump,
134
+ error,
135
+ question,
136
+ setQuestion,
137
+ onSend,
138
+ followUpSuggestions = [],
139
+ suggestionsEnabled = true,
140
+ onSuggestionsEnabledChange,
141
+ webSearchEnabled = false,
142
+ onWebSearchEnabledChange,
143
+ onPickFollowUp,
144
+ sidebarExpanded = true,
145
+ collapsedSidebarRail = false,
146
+ onOpenSidebar = () => {},
147
+ },
148
+ scrollRef,
149
+ ) {
150
+ const [sourceMenuOpen, setSourceMenuOpen] = useState(false)
151
+ const sourceMenuWrapRef = useRef(null)
152
+
153
+ useEffect(() => {
154
+ if (!sourceMenuOpen) return
155
+ function handlePointerDown(e) {
156
+ const el = sourceMenuWrapRef.current
157
+ if (el && !el.contains(e.target)) setSourceMenuOpen(false)
158
+ }
159
+ function handleKey(e) {
160
+ if (e.key === 'Escape') setSourceMenuOpen(false)
161
+ }
162
+ document.addEventListener('mousedown', handlePointerDown)
163
+ window.addEventListener('keydown', handleKey)
164
+ return () => {
165
+ document.removeEventListener('mousedown', handlePointerDown)
166
+ window.removeEventListener('keydown', handleKey)
167
+ }
168
+ }, [sourceMenuOpen])
169
+
170
+ useEffect(() => {
171
+ if (!chatId || loadingChat) return
172
+ const el = scrollRef?.current
173
+ if (!el) return
174
+ const scrollToEnd = () => {
175
+ el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' })
176
+ }
177
+ requestAnimationFrame(() => {
178
+ requestAnimationFrame(scrollToEnd)
179
+ })
180
+ }, [chatId, loadingChat, tailBump])
181
+
182
+ const showHeaderOpenSidebar =
183
+ !sidebarExpanded && !collapsedSidebarRail
184
+
185
+ const headerTools = (
186
+ <div className="flex w-full shrink-0 flex-wrap items-center justify-end gap-2 sm:w-auto sm:gap-3">
187
+ <div className="flex items-center gap-2 rounded-full bg-slate-50 px-2 py-1 ring-1 ring-slate-200/70">
188
+ <span className="hidden text-[11px] font-medium text-slate-500 sm:inline">Follow-ups</span>
189
+ <button
190
+ type="button"
191
+ role="switch"
192
+ aria-checked={suggestionsEnabled}
193
+ title={suggestionsEnabled ? 'Follow-up ideas on' : 'Follow-up ideas off'}
194
+ onClick={() => onSuggestionsEnabledChange?.(!suggestionsEnabled)}
195
+ className={`relative h-7 w-11 shrink-0 rounded-full transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-2 ${
196
+ suggestionsEnabled ? 'bg-comsats-purple' : 'bg-slate-300'
197
+ }`}
198
+ >
199
+ <span
200
+ className={`absolute top-0.5 left-0.5 h-6 w-6 rounded-full bg-white shadow transition-transform duration-200 ease-out ${
201
+ suggestionsEnabled ? 'translate-x-[1.125rem]' : 'translate-x-0'
202
+ }`}
203
+ />
204
+ </button>
205
+ </div>
206
+ </div>
207
+ )
208
+
209
+ if (!chatId) {
210
+ return (
211
+ <main className="relative flex min-h-0 flex-1 flex-col bg-gradient-to-b from-slate-50 via-chat-canvas to-slate-100/80">
212
+ <header className="flex h-14 shrink-0 items-center gap-3 border-b border-slate-200/60 bg-white/80 px-3 backdrop-blur-md md:hidden">
213
+ {showHeaderOpenSidebar ? (
214
+ <button
215
+ type="button"
216
+ onClick={() => onOpenSidebar()}
217
+ className="flex shrink-0 rounded-xl bg-white p-0.5 shadow-sm ring-1 ring-slate-200/80 transition-shadow hover:ring-comsats-purple/25"
218
+ aria-label="Open sidebar"
219
+ >
220
+ <ComsatsLogo className="h-9 w-9" />
221
+ </button>
222
+ ) : null}
223
+ <span className="min-w-0 truncate text-sm font-semibold text-slate-800">COMSATS Chat</span>
224
+ </header>
225
+ <div className="flex flex-1 flex-col items-center justify-center px-4 py-12 text-center">
226
+ <div className="mx-auto max-w-md rounded-3xl border border-white/80 bg-white/90 p-8 shadow-[0_20px_60px_-24px_rgba(75,46,131,0.35)] ring-1 ring-slate-200/60 backdrop-blur-sm">
227
+ <div
228
+ className="mx-auto mb-5 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-comsats-purple/12 to-comsats-blue/15 text-comsats-purple shadow-inner"
229
+ aria-hidden
230
+ >
231
+ <AssistantAvatarIcon className="h-8 w-8" />
232
+ </div>
233
+ <h1 className="text-2xl font-semibold tracking-tight text-slate-900">COMSATS assistant</h1>
234
+ <p className="mt-3 text-[15px] leading-relaxed text-slate-600">
235
+ Open the sidebar to pick a chat or start fresh — admissions, programs, and campus questions
236
+ welcome.
237
+ </p>
238
+ </div>
239
+ </div>
240
+ </main>
241
+ )
242
+ }
243
+
244
+ const showEmptyWelcome = !loadingChat && turns.length === 0 && !sending
245
+
246
+ return (
247
+ <main className="flex min-h-0 flex-1 flex-col overflow-hidden bg-gradient-to-b from-slate-50/95 via-chat-canvas to-slate-100/70">
248
+ <header
249
+ className="flex min-h-[3.25rem] shrink-0 flex-col gap-2 border-b border-slate-200/60 bg-white/85 px-3 py-2 shadow-[0_1px_0_rgba(0,0,0,0.03)] backdrop-blur-md sm:min-h-14 sm:flex-row sm:items-center sm:gap-x-3 md:flex-wrap md:px-6 md:py-2.5"
250
+ title={chatId ? `Technical ID (support): ${chatId}` : undefined}
251
+ >
252
+ {showHeaderOpenSidebar ? (
253
+ <button
254
+ type="button"
255
+ onClick={() => onOpenSidebar()}
256
+ className="flex shrink-0 rounded-xl bg-white p-0.5 shadow-md shadow-slate-900/5 ring-1 ring-slate-200/90 transition-all hover:ring-comsats-purple/30 hover:shadow-comsats-purple/10"
257
+ aria-label="Open sidebar"
258
+ >
259
+ <ComsatsLogo className="h-9 w-9 md:h-10 md:w-10" />
260
+ </button>
261
+ ) : null}
262
+ <div className="flex min-w-0 flex-1 flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
263
+ <div className="min-w-0 flex-1">
264
+ <h2 className="line-clamp-2 text-[15px] font-semibold leading-snug text-slate-900 sm:line-clamp-2 md:line-clamp-1">
265
+ {chatTitle}
266
+ </h2>
267
+ <p className="mt-0.5 text-[11px] text-slate-500 sm:text-[12px]">
268
+ <span className="font-medium text-comsats-purple/90">COMSATS Attock</span>
269
+ <span className="mx-1.5 text-slate-300">·</span>
270
+ Knowledge assistant
271
+ </p>
272
+ </div>
273
+ {headerTools}
274
+ </div>
275
+ </header>
276
+
277
+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto">
278
+ {loadingChat ? (
279
+ <div className="flex flex-col items-center justify-center gap-3 py-24">
280
+ <div className="h-8 w-8 animate-spin rounded-full border-2 border-comsats-purple/20 border-t-comsats-purple" />
281
+ <p className="text-[14px] font-medium text-slate-500">Loading messages…</p>
282
+ </div>
283
+ ) : (
284
+ <div className="mx-auto w-full max-w-[min(100%,56rem)] pb-4 pt-2 sm:pb-5 md:pb-6 md:pt-4">
285
+ {hasOlder ? (
286
+ <div className="mb-6 flex justify-center px-4">
287
+ <button
288
+ type="button"
289
+ disabled={loadingOlder}
290
+ onClick={onLoadOlder}
291
+ className="rounded-full border border-slate-200/90 bg-white px-5 py-2 text-[13px] font-medium text-comsats-purple shadow-sm transition-all hover:border-comsats-purple/25 hover:bg-comsats-purple/[0.04] hover:shadow disabled:opacity-50"
292
+ >
293
+ {loadingOlder ? 'Loading older…' : 'Load older messages'}
294
+ </button>
295
+ </div>
296
+ ) : null}
297
+
298
+ {showEmptyWelcome ? (
299
+ <div className="flex flex-col items-center px-3 py-10 text-center sm:px-5 sm:py-14 md:py-20">
300
+ <div className="mb-6 flex h-[4.5rem] w-[4.5rem] items-center justify-center rounded-3xl bg-white shadow-[0_12px_40px_-16px_rgba(0,94,184,0.35)] ring-1 ring-comsats-blue/15">
301
+ <SparklesIcon className="h-9 w-9 text-comsats-blue" />
302
+ </div>
303
+ <p className="max-w-xl text-2xl font-semibold tracking-tight text-slate-900 md:text-[1.65rem]">
304
+ What would you like to know?
305
+ </p>
306
+ <p className="mt-3 max-w-lg text-[15px] leading-relaxed text-slate-600">
307
+ I can help with programs, admissions, fees, and campus life. After you open a chat,
308
+ use the <span className="font-semibold text-slate-700">⋯</span> menu next to the
309
+ message box to choose{' '}
310
+ <span className="font-semibold text-comsats-purple">RAG</span> (knowledge base) or{' '}
311
+ <span className="font-semibold text-comsats-blue">Web search</span>.
312
+ </p>
313
+ <p className="mt-10 text-[12px] font-semibold uppercase tracking-[0.12em] text-slate-400">
314
+ Try one of these
315
+ </p>
316
+ <div className="mt-4 grid w-full max-w-xl gap-3">
317
+ {EMPTY_THREAD_STARTERS.map((s) => (
318
+ <button
319
+ key={s}
320
+ type="button"
321
+ onClick={() => onPickFollowUp?.(s)}
322
+ className="group rounded-2xl border border-slate-200/90 bg-white px-5 py-4 text-left text-[15px] font-medium text-slate-800 shadow-[0_2px_8px_rgba(0,0,0,0.04)] ring-1 ring-white transition-all hover:-translate-y-0.5 hover:border-comsats-purple/30 hover:shadow-[0_12px_28px_-12px_rgba(75,46,131,0.25)]"
323
+ dir="auto"
324
+ >
325
+ <span className="flex items-start gap-3">
326
+ <span className="mt-1 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-comsats-purple/10 text-comsats-purple transition-colors group-hover:bg-comsats-purple group-hover:text-white">
327
+ <SparklesIcon className="h-3.5 w-3.5" />
328
+ </span>
329
+ <span className="leading-snug">{s}</span>
330
+ </span>
331
+ </button>
332
+ ))}
333
+ </div>
334
+ </div>
335
+ ) : null}
336
+
337
+ <div className="flex flex-col divide-y divide-slate-200/50">
338
+ {turns.map((turn) => {
339
+ const key =
340
+ turn.clientKey != null ? turn.clientKey : `pair-${turn.pairIndex ?? 'x'}`
341
+ return (
342
+ <article key={key} className="first:pt-0">
343
+ <div className="space-y-4 px-3 py-5 sm:space-y-5 sm:px-5 md:space-y-6 md:px-8 md:py-8">
344
+ <div className="flex justify-end">
345
+ <div className="flex max-w-[min(100%,min(92vw,36rem))] items-end gap-2 sm:gap-3">
346
+ <div
347
+ className="min-w-0 rounded-[1.35rem] rounded-br-lg bg-gradient-to-br from-comsats-purple to-[#3d2469] px-4 py-3 text-[14px] leading-relaxed text-white shadow-lg shadow-comsats-purple/25 ring-1 ring-white/15 sm:px-[18px] sm:py-3.5 sm:text-[15px]"
348
+ dir="auto"
349
+ >
350
+ <span className="sr-only">You: </span>
351
+ <MarkdownText content={turn.question} tone="user" />
352
+ </div>
353
+ <MessageRoleSticker role="user" />
354
+ </div>
355
+ </div>
356
+
357
+ <div className="flex items-start gap-2 sm:gap-3 md:gap-4">
358
+ <MessageRoleSticker role="assistant" />
359
+ <div
360
+ className="min-w-0 flex-1 rounded-2xl bg-white px-4 py-4 shadow-[0_2px_12px_rgba(0,0,0,0.05)] ring-1 ring-slate-200/70 md:rounded-[1.35rem] md:px-6 md:py-5"
361
+ dir="auto"
362
+ >
363
+ <span className="sr-only">Assistant: </span>
364
+ {turn.pending ? (
365
+ <span className="inline-flex items-center gap-2.5 text-[15px] text-slate-500">
366
+ <span className="inline-flex gap-1">
367
+ <span className="h-2 w-2 animate-bounce rounded-full bg-comsats-blue [animation-delay:-0.3s]" />
368
+ <span className="h-2 w-2 animate-bounce rounded-full bg-comsats-blue [animation-delay:-0.15s]" />
369
+ <span className="h-2 w-2 animate-bounce rounded-full bg-comsats-blue" />
370
+ </span>
371
+ Thinking…
372
+ </span>
373
+ ) : (
374
+ <div className="text-slate-800">
375
+ <MarkdownText content={turn.answer} tone="assistant" />
376
+ </div>
377
+ )}
378
+ </div>
379
+ </div>
380
+ </div>
381
+ </article>
382
+ )
383
+ })}
384
+ </div>
385
+ </div>
386
+ )}
387
+ </div>
388
+
389
+ {error ? (
390
+ <div className="border-t border-red-200/80 bg-red-50 px-4 py-2.5 text-center text-[13px] font-medium text-red-800">
391
+ {error}
392
+ </div>
393
+ ) : null}
394
+
395
+ <footer className="relative shrink-0 border-t border-slate-200/60 bg-gradient-to-t from-white via-white to-slate-50/90 pb-[max(0.5rem,env(safe-area-inset-bottom))] shadow-[0_-8px_30px_rgba(0,0,0,0.04)]">
396
+ {suggestionsEnabled && followUpSuggestions.length > 0 && !sending ? (
397
+ <div className="border-b border-slate-100/90 bg-white/60 px-2 py-2 sm:px-4 md:px-6">
398
+ <div className="mx-auto flex max-w-[min(100%,56rem)] items-center gap-2">
399
+ <span className="flex shrink-0 items-center gap-1 text-[10px] font-bold uppercase tracking-wider text-slate-400">
400
+ <SparklesIcon className="h-3.5 w-3.5 text-comsats-purple" aria-hidden />
401
+ Ideas
402
+ </span>
403
+ <div className="no-scrollbar flex min-w-0 flex-1 gap-2 overflow-x-auto py-0.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
404
+ {followUpSuggestions.map((s, i) => (
405
+ <button
406
+ key={`${i}-${s.slice(0, 24)}`}
407
+ type="button"
408
+ onClick={() => onPickFollowUp?.(s)}
409
+ className="max-w-[min(85vw,20rem)] shrink-0 rounded-full border border-slate-200/90 bg-white px-3 py-1.5 text-left text-[11px] font-medium leading-snug text-slate-800 shadow-sm ring-slate-900/[0.02] transition-colors hover:border-comsats-purple/35 hover:bg-comsats-purple/[0.04] sm:max-w-xs sm:text-xs md:text-[13px]"
410
+ dir="auto"
411
+ title={s}
412
+ >
413
+ <span className="line-clamp-2">{s}</span>
414
+ </button>
415
+ ))}
416
+ </div>
417
+ </div>
418
+ <p className="sr-only">Suggested follow-up questions; swipe sideways or tap one.</p>
419
+ </div>
420
+ ) : null}
421
+
422
+ <div className="mx-auto max-w-[min(100%,56rem)] px-3 pb-4 pt-3 sm:px-5 sm:pb-5 sm:pt-4 md:px-8 md:pb-6 md:pt-5">
423
+ <div className="mb-2 flex flex-wrap items-center gap-2 px-0.5">
424
+ <span className="text-[11px] font-medium text-slate-500">Answer source</span>
425
+ <span
426
+ className={`inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-bold uppercase tracking-wide ring-1 ${
427
+ webSearchEnabled
428
+ ? 'bg-comsats-blue/12 text-comsats-blue ring-comsats-blue/25'
429
+ : 'bg-comsats-purple/12 text-comsats-purple ring-comsats-purple/25'
430
+ }`}
431
+ >
432
+ {webSearchEnabled ? 'Web search' : 'RAG'}
433
+ </span>
434
+ </div>
435
+ <form
436
+ onSubmit={(e) => {
437
+ e.preventDefault()
438
+ onSend()
439
+ }}
440
+ className="relative flex items-end gap-1 rounded-[28px] border border-slate-200/90 bg-white px-2 py-2 shadow-[0_4px_24px_rgba(0,0,0,0.06)] ring-slate-900/[0.02] transition-[border-color,box-shadow] focus-within:border-comsats-blue/40 focus-within:shadow-[0_8px_32px_-8px_rgba(0,94,184,0.22)] focus-within:ring-2 focus-within:ring-comsats-blue/18 sm:gap-2 sm:px-3 sm:py-2.5"
441
+ >
442
+ <label htmlFor="chat-composer" className="sr-only">
443
+ Message
444
+ </label>
445
+ <div ref={sourceMenuWrapRef} className="relative shrink-0 self-end pb-1">
446
+ <button
447
+ type="button"
448
+ aria-expanded={sourceMenuOpen}
449
+ aria-haspopup="menu"
450
+ aria-label="Choose answer source: RAG or Web search"
451
+ onClick={() => setSourceMenuOpen((o) => !o)}
452
+ className="flex h-10 w-10 items-center justify-center rounded-xl text-slate-500 transition-colors hover:bg-slate-100 hover:text-comsats-purple focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-1"
453
+ >
454
+ <DotsVerticalIcon className="h-5 w-5" />
455
+ </button>
456
+ {sourceMenuOpen ? (
457
+ <div
458
+ role="menu"
459
+ className="absolute bottom-[calc(100%+6px)] left-0 z-40 w-[min(calc(100vw-2rem),14rem)] rounded-xl border border-slate-200/90 bg-white py-1 shadow-[0_12px_40px_-12px_rgba(0,0,0,0.25)] ring-1 ring-slate-900/5"
460
+ >
461
+ <button
462
+ type="button"
463
+ role="menuitemradio"
464
+ aria-checked={!webSearchEnabled}
465
+ className="flex w-full items-center gap-2 px-3 py-2.5 text-left text-[13px] font-medium text-slate-800 hover:bg-slate-50"
466
+ onClick={() => {
467
+ onWebSearchEnabledChange?.(false)
468
+ setSourceMenuOpen(false)
469
+ }}
470
+ >
471
+ <span className="flex w-5 shrink-0 justify-center text-comsats-purple">
472
+ {!webSearchEnabled ? <CheckMiniIcon className="h-4 w-4" /> : null}
473
+ </span>
474
+ Knowledge base (RAG)
475
+ </button>
476
+ <button
477
+ type="button"
478
+ role="menuitemradio"
479
+ aria-checked={webSearchEnabled}
480
+ className="flex w-full items-center gap-2 px-3 py-2.5 text-left text-[13px] font-medium text-slate-800 hover:bg-slate-50"
481
+ onClick={() => {
482
+ onWebSearchEnabledChange?.(true)
483
+ setSourceMenuOpen(false)
484
+ }}
485
+ >
486
+ <span className="flex w-5 shrink-0 justify-center text-comsats-blue">
487
+ {webSearchEnabled ? <CheckMiniIcon className="h-4 w-4" /> : null}
488
+ </span>
489
+ Web search
490
+ </button>
491
+ </div>
492
+ ) : null}
493
+ </div>
494
+ <textarea
495
+ id="chat-composer"
496
+ rows={1}
497
+ value={question}
498
+ onChange={(e) => setQuestion(e.target.value)}
499
+ onKeyDown={(e) => {
500
+ if (e.key === 'Enter' && !e.shiftKey) {
501
+ e.preventDefault()
502
+ if (!sending && question.trim()) onSend()
503
+ }
504
+ }}
505
+ placeholder="Ask anything about COMSATS Attock…"
506
+ disabled={sending}
507
+ className="max-h-44 min-h-[48px] min-w-0 flex-1 resize-none bg-transparent py-2.5 pr-1 text-[15px] leading-snug text-slate-900 outline-none placeholder:text-slate-400 disabled:opacity-60"
508
+ dir="auto"
509
+ />
510
+ <button
511
+ type="submit"
512
+ disabled={sending || !question.trim()}
513
+ className="mb-0.5 flex h-11 w-11 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-comsats-blue to-[#004a94] text-white shadow-md shadow-comsats-blue/25 transition-all hover:from-comsats-purple hover:to-comsats-purple hover:shadow-lg hover:shadow-comsats-purple/25 disabled:opacity-35 disabled:shadow-none"
514
+ aria-label="Send message"
515
+ >
516
+ <SendIcon className="h-[19px] w-[19px] -translate-y-px translate-x-px" />
517
+ </button>
518
+ </form>
519
+ <p className="mt-3 text-center text-[11px] leading-relaxed text-slate-400">
520
+ Answers are generated by AI — double-check important details with official COMSATS sources.
521
+ </p>
522
+ </div>
523
+ </footer>
524
+ </main>
525
+ )
526
+ })
527
+
528
+ export default ChatMain
frontend/src/components/chat/ChatSidebar.jsx ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ComsatsLogo from '../ComsatsLogo'
2
+
3
+ function PlusIcon({ className = '' }) {
4
+ return (
5
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
6
+ <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
7
+ </svg>
8
+ )
9
+ }
10
+
11
+ function ChevronLeftIcon({ className = '' }) {
12
+ return (
13
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
14
+ <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
15
+ </svg>
16
+ )
17
+ }
18
+
19
+ function UserCircleIcon({ className = '' }) {
20
+ return (
21
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
22
+ <path
23
+ strokeLinecap="round"
24
+ strokeLinejoin="round"
25
+ d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"
26
+ />
27
+ </svg>
28
+ )
29
+ }
30
+
31
+ function LogoutIcon({ className = '' }) {
32
+ return (
33
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
34
+ <path
35
+ strokeLinecap="round"
36
+ strokeLinejoin="round"
37
+ d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15m3 0l3-3m0 0l-3-3m3 3H9"
38
+ />
39
+ </svg>
40
+ )
41
+ }
42
+
43
+ export default function ChatSidebar({
44
+ user,
45
+ chats,
46
+ selectedId,
47
+ onSelectChat,
48
+ onNewChat,
49
+ onDeleteChat,
50
+ onEditProfile,
51
+ onLogout,
52
+ onCloseSidebar,
53
+ loadingList,
54
+ hasMoreChats,
55
+ loadingMoreChats,
56
+ onLoadMoreChats,
57
+ chatListTotal,
58
+ }) {
59
+ return (
60
+ <aside className="relative flex h-full min-h-0 w-full min-w-0 flex-col bg-chat-sidebar">
61
+ <div className="shrink-0 border-b border-slate-200/60 bg-gradient-to-br from-white via-chat-sidebar to-comsats-purple/[0.04] px-3 py-3.5 md:px-3.5">
62
+ <div className="flex items-start gap-2">
63
+ <div className="flex min-w-0 flex-1 items-center gap-3">
64
+ <ComsatsLogo className="h-10 w-10 shrink-0 shadow-sm ring-2 ring-white md:h-11 md:w-11" />
65
+ <div className="min-w-0 flex-1">
66
+ <p className="truncate text-[14px] font-bold tracking-tight text-comsats-purple">
67
+ COMSATS Attock
68
+ </p>
69
+ <p className="truncate text-[11px] leading-tight text-slate-500">{user?.email}</p>
70
+ </div>
71
+ </div>
72
+ <button
73
+ type="button"
74
+ onClick={onCloseSidebar}
75
+ aria-label="Close sidebar"
76
+ title="Close sidebar"
77
+ className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl border border-slate-200/80 bg-white/90 text-slate-600 shadow-sm transition-colors hover:border-comsats-purple/25 hover:bg-white hover:text-comsats-purple"
78
+ >
79
+ <ChevronLeftIcon className="h-[18px] w-[18px]" />
80
+ </button>
81
+ </div>
82
+ </div>
83
+
84
+ <div className="shrink-0 px-2.5 pb-2 pt-3 md:px-3">
85
+ <button
86
+ type="button"
87
+ onClick={onNewChat}
88
+ className="flex w-full items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-comsats-purple to-[#3d2469] px-3 py-2.5 text-[13px] font-semibold text-white shadow-md shadow-comsats-purple/25 transition-all hover:brightness-110 hover:shadow-lg active:scale-[0.99]"
89
+ >
90
+ <PlusIcon className="h-4 w-4 opacity-95" />
91
+ New chat
92
+ </button>
93
+ </div>
94
+
95
+ <div className="min-h-0 flex-1 overflow-y-auto overflow-x-hidden px-2 pb-2 md:px-2.5">
96
+ <p className="flex items-center justify-between px-1.5 pb-2 pt-1 text-[11px] font-semibold uppercase tracking-[0.08em] text-slate-400">
97
+ <span>Your chats</span>
98
+ {chatListTotal > 0 ? (
99
+ <span className="font-medium normal-case tracking-normal text-slate-400 tabular-nums">
100
+ {chats.length}/{chatListTotal}
101
+ </span>
102
+ ) : null}
103
+ </p>
104
+ {loadingList ? (
105
+ <p className="px-2 py-3 text-[13px] text-slate-500">Loading…</p>
106
+ ) : chats.length === 0 ? (
107
+ <div className="mx-2 rounded-xl border border-dashed border-slate-200/90 bg-white/50 px-3 py-6 text-center">
108
+ <p className="text-[13px] leading-relaxed text-slate-500">No chats yet. Start one above.</p>
109
+ </div>
110
+ ) : (
111
+ <ul className="flex flex-col gap-1">
112
+ {chats.map((c) => {
113
+ const active = selectedId === c.chat_id
114
+ return (
115
+ <li key={c.chat_id}>
116
+ <div
117
+ className={`group flex items-stretch overflow-hidden rounded-xl border transition-all ${
118
+ active
119
+ ? 'border-comsats-purple/25 bg-white shadow-[0_4px_14px_-6px_rgba(75,46,131,0.35)] ring-1 ring-comsats-purple/15'
120
+ : 'border-transparent hover:border-slate-200/80 hover:bg-white/70'
121
+ }`}
122
+ >
123
+ <button
124
+ type="button"
125
+ onClick={() => onSelectChat(c.chat_id)}
126
+ className={`min-w-0 flex-1 border-l-[3px] py-2.5 pl-3 pr-2 text-left ${
127
+ active ? 'border-l-comsats-purple' : 'border-l-transparent'
128
+ }`}
129
+ >
130
+ <span
131
+ className={`line-clamp-2 text-[13px] leading-snug ${
132
+ active ? 'font-semibold text-slate-900' : 'font-medium text-slate-700'
133
+ }`}
134
+ >
135
+ {c.preview}
136
+ </span>
137
+ <span className="mt-1 block text-[11px] text-slate-400">
138
+ {c.message_count ? `${c.message_count} messages` : 'Empty'}
139
+ </span>
140
+ </button>
141
+ <button
142
+ type="button"
143
+ title="Delete chat"
144
+ onClick={(e) => {
145
+ e.stopPropagation()
146
+ onDeleteChat(c.chat_id)
147
+ }}
148
+ className="shrink-0 px-2.5 text-slate-400 opacity-0 transition-opacity hover:text-red-600 group-hover:opacity-100"
149
+ >
150
+ ×
151
+ </button>
152
+ </div>
153
+ </li>
154
+ )
155
+ })}
156
+ </ul>
157
+ )}
158
+ {hasMoreChats ? (
159
+ <div className="px-1 pt-3">
160
+ <button
161
+ type="button"
162
+ disabled={loadingMoreChats || loadingList}
163
+ onClick={onLoadMoreChats}
164
+ className="w-full rounded-xl py-2.5 text-[12px] font-semibold text-comsats-purple hover:bg-white/70 disabled:opacity-50"
165
+ >
166
+ {loadingMoreChats ? 'Loading…' : 'Load more chats'}
167
+ </button>
168
+ </div>
169
+ ) : null}
170
+ </div>
171
+
172
+ <div className="shrink-0 border-t border-slate-200/60 bg-white/40 p-2 md:p-2.5">
173
+ <button
174
+ type="button"
175
+ onClick={onEditProfile}
176
+ className="flex w-full items-center gap-2.5 rounded-xl px-3 py-2.5 text-left text-[13px] font-medium text-slate-700 transition-colors hover:bg-white"
177
+ >
178
+ <UserCircleIcon className="h-5 w-5 shrink-0 text-slate-500" />
179
+ Edit profile
180
+ </button>
181
+ <button
182
+ type="button"
183
+ onClick={onLogout}
184
+ className="flex w-full items-center gap-2.5 rounded-xl px-3 py-2.5 text-left text-[13px] font-medium text-red-600 transition-colors hover:bg-red-50"
185
+ >
186
+ <LogoutIcon className="h-5 w-5 shrink-0 opacity-90" />
187
+ Log out
188
+ </button>
189
+ </div>
190
+ </aside>
191
+ )
192
+ }
frontend/src/components/chat/CollapsedSidebarRail.jsx ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ComsatsLogo from '../ComsatsLogo'
2
+
3
+ function UserCircleIcon({ className = '' }) {
4
+ return (
5
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
6
+ <path
7
+ strokeLinecap="round"
8
+ strokeLinejoin="round"
9
+ d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"
10
+ />
11
+ </svg>
12
+ )
13
+ }
14
+
15
+ function LogoutIcon({ className = '' }) {
16
+ return (
17
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
18
+ <path
19
+ strokeLinecap="round"
20
+ strokeLinejoin="round"
21
+ d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15m3 0l3-3m0 0l-3-3m3 3H9"
22
+ />
23
+ </svg>
24
+ )
25
+ }
26
+
27
+ export default function CollapsedSidebarRail({ onOpenSidebar, onEditProfile, onLogout }) {
28
+ const railBtn =
29
+ 'flex w-full flex-col items-center gap-1 rounded-xl px-1 py-2 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-1'
30
+
31
+ return (
32
+ <aside
33
+ className="hidden min-h-0 w-[84px] shrink-0 flex-col items-stretch border-r border-slate-200/70 bg-chat-sidebar px-1.5 py-3 shadow-[inset_-1px_0_0_rgba(0,0,0,0.04)] md:flex"
34
+ aria-label="Collapsed sidebar"
35
+ >
36
+ <div className="flex flex-col items-center gap-2">
37
+ <button
38
+ type="button"
39
+ onClick={onOpenSidebar}
40
+ aria-label="Open sidebar"
41
+ title="Open chats"
42
+ className="rounded-xl bg-white p-1 shadow-md shadow-slate-900/8 ring-1 ring-slate-200/85 transition-all hover:ring-comsats-purple/35"
43
+ >
44
+ <ComsatsLogo className="h-9 w-9" />
45
+ </button>
46
+ <span className="max-w-full px-0.5 text-center text-[8px] font-semibold uppercase leading-tight tracking-wide text-slate-500">
47
+ Chats
48
+ </span>
49
+ <div className="h-px w-10 max-w-full shrink-0 bg-slate-200/90" aria-hidden />
50
+ </div>
51
+
52
+ <div className="min-h-0 flex-1" aria-hidden />
53
+
54
+ <div className="flex flex-col items-stretch gap-2 pb-1">
55
+ <button
56
+ type="button"
57
+ onClick={onEditProfile}
58
+ aria-label="Edit profile"
59
+ title="Edit profile"
60
+ className={`${railBtn} text-slate-700 hover:bg-white/90 hover:text-comsats-purple`}
61
+ >
62
+ <UserCircleIcon className="h-5 w-5 shrink-0 text-slate-600" />
63
+ <span className="max-w-[4.75rem] text-center text-[8px] font-semibold leading-snug">
64
+ Edit profile
65
+ </span>
66
+ </button>
67
+
68
+ <button
69
+ type="button"
70
+ onClick={onLogout}
71
+ aria-label="Log out"
72
+ title="Log out"
73
+ className={`${railBtn} text-red-700 hover:bg-red-50`}
74
+ >
75
+ <LogoutIcon className="h-5 w-5 shrink-0" />
76
+ <span className="text-[9px] font-semibold leading-tight">Log out</span>
77
+ </button>
78
+ </div>
79
+ </aside>
80
+ )
81
+ }
frontend/src/components/chat/MessageRoleSticker.jsx ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** Compact role badge + label for chat bubbles (professional, not playful). */
2
+ export function MessageRoleSticker({ role }) {
3
+ if (role === 'user') {
4
+ return (
5
+ <div className="flex shrink-0 flex-col items-center gap-1">
6
+ <div
7
+ className="flex h-11 w-11 items-center justify-center rounded-2xl bg-gradient-to-br from-comsats-purple via-[#4b2e83] to-[#2d1a52] text-white shadow-[0_6px_20px_-4px_rgba(75,46,131,0.45)] ring-2 ring-white/50"
8
+ aria-hidden
9
+ >
10
+ <svg className="h-6 w-6 opacity-[0.98]" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
11
+ <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v1c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-1c0-2.66-5.33-4-8-4z" />
12
+ </svg>
13
+ </div>
14
+ <span className="select-none text-[9px] font-bold uppercase tracking-[0.15em] text-comsats-purple/85">
15
+ You
16
+ </span>
17
+ </div>
18
+ )
19
+ }
20
+
21
+ return (
22
+ <div className="flex shrink-0 flex-col items-center gap-1">
23
+ <div
24
+ className="relative flex h-11 w-11 items-center justify-center overflow-hidden rounded-2xl bg-white shadow-[0_4px_16px_-6px_rgba(0,94,184,0.35)] ring-2 ring-comsats-blue/30"
25
+ aria-hidden
26
+ >
27
+ <span className="absolute inset-0 bg-gradient-to-br from-comsats-blue/[0.14] via-white to-comsats-purple/[0.12]" />
28
+ <svg
29
+ className="relative h-[22px] w-[22px] text-comsats-blue"
30
+ viewBox="0 0 24 24"
31
+ fill="none"
32
+ stroke="currentColor"
33
+ strokeWidth="1.75"
34
+ aria-hidden
35
+ >
36
+ <path
37
+ strokeLinecap="round"
38
+ strokeLinejoin="round"
39
+ d="M8.25 3v1.5M4.5 8.25H3m18 0h-1.5M4.5 12H3m18 0h-1.5m-15 3.75H3m18 0h-1.5M8.25 19.5V21M12 3v1.5m0 15V21m3.75-18v1.5m0 15V21m-9-1.5h10.5a2.25 2.25 0 002.25-2.25V6.75a2.25 2.25 0 00-2.25-2.25H6.75A2.25 2.25 0 004.5 6.75v10.5a2.25 2.25 0 002.25 2.25zm.75-12h9v9h-9v-9z"
40
+ />
41
+ </svg>
42
+ </div>
43
+ <span className="max-w-[3.25rem] select-none text-center text-[8px] font-bold uppercase leading-tight tracking-[0.08em] text-comsats-blue">
44
+ Assistant
45
+ </span>
46
+ </div>
47
+ )
48
+ }
frontend/src/components/chat/ProfileModal.jsx ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from 'react'
2
+ import { updateProfile } from '../../api/auth'
3
+ import { getStoredUser, patchStoredUser } from '../../auth/storage'
4
+
5
+ export default function ProfileModal({ open, onClose }) {
6
+ const user = getStoredUser()
7
+ const [fullName, setFullName] = useState('')
8
+ const [email, setEmail] = useState('')
9
+ const [error, setError] = useState('')
10
+ const [saving, setSaving] = useState(false)
11
+
12
+ useEffect(() => {
13
+ if (!open || !user) return
14
+ setFullName(user.full_name || '')
15
+ setEmail(user.email || '')
16
+ setError('')
17
+ }, [open, user])
18
+
19
+ useEffect(() => {
20
+ if (!open) return
21
+ function onKey(e) {
22
+ if (e.key === 'Escape') onClose()
23
+ }
24
+ window.addEventListener('keydown', onKey)
25
+ return () => window.removeEventListener('keydown', onKey)
26
+ }, [open, onClose])
27
+
28
+ async function handleSubmit(e) {
29
+ e.preventDefault()
30
+ setError('')
31
+ setSaving(true)
32
+ try {
33
+ const body = {}
34
+ if ((fullName || '').trim() !== (user?.full_name || ''))
35
+ body.full_name = fullName.trim() || null
36
+ if ((email || '').trim().toLowerCase() !== (user?.email || '').toLowerCase())
37
+ body.email = email.trim()
38
+
39
+ if (Object.keys(body).length === 0) {
40
+ onClose()
41
+ return
42
+ }
43
+
44
+ const updated = await updateProfile(body)
45
+ patchStoredUser({
46
+ email: updated.email,
47
+ full_name: updated.full_name,
48
+ user_id: updated.user_id,
49
+ })
50
+ onClose()
51
+ } catch (err) {
52
+ setError(err.message || 'Could not update profile')
53
+ } finally {
54
+ setSaving(false)
55
+ }
56
+ }
57
+
58
+ if (!open) return null
59
+
60
+ return (
61
+ <div
62
+ className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4"
63
+ role="dialog"
64
+ aria-modal="true"
65
+ aria-labelledby="profile-title"
66
+ onMouseDown={(e) => {
67
+ if (e.target === e.currentTarget) onClose()
68
+ }}
69
+ >
70
+ <div className="w-full max-w-md rounded-2xl border border-slate-200 bg-white p-6 shadow-xl">
71
+ <h2 id="profile-title" className="text-lg font-semibold text-slate-900">
72
+ Edit profile
73
+ </h2>
74
+ <p className="mt-1 text-sm text-slate-600">Update your name or email.</p>
75
+
76
+ <form onSubmit={handleSubmit} className="mt-6 flex flex-col gap-4">
77
+ {error ? (
78
+ <div
79
+ role="alert"
80
+ className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800"
81
+ >
82
+ {error}
83
+ </div>
84
+ ) : null}
85
+
86
+ <div className="flex flex-col gap-1.5">
87
+ <label htmlFor="profile-name" className="text-sm font-medium text-slate-700">
88
+ Full name
89
+ </label>
90
+ <input
91
+ id="profile-name"
92
+ type="text"
93
+ value={fullName}
94
+ onChange={(e) => setFullName(e.target.value)}
95
+ className="rounded-lg border border-slate-300 px-3 py-2 text-slate-900 outline-none focus:border-comsats-blue focus:ring-2 focus:ring-comsats-blue/25"
96
+ />
97
+ </div>
98
+
99
+ <div className="flex flex-col gap-1.5">
100
+ <label htmlFor="profile-email" className="text-sm font-medium text-slate-700">
101
+ Email
102
+ </label>
103
+ <input
104
+ id="profile-email"
105
+ type="email"
106
+ required
107
+ value={email}
108
+ onChange={(e) => setEmail(e.target.value)}
109
+ className="rounded-lg border border-slate-300 px-3 py-2 text-slate-900 outline-none focus:border-comsats-blue focus:ring-2 focus:ring-comsats-blue/25"
110
+ />
111
+ </div>
112
+
113
+ <div className="mt-2 flex justify-end gap-2">
114
+ <button
115
+ type="button"
116
+ onClick={onClose}
117
+ className="rounded-lg border border-slate-300 px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50"
118
+ >
119
+ Cancel
120
+ </button>
121
+ <button
122
+ type="submit"
123
+ disabled={saving}
124
+ className="rounded-lg bg-comsats-purple px-4 py-2 text-sm font-semibold text-white hover:bg-comsats-blue disabled:opacity-60"
125
+ >
126
+ {saving ? 'Saving…' : 'Save'}
127
+ </button>
128
+ </div>
129
+ </form>
130
+ </div>
131
+ </div>
132
+ )
133
+ }
frontend/src/index.css ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import 'tailwindcss';
2
+
3
+ @theme {
4
+ /* Official seal palette */
5
+ --color-comsats-purple: #4b2e83;
6
+ --color-comsats-blue: #005eb8;
7
+ --color-chat-canvas: #f7f7f8;
8
+ --color-chat-sidebar: #f4f4f5;
9
+ }
10
+
11
+ @layer base {
12
+ body {
13
+ @apply m-0 min-h-screen antialiased bg-white text-slate-900;
14
+ font-family:
15
+ ui-sans-serif,
16
+ system-ui,
17
+ -apple-system,
18
+ 'Segoe UI',
19
+ Roboto,
20
+ 'Helvetica Neue',
21
+ Arial,
22
+ sans-serif;
23
+ }
24
+
25
+ #root {
26
+ @apply min-h-dvh bg-white;
27
+ }
28
+ }
frontend/src/main.jsx ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import { StrictMode } from 'react'
2
+ import { createRoot } from 'react-dom/client'
3
+ import './index.css'
4
+ import App from './App.jsx'
5
+
6
+ createRoot(document.getElementById('root')).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>,
10
+ )
frontend/src/pages/AdminLogin.jsx ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from 'react'
2
+ import { Link, useLocation, useNavigate } from 'react-router-dom'
3
+ import { adminLogin } from '../api/admin'
4
+ import { setAdminSession } from '../auth/adminStorage'
5
+ import AuthLayout from './AuthLayout'
6
+
7
+ function EnvelopeIcon({ className = '' }) {
8
+ return (
9
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
10
+ <path
11
+ strokeLinecap="round"
12
+ strokeLinejoin="round"
13
+ d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"
14
+ />
15
+ </svg>
16
+ )
17
+ }
18
+
19
+ function LockIcon({ className = '' }) {
20
+ return (
21
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
22
+ <path
23
+ strokeLinecap="round"
24
+ strokeLinejoin="round"
25
+ d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
26
+ />
27
+ </svg>
28
+ )
29
+ }
30
+
31
+ export default function AdminLogin() {
32
+ const navigate = useNavigate()
33
+ const location = useLocation()
34
+ const [email, setEmail] = useState('')
35
+ const [password, setPassword] = useState('')
36
+ const [error, setError] = useState('')
37
+ const [loading, setLoading] = useState(false)
38
+
39
+ useEffect(() => {
40
+ if (location.state?.email) setEmail(location.state.email)
41
+ }, [location.state])
42
+
43
+ async function handleSubmit(e) {
44
+ e.preventDefault()
45
+ setError('')
46
+ setLoading(true)
47
+ try {
48
+ const data = await adminLogin(email.trim(), password)
49
+ setAdminSession({
50
+ access_token: data.access_token,
51
+ refresh_token: data.refresh_token,
52
+ admin: data.admin,
53
+ })
54
+ const to = location.state?.from && location.state.from.startsWith('/admin') ? location.state.from : '/admin'
55
+ navigate(to, { replace: true })
56
+ } catch (err) {
57
+ setError(err.message || 'Login failed')
58
+ } finally {
59
+ setLoading(false)
60
+ }
61
+ }
62
+
63
+ return (
64
+ <AuthLayout
65
+ brandTo="/admin/login"
66
+ title="Admin sign in"
67
+ subtitle="Manage chatbot user accounts."
68
+ variant="admin"
69
+ >
70
+ <form onSubmit={handleSubmit} className="flex flex-col gap-5 sm:gap-6">
71
+ {location.state?.registered ? (
72
+ <div
73
+ role="status"
74
+ className="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-900"
75
+ >
76
+ Admin account created. You can sign in now.
77
+ </div>
78
+ ) : null}
79
+ {error ? (
80
+ <div
81
+ role="alert"
82
+ className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800"
83
+ >
84
+ {error}
85
+ </div>
86
+ ) : null}
87
+
88
+ <div className="flex flex-col gap-1.5">
89
+ <label htmlFor="admin-login-email" className="text-sm font-medium text-slate-700">
90
+ Email
91
+ </label>
92
+ <div className="relative">
93
+ <EnvelopeIcon className="pointer-events-none absolute left-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
94
+ <input
95
+ id="admin-login-email"
96
+ name="email"
97
+ type="email"
98
+ autoComplete="username"
99
+ required
100
+ value={email}
101
+ onChange={(e) => setEmail(e.target.value)}
102
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white py-3 pl-11 pr-4 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-purple focus:ring-2 focus:ring-comsats-purple/20 sm:text-sm"
103
+ />
104
+ </div>
105
+ </div>
106
+
107
+ <div className="flex flex-col gap-1.5">
108
+ <label htmlFor="admin-login-password" className="text-sm font-medium text-slate-700">
109
+ Password
110
+ </label>
111
+ <div className="relative">
112
+ <LockIcon className="pointer-events-none absolute left-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
113
+ <input
114
+ id="admin-login-password"
115
+ name="password"
116
+ type="password"
117
+ autoComplete="current-password"
118
+ required
119
+ value={password}
120
+ onChange={(e) => setPassword(e.target.value)}
121
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white py-3 pl-11 pr-4 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-purple focus:ring-2 focus:ring-comsats-purple/20 sm:text-sm"
122
+ />
123
+ </div>
124
+ </div>
125
+
126
+ <button
127
+ type="submit"
128
+ disabled={loading}
129
+ className="mt-1 flex min-h-[48px] w-full items-center justify-center rounded-xl bg-gradient-to-r from-comsats-purple to-[#3d2469] px-4 py-3 text-sm font-semibold text-white shadow-md shadow-comsats-purple/25 transition-all hover:brightness-105 focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60"
130
+ >
131
+ {loading ? 'Signing in…' : 'Sign in'}
132
+ </button>
133
+
134
+ <p className="text-center text-sm text-slate-600">
135
+ <Link to="/admin/register" className="font-semibold text-comsats-blue underline-offset-2 hover:underline">
136
+ Register admin
137
+ </Link>
138
+ <span className="mx-2 text-slate-300">·</span>
139
+ <Link to="/login" className="text-slate-500 underline-offset-2 hover:underline">
140
+ User login
141
+ </Link>
142
+ </p>
143
+ </form>
144
+ </AuthLayout>
145
+ )
146
+ }
frontend/src/pages/AdminPanel.jsx ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useEffect, useState } from 'react'
2
+ import { Link, useNavigate } from 'react-router-dom'
3
+ import { deleteUserAdmin, getKbStatus, listUsersAdmin, mergeKbCsvUpload } from '../api/admin'
4
+ import { clearAdminSession, getStoredAdmin } from '../auth/adminStorage'
5
+ import ComsatsLogo from '../components/ComsatsLogo'
6
+
7
+ const PAGE_SIZE = 15
8
+
9
+ export default function AdminPanel() {
10
+ const navigate = useNavigate()
11
+ const [admin] = useState(() => getStoredAdmin())
12
+ const [page, setPage] = useState(1)
13
+ const [data, setData] = useState(null)
14
+ const [loading, setLoading] = useState(true)
15
+ const [usersError, setUsersError] = useState('')
16
+ const [deletingId, setDeletingId] = useState(null)
17
+
18
+ const [kbStatus, setKbStatus] = useState(null)
19
+ const [kbLoading, setKbLoading] = useState(true)
20
+ const [kbFile, setKbFile] = useState(null)
21
+ const [kbUploading, setKbUploading] = useState(false)
22
+ const [kbError, setKbError] = useState('')
23
+ const [kbSuccess, setKbSuccess] = useState('')
24
+
25
+ const loadKb = useCallback(async () => {
26
+ setKbError('')
27
+ setKbLoading(true)
28
+ try {
29
+ setKbStatus(await getKbStatus())
30
+ } catch (e) {
31
+ setKbError(e.message || 'Failed to load knowledge base status')
32
+ setKbStatus(null)
33
+ } finally {
34
+ setKbLoading(false)
35
+ }
36
+ }, [])
37
+
38
+ useEffect(() => {
39
+ loadKb()
40
+ }, [loadKb])
41
+
42
+ const load = useCallback(async () => {
43
+ setUsersError('')
44
+ setLoading(true)
45
+ try {
46
+ const res = await listUsersAdmin(page, PAGE_SIZE)
47
+ setData(res)
48
+ } catch (e) {
49
+ setUsersError(e.message || 'Failed to load users')
50
+ setData(null)
51
+ } finally {
52
+ setLoading(false)
53
+ }
54
+ }, [page])
55
+
56
+ useEffect(() => {
57
+ load()
58
+ }, [load])
59
+
60
+ function logout() {
61
+ clearAdminSession()
62
+ navigate('/admin/login', { replace: true })
63
+ }
64
+
65
+ async function onDelete(userId, email) {
66
+ if (!window.confirm(`Delete user ${email}? Their chats will be removed.`)) return
67
+ setDeletingId(userId)
68
+ setUsersError('')
69
+ try {
70
+ await deleteUserAdmin(userId)
71
+ await load()
72
+ } catch (e) {
73
+ setUsersError(e.message || 'Delete failed')
74
+ } finally {
75
+ setDeletingId(null)
76
+ }
77
+ }
78
+
79
+ const pages = data?.pages ?? 0
80
+ const total = data?.total ?? 0
81
+
82
+ async function onKbMergeUpload(e) {
83
+ e.preventDefault()
84
+ if (!kbFile) return
85
+ setKbError('')
86
+ setKbSuccess('')
87
+ setKbUploading(true)
88
+ const fileRef = kbFile
89
+ try {
90
+ const res = await mergeKbCsvUpload(() => {
91
+ const fd = new FormData()
92
+ fd.append('file', fileRef)
93
+ return fd
94
+ })
95
+ setKbSuccess(
96
+ `${res.message} Merged ${res.rows_merged ?? 0} rows. Stored as ${res.saved_as ?? 'upload'}.`,
97
+ )
98
+ setKbFile(null)
99
+ const input = document.getElementById('admin-kb-merge-csv')
100
+ if (input) input.value = ''
101
+ await loadKb()
102
+ } catch (err) {
103
+ setKbError(err.message || 'Upload failed')
104
+ } finally {
105
+ setKbUploading(false)
106
+ }
107
+ }
108
+
109
+ return (
110
+ <div className="flex min-h-dvh flex-col bg-gradient-to-b from-slate-50 to-white">
111
+ <header className="sticky top-0 z-10 border-b border-slate-200/90 bg-white/90 backdrop-blur-md">
112
+ <div className="mx-auto flex max-w-5xl flex-wrap items-center justify-between gap-3 px-4 py-3 sm:px-6">
113
+ <div className="flex items-center gap-3">
114
+ <div className="rounded-xl bg-white p-1 shadow-sm ring-1 ring-slate-200/80">
115
+ <ComsatsLogo className="h-10 w-10" />
116
+ </div>
117
+ <div>
118
+ <h1 className="text-lg font-bold tracking-tight text-comsats-purple">Admin</h1>
119
+ <p className="text-[12px] text-slate-500">
120
+ {admin?.email ?? 'Signed in'}
121
+ </p>
122
+ </div>
123
+ </div>
124
+ <div className="flex items-center gap-2">
125
+ <Link
126
+ to="/chat"
127
+ className="rounded-lg px-3 py-2 text-[13px] font-medium text-comsats-blue hover:bg-comsats-blue/10"
128
+ >
129
+ User chat
130
+ </Link>
131
+ <button
132
+ type="button"
133
+ onClick={logout}
134
+ className="rounded-lg border border-slate-200 bg-white px-3 py-2 text-[13px] font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50"
135
+ >
136
+ Log out
137
+ </button>
138
+ </div>
139
+ </div>
140
+ </header>
141
+
142
+ <main className="mx-auto w-full max-w-5xl flex-1 px-4 py-6 sm:px-6 sm:py-8">
143
+ <section className="mb-10 rounded-2xl border border-slate-200/90 bg-white p-5 shadow-sm ring-1 ring-slate-900/[0.03] sm:p-6">
144
+ <div className="flex flex-wrap items-start justify-between gap-3">
145
+ <div>
146
+ <h2 className="text-lg font-semibold text-slate-900">Knowledge base (RAG merge)</h2>
147
+ <p className="mt-1 text-sm text-slate-600">
148
+ Upload one CSV (same format as your FAQ data). Rows are embedded and{' '}
149
+ <strong className="font-semibold text-slate-800">merged</strong> into the running FAISS index via{' '}
150
+ <code className="rounded bg-slate-100 px-1 py-0.5 text-[12px]">merge_from</code>
151
+ — no full rebuild. The file is saved under <span className="font-mono text-[12px]">kb_uploads/</span>.
152
+ </p>
153
+ </div>
154
+ <span
155
+ className={`inline-flex shrink-0 rounded-full px-3 py-1 text-[11px] font-bold uppercase tracking-wide ring-1 ${
156
+ kbStatus?.retriever_ready
157
+ ? 'bg-emerald-50 text-emerald-800 ring-emerald-200'
158
+ : 'bg-amber-50 text-amber-900 ring-amber-200'
159
+ }`}
160
+ >
161
+ {kbLoading ? 'Checking…' : kbStatus?.retriever_ready ? 'Retriever ready' : 'Retriever offline'}
162
+ </span>
163
+ </div>
164
+
165
+ {kbError ? (
166
+ <div
167
+ role="alert"
168
+ className="mt-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800"
169
+ >
170
+ {kbError}
171
+ </div>
172
+ ) : null}
173
+ {kbSuccess ? (
174
+ <div
175
+ role="status"
176
+ className="mt-4 rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-900"
177
+ >
178
+ {kbSuccess}
179
+ </div>
180
+ ) : null}
181
+
182
+ {kbStatus && !kbLoading ? (
183
+ <dl className="mt-4 grid gap-2 text-[13px] text-slate-600 sm:grid-cols-2">
184
+ <div>
185
+ <dt className="font-medium text-slate-500">FAISS folder</dt>
186
+ <dd className="font-mono text-[12px] text-slate-800">{kbStatus.index_path}</dd>
187
+ </div>
188
+ <div>
189
+ <dt className="font-medium text-slate-500">Upload folder</dt>
190
+ <dd className="font-mono text-[12px] text-slate-800">{kbStatus.kb_upload_dir}</dd>
191
+ </div>
192
+ <div className="sm:col-span-2">
193
+ <dt className="font-medium text-slate-500">Past uploads</dt>
194
+ <dd className="mt-0.5 text-slate-800">
195
+ {kbStatus.uploaded_csv_files?.length
196
+ ? kbStatus.uploaded_csv_files.join(', ')
197
+ : 'None yet'}
198
+ </dd>
199
+ </div>
200
+ </dl>
201
+ ) : kbLoading ? (
202
+ <p className="mt-4 text-sm text-slate-500">Loading knowledge base status…</p>
203
+ ) : null}
204
+
205
+ <form onSubmit={onKbMergeUpload} className="mt-6 flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-end">
206
+ <div className="min-w-0 flex-1">
207
+ <label htmlFor="admin-kb-merge-csv" className="mb-1 block text-sm font-medium text-slate-700">
208
+ CSV file
209
+ </label>
210
+ <input
211
+ id="admin-kb-merge-csv"
212
+ name="file"
213
+ type="file"
214
+ accept=".csv,text/csv"
215
+ disabled={kbUploading}
216
+ onChange={(ev) => setKbFile(ev.target.files?.[0] ?? null)}
217
+ className="block w-full max-w-md text-[13px] text-slate-800 file:mr-3 file:rounded-lg file:border-0 file:bg-comsats-purple/10 file:px-3 file:py-2 file:text-[13px] file:font-semibold file:text-comsats-purple hover:file:bg-comsats-purple/15"
218
+ />
219
+ </div>
220
+ <button
221
+ type="submit"
222
+ disabled={!kbFile || kbUploading}
223
+ className="rounded-xl bg-gradient-to-r from-comsats-purple to-[#3d2469] px-5 py-2.5 text-sm font-semibold text-white shadow-md shadow-comsats-purple/20 transition-all hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-50"
224
+ >
225
+ {kbUploading ? 'Merging…' : 'Upload & merge into FAISS'}
226
+ </button>
227
+ </form>
228
+ </section>
229
+
230
+ <div className="mb-6 flex flex-col gap-1">
231
+ <h2 className="text-xl font-semibold text-slate-900">Users</h2>
232
+ <p className="text-sm text-slate-600">
233
+ {total} registered {total === 1 ? 'user' : 'users'}
234
+ {pages > 0 ? ` · Page ${page} of ${pages}` : ''}
235
+ </p>
236
+ </div>
237
+
238
+ {usersError ? (
239
+ <div
240
+ role="alert"
241
+ className="mb-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-800"
242
+ >
243
+ {usersError}
244
+ </div>
245
+ ) : null}
246
+
247
+ <div className="overflow-hidden rounded-2xl border border-slate-200/90 bg-white shadow-sm ring-1 ring-slate-900/[0.03]">
248
+ <div className="overflow-x-auto">
249
+ <table className="w-full min-w-[480px] text-left text-[13px]">
250
+ <thead>
251
+ <tr className="border-b border-slate-200 bg-slate-50/90 text-[11px] font-bold uppercase tracking-wider text-slate-500">
252
+ <th className="px-4 py-3 sm:px-5">Email</th>
253
+ <th className="px-4 py-3 sm:px-5">Name</th>
254
+ <th className="w-[100px] px-4 py-3 text-right sm:px-5">Actions</th>
255
+ </tr>
256
+ </thead>
257
+ <tbody className="divide-y divide-slate-100">
258
+ {loading ? (
259
+ <tr>
260
+ <td colSpan={3} className="px-5 py-12 text-center text-slate-500">
261
+ Loading…
262
+ </td>
263
+ </tr>
264
+ ) : !data?.items?.length ? (
265
+ <tr>
266
+ <td colSpan={3} className="px-5 py-12 text-center text-slate-500">
267
+ No users yet.
268
+ </td>
269
+ </tr>
270
+ ) : (
271
+ data.items.map((row) => (
272
+ <tr key={row.user_id} className="bg-white hover:bg-slate-50/80">
273
+ <td className="max-w-[220px] truncate px-4 py-3 font-medium text-slate-900 sm:max-w-xs sm:px-5">
274
+ {row.email}
275
+ </td>
276
+ <td className="px-4 py-3 text-slate-600 sm:px-5">{row.full_name || '—'}</td>
277
+ <td className="px-4 py-3 text-right sm:px-5">
278
+ <button
279
+ type="button"
280
+ disabled={deletingId === row.user_id}
281
+ onClick={() => onDelete(row.user_id, row.email)}
282
+ className="rounded-lg border border-red-200 bg-white px-2.5 py-1.5 text-[12px] font-semibold text-red-700 transition-colors hover:bg-red-50 disabled:opacity-50"
283
+ >
284
+ {deletingId === row.user_id ? '…' : 'Delete'}
285
+ </button>
286
+ </td>
287
+ </tr>
288
+ ))
289
+ )}
290
+ </tbody>
291
+ </table>
292
+ </div>
293
+ </div>
294
+
295
+ {pages > 1 ? (
296
+ <nav
297
+ className="mt-6 flex flex-wrap items-center justify-between gap-3"
298
+ aria-label="Pagination"
299
+ >
300
+ <button
301
+ type="button"
302
+ disabled={page <= 1 || loading}
303
+ onClick={() => setPage((p) => Math.max(1, p - 1))}
304
+ className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-[13px] font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-40"
305
+ >
306
+ Previous
307
+ </button>
308
+ <span className="text-[13px] text-slate-500">
309
+ Page {page} / {pages}
310
+ </span>
311
+ <button
312
+ type="button"
313
+ disabled={page >= pages || loading}
314
+ onClick={() => setPage((p) => Math.min(pages, p + 1))}
315
+ className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-[13px] font-semibold text-slate-700 shadow-sm transition-colors hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-40"
316
+ >
317
+ Next
318
+ </button>
319
+ </nav>
320
+ ) : null}
321
+ </main>
322
+ </div>
323
+ )
324
+ }
frontend/src/pages/AdminRegister.jsx ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react'
2
+ import { Link, useNavigate } from 'react-router-dom'
3
+ import { adminRegister } from '../api/admin'
4
+ import AuthLayout from './AuthLayout'
5
+
6
+ function EnvelopeIcon({ className = '' }) {
7
+ return (
8
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
9
+ <path
10
+ strokeLinecap="round"
11
+ strokeLinejoin="round"
12
+ d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"
13
+ />
14
+ </svg>
15
+ )
16
+ }
17
+
18
+ function LockIcon({ className = '' }) {
19
+ return (
20
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
21
+ <path
22
+ strokeLinecap="round"
23
+ strokeLinejoin="round"
24
+ d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
25
+ />
26
+ </svg>
27
+ )
28
+ }
29
+
30
+ export default function AdminRegister() {
31
+ const navigate = useNavigate()
32
+ const [email, setEmail] = useState('')
33
+ const [password, setPassword] = useState('')
34
+ const [fullName, setFullName] = useState('')
35
+ const [bootstrapSecret, setBootstrapSecret] = useState('')
36
+ const [error, setError] = useState('')
37
+ const [loading, setLoading] = useState(false)
38
+
39
+ async function handleSubmit(e) {
40
+ e.preventDefault()
41
+ setError('')
42
+ setLoading(true)
43
+ try {
44
+ await adminRegister({
45
+ email: email.trim(),
46
+ password,
47
+ full_name: fullName,
48
+ bootstrapSecret,
49
+ })
50
+ navigate('/admin/login', { replace: true, state: { registered: true, email: email.trim() } })
51
+ } catch (err) {
52
+ setError(err.message || 'Registration failed')
53
+ } finally {
54
+ setLoading(false)
55
+ }
56
+ }
57
+
58
+ return (
59
+ <AuthLayout
60
+ brandTo="/admin/login"
61
+ title="Register admin"
62
+ subtitle="First admin: no secret needed. Later admins require ADMIN_BOOTSTRAP_SECRET on the server and the matching header below."
63
+ variant="admin"
64
+ >
65
+ <form onSubmit={handleSubmit} className="flex flex-col gap-5 sm:gap-6">
66
+ {error ? (
67
+ <div
68
+ role="alert"
69
+ className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800"
70
+ >
71
+ {error}
72
+ </div>
73
+ ) : null}
74
+
75
+ <div className="flex flex-col gap-1.5">
76
+ <label htmlFor="admin-reg-email" className="text-sm font-medium text-slate-700">
77
+ Email
78
+ </label>
79
+ <div className="relative">
80
+ <EnvelopeIcon className="pointer-events-none absolute left-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
81
+ <input
82
+ id="admin-reg-email"
83
+ name="email"
84
+ type="email"
85
+ autoComplete="email"
86
+ required
87
+ value={email}
88
+ onChange={(e) => setEmail(e.target.value)}
89
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white py-3 pl-11 pr-4 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-purple focus:ring-2 focus:ring-comsats-purple/20 sm:text-sm"
90
+ />
91
+ </div>
92
+ </div>
93
+
94
+ <div className="flex flex-col gap-1.5">
95
+ <label htmlFor="admin-reg-name" className="text-sm font-medium text-slate-700">
96
+ Full name <span className="font-normal text-slate-400">(optional)</span>
97
+ </label>
98
+ <input
99
+ id="admin-reg-name"
100
+ name="full_name"
101
+ type="text"
102
+ autoComplete="name"
103
+ value={fullName}
104
+ onChange={(e) => setFullName(e.target.value)}
105
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white px-4 py-3 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-purple focus:ring-2 focus:ring-comsats-purple/20 sm:text-sm"
106
+ />
107
+ </div>
108
+
109
+ <div className="flex flex-col gap-1.5">
110
+ <label htmlFor="admin-reg-password" className="text-sm font-medium text-slate-700">
111
+ Password
112
+ </label>
113
+ <div className="relative">
114
+ <LockIcon className="pointer-events-none absolute left-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
115
+ <input
116
+ id="admin-reg-password"
117
+ name="password"
118
+ type="password"
119
+ autoComplete="new-password"
120
+ required
121
+ minLength={6}
122
+ value={password}
123
+ onChange={(e) => setPassword(e.target.value)}
124
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white py-3 pl-11 pr-4 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-purple focus:ring-2 focus:ring-comsats-purple/20 sm:text-sm"
125
+ />
126
+ </div>
127
+ </div>
128
+
129
+ <div className="flex flex-col gap-1.5">
130
+ <label htmlFor="admin-bootstrap" className="text-sm font-medium text-slate-700">
131
+ Bootstrap secret <span className="font-normal text-slate-400">(optional)</span>
132
+ </label>
133
+ <input
134
+ id="admin-bootstrap"
135
+ name="bootstrap_secret"
136
+ type="password"
137
+ autoComplete="off"
138
+ value={bootstrapSecret}
139
+ onChange={(e) => setBootstrapSecret(e.target.value)}
140
+ placeholder="Only if admins already exist"
141
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white px-4 py-3 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-purple focus:ring-2 focus:ring-comsats-purple/20 sm:text-sm"
142
+ />
143
+ </div>
144
+
145
+ <button
146
+ type="submit"
147
+ disabled={loading}
148
+ className="mt-1 flex min-h-[48px] w-full items-center justify-center rounded-xl bg-gradient-to-r from-comsats-purple to-[#3d2469] px-4 py-3 text-sm font-semibold text-white shadow-md shadow-comsats-purple/25 transition-all hover:brightness-105 focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60"
149
+ >
150
+ {loading ? 'Creating…' : 'Create admin'}
151
+ </button>
152
+
153
+ <p className="text-center text-sm text-slate-600">
154
+ <Link to="/admin/login" className="font-semibold text-comsats-blue underline-offset-2 hover:underline">
155
+ Back to admin sign in
156
+ </Link>
157
+ </p>
158
+ </form>
159
+ </AuthLayout>
160
+ )
161
+ }
frontend/src/pages/AuthLayout.jsx ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Link } from 'react-router-dom'
2
+ import ComsatsLogo from '../components/ComsatsLogo'
3
+
4
+ function ShieldIcon({ className = '' }) {
5
+ return (
6
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
7
+ <path
8
+ strokeLinecap="round"
9
+ strokeLinejoin="round"
10
+ d="M9 12.75L11.25 15 15 9.75m-3-7.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285z"
11
+ />
12
+ </svg>
13
+ )
14
+ }
15
+
16
+ export default function AuthLayout({ title, subtitle, children, brandTo = '/login', variant = 'user' }) {
17
+ return (
18
+ <div className="flex min-h-dvh w-full flex-col items-center justify-start overflow-x-hidden overflow-y-auto bg-gradient-to-b from-chat-sidebar via-white to-comsats-blue/[0.08] px-4 py-8 pb-[max(1.5rem,env(safe-area-inset-bottom))] pt-[max(1.25rem,env(safe-area-inset-top))] sm:justify-center sm:py-12">
19
+ <div className="flex w-full max-w-[440px] flex-col items-center gap-6 sm:gap-8">
20
+ <Link
21
+ to={brandTo}
22
+ className="group flex flex-col items-center gap-3 rounded-2xl text-center no-underline outline-none transition-opacity hover:opacity-95 focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-2"
23
+ >
24
+ <div className="rounded-full bg-white p-1 shadow-[0_8px_30px_-12px_rgba(75,46,131,0.35)] ring-2 ring-white transition-shadow group-hover:shadow-[0_12px_36px_-12px_rgba(75,46,131,0.4)]">
25
+ <ComsatsLogo className="h-[4.5rem] w-[4.5rem] sm:h-24 sm:w-24" />
26
+ </div>
27
+ <span className="text-xl font-bold tracking-tight text-comsats-purple sm:text-2xl">
28
+ COMSATS Chatbot
29
+ {variant === 'admin' ? (
30
+ <span className="ml-2 align-middle text-sm font-semibold text-slate-500 sm:text-base">
31
+ Admin
32
+ </span>
33
+ ) : null}
34
+ </span>
35
+ </Link>
36
+
37
+ <div className="w-full rounded-2xl border border-slate-200/90 bg-white p-6 shadow-[0_12px_48px_-20px_rgba(75,46,131,0.22)] sm:rounded-3xl sm:p-8">
38
+ <div className="mb-6 text-center">
39
+ <h1 className="text-2xl font-semibold tracking-tight text-slate-900">{title}</h1>
40
+ {subtitle ? (
41
+ <p className="mt-2 text-[15px] leading-relaxed text-slate-600">{subtitle}</p>
42
+ ) : null}
43
+ </div>
44
+
45
+ <div className="mb-6 flex flex-col items-center gap-2 rounded-xl bg-gradient-to-r from-slate-50 to-comsats-blue/[0.06] px-3 py-2.5 text-center text-[11px] font-medium leading-snug text-slate-600 ring-1 ring-slate-100 sm:flex-row sm:justify-center sm:text-[12px]">
46
+ <ShieldIcon className="h-4 w-4 shrink-0 text-comsats-blue" />
47
+ <span>
48
+ {variant === 'admin'
49
+ ? 'Administrator console — restricted access'
50
+ : 'Secure campus sign-in — your session is protected'}
51
+ </span>
52
+ </div>
53
+
54
+ {children}
55
+ </div>
56
+ </div>
57
+ </div>
58
+ )
59
+ }
frontend/src/pages/ChatPage.jsx ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useCallback, useEffect, useRef, useState } from 'react'
2
+ import { useNavigate } from 'react-router-dom'
3
+ import {
4
+ createChat,
5
+ fetchChatPage,
6
+ listChats,
7
+ removeChat,
8
+ sendMessage,
9
+ } from '../api/chat'
10
+ import { clearSession, getStoredUser } from '../auth/storage'
11
+ import ChatMain from '../components/chat/ChatMain'
12
+ import CollapsedSidebarRail from '../components/chat/CollapsedSidebarRail'
13
+ import ChatSidebar from '../components/chat/ChatSidebar'
14
+ import ProfileModal from '../components/chat/ProfileModal'
15
+
16
+ const THREAD_LIMIT = 20
17
+ const SIDEBAR_LIMIT = 25
18
+ const SUGGESTIONS_PREF_KEY = 'comsats_suggestions_enabled'
19
+ const WEB_SEARCH_PREF_KEY = 'comsats_use_web_search'
20
+
21
+ function readSuggestionsPref() {
22
+ try {
23
+ return localStorage.getItem(SUGGESTIONS_PREF_KEY) !== 'false'
24
+ } catch {
25
+ return true
26
+ }
27
+ }
28
+
29
+ function readWebSearchPref() {
30
+ try {
31
+ const raw = localStorage.getItem(WEB_SEARCH_PREF_KEY)
32
+ if (raw === null) {
33
+ localStorage.setItem(WEB_SEARCH_PREF_KEY, 'false')
34
+ return false
35
+ }
36
+ return raw === 'true'
37
+ } catch {
38
+ return false
39
+ }
40
+ }
41
+
42
+ function enrichSlice(slice, rangeStart) {
43
+ return slice.map((pair, i) => ({
44
+ question: pair.question,
45
+ answer: pair.answer,
46
+ pairIndex: rangeStart + i,
47
+ pending: false,
48
+ }))
49
+ }
50
+
51
+ export default function ChatPage() {
52
+ const navigate = useNavigate()
53
+ const user = getStoredUser()
54
+ const scrollRef = useRef(null)
55
+
56
+ const [chats, setChats] = useState([])
57
+ const [chatListTotal, setChatListTotal] = useState(0)
58
+ const [chatListHasMore, setChatListHasMore] = useState(false)
59
+ const [loadingMoreChats, setLoadingMoreChats] = useState(false)
60
+
61
+ const [selectedId, setSelectedId] = useState(null)
62
+ const [turns, setTurns] = useState([])
63
+ const [nextBeforeIndex, setNextBeforeIndex] = useState(null)
64
+ const [hasOlder, setHasOlder] = useState(false)
65
+ const [totalPairs, setTotalPairs] = useState(0)
66
+
67
+ const [question, setQuestion] = useState('')
68
+ const [loadingList, setLoadingList] = useState(true)
69
+ const [loadingChat, setLoadingChat] = useState(false)
70
+ const [loadingOlder, setLoadingOlder] = useState(false)
71
+ const [sending, setSending] = useState(false)
72
+ const [sendError, setSendError] = useState('')
73
+ const [profileOpen, setProfileOpen] = useState(false)
74
+ const [tailBump, setTailBump] = useState(0)
75
+ const [followUpSuggestions, setFollowUpSuggestions] = useState([])
76
+ const [suggestionsEnabled, setSuggestionsEnabled] = useState(readSuggestionsPref)
77
+ const [webSearchEnabled, setWebSearchEnabled] = useState(() =>
78
+ readWebSearchPref(),
79
+ )
80
+ const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false)
81
+ const [desktopSidebarOpen, setDesktopSidebarOpen] = useState(true)
82
+ const [viewportMd, setViewportMd] = useState(() =>
83
+ typeof window !== 'undefined' ? window.matchMedia('(min-width: 768px)').matches : true,
84
+ )
85
+
86
+ const emptyListBootstrapRef = useRef(false)
87
+ const chatsRef = useRef([])
88
+ chatsRef.current = chats
89
+
90
+ const loadSidebarFirstPage = useCallback(async () => {
91
+ setLoadingList(true)
92
+ try {
93
+ const data = await listChats({ skip: 0, limit: SIDEBAR_LIMIT })
94
+ setChats(data.chats || [])
95
+ setChatListTotal(data.total ?? 0)
96
+ setChatListHasMore(!!data.has_more)
97
+ } catch {
98
+ setChats([])
99
+ setChatListTotal(0)
100
+ setChatListHasMore(false)
101
+ } finally {
102
+ setLoadingList(false)
103
+ }
104
+ }, [])
105
+
106
+ const loadMoreSidebarChats = useCallback(async () => {
107
+ setLoadingMoreChats(true)
108
+ try {
109
+ const data = await listChats({
110
+ skip: chatsRef.current.length,
111
+ limit: SIDEBAR_LIMIT,
112
+ })
113
+ const batch = data.chats || []
114
+ setChats((prev) => {
115
+ const seen = new Set(prev.map((c) => c.chat_id))
116
+ const merged = [...prev]
117
+ for (const c of batch) {
118
+ if (!seen.has(c.chat_id)) merged.push(c)
119
+ }
120
+ return merged
121
+ })
122
+ setChatListTotal(data.total ?? 0)
123
+ setChatListHasMore(!!data.has_more)
124
+ } catch {
125
+ /* keep existing */
126
+ } finally {
127
+ setLoadingMoreChats(false)
128
+ }
129
+ }, [])
130
+
131
+ useEffect(() => {
132
+ loadSidebarFirstPage()
133
+ }, [loadSidebarFirstPage])
134
+
135
+ useEffect(() => {
136
+ const mq = window.matchMedia('(min-width: 768px)')
137
+ function onViewportChange() {
138
+ const md = mq.matches
139
+ setViewportMd(md)
140
+ if (md) setMobileSidebarOpen(false)
141
+ }
142
+ onViewportChange()
143
+ mq.addEventListener('change', onViewportChange)
144
+ return () => mq.removeEventListener('change', onViewportChange)
145
+ }, [])
146
+
147
+ useEffect(() => {
148
+ try {
149
+ localStorage.setItem(SUGGESTIONS_PREF_KEY, String(suggestionsEnabled))
150
+ } catch {
151
+ /* ignore */
152
+ }
153
+ if (!suggestionsEnabled) setFollowUpSuggestions([])
154
+ }, [suggestionsEnabled])
155
+
156
+ useEffect(() => {
157
+ try {
158
+ localStorage.setItem(WEB_SEARCH_PREF_KEY, String(webSearchEnabled))
159
+ } catch {
160
+ /* ignore */
161
+ }
162
+ }, [webSearchEnabled])
163
+
164
+ const selectChat = useCallback(async (chatId) => {
165
+ setSelectedId(chatId)
166
+ setLoadingChat(true)
167
+ setSendError('')
168
+ setFollowUpSuggestions([])
169
+ setTurns([])
170
+ setHasOlder(false)
171
+ setNextBeforeIndex(null)
172
+ setTotalPairs(0)
173
+ try {
174
+ const data = await fetchChatPage(chatId, { limit: THREAD_LIMIT })
175
+ const slice = data.history || []
176
+ const rangeStart = data.range_start ?? 0
177
+ setTurns(enrichSlice(slice, rangeStart))
178
+ setTotalPairs(data.total_pairs ?? slice.length)
179
+ setHasOlder(!!data.has_older)
180
+ setNextBeforeIndex(
181
+ data.next_before_index != null ? data.next_before_index : rangeStart,
182
+ )
183
+ } catch {
184
+ setTurns([])
185
+ setSendError('Could not load this chat.')
186
+ } finally {
187
+ setLoadingChat(false)
188
+ }
189
+ }, [])
190
+
191
+ useEffect(() => {
192
+ if (loadingList) return
193
+
194
+ if (chats.length === 0) {
195
+ if (emptyListBootstrapRef.current) return
196
+ emptyListBootstrapRef.current = true
197
+ ;(async () => {
198
+ try {
199
+ const created = await createChat()
200
+ const id = created.chat_id
201
+ setChats([
202
+ {
203
+ chat_id: id,
204
+ preview: 'New conversation',
205
+ updated_at: null,
206
+ message_count: 0,
207
+ },
208
+ ])
209
+ setChatListTotal(1)
210
+ setChatListHasMore(false)
211
+ setSelectedId(id)
212
+ setFollowUpSuggestions([])
213
+ setTurns([])
214
+ setHasOlder(false)
215
+ setNextBeforeIndex(null)
216
+ setTotalPairs(0)
217
+ } catch {
218
+ setSendError('Could not start a chat. Is the API running on port 8000?')
219
+ }
220
+ })()
221
+ return
222
+ }
223
+
224
+ if (!selectedId && chats[0]) {
225
+ selectChat(chats[0].chat_id)
226
+ }
227
+ }, [loadingList, chats, selectedId, selectChat])
228
+
229
+ async function handleLoadOlderMessages() {
230
+ if (!selectedId || !hasOlder || loadingOlder) return
231
+ const beforeIdx =
232
+ nextBeforeIndex != null ? nextBeforeIndex : turns[0]?.pairIndex ?? 0
233
+ const el = scrollRef.current
234
+ const prevScrollHeight = el?.scrollHeight ?? 0
235
+ const prevScrollTop = el?.scrollTop ?? 0
236
+
237
+ setLoadingOlder(true)
238
+ try {
239
+ const data = await fetchChatPage(selectedId, {
240
+ beforeIndex: beforeIdx,
241
+ limit: THREAD_LIMIT,
242
+ })
243
+ const slice = data.history || []
244
+ const rangeStart = data.range_start ?? 0
245
+ const older = enrichSlice(slice, rangeStart)
246
+ setTurns((prev) => [...older, ...prev])
247
+ setHasOlder(!!data.has_older)
248
+ setNextBeforeIndex(data.next_before_index ?? 0)
249
+
250
+ requestAnimationFrame(() => {
251
+ const el2 = scrollRef.current
252
+ if (el2) {
253
+ el2.scrollTop = el2.scrollHeight - prevScrollHeight + prevScrollTop
254
+ }
255
+ })
256
+ } catch (e) {
257
+ setSendError(e.message || 'Could not load older messages')
258
+ } finally {
259
+ setLoadingOlder(false)
260
+ }
261
+ }
262
+
263
+ async function handleNewChat() {
264
+ setSendError('')
265
+ try {
266
+ const created = await createChat()
267
+ const id = created.chat_id
268
+ const entry = {
269
+ chat_id: id,
270
+ preview: 'New conversation',
271
+ updated_at: null,
272
+ message_count: 0,
273
+ }
274
+ setChats((prev) => [entry, ...prev.filter((c) => c.chat_id !== id)])
275
+ setChatListTotal((t) => t + 1)
276
+ setSelectedId(id)
277
+ setFollowUpSuggestions([])
278
+ setTurns([])
279
+ setHasOlder(false)
280
+ setNextBeforeIndex(null)
281
+ setTotalPairs(0)
282
+ setTailBump((x) => x + 1)
283
+ } catch (e) {
284
+ setSendError(e.message || 'Could not create chat')
285
+ }
286
+ }
287
+
288
+ async function handleDeleteChat(chatId) {
289
+ if (!window.confirm('Delete this conversation?')) return
290
+ try {
291
+ await removeChat(chatId)
292
+ const remaining = chats.filter((c) => c.chat_id !== chatId)
293
+ setChats(remaining)
294
+ setChatListTotal((t) => Math.max(0, t - 1))
295
+ if (selectedId === chatId) {
296
+ if (remaining.length > 0) {
297
+ await selectChat(remaining[0].chat_id)
298
+ } else {
299
+ emptyListBootstrapRef.current = false
300
+ const created = await createChat()
301
+ const id = created.chat_id
302
+ setChats([
303
+ {
304
+ chat_id: id,
305
+ preview: 'New conversation',
306
+ updated_at: null,
307
+ message_count: 0,
308
+ },
309
+ ])
310
+ setChatListTotal(1)
311
+ setChatListHasMore(false)
312
+ setSelectedId(id)
313
+ setFollowUpSuggestions([])
314
+ setTurns([])
315
+ setHasOlder(false)
316
+ setNextBeforeIndex(null)
317
+ setTotalPairs(0)
318
+ emptyListBootstrapRef.current = true
319
+ }
320
+ }
321
+ } catch (e) {
322
+ setSendError(e.message || 'Could not delete chat')
323
+ }
324
+ }
325
+
326
+ async function handleSend(overrideText) {
327
+ const raw =
328
+ overrideText !== undefined && overrideText !== null
329
+ ? String(overrideText)
330
+ : question
331
+ const q = raw.trim()
332
+ if (!selectedId || !q || sending) return
333
+
334
+ const clientKey = crypto.randomUUID()
335
+ const pairIdx = totalPairs
336
+
337
+ setSendError('')
338
+ setSending(true)
339
+ setQuestion('')
340
+ setTurns((prev) => [
341
+ ...prev,
342
+ {
343
+ question: q,
344
+ answer: null,
345
+ pending: true,
346
+ clientKey,
347
+ },
348
+ ])
349
+ setTailBump((x) => x + 1)
350
+
351
+ try {
352
+ const res = await sendMessage(selectedId, q, {
353
+ allowAugmentation: suggestionsEnabled,
354
+ useWebSearch: webSearchEnabled,
355
+ })
356
+ const answer = res.answer
357
+ if (suggestionsEnabled) {
358
+ setFollowUpSuggestions(
359
+ Array.isArray(res.suggested_questions) ? res.suggested_questions : [],
360
+ )
361
+ } else {
362
+ setFollowUpSuggestions([])
363
+ }
364
+ setTurns((prev) =>
365
+ prev.map((t) =>
366
+ t.clientKey === clientKey
367
+ ? {
368
+ question: q,
369
+ answer,
370
+ pending: false,
371
+ pairIndex: pairIdx,
372
+ }
373
+ : t,
374
+ ),
375
+ )
376
+ setTotalPairs((n) => n + 1)
377
+ setTailBump((x) => x + 1)
378
+
379
+ setChats((prev) =>
380
+ prev.map((c) =>
381
+ c.chat_id === selectedId
382
+ ? {
383
+ ...c,
384
+ preview: q.slice(0, 100),
385
+ message_count: (c.message_count || 0) + 1,
386
+ }
387
+ : c,
388
+ ),
389
+ )
390
+ } catch (e) {
391
+ setFollowUpSuggestions([])
392
+ setTurns((prev) => prev.filter((t) => t.clientKey !== clientKey))
393
+ setQuestion(q)
394
+ setSendError(e.message || 'Failed to send')
395
+ } finally {
396
+ setSending(false)
397
+ }
398
+ }
399
+
400
+ function logout() {
401
+ clearSession()
402
+ navigate('/login', { replace: true })
403
+ }
404
+
405
+ const selectedChat = selectedId
406
+ ? chats.find((c) => c.chat_id === selectedId)
407
+ : null
408
+ const chatTitle = selectedChat?.preview?.trim() || 'New conversation'
409
+
410
+ function closeMobileSidebar() {
411
+ setMobileSidebarOpen(false)
412
+ }
413
+
414
+ function handleCloseSidebar() {
415
+ if (viewportMd) setDesktopSidebarOpen(false)
416
+ else closeMobileSidebar()
417
+ }
418
+
419
+ function handleOpenSidebar() {
420
+ if (viewportMd) setDesktopSidebarOpen(true)
421
+ else setMobileSidebarOpen(true)
422
+ }
423
+
424
+ const sidebarExpanded = viewportMd ? desktopSidebarOpen : mobileSidebarOpen
425
+ const collapsedSidebarRail = viewportMd && !desktopSidebarOpen
426
+
427
+ return (
428
+ <div className="relative flex h-dvh min-h-0 w-full overflow-hidden bg-chat-canvas md:bg-white">
429
+ {mobileSidebarOpen ? (
430
+ <button
431
+ type="button"
432
+ aria-label="Close sidebar"
433
+ className="fixed inset-0 z-30 bg-slate-900/35 backdrop-blur-[1px] md:hidden"
434
+ onClick={closeMobileSidebar}
435
+ />
436
+ ) : null}
437
+
438
+ <div
439
+ className={`fixed inset-y-0 left-0 z-40 flex h-dvh shrink-0 flex-col overflow-hidden border-r border-slate-200/70 bg-chat-sidebar shadow-[4px_0_24px_rgba(0,0,0,0.08)] transition-[transform,width,min-width,max-width] duration-200 ease-out md:z-0 md:shadow-none ${
440
+ mobileSidebarOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'
441
+ } ${
442
+ desktopSidebarOpen
443
+ ? 'w-[min(92vw,360px)] md:relative md:w-[320px] md:min-w-[320px] lg:w-[360px] lg:min-w-[360px]'
444
+ : 'w-[min(92vw,360px)] md:relative md:w-0 md:min-w-0 md:max-w-0 md:border-r-0 md:opacity-0 md:pointer-events-none'
445
+ }`}
446
+ >
447
+ <ChatSidebar
448
+ user={user}
449
+ chats={chats}
450
+ selectedId={selectedId}
451
+ onCloseSidebar={handleCloseSidebar}
452
+ onSelectChat={(id) => {
453
+ selectChat(id)
454
+ closeMobileSidebar()
455
+ }}
456
+ onNewChat={() => {
457
+ handleNewChat()
458
+ closeMobileSidebar()
459
+ }}
460
+ onDeleteChat={handleDeleteChat}
461
+ onEditProfile={() => {
462
+ setProfileOpen(true)
463
+ closeMobileSidebar()
464
+ }}
465
+ onLogout={() => {
466
+ logout()
467
+ closeMobileSidebar()
468
+ }}
469
+ loadingList={loadingList}
470
+ hasMoreChats={chatListHasMore}
471
+ loadingMoreChats={loadingMoreChats}
472
+ onLoadMoreChats={loadMoreSidebarChats}
473
+ chatListTotal={chatListTotal}
474
+ />
475
+ </div>
476
+
477
+ <div className="flex min-h-0 min-w-0 flex-1 md:bg-chat-canvas">
478
+ {collapsedSidebarRail ? (
479
+ <CollapsedSidebarRail
480
+ onOpenSidebar={handleOpenSidebar}
481
+ onEditProfile={() => setProfileOpen(true)}
482
+ onLogout={logout}
483
+ />
484
+ ) : null}
485
+
486
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
487
+ <ChatMain
488
+ ref={scrollRef}
489
+ chatId={selectedId}
490
+ chatTitle={chatTitle}
491
+ turns={turns}
492
+ loadingChat={loadingChat}
493
+ loadingOlder={loadingOlder}
494
+ hasOlder={hasOlder}
495
+ onLoadOlder={handleLoadOlderMessages}
496
+ sending={sending}
497
+ tailBump={tailBump}
498
+ error={sendError}
499
+ question={question}
500
+ setQuestion={setQuestion}
501
+ onSend={handleSend}
502
+ followUpSuggestions={followUpSuggestions}
503
+ suggestionsEnabled={suggestionsEnabled}
504
+ onSuggestionsEnabledChange={setSuggestionsEnabled}
505
+ webSearchEnabled={webSearchEnabled}
506
+ onWebSearchEnabledChange={setWebSearchEnabled}
507
+ onPickFollowUp={(text) => handleSend(text)}
508
+ sidebarExpanded={sidebarExpanded}
509
+ collapsedSidebarRail={collapsedSidebarRail}
510
+ onOpenSidebar={handleOpenSidebar}
511
+ />
512
+ </div>
513
+ </div>
514
+ <ProfileModal open={profileOpen} onClose={() => setProfileOpen(false)} />
515
+ </div>
516
+ )
517
+ }
frontend/src/pages/Login.jsx ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useEffect, useState } from 'react'
2
+ import { Link, useLocation, useNavigate } from 'react-router-dom'
3
+ import { login } from '../api/auth'
4
+ import { setSession } from '../auth/storage'
5
+ import AuthLayout from './AuthLayout'
6
+
7
+ function EnvelopeIcon({ className = '' }) {
8
+ return (
9
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
10
+ <path
11
+ strokeLinecap="round"
12
+ strokeLinejoin="round"
13
+ d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"
14
+ />
15
+ </svg>
16
+ )
17
+ }
18
+
19
+ function LockIcon({ className = '' }) {
20
+ return (
21
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
22
+ <path
23
+ strokeLinecap="round"
24
+ strokeLinejoin="round"
25
+ d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
26
+ />
27
+ </svg>
28
+ )
29
+ }
30
+
31
+ export default function Login() {
32
+ const navigate = useNavigate()
33
+ const location = useLocation()
34
+ const [email, setEmail] = useState('')
35
+ const [password, setPassword] = useState('')
36
+ const [error, setError] = useState('')
37
+ const [loading, setLoading] = useState(false)
38
+
39
+ useEffect(() => {
40
+ if (location.state?.email) setEmail(location.state.email)
41
+ }, [location.state])
42
+
43
+ async function handleSubmit(e) {
44
+ e.preventDefault()
45
+ setError('')
46
+ setLoading(true)
47
+ try {
48
+ const data = await login(email.trim(), password)
49
+ setSession({
50
+ access_token: data.access_token,
51
+ refresh_token: data.refresh_token,
52
+ user: data.user,
53
+ })
54
+ navigate('/chat', { replace: true })
55
+ } catch (err) {
56
+ setError(err.message || 'Login failed')
57
+ } finally {
58
+ setLoading(false)
59
+ }
60
+ }
61
+
62
+ return (
63
+ <AuthLayout
64
+ brandTo="/login"
65
+ title="Sign in"
66
+ subtitle="Use your COMSATS chatbot account."
67
+ >
68
+ <form onSubmit={handleSubmit} className="flex flex-col gap-5 sm:gap-6">
69
+ {location.state?.registered ? (
70
+ <div
71
+ role="status"
72
+ className="rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-2 text-sm text-emerald-900"
73
+ >
74
+ Account created. You can sign in now.
75
+ </div>
76
+ ) : null}
77
+ {error ? (
78
+ <div
79
+ role="alert"
80
+ className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800"
81
+ >
82
+ {error}
83
+ </div>
84
+ ) : null}
85
+
86
+ <div className="flex flex-col gap-1.5">
87
+ <label htmlFor="login-email" className="text-sm font-medium text-slate-700">
88
+ Email
89
+ </label>
90
+ <div className="relative">
91
+ <EnvelopeIcon className="pointer-events-none absolute left-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
92
+ <input
93
+ id="login-email"
94
+ name="email"
95
+ type="email"
96
+ autoComplete="email"
97
+ required
98
+ value={email}
99
+ onChange={(e) => setEmail(e.target.value)}
100
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white py-3 pl-11 pr-4 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-blue focus:ring-2 focus:ring-comsats-blue/20 sm:text-sm"
101
+ />
102
+ </div>
103
+ </div>
104
+
105
+ <div className="flex flex-col gap-1.5">
106
+ <label htmlFor="login-password" className="text-sm font-medium text-slate-700">
107
+ Password
108
+ </label>
109
+ <div className="relative">
110
+ <LockIcon className="pointer-events-none absolute left-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
111
+ <input
112
+ id="login-password"
113
+ name="password"
114
+ type="password"
115
+ autoComplete="current-password"
116
+ required
117
+ value={password}
118
+ onChange={(e) => setPassword(e.target.value)}
119
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white py-3 pl-11 pr-4 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-blue focus:ring-2 focus:ring-comsats-blue/20 sm:text-sm"
120
+ />
121
+ </div>
122
+ </div>
123
+
124
+ <button
125
+ type="submit"
126
+ disabled={loading}
127
+ className="mt-1 flex min-h-[48px] w-full items-center justify-center rounded-xl bg-gradient-to-r from-comsats-purple to-[#3d2469] px-4 py-3 text-sm font-semibold text-white shadow-md shadow-comsats-purple/25 transition-all hover:brightness-105 focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60"
128
+ >
129
+ {loading ? 'Signing in…' : 'Sign in'}
130
+ </button>
131
+
132
+ <p className="text-center text-sm text-slate-600">
133
+ No account?{' '}
134
+ <Link
135
+ to="/signup"
136
+ className="font-semibold text-comsats-blue underline-offset-2 hover:underline"
137
+ >
138
+ Create one
139
+ </Link>
140
+ <span className="mx-2 text-slate-300">·</span>
141
+ <Link
142
+ to="/admin/login"
143
+ className="font-semibold text-slate-600 underline-offset-2 hover:text-comsats-purple hover:underline"
144
+ >
145
+ Administrator sign-in
146
+ </Link>
147
+ </p>
148
+ </form>
149
+ </AuthLayout>
150
+ )
151
+ }
frontend/src/pages/Signup.jsx ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useState } from 'react'
2
+ import { Link, useNavigate } from 'react-router-dom'
3
+ import { signup } from '../api/auth'
4
+ import AuthLayout from './AuthLayout'
5
+
6
+ function UserIcon({ className = '' }) {
7
+ return (
8
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
9
+ <path
10
+ strokeLinecap="round"
11
+ strokeLinejoin="round"
12
+ d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z"
13
+ />
14
+ </svg>
15
+ )
16
+ }
17
+
18
+ function EnvelopeIcon({ className = '' }) {
19
+ return (
20
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
21
+ <path
22
+ strokeLinecap="round"
23
+ strokeLinejoin="round"
24
+ d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"
25
+ />
26
+ </svg>
27
+ )
28
+ }
29
+
30
+ function LockIcon({ className = '' }) {
31
+ return (
32
+ <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" aria-hidden>
33
+ <path
34
+ strokeLinecap="round"
35
+ strokeLinejoin="round"
36
+ d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
37
+ />
38
+ </svg>
39
+ )
40
+ }
41
+
42
+ export default function Signup() {
43
+ const navigate = useNavigate()
44
+ const [email, setEmail] = useState('')
45
+ const [password, setPassword] = useState('')
46
+ const [fullName, setFullName] = useState('')
47
+ const [error, setError] = useState('')
48
+ const [loading, setLoading] = useState(false)
49
+
50
+ async function handleSubmit(e) {
51
+ e.preventDefault()
52
+ setError('')
53
+ if (password.length < 6) {
54
+ setError('Password must be at least 6 characters.')
55
+ return
56
+ }
57
+ setLoading(true)
58
+ try {
59
+ await signup({ email: email.trim(), password, full_name: fullName })
60
+ navigate('/login', {
61
+ replace: false,
62
+ state: { email: email.trim(), registered: true },
63
+ })
64
+ } catch (err) {
65
+ setError(err.message || 'Signup failed')
66
+ } finally {
67
+ setLoading(false)
68
+ }
69
+ }
70
+
71
+ return (
72
+ <AuthLayout
73
+ brandTo="/signup"
74
+ title="Create account"
75
+ subtitle="Register to use the COMSATS assistant."
76
+ >
77
+ <form onSubmit={handleSubmit} className="flex flex-col gap-5 sm:gap-6">
78
+ {error ? (
79
+ <div
80
+ role="alert"
81
+ className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-800"
82
+ >
83
+ {error}
84
+ </div>
85
+ ) : null}
86
+
87
+ <div className="flex flex-col gap-1.5">
88
+ <label htmlFor="signup-name" className="text-sm font-medium text-slate-700">
89
+ Full name <span className="font-normal text-slate-500">(optional)</span>
90
+ </label>
91
+ <div className="relative">
92
+ <UserIcon className="pointer-events-none absolute left-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
93
+ <input
94
+ id="signup-name"
95
+ name="full_name"
96
+ type="text"
97
+ autoComplete="name"
98
+ value={fullName}
99
+ onChange={(e) => setFullName(e.target.value)}
100
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white py-3 pl-11 pr-4 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-blue focus:ring-2 focus:ring-comsats-blue/20 sm:text-sm"
101
+ />
102
+ </div>
103
+ </div>
104
+
105
+ <div className="flex flex-col gap-1.5">
106
+ <label htmlFor="signup-email" className="text-sm font-medium text-slate-700">
107
+ Email
108
+ </label>
109
+ <div className="relative">
110
+ <EnvelopeIcon className="pointer-events-none absolute left-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
111
+ <input
112
+ id="signup-email"
113
+ name="email"
114
+ type="email"
115
+ autoComplete="email"
116
+ required
117
+ value={email}
118
+ onChange={(e) => setEmail(e.target.value)}
119
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white py-3 pl-11 pr-4 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-blue focus:ring-2 focus:ring-comsats-blue/20 sm:text-sm"
120
+ />
121
+ </div>
122
+ </div>
123
+
124
+ <div className="flex flex-col gap-1.5">
125
+ <label htmlFor="signup-password" className="text-sm font-medium text-slate-700">
126
+ Password
127
+ </label>
128
+ <div className="relative">
129
+ <LockIcon className="pointer-events-none absolute left-3.5 top-1/2 h-5 w-5 -translate-y-1/2 text-slate-400" />
130
+ <input
131
+ id="signup-password"
132
+ name="password"
133
+ type="password"
134
+ autoComplete="new-password"
135
+ required
136
+ minLength={6}
137
+ value={password}
138
+ onChange={(e) => setPassword(e.target.value)}
139
+ className="min-h-[48px] w-full rounded-xl border border-slate-300 bg-white py-3 pl-11 pr-4 text-base text-slate-900 shadow-sm outline-none transition-colors focus:border-comsats-blue focus:ring-2 focus:ring-comsats-blue/20 sm:text-sm"
140
+ />
141
+ </div>
142
+ <p className="text-xs text-slate-500">Minimum 6 characters.</p>
143
+ </div>
144
+
145
+ <button
146
+ type="submit"
147
+ disabled={loading}
148
+ className="mt-1 flex min-h-[48px] w-full items-center justify-center rounded-xl bg-gradient-to-r from-comsats-purple to-[#3d2469] px-4 py-3 text-sm font-semibold text-white shadow-md shadow-comsats-purple/25 transition-all hover:brightness-105 focus:outline-none focus-visible:ring-2 focus-visible:ring-comsats-blue focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60"
149
+ >
150
+ {loading ? 'Creating account…' : 'Sign up'}
151
+ </button>
152
+
153
+ <p className="text-center text-sm text-slate-600">
154
+ Already registered?{' '}
155
+ <Link
156
+ to="/login"
157
+ className="font-semibold text-comsats-blue underline-offset-2 hover:underline"
158
+ >
159
+ Sign in
160
+ </Link>
161
+ </p>
162
+ </form>
163
+ </AuthLayout>
164
+ )
165
+ }
frontend/vite.config.js ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { defineConfig } from 'vite'
2
+ import react from '@vitejs/plugin-react'
3
+ import tailwindcss from '@tailwindcss/vite'
4
+
5
+ // https://vite.dev/config/
6
+ export default defineConfig({
7
+ plugins: [react(), tailwindcss()],
8
+ server: {
9
+ proxy: {
10
+ '/users': { target: 'http://127.0.0.1:8000', changeOrigin: true },
11
+ '/admin': { target: 'http://127.0.0.1:8000', changeOrigin: true },
12
+ '/get_new_chat': { target: 'http://127.0.0.1:8000', changeOrigin: true },
13
+ '/get_chat': { target: 'http://127.0.0.1:8000', changeOrigin: true },
14
+ '/delete_chat': { target: 'http://127.0.0.1:8000', changeOrigin: true },
15
+ '/list_chats': { target: 'http://127.0.0.1:8000', changeOrigin: true },
16
+ '/response': { target: 'http://127.0.0.1:8000', changeOrigin: true },
17
+ },
18
+ },
19
+ })
requirements.txt CHANGED
@@ -1,7 +1,12 @@
 
 
 
1
  pymongo==4.9.2
2
- groq==0.5.0
 
3
  faiss-cpu==1.7.4
4
  torch==2.1.1
 
5
  transformers==4.43.4
6
  Pillow==10.4.0
7
  fastapi==0.112.0
@@ -9,7 +14,10 @@ uvicorn==0.30.5
9
  pydantic==2.8.2
10
  deep-translator
11
  langdetect
12
- langchain-groq
13
  langchain_community
14
  langchain
15
  sentence_transformers
 
 
 
 
1
+ # CPU-only PyTorch wheels (avoids CUDA). transformers has no separate CPU wheel—it runs on CPU via this torch.
2
+ --extra-index-url https://download.pytorch.org/whl/cpu
3
+
4
  pymongo==4.9.2
5
+ groq>=0.30.0,<1.0.0
6
+ google-genai>=1.0.0
7
  faiss-cpu==1.7.4
8
  torch==2.1.1
9
+ torchvision==0.16.1
10
  transformers==4.43.4
11
  Pillow==10.4.0
12
  fastapi==0.112.0
 
14
  pydantic==2.8.2
15
  deep-translator
16
  langdetect
17
+ langchain-groq==0.3.8
18
  langchain_community
19
  langchain
20
  sentence_transformers
21
+ passlib[bcrypt]==1.7.4
22
+ python-jose[cryptography]==3.3.0
23
+ email-validator>=2.0.0
routes/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from . import admin, chathistory, query, users
2
+
3
+ __all__ = ["admin", "users", "query", "chathistory"]
routes/admin.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ from math import ceil
4
+
5
+ from fastapi import APIRouter, File, Header, HTTPException, Query, Request, UploadFile
6
+ from passlib.context import CryptContext
7
+ from pydantic import BaseModel, EmailStr, Field
8
+
9
+ from database import chats_collection
10
+ from dependencies import CurrentAdminIdDep
11
+ from security import (
12
+ create_admin_access_token,
13
+ create_admin_refresh_token,
14
+ decode_admin_refresh_token,
15
+ )
16
+
17
+ router = APIRouter(prefix="/admin", tags=["admin"])
18
+
19
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
20
+
21
+ MAX_KB_CSV_BYTES = 25 * 1024 * 1024
22
+
23
+
24
+ class AdminRegister(BaseModel):
25
+ email: EmailStr
26
+ password: str = Field(min_length=6)
27
+ full_name: str | None = None
28
+
29
+
30
+ class AdminLogin(BaseModel):
31
+ email: EmailStr
32
+ password: str
33
+
34
+
35
+ class AdminPublic(BaseModel):
36
+ admin_id: str
37
+ email: str
38
+ full_name: str | None = None
39
+
40
+
41
+ class AdminRefreshRequest(BaseModel):
42
+ refresh_token: str
43
+
44
+
45
+ class UserRow(BaseModel):
46
+ user_id: str
47
+ email: str
48
+ full_name: str | None = None
49
+
50
+
51
+ class PaginatedUsers(BaseModel):
52
+ items: list[UserRow]
53
+ total: int
54
+ page: int
55
+ page_size: int
56
+ pages: int
57
+
58
+
59
+ def _hash_password(password: str) -> str:
60
+ return pwd_context.hash(password)
61
+
62
+
63
+ def _verify_password(plain: str, hashed: str) -> bool:
64
+ return pwd_context.verify(plain, hashed)
65
+
66
+
67
+ def _admin_public(doc: dict) -> AdminPublic:
68
+ return AdminPublic(
69
+ admin_id=doc["_id"],
70
+ email=doc["email"],
71
+ full_name=doc.get("full_name"),
72
+ )
73
+
74
+
75
+ def _user_row(doc: dict) -> UserRow:
76
+ return UserRow(
77
+ user_id=doc["_id"],
78
+ email=doc["email"],
79
+ full_name=doc.get("full_name"),
80
+ )
81
+
82
+
83
+ def _bootstrap_ok(request: Request, bootstrap_secret_header: str | None) -> bool:
84
+ admins_coll = request.app.state.admins_collection
85
+ if admins_coll.count_documents({}) == 0:
86
+ return True
87
+ env_secret = os.getenv("ADMIN_BOOTSTRAP_SECRET", "").strip()
88
+ if not env_secret:
89
+ return False
90
+ hdr = (bootstrap_secret_header or "").strip()
91
+ return hdr == env_secret
92
+
93
+
94
+ @router.post("/register", response_model=AdminPublic)
95
+ def register_admin(
96
+ body: AdminRegister,
97
+ request: Request,
98
+ x_admin_bootstrap_secret: str | None = Header(default=None, alias="X-Admin-Bootstrap-Secret"),
99
+ ):
100
+ if not _bootstrap_ok(request, x_admin_bootstrap_secret):
101
+ raise HTTPException(
102
+ status_code=403,
103
+ detail="Admin registration is closed. Set ADMIN_BOOTSTRAP_SECRET and send "
104
+ "X-Admin-Bootstrap-Secret header, or register while no admins exist.",
105
+ )
106
+
107
+ admins_coll = request.app.state.admins_collection
108
+ email_lower = body.email.lower().strip()
109
+ if admins_coll.find_one({"email": email_lower}):
110
+ raise HTTPException(status_code=409, detail="Email already registered")
111
+
112
+ admin_id = str(uuid.uuid4())
113
+ doc = {
114
+ "_id": admin_id,
115
+ "email": email_lower,
116
+ "password_hash": _hash_password(body.password),
117
+ "full_name": body.full_name.strip() if body.full_name else None,
118
+ }
119
+ admins_coll.insert_one(doc)
120
+ return _admin_public(doc)
121
+
122
+
123
+ @router.post("/login")
124
+ def admin_login(body: AdminLogin, request: Request):
125
+ admins_coll = request.app.state.admins_collection
126
+ email_lower = body.email.lower().strip()
127
+ admin = admins_coll.find_one({"email": email_lower})
128
+ if not admin or not _verify_password(body.password, admin["password_hash"]):
129
+ raise HTTPException(status_code=401, detail="Invalid email or password")
130
+
131
+ aid = admin["_id"]
132
+ return {
133
+ "access_token": create_admin_access_token(aid),
134
+ "refresh_token": create_admin_refresh_token(aid),
135
+ "token_type": "bearer",
136
+ "admin": _admin_public(admin),
137
+ }
138
+
139
+
140
+ @router.post("/refresh")
141
+ def admin_refresh(body: AdminRefreshRequest, request: Request):
142
+ admins_coll = request.app.state.admins_collection
143
+ aid = decode_admin_refresh_token(body.refresh_token.strip())
144
+ admin = admins_coll.find_one({"_id": aid})
145
+ if not admin:
146
+ raise HTTPException(status_code=401, detail="Admin no longer exists")
147
+
148
+ return {
149
+ "access_token": create_admin_access_token(aid),
150
+ "refresh_token": create_admin_refresh_token(aid),
151
+ "token_type": "bearer",
152
+ }
153
+
154
+
155
+ @router.get("/users", response_model=PaginatedUsers)
156
+ def list_users(
157
+ _: CurrentAdminIdDep,
158
+ request: Request,
159
+ page: int = Query(default=1, ge=1),
160
+ page_size: int = Query(default=20, ge=1, le=100),
161
+ ):
162
+ users_coll = request.app.state.users_collection
163
+ total = users_coll.count_documents({})
164
+ skip = (page - 1) * page_size
165
+ cursor = (
166
+ users_coll.find({}, {"password_hash": 0})
167
+ .sort("email", 1)
168
+ .skip(skip)
169
+ .limit(page_size)
170
+ )
171
+ items = [_user_row(doc) for doc in cursor]
172
+ pages = ceil(total / page_size) if total else 0
173
+ return PaginatedUsers(
174
+ items=items,
175
+ total=total,
176
+ page=page,
177
+ page_size=page_size,
178
+ pages=pages,
179
+ )
180
+
181
+
182
+ @router.delete("/users/{user_id}")
183
+ def delete_user(
184
+ user_id: str,
185
+ _: CurrentAdminIdDep,
186
+ request: Request,
187
+ ):
188
+ users_coll = request.app.state.users_collection
189
+ result = users_coll.delete_one({"_id": user_id})
190
+ if result.deleted_count == 0:
191
+ raise HTTPException(status_code=404, detail="User not found")
192
+ chats_collection.delete_many({"user_id": user_id})
193
+ return {"message": "User and related chats deleted."}
194
+
195
+
196
+ @router.get("/knowledge-base/status")
197
+ def knowledge_base_status(_: CurrentAdminIdDep, request: Request):
198
+ bot = request.app.state.chatbot
199
+ base_present = [p for p in bot.paths if os.path.isfile(p)]
200
+ return {
201
+ "index_path": bot.index_path,
202
+ "kb_upload_dir": bot.kb_upload_dir,
203
+ "index_on_disk": os.path.exists(bot.index_path),
204
+ "retriever_ready": bot.faiss_retriever is not None,
205
+ "base_csv_files": base_present,
206
+ "uploaded_csv_files": bot.list_kb_upload_filenames(),
207
+ }
208
+
209
+
210
+ @router.post("/knowledge-base/upload")
211
+ async def upload_knowledge_base_csv_merge(
212
+ _: CurrentAdminIdDep,
213
+ request: Request,
214
+ file: UploadFile = File(...),
215
+ ):
216
+ """Accept one CSV; embed rows and merge into FAISS (`update_faiss_index`)."""
217
+ if not file.filename or not str(file.filename).strip():
218
+ raise HTTPException(status_code=400, detail="No filename.")
219
+ if not str(file.filename).lower().endswith('.csv'):
220
+ raise HTTPException(status_code=400, detail="Only .csv files are accepted.")
221
+ data = await file.read()
222
+ if len(data) > MAX_KB_CSV_BYTES:
223
+ raise HTTPException(status_code=413, detail="File too large (max 25 MB).")
224
+ chatbot = request.app.state.chatbot
225
+ try:
226
+ stats = chatbot.merge_kb_csv_bytes(file.filename, data)
227
+ except ValueError as e:
228
+ raise HTTPException(status_code=400, detail=str(e))
229
+ except RuntimeError as e:
230
+ raise HTTPException(status_code=503, detail=str(e))
231
+ except Exception:
232
+ raise HTTPException(
233
+ status_code=500,
234
+ detail="Could not merge CSV into the index (check embedding model matches existing index).",
235
+ )
236
+ return {
237
+ "message": "Knowledge base updated (merged into FAISS).",
238
+ **stats,
239
+ }
routes/chathistory.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+
3
+ from fastapi import APIRouter, HTTPException, Query
4
+
5
+ from dependencies import ChatbotDep, CurrentUserIdDep
6
+
7
+ router = APIRouter(tags=["chathistory"])
8
+
9
+
10
+ @router.get("/list_chats")
11
+ def list_chats(
12
+ chatbot: ChatbotDep,
13
+ user_id: CurrentUserIdDep,
14
+ skip: int = Query(0, ge=0),
15
+ limit: int = Query(30, ge=1, le=100),
16
+ ):
17
+ try:
18
+ return chatbot.list_chats(user_id, skip=skip, limit=limit)
19
+ except Exception as e:
20
+ raise HTTPException(status_code=500, detail=str(e))
21
+
22
+
23
+ @router.post("/get_new_chat")
24
+ def create_new_chat(chatbot: ChatbotDep, user_id: CurrentUserIdDep):
25
+ try:
26
+ chat_id = str(uuid.uuid4())
27
+ chatbot.new_chat(chat_id, user_id)
28
+ return {"chat_id": chat_id, "message": "Successfully created new chat.", "user_id": user_id}
29
+ except KeyError:
30
+ raise HTTPException(
31
+ status_code=404,
32
+ detail="Chat ID already exist try again plz...",
33
+ )
34
+ except Exception as e:
35
+ raise HTTPException(status_code=500, detail=str(e))
36
+
37
+
38
+ @router.get("/get_chat/{chat_id}")
39
+ def get_chat(
40
+ chat_id: str,
41
+ chatbot: ChatbotDep,
42
+ user_id: CurrentUserIdDep,
43
+ before_index: int | None = Query(
44
+ None,
45
+ description="Load older pairs with indices strictly before this index.",
46
+ ),
47
+ limit: int = Query(20, ge=1, le=100),
48
+ ):
49
+ try:
50
+ page = chatbot.load_chat_history_page(
51
+ chat_id, user_id, before_index=before_index, limit=limit
52
+ )
53
+ return {
54
+ "chat_id": chat_id,
55
+ "user_id": user_id,
56
+ **page,
57
+ }
58
+ except KeyError:
59
+ raise HTTPException(status_code=404, detail="Chat ID not found")
60
+ except Exception as e:
61
+ raise HTTPException(status_code=500, detail=str(e))
62
+
63
+
64
+ @router.delete("/delete_chat/{chat_id}")
65
+ def delete_chat(chat_id: str, chatbot: ChatbotDep, user_id: CurrentUserIdDep):
66
+ try:
67
+ chatbot.delete_chat(chat_id, user_id)
68
+ return {"message": f"Chat with ID {chat_id} has been deleted successfully."}
69
+ except KeyError:
70
+ raise HTTPException(status_code=404, detail="Chat ID not found")
71
+ except Exception as e:
72
+ raise HTTPException(status_code=500, detail=str(e))
routes/query.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, HTTPException
2
+ from pydantic import BaseModel
3
+
4
+ from dependencies import ChatbotDep, CurrentUserIdDep
5
+
6
+ router = APIRouter(tags=["query"])
7
+
8
+
9
+ class ChatRequest(BaseModel):
10
+ chat_id: str
11
+ question: str
12
+ allow_augmentation: bool = False
13
+ use_web_search: bool = False
14
+
15
+
16
+ @router.post("/response")
17
+ def response(request_body: ChatRequest, chatbot: ChatbotDep, user_id: CurrentUserIdDep):
18
+ try:
19
+ answer, suggested_questions = chatbot.response(
20
+ request_body.question,
21
+ request_body.chat_id,
22
+ user_id,
23
+ allow_augmentation=request_body.allow_augmentation,
24
+ use_web_search=request_body.use_web_search,
25
+ )
26
+ return {
27
+ "answer": answer,
28
+ "suggested_questions": suggested_questions,
29
+ }
30
+ except KeyError:
31
+ raise HTTPException(status_code=404, detail="Chat ID not found")
32
+ except Exception:
33
+ raise HTTPException(status_code=500, detail="GPU error, try after some time...")
routes/users.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+
3
+ from fastapi import APIRouter, HTTPException, Request
4
+ from passlib.context import CryptContext
5
+ from pydantic import BaseModel, EmailStr, Field
6
+
7
+ from database import chats_collection
8
+ from dependencies import CurrentUserIdDep
9
+ from security import create_access_token, create_refresh_token, decode_refresh_token
10
+
11
+ router = APIRouter(prefix="/users", tags=["users"])
12
+
13
+ pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
14
+
15
+
16
+ class UserCreate(BaseModel):
17
+ email: EmailStr
18
+ password: str = Field(min_length=6)
19
+ full_name: str | None = None
20
+
21
+
22
+ class UserLogin(BaseModel):
23
+ email: EmailStr
24
+ password: str
25
+
26
+
27
+ class UserProfileUpdate(BaseModel):
28
+ full_name: str | None = None
29
+ email: EmailStr | None = None
30
+
31
+
32
+ class UserPublic(BaseModel):
33
+ user_id: str
34
+ email: str
35
+ full_name: str | None = None
36
+
37
+
38
+ class RefreshRequest(BaseModel):
39
+ refresh_token: str
40
+
41
+
42
+ def _hash_password(password: str) -> str:
43
+ return pwd_context.hash(password)
44
+
45
+
46
+ def _verify_password(plain: str, hashed: str) -> bool:
47
+ return pwd_context.verify(plain, hashed)
48
+
49
+
50
+ def _user_public(doc: dict) -> UserPublic:
51
+ return UserPublic(
52
+ user_id=doc["_id"],
53
+ email=doc["email"],
54
+ full_name=doc.get("full_name"),
55
+ )
56
+
57
+
58
+ @router.post("", response_model=UserPublic)
59
+ def create_user(body: UserCreate, request: Request):
60
+ users_coll = request.app.state.users_collection
61
+ email_lower = body.email.lower().strip()
62
+ if users_coll.find_one({"email": email_lower}):
63
+ raise HTTPException(status_code=409, detail="Email already registered")
64
+
65
+ user_id = str(uuid.uuid4())
66
+ doc = {
67
+ "_id": user_id,
68
+ "email": email_lower,
69
+ "password_hash": _hash_password(body.password),
70
+ "full_name": body.full_name.strip() if body.full_name else None,
71
+ }
72
+ users_coll.insert_one(doc)
73
+ return _user_public(doc)
74
+
75
+
76
+ @router.get("/me", response_model=UserPublic)
77
+ def get_profile(user_id: CurrentUserIdDep, request: Request):
78
+ users_coll = request.app.state.users_collection
79
+ user = users_coll.find_one({"_id": user_id})
80
+ if not user:
81
+ raise HTTPException(status_code=404, detail="User not found")
82
+ return _user_public(user)
83
+
84
+
85
+ @router.patch("/me", response_model=UserPublic)
86
+ def edit_profile(body: UserProfileUpdate, user_id: CurrentUserIdDep, request: Request):
87
+ users_coll = request.app.state.users_collection
88
+ user = users_coll.find_one({"_id": user_id})
89
+ if not user:
90
+ raise HTTPException(status_code=404, detail="User not found")
91
+
92
+ updates: dict = {}
93
+ if body.full_name is not None:
94
+ updates["full_name"] = body.full_name.strip() or None
95
+ if body.email is not None:
96
+ new_email = body.email.lower().strip()
97
+ existing = users_coll.find_one({"email": new_email, "_id": {"$ne": user_id}})
98
+ if existing:
99
+ raise HTTPException(status_code=409, detail="Email already in use")
100
+ updates["email"] = new_email
101
+
102
+ if not updates:
103
+ return _user_public(user)
104
+
105
+ users_coll.update_one({"_id": user_id}, {"$set": updates})
106
+ updated = users_coll.find_one({"_id": user_id})
107
+ return _user_public(updated)
108
+
109
+
110
+ @router.delete("/me")
111
+ def delete_me(user_id: CurrentUserIdDep, request: Request):
112
+ users_coll = request.app.state.users_collection
113
+ result = users_coll.delete_one({"_id": user_id})
114
+ if result.deleted_count == 0:
115
+ raise HTTPException(status_code=404, detail="User not found")
116
+ chats_collection.delete_many({"user_id": user_id})
117
+ return {"message": "User account and related chats deleted successfully."}
118
+
119
+
120
+ @router.post("/login")
121
+ def login(body: UserLogin, request: Request):
122
+ users_coll = request.app.state.users_collection
123
+ email_lower = body.email.lower().strip()
124
+ user = users_coll.find_one({"email": email_lower})
125
+ if not user or not _verify_password(body.password, user["password_hash"]):
126
+ raise HTTPException(status_code=401, detail="Invalid email or password")
127
+
128
+ uid = user["_id"]
129
+ return {
130
+ "access_token": create_access_token(uid),
131
+ "refresh_token": create_refresh_token(uid),
132
+ "token_type": "bearer",
133
+ "user": _user_public(user),
134
+ }
135
+
136
+
137
+ @router.post("/refresh")
138
+ def refresh_tokens(body: RefreshRequest, request: Request):
139
+ users_coll = request.app.state.users_collection
140
+ uid = decode_refresh_token(body.refresh_token.strip())
141
+ user = users_coll.find_one({"_id": uid})
142
+ if not user:
143
+ raise HTTPException(status_code=401, detail="User no longer exists")
144
+
145
+ return {
146
+ "access_token": create_access_token(uid),
147
+ "refresh_token": create_refresh_token(uid),
148
+ "token_type": "bearer",
149
+ }
security.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from datetime import datetime, timedelta, timezone
3
+ from typing import Annotated
4
+
5
+ from fastapi import Depends, HTTPException, status
6
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
7
+ from jose import JWTError, jwt
8
+
9
+ SECRET_KEY = os.getenv("JWT_SECRET_KEY", "dev-secret-change-in-production")
10
+ ALGORITHM = "HS256"
11
+ ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60"))
12
+ REFRESH_TOKEN_EXPIRE_DAYS = int(os.getenv("REFRESH_TOKEN_EXPIRE_DAYS", "7"))
13
+
14
+ TOKEN_TYPE_ACCESS = "access"
15
+ TOKEN_TYPE_REFRESH = "refresh"
16
+ TOKEN_TYPE_ADMIN_REFRESH = "admin_refresh"
17
+ ROLE_ADMIN = "admin"
18
+
19
+ security_scheme = HTTPBearer()
20
+
21
+
22
+ def create_access_token(subject: str) -> str:
23
+ expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
24
+ return jwt.encode(
25
+ {"sub": subject, "exp": expire, "typ": TOKEN_TYPE_ACCESS},
26
+ SECRET_KEY,
27
+ algorithm=ALGORITHM,
28
+ )
29
+
30
+
31
+ def create_refresh_token(subject: str) -> str:
32
+ expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
33
+ return jwt.encode(
34
+ {"sub": subject, "exp": expire, "typ": TOKEN_TYPE_REFRESH},
35
+ SECRET_KEY,
36
+ algorithm=ALGORITHM,
37
+ )
38
+
39
+
40
+ def create_admin_access_token(subject: str) -> str:
41
+ expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
42
+ return jwt.encode(
43
+ {
44
+ "sub": subject,
45
+ "exp": expire,
46
+ "typ": TOKEN_TYPE_ACCESS,
47
+ "role": ROLE_ADMIN,
48
+ },
49
+ SECRET_KEY,
50
+ algorithm=ALGORITHM,
51
+ )
52
+
53
+
54
+ def create_admin_refresh_token(subject: str) -> str:
55
+ expire = datetime.now(timezone.utc) + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
56
+ return jwt.encode(
57
+ {"sub": subject, "exp": expire, "typ": TOKEN_TYPE_ADMIN_REFRESH},
58
+ SECRET_KEY,
59
+ algorithm=ALGORITHM,
60
+ )
61
+
62
+
63
+ def decode_refresh_token(token: str) -> str:
64
+ try:
65
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
66
+ except JWTError:
67
+ raise HTTPException(
68
+ status_code=status.HTTP_401_UNAUTHORIZED,
69
+ detail="Invalid or expired refresh token",
70
+ )
71
+ if payload.get("typ") != TOKEN_TYPE_REFRESH:
72
+ raise HTTPException(
73
+ status_code=status.HTTP_401_UNAUTHORIZED,
74
+ detail="Invalid refresh token",
75
+ )
76
+ sub = payload.get("sub")
77
+ if not isinstance(sub, str) or not sub:
78
+ raise HTTPException(
79
+ status_code=status.HTTP_401_UNAUTHORIZED,
80
+ detail="Invalid refresh token",
81
+ )
82
+ return sub
83
+
84
+
85
+ def decode_admin_refresh_token(token: str) -> str:
86
+ try:
87
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
88
+ except JWTError:
89
+ raise HTTPException(
90
+ status_code=status.HTTP_401_UNAUTHORIZED,
91
+ detail="Invalid or expired refresh token",
92
+ )
93
+ if payload.get("typ") != TOKEN_TYPE_ADMIN_REFRESH:
94
+ raise HTTPException(
95
+ status_code=status.HTTP_401_UNAUTHORIZED,
96
+ detail="Invalid refresh token",
97
+ )
98
+ sub = payload.get("sub")
99
+ if not isinstance(sub, str) or not sub:
100
+ raise HTTPException(
101
+ status_code=status.HTTP_401_UNAUTHORIZED,
102
+ detail="Invalid refresh token",
103
+ )
104
+ return sub
105
+
106
+
107
+ def get_current_user_id(
108
+ credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
109
+ ) -> str:
110
+ credentials_exception = HTTPException(
111
+ status_code=status.HTTP_401_UNAUTHORIZED,
112
+ detail="Invalid or expired token",
113
+ headers={"WWW-Authenticate": "Bearer"},
114
+ )
115
+ try:
116
+ payload = jwt.decode(
117
+ credentials.credentials,
118
+ SECRET_KEY,
119
+ algorithms=[ALGORITHM],
120
+ )
121
+ if payload.get("typ") == TOKEN_TYPE_REFRESH:
122
+ raise credentials_exception
123
+ typ = payload.get("typ")
124
+ if typ is not None and typ != TOKEN_TYPE_ACCESS:
125
+ raise credentials_exception
126
+ sub = payload.get("sub")
127
+ if not isinstance(sub, str) or not sub:
128
+ raise credentials_exception
129
+ if payload.get("role") == ROLE_ADMIN:
130
+ raise credentials_exception
131
+ return sub
132
+ except JWTError:
133
+ raise credentials_exception
134
+
135
+
136
+ def get_current_admin_id(
137
+ credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
138
+ ) -> str:
139
+ credentials_exception = HTTPException(
140
+ status_code=status.HTTP_401_UNAUTHORIZED,
141
+ detail="Invalid or expired token",
142
+ headers={"WWW-Authenticate": "Bearer"},
143
+ )
144
+ forbidden = HTTPException(
145
+ status_code=status.HTTP_403_FORBIDDEN,
146
+ detail="Admin access required",
147
+ )
148
+ try:
149
+ payload = jwt.decode(
150
+ credentials.credentials,
151
+ SECRET_KEY,
152
+ algorithms=[ALGORITHM],
153
+ )
154
+ if payload.get("typ") == TOKEN_TYPE_REFRESH:
155
+ raise credentials_exception
156
+ if payload.get("typ") == TOKEN_TYPE_ADMIN_REFRESH:
157
+ raise credentials_exception
158
+ typ = payload.get("typ")
159
+ if typ is not None and typ != TOKEN_TYPE_ACCESS:
160
+ raise credentials_exception
161
+ if payload.get("role") != ROLE_ADMIN:
162
+ raise forbidden
163
+ sub = payload.get("sub")
164
+ if not isinstance(sub, str) or not sub:
165
+ raise credentials_exception
166
+ return sub
167
+ except JWTError:
168
+ raise credentials_exception