Spaces:
Paused

dushyantsingh0 commited on
Commit
5df0bfe
·
1 Parent(s): db51981

feat: unified portal migration with local redis and fixed routing

Browse files
Dockerfile CHANGED
@@ -1,10 +1,23 @@
1
- # --- STAGE 1: BASE (Lightweight Core) ---
2
- FROM python:3.11-slim AS base
 
 
 
 
 
 
 
 
 
 
 
 
3
 
 
 
4
  ENV PYTHONDONTWRITEBYTECODE=1 \
5
  PYTHONUNBUFFERED=1 \
6
  PYTHONPATH=/app
7
-
8
  WORKDIR /app
9
 
10
  # Install minimal system dependencies
@@ -14,43 +27,36 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
14
  gcc \
15
  curl \
16
  ca-certificates \
17
- && apt-get clean && rm -rf /var/lib/apt/lists/* \
18
- && update-ca-certificates
19
 
20
  # Install core requirements
21
  COPY requirements.txt .
22
  RUN pip install --no-cache-dir -r requirements.txt
23
 
24
- # Copy application code
25
- COPY . .
26
-
27
- # Create directory for uploads
28
- RUN mkdir -p uploads logs
29
-
30
- EXPOSE 7860
31
- CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
32
-
33
-
34
- # --- STAGE 2: HYBRID-AI (Optimized Worker) ---
35
  FROM base AS heavy
36
-
37
- # Install lightweight AI dependencies (No Torch/CUDA)
38
  COPY requirements-ai.txt .
39
  RUN pip install --no-cache-dir -r requirements-ai.txt
40
 
41
- # PRE-CACHE ONNX WEIGHTS
42
- # This ensures sub-second boot times for local CLIP inference without 10GB of bloat.
43
- # Placeholder for ONNX download script - in production, this would pull from HF.
44
- RUN mkdir -p models && \
45
- python -c "print('Pre-caching ONNX weights for clip-ViT-B-32...')"
46
-
47
- # --- STAGE 3: PRODUCTION (Unified API + Worker) ---
48
  FROM heavy AS production
 
 
 
 
 
 
 
 
 
 
 
49
 
50
  # Expose Hugging Face default port
51
  EXPOSE 7860
52
 
53
- # Ensure entrypoint script is executable and has Linux line endings
54
  RUN sed -i 's/\r$//' scripts/run_prod.sh && \
55
  chmod +x scripts/run_prod.sh
56
 
 
1
+ # --- STAGE 1: FRONTEND BUILD (Node.js) ---
2
+ FROM node:20-slim AS frontend-builder
3
+ WORKDIR /app/frontend
4
+
5
+ # Copy frontend workspace files
6
+ COPY frontend/package*.json ./
7
+ COPY frontend/packages ./packages
8
+ COPY frontend/apps ./apps
9
+ COPY frontend/tsconfig.json ./
10
+
11
+ # Install and Build all workspaces
12
+ # Note: We build WITHOUT an explicit VITE_API_URL so the client defaults to relative paths
13
+ RUN npm install
14
+ RUN npm run build --workspaces
15
 
16
+ # --- STAGE 2: BACKEND BASE (Python) ---
17
+ FROM python:3.11-slim AS base
18
  ENV PYTHONDONTWRITEBYTECODE=1 \
19
  PYTHONUNBUFFERED=1 \
20
  PYTHONPATH=/app
 
21
  WORKDIR /app
22
 
23
  # Install minimal system dependencies
 
27
  gcc \
28
  curl \
29
  ca-certificates \
30
+ redis-server \
31
+ && apt-get clean && rm -rf /var/lib/apt/lists/*
32
 
33
  # Install core requirements
34
  COPY requirements.txt .
35
  RUN pip install --no-cache-dir -r requirements.txt
36
 
37
+ # --- STAGE 3: HEAVY-AI (Optional logic) ---
 
 
 
 
 
 
 
 
 
 
38
  FROM base AS heavy
 
 
39
  COPY requirements-ai.txt .
40
  RUN pip install --no-cache-dir -r requirements-ai.txt
41
 
42
+ # --- STAGE 4: PRODUCTION (Unified) ---
 
 
 
 
 
 
43
  FROM heavy AS production
44
+ WORKDIR /app
45
+
46
+ # Copy backend application code
47
+ COPY . .
48
+
49
+ # Copy BUILT frontend assets from Stage 1 into the backend directories
50
+ COPY --from=frontend-builder /app/frontend/apps/customer/dist ./frontend/apps/customer/dist
51
+ COPY --from=frontend-builder /app/frontend/apps/internal/dist ./frontend/apps/internal/dist
52
+
53
+ # Create runtime directories
54
+ RUN mkdir -p uploads logs
55
 
56
  # Expose Hugging Face default port
57
  EXPOSE 7860
58
 
59
+ # Ensure entrypoint script is executable
60
  RUN sed -i 's/\r$//' scripts/run_prod.sh && \
61
  chmod +x scripts/run_prod.sh
62
 
README.md CHANGED
@@ -1,19 +1,29 @@
1
  ---
2
- title: Nexus Backend
3
- emoji: 🪐
4
- colorFrom: indigo
5
- colorTo: gray
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
  ---
10
 
11
- # Nexus AI Backend (Beta 1.0)
12
 
13
- Distributed, local-first AI platform for unified workspace management.
14
 
15
- ### Deployment Details
16
- - **Architecture**: Unified FastAPI + Arq Worker Sidecar.
17
- - **Port**: 7860 (Hugging Face Default).
18
- - **Persistence**: Mounted via `/data` storage bucket.
19
- - **AI Intelligence**: Hybrid (Local Ollama Tunnel + Google Gemini).
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Nexus Unified Gateway
3
+ emoji: 🛡️
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: docker
7
  app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # Nexus Unified Gateway
12
 
13
+ This is the unified deployment of the Nexus Customer Support Portal and Internal Staff Gateway.
14
 
15
+ ## Live Dashboards
16
+ - **Customer Portal**: `https://[space-name].hf.space/`
17
+ - **Internal Staff Portal**: `https://[space-name].hf.space/admin/`
18
+ - **API Documentation**: `https://[space-name].hf.space/docs`
19
+
20
+ ## Features
21
+ - **Hybrid AI Core**: Integrated LangGraph agent and semantic search.
22
+ - **Unified Logic**: Frontend and Backend served from a single origin (Zero CORS issues).
23
+ - **Auto-Sync**: Background worker for Knowledge Base re-indexing is built into the sidecar process.
24
+
25
+ ## Local Development
26
+ To run this locally without Docker:
27
+ 1. Start Backend: `python main.py`
28
+ 2. Start Customer: `npm run dev -w frontend/apps/customer`
29
+ 3. Start Internal: `npm run dev -w frontend/apps/internal`
core/config.py CHANGED
@@ -66,7 +66,7 @@ class Settings(BaseSettings):
66
  return self.DB_HOST
67
 
68
  REDIS_URL: str = "redis://localhost:6379"
69
- CACHE_REDIS_URL: str = "redis://localhost:6380"
70
 
71
  # JWT Auth
72
  SECRET_KEY: str = "your-secret-key-change-in-production"
@@ -123,6 +123,13 @@ class Settings(BaseSettings):
123
  UPLOAD_DIR: str = "uploads"
124
  LOG_DIR: str = "logs"
125
 
 
 
 
 
 
 
 
126
  class Config:
127
  case_sensitive = True
128
  env_file = ".env"
 
66
  return self.DB_HOST
67
 
68
  REDIS_URL: str = "redis://localhost:6379"
69
+ CACHE_REDIS_URL: str = "redis://localhost:6379"
70
 
71
  # JWT Auth
72
  SECRET_KEY: str = "your-secret-key-change-in-production"
 
123
  UPLOAD_DIR: str = "uploads"
124
  LOG_DIR: str = "logs"
125
 
126
+ # S3 Configuration (Required if STORAGE_BACKEND="s3")
127
+ S3_ACCESS_KEY: str | None = None
128
+ S3_SECRET_KEY: str | None = None
129
+ S3_BUCKET: str | None = None
130
+ S3_REGION: str = "us-east-1"
131
+ S3_ENDPOINT_URL: str | None = None # For Cloudflare R2 or Minio
132
+
133
  class Config:
134
  case_sensitive = True
135
  env_file = ".env"
frontend/apps/customer/src/components/Analytics.tsx CHANGED
@@ -35,7 +35,7 @@ const Sparkline: React.FC<{ data: number[], color: string }> = ({ data, color })
35
  };
36
 
37
  export const Analytics: React.FC<AnalyticsProps> = ({ tickets }) => {
38
- const { volume, sla, loading: reportsLoading, refresh: refreshReports } = useReports();
39
  const { narrative, loading: narrativeLoading, refresh: refreshNarrative } = useServiceNarrative();
40
  const [isResummarizing, setIsResummarizing] = useState(false);
41
 
@@ -121,11 +121,13 @@ export const Analytics: React.FC<AnalyticsProps> = ({ tickets }) => {
121
  },
122
  {
123
  label: "CSAT Score",
124
- value: showReportsLoading ? <Skeleton width={60} height={32} /> : "4.8",
125
- footer: showReportsLoading ? <Skeleton width={100} height={12} /> : `Lifetime Satisfactory`,
126
  color: "hsl(38, 92%, 50%)",
127
  icon: "⭐",
128
- viz: showReportsLoading ? <Skeleton width={80} height={11} /> : <div style={{ fontSize: 11, color: "#EAB308" }}>{"★".repeat(5) + "☆".repeat(0)}</div>
 
 
129
  },
130
  ].map(s => (
131
  <div key={s.label} style={{
 
35
  };
36
 
37
  export const Analytics: React.FC<AnalyticsProps> = ({ tickets }) => {
38
+ const { volume, sla, csat, loading: reportsLoading, refresh: refreshReports } = useReports();
39
  const { narrative, loading: narrativeLoading, refresh: refreshNarrative } = useServiceNarrative();
40
  const [isResummarizing, setIsResummarizing] = useState(false);
41
 
 
121
  },
122
  {
123
  label: "CSAT Score",
124
+ value: showReportsLoading ? <Skeleton width={60} height={32} /> : (csat ? csat.average_rating.toFixed(1) : "—"),
125
+ footer: showReportsLoading ? <Skeleton width={100} height={12} /> : (csat?.total_responses ? `${csat.total_responses} Total Ratings` : "No Ratings Yet"),
126
  color: "hsl(38, 92%, 50%)",
127
  icon: "⭐",
128
+ viz: showReportsLoading ? <Skeleton width={80} height={11} /> : <div style={{ fontSize: 11, color: "#EAB308" }}>
129
+ {"★".repeat(Math.floor(csat?.average_rating || 0)) + "☆".repeat(5 - Math.floor(csat?.average_rating || 0))}
130
+ </div>
131
  },
132
  ].map(s => (
133
  <div key={s.label} style={{
frontend/apps/customer/src/components/KnowledgeBase.module.css ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Customer Portal KB Premium Styles */
2
+ .container {
3
+ padding: 32px 48px;
4
+ color: #111827;
5
+ }
6
+
7
+ .searchHero {
8
+ margin-bottom: 48px;
9
+ }
10
+
11
+ .searchHero h1 {
12
+ font-size: 32px;
13
+ font-weight: 800;
14
+ color: #111827;
15
+ margin-bottom: 8px;
16
+ letter-spacing: -0.02em;
17
+ }
18
+
19
+ .description {
20
+ color: #6B7280;
21
+ font-size: 15px;
22
+ margin-bottom: 32px;
23
+ }
24
+
25
+ .searchControls {
26
+ display: flex;
27
+ gap: 20px;
28
+ align-items: center;
29
+ flex-wrap: wrap;
30
+ }
31
+
32
+ .searchWrapper {
33
+ position: relative;
34
+ flex: 1;
35
+ min-width: 320px;
36
+ }
37
+
38
+ .searchInput {
39
+ width: 100%;
40
+ padding: 16px 20px 16px 52px;
41
+ border-radius: 16px;
42
+ border: 1px solid #E5E7EB;
43
+ font-size: 16px;
44
+ box-sizing: border-box;
45
+ outline: none;
46
+ box-shadow: 0 2px 10px rgba(0,0,0,0.03);
47
+ transition: all 0.2s;
48
+ }
49
+
50
+ .searchInput:focus {
51
+ border-color: #1E40AF;
52
+ box-shadow: 0 0 0 4px rgba(30, 64, 175, 0.1);
53
+ }
54
+
55
+ .searchBtn {
56
+ position: absolute;
57
+ right: 12px;
58
+ top: 50%;
59
+ transform: translateY(-50%);
60
+ background: #1E40AF;
61
+ color: #fff;
62
+ border: none;
63
+ padding: 8px 16px;
64
+ border-radius: 10px;
65
+ cursor: pointer;
66
+ font-size: 13px;
67
+ font-weight: 700;
68
+ transition: background 0.2s;
69
+ }
70
+
71
+ .searchBtn:hover {
72
+ background: #1E3A8A;
73
+ }
74
+
75
+ .searchIcon {
76
+ position: absolute;
77
+ left: 20px;
78
+ top: 50%;
79
+ transform: translateY(-50%);
80
+ color: #9CA3AF;
81
+ }
82
+
83
+ .searchPulse {
84
+ position: absolute;
85
+ right: 100px;
86
+ top: 50%;
87
+ transform: translateY(-50%);
88
+ display: flex;
89
+ align-items: center;
90
+ gap: 8px;
91
+ font-size: 10px;
92
+ font-weight: 800;
93
+ color: #16A34A;
94
+ animation: pulse 2s infinite;
95
+ }
96
+
97
+ @keyframes pulse {
98
+ 0% { opacity: 0.6; }
99
+ 50% { opacity: 1; }
100
+ 100% { opacity: 0.6; }
101
+ }
102
+
103
+ .pulseIcon {
104
+ animation: rotate 2s linear infinite;
105
+ }
106
+
107
+ @keyframes rotate {
108
+ from { transform: rotate(0deg); }
109
+ to { transform: rotate(360deg); }
110
+ }
111
+
112
+ /* AI Answer Spotlight */
113
+ .aiSpotlight {
114
+ max-width: 1100px;
115
+ margin: 0 auto 48px;
116
+ background: white;
117
+ border: 1px solid #E5E7EB;
118
+ border-radius: 20px;
119
+ padding: 40px;
120
+ position: relative;
121
+ box-shadow: 0 4px 20px rgba(0,0,0,0.02);
122
+ }
123
+
124
+ .aiSpotlight::before {
125
+ content: '';
126
+ position: absolute;
127
+ top: 0;
128
+ left: 0;
129
+ width: 100%;
130
+ height: 3px;
131
+ background: #1E40AF;
132
+ border-radius: 20px 20px 0 0;
133
+ }
134
+
135
+ .spotlightHeader {
136
+ display: flex;
137
+ justify-content: space-between;
138
+ align-items: center;
139
+ margin-bottom: 24px;
140
+ }
141
+
142
+ .spotlightBadge {
143
+ display: flex;
144
+ align-items: center;
145
+ gap: 10px;
146
+ background: #EFF6FF;
147
+ padding: 6px 14px;
148
+ border-radius: 8px;
149
+ color: #1E40AF;
150
+ font-size: 11px;
151
+ font-weight: 900;
152
+ text-transform: uppercase;
153
+ letter-spacing: 0.1em;
154
+ }
155
+
156
+ .syntheticFlag {
157
+ font-size: 10px;
158
+ font-weight: 800;
159
+ color: #16A34A;
160
+ background: #F0FDF4;
161
+ padding: 4px 8px;
162
+ border-radius: 4px;
163
+ }
164
+
165
+ .answerText {
166
+ font-size: 18px;
167
+ line-height: 1.8;
168
+ color: #111827;
169
+ font-weight: 600;
170
+ font-style: italic;
171
+ margin: 0;
172
+ }
173
+
174
+ .spotlightFooter {
175
+ margin-top: 24px;
176
+ padding-top: 20px;
177
+ border-top: 1px solid #F3F4F6;
178
+ font-size: 11px;
179
+ font-weight: 700;
180
+ color: #9CA3AF;
181
+ text-transform: uppercase;
182
+ letter-spacing: 0.1em;
183
+ }
184
+
185
+ /* Articles Grid */
186
+ .articlesGrid {
187
+ display: grid;
188
+ grid-template-columns: repeat(auto-fill, minmax(440px, 1fr));
189
+ gap: 32px;
190
+ max-width: 1100px;
191
+ margin: 0 auto;
192
+ }
193
+
194
+ .articleCard {
195
+ background: #fff;
196
+ border: 1px solid #F3F4FB;
197
+ border-radius: 20px;
198
+ padding: 32px;
199
+ cursor: pointer;
200
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
201
+ box-shadow: 0 2px 4px rgba(0,0,0,0.02);
202
+ display: flex;
203
+ flex-direction: column;
204
+ height: 100%;
205
+ }
206
+
207
+ .articleCard:hover {
208
+ transform: translateY(-4px);
209
+ box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.05);
210
+ border-color: #1E40AF;
211
+ }
212
+
213
+ .cardHeader {
214
+ display: flex;
215
+ justify-content: space-between;
216
+ align-items: center;
217
+ margin-bottom: 16px;
218
+ }
219
+
220
+ .categoryBadge {
221
+ font-size: 10px;
222
+ font-weight: 800;
223
+ color: #1E40AF;
224
+ text-transform: uppercase;
225
+ letter-spacing: 0.1em;
226
+ }
227
+
228
+ .matchBadge {
229
+ font-size: 10px;
230
+ font-weight: 800;
231
+ padding: 2px 8px;
232
+ border-radius: 4px;
233
+ }
234
+
235
+ .highMatch {
236
+ color: #16A34A;
237
+ background: #F0FDF4;
238
+ }
239
+
240
+ .regularMatch {
241
+ color: #1E40AF;
242
+ background: #EFF6FF;
243
+ }
244
+
245
+ .articleTitle {
246
+ font-size: 22px;
247
+ font-weight: 800;
248
+ color: #111827;
249
+ margin-bottom: 12px;
250
+ line-height: 1.2;
251
+ }
252
+
253
+ .articleSnippet {
254
+ font-size: 15px;
255
+ color: #4B5563;
256
+ line-height: 1.6;
257
+ margin-bottom: 24px;
258
+ display: -webkit-box;
259
+ -webkit-line-clamp: 3;
260
+ -webkit-box-orient: vertical;
261
+ overflow: hidden;
262
+ }
263
+
264
+ .cardFooter {
265
+ display: flex;
266
+ justify-content: space-between;
267
+ align-items: center;
268
+ border-top: 1px solid #F9FAFB;
269
+ padding-top: 24px;
270
+ margin-top: auto;
271
+ }
272
+
273
+ .articleDate {
274
+ font-size: 12px;
275
+ color: #9CA3AF;
276
+ font-weight: 500;
277
+ }
278
+
279
+ .readMore {
280
+ font-size: 13px;
281
+ font-weight: 700;
282
+ color: #1E40AF;
283
+ }
284
+
285
+ /* Category Nav */
286
+ .categoryNav {
287
+ display: flex;
288
+ gap: 12px;
289
+ margin-bottom: 40px;
290
+ border-bottom: 1px solid #F3F4FB;
291
+ padding-bottom: 16px;
292
+ overflow-x: auto;
293
+ }
294
+
295
+ .navItem {
296
+ padding: 8px 0;
297
+ border: none;
298
+ background: none;
299
+ font-size: 14px;
300
+ font-weight: 600;
301
+ cursor: pointer;
302
+ margin-right: 24px;
303
+ white-space: nowrap;
304
+ color: #6B7280;
305
+ transition: all 0.2s;
306
+ }
307
+
308
+ .navItemActive {
309
+ color: #1E40AF;
310
+ font-weight: 700;
311
+ border-bottom: 2px solid #1E40AF;
312
+ }
313
+
314
+ /* Article View Enhancements */
315
+ .articleDetail {
316
+ padding: 40px 60px;
317
+ maxWidth: 900px;
318
+ margin: 0 auto;
319
+ }
320
+
321
+ .backBtn {
322
+ background: none;
323
+ border: none;
324
+ color: #1E40AF;
325
+ font-weight: 700;
326
+ font-size: 14px;
327
+ cursor: pointer;
328
+ margin-bottom: 32px;
329
+ display: flex;
330
+ align-items: center;
331
+ gap: 8px;
332
+ }
333
+
334
+ .mermaidContainer {
335
+ margin: 24px 0;
336
+ background: #1F2937;
337
+ padding: 32px;
338
+ border-radius: 16px;
339
+ overflow-x: auto;
340
+ display: flex;
341
+ justify-content: center;
342
+ }
343
+
344
+ .shimmerText {
345
+ animation: shimmer 1.5s infinite linear;
346
+ }
347
+
348
+ @keyframes shimmer {
349
+ 0% { opacity: 0.5; }
350
+ 50% { opacity: 1; }
351
+ 100% { opacity: 0.5; }
352
+ }
frontend/apps/customer/src/components/KnowledgeBase.tsx CHANGED
@@ -1,402 +1,407 @@
1
- import React, { useState, useEffect } from 'react';
2
- import { api, NexusMarkdown } from '@nexus/shared';
3
- import { Skeleton } from './Skeleton';
4
- import { Search, ChevronLeft, ChevronRight, Sparkles } from 'lucide-react';
 
 
 
 
 
 
5
 
