Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (14)
- Frontend/src/admin/pages/AdminDashboard.jsx+48-24
- Frontend/src/hooks/useWebSocket.jsAdded+207
- Frontend/src/store/ticketStore.js+41-6
- MobileApp/App.js+77-18
- MobileApp/metro.config.jsAdded+8
- MobileApp/package-lock.json+1-1
- MobileApp/package.json+1-1
- backend/main.py+274-24
- backend/requirements.txt+2
- backend/services/classifier_service.py+26-5
- backend/services/gemini_service.py+5-1
- backend/services/spam_service.pyAdded+156
- deploy/monitoring/grafana_dashboard.json+155-87
- requirements.txt+2
1234567891011121390 unmodified lines10410510610710810911011111211311411511611711811912013 unmodified lines1341351361371381391401411421 unmodified line14414514614714814915049 unmodified lines20020120220320420520620720820921021121270 unmodified lines28328428528628728828929029118 unmodified lines310311312313314315316317318import React, { useMemo } from 'react';import { useNavigate } from 'react-router-dom';import { Activity, AlertTriangle, Clock, ShieldCheck } from 'lucide-react';import useAuthStore from "../../store/authStore";import { supabase } from "../../lib/supabaseClient";import useTicketsRealtime from "../../hooks/useTicketsRealtime";import StatCard from "../components/StatCard";import TicketTable from "../components/TicketTable";import { formatTimelineDate } from "../../utils/dateUtils";// Inline SVG icon componentsconst TicketIcon = () => (90 unmodified linesconst AdminDashboard = () => {const navigate = useNavigate();const { profile } = useAuthStore();const [tickets, setTickets] = React.useState([]);const [isLoading, setIsLoading] = React.useState(true);const [nowMs, setNowMs] = React.useState(() => Date.now());useTicketsRealtime({company: profile?.company,enabled: Boolean(profile),onTicketsChange: setTickets,channelName: 'admin_dashboard_tickets_realtime',});React.useEffect(() => {if (profile) {const fetchStats = async () => {13 unmodified linesconsole.warn("Retrying dashboard fetch without relation...", error);const { data: basicData, error: basicError } = await supabase.from('tickets').select('*').eq('company', profile?.company).order('created_at', { ascending: false });if (basicError) throw basicError;setTickets(basicData || []);} else {setTickets(data || []);}} catch (err) { console.error("Dashboard fetch error:", err); }finally { setIsLoading(false); }1 unmodified linefetchStats();}}, [profile]);React.useEffect(() => {const timer = setInterval(() => setNowMs(Date.now()), 60 * 1000);49 unmodified linesDashboard</h1><p style={{ color: '#6b7280', fontSize: '13px', marginTop: '4px', display: 'flex', alignItems: 'center', gap: '8px', fontWeight: 500 }}><span style={{ width: 6, height: 6, borderRadius: '50%', background: '#22c55e', display: 'inline-block' }}></span>Real-time updates active</p></div><div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 16px', background: '#F0FDF4', border: '1.5px solid #BBF7D0', borderRadius: '100px' }}><span style={{ width: 6, height: 6, borderRadius: '50%', background: '#22c55e', display: 'inline-block', animation: 'pulse-dot 2s infinite' }}></span><span style={{ fontSize: '11px', fontWeight: 700, color: '#15803d', letterSpacing: '0.08em', textTransform: 'uppercase' }}>System Active</span></div></div>70 unmodified lines<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#16a34a" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/></svg>AI Status</h2><div style={{ display: 'flex', alignItems: 'center', gap: '6px', background: '#F0FDF4', border: '1px solid #BBF7D0', borderRadius: '100px', padding: '3px 10px' }}><span style={{ width: 5, height: 5, borderRadius: '50%', background: '#22c55e', display: 'inline-block', animation: 'pulse-dot 2s infinite' }}></span><span style={{ fontSize: '10px', fontWeight: 700, color: '#15803d' }}>LIVE SYNC</span></div></div><div style={{ background: '#fff', borderRadius: '20px', border: '1px solid #f0fdf4', padding: '24px' }}>18 unmodified lines<div className="pt-4 mt-4 border-t border-gray-100 flex flex-col items-center gap-2"><p style={{ fontSize: '10px', color: '#9ca3af', letterSpacing: '0.14em', fontWeight: 600, textTransform: 'uppercase' }}>All systems operating normally</p><div style={{ display: 'flex', alignItems: 'center', gap: '6px', padding: '4px 10px', background: '#f8faf9', borderRadius: '100px', border: '1px solid #e5e7eb' }}><Activity size={10} color="#9ca3af" /><span style={{ fontSize: '9px', fontWeight: 600, color: '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.1em' }}>Last Synced: {formatTimelineDate(new Date())}</span></div></div>1234567891011121390 unmodified lines10410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513 unmodified lines1491501511521531541551561571581591601611621 unmodified line16416516616716816917049 unmodified lines22022122222322422522622722822923023123223323423523670 unmodified lines30730830931031131231331431518 unmodified lines334335336337338339340341342import React, { useMemo } from 'react';import { useNavigate } from 'react-router-dom';import { Activity, AlertTriangle, Clock, ShieldCheck, Wifi, WifiOff } from 'lucide-react';import useAuthStore from "../../store/authStore";import useTicketStore from "../../store/ticketStore";import useWebSocket from "../../hooks/useWebSocket";import { supabase } from "../../lib/supabaseClient";import StatCard from "../components/StatCard";import TicketTable from "../components/TicketTable";// Inline SVG icon componentsconst TicketIcon = () => (90 unmodified linesconst AdminDashboard = () => {const navigate = useNavigate();const { profile } = useAuthStore();const [isLoading, setIsLoading] = React.useState(true);const [nowMs, setNowMs] = React.useState(() => Date.now());// WebSocket connection for real-time ticket updatesconst { isConnected: wsConnected, lastMessage } = useWebSocket(profile?.company);// Read tickets from the Zustand store (populated below and updated by WS)const tickets = useTicketStore((s) => s.tickets);const handleWsMessage = useTicketStore((s) => s.handleWsMessage);const setWsConnected = useTicketStore((s) => s.setWsConnected);const upsertTicket = useTicketStore((s) => s.upsertTicket);const removeTicket = useTicketStore((s) => s.removeTicket);// Sync WebSocket connection status to storeReact.useEffect(() => {setWsConnected(wsConnected);}, [wsConnected, setWsConnected]);// Route incoming WebSocket messages into the ticket storeReact.useEffect(() => {if (lastMessage) {handleWsMessage(lastMessage);}}, [lastMessage, handleWsMessage]);// Initial fetch — populate store from Supabase on mountReact.useEffect(() => {if (profile) {const fetchStats = async () => {13 unmodified linesconsole.warn("Retrying dashboard fetch without relation...", error);const { data: basicData, error: basicError } = await supabase.from('tickets').select('*').eq('company', profile?.company).order('created_at', { ascending: false });if (basicError) throw basicError;// Bulk-load into store (avoid duplicates)for (const t of basicData || []) {upsertTicket(t);}} else {for (const t of data || []) {upsertTicket(t);}}} catch (err) { console.error("Dashboard fetch error:", err); }finally { setIsLoading(false); }1 unmodified linefetchStats();}}, [profile, upsertTicket]);React.useEffect(() => {const timer = setInterval(() => setNowMs(Date.now()), 60 * 1000);49 unmodified linesDashboard</h1><p style={{ color: '#6b7280', fontSize: '13px', marginTop: '4px', display: 'flex', alignItems: 'center', gap: '8px', fontWeight: 500 }}>{wsConnected ? (<Wifi size={14} color="#22c55e" />) : (<WifiOff size={14} color="#f97316" />)}{wsConnected ? 'WebSocket connected' : 'Reconnecting...'}</p></div><div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 16px', background: wsConnected ? '#F0FDF4' : '#FFF7ED', border: wsConnected ? '1.5px solid #BBF7D0' : '1.5px solid #FED7AA', borderRadius: '100px' }}><span style={{ width: 6, height: 6, borderRadius: '50%', background: wsConnected ? '#22c55e' : '#f97316', display: 'inline-block', animation: 'pulse-dot 2s infinite' }}></span><span style={{ fontSize: '11px', fontWeight: 700, color: wsConnected ? '#15803d' : '#c2410c', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{wsConnected ? 'Live' : 'Reconnecting'}</span></div></div>70 unmodified lines<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#16a34a" strokeWidth="2"><circle cx="12" cy="12" r="3"/><path d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83"/></svg>AI Status</h2><div style={{ display: 'flex', alignItems: 'center', gap: '6px', background: wsConnected ? '#F0FDF4' : '#FFF7ED', border: wsConnected ? '1px solid #BBF7D0' : '1px solid #FED7AA', borderRadius: '100px', padding: '3px 10px' }}><span style={{ width: 5, height: 5, borderRadius: '50%', background: wsConnected ? '#22c55e' : '#f97316', display: 'inline-block', animation: 'pulse-dot 2s infinite' }}></span><span style={{ fontSize: '10px', fontWeight: 700, color: wsConnected ? '#15803d' : '#c2410c' }}>{wsConnected ? 'WS CONNECTED' : 'RECONNECTING'}</span></div></div><div style={{ background: '#fff', borderRadius: '20px', border: '1px solid #f0fdf4', padding: '24px' }}>18 unmodified lines<div className="pt-4 mt-4 border-t border-gray-100 flex flex-col items-center gap-2"><p style={{ fontSize: '10px', color: '#9ca3af', letterSpacing: '0.14em', fontWeight: 600, textTransform: 'uppercase' }}>All systems operating normally</p><div style={{ display: 'flex', alignItems: 'center', gap: '6px', padding: '4px 10px', background: '#f8faf9', borderRadius: '100px', border: '1px solid #e5e7eb' }}>{wsConnected ? <Activity size={10} color="#22c55e" /> : <Activity size={10} color="#f97316" />}<span style={{ fontSize: '9px', fontWeight: 600, color: wsConnected ? '#16a34a' : '#9ca3af', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{wsConnected ? 'Live via WebSocket' : 'Reconnecting via WebSocket...'}</span></div></div>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207/** * useWebSocket — auto-reconnecting WebSocket hook with heartbeat support. * * Connects to the backend WebSocket endpoint for real-time ticket updates. * Automatically re-establishes the connection on drop with exponential backoff. * * Usage: * import useWebSocket from "../../hooks/useWebSocket"; * * const { isConnected, sendMessage, lastMessage } = useWebSocket(companyId); * * // lastMessage updates on every incoming message → use in a useEffect * useEffect(() => { * if (lastMessage?.type === "ticket_update") { * store.addTicket(lastMessage.ticket); * } * }, [lastMessage]); */
import { useEffect, useRef, useState, useCallback } from "react";
// ---------------------------------------------------------------------------// Constants// ---------------------------------------------------------------------------
const WS_BASE_URL = import.meta.env.VITE_WS_URL || "ws://localhost:7860";const PING_INTERVAL_MS = 25_000; // slightly < server-side 30s so pong arrives firstconst PONG_TIMEOUT_MS = 12_000; // slightly > server-side 10s timeoutconst MAX_RECONNECT_DELAY_MS = 30_000;const INITIAL_RECONNECT_DELAY_MS = 1_000;
// ---------------------------------------------------------------------------// Hook// ---------------------------------------------------------------------------
export default function useWebSocket(companyId) { const [isConnected, setIsConnected] = useState(false); const [lastMessage, setLastMessage] = useState(null); const [connectionError, setConnectionError] = useState(null);
const wsRef = useRef(null); const pingTimerRef = useRef(null); const pongTimeoutRef = useRef(null); const reconnectTimerRef = useRef(null); const reconnectAttemptRef = useRef(0); const mountedRef = useRef(true); const companyIdRef = useRef(companyId);
// Keep a ref to latest companyId so the effect closure always has it companyIdRef.current = companyId;
// ---- Cleanup helpers ---------------------------------------------------
const clearTimers = useCallback(() => { if (pingTimerRef.current) { clearInterval(pingTimerRef.current); pingTimerRef.current = null; } if (pongTimeoutRef.current) { clearTimeout(pongTimeoutRef.current); pongTimeoutRef.current = null; } if (reconnectTimerRef.current) { clearTimeout(reconnectTimerRef.current); reconnectTimerRef.current = null; } }, []);
const cleanup = useCallback(() => { clearTimers(); if (wsRef.current) { wsRef.current.onopen = null; wsRef.current.onclose = null; wsRef.current.onmessage = null; wsRef.current.onerror = null; wsRef.current.close(); wsRef.current = null; } }, [clearTimers]);
// ---- Start heartbeat timers (called after connect) --------------------
const startHeartbeat = useCallback(() => { // Periodic pings pingTimerRef.current = setInterval(() => { if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { wsRef.current.send(JSON.stringify({ type: "pong" })); } }, PING_INTERVAL_MS); }, []);
// ---- WebSocket lifecycle -----------------------------------------------
const connect = useCallback(() => { cleanup();
const cid = companyIdRef.current; if (!cid) return;
const url = `${WS_BASE_URL}/ws/${encodeURIComponent(cid)}`; setConnectionError(null);
let socket; try { socket = new WebSocket(url); } catch (err) { setConnectionError(err.message || "Failed to create WebSocket"); scheduleReconnect(); return; } wsRef.current = socket;
socket.onopen = () => { if (!mountedRef.current) return; setIsConnected(true); setConnectionError(null); reconnectAttemptRef.current = 0; startHeartbeat(); };
socket.onmessage = (event) => { if (!mountedRef.current) return; try { const data = JSON.parse(event.data);
// Respond to server pings immediately if (data.type === "ping") { if (socket.readyState === WebSocket.OPEN) { socket.send(JSON.stringify({ type: "pong" })); } return; }
setLastMessage(data); } catch { // ignore malformed frames } };
socket.onclose = (event) => { if (!mountedRef.current) return; setIsConnected(false); clearTimers();
// Don't reconnect on clean closes (1000 = normal, 400x = intentional) if (event.code === 1000 || (event.code >= 4000 && event.code < 5000)) { return; }
scheduleReconnect(); };
socket.onerror = () => { // onclose fires immediately after onerror, so reconnect is handled there }; }, [cleanup, clearTimers, startHeartbeat]);
// ---- Reconnection with exponential backoff -----------------------------
const scheduleReconnect = useCallback(() => { if (!mountedRef.current || !companyIdRef.current) return;
const attempt = reconnectAttemptRef.current; const delay = Math.min( INITIAL_RECONNECT_DELAY_MS * Math.pow(2, attempt), MAX_RECONNECT_DELAY_MS ); reconnectAttemptRef.current = attempt + 1;
setConnectionError(`Reconnecting in ${Math.round(delay / 1000)}s...`);
reconnectTimerRef.current = setTimeout(() => { if (mountedRef.current) connect(); }, delay); }, [connect]);
// ---- Send helper -------------------------------------------------------
const sendMessage = useCallback( (msg) => { if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) { wsRef.current.send( typeof msg === "string" ? msg : JSON.stringify(msg) ); } }, [] );
// ---- Main effect -------------------------------------------------------
useEffect(() => { mountedRef.current = true; companyIdRef.current = companyId;
if (companyId) { connect(); }
return () => { mountedRef.current = false; cleanup(); }; }, [companyId, connect, cleanup]);
return { isConnected, lastMessage, connectionError, sendMessage };}2 unmodified lines34567891011121314151610 unmodified lines2728293031323318 unmodified lines525354555657585960616263646566672 unmodified linesconst useTicketStore = create(persist((set) => ({aiTicket: null,activeTicket: null,autoResolvedTickets: [], // For analyticstickets: [], // Global queue for adminsnotifications: [], // User notificationssetAITicket: (data) => set({ aiTicket: data }),setActiveTicket: (ticket) => set({ activeTicket: ticket }),addAutoResolvedTicket: (record) => set((state) => ({autoResolvedTickets: [...state.autoResolvedTickets, record]})),10 unmodified lines})),addTicket: (ticket) => set((state) => {return {tickets: [ticket, ...state.tickets]};}),upsertTicket: (ticket) => set((state) => {18 unmodified lines: state.activeTicket})),updateTicket: (ticketId, updates) => set((state) => {// eslint-disable-next-line no-unused-varsconst existingTicket = state.tickets.find(t => (t.id ?? t.ticket_id) === ticketId);const updatedTickets = state.tickets.map(t => ((t.id ?? t.ticket_id) === ticketId) ? { ...t, ...updates } : t);const shouldUpdateActive = ((state.activeTicket?.id ?? state.activeTicket?.ticket_id) === ticketId);return {tickets: updatedTickets,activeTicket: shouldUpdateActive ? { ...state.activeTicket, ...updates } : state.activeTicket};}),appendMessage: (ticketId, message) => set((state) => {const updatedTickets = state.tickets.map(t =>t.ticket_id === ticketId2 unmodified lines345678910111213141516171819202110 unmodified lines3233343536373818 unmodified lines575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011022 unmodified linesconst useTicketStore = create(persist((set, get) => ({aiTicket: null,activeTicket: null,autoResolvedTickets: [], // For analyticstickets: [], // Global queue for adminsnotifications: [], // User notificationswsConnected: false, // WebSocket connection statussetAITicket: (data) => set({ aiTicket: data }),setActiveTicket: (ticket) => set({ activeTicket: ticket }),setWsConnected: (connected) => set({ wsConnected: connected }),addAutoResolvedTicket: (record) => set((state) => ({autoResolvedTickets: [...state.autoResolvedTickets, record]})),10 unmodified lines})),addTicket: (ticket) => set((state) => {return {tickets: [...state.tickets, ticket]};}),upsertTicket: (ticket) => set((state) => {18 unmodified lines: state.activeTicket})),updateTicket: (ticketId, updates) => set((state) => {const existingTicket = state.tickets.find(t => (t.id ?? t.ticket_id) === ticketId);if (!existingTicket) return state;const updatedTickets = state.tickets.map(t => (t.id ?? t.ticket_id) === ticketId ? { ...t, ...updates } : t);const shouldUpdateActive = (state.activeTicket?.id ?? state.activeTicket?.ticket_id) === ticketId;return {tickets: updatedTickets,activeTicket: shouldUpdateActive ? { ...state.activeTicket, ...updates } : state.activeTicket};}),/*** Route an incoming WebSocket message to the correct store action.** Call this from the component that owns the WebSocket connection* (e.g. AdminDashboard) whenever a message arrives.*/handleWsMessage: (msg) => {if (!msg || !msg.type) return;const { type, event, ticket, ticket_id } = msg;switch (type) {case "ticket_update": {if (!ticket) break;if (event === "created") {// Avoid duplicates — use upsertget().upsertTicket(ticket);} else if (event === "updated") {get().upsertTicket(ticket);} else if (event === "deleted") {get().removeTicket(ticket_id);}break;}default:// Ignore unknown message types (e.g. heartbeat)break;}},appendMessage: (ticketId, message) => set((state) => {const updatedTickets = state.tickets.map(t =>t.ticket_id === ticketId
126 unmodified lines1271281291301311321331341351361371381391401411421432 unmodified lines14614714814915015115215315415515615715815916016116216316416518 unmodified lines1841851861871881891901911921931941953 unmodified lines19920020120220320411 unmodified lines2162172182192202212222232244 unmodified lines22923023123223323423519 unmodified lines255256257258259260261262263126 unmodified linesconst [userRole, setUserRole] = useState('user'); // 'user', 'admin', 'master_admin'useEffect(() => {const initialize = async () => {try {const { data: { session } } = await supabase.auth.getSession();setSession(session);if (session?.user) {const { data, error } = await supabase.from('profiles').select('status, role').eq('id', session.user.id).single();if (error) {console.log('[AuthInit] Profile fetch error, validating session:', error.message);2 unmodified linesif (userError) {console.log('[AuthInit] Token validation failed. Clearing session.');setSession(null);} else {// Valid token but profiles table is temporarily offline; default to usersetUserStatus('active');setUserRole('user');}} else {setUserStatus(data?.status || 'active');setUserRole(data?.role || 'user');}}} catch (e) {console.log('[AuthInit] Crash caught during initialization:', e);} finally {// Guarantee showOnboarding is resolved to a boolean to prevent React Navigation stack layout mismatchtry {const onboardingDone = await AsyncStorage.getItem('@onboarding_complete');setShowOnboarding(onboardingDone === null);18 unmodified linesif (error) {console.log('[AuthChange] Profile query failed:', error.message);// Default to safe values to avoid blank screenssetUserStatus('active');setUserRole('user');} else {setUserStatus(data?.status || 'active');setUserRole(data?.role || 'user');}} catch (err) {console.warn('[AuthChange] Uncaught exception inside handler:', err);3 unmodified lines} else {setUserStatus(null);setUserRole('user');}});11 unmodified linesschema: 'public',table: 'profiles',filter: `id=eq.${session.user.id}`,}, (payload) => {setUserStatus(payload.new.status);setUserRole(payload.new.role || 'user');}).subscribe();4 unmodified linesuseEffect(() => {const handleUrl = async ({ url }) => {if (!url) return;// Parse hash fragment: helpdeskai://login#access_token=...&refresh_token=...const hashIndex = url.indexOf('#');if (hashIndex === -1) return;const hash = url.substring(hashIndex + 1);19 unmodified lines}};// Handle app already openconst subscription = Linking.addEventListener('url', handleUrl);// Handle cold start — app launched from the linkLinking.getInitialURL().then(url => url && handleUrl({ url }));return () => subscription.remove();126 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801812 unmodified lines18418518618718818919019119219319419519619719819920020120220320420520620720820921021121218 unmodified lines2312322332342352362372382392402412422432442452462473 unmodified lines25125225325425525625725825926011 unmodified lines2722732742752762772782792802812822832842852864 unmodified lines29129229329429529619 unmodified lines316317318319320321322126 unmodified linesconst [userRole, setUserRole] = useState('user'); // 'user', 'admin', 'master_admin'useEffect(() => {let finished = false;const initialize = async () => {// Safety timeout wrapper: if anything hangs, force mount after 3 secondsconst timeoutId = setTimeout(async () => {if (!finished) {console.log('[AuthInit] Timeout reached (3s). Forcing mount fallback.');try {const onboardingDone = await AsyncStorage.getItem('@onboarding_complete');setShowOnboarding(onboardingDone === null);} catch (err) {setShowOnboarding(false);}setLoading(false);}}, 3000);try {// 1. Instantly load cached status and role from AsyncStorage (stale-while-revalidate pattern)const [cachedStatus, cachedRole] = await Promise.all([AsyncStorage.getItem('@user_status'),AsyncStorage.getItem('@user_role'),]);if (cachedStatus) setUserStatus(cachedStatus);if (cachedRole) setUserRole(cachedRole);// 2. Fetch session with a 2.5 second timeout wrapper to prevent slow refreshing from locking the appconst sessionPromise = supabase.auth.getSession();const sessionTimeoutPromise = new Promise((_, reject) =>setTimeout(() => reject(new Error('Session fetch timed out')), 2500));const { data: { session } } = await Promise.race([sessionPromise, sessionTimeoutPromise]);setSession(session);// 3. If session is valid, validate/fetch the user profileif (session?.user) {const profilePromise = supabase.from('profiles').select('status, role').eq('id', session.user.id).single();const profileTimeoutPromise = new Promise((_, reject) =>setTimeout(() => reject(new Error('Profile fetch timed out')), 2000));const { data, error } = await Promise.race([profilePromise, profileTimeoutPromise]);if (error) {console.log('[AuthInit] Profile fetch error, validating session:', error.message);2 unmodified linesif (userError) {console.log('[AuthInit] Token validation failed. Clearing session.');setSession(null);await AsyncStorage.removeItem('@user_status');await AsyncStorage.removeItem('@user_role');} else {// Valid token but profiles table is offline; retain cached or default to safe user statusif (!cachedStatus) setUserStatus('active');if (!cachedRole) setUserRole('user');}} else {const status = data?.status || 'active';const role = data?.role || 'user';setUserStatus(status);setUserRole(role);await Promise.all([AsyncStorage.setItem('@user_status', status),AsyncStorage.setItem('@user_role', role),]);}}} catch (e) {console.log('[AuthInit] Exception caught during initialization:', e.message || e);} finally {finished = true;clearTimeout(timeoutId);try {const onboardingDone = await AsyncStorage.getItem('@onboarding_complete');setShowOnboarding(onboardingDone === null);18 unmodified linesif (error) {console.log('[AuthChange] Profile query failed:', error.message);setUserStatus('active');setUserRole('user');} else {const status = data?.status || 'active';const role = data?.role || 'user';setUserStatus(status);setUserRole(role);await Promise.all([AsyncStorage.setItem('@user_status', status),AsyncStorage.setItem('@user_role', role),]);}} catch (err) {console.warn('[AuthChange] Uncaught exception inside handler:', err);3 unmodified lines} else {setUserStatus(null);setUserRole('user');await Promise.all([AsyncStorage.removeItem('@user_status'),AsyncStorage.removeItem('@user_role'),]);}});11 unmodified linesschema: 'public',table: 'profiles',filter: `id=eq.${session.user.id}`,}, async (payload) => {const status = payload.new.status;const role = payload.new.role || 'user';setUserStatus(status);setUserRole(role);await Promise.all([AsyncStorage.setItem('@user_status', status),AsyncStorage.setItem('@user_role', role),]);}).subscribe();4 unmodified linesuseEffect(() => {const handleUrl = async ({ url }) => {if (!url) return;const hashIndex = url.indexOf('#');if (hashIndex === -1) return;const hash = url.substring(hashIndex + 1);19 unmodified lines}};const subscription = Linking.addEventListener('url', handleUrl);Linking.getInitialURL().then(url => url && handleUrl({ url }));return () => subscription.remove();
12345678// metro.config.js – extend Expo's default Metro configconst { getDefaultConfig } = require('expo/metro-config');
module.exports = (async () => { const defaultConfig = await getDefaultConfig(__dirname); // Add any customizations here if needed (e.g., extra asset extensions) return defaultConfig;})();30 unmodified lines3132333435363730 unmodified lines"react-native-screens": "~4.16.0","react-native-svg": "15.12.1","react-native-url-polyfill": "^3.0.0","react-native-webview": "^13.16.1","zustand": "^5.0.12"},"devDependencies": {30 unmodified lines3132333435363730 unmodified lines"react-native-screens": "~4.16.0","react-native-svg": "15.12.1","react-native-url-polyfill": "^3.0.0","react-native-webview": "^13.15.0","zustand": "^5.0.12"},"devDependencies": {
31 unmodified lines3233343536373831 unmodified lines"react-native-screens": "~4.16.0","react-native-svg": "15.12.1","react-native-url-polyfill": "^3.0.0","react-native-webview": "^13.16.1","zustand": "^5.0.12"},"private": true,31 unmodified lines3233343536373831 unmodified lines"react-native-screens": "~4.16.0","react-native-svg": "15.12.1","react-native-url-polyfill": "^3.0.0","react-native-webview": "^13.15.0","zustand": "^5.0.12"},"private": true,
19 unmodified lines20212223242526272829303137 unmodified lines697071727374757677787980139 unmodified lines22022122222322422519 unmodified lines24524624724824925057 unmodified lines308309310311312313314315316317318319144 unmodified lines464465466467468469470420 unmodified lines89189289389489589689789889990090190290390490590690790890991091193 unmodified lines100510061007100810091010101110121013101410151016131 unmodified lines1148114911501151115211531154115546 unmodified lines1202120312041205120612071208120930 unmodified lines12401241124212431244124536 unmodified lines128212831284128512861287128812891290129125 unmodified lines13171318131913201321132235 unmodified lines13581359136013611362136340 unmodified lines140414051406140714081409141014111412141323 unmodified lines143714381439144014411442151 unmodified lines1594159515961597159815991600160116021603160416051606160751 unmodified lines1659166016611662166316643 unmodified lines166816691670167116721673167449 unmodified lines17241725172619 unmodified lineswarnings.filterwarnings("ignore", message="'pin_memory'")# HF Rebuild Trigger: 2026-03-08-2030from fastapi import FastAPI, Depends, HTTPException, Requestfrom slowapi import Limiter, _rate_limit_exceeded_handlerfrom slowapi.util import get_remote_addressfrom slowapi.errors import RateLimitExceededfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse, JSONResponse, StreamingResponsefrom fastapi.encoders import jsonable_encoderimport asynciofrom pathlib import Path37 unmodified linesfrom backend.services.onnx_service import onnx_classifierfrom backend.services.ner_service import NERServicefrom backend.services.duplicate_service import DuplicateServicefrom backend.services.rag_service import RagServicefrom backend.services.sla_engine import SLAEngine, compute_sla_breach_at, get_sla_policyfrom backend.services.redis_cache import redis_cachefrom backend.auth_cookie import router as auth_cookie_router, get_current_user # noqa: F401# ---------------------------------------------------------------------------# Request / Response models# ---------------------------------------------------------------------------139 unmodified linesconfidence: floatclass TicketResponse(BaseModel):id: str | int | None = Noneticket_id: str | None = None19 unmodified linessource_language: str = "en"source_language_name: str = "English"was_translated: bool = Falseversion: str = "2.1.0-Neural-Diagnostic"57 unmodified lines# ---------------------------------------------------------------------------# Service singletons# ---------------------------------------------------------------------------from backend.services.semantic_duplicate_service import SemanticDuplicateServiceclassifier_service = ClassifierService()ner_service = NERService()duplicate_service = DuplicateService()rag_service = RagService()sla_engine = SLAEngine(supabase_client=None) # Will be reassigned after supabase initsemantic_dupe_service = SemanticDuplicateService(supabase_client=None) # wired in lifespan144 unmodified linesprint("[Startup] Classifier V2 Shadow: Ready.")print(f"[Startup] ONNX MiniLM Fallback: {'READY' if getattr(onnx_classifier, '_loaded', False) else 'DEGRADED (artifacts missing)'}")print("[Startup] Ready.")yieldprint("[Shutdown] Cleaning up ...")420 unmodified linesfinal_data["sla_status"] = final_data.get("sla_status") or classify_sla_status(final_data.get("sla_breach_at"))final_data["escalation_level"] = int(final_data.get("escalation_level") or 0)import hashlibuser_hash = hashlib.sha256(str(request_body.user_id).encode()).hexdigest()[:8]logger.info(f"Tenant linkage: user_hash={user_hash}, company_id={final_data.get('company_id')}")duplicate_text = (request_body.description or "").strip() or (request_body.subject or "").strip()duplicate_threshold = get_duplicate_threshold(final_data.get("company_id"), 0.85)duplicate_result = {"is_duplicate": False,"duplicate_ticket_id": None,"parent_ticket_id": None,"is_potential_duplicate": False,"similarity": 0.0,}user_hash = hashlib.sha256(str(request_body.user_id).encode()).hexdigest()[:8]logger.info(f"Tenant linkage: user_hash={user_hash}, company_id={final_data.get('company_id')}")# Semantic duplicate check BEFORE inserting the ticket93 unmodified linesresponse["parent_subject"] = duplicate_check_result.get("parent_subject")response["similarity"] = duplicate_check_result["similarity"]response["candidates"] = duplicate_check_result.get("candidates", [])return responseexcept Exception as e:traceback.print_exc()raise HTTPException(status_code=500, detail=str(e))@app.get("/tickets/{ticket_id}")async def get_ticket_by_id(request: Request,131 unmodified linestext = f"{text} {local_ocr_text}".strip()print(f"[AI] OCR added {len(local_ocr_text)} chars to context.")# Initalize Timelinereturn await analyze_only(request_body)@app.post("/ai/analyze")async def analyze_only(request_body: TicketRequest):46 unmodified lineshighlights=[],timeline={"received": _dt.datetime.utcnow().isoformat() + "Z"},env_metadata={},is_potential_duplicate=False,parent_ticket_id=None,sla_breach_at=_sla_breach.isoformat().replace("+00:00", "Z"),original_text=request_body.text,source_language=translation_ctx["source_language"],30 unmodified linessummary = text[:100] + ("…" if len(text) > 100 else "")# --- Classification ---classification = classify_ticket_text(text)36 unmodified linesdecision_factors.append(f"Found similar incident ({int(dup_result['similarity']*100)}%)")if rag_match:decision_factors.append(f"Found solution article: '{rag_match['title']}'")reasoning = f"Categorized as '{classification['category']}' - {classification['subcategory']}."if classification["auto_resolve"]:reasoning += " Flagged for AI auto-resolution via Knowledge Base." if rag_match else " Flagged for auto-resolution."timeline["routed"] = get_now_ist()25 unmodified lineshighlights=[e.get("text", "") for e in entities], # Use entity texts as highlights for nowtimeline=timeline,env_metadata=env_metadata,is_potential_duplicate=dup_result.get("is_potential_duplicate", False),parent_ticket_id=dup_result.get("parent_ticket_id"),sla_breach_at=sla_breach_dt.isoformat().replace("+00:00", "Z"),35 unmodified linessummary = text[:100] + ("…" if len(text) > 100 else "")# 2. NERyield f"data: {json.dumps({'step': 'Extracting technical entities', 'status': 'in_progress'})}\n\n"await asyncio.sleep(0.2)40 unmodified linesdecision_factors.append(f"Found similar incident ({int(dup_result['similarity']*100)}%)")if rag_match:decision_factors.append(f"Found solution article: '{rag_match['title']}'")reasoning = f"Categorized as '{classification['category']}' - {classification['subcategory']}."if classification["auto_resolve"]:reasoning += " Flagged for AI auto-resolution via Knowledge Base." if rag_match else " Flagged for auto-resolution."timeline["routed"] = get_now_ist()23 unmodified lines"highlights": [e.get("text", "") for e in entities],"timeline": timeline,"env_metadata": env_metadata,"sla_breach_at": sla_breach_dt.isoformat() + "Z"}151 unmodified linesif not supabase:# Return defaults from codepolicies = []for pri, cfg in sla_engine.SLA_POLICIES.items() if hasattr(sla_engine, 'SLA_POLICIES') else SLA_POLICIES.items():policies.append({"priority": pri,"max_hours": cfg["max_hours"],"warning_pct": cfg["warning_pct"],"auto_escalate": cfg["auto_escalate_on_breach"],"l2_after_minutes": cfg["l2_escalation_mins"],"l3_after_minutes": cfg["l3_escalation_mins"],})return {"policies": policies}51 unmodified lines@app.get("/system/settings")async def get_system_settings_endpoint():"""Fetch all system settings."""if not supabase:raise HTTPException(status_code=503, detail="Database not connected")try:3 unmodified linessettings[row["key"]] = row["value"]return settingsexcept Exception as e:logger.warning(f"[SETTINGS] Query failed: {e}")return {}49 unmodified lines"sla_evaluation": result,"escalations": escalations,}19 unmodified lines2021222324252627282930313237 unmodified lines707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217139 unmodified lines35735835936036136236336436536636736836937019 unmodified lines39039139239339439539657 unmodified lines454455456457458459460461462463464144 unmodified lines609610611612613614615616617618619620621622623624625626627420 unmodified lines1048104910501051105210531054105510561057105893 unmodified lines11521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222131 unmodified lines13541355135613571358135913601361136246 unmodified lines14091410141114121413141430 unmodified lines144514461447144814491450145114521453145414551456145714581459146036 unmodified lines14971498149915001501150215031504150515061507150815091510151115121513151425 unmodified lines154015411542154315441545154635 unmodified lines15821583158415851586158715881589159015911592159315941595159640 unmodified lines16371638163916401641164216431644164516461647164816491650165116521653165423 unmodified lines1678167916801681168216831684151 unmodified lines18361837183818391840184118421843184418451846184718481849185051 unmodified lines19021903190419051906190719083 unmodified lines191219131914191519161917191849 unmodified lines19681969197019711972197319741975197619 unmodified lineswarnings.filterwarnings("ignore", message="'pin_memory'")# HF Rebuild Trigger: 2026-03-08-2030from fastapi import FastAPI, Depends, HTTPException, Request, WebSocket, WebSocketDisconnectfrom slowapi import Limiter, _rate_limit_exceeded_handlerfrom slowapi.util import get_remote_addressfrom slowapi.errors import RateLimitExceededfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse, JSONResponse, Response, StreamingResponsefrom prometheus_client import CONTENT_TYPE_LATEST, generate_latestfrom fastapi.encoders import jsonable_encoderimport asynciofrom pathlib import Path37 unmodified linesfrom backend.services.onnx_service import onnx_classifierfrom backend.services.ner_service import NERServicefrom backend.services.duplicate_service import DuplicateServicefrom backend.services.semantic_duplicate_service import SemanticDuplicateServicefrom backend.services.rag_service import RagServicefrom backend.services.spam_service import SpamServicefrom backend.services.sla_engine import SLAEngine, compute_sla_breach_at, get_sla_policyfrom backend.services.redis_cache import redis_cachefrom backend.auth_cookie import router as auth_cookie_router, get_current_user # noqa: F401# ---------------------------------------------------------------------------# WebSocket Connection Manager — real-time ticket dashboards# ---------------------------------------------------------------------------HEARTBEAT_INTERVAL = 30 # seconds between ping broadcastsHEARTBEAT_TIMEOUT = 10 # seconds to wait for a pong before disconnectclass ConnectionManager:"""Tracks active WebSocket connections grouped by ``company_id``.Thread-safe for concurrent connect/disconnect calls from multipleASGI workers (single-process via ``asyncio.Lock``)."""def __init__(self) -> None:self._connections: dict[str, set[WebSocket]] = {}self._lock = asyncio.Lock()async def connect(self, company_id: str, ws: WebSocket) -> None:"""Accept a new WebSocket and register it under ``company_id``."""await ws.accept()async with self._lock:self._connections.setdefault(company_id, set()).add(ws)async def disconnect(self, company_id: str, ws: WebSocket) -> None:"""Remove a WebSocket from the pool."""async with self._lock:connections = self._connections.get(company_id)if connections:connections.discard(ws)# Clean up empty company groupsif not connections:del self._connections[company_id]async def broadcast(self, company_id: str, message: dict) -> int:"""Send a JSON message to every client in a company group.Returns:Number of successfully sent messages."""payload = json.dumps(message, default=str)sent = 0async with self._lock:connections = set(self._connections.get(company_id, []))for ws in connections:try:await ws.send_text(payload)sent += 1except Exception:await self.disconnect(company_id, ws)return sentasync def broadcast_all(self, message: dict) -> int:"""Send a JSON message to **all** connected clients."""payload = json.dumps(message, default=str)sent = 0async with self._lock:all_connections = {ws for group in self._connections.values() for ws in group}for ws in all_connections:try:await ws.send_text(payload)sent += 1except Exception:passreturn sentasync def ping_all(self) -> None:"""Send a ``{"type": "ping"}`` heartbeat to every connection.Connections that fail to receive the ping are removed."""async with self._lock:# Snapshot all connections under lock so iteration is safesnapshot = {cid: set(ws_set) for cid, ws_set in self._connections.items()}for cid, ws_set in snapshot.items():for ws in list(ws_set):try:await ws.send_json({"type": "ping"})except Exception:await self.disconnect(cid, ws)@propertydef active_count(self) -> int:"""Total number of connected clients across all companies."""return sum(len(ws_set) for ws_set in self._connections.values())# Singleton — reused across lifespan and WebSocket routeconnection_manager = ConnectionManager()async def _heartbeat_loop() -> None:"""Background task: broadcast ping every ``HEARTBEAT_INTERVAL`` seconds.Clients that fail the ping are disconnected automatically by``ConnectionManager.ping_all()``."""while True:await asyncio.sleep(HEARTBEAT_INTERVAL)try:await connection_manager.ping_all()count = connection_manager.active_countif count:print(f"[WS] Heartbeat sent to {count} active connection(s)")except Exception as exc:print(f"[WS] Heartbeat error: {exc}")# ---------------------------------------------------------------------------# SLA helper functions (must be defined before save_ticket uses them)# ---------------------------------------------------------------------------def calculate_sla_breach_at(priority: str) -> datetime.datetime:"""Return the UTC datetime by which the ticket must be resolved."""hours_map = {"critical": 2, "high": 8, "medium": 24, "low": 72}hours = hours_map.get(str(priority).lower().strip(), 72)return datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=hours)def calculate_sla_response_at(priority: str) -> datetime.datetime:"""Return the UTC datetime by which the ticket must receive a first response."""hours_map = {"critical": 0.5, "high": 2, "medium": 6, "low": 18}hours = hours_map.get(str(priority).lower().strip(), 6)return datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=hours)# ---------------------------------------------------------------------------# Request / Response models# ---------------------------------------------------------------------------139 unmodified linesconfidence: floatclass SpamCheck(BaseModel):is_spam: bool = Falserisk_score: float = 0.0reasons: list[str] = []suspicious_urls: list[str] = []matched_keywords: list[str] = []class TicketResponse(BaseModel):id: str | int | None = Noneticket_id: str | None = None19 unmodified linessource_language: str = "en"source_language_name: str = "English"was_translated: bool = Falsespam_check: SpamCheck = SpamCheck()version: str = "2.1.0-Neural-Diagnostic"57 unmodified lines# ---------------------------------------------------------------------------# Service singletons# ---------------------------------------------------------------------------classifier_service = ClassifierService()ner_service = NERService()duplicate_service = DuplicateService()rag_service = RagService()spam_service = SpamService()sla_engine = SLAEngine(supabase_client=None) # Will be reassigned after supabase initsemantic_dupe_service = SemanticDuplicateService(supabase_client=None) # wired in lifespan144 unmodified linesprint("[Startup] Classifier V2 Shadow: Ready.")print(f"[Startup] ONNX MiniLM Fallback: {'READY' if getattr(onnx_classifier, '_loaded', False) else 'DEGRADED (artifacts missing)'}")print("[Startup] Ready.")# Start WebSocket heartbeat background loopheartbeat_task = asyncio.create_task(_heartbeat_loop())print("[Startup] WebSocket heartbeat loop started (interval=30s).")yield# Cancel background tasks on shutdownheartbeat_task.cancel()try:await heartbeat_taskexcept asyncio.CancelledError:passprint("[Shutdown] Cleaning up ...")420 unmodified linesfinal_data["sla_status"] = final_data.get("sla_status") or classify_sla_status(final_data.get("sla_breach_at"))final_data["escalation_level"] = int(final_data.get("escalation_level") or 0)user_hash = hashlib.sha256(str(request_body.user_id).encode()).hexdigest()[:8]logger.info(f"Tenant linkage: user_hash={user_hash}, company_id={final_data.get('company_id')}")duplicate_text = (request_body.description or "").strip() or (request_body.subject or "").strip()duplicate_threshold = get_duplicate_threshold(final_data.get("company_id"), 0.85) # noqa: F841# Semantic duplicate check BEFORE inserting the ticket93 unmodified linesresponse["parent_subject"] = duplicate_check_result.get("parent_subject")response["similarity"] = duplicate_check_result["similarity"]response["candidates"] = duplicate_check_result.get("candidates", [])# Broadcast the new/updated ticket to all WebSocket clients for this companycompany_id = final_data.get("company_id")if company_id:asyncio.create_task(connection_manager.broadcast(company_id,{"type": "ticket_update","event": "created","ticket": insert_data,"ticket_id": str(ticket_id),},))return responseexcept Exception as e:traceback.print_exc()raise HTTPException(status_code=500, detail=str(e))@app.websocket("/ws/{company_id}")async def websocket_endpoint(ws: WebSocket, company_id: str):"""Real-time WebSocket feed for a company's ticket dashboard.Protocol:- Server sends ``{"type": "ping"}`` every 30s (heartbeat).- Client must respond with ``{"type": "pong"}`` within 10s.- Server pushes ``{"type": "ticket_update", ...}`` on changes.Usage (frontend):const socket = new WebSocket("ws://host:7860/ws/{company_id}");socket.onmessage = (event) => { const msg = JSON.parse(event.data); };"""if not company_id or not company_id.strip():await ws.close(code=4000, reason="Missing company_id")returncompany_id = company_id.strip()await connection_manager.connect(company_id, ws)print(f"[WS] Client connected — company_id={company_id}")try:while True:raw = await ws.receive_text()if not raw.strip():continuetry:data = json.loads(raw)except json.JSONDecodeError:continue # ignore malformed frames# Handle pong responseif data.get("type") == "pong":continueexcept WebSocketDisconnect:passexcept Exception as exc:print(f"[WS] Connection error for company_id={company_id}: {exc}")finally:await connection_manager.disconnect(company_id, ws)print(f"[WS] Client disconnected — company_id={company_id}")@app.get("/tickets/{ticket_id}")async def get_ticket_by_id(request: Request,131 unmodified linestext = f"{text} {local_ocr_text}".strip()print(f"[AI] OCR added {len(local_ocr_text)} chars to context.")# Pass OCR-enriched text downstream so the analyze_only endpoint uses it.enriched = request_body.model_copy(update={"text": text, "image_text": local_ocr_text})return await analyze_only(enriched)@app.post("/ai/analyze")async def analyze_only(request_body: TicketRequest):46 unmodified lineshighlights=[],timeline={"received": _dt.datetime.utcnow().isoformat() + "Z"},env_metadata={},sla_breach_at=_sla_breach.isoformat().replace("+00:00", "Z"),original_text=request_body.text,source_language=translation_ctx["source_language"],30 unmodified linessummary = text[:100] + ("…" if len(text) > 100 else "")# --- Spam / Phishing Detection (runs before classification) ---try:spam_result = spam_service.check(text, gemini_analysis.get("ocr_text", ""))except Exception as e:print(f"[SPAM ERROR] {e}")spam_result = {"is_spam": False, "risk_score": 0.0, "reasons": [],"suspicious_urls": [], "matched_keywords": [],}# --- Classification ---classification = classify_ticket_text(text)36 unmodified linesdecision_factors.append(f"Found similar incident ({int(dup_result['similarity']*100)}%)")if rag_match:decision_factors.append(f"Found solution article: '{rag_match['title']}'")if spam_result["is_spam"]:decision_factors.append(f"Flagged as spam/phishing (risk {spam_result['risk_score']:.2f})")classification["assigned_team"] = "Spam / Suspicious"classification["auto_resolve"] = Falsereasoning = f"Categorized as '{classification['category']}' - {classification['subcategory']}."if classification["auto_resolve"]:reasoning += " Flagged for AI auto-resolution via Knowledge Base." if rag_match else " Flagged for auto-resolution."if spam_result["is_spam"]:reasoning += " Ticket flagged as spam/phishing and quarantined from agent inbox."timeline["routed"] = get_now_ist()25 unmodified lineshighlights=[e.get("text", "") for e in entities], # Use entity texts as highlights for nowtimeline=timeline,env_metadata=env_metadata,spam_check=SpamCheck(**spam_result),is_potential_duplicate=dup_result.get("is_potential_duplicate", False),parent_ticket_id=dup_result.get("parent_ticket_id"),sla_breach_at=sla_breach_dt.isoformat().replace("+00:00", "Z"),35 unmodified linessummary = text[:100] + ("…" if len(text) > 100 else "")# Spam / Phishing check (silent step — does not get its own SSE event)try:spam_result = spam_service.check(text, gemini_analysis.get("ocr_text", ""))except Exception:spam_result = {"is_spam": False, "risk_score": 0.0, "reasons": [],"suspicious_urls": [], "matched_keywords": [],}# 2. NERyield f"data: {json.dumps({'step': 'Extracting technical entities', 'status': 'in_progress'})}\n\n"await asyncio.sleep(0.2)40 unmodified linesdecision_factors.append(f"Found similar incident ({int(dup_result['similarity']*100)}%)")if rag_match:decision_factors.append(f"Found solution article: '{rag_match['title']}'")if spam_result["is_spam"]:decision_factors.append(f"Flagged as spam/phishing (risk {spam_result['risk_score']:.2f})")classification["assigned_team"] = "Spam / Suspicious"classification["auto_resolve"] = Falsereasoning = f"Categorized as '{classification['category']}' - {classification['subcategory']}."if classification["auto_resolve"]:reasoning += " Flagged for AI auto-resolution via Knowledge Base." if rag_match else " Flagged for auto-resolution."if spam_result["is_spam"]:reasoning += " Ticket flagged as spam/phishing and quarantined from agent inbox."timeline["routed"] = get_now_ist()23 unmodified lines"highlights": [e.get("text", "") for e in entities],"timeline": timeline,"env_metadata": env_metadata,"spam_check": spam_result,"sla_breach_at": sla_breach_dt.isoformat() + "Z"}151 unmodified linesif not supabase:# Return defaults from codepolicies = []policy_source = sla_engine.SLA_POLICIES if hasattr(sla_engine, "SLA_POLICIES") else {}for pri, cfg in policy_source.items():policies.append({"priority": pri,"max_hours": cfg["max_hours"],"warning_pct": cfg["warning_pct"],"auto_escalate": cfg.get("auto_escalate_on_breach", False),"l2_after_minutes": cfg.get("l2_escalation_mins", 0),"l3_after_minutes": cfg.get("l3_escalation_mins", 0),})return {"policies": policies}51 unmodified lines@app.get("/system/settings")async def get_system_settings_endpoint():"""Fetch all system settings."""_logger = logging.getLogger(__name__)if not supabase:raise HTTPException(status_code=503, detail="Database not connected")try:3 unmodified linessettings[row["key"]] = row["value"]return settingsexcept Exception as e:_logger.warning(f"[SETTINGS] Query failed: {e}")return {}49 unmodified lines"sla_evaluation": result,"escalations": escalations,}@app.get("/metrics")async def metrics():"""Prometheus scrape endpoint — exposes AI inference latency, request counts, and tokens."""return Response(content=generate_latest(), media_type=CONTENT_TYPE_LATEST)
21 unmodified lines2223242521 unmodified linespytest-asynciohttpxcryptography>=42.0.021 unmodified lines22232425262721 unmodified linespytest-asynciohttpxcryptography>=42.0.0websockets>=12.0prometheus-client>=0.19.0
21 unmodified lines22232425262783 unmodified lines11111211311411511611711811912012121 unmodified linesDEVICE = torch.device("cuda" if torch and torch.cuda.is_available() else "cpu") if _HAS_TORCH else NoneMAX_LEN = 128# Priority mapping based on sub-category severityPRIORITY_MAP = {"Blue Screen": "Critical", "Overheating": "Critical", "Data Loss": "Critical",83 unmodified linesinput_ids = encoding["input_ids"].to(DEVICE)attention_mask = encoding["attention_mask"].to(DEVICE)with torch.no_grad():outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)logits = outputs.logitsprobs = F.softmax(logits, dim=1)confidence, pred_idx = torch.max(probs, dim=1)pred_idx = pred_idx.item()confidence = round(confidence.item(), 4)21 unmodified lines2223242526272829303132333435363783 unmodified lines12112212312412512612712812913013113213313413513613713813914014114221 unmodified linesDEVICE = torch.device("cuda" if torch and torch.cuda.is_available() else "cpu") if _HAS_TORCH else NoneMAX_LEN = 128try:from backend.services.metrics_service import (CLASSIFIER_LATENCY,CLASSIFIER_REQUESTS,CLASSIFIER_TOKENS,)_METRICS_ENABLED = Trueexcept Exception:_METRICS_ENABLED = False# Priority mapping based on sub-category severityPRIORITY_MAP = {"Blue Screen": "Critical", "Overheating": "Critical", "Data Loss": "Critical",83 unmodified linesinput_ids = encoding["input_ids"].to(DEVICE)attention_mask = encoding["attention_mask"].to(DEVICE)import time_t0 = time.perf_counter()try:with torch.no_grad():outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)logits = outputs.logitsprobs = F.softmax(logits, dim=1)confidence, pred_idx = torch.max(probs, dim=1)except Exception:if _METRICS_ENABLED:CLASSIFIER_REQUESTS.labels(model="distilbert", status="error").inc()raiseif _METRICS_ENABLED:CLASSIFIER_LATENCY.labels(model="distilbert").observe(time.perf_counter() - _t0)CLASSIFIER_REQUESTS.labels(model="distilbert", status="ok").inc()CLASSIFIER_TOKENS.labels(model="distilbert").inc(int(attention_mask.sum().item()))pred_idx = pred_idx.item()confidence = round(confidence.item(), 4)
27 unmodified lines2829303132333412 unmodified lines47484950515227 unmodified lineselse:print("[GeminiService] WARNING: GEMINI_API_KEY not found in environment.")def analyze_image(self, image_base64: str) -> dict:"""Perform OCR and image analysis using Gemini logic."""12 unmodified linesprompt = ("Analyze this screenshot from a user reporting a technical issue. ""1. Provide a concise description of what is shown in the image. ""2. Perform OCR and extract any error messages or key text. ""3. Identify the main technical problem depicted. "27 unmodified lines2829303132333412 unmodified lines4748495051525354555627 unmodified lineselse:print("[GeminiService] WARNING: GEMINI_API_KEY not found in environment.")def analyze_image(self, image_base64: str, context_text: str = None) -> dict:"""Perform OCR and image analysis using Gemini logic."""12 unmodified linesprompt = ("Analyze this screenshot from a user reporting a technical issue. ")if context_text:prompt += f"Context/description provided by user: '{context_text}'\n"prompt += ("1. Provide a concise description of what is shown in the image. ""2. Perform OCR and extract any error messages or key text. ""3. Identify the main technical problem depicted. "
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Spam & Phishing Detection Service — lightweight, dependency-free heuristics.
Scans ticket text (and OCR-extracted text) for common phishing patterns,suspicious URLs, and social-engineering keywords. Designed to run before theclassification cascade so high-risk tickets can be flagged in the UI andkept away from support agents' inboxes."""
import refrom urllib.parse import urlparse
# Common phishing / social-engineering keywords. Kept conservative to avoid# false-positives on legitimate IT tickets ("password reset" is normal)._PHISHING_KEYWORDS = [ "verify your account", "verify your identity", "confirm your password", "update your password immediately", "account has been suspended", "account will be closed", "unusual sign-in activity", "unusual login attempt", "click here to claim", "you have won", "congratulations you", "wire transfer", "send bitcoin", "send btc", "gift card", "limited time offer", "act now", "urgent action required", "final notice",]
# Free / disposable / known-abused TLDs. Not exhaustive — a starting list._SUSPICIOUS_TLDS = { "zip", "mov", "xyz", "top", "click", "country", "stream", "gq", "tk", "ml", "cf", "ga", "work", "loan", "kim", "men",}
# Common URL shorteners — frequently used to hide phishing destinations._URL_SHORTENERS = { "bit.ly", "tinyurl.com", "goo.gl", "t.co", "ow.ly", "is.gd", "buff.ly", "shorte.st", "adf.ly", "cutt.ly", "rebrand.ly", "rb.gy", "s.id",}
_URL_RE = re.compile( r"\b((?:https?://|www\.)[^\s<>\"')]+)", re.IGNORECASE,)
_IP_HOST_RE = re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}$")
def extract_urls(text: str) -> list[str]: """Return all URLs found in the text, lightly normalized.""" if not text: return [] urls = [] for match in _URL_RE.findall(text): url = match.rstrip(".,);:!?") if not url.lower().startswith(("http://", "https://")): url = "http://" + url urls.append(url) return urls
def _classify_url(url: str) -> str | None: """Return a reason string if the URL looks suspicious, else None.""" try: parsed = urlparse(url) except ValueError: return "Malformed URL"
host = (parsed.hostname or "").lower() if not host: return "URL missing host"
if _IP_HOST_RE.match(host): return f"URL uses raw IP address ({host})"
if host in _URL_SHORTENERS: return f"URL shortener detected ({host})"
tld = host.rsplit(".", 1)[-1] if "." in host else "" if tld in _SUSPICIOUS_TLDS: return f"Suspicious TLD .{tld} ({host})"
# "@" inside the authority is a classic phishing trick to hide the real host. if "@" in (parsed.netloc or ""): return f"URL contains embedded credentials ({parsed.netloc})"
return None
class SpamService: """Stateless heuristic spam / phishing detector."""
# Risk score thresholds — kept on the conservative side. SPAM_THRESHOLD = 0.6
def check(self, text: str, ocr_text: str = "") -> dict: """ Analyze `text` (and optional `ocr_text`) and return a structured verdict.
Returns: { "is_spam": bool, "risk_score": float, # 0.0–1.0 "reasons": list[str], "suspicious_urls": list[str], "matched_keywords": list[str], } """ combined = " ".join(filter(None, [text or "", ocr_text or ""])).strip() if not combined: return { "is_spam": False, "risk_score": 0.0, "reasons": [], "suspicious_urls": [], "matched_keywords": [], }
lowered = combined.lower() matched_keywords = [kw for kw in _PHISHING_KEYWORDS if kw in lowered]
suspicious_urls: list[str] = [] url_reasons: list[str] = [] for url in extract_urls(combined): reason = _classify_url(url) if reason: suspicious_urls.append(url) url_reasons.append(reason)
reasons: list[str] = [] if matched_keywords: reasons.append( f"Matched {len(matched_keywords)} phishing keyword(s): " + ", ".join(matched_keywords[:3]) ) reasons.extend(url_reasons)
# Score: 0.35 per keyword hit + 0.4 per suspicious URL, capped at 1.0. score = min(1.0, 0.35 * len(matched_keywords) + 0.4 * len(suspicious_urls))
return { "is_spam": score >= self.SPAM_THRESHOLD, "risk_score": round(score, 3), "reasons": reasons, "suspicious_urls": suspicious_urls, "matched_keywords": matched_keywords, }8 unmodified lines9101112131415161718192 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721738 unmodified lines},"enable": true,"hide": true,"name": "Annotations & Alerts","type": "dashboard"}]},"editable": true,"fiscalYearStartMonth": 0,"graphTooltip": 0,2 unmodified lines"liveNow": false,"panels": [{"collapsed": false,"gridPos": {"h": 8,"w": 12,"x": 0,"y": 0},"id": 1,"title": "Model Prediction Throughput (Requests / sec)","type": "timeseries","datasource": {"type": "prometheus","uid": "prometheus"},"targets": [{"expr": "sum(rate(model_predictions_total[1m])) by (status)","legendFormat": "Predictions: {{status}}","refId": "A"}],"fieldConfig": {"defaults": {"custom": {"drawStyle": "line","lineInterpolation": "smooth"},"unit": "reqps"}}},{"collapsed": false,"gridPos": {"h": 8,"w": 12,"x": 12,"y": 0},"id": 2,"title": "DistilBERT Model Inference Latency","type": "timeseries","datasource": {"type": "prometheus","uid": "prometheus"},"targets": [{"expr": "histogram_quantile(0.95, sum(rate(model_prediction_latency_seconds_bucket[5m])) by (le))","legendFormat": "p95 Latency","refId": "A"},{"expr": "histogram_quantile(0.99, sum(rate(model_prediction_latency_seconds_bucket[5m])) by (le))","legendFormat": "p99 Latency","refId": "B"},{"expr": "sum(rate(model_prediction_latency_seconds_sum[5m])) / sum(rate(model_prediction_latency_seconds_count[5m]))","legendFormat": "Avg Latency","refId": "C"}],"fieldConfig": {"defaults": {"custom": {"drawStyle": "line","lineInterpolation": "smooth"},"unit": "s"}}},{"collapsed": false,"gridPos": {"h": 8,"w": 12,"x": 0,"y": 8},"id": 3,"title": "Backend CPU Usage","type": "timeseries","datasource": {"type": "prometheus","uid": "prometheus"},"targets": [{"expr": "rate(process_cpu_seconds_total[1m]) * 100","legendFormat": "CPU Usage","refId": "A"}],"fieldConfig": {"defaults": {"custom": {"drawStyle": "line","lineInterpolation": "smooth"},"unit": "percent"}}},{"collapsed": false,"gridPos": {"h": 8,"w": 12,"x": 12,"y": 8},"id": 4,"title": "Backend Memory Usage (Resident Set Size)","type": "timeseries","datasource": {"type": "prometheus","uid": "prometheus"},"targets": [{"expr": "process_resident_memory_bytes","legendFormat": "Memory RSS","refId": "A"}],"fieldConfig": {"defaults": {"custom": {"drawStyle": "line","lineInterpolation": "smooth"},"unit": "bytes"}}}],"schemaVersion": 36,"style": "dark","tags": ["helpdesk","monitoring","ai"],"title": "FastAPI AI Helpdesk Performance Telemetry","timezone": "browser","weekStart": ""}8 unmodified lines91011121314151617181920212 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402418 unmodified lines},"enable": true,"hide": true,"iconColor": "rgba(0, 211, 255, 1)","name": "Annotations & Alerts","type": "dashboard"}]},"description": "HELPDESK.AI service telemetry — AI inference latency, API throughput, token counts, and host resources.","editable": true,"fiscalYearStartMonth": 0,"graphTooltip": 0,2 unmodified lines"liveNow": false,"panels": [{"datasource": {"type": "prometheus","uid": "${DS_PROMETHEUS}"},"fieldConfig": {"defaults": {"color": {"mode": "palette-classic"},"custom": {"axisLabel": "seconds","drawStyle": "line","fillOpacity": 10,"lineWidth": 2,"showPoints": "never"},"unit": "s"},"overrides": []},"gridPos": {"h": 9, "w": 12, "x": 0, "y": 0},"id": 1,"options": {"legend": {"calcs": ["mean", "max"], "displayMode": "table", "placement": "bottom"},"tooltip": {"mode": "multi"}},"title": "DistilBERT Inference Latency (p50 / p95 / p99)","targets": [{"expr": "histogram_quantile(0.50, sum by (le) (rate(ai_classifier_inference_latency_seconds_bucket[5m])))","legendFormat": "p50","refId": "A"},{"expr": "histogram_quantile(0.95, sum by (le) (rate(ai_classifier_inference_latency_seconds_bucket[5m])))","legendFormat": "p95","refId": "B"},{"expr": "histogram_quantile(0.99, sum by (le) (rate(ai_classifier_inference_latency_seconds_bucket[5m])))","legendFormat": "p99","refId": "C"}],"type": "timeseries"},{"datasource": {"type": "prometheus","uid": "${DS_PROMETHEUS}"},"fieldConfig": {"defaults": {"color": {"mode": "palette-classic"},"custom": {"axisLabel": "req/s","drawStyle": "line","fillOpacity": 10,"lineWidth": 2,"showPoints": "never"},"unit": "reqps"},"overrides": []},"gridPos": {"h": 9, "w": 12, "x": 12, "y": 0},"id": 2,"options": {"legend": {"calcs": ["mean"], "displayMode": "table", "placement": "bottom"},"tooltip": {"mode": "multi"}},"title": "Classifier Request Rate (by status)","targets": [{"expr": "sum by (status) (rate(ai_classifier_inference_requests_total[1m]))","legendFormat": "{{status}}","refId": "A"}],"type": "timeseries"},{"datasource": {"type": "prometheus","uid": "${DS_PROMETHEUS}"},"fieldConfig": {"defaults": {"color": {"mode": "palette-classic"},"custom": {"axisLabel": "tokens/s","drawStyle": "line","fillOpacity": 10,"lineWidth": 2,"showPoints": "never"},"unit": "short"},"overrides": []},"gridPos": {"h": 9, "w": 12, "x": 0, "y": 9},"id": 3,"options": {"legend": {"calcs": ["mean", "max"], "displayMode": "table", "placement": "bottom"},"tooltip": {"mode": "multi"}},"title": "Token Throughput (input tokens / sec)","targets": [{"expr": "sum by (model) (rate(ai_classifier_input_tokens_total[1m]))","legendFormat": "{{model}}","refId": "A"}],"type": "timeseries"},{"datasource": {"type": "prometheus","uid": "${DS_PROMETHEUS}"},"fieldConfig": {"defaults": {"color": {"mode": "palette-classic"},"custom": {"axisLabel": "bytes","drawStyle": "line","fillOpacity": 10,"lineWidth": 2,"showPoints": "never"},"unit": "decbytes"},"overrides": []},"gridPos": {"h": 9, "w": 12, "x": 12, "y": 9},"id": 4,"options": {"legend": {"calcs": ["mean", "max"], "displayMode": "table", "placement": "bottom"},"tooltip": {"mode": "multi"}},"title": "Process Memory (RSS)","targets": [{"expr": "process_resident_memory_bytes","legendFormat": "{{instance}}","refId": "A"}],"type": "timeseries"},{"datasource": {"type": "prometheus","uid": "${DS_PROMETHEUS}"},"fieldConfig": {"defaults": {"color": {"mode": "palette-classic"},"custom": {"axisLabel": "CPU seconds/sec","drawStyle": "line","fillOpacity": 10,"lineWidth": 2,"showPoints": "never"},"unit": "percentunit"},"overrides": []},"gridPos": {"h": 9, "w": 24, "x": 0, "y": 18},"id": 5,"options": {"legend": {"calcs": ["mean", "max"], "displayMode": "table", "placement": "bottom"},"tooltip": {"mode": "multi"}},"title": "Process CPU Usage","targets": [{"expr": "rate(process_cpu_seconds_total[1m])","legendFormat": "{{instance}}","refId": "A"}],"type": "timeseries"}],"refresh": "10s","schemaVersion": 38,"style": "dark","tags": ["helpdesk-ai", "fastapi", "ai-inference", "prometheus"],"templating": {"list": [{"current": {"selected": false, "text": "Prometheus", "value": "Prometheus"},"hide": 0,"includeAll": false,"label": "Datasource","multi": false,"name": "DS_PROMETHEUS","options": [],"query": "prometheus","refresh": 1,"regex": "","skipUrlSync": false,"type": "datasource"}]},"time": {"from": "now-1h", "to": "now"},"timepicker": {},"timezone": "","title": "HELPDESK.AI — Service Telemetry","uid": "helpdesk-ai-telemetry","version": 1,"weekStart": ""}
21 unmodified lines2223242521 unmodified linespytest-asynciohttpxcryptography>=42.0.021 unmodified lines22232425262721 unmodified linespytest-asynciohttpxcryptography>=42.0.0websockets>=12.0prometheus-client>=0.19.0
Frontend/src/admin/pages/AdminDashboard.jsx+48-24
Frontend/src/hooks/useWebSocket.jsAdded+207
Frontend/src/store/ticketStore.js+41-6
MobileApp/App.js+77-18
MobileApp/metro.config.jsAdded+8
MobileApp/package-lock.json+1-1
MobileApp/package.json+1-1
backend/main.py+274-24
backend/requirements.txt+2
backend/services/classifier_service.py+26-5
backend/services/gemini_service.py+5-1
backend/services/spam_service.pyAdded+156
deploy/monitoring/grafana_dashboard.json+155-87
requirements.txt+2