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

from fastapi import APIRouter, HTTPException, Depends, Header
from pydantic import BaseModel
from typing import Optional, List, Dict, Any
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy import update, delete
import logging
import uuid

# Import agents
from agents.monitoring_agent import MonitoringAgent
from agents.forecast_agent import ForecastAgent
from agents.report_agent import ReportAgent
from agents.memory_agent import MemoryAgent

from database.db import get_db
from database.orm import NotificationSettings as NotificationSettingsModel, PushToken, WorkspaceMember, AIInsight, AgentLog
from database import get_current_user_optional, AuthUser

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["notifications"])

# ============================================================================
# MODELS
# ============================================================================

class NotificationSettingsReq(BaseModel):
    email_notifications: Optional[bool] = None
    push_notifications: Optional[bool] = None
    weekly_reports: Optional[bool] = None
    ai_insights: Optional[bool] = None
    severity_threshold: Optional[str] = None
    dnd_start: Optional[str] = None
    dnd_end: Optional[str] = None

class PushSubscription(BaseModel):
    workspace_id: str
    user_id: str
    token: str
    platform: Optional[str] = "web"

class AgentRunRequest(BaseModel):
    workspace_id: str

# ============================================================================
# AUTH HELPER
# ============================================================================

async def get_current_user_id(
    current_user: Optional[AuthUser] = Depends(get_current_user_optional)
) -> str:
    """Extract and validate user_id from auth"""
    if current_user:
        return current_user.id
    logger.warning("No valid authorization found - using fallback for development")
    return "dev-user-fallback"

async def verify_workspace_membership(user_id: str, workspace_id: str, db: AsyncSession) -> bool:
    if user_id == "dev-user-fallback": return True
    stmt = select(WorkspaceMember).where(
        WorkspaceMember.user_id == uuid.UUID(user_id),
        WorkspaceMember.workspace_id == workspace_id
    )
    result = await db.scalar(stmt)
    return result is not None

# ============================================================================
# NOTIFICATION SETTINGS ENDPOINTS
# ============================================================================

@router.get("/settings/{workspace_id}/{user_id}")
async def get_settings(
    workspace_id: str,
    user_id: str,
    current_user_id: str = Depends(get_current_user_id),
    db: AsyncSession = Depends(get_db)
):
    if current_user_id != user_id and current_user_id != "dev-user-fallback":
        raise HTTPException(status_code=403, detail="Access denied")
        
    stmt = select(NotificationSettingsModel).where(
        NotificationSettingsModel.workspace_id == workspace_id,
        NotificationSettingsModel.user_id == uuid.UUID(user_id)
    )
    settings = await db.scalar(stmt)
    
    if not settings:
        return {
            'workspace_id': workspace_id,
            'user_id': user_id,
            'email_notifications': True,
            'push_notifications': False,
            'weekly_reports': True,
            'ai_insights': True,
            'severity_threshold': 'medium',
            'dnd_start': None,
            'dnd_end': None
        }
        
    return {
        'workspace_id': settings.workspace_id,
        'user_id': str(settings.user_id),
        'email_notifications': settings.email_notifications,
        'push_notifications': settings.push_notifications,
        'weekly_reports': settings.weekly_reports,
        'ai_insights': settings.ai_insights,
        'severity_threshold': settings.severity_threshold,
        'dnd_start': settings.dnd_start,
        'dnd_end': settings.dnd_end
    }

@router.patch("/settings/{workspace_id}/{user_id}")
async def update_settings(
    workspace_id: str,
    user_id: str,
    settings: NotificationSettingsReq,
    current_user_id: str = Depends(get_current_user_id),
    db: AsyncSession = Depends(get_db)
):
    if current_user_id != user_id and current_user_id != "dev-user-fallback":
        raise HTTPException(status_code=403, detail="Access denied")
        
    stmt = select(NotificationSettingsModel).where(
        NotificationSettingsModel.workspace_id == workspace_id,
        NotificationSettingsModel.user_id == uuid.UUID(user_id)
    )
    db_settings = await db.scalar(stmt)
    
    if not db_settings:
        db_settings = NotificationSettingsModel(workspace_id=workspace_id, user_id=uuid.UUID(user_id))
        db.add(db_settings)
        
    if settings.email_notifications is not None: db_settings.email_notifications = settings.email_notifications
    if settings.push_notifications is not None: db_settings.push_notifications = settings.push_notifications
    if settings.weekly_reports is not None: db_settings.weekly_reports = settings.weekly_reports
    if settings.ai_insights is not None: db_settings.ai_insights = settings.ai_insights
    if settings.severity_threshold is not None: db_settings.severity_threshold = settings.severity_threshold
    if settings.dnd_start is not None: db_settings.dnd_start = settings.dnd_start
    if settings.dnd_end is not None: db_settings.dnd_end = settings.dnd_end
    
    await db.commit()
    return {
        'workspace_id': db_settings.workspace_id,
        'user_id': str(db_settings.user_id),
        'email_notifications': db_settings.email_notifications,
        'push_notifications': db_settings.push_notifications,
        'weekly_reports': db_settings.weekly_reports,
        'ai_insights': db_settings.ai_insights,
        'severity_threshold': db_settings.severity_threshold,
        'dnd_start': db_settings.dnd_start,
        'dnd_end': db_settings.dnd_end
    }