6
- const COLORS = {
7
- brand: "#1E40AF",
8
- brandLight: "#EFF6FF",
9
- brandDeep: "#1E3A8A",
10
- success: "#16A34A",
11
- gray50: "#F9FAFB",
12
- gray100: "#F3F4FB",
13
- gray200: "#E5E7EB",
14
- gray300: "#D1D5DB",
15
- gray400: "#9CA3AF",
16
- gray500: "#6B7280",
17
- gray600: "#4B5563",
18
- gray700: "#374151",
19
- gray800: "#1F2937",
20
- gray900: "#111827",
 
 
 
 
 
 
 
 
21
  };
22
 
23
- const ITEMS_PER_PAGE = 4;
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  interface KnowledgeBaseProps {
26
  onNewTicket?: () => void;
27
  }
28
 
29
  export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ onNewTicket }) => {
30
- const [articles, setArticles] = useState<any[]>([]);
31
- const [categories, setCategories] = useState<string[]>([]);
32
  const [loading, setLoading] = useState(true);
33
- const [search, setSearch] = useState("");
34
- const [searchInput, setSearchInput] = useState("");
35
- const [suggestions, setSuggestions] = useState<string[]>([]);
36
- const [activeCategory, setActiveCategory] = useState<string | null>(null);
37
- const [sortBy, setSortBy] = useState<"newest" | "oldest">("newest");
38
- const [page, setPage] = useState(1);
39
- const [selectedArticle, setSelectedArticle] = useState<any | null>(null);
40
-
41
- // Pinpoint Engine State
42
  const [aiAnswer, setAiAnswer] = useState<string | null>(null);
43
  const [isAiSynthetic, setIsAiSynthetic] = useState(false);
 
 
 
 
 
 
 
 
44
 
45
- useEffect(() => {
46
- fetchCategories();
47
- }, []);
48
-
49
- useEffect(() => {
50
- const delayDebounceFn = setTimeout(() => {
51
- fetchArticles();
52
- }, search ? 400 : 0);
53
-
54
- return () => clearTimeout(delayDebounceFn);
55
- }, [search, activeCategory, sortBy]);
56
-
57
- // Reactive Search Reset
58
- useEffect(() => {
59
- if (searchInput.trim() === "") {
60
- setSearch("");
61
- setAiAnswer(null);
62
- setSuggestions([]);
63
- setIsAiSynthetic(false);
64
- }
65
- }, [searchInput]);
66
-
67
- const fetchCategories = async () => {
68
  try {
69
- const res = await api.get('kb/categories/');
70
- setCategories(res.data || []);
71
  } catch (err) {
72
- console.error("Failed to load categories:", err);
73
  }
74
- };
75
 
76
- const fetchArticles = async () => {
77
  setLoading(true);
 
 
78
  try {
79
- let res;
80
- if (search.trim().length > 1) {
81
- res = await api.get('kb/search/', { params: { q: search, category: activeCategory } });
82
- setArticles(res.data.results || []);
83
- setSuggestions(res.data.expanded_queries || []);
84
- setAiAnswer(res.data.answer || null);
85
- setIsAiSynthetic(res.data.is_ai_synthetic || false);
 
 
 
 
86
  } else {
87
- res = await api.get('kb/', { params: { category: activeCategory } });
88
- let data = res.data || [];
89
  data.sort((a: any, b: any) => {
90
  const dateA = new Date(a.created_at).getTime();
91
  const dateB = new Date(b.created_at).getTime();
92
- return sortBy === "newest" ? dateB - dateA : dateA - dateB;
93
  });
94
  setArticles(data);
95
  setSuggestions([]);
96
  setAiAnswer(null);
97
  setIsAiSynthetic(false);
 
98
  }
99
  setPage(1);
100
  } catch (err) {
101
- console.error("Failed to load KB articles:", err);
102
  } finally {
103
  setLoading(false);
 
104
  }
105
- };
 
 
 
 
 
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  const paginated = articles.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
109
  const totalPages = Math.ceil(articles.length / ITEMS_PER_PAGE);
110
 
111
  if (selectedArticle) {
112
  return (
113
- <div style={{ padding: "40px 60px", maxWidth: 900, margin: "0 auto", animation: "fadeIn 0.4s ease-out" }}>
114
- <button
115
- onClick={() => setSelectedArticle(null)}
116
- style={{
117
- background: "none", border: "none", color: COLORS.brand, fontWeight: 700,
118
- fontSize: 14, cursor: "pointer", marginBottom: 32, display: "flex", alignItems: "center", gap: 8
119
- }}
120
- >
121
  <ChevronLeft size={16} /> Back to Library
122
  </button>
123
 
124
- <div style={{ marginBottom: 40 }}>
125
- <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 16 }}>
126
- <span style={{ fontSize: 11, fontWeight: 800, color: COLORS.brand, textTransform: "uppercase", letterSpacing: "0.05em", background: COLORS.brandLight, padding: "4px 10px", borderRadius: 6 }}>
127
- {selectedArticle.category || "N/A"}
128
- </span>
129
- <span style={{ fontSize: 13, color: COLORS.gray500 }}>
130
- Published by <strong>Admin</strong> • {new Date(selectedArticle.created_at).toLocaleDateString()}
131
- </span>
132
  </div>
133
- <h1 style={{ fontSize: 42, fontWeight: 800, color: COLORS.gray900, lineHeight: 1.1, marginBottom: 24, letterSpacing: "-0.02em" }}>
134
- {selectedArticle.title}
135
- </h1>
136
- <div style={{ width: 60, height: 4, background: COLORS.brand, borderRadius: 2 }} />
137
- </div>
138
 
139
- {/* AI Insight Section (Article Detail) */}
140
  {selectedArticle.summary && (
141
- <div style={{
142
- background: "linear-gradient(135deg, #F0F7FF 0%, #F5F3FF 100%)",
143
- border: `1px solid ${COLORS.brand}15`,
144
- borderRadius: 16,
145
- padding: "24px 32px",
146
- marginBottom: 48,
147
- position: "relative",
148
- overflow: "hidden",
149
- boxShadow: "0 4px 20px rgba(30, 64, 175, 0.04)"
150
- }}>
151
- <div style={{
152
- position: "absolute", left: 0, top: 0, width: 4, height: "100%", background: COLORS.brand
153
- }} />
154
- <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 16 }}>
155
- <Sparkles size={16} color={COLORS.brand} />
156
- <span style={{ fontSize: 11, fontWeight: 900, color: COLORS.brand, letterSpacing: "0.1em", textTransform: "uppercase" }}>
157
- AI GENERATED SUMMARY
158
- </span>
159
- </div>
160
- <div style={{
161
- fontSize: 16, lineHeight: 1.7, color: COLORS.gray800, fontWeight: 500, fontStyle: "italic", margin: 0
162
- }}>
163
- <NexusMarkdown content={selectedArticle.summary} />
164
  </div>
 
165
  </div>
166
  )}
