Spaces:
3SCError404
/
Paused

File size: 9,032 Bytes
5eb4857
6130eba
5eb4857
 
 
 
 
 
b7980f7
5eb4857
 
 
 
 
 
 
a27a4ab
01dccd3
5eb4857
a27a4ab
b7980f7
 
a27a4ab
5eb4857
 
 
 
01dccd3
a27a4ab
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6130eba
 
 
 
 
 
 
 
 
 
 
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
from typing import Any, Dict, List, Optional
import uuid
from uuid import UUID
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, desc
from core.logging import get_logger
from models.user import User, UserRole
from models.user_workspace import UserWorkspace
from models.kb_article import KBArticle
from models.kb_article_chunk import KBArticleChunk

logger = get_logger(__name__)

async def get_available_agents(db: AsyncSession, workspace_id: UUID) -> List[User]:
    """
    Fetch all active INTERNAL staff members for the given workspace context.
    Strictly restricted to users with a direct UserWorkspace relationship.
    """
    # 1. Standard approach: Join with UserWorkspace and strictly whitelist staff roles
    stmt = select(User).join(UserWorkspace).where(
        UserWorkspace.workspace_id == workspace_id,
        UserWorkspace.role.in_([UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]), # INTERNAL ONLY
        User.is_active == True,
        User.deleted_at.is_(None)
    )
    result = await db.execute(stmt)
    verified_staff = list(result.scalars().all())
    
    logger.debug(f"Fetched {len(verified_staff)} verified staff agents for workspace {workspace_id}")
    return verified_staff

async def update_ticket_ai_metadata(db: AsyncSession, ticket_id: UUID, metadata: Dict[str, Any]):
    """
    Utility to update ticket AI metadata in the DB.
    """
    from models.ticket import Ticket
    stmt = select(Ticket).where(Ticket.id == ticket_id)
    result = await db.execute(stmt)
    ticket = result.scalar_one_or_none()
    if ticket:
        # Merge new metadata
        existing = ticket.ai_metadata or {}
        existing.update(metadata)
        ticket.ai_metadata = existing
        db.add(ticket)

async def semantic_search_kb(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]:
    """
    Search KBArticles by embedding.
    """
    from models.kb_article import KBArticle
    stmt = select(KBArticle).where(
        KBArticle.workspace_id == workspace_id,
        KBArticle.deleted_at.is_(None),
        KBArticle.duplicate_of_id.is_(None)
    ).order_by(
        KBArticle.embedding.cosine_distance(query_embedding)
    ).limit(limit)
    logger.info(f"AI: Semantic search KB for workspace {workspace_id}")
    result = await db.execute(stmt)
    return list(result.scalars().all())

async def semantic_search_past_tickets(db: AsyncSession, workspace_id: UUID, query_embedding: List[float], limit: int = 3) -> List[Any]:
    """
    Search resolved Tickets by embedding.
    """
    from models.ticket import Ticket, TicketStatus
    stmt = select(Ticket).where(
        Ticket.workspace_id == workspace_id,
        Ticket.status == TicketStatus.RESOLVED,
        Ticket.embedding.isnot(None),
        Ticket.deleted_at.is_(None)
    ).order_by(
        Ticket.embedding.cosine_distance(query_embedding)
    ).limit(limit)
    logger.info(f"AI: Semantic search past tickets for workspace {workspace_id}")
    result = await db.execute(stmt)
    return list(result.scalars().all())