@router.post("/push/subscribe")
async def subscribe_push(
    subscription: PushSubscription,
    current_user_id: str = Depends(get_current_user_id),
    db: AsyncSession = Depends(get_db)
):
    if current_user_id != subscription.user_id and current_user_id != "dev-user-fallback":
        raise HTTPException(status_code=403, detail="Access denied")
        
    if not await verify_workspace_membership(current_user_id, subscription.workspace_id, db):
        raise HTTPException(status_code=403, detail="Not a member of this workspace")
        
    token = PushToken(
        workspace_id=subscription.workspace_id,
        user_id=uuid.UUID(subscription.user_id),
        token=subscription.token,
        platform=subscription.platform
    )
    db.add(token)
    await db.commit()
    
    return {"message": "Push subscription successful", "id": str(token.id)}

@router.delete("/push/unsubscribe/{token_id}")
async def unsubscribe_push(
    token_id: str,
    current_user_id: str = Depends(get_current_user_id),
    db: AsyncSession = Depends(get_db)
):
    stmt = select(PushToken).where(PushToken.id == uuid.UUID(token_id))
    token = await db.scalar(stmt)
    
    if not token or (str(token.user_id) != current_user_id and current_user_id != "dev-user-fallback"):
        raise HTTPException(status_code=403, detail="Access denied")
        
    await db.delete(token)
    await db.commit()
    
    return {"message": "Unsubscribed successfully"}

@router.get("/insights/{workspace_id}")
async def get_insights(
    workspace_id: str,
    limit: int = 20,
    current_user_id: str = Depends(get_current_user_id),
    db: AsyncSession = Depends(get_db)
):
    if not await verify_workspace_membership(current_user_id, workspace_id, db):
        raise HTTPException(status_code=403, detail="Not a member of this workspace")
        
    stmt = select(AIInsight).where(AIInsight.workspace_id == workspace_id).order_by(AIInsight.created_at.desc()).limit(limit)
    result = await db.execute(stmt)
    insights = result.scalars().all()
    
    return [{
        "id": str(i.id),
        "workspace_id": i.workspace_id,
        "title": i.title,
        "description": i.description,
        "insight_type": i.insight_type,
        "created_at": i.created_at
    } for i in insights]

@router.post("/agents/run/{agent_name}")
async def run_agent(
    agent_name: str,
    request: AgentRunRequest,
    current_user_id: str = Depends(get_current_user_id),
    db: AsyncSession = Depends(get_db)
):
    if current_user_id != "dev-user-fallback":
        stmt = select(WorkspaceMember).where(
            WorkspaceMember.workspace_id == request.workspace_id,
            WorkspaceMember.user_id == uuid.UUID(current_user_id)
        )
        membership = await db.scalar(stmt)
        if not membership or membership.role not in ['admin', 'owner']:
            raise HTTPException(status_code=403, detail="Admin access required")
            
    agent = None
    if agent_name == 'MonitoringAgent':
        agent = MonitoringAgent()
    elif agent_name == 'ForecastAgent':
        agent = ForecastAgent()
    elif agent_name == 'ReportAgent':
        agent = ReportAgent()
    elif agent_name == 'MemoryAgent':
        agent = MemoryAgent()
    else:
        raise HTTPException(status_code=400, detail=f"Unknown agent: {agent_name}")
        
    import asyncio
    asyncio.create_task(agent.run(request.workspace_id))
    
    return {"message": f"{agent_name} triggered for workspace {request.workspace_id}"}

@router.get("/agent-logs/{workspace_id}")
async def get_agent_logs(
    workspace_id: str,
    limit: int = 50,
    current_user_id: str = Depends(get_current_user_id),
    db: AsyncSession = Depends(get_db)
):
    if current_user_id != "dev-user-fallback":
        stmt = select(WorkspaceMember).where(
            WorkspaceMember.workspace_id == workspace_id,
            WorkspaceMember.user_id == uuid.UUID(current_user_id)
        )
        membership = await db.scalar(stmt)
        if not membership or membership.role not in ['admin', 'owner']:
            raise HTTPException(status_code=403, detail="Admin access required")
            
    stmt = select(AgentLog).where(AgentLog.workspace_id == workspace_id).order_by(AgentLog.executed_at.desc()).limit(limit)
    result = await db.execute(stmt)
    logs = result.scalars().all()
    
    return [{
        "id": str(l.id),
        "workspace_id": l.workspace_id,
        "agent_name": l.agent_name,
        "status": l.status,
        "message": l.message,
        "executed_at": l.executed_at
    } for l in logs]

# Export router
__all__ = ['router']