167
 
168
- <div style={{
169
- fontSize: 18, color: COLORS.gray800, lineHeight: 1.8,
170
- fontFamily: "'Inter', sans-serif", borderTop: `1px solid ${COLORS.gray100}`, paddingTop: 40,
171
- wordBreak: "break-word", overflowWrap: "anywhere"
172
- }}>
173
- <NexusMarkdown content={selectedArticle.content} />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
  </div>
175
 
176
- <div style={{ marginTop: 60, padding: 32, background: COLORS.gray50, borderRadius: 16, textAlign: "center", border: `1px dashed ${COLORS.gray300}` }}>
177
- <div style={{ fontSize: 18, fontWeight: 700, color: COLORS.gray900, marginBottom: 8 }}>Found this guide useful?</div>
178
- <div style={{ fontSize: 14, color: COLORS.gray600, marginBottom: 24 }}>If you still need assistance, our support team is available 24/7.</div>
179
  <button
180
  onClick={onNewTicket}
181
- style={{ background: COLORS.brand, color: "#fff", border: "none", padding: "12px 24px", borderRadius: 10, cursor: "pointer", fontWeight: 700, boxShadow: "0 4px 12px rgba(30,64,175,0.2)" }}
182
  >
183
  Submit a Support Ticket
184
  </button>