async def hybrid_search_kb_internal(
    db: AsyncSession, 
    workspace_id: UUID, 
    query_text: str, 
    query_embedding: List[float],
    threshold: float = 0.2,
    limit: int = 5
) -> List[Dict[str, Any]]:
    """
    Internal utility for hybrid search (FTS + Vector) to be used by AI nodes.
    Returns a list of dictionaries containing the article object and its hybrid score.
    """
    # 1. Semantic Chunk Search
    semantic_stmt = (
        select(
            KBArticle,
            (1 - KBArticleChunk.embedding.cosine_distance(query_embedding)).label("sim_score")
        )
        .join(KBArticleChunk, KBArticle.id == KBArticleChunk.article_id)
        .where(
            KBArticle.workspace_id == workspace_id,
            KBArticle.deleted_at.is_(None),
            KBArticle.is_published == True,
            KBArticle.duplicate_of_id.is_(None)
        )
        .order_by(desc("sim_score"))
        .limit(20)
    )
    semantic_res = await db.execute(semantic_stmt)
    
    # 2. Keyword FTS Search
    fts_stmt = (
        select(
            KBArticle,
            func.ts_rank(
                func.to_tsvector('english', KBArticle.title + " " + KBArticle.content),
                func.plainto_tsquery('english', query_text)
            ).label("fts_rank")
        )
        .where(
            KBArticle.workspace_id == workspace_id,
            KBArticle.deleted_at.is_(None),
            KBArticle.is_published == True,
            KBArticle.duplicate_of_id.is_(None),
            func.to_tsvector('english', KBArticle.title + " " + KBArticle.content).op("@@")(func.plainto_tsquery('english', query_text))
        )
        .order_by(desc("fts_rank"))
        .limit(20)
    )
    fts_res = await db.execute(fts_stmt)

    # 3. Score Fusion
    article_scores = {}
    for article, sim in semantic_res.all():
        if article.id not in article_scores:
            article_scores[article.id] = {"obj": article, "semantic": sim, "fts": 0.0}
        else:
            article_scores[article.id]["semantic"] = max(article_scores[article.id]["semantic"], sim)

    for article, rank in fts_res.all():
        if article.id not in article_scores:
            article_scores[article.id] = {"obj": article, "semantic": 0.0, "fts": rank}
        else:
            article_scores[article.id]["fts"] = rank

    final_results = []
    for art_id, data in article_scores.items():
        score = (data["semantic"] * 0.7) + (min(data["fts"], 1.0) * 0.3)
        if score >= threshold:
            final_results.append({"article": data["obj"], "score": score})

    final_results.sort(key=lambda x: x["score"], reverse=True)
    return final_results[:limit]


async def get_workspace_manager(db: AsyncSession, workspace_id: UUID) -> Optional[User]:
    """Find the best person to notify in a workspace (Lead first, then Admin)."""
    # 1. Try to find a Lead within this workspace
    stmt = (
        select(User)
        .join(UserWorkspace)
        .where(
            UserWorkspace.workspace_id == workspace_id,
            UserWorkspace.role == UserRole.SC_LEAD,
            User.is_active == True,
            User.deleted_at.is_(None)
        )
        .limit(1)
    )
    res = await db.execute(stmt)
    manager = res.scalar_one_or_none()
    if manager:
        return manager
        
    # 2. Fallback to an Admin associated with this workspace
    admin_stmt = (
        select(User)
        .join(UserWorkspace)
        .where(
            UserWorkspace.workspace_id == workspace_id,
            UserWorkspace.role == UserRole.SC_ADMIN,
            User.is_active == True,
            User.deleted_at.is_(None)
        )
        .limit(1)
    )
    res = await db.execute(admin_stmt)
    manager = res.scalar_one_or_none()
    if manager:
        return manager

    # 3. Final Fallback: The Global Super Admin (Platform level)
    global_admin_stmt = (
        select(User)
        .where(
            User.global_role == UserRole.SC_ADMIN,
            User.is_active == True,
            User.deleted_at.is_(None)
        )
        .limit(1)
    )
    res = await db.execute(global_admin_stmt)
    return res.scalar_one_or_none()


import json
class CustomEncoder(json.JSONEncoder):
    """JSON encoder that handles UUID objects by converting them to strings."""
    def default(self, obj):
        if isinstance(obj, UUID):
            return str(obj)
        if isinstance(obj, datetime):
            return obj.isoformat()
        return super().default(obj)


def sanitize_for_db(data: Any) -> Any:
    """Recursively converts UUIDs and datetimes to strings for DB storage."""
    if isinstance(data, dict):
        return {k: sanitize_for_db(v) for k, v in data.items()}
    elif isinstance(data, list):
        return [sanitize_for_db(i) for i in data]
    elif isinstance(data, UUID):
        return str(data)
    elif isinstance(data, datetime):
        return data.isoformat()
    return data

def safe_uuid(val: Any) -> Optional[UUID]:
    """Safely attempts to cast a value to UUID. Returns None on failure."""
    if not val:
        return None
    if isinstance(val, UUID):
        return val
    try:
        # Check for common short-codes or hex strings that are not UUIDs
        s_val = str(val).strip()
        if len(s_val) < 32:
            return None
        return UUID(s_val)
    except (ValueError, TypeError, AttributeError):
        return None

def get_deterministic_uuid(val: Any) -> UUID:
    """
    Deterministically maps any input (string, int, etc) to a valid UUID v5.
    Ensures that arq string IDs (like cron tasks) can be stored in our UUID-based DB.
    """
    if isinstance(val, UUID):
        return val
        
    # Use a dedicated namespace for Nexus Worker jobs
    NEXUS_NAMESPACE = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') # DNS Namespace as base
    return uuid.uuid5(NEXUS_NAMESPACE, str(val))