Spaces:
Paused

dushyantsingh0 commited on
Commit
eefcb41
·
1 Parent(s): 4a6adfb

intial commits

Browse files
api/v1/messages.py CHANGED
@@ -170,7 +170,16 @@ async def send_message(
170
  except Exception as e:
171
  logger.error(f"FAILED TO QUEUE MENTION NOTIFICATION: {e}")
172
 
173
- await enqueue_task(arq_pool, "auto_summarize_ticket", str(ticket_id))
 
 
 
 
 
 
 
 
 
174
 
175
  if is_staff and not payload.is_internal and ticket.created_by != current_user.id:
176
  try:
 
170
  except Exception as e:
171
  logger.error(f"FAILED TO QUEUE MENTION NOTIFICATION: {e}")
172
 
173
+ # --- AI FREQUENCY OPTIMIZATION ---
174
+ # Only summarize on the 1st message (initial context) and every 10th message thereafter
175
+ # to preserve compute resources and reduce "Neural Core" noise.
176
+ msg_count_stmt = select(func.count(Message.id)).where(Message.ticket_id == ticket_id, Message.deleted_at.is_(None))
177
+ msg_count = (await db.execute(msg_count_stmt)).scalar() or 0
178
+
179
+ if msg_count == 1 or msg_count % 10 == 0:
180
+ await enqueue_task(arq_pool, "auto_summarize_ticket", str(ticket_id))
181
+ else:
182
+ logger.info(f"Skipping auto-summary for ticket {ticket_id} (Message count: {msg_count})")
183
 
184
  if is_staff and not payload.is_internal and ticket.created_by != current_user.id:
185
  try:
brain/ee1f36a8-2d45-4b2b-82a9-c0b167d506c5/scratch/test_enum.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+
3
+ class UserRole(str, enum.Enum):
4
+ CUSTOMER_ADMIN = "customer_admin"
5
+ CUSTOMER_USER = "customer_user"
6
+
7
+ WORKSPACE_ADMIN_ROLES = [UserRole.CUSTOMER_ADMIN]
8
+
9
+ current_user_role = "customer_admin"
10
+
11
+ print(f"Comparison: {current_user_role == UserRole.CUSTOMER_ADMIN}")
12
+ print(f"In Check: {current_user_role in WORKSPACE_ADMIN_ROLES}")
core/deps.py CHANGED
@@ -126,7 +126,12 @@ async def get_current_user_from_token(token: str, db: AsyncSession, portal: Opti
126
 
127
  if cached_profile:
128
  # Reconstruct detached model from cache for logic checks
129
- merged_user = User(**cached_profile)
 
 
 
 
 
130
  # Re-attach is_active if it was missing
131
  if not merged_user.is_active:
132
  raise credentials_exception
 
126
 
127
  if cached_profile:
128
  # Reconstruct detached model from cache for logic checks
129
+ from uuid import UUID
130
+ profile_data = cached_profile.copy()
131
+ if profile_data.get("id"): profile_data["id"] = UUID(profile_data["id"])
132
+ if profile_data.get("workspace_id"): profile_data["workspace_id"] = UUID(profile_data["workspace_id"])
133
+
134
+ merged_user = User(**profile_data)
135
  # Re-attach is_active if it was missing
136
  if not merged_user.is_active:
137
  raise credentials_exception
core/vision.py CHANGED
@@ -97,15 +97,15 @@ async def extract_visual_context(db: AsyncSession, workspace_id: UUID, text: str
97
  return []
98
 
99
  matches = IMAGE_PATTERN.findall(text)
100
- images = []
 
 
 
 
 
 
 
101
 
102
- for identifier in matches:
103
- if len(images) >= limit:
104
- break
105
- resolved = await resolve_image(db, workspace_id, identifier.strip())
106
- if resolved:
107
- images.append(resolved)
108
-
109
  if images:
110
  logger.info(f"Vision: Resolved {len(images)} images for multimodal context from workspace {workspace_id}")
111
 
 
97
  return []
98
 
99
  matches = IMAGE_PATTERN.findall(text)
100
+ if not matches:
101
+ return []
102
+
103
+ # CONCURRENCY OPTIMIZATION: Resolve all images in parallel
104
+ tasks = [resolve_image(db, workspace_id, identifier.strip()) for identifier in matches[:limit]]
105
+ results = await asyncio.gather(*tasks)
106
+
107
+ images = [r for r in results if r]
108
 
 
 
 
 
 
 
 
109
  if images:
110
  logger.info(f"Vision: Resolved {len(images)} images for multimodal context from workspace {workspace_id}")
111
 
frontend/apps/customer/src/components/Dashboard.tsx CHANGED
@@ -125,7 +125,7 @@ export const Dashboard: React.FC<DashboardProps> = ({ setActive, setSelectedTick
125
  {ticketsLoading && tickets.length === 0 ? (
126
  "Loading your support dashboard and ticket status..."
127
  ) : (
128
- <>You have <span style={{ color: 'var(--banner-text)', fontWeight: 800, textDecoration: 'underline', textDecorationColor: 'var(--primary)' }}>{activeTickets.length} active tickets</span> currently being handled by our team.</>
129
  )}
130
  </p>
131
 
@@ -135,17 +135,17 @@ export const Dashboard: React.FC<DashboardProps> = ({ setActive, setSelectedTick
135
  style={{
136
  marginTop: 32,
137
  padding: "16px 32px",
138
- background: "var(--primary)",
139
  border: "none",
140
  borderRadius: 16,
141
- color: "#ffffff",
142
  fontSize: 14,
143
  cursor: "pointer",
144
  fontWeight: 800,
145
  display: 'flex',
146
  alignItems: 'center',
147
  gap: 12,
148
- boxShadow: "0 10px 20px var(--primary-glow)",
149
  transition: 'all 0.3s cubic-bezier(0.19, 1, 0.22, 1)',
150
  fontFamily: "var(--font-heading)",
151
  textTransform: 'uppercase',
@@ -163,35 +163,39 @@ export const Dashboard: React.FC<DashboardProps> = ({ setActive, setSelectedTick
163
  label: "TOTAL TICKETS",
164
  value: ticketsLoading ? <Skeleton width={60} height={32} /> : tickets.length,
165
  sub: "SUBMITTED TICKETS",
166
- icon: <TrendingUp size={18} />
 
167
  },
168
  {
169
  label: "ACTIVE TICKETS",
170
  value: ticketsLoading ? <Skeleton width={60} height={32} /> : activeTickets.length,
171
  sub: "OPEN REQUESTS",
172
- icon: <Zap size={18} />
 
173
  },
174
  {
175
  label: "RESOLVED TICKETS",
176
  value: ticketsLoading ? <Skeleton width={60} height={32} /> : resolvedCount,
177
  sub: "CLOSED SUCCESSFULLY",
178
- icon: <CheckCircle size={18} />
 
179
  }
180
  ].map(s => (
181
  <div key={s.label} className="glass-card" style={{
182
  background: "var(--banner-card-bg)",
183
  backdropFilter: 'blur(10px)',
184
- border: '1px solid var(--border-subtle)',
185
  padding: "24px",
186
  borderRadius: 24,
187
- boxShadow: "0 10px 40px rgba(0,0,0,0.05)"
 
188
  }}>
189
  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
190
- <div className="metadata" style={{ fontSize: 10, fontWeight: 900, color: 'var(--banner-subtitle)' }}>{s.label}</div>
191
- <div style={{ color: 'var(--primary)', opacity: 0.8 }}>{s.icon}</div>
192
  </div>
193
  <div className="numeric" style={{ fontSize: 32, fontWeight: 800, marginBottom: 6, letterSpacing: '-0.02em', color: 'var(--banner-text)' }}>{s.value}</div>
194
- <div className="metadata" style={{ fontSize: 9, opacity: 0.5, color: 'var(--banner-subtitle)' }}>{s.sub}</div>
195
  </div>
196
  ))}
197
  </div>
 
125
  {ticketsLoading && tickets.length === 0 ? (
126
  "Loading your support dashboard and ticket status..."
127
  ) : (
128
+ <>You have <span style={{ color: '#ffffff', fontWeight: 800, textDecoration: 'underline', textDecorationColor: 'rgba(255,255,255,0.4)' }}>{activeTickets.length} active tickets</span> currently being handled by our team.</>
129
  )}
130
  </p>
131
 
 
135
  style={{
136
  marginTop: 32,
137
  padding: "16px 32px",
138
+ background: "#ffffff",
139
  border: "none",
140
  borderRadius: 16,
141
+ color: "var(--primary)",
142
  fontSize: 14,
143
  cursor: "pointer",
144
  fontWeight: 800,
145
  display: 'flex',
146
  alignItems: 'center',
147
  gap: 12,
148
+ boxShadow: "0 10px 20px rgba(0,0,0,0.1)",
149
  transition: 'all 0.3s cubic-bezier(0.19, 1, 0.22, 1)',
150
  fontFamily: "var(--font-heading)",
151
  textTransform: 'uppercase',
 
163
  label: "TOTAL TICKETS",
164
  value: ticketsLoading ? <Skeleton width={60} height={32} /> : tickets.length,
165
  sub: "SUBMITTED TICKETS",
166
+ icon: <TrendingUp size={18} />,
167
+ color: "#6366f1"
168
  },
169
  {
170
  label: "ACTIVE TICKETS",
171
  value: ticketsLoading ? <Skeleton width={60} height={32} /> : activeTickets.length,
172
  sub: "OPEN REQUESTS",
173
+ icon: <Zap size={18} />,
174
+ color: "#3b82f6"
175
  },
176
  {
177
  label: "RESOLVED TICKETS",
178
  value: ticketsLoading ? <Skeleton width={60} height={32} /> : resolvedCount,
179
  sub: "CLOSED SUCCESSFULLY",
180
+ icon: <CheckCircle size={18} />,
181
+ color: "var(--success)"
182
  }
183
  ].map(s => (
184
  <div key={s.label} className="glass-card" style={{
185
  background: "var(--banner-card-bg)",
186
  backdropFilter: 'blur(10px)',
187
+ border: `1.5px solid ${s.color}15`,
188
  padding: "24px",
189
  borderRadius: 24,
190
+ boxShadow: `0 10px 40px ${s.color}08`,
191
+ position: 'relative'
192
  }}>
193
  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
194
+ <div className="metadata" style={{ fontSize: 10, fontWeight: 900, color: s.color }}>{s.label}</div>
195
+ <div style={{ color: s.color }}>{s.icon}</div>
196
  </div>
197
  <div className="numeric" style={{ fontSize: 32, fontWeight: 800, marginBottom: 6, letterSpacing: '-0.02em', color: 'var(--banner-text)' }}>{s.value}</div>
198
+ <div className="metadata" style={{ fontSize: 9, opacity: 0.6, fontWeight: 700, color: 'var(--banner-subtitle)' }}>{s.sub}</div>
199
  </div>
200
  ))}
201
  </div>
frontend/apps/customer/src/components/TopBar.tsx CHANGED
@@ -182,7 +182,7 @@ export const TopBar: React.FC<TopBarProps> = ({ title, subtitle, logoUrl, onSele
182
  }}>
183
  <div>
184
  <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
185
- <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: COLORS.text, letterSpacing: "-0.03em", fontFamily: "var(--font-heading)" }}>{title}</h1>
186
  {logoUrl && (
187
  <div style={{
188
  height: 22,
@@ -196,10 +196,9 @@ export const TopBar: React.FC<TopBarProps> = ({ title, subtitle, logoUrl, onSele
196
  alt="Workspace Branding"
197
  style={{
198
  height: '100%',
199
- maxWidth: 120,
200
  objectFit: 'contain',
201
- filter: theme === 'dark' ? 'grayscale(100%) invert(1) brightness(1.5)' : 'grayscale(100%) contrast(0.8)',
202
- opacity: theme === 'dark' ? 0.8 : 0.65,
203
  transition: 'all 0.3s ease'
204
  }}
205
  />
 
182
  }}>
183
  <div>
184
  <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
185
+ <h1 style={{ margin: 0, fontSize: 22, fontWeight: 900, color: "var(--primary)", letterSpacing: "-0.04em", fontFamily: "var(--font-heading)" }}>{title}</h1>
186
  {logoUrl && (
187
  <div style={{
188
  height: 22,
 
196
  alt="Workspace Branding"
197
  style={{
198
  height: '100%',
199
+ maxWidth: 140,
200
  objectFit: 'contain',
201
+ opacity: 1,
 
202
  transition: 'all 0.3s ease'
203
  }}
204
  />
frontend/apps/internal/src/components/DashboardOverview.tsx CHANGED
@@ -110,7 +110,7 @@ export const DashboardOverview: React.FC<DashboardOverviewProps> = ({ workspaceI
110
  {isSyncing && !queueTickets.length ? (
111
  <div className={`${styles.skeleton} ${styles.sValue}`} />
112
  ) : (
113
- <div className={styles.fValue}>
114
  {queueTickets.filter(t => ['OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS'].includes(t.status)).length}
115
  </div>
116
  )}
 
110
  {isSyncing && !queueTickets.length ? (
111
  <div className={`${styles.skeleton} ${styles.sValue}`} />
112
  ) : (
113
+ <div className={styles.fValue} style={{ color: '#6366f1' }}>
114
  {queueTickets.filter(t => ['OPEN', 'ACKNOWLEDGED', 'IN_PROGRESS'].includes(t.status)).length}
115
  </div>
116
  )}
frontend/apps/internal/src/components/TopBar.module.css CHANGED
@@ -86,16 +86,14 @@
86
 
87
  .logoImage {
88
  height: 100%;
89
- max-width: 120px;
90
  object-fit: contain;
91
- filter: grayscale(100%) contrast(0.8);
92
- opacity: 0.65;
93
  transition: all 0.3s ease;
94
  }
95
 
96
  :global(.theme-dark) .logoImage {
97
- filter: grayscale(100%) invert(1) brightness(1.5);
98
- opacity: 0.8;
99
  }
100
 
101
  .right {
 
86
 
87
  .logoImage {
88
  height: 100%;
89
+ max-width: 140px;
90
  object-fit: contain;
91
+ opacity: 1;
 
92
  transition: all 0.3s ease;
93
  }
94
 
95
  :global(.theme-dark) .logoImage {
96
+ opacity: 0.9;
 
97
  }
98
 
99
  .right {
frontend/apps/internal/src/components/TopBar.tsx CHANGED
@@ -185,7 +185,7 @@ export const TopBar: React.FC<TopBarProps> = ({ title, subtitle, logoUrl, onTick
185
  <Menu size={20} />
186
  </button>
187
  )}
188
- <div className={styles.title}>{title}</div>
189
  {logoUrl && (
190
  <div className={styles.logoContainer}>
191
  <img src={logoUrl} alt="Workspace Branding" className={styles.logoImage} />
 
185
  <Menu size={20} />
186
  </button>
187
  )}
188
+ <div className={styles.title} style={{ color: 'var(--primary)', fontWeight: 900, letterSpacing: '-0.04em' }}>{title}</div>
189
  {logoUrl && (
190
  <div className={styles.logoContainer}>
191
  <img src={logoUrl} alt="Workspace Branding" className={styles.logoImage} />
frontend/packages/shared/src/styles/theme.css CHANGED
@@ -38,10 +38,10 @@
38
  --border-hi: #cbd5e1;
39
  --glass-bg: rgba(255, 255, 255, 0.7);
40
  --glass-border: rgba(0, 0, 0, 0.04);
41
- --banner-bg: #ffffff;
42
- --banner-text: var(--text-main);
43
- --banner-subtitle: var(--text-muted);
44
- --banner-card-bg: var(--bg-hover);
45
  --banner-gradient: linear-gradient(135deg, #6d28d9 0%, #7c3aed 100%);
46
  --glass-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
47
  --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.04);
 
38
  --border-hi: #cbd5e1;
39
  --glass-bg: rgba(255, 255, 255, 0.7);
40
  --glass-border: rgba(0, 0, 0, 0.04);
41
+ --banner-bg: linear-gradient(135deg, #6d28d9 0%, #7c3aed 100%);
42
+ --banner-text: #ffffff;
43
+ --banner-subtitle: rgba(255, 255, 255, 0.8);
44
+ --banner-card-bg: rgba(255, 255, 255, 0.9);
45
  --banner-gradient: linear-gradient(135deg, #6d28d9 0%, #7c3aed 100%);
46
  --glass-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
47
  --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.04);
services/ticket_service.py CHANGED
@@ -396,8 +396,33 @@ class TicketService:
396
  result = await db.execute(stmt)
397
  tickets = result.scalars().unique().all()
398
 
399
- # 7. Process items through role-based sanitizer
400
- items = [await TicketService.sanitize_ticket_response(t, current_user, db) for t in tickets]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
 
402
  return {
403
  "items": items,
 
396
  result = await db.execute(stmt)
397
  tickets = result.scalars().unique().all()
398
 
399
+ # 7. Batch Context Optimization: Pre-fetch shared data to prevent N+1 in sanitizer
400
+ # 7.1 Pre-fetch Workspace Leads (Common across all tickets in this view)
401
+ lead_name = None
402
+ if any(t.is_escalated for t in tickets):
403
+ lead_stmt = select(UserTable.full_name).join(UserWorkspace).where(
404
+ UserWorkspace.workspace_id == target_ws,
405
+ UserWorkspace.role.in_([UserRole.SC_LEAD, UserRole.SC_ADMIN]),
406
+ UserTable.is_active
407
+ ).limit(1)
408
+ lead_name = (await db.execute(lead_stmt)).scalar_one_or_none()
409
+
410
+ # 7.2 Pre-fetch Duplicate Titles
411
+ dup_map = {}
412
+ dup_ids = [t.duplicate_of_id for t in tickets if t.duplicate_of_id]
413
+ if dup_ids:
414
+ dup_stmt = select(Ticket.id, Ticket.title).where(Ticket.id.in_(dup_ids))
415
+ dup_res = await db.execute(dup_stmt)
416
+ dup_map = {row[0]: row[1] for row in dup_res.all()}
417
+
418
+ # 8. Process items through role-based sanitizer with injected context
419
+ items = [await TicketService.sanitize_ticket_response(
420
+ t,
421
+ current_user,
422
+ db,
423
+ lead_name=lead_name,
424
+ dup_title=dup_map.get(t.duplicate_of_id)
425
+ ) for t in tickets]
426
 
427
  return {
428
  "items": items,
tasks/ai.py CHANGED
@@ -76,8 +76,11 @@ async def auto_summarize_ticket(ctx, ticket_id: UUID, **kwargs):
76
  HumanMessage(content=[{"type": "text", "text": f"Title: {ticket.title}\n{context_str}Convo:\n{format_convo(messages)}"}])
77
  ]
78
 
79
- cust_resp = await llm.ainvoke(cust_prompt)
80
- intl_resp = await llm.ainvoke(intl_prompt)
 
 
 
81
  summary_data = {"customer_summary": str(cust_resp.content), "internal_summary": str(intl_resp.content)}
82
 
83
  meta = dict(ticket.ai_metadata or {})
 
76
  HumanMessage(content=[{"type": "text", "text": f"Title: {ticket.title}\n{context_str}Convo:\n{format_convo(messages)}"}])
77
  ]
78
 
79
+ # CONCURRENCY OPTIMIZATION: Run dual summaries in parallel
80
+ cust_task = llm.ainvoke(cust_prompt)
81
+ intl_task = llm.ainvoke(intl_prompt)
82
+ cust_resp, intl_resp = await asyncio.gather(cust_task, intl_task)
83
+
84
  summary_data = {"customer_summary": str(cust_resp.content), "internal_summary": str(intl_resp.content)}
85
 
86
  meta = dict(ticket.ai_metadata or {})