Spaces:
Paused

File size: 15,509 Bytes
ad4fe35
5eb4857
ad4fe35
d02993d
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da377dd
 
5eb4857
 
 
 
 
 
 
 
5df0bfe
ad4fe35
5eb4857
 
 
 
 
ad4fe35
 
5eb4857
 
 
 
 
 
 
 
 
ad4fe35
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad4fe35
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
ad4fe35
 
5eb4857
 
ad4fe35
5eb4857
 
 
ad4fe35
 
5eb4857
 
ad4fe35
 
5eb4857
 
 
 
ad4fe35
 
5eb4857
 
ad4fe35
5eb4857
 
 
5df0bfe
 
5eb4857
 
5df0bfe
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad4fe35
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad4fe35
5eb4857
 
 
ad4fe35
5eb4857
 
 
ad4fe35
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
ad4fe35
5eb4857
 
 
 
 
 
 
 
 
ad4fe35
d02993d
 
 
 
 
 
5eb4857
ad4fe35
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad4fe35
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import React, { useState } from 'react';
import { StatusBadge, PriorityBadge } from './Badges';
import { useReports, useServiceNarrative, NexusMarkdown } from '@nexus/shared';
import { Skeleton } from './Skeleton';

const COLORS = {
  brand: "#1E40AF",
  brandLight: "rgba(30, 64, 175, 0.1)",
  gray50: "#F9FAFB",
  gray100: "#F3F4F6",
  gray200: "#E5E7EB",
  gray400: "#9CA3AF",
  gray500: "#6B7280",
  gray700: "#374151",
  gray800: "#1F2937",
  gray900: "#111827",
};

interface AnalyticsProps {
  tickets: any[];
}

const Sparkline: React.FC<{ data: number[], color: string }> = ({ data, color }) => {
  if (!data || data.length === 0) return null;
  const max = Math.max(...data, 1);
  const width = 100;
  const height = 30;
  const divisor = data.length > 1 ? data.length - 1 : 1;
  const points = data.map((v, i) => `${(i / divisor) * width},${height - (v / max) * height}`).join(' ');
  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} style={{ overflow: 'visible' }}>
      <polyline fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" points={points} />
    </svg>
  );
};