185
  </div>
186
- </div>
187
  );
188
  }
189
 
190
  return (
191
- <div style={{ padding: "32px 48px" }}>
192
- {/* Search Hero */}
193
- <div style={{ marginBottom: 48 }}>
194
- <h1 style={{ fontSize: 32, fontWeight: 800, color: COLORS.gray900, marginBottom: 8, letterSpacing: "-0.02em" }}>Knowledge Base</h1>
195
- <p style={{ color: COLORS.gray500, fontSize: 15, marginBottom: 32 }}>Expert guides and troubleshooting for everything Nexus.</p>
196
 
197
- <div style={{ display: "flex", gap: 20, alignItems: "center", flexWrap: "wrap" }}>
198
- <div style={{ position: "relative", flex: 1, minWidth: 320 }}>
 
199
  <input
200
- value={searchInput}
201
- onChange={e => setSearchInput(e.target.value)}
202
- onKeyDown={e => {
203
- if (e.key === 'Enter') setSearch(searchInput);
204
- }}
205
  placeholder="How can we help you today?"
206
- style={{
207
- width: "100%", padding: "16px 20px 16px 52px", borderRadius: 16, border: `1px solid ${COLORS.gray200}`,
208
- fontSize: 16, boxSizing: "border-box", outline: "none", boxShadow: "0 2px 10px rgba(0,0,0,0.03)"
209
- }}
210
  />
211
- <button
212
- onClick={() => setSearch(searchInput)}
213
- style={{
214
- position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)",
215
- background: COLORS.brand, color: "#fff", border: "none", padding: "8px 16px",
216
- borderRadius: 10, cursor: "pointer", fontSize: 13, fontWeight: 700
217
- }}
218
- >
219
- <Search size={14} style={{ display: 'inline', marginRight: 6 }} />
220
- Search
221
- </button>
222
- <Search size={20} color={COLORS.gray400} style={{ position: "absolute", left: 20, top: "50%", transform: "translateY(-50%)" }} />
223
  </div>
224
 
225
- <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
226
- <span style={{ fontSize: 11, fontWeight: 800, color: COLORS.gray400, letterSpacing: "0.05em" }}>SORT BY:</span>
227
  <select
 
 
228
  value={sortBy}
229
  onChange={e => setSortBy(e.target.value as any)}
230
- style={{ padding: "12px 16px", borderRadius: 12, border: `1px solid ${COLORS.gray200}`, background: "#fff", fontSize: 13, fontWeight: 600, color: COLORS.gray700, outline: "none", cursor: "pointer" }}
231
  >
232
  <option value="newest">Newest First</option>
233
  <option value="oldest">Oldest First</option>
234
  </select>
235
  </div>
236
- </div>
237
 
238
- {suggestions.length > 0 && (
239
- <div style={{ marginTop: 20, display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
240
- <span style={{ fontSize: 11, fontWeight: 800, color: COLORS.brand, textTransform: "uppercase", letterSpacing: "0.05em" }}>Suggestions:</span>
241
- {suggestions.map(s => (
242
- <button
243
- key={s}
244
- onClick={() => { setSearchInput(s); setSearch(s); }}
245
- style={{ padding: "6px 14px", borderRadius: 20, border: `1px solid ${COLORS.brand}22`, background: COLORS.brandLight, color: COLORS.brand, fontSize: 12, fontWeight: 600, cursor: "pointer" }}
246
- >
247
- {s}
248
- </button>
249
- ))}
250
- </div>
251
- )}
252
- </div>
 
 
 
 
 
 
 
 
253
 
254
- {/* Category Toolbar */}
255
- <div style={{ display: "flex", gap: 12, marginBottom: 40, borderBottom: `1px solid ${COLORS.gray100}`, paddingBottom: 16, overflowX: "auto" }}>
256
- <button
257
- onClick={() => setActiveCategory(null)}
258
- style={{ padding: "8px 0", border: "none", background: "none", color: !activeCategory ? COLORS.brand : COLORS.gray500, fontSize: 14, fontWeight: 700, cursor: "pointer", borderBottom: !activeCategory ? `2px solid ${COLORS.brand}` : "none", marginRight: 24 }}
259
- >
260
- All Documentation
261
- </button>
262
  {categories.map(cat => (
263
  <button
264
  key={cat}
265
- onClick={() => setActiveCategory(activeCategory === cat ? null : cat)}
266
- style={{ padding: "8px 0", border: "none", background: "none", color: activeCategory === cat ? COLORS.brand : COLORS.gray500, fontSize: 14, fontWeight: 600, cursor: "pointer", borderBottom: activeCategory === cat ? `2px solid ${COLORS.brand}` : "none", marginRight: 24, whiteSpace: "nowrap" }}
267
  >
268
  {cat}
269
  </button>
270
  ))}
271
- </div>
272
 
273
- {/* AI Spotlight Section (Search Results) */}
274
- {aiAnswer && (
275
- <div style={{
276
- maxWidth: 1100, margin: "0 auto 48px",
277
- background: "white",
278
- border: `1px solid ${COLORS.gray200}`,
279
- borderRadius: 20,
280
- padding: 40,
281
- position: "relative",
282
- boxShadow: "0 4px 20px rgba(0,0,0,0.02)"
283
- }}>
284
- <div style={{ position: "absolute", top: 0, left: 0, width: "100%", height: 3, background: COLORS.brand, borderRadius: "20px 20px 0 0" }} />
285
- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24 }}>
286
- <div style={{ display: "flex", alignItems: "center", gap: 10, background: COLORS.brandLight, padding: "6px 14px", borderRadius: 8 }}>
287
- <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
288
- <Sparkles size={16} color={COLORS.brand} />
289
- <span style={{ fontSize: 11, fontWeight: 900, color: COLORS.brand, letterSpacing: "0.1em", textTransform: "uppercase" }}>
290
- AI DIRECT ANSWER
291
- </span>
292
  </div>
293
- </div>
294
- {isAiSynthetic && (
295
- <span style={{ fontSize: 10, fontWeight: 800, color: "#16A34A", background: "#F0FDF4", padding: "4px 8px", borderRadius: 4 }}>
296
- REAL-TIME SYNTHESIS
297
- </span>
298
- )}
299
- </div>
300
- <div style={{ fontSize: 18, lineHeight: 1.8, color: COLORS.gray900, fontWeight: 600, fontStyle: "italic", margin: 0 }}>
301
- <NexusMarkdown content={aiAnswer} />
302
- </div>
303
- <div style={{ marginTop: 24, paddingTop: 20, borderTop: `1px solid ${COLORS.gray100}`, fontSize: 11, fontWeight: 700, color: COLORS.gray400, textTransform: "uppercase", letterSpacing: "0.1em" }}>
304
- Reference guides found below
305
- </div>
306
- </div>
307
- )}
308
 