export const Analytics: React.FC<AnalyticsProps> = ({ tickets }) => {
  const { volume, sla, csat, loading: reportsLoading, refresh: refreshReports } = useReports();
  const { narrative, loading: narrativeLoading, refresh: refreshNarrative } = useServiceNarrative();
  const [isResummarizing, setIsResummarizing] = useState(false);

  const handleResummarize = async () => {
    setIsResummarizing(true);
    try {
      await refreshNarrative();
      await refreshReports();
    } catch (err) {
      console.error("Resummarization failed:", err);
    } finally {
      setIsResummarizing(false);
    }
  };

  const resolvedCount = tickets.filter(t => t.status === "RESOLVED" || t.status === "CLOSED").length;
  const total = tickets.length;
  const volumeValues = volume ? Object.values(volume) : [];

  const categoryCounts = tickets.reduce((acc: any, t) => {
    const cat = t.category || "Uncategorized";
    acc[cat] = (acc[cat] || 0) + 1;
    return acc;
  }, {});
  const sortedCategories = Object.entries(categoryCounts).sort((a: any, b: any) => b[1] - a[1]);

  const priorityCounts = tickets.reduce((acc: any, t) => {
    const rawPrio = (t.priority || "P2").toUpperCase();
    const PRIO_MAP: Record<string, string> = { "P0": "URGENT", "P1": "HIGH", "P2": "MEDIUM", "P3": "LOW" };
    const prio = PRIO_MAP[rawPrio] || rawPrio;
    acc[prio] = (acc[prio] || 0) + 1;
    return acc;
  }, {});
  
  const resolvedTickets = tickets.filter(t => t.resolved_at && (t.status === "RESOLVED" || t.status === "CLOSED"));
  let avgResHours = 0;
  if (resolvedTickets.length > 0) {
    const totalHours = resolvedTickets.reduce((acc, t) => {
      const start = new Date(t.created_at).getTime();
      const end = new Date(t.resolved_at!).getTime();
      return acc + (end - start) / (1000 * 60 * 60);
    }, 0);
    avgResHours = totalHours / resolvedTickets.length;
  }

  const showReportsLoading = reportsLoading && !volume;
  const showNarrativeLoading = (narrativeLoading || isResummarizing) && !narrative;

  return (
    <div style={{ padding: "32px", color: COLORS.gray900, background: COLORS.gray50, minHeight: "100%" }}>
      <div style={{ marginBottom: 32 }}>
        <h1 style={{ fontSize: 28, fontWeight: 800, color: COLORS.gray900, marginBottom: 4 }}>Workspace Analytics</h1>
        <p style={{ color: COLORS.gray500, fontSize: 14 }}>Real-time operational metrics and historical trends</p>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20, marginBottom: 32 }}>
        {[
          { 
            label: "Active Tickets", 
            value: showReportsLoading ? <Skeleton width={60} height={32} /> : total - resolvedCount, 
            footer: showReportsLoading ? <Skeleton width={100} height={12} /> : `${total} Total Tickets`, 
            color: "hsl(217, 91%, 60%)", 
            icon: "πŸ“Š",
            viz: showReportsLoading ? <Skeleton width={100} height={30} /> : <Sparkline data={volumeValues.length > 0 ? volumeValues : [0,0,0]} color="hsl(217, 91%, 60%)" />
          },
          { 
            label: "SLA Compliance", 
            value: showReportsLoading ? <Skeleton width={80} height={32} /> : (sla ? `${Math.round(sla.sla_compliance_rate * 100)}%` : "100%"), 
            footer: showReportsLoading ? <Skeleton width={100} height={12} /> : `${sla?.breached_tickets || 0} Rule Breaches`, 
            color: "hsl(142, 71%, 45%)", 
            icon: "⚑",
            viz: showReportsLoading ? <Skeleton height={4} /> : <div style={{ height: 4, width: '100%', background: COLORS.gray100, borderRadius: 2 }}>
                  <div style={{ height: '100%', width: sla ? `${sla.sla_compliance_rate * 100}%` : '100%', background: "hsl(142, 71%, 45%)", borderRadius: 2 }} />
                 </div>
          },
          { 
            label: "Avg. Resolution", 
            value: showReportsLoading ? <Skeleton width={70} height={32} /> : (avgResHours > 0 ? `${avgResHours.toFixed(1)}h` : "β€”"), 
            footer: showReportsLoading ? <Skeleton width={100} height={12} /> : `${resolvedCount} Resolved Tickets`, 
            color: "hsl(262, 83%, 58%)", 
            icon: "βœ…",
            viz: showReportsLoading ? <Skeleton width={120} height={11} /> : <div style={{ fontSize: 11, fontWeight: 600, color: COLORS.gray400 }}>Operational Threshold: 24h</div>
          },
          { 
            label: "CSAT Score", 
            value: showReportsLoading ? <Skeleton width={60} height={32} /> : (csat ? csat.average_rating.toFixed(1) : "β€”"), 
            footer: showReportsLoading ? <Skeleton width={100} height={12} /> : (csat?.total_responses ? `${csat.total_responses} Total Ratings` : "No Ratings Yet"), 
            color: "hsl(38, 92%, 50%)", 
            icon: "⭐",
            viz: showReportsLoading ? <Skeleton width={80} height={11} /> : <div style={{ fontSize: 11, color: "#EAB308" }}>
                  {"β˜…".repeat(Math.floor(csat?.average_rating || 0)) + "β˜†".repeat(5 - Math.floor(csat?.average_rating || 0))}
                </div>
          },
        ].map(s => (
          <div key={s.label} style={{ 
            background: "#fff", 
            border: `1px solid ${COLORS.gray200}`, 
            borderRadius: 16, 
            padding: "20px",
            display: "flex",
            flexDirection: "column",
            justifyContent: "space-between",
            height: 140,
            boxShadow: "0 1px 3px rgba(0,0,0,0.02)"
          }}>
            <div style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "center" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
                <span style={{ fontSize: 11, color: COLORS.gray500, fontWeight: 750, textTransform: "uppercase", letterSpacing: "0.05em" }}>{s.label}</span>
                <span style={{ fontSize: 16 }}>{s.icon}</span>
              </div>
              <div style={{ fontSize: 26, fontWeight: 800, color: COLORS.gray900, marginBottom: 4 }}>{s.value}</div>
            </div>
            <div style={{ height: 40, display: "flex", flexDirection: "column", justifyContent: "flex-end" }}>
              <div style={{ marginBottom: 6 }}>{s.viz}</div>
              <div style={{ fontSize: 11, color: COLORS.gray400, fontWeight: 600 }}>{s.footer}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "3fr 2fr", gap: 24, marginBottom: 32 }}>
        <div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 20, padding: "24px" }}>
          <div style={{ fontSize: 15, fontWeight: 800, color: COLORS.gray900, marginBottom: 20, display: "flex", justifyContent: "space-between" }}>
             <span>Ticket Volume by Category</span>
             <span style={{ fontSize: 11, color: COLORS.gray400 }}>Distribution Analysis</span>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {sortedCategories.length > 0 ? sortedCategories.map(([cat, count]: any) => (
              <div key={cat}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 6, fontSize: 12, fontWeight: 600 }}>
                  <span style={{ color: COLORS.gray700 }}>{cat}</span>
                  <span style={{ color: COLORS.gray900 }}>{count}</span>
                </div>
                <div style={{ height: 6, background: COLORS.gray100, borderRadius: 3 }}>
                   <div style={{ height: "100%", width: `${(count / total) * 100}%`, background: COLORS.brand, borderRadius: 3, transition: "width 0.5s ease" }} />
                </div>
              </div>
            )) : <div style={{ padding: "40px", textAlign: "center", color: COLORS.gray400, fontSize: 13 }}>No categorical data available</div>}
          </div>
        </div>

        <div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 20, padding: "24px" }}>
          <div style={{ fontSize: 15, fontWeight: 800, color: COLORS.gray900, marginBottom: 20 }}>Priority Distribution</div>
          <div style={{ height: 200, display: "flex", alignItems: "flex-end", gap: 20, paddingTop: 20 }}>
            {["URGENT", "HIGH", "MEDIUM", "LOW"].map(prio => {
              const count = priorityCounts[prio] || 0;
              const height = total > 0 ? (count / total) * 140 : 0;
              return (
                <div key={prio} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
                  <div style={{ 
                    width: "100%", 
                    height: (height || 2), 
                    background: prio === "URGENT" ? "#EF4444" : prio === "HIGH" ? "#F59E0B" : prio === "MEDIUM" ? "#3B82F6" : "#10B981", 
                    borderRadius: "4px 4px 0 0",
                    transition: "height 0.5s ease"
                  }} />
                  <span style={{ fontSize: 10, fontWeight: 700, color: COLORS.gray500 }}>{prio}</span>
                  <span style={{ fontSize: 12, fontWeight: 800, color: COLORS.gray900 }}>{count}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div style={{ 
        background: "#fff", 
        border: `1px solid ${COLORS.gray200}`, 
        borderRadius: 20, 
        padding: "32px", 
        marginBottom: 32,
        position: "relative",
        boxShadow: "0 10px 40px rgba(0,0,0,0.02)"
      }}>
        <style>
          {`
            @keyframes intelligence-shimmer {
              0% { color: #6B7280; }
              50% { color: #D1D5DB; }
              100% { color: #6B7280; }
            }
            .shimmer-text {
              animation: intelligence-shimmer 2s infinite ease-in-out;
            }
          `}
        </style>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            <div style={{ width: 8, height: 8, borderRadius: "50%", background: "#10B981" }} />
            <span style={{ fontSize: 12, fontWeight: 800, color: COLORS.gray900, textTransform: "uppercase", letterSpacing: "0.05em" }}>Nexus Workspace Intelligence</span>
          </div>
          <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
            <div style={{ fontSize: 11, color: COLORS.brand, fontWeight: 700, padding: "4px 10px", background: COLORS.brandLight, borderRadius: 20 }}>
               AI-Synthesized Report
            </div>
            <button 
              onClick={handleResummarize}
              disabled={narrativeLoading || isResummarizing}
              style={{
                background: "none",
                border: "none",
                cursor: (narrativeLoading || isResummarizing) ? "wait" : "pointer",
                padding: "4px",
                display: "flex",
                alignItems: "center",
                color: (narrativeLoading || isResummarizing) ? COLORS.gray200 : COLORS.gray400,
                transition: "color 0.2s"
              }}
              title="Resummarize insights"
            >
              <span style={{ 
                fontSize: 16, 
                display: "inline-block", 
                animation: isResummarizing ? "spin 1s linear infinite" : "none" 
              }}>πŸ”„</span>
            </button>
          </div>
        </div>
        <div 
          className={showNarrativeLoading ? "shimmer-text" : ""}
          style={{ 
            color: COLORS.gray700, 
            fontSize: 15, 
            lineHeight: 1.7, 
            fontWeight: 500,
            opacity: isResummarizing ? 0.5 : 1,
            transition: "opacity 0.3s ease"
          }}
        >
          {showNarrativeLoading ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Skeleton width="100%" height={16} />
              <Skeleton width="95%" height={16} />
              <Skeleton width="90%" height={16} />
            </div>
          ) : (
            <div className="prose prose-sm max-w-none">
               <NexusMarkdown content={narrative?.insights || "Workspace metrics are within normal operational parameters. All systems reporting healthy compliance levels."} />
            </div>
          )}
        </div>
      </div>

      <div style={{ background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 20, padding: "24px" }}>
        <div style={{ fontSize: 15, fontWeight: 800, color: COLORS.gray900, marginBottom: 20 }}>Operational Activity History</div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr>
                {["Ticket", "Subject", "Status", "Priority", "Duration"].map(h => (
                  <th key={h} style={{ textAlign: "left", padding: "12px", fontSize: 11, fontWeight: 800, color: COLORS.gray500, borderBottom: `1px solid ${COLORS.gray100}`, textTransform: "uppercase", letterSpacing: "0.05em" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {tickets.slice(0, 10).map(t => (
                <tr key={t.id} style={{ borderBottom: `1px solid ${COLORS.gray50}` }}>
                  <td style={{ padding: "12px", fontSize: 12, fontFamily: "monospace", color: COLORS.brand, fontWeight: 700 }}>{t.id?.slice(0, 8)}</td>
                  <td style={{ padding: "12px", maxWidth: 200, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: COLORS.gray800, fontWeight: 500 }}>{t.title}</td>
                  <td style={{ padding: "12px" }}><StatusBadge status={t.status} /></td>
                  <td style={{ padding: "12px" }}><PriorityBadge priority={t.priority} /></td>
                  <td style={{ padding: "12px", fontSize: 12, color: COLORS.gray500, fontWeight: 600 }}>
                    {t.resolved_at ? `${Math.round((new Date(t.resolved_at).getTime() - new Date(t.created_at).getTime()) / (1000 * 60 * 60))}h` : "β€”"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};