309
- {/* Article Feed */}
310
- <div style={{ maxWidth: 1100, margin: "0 auto" }}>
311
- {loading ? (
312
- <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(440px, 1fr))", gap: 32 }}>
313
  {[1, 2, 3, 4].map(i => (
314
- <div key={i} style={{ background: "#fff", border: `1px solid ${COLORS.gray100}`, borderRadius: 20, padding: 32 }}>
315
- <Skeleton width="30%" height={12} marginBottom={16} />
316
- <Skeleton width="80%" height={24} marginBottom={12} />
317
- <Skeleton width="100%" height={16} marginBottom={8} />
318
- <Skeleton width="100%" height={16} marginBottom={8} />
319
- <Skeleton width="60%" height={16} marginBottom={24} />
320
- <div style={{ display: "flex", justifyContent: "space-between", borderTop: `1px solid ${COLORS.gray50}`, paddingTop: 24 }}>
321
- <Skeleton width="40%" height={12} />
322
- <Skeleton width="20%" height={12} />
323
- </div>
324
  </div>
325
  ))}
326
  </div>
327
  ) : articles.length === 0 ? (
328
- <div style={{ padding: "100px 0", textAlign: "center" }}>
 
 
 
 
329
  <div style={{ fontSize: 48, marginBottom: 20 }}>🔍</div>
330
- <h3 style={{ fontSize: 20, fontWeight: 700, color: COLORS.gray900, marginBottom: 8 }}>We couldn't find that</h3>
331
- <p style={{ color: COLORS.gray500, fontSize: 14 }}>Try searching for broader terms or check a different category.</p>
332
- </div>
 
 
 
 
333
  ) : (
334
  <>
335
- <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(440px, 1fr))", gap: 32 }}>
336
- {paginated.map(article => (
337
- <div
 
 
 
 
338
  key={article.id}
 
 
 
 
339
  onClick={() => setSelectedArticle(article)}
340
- style={{ cursor: "pointer", display: "flex" }}
341
  >
342
- <div style={{
343
- background: "#fff", border: `1px solid ${COLORS.gray100}`, borderRadius: 20, padding: 32, transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
344
- boxShadow: "0 2px 4px rgba(0,0,0,0.02)", display: "flex", flexDirection: "column", flex: 1, height: "100%"
345
- }}
346
- onMouseEnter={e => {
347
- e.currentTarget.style.transform = "translateY(-4px)";
348
- e.currentTarget.style.boxShadow = "0 20px 25px -5px rgba(0, 0, 0, 0.05), 0 10px 10px -5px rgba(0, 0, 0, 0.04)";
349
- e.currentTarget.style.borderColor = COLORS.brand;
350
- }}
351
- onMouseLeave={e => {
352
- e.currentTarget.style.transform = "none";
353
- e.currentTarget.style.boxShadow = "0 2px 4px rgba(0,0,0,0.02)";
354
- e.currentTarget.style.borderColor = COLORS.gray100;
355
- }}
356
- >
357
- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
358
- <span style={{ fontSize: 10, fontWeight: 800, color: COLORS.brand, textTransform: "uppercase", letterSpacing: "0.1em" }}>{article.category || "N/A"}</span>
359
- {article.score && (
360
- <span style={{ fontSize: 10, fontWeight: 800, color: article.score > 80 ? COLORS.success : COLORS.brand, background: article.score > 80 ? "#F0FDF4" : COLORS.brandLight, padding: "2px 8px", borderRadius: 4 }}>
361
- {article.score.toFixed(0)}% MATCH
362
- </span>
363
- )}
364
- </div>
365
- <h3 style={{ fontSize: 22, fontWeight: 800, color: COLORS.gray900, marginBottom: 12, lineHeight: 1.2, wordBreak: "break-word", overflowWrap: "anywhere" }}>{article.title}</h3>
366
- <p style={{
367
- fontSize: 15, color: COLORS.gray600, lineHeight: 1.6, marginBottom: 24,
368
- display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden",
369
- wordBreak: "break-word", overflowWrap: "anywhere"
370
- }}>
371
- {article.snippet ? (
372
- <span><strong style={{ color: COLORS.brand, fontSize: 11, marginRight: 6 }}>[MATCH]</strong> {article.snippet}</span>
373
- ) : article.summary ? (
374
- <span><Sparkles size={12} style={{ display: "inline", marginRight: 6, verticalAlign: "middle" }} color={COLORS.brand} /> {article.summary}</span>
375
- ) : article.content.replace(/[#*`]/g, '').slice(0, 180)}...
376
- </p>
377
- <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: `1px solid ${COLORS.gray50}`, paddingTop: 24, marginTop: "auto" }}>
378
- <span style={{ fontSize: 12, color: COLORS.gray400, fontWeight: 500 }}>Published {new Date(article.created_at).toLocaleDateString()}</span>
379
- <span style={{ fontSize: 13, fontWeight: 700, color: COLORS.brand }}>Read Guide →</span>
380
- </div>
381
  </div>
382
- </div>
 
 
 
 
 
 
 
 
 
 
383
  ))}
384
- </div>
385
 
386
  {totalPages > 1 && (
387
- <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: 24, marginTop: 60 }}>
388
  <button
389
  disabled={page === 1}
390
  onClick={() => setPage(p => p - 1)}
391
- style={{ padding: "10px 24px", borderRadius: 12, border: `1px solid ${COLORS.gray200}`, background: "#fff", fontWeight: 700, fontSize: 14, color: page === 1 ? COLORS.gray300 : COLORS.gray900, cursor: page === 1 ? "default" : "pointer" }}
 
392
  >
393
  <ChevronLeft size={16} />
394
  </button>
395
- <div style={{ fontSize: 14, fontWeight: 600, color: COLORS.gray600 }}>Page {page} of {totalPages}</div>
396
  <button
397
  disabled={page === totalPages}
398
  onClick={() => setPage(p => p + 1)}
399
- style={{ padding: "10px 24px", borderRadius: 12, border: `1px solid ${COLORS.gray200}`, background: "#fff", fontWeight: 700, fontSize: 14, color: page === totalPages ? COLORS.gray300 : COLORS.gray900, cursor: page === totalPages ? "default" : "pointer" }}
 
400
  >
401
  <ChevronRight size={16} />
402
  </button>
 
1
+ import React, { useState, useEffect, useCallback, useRef } from 'react';
2
+ import ReactMarkdown from 'react-markdown';
3
+ import remarkGfm from 'remark-gfm';
4
+ import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
5
+ import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
6
+ import { motion, AnimatePresence } from 'framer-motion';
7
+ import { Search, ChevronLeft, ChevronRight, Sparkles, Zap, Info, Radio, Clock, User as UserIcon } from 'lucide-react';
8
+ import { api } from '@nexus/shared';
9
+ import mermaid from 'mermaid';
10
+ import styles from './KnowledgeBase.module.css';
11
 
12
+ // Initialize Mermaid
13
+ mermaid.initialize({
14
+ startOnLoad: true,
15
+ theme: 'dark',
16
+ securityLevel: 'loose',
17
+ });
18
+
19
+ // Mermaid Component
20
+ const Mermaid: React.FC<{ chart: string }> = ({ chart }) => {
21
+ const ref = useRef<HTMLDivElement>(null);
22
+
23
+ useEffect(() => {
24
+ if (ref.current && chart) {
25
+ const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`;
26
+ mermaid.render(id, chart).then((res) => {
27
+ if (ref.current) ref.current.innerHTML = res.svg;
28
+ }).catch(err => {
29
+ console.error("Mermaid render failed:", err);
30
+ });
31
+ }
32
+ }, [chart]);
33
+
34
+ return <div ref={ref} className={styles.mermaidContainer} />;
35
  };
36
 
37
+ interface Article {
38
+ id: string;
39
+ title: string;
40
+ content: string;
41
+ category: string;
42
+ author_id: string;
43
+ is_published: boolean;
44
+ created_at: string;
45
+ updated_at: string;
46
+ summary?: string;
47
+ score?: number;
48
+ match_type?: string;
49
+ snippet?: string;
50
+ }
51
 
52
  interface KnowledgeBaseProps {
53
  onNewTicket?: () => void;
54
  }
55
 
56
  export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ onNewTicket }) => {
57
+ const [articles, setArticles] = useState<Article[]>([]);
58
+ const [categories, setCategories] = useState<string[]>(['All Documentation']);
59
  const [loading, setLoading] = useState(true);
60
+ const [isScanning, setIsScanning] = useState(false);
61
+
62
+ // Search State
63
+ const [searchInput, setSearchInput] = useState('');
64
+ const [activeQuery, setActiveQuery] = useState('');
65
+ const [selectedCategory, setSelectedCategory] = useState('All Documentation');
66
+
67
+ // AI Direct Answer State
 
68
  const [aiAnswer, setAiAnswer] = useState<string | null>(null);
69
  const [isAiSynthetic, setIsAiSynthetic] = useState(false);
70
+ const [suggestions, setSuggestions] = useState<string[]>([]);
71
+ const [aiSuggestion, setAiSuggestion] = useState<string | null>(null);
72
+
73
+ // UI State
74
+ const [page, setPage] = useState(1);
75
+ const ITEMS_PER_PAGE = 4;
76
+ const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);
77
+ const [sortBy, setSortBy] = useState<'newest' | 'oldest'>('newest');
78
 
79
+ const fetchCategories = useCallback(async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  try {
81
+ const resp = await api.get('kb/categories/');
82
+ setCategories(['All Documentation', ...resp.data]);
83
  } catch (err) {
84
+ console.error('Failed to fetch categories:', err);
85
  }
86
+ }, []);
87
 
88
+ const fetchArticles = useCallback(async (query: string = '', cat: string = 'All Documentation') => {
89
  setLoading(true);
90
+ if (query.length > 0) setIsScanning(true);
91
+
92
  try {
93
+ const params: any = {};
94
+ if (cat !== 'All Documentation') params.category = cat;
95
+
96
+ if (query.trim().length > 0) {
97
+ params.q = query;
98
+ const resp = await api.get('kb/search/', { params });
99
+ setArticles(resp.data.results || []);
100
+ setSuggestions(resp.data.expanded_queries || []);
101
+ setAiSuggestion(resp.data.suggestion || null);
102
+ setAiAnswer(resp.data.answer || null);
103
+ setIsAiSynthetic(resp.data.is_ai_synthetic || false);
104
  } else {
105
+ const resp = await api.get('kb/', { params });
106
+ let data = resp.data || [];
107
  data.sort((a: any, b: any) => {
108
  const dateA = new Date(a.created_at).getTime();
109
  const dateB = new Date(b.created_at).getTime();
110
+ return sortBy === 'newest' ? dateB - dateA : dateA - dateB;
111
  });
112
  setArticles(data);
113
  setSuggestions([]);
114
  setAiAnswer(null);
115
  setIsAiSynthetic(false);
116
+ setAiSuggestion(null);
117
  }
118
  setPage(1);
119
  } catch (err) {
120
+ console.error('Failed to fetch articles:', err);
121
  } finally {
122
  setLoading(false);
123
+ setIsScanning(false);
124
  }
125
+ }, [sortBy]);
126
+
127
+ useEffect(() => {
128
+ fetchCategories();
129
+ fetchArticles('', 'All Documentation');
130
+ }, [fetchCategories, fetchArticles]);
131
 
132
+ // Reactive Search Reset
133
+ useEffect(() => {
134
+ if (searchInput.trim() === '') {
135
+ setActiveQuery('');
136
+ if (articles.length > 0 && activeQuery !== '') {
137
+ fetchArticles('', selectedCategory);
138
+ }
139
+ }
140
+ }, [searchInput, selectedCategory, fetchArticles]);
141
+
142
+ const handleSearchTrigger = (e?: React.FormEvent) => {
143
+ if (e) e.preventDefault();
144
+ setActiveQuery(searchInput);
145
+ fetchArticles(searchInput, selectedCategory);
146
+ };
147
 
148
  const paginated = articles.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE);
149
  const totalPages = Math.ceil(articles.length / ITEMS_PER_PAGE);
150
 
151
  if (selectedArticle) {
152
  return (
153
+ <motion.div
154
+ className={styles.articleDetail}
155
+ initial={{ opacity: 0, y: 10 }}
156
+ animate={{ opacity: 1, y: 0 }}
157
+ >
158
+ <button className={styles.backBtn} onClick={() => setSelectedArticle(null)}>
 
 
159
  <ChevronLeft size={16} /> Back to Library
160
  </button>
161
 
162
+ <header style={{ marginBottom: 40 }}>
163
+ <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 16 }}>
164
+ <span className={styles.categoryBadge}>{selectedArticle.category || 'General'}</span>
165
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: '#6B7280', fontSize: 13 }}>
166
+ <UserIcon size={14} /> <span>Admin</span>
167
+ <Clock size={14} style={{ marginLeft: 8 }} />
168
+ <span>{new Date(selectedArticle.created_at).toLocaleDateString()}</span>
169
+ </div>
170
  </div>
171
+ <h1 className={styles.articleTitle} style={{ fontSize: 42 }}>{selectedArticle.title}</h1>
172
+ <div style={{ width: 60, height: 4, background: '#1E40AF', borderRadius: 2, marginTop: 24 }} />
173
+ </header>
 
 
174
 
 
175
  {selectedArticle.summary && (
176
+ <div className={styles.aiSpotlight} style={{ margin: '0 0 48px 0', padding: '24px 32px' }}>
177
+ <div className={styles.spotlightHeader} style={{ marginBottom: 16 }}>
178
+ <div className={styles.spotlightBadge}>
179
+ <Sparkles size={14} /> AI GENERATED SUMMARY
180
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  </div>
182
+ <p className={styles.answerText} style={{ fontSize: 16 }}>{selectedArticle.summary}</p>
183
  </div>
184
  )}
185
 
186
+ <div className={styles.markdownContent}>
187
+ <ReactMarkdown
188
+ remarkPlugins={[remarkGfm]}
189
+ components={{
190
+ code({node, inline, className, children, ...props}: any) {
191
+ const match = /language-(\w+)/.exec(className || '');
192
+ if (!inline && match && match[1] === 'mermaid') {
193
+ return <Mermaid chart={String(children)} />;
194
+ }
195
+ return !inline && match ? (
196
+ <SyntaxHighlighter
197
+ style={vscDarkPlus}
198
+ language={match[1]}
199
+ PreTag="div"
200
+ {...props}
201
+ >
202
+ {String(children).replace(/\n$/, '')}
203
+ </SyntaxHighlighter>
204
+ ) : (
205
+ <code className={className} {...props}>
206
+ {children}
207
+ </code>
208
+ );
209
+ }
210
+ }}
211
+ >
212
+ {selectedArticle.content}
213
+ </ReactMarkdown>
214
  </div>
215
 
216
+ <div style={{ marginTop: 60, padding: 32, background: '#F9FAFB', borderRadius: 16, textAlign: 'center', border: '1px dashed #D1D5DB' }}>
217
+ <h3 style={{ fontSize: 18, fontWeight: 700, color: '#111827', marginBottom: 8 }}>Found this guide useful?</h3>
218
+ <p style={{ fontSize: 14, color: '#4B5563', marginBottom: 24 }}>If you still need assistance, our support team is available 24/7.</p>
219
  <button
220
  onClick={onNewTicket}
221
+ style={{ background: '#1E40AF', color: '#fff', border: 'none', padding: '12px 24px', borderRadius: 10, cursor: 'pointer', fontWeight: 700, boxShadow: '0 4px 12px rgba(30,64,175,0.2)' }}
222
  >
223
  Submit a Support Ticket
224
  </button>
225
  </div>
226
+ </motion.div>
227
  );
228
  }
229
 
230
  return (
231
+ <div className={styles.container}>
232
+ <header className={styles.searchHero}>
233
+ <h1>Knowledge Base</h1>
234
+ <p className={styles.description}>Expert guides and troubleshooting for everything Nexus.</p>
 
235
 
236
+ <form className={styles.searchControls} onSubmit={handleSearchTrigger}>
237
+ <div className={styles.searchWrapper}>
238
+ <Search className={styles.searchIcon} size={20} />
239
  <input
240
+ type="text"
241
+ className={styles.searchInput}
 
 
 
242
  placeholder="How can we help you today?"
243
+ value={searchInput}
244
+ onChange={(e) => setSearchInput(e.target.value)}
 
 
245
  />
246
+ {isScanning && (
247
+ <div className={styles.searchPulse}>
248
+ <Radio size={14} className={styles.pulseIcon} />
249
+ <span>NEURAL SCANNING</span>
250
+ </div>
251
+ )}
252
+ <button type="submit" className={styles.searchBtn}>Search</button>
 
 
 
 
 
253
  </div>
254
 
255
+ <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
256
+ <span style={{ fontSize: 11, fontWeight: 800, color: '#9CA3AF', letterSpacing: '0.05em' }}>SORT BY:</span>
257
  <select
258
+ className={styles.navItem}
259
+ style={{ padding: '8px 12px', background: '#fff', border: '1px solid #E5E7EB', borderRadius: 8, marginRight: 0 }}
260
  value={sortBy}
261
  onChange={e => setSortBy(e.target.value as any)}
 
262
  >
263
  <option value="newest">Newest First</option>
264
  <option value="oldest">Oldest First</option>
265
  </select>
266
  </div>
267
+ </form>
268
 
269
+ <AnimatePresence>
270
+ {suggestions.length > 0 && (
271
+ <motion.div
272
+ className={styles.suggestions}
273
+ initial={{ opacity: 0, y: -10 }}
274
+ animate={{ opacity: 1, y: 0 }}
275
+ style={{ marginTop: 24, display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}
276
+ >
277
+ <span className={styles.categoryBadge}>Suggestions:</span>
278
+ {suggestions.map(s => (
279
+ <button
280
+ key={s}
281
+ onClick={() => { setSearchInput(s); fetchArticles(s, selectedCategory); }}
282
+ className={styles.regularMatch}
283
+ style={{ padding: '6px 14px', borderRadius: 20, border: '1px solid #1E40AF22', fontSize: 12, fontWeight: 600, cursor: 'pointer' }}
284
+ >
285
+ {s}
286
+ </button>
287
+ ))}
288
+ </motion.div>
289
+ )}
290
+ </AnimatePresence>
291
+ </header>
292
 
293
+ <nav className={styles.categoryNav}>
 
 
 
 
 
 
 
294
  {categories.map(cat => (
295
  <button
296
  key={cat}
297
+ className={`${styles.navItem} ${selectedCategory === cat ? styles.navItemActive : ''}`}
298
+ onClick={() => { setSelectedCategory(cat); fetchArticles(activeQuery, cat); }}
299
  >
300
  {cat}
301
  </button>
302
  ))}
303
+ </nav>
304
 
305
+ <div className={styles.resultsContainer}>
306
+ <AnimatePresence mode="wait">
307
+ {aiAnswer && (
308
+ <motion.div
309
+ className={styles.aiSpotlight}
310
+ initial={{ opacity: 0, y: 20 }}
311
+ animate={{ opacity: 1, y: 0 }}
312
+ exit={{ opacity: 0, scale: 0.95 }}
313
+ >
314
+ <div className={styles.spotlightHeader}>
315
+ <div className={styles.spotlightBadge}>
316
+ <Sparkles size={14} /> AI DIRECT ANSWER
 
 
 
 
 
 
 
317
  </div>
318
+ {isAiSynthetic && <span className={styles.syntheticFlag}>REAL-TIME SYNTHESIS</span>}
319
+ </div>
320
+ <p className={styles.answerText}>{aiAnswer}</p>
321
+ <div className={styles.spotlightFooter}>Based on the documentation below.</div>
322
+ </motion.div>
323
+ )}
324
+ </AnimatePresence>
 
 
 
 
 
 
 
 
325
 
326
+ {loading && articles.length === 0 ? (
327
+ <div className={styles.articlesGrid}>
 
 
328
  {[1, 2, 3, 4].map(i => (
329
+ <div key={i} className={styles.articleCard} style={{ opacity: 0.5 }}>
330
+ <div style={{ height: 12, width: '30%', background: '#F3F4F6', borderRadius: 4, marginBottom: 16 }} />
331
+ <div style={{ height: 24, width: '80%', background: '#F3F4F6', borderRadius: 4, marginBottom: 12 }} />
332
+ <div style={{ height: 16, width: '100%', background: '#F3F4F6', borderRadius: 4, marginBottom: 8 }} />
333
+ <div style={{ height: 16, width: '60%', background: '#F3F4F6', borderRadius: 4, marginBottom: 24 }} />
 
 
 
 
 
334
  </div>
335
  ))}
336
  </div>
337
  ) : articles.length === 0 ? (
338
+ <motion.div
339
+ initial={{ opacity: 0 }}
340
+ animate={{ opacity: 1 }}
341
+ style={{ padding: '100px 0', textAlign: 'center' }}
342
+ >
343
  <div style={{ fontSize: 48, marginBottom: 20 }}>🔍</div>
344
+ <h3 style={{ fontSize: 20, fontWeight: 700, color: '#111827', marginBottom: 8 }}>We couldn't find that</h3>
345
+ {aiSuggestion && (
346
+ <div style={{ marginTop: 16, color: '#6B7280' }}>
347
+ Did you mean: <button onClick={() => { setSearchInput(aiSuggestion); fetchArticles(aiSuggestion, selectedCategory); }} style={{ color: '#1E40AF', fontWeight: 700, background: 'none', border: 'none', cursor: 'pointer' }}>{aiSuggestion}</button>?
348
+ </div>
349
+ )}
350
+ </motion.div>
351
  ) : (
352
  <>
353
+ <motion.div
354
+ className={styles.articlesGrid}
355
+ initial={{ opacity: 0 }}
356
+ animate={{ opacity: 1 }}
357
+ >
358
+ {paginated.map((article, i) => (
359
+ <motion.div
360
  key={article.id}
361
+ className={styles.articleCard}
362
+ initial={{ opacity: 0, y: 20 }}
363
+ animate={{ opacity: 1, y: 0 }}
364
+ transition={{ delay: i * 0.05 }}
365
  onClick={() => setSelectedArticle(article)}
 
366
  >
367
+ <div className={styles.cardHeader}>
368
+ <span className={styles.categoryBadge}>{article.category || 'General'}</span>
369
+ {article.score && (
370
+ <span className={`${styles.matchBadge} ${article.score > 80 ? styles.highMatch : styles.regularMatch}`}>
371
+ {Math.round(article.score)}% MATCH
372
+ </span>
373
+ )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  </div>
375
+ <h3 className={styles.articleTitle}>{article.title}</h3>
376
+ <p className={styles.articleSnippet}>
377
+ {article.snippet ? (
378
+ <span><strong style={{ color: '#1E40AF', fontSize: 11, marginRight: 6 }}>[MATCH]</strong> {article.snippet}</span>
379
+ ) : article.summary || article.content.replace(/[#*`]/g, '').slice(0, 160) + '...'}
380
+ </p>
381
+ <div className={styles.cardFooter}>
382
+ <span className={styles.articleDate}>Published {new Date(article.created_at).toLocaleDateString()}</span>
383
+ <span className={styles.readMore}>Read Guide →</span>
384
+ </div>
385
+ </motion.div>
386
  ))}
387
+ </motion.div>
388
 
389
  {totalPages > 1 && (
390
+ <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 24, marginTop: 60 }}>
391
  <button
392
  disabled={page === 1}
393
  onClick={() => setPage(p => p - 1)}
394
+ className={styles.navItem}
395
+ style={{ border: '1px solid #E5E7EB', borderRadius: 12, padding: '10px 24px', opacity: page === 1 ? 0.3 : 1 }}
396
  >
397
  <ChevronLeft size={16} />
398
  </button>
399
+ <div style={{ fontSize: 14, fontWeight: 600, color: '#6B7280' }}>Page {page} of {totalPages}</div>
400
  <button
401
  disabled={page === totalPages}
402
  onClick={() => setPage(p => p + 1)}
403
+ className={styles.navItem}
404
+ style={{ border: '1px solid #E5E7EB', borderRadius: 12, padding: '10px 24px', opacity: page === totalPages ? 0.3 : 1 }}
405
  >
406
  <ChevronRight size={16} />
407
  </button>
frontend/apps/internal/vite.config.ts CHANGED
@@ -5,6 +5,7 @@ import tsconfigPaths from 'vite-tsconfig-paths'
5
  // https://vite.dev/config/
6
  export default defineConfig({
7
  plugins: [react(), tsconfigPaths()],
 
8
  server: {
9
  port: 5174
10
  }
 
5
  // https://vite.dev/config/
6
  export default defineConfig({
7
  plugins: [react(), tsconfigPaths()],
8
+ base: '/admin/',
9
  server: {
10
  port: 5174
11
  }
frontend/packages/shared/src/hooks/useDashboard.ts CHANGED
@@ -35,6 +35,11 @@ export interface DailyStat {
35
  categories: Record<string, number>;
36
  }
37
 
 
 
 
 
 
38
  // Global singleton state for dashboard stats to ensure UI consistency
39
  let globalStats: DashboardStats | null = null;
40
  let globalStatsLoading = false;
@@ -109,7 +114,8 @@ let globalReports: {
109
  volume: VolumeTrend | null;
110
  daily: DailyStat[];
111
  sla: SLAMetrics | null;
112
- } = { volume: null, daily: [], sla: null };
 
113
  let globalReportsLoading = false;
114
  let globalReportsError: string | null = null;
115
  const reportsListeners = new Set<(r: typeof globalReports, l: boolean, e: string | null) => void>();
@@ -144,22 +150,27 @@ export const useReports = (workspaceId?: string) => {
144
  let slaUrl = workspaceId ? `reports/sla/?workspace_id=${workspaceId}` : 'reports/sla/';
145
  let dailyUrl = workspaceId ? `reports/daily-stats/?workspace_id=${workspaceId}` : 'reports/daily-stats/';
146
 
 
 
147
  if (force) {
148
  const flag = (u: string) => u + (u.includes('?') ? '&' : '?') + 'refresh=true';
149
  volUrl = flag(volUrl);
150
  slaUrl = flag(slaUrl);
151
  dailyUrl = flag(dailyUrl);
 
152
  }
153
 
154
- const [volRes, slaRes, dRes] = await Promise.all([
155
  api.get(volUrl),
156
  api.get(slaUrl),
157
- api.get(dailyUrl)
 
158
  ]);
159
  globalReports = {
160
  volume: volRes.data,
161
  sla: slaRes.data,
162
- daily: dRes.data
 
163
  };
164
  globalReportsError = null;
165
  } catch (err: any) {
 
35
  categories: Record<string, number>;
36
  }
37
 
38
+ export interface CSATMetrics {
39
+ average_rating: number;
40
+ total_responses: number;
41
+ }
42
+
43
  // Global singleton state for dashboard stats to ensure UI consistency
44
  let globalStats: DashboardStats | null = null;
45
  let globalStatsLoading = false;
 
114
  volume: VolumeTrend | null;
115
  daily: DailyStat[];
116
  sla: SLAMetrics | null;
117
+ csat: CSATMetrics | null;
118
+ } = { volume: null, daily: [], sla: null, csat: null };
119
  let globalReportsLoading = false;
120
  let globalReportsError: string | null = null;
121
  const reportsListeners = new Set<(r: typeof globalReports, l: boolean, e: string | null) => void>();
 
150
  let slaUrl = workspaceId ? `reports/sla/?workspace_id=${workspaceId}` : 'reports/sla/';
151
  let dailyUrl = workspaceId ? `reports/daily-stats/?workspace_id=${workspaceId}` : 'reports/daily-stats/';
152
 
153
+ let csatUrl = workspaceId ? `reports/csat/?workspace_id=${workspaceId}` : 'reports/csat/';
154
+
155
  if (force) {
156
  const flag = (u: string) => u + (u.includes('?') ? '&' : '?') + 'refresh=true';
157
  volUrl = flag(volUrl);
158
  slaUrl = flag(slaUrl);
159
  dailyUrl = flag(dailyUrl);
160
+ csatUrl = flag(csatUrl);
161
  }
162
 
163
+ const [volRes, slaRes, dRes, csatRes] = await Promise.all([
164
  api.get(volUrl),
165
  api.get(slaUrl),
166
+ api.get(dailyUrl),
167
+ api.get(csatUrl)
168
  ]);
169
  globalReports = {
170
  volume: volRes.data,
171
  sla: slaRes.data,
172
+ daily: dRes.data,
173
+ csat: csatRes.data
174
  };
175
  globalReportsError = null;
176
  } catch (err: any) {
frontend/packages/shared/src/utils/api.ts CHANGED
@@ -1,16 +1,16 @@
1
  import axios from 'axios';
2
 
3
- const rawBaseUrl = import.meta.env.VITE_API_URL || 'http://localhost:8000/api/v1';
 
4
 
5
  // Intelligent URL Normalization:
6
- // 1. Ensure it starts with http/https
7
- // 2. Ensure it includes the /api/v1 suffix if missing
8
- // 3. Ensure it DOES NOT have a double slash
9
  let sanitizedBaseUrl = rawBaseUrl.trim();
10
 
11
- // Special Case: Tunnel URL usually arrives without /api/v1
12
- if (!sanitizedBaseUrl.includes('/api/')) {
13
- sanitizedBaseUrl = sanitizedBaseUrl.endsWith('/') ? `${sanitizedBaseUrl}api/v1` : `${sanitizedBaseUrl}/api/v1`;
 
 
14
  }
15
 
16
  // Final trailing slash for clean joins
 
1
  import axios from 'axios';
2
 
3
+ const rawBaseUrl = import.meta.env.VITE_API_URL ||
4
+ (import.meta.env.DEV ? 'http://localhost:8000/api/v1' : '/api/v1');
5
 
6
  // Intelligent URL Normalization:
 
 
 
7
  let sanitizedBaseUrl = rawBaseUrl.trim();
8
 
9
+ // Ensure absolute URLs have a protocol and /api/v1 suffix
10
+ if (sanitizedBaseUrl.startsWith('http')) {
11
+ if (!sanitizedBaseUrl.includes('/api/')) {
12
+ sanitizedBaseUrl = sanitizedBaseUrl.endsWith('/') ? `${sanitizedBaseUrl}api/v1` : `${sanitizedBaseUrl}/api/v1`;
13
+ }
14
  }
15
 
16
  // Final trailing slash for clean joins
main.py CHANGED
@@ -152,7 +152,17 @@ app.include_router(escalations.router, prefix=f"{settings.API_V1_STR}/escalation
152
  app.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"])
153
  app.include_router(nexus.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])
154
  app.include_router(nexus_stream.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])
155
- app.include_router(system.router, prefix=f"{settings.API_V1_STR}/system", tags=["System Diagnostics"])
156
- app.include_router(websockets.router, tags=["websockets"])
 
 
 
 
 
 
 
 
 
 
157
 
158
 
 
152
  app.include_router(reports.router, prefix=f"{settings.API_V1_STR}/reports", tags=["reports"])
153
  app.include_router(nexus.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])
154
  app.include_router(nexus_stream.router, prefix=f"{settings.API_V1_STR}/nexus", tags=["Nexus Master Agent"])
155
+ import os
156
+ from fastapi.staticfiles import StaticFiles
157
+
158
+ # --- UNIFIED PORTAL HOSTING ---
159
+ # Serve Customer Portal at / and Internal Portal at /admin
160
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
161
+ FRONTEND_CUSTOMER_PATH = os.path.join(BASE_DIR, "frontend/apps/customer/dist")
162
+ FRONTEND_INTERNAL_PATH = os.path.join(BASE_DIR, "frontend/apps/internal/dist")
163
+
164
+ # Note: Mounting Internal BEFORE Customer to avoid catch-all collisions
165
+ app.mount("/admin", StaticFiles(directory=FRONTEND_INTERNAL_PATH, html=True), name="internal")
166
+ app.mount("/", StaticFiles(directory=FRONTEND_CUSTOMER_PATH, html=True), name="customer")
167
 
168
 
scripts/run_prod.sh CHANGED
@@ -5,6 +5,10 @@
5
 
6
  echo "--- NEXUS PRODUCTION BOOTSTRAP ---"
7
 
 
 
 
 
8
  # Start Arq Worker in the background
9
  echo "[1/2] Starting Nexus AI Worker (arq)..."
10
  # Persistence Mapping: Use the /data mount if available
 
5
 
6
  echo "--- NEXUS PRODUCTION BOOTSTRAP ---"
7
 
8
+ # Start Local Redis for Caching (Ephemeral)
9
+ echo "[0/3] Starting Local Redis..."
10
+ redis-server --daemonize yes --port 6379
11
+
12
  # Start Arq Worker in the background
13
  echo "[1/2] Starting Nexus AI Worker (arq)..."
14
  # Persistence Mapping: Use the /data mount if available