U
    h4                     @   sP  d Z ddlmZmZmZ ddlmZmZmZ ddl	m
Z
 ddlmZ ddlmZ ddlmZmZ ddlmZ d	d
lmZmZmZmZ d	dlmZ d	dlmZmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z% G dd dej&Z'G dd dej&Z(G dd dej&Z)G dd dej&Z*edgeej+gdd Z,edgeej+gdd Z-dS )z
REST API Views for Notifications Application

This module contains Django REST Framework views for managing
notifications, channels, templates, and rules through a RESTful API.
    )viewsetsstatuspermissions)api_viewpermission_classesaction)Response)DjangoFilterBackend)timezone)CountAvg)	timedelta   )NotificationChannelNotificationTemplateNotificationNotificationRule)NotificationService)process_notificationsend_notification_via_rule)NotificationAPIThrottle   )NotificationChannelSerializerNotificationTemplateSerializerNotificationSerializerNotificationRuleSerializerNotificationStatsSerializerc                   @   sn   e Zd ZdZej dZe	Z
ejgZegZegZddgZddgZdgZdd Zed	d
gddddZdS )NotificationChannelViewSetz
    ViewSet for managing notification channels.
    
    Provides CRUD operations for notification channels with
    configuration validation and testing capabilities.
    
created_bychannel_type	is_activename
created_atc                 C   s   |j | jjd dS )z,Set the current user as the channel creator.)r   N)saverequestuser)self
serializer r(   A/var/www/html/StreamProcessor/src/apps/notifications/api/views.pyperform_create+   s    z)NotificationChannelViewSet.perform_createTpostdetailmethodsNc              
   C   s   |   }zFt }||}|r6tdd|j dW S tdddtjdW S W n> tk
r } z tdt|dtj	d W Y S d}~X Y nX dS )	z.Send a test notification through this channel.TzTest notification sent via )successmessageFz Failed to send test notification)r/   errorr   N)

get_objectr   Zsend_test_notificationr   r!   r   HTTP_400_BAD_REQUEST	ExceptionstrHTTP_500_INTERNAL_SERVER_ERROR)r&   r$   pkchannelnotification_servicer/   er(   r(   r)   test/   s,    


zNotificationChannelViewSet.test)N)__name__
__module____qualname____doc__r   objectsallselect_relatedquerysetr   serializer_classr   IsAuthenticatedr   r   throttle_classesr	   filter_backendsfilterset_fieldsordering_fieldsorderingr*   r   r<   r(   r(   r(   r)   r      s   r   c                   @   sh   e Zd ZdZej ZeZ	e
jgZegZegZddgZddgZddgZdgZeddgddd
dZd	S )NotificationTemplateViewSetz
    ViewSet for managing notification templates.
    
    Provides CRUD operations for templates with usage statistics
    and validation capabilities.
    template_typer    r!   r"   Tgetr,   Nc              
   C   s   |   }dddt ddd}z&||}||}t|||dW S  tk
r } z$tdd	t| itj	d
 W Y S d}~X Y nX dS )z"Preview template with sample data.zSample ChannelzSample Jinglegffffff?   zUS-EAST)channel_namejingle_nameconfidence_scoredetection_timeduration_secondsregion)subjectr0   sample_contextr1   zTemplate rendering failed: r2   N)
r3   r
   nowrender_subjectrender_messager   r5   r6   r   r4   )r&   r$   r8   templaterW   Zrendered_subjectZrendered_messager;   r(   r(   r)   preview\   s.    	


 z#NotificationTemplateViewSet.preview)N)r=   r>   r?   r@   r   rA   rB   rD   r   rE   r   rF   r   r   rG   r	   rH   rI   search_fieldsrJ   rK   r   r\   r(   r(   r(   r)   rL   J   s   
rL   c                   @   s   e Zd ZdZej ddZe	Z
ejgZegZegZdddgZddgZdgZedd	gd
dddZeddgd
dd ZdS )NotificationViewSetz
    ViewSet for managing notifications.
    
    Provides access to notification history with filtering
    and retry capabilities.
    r9   r[   r   r"   sent_at-created_atTr+   r,   Nc              
   C   s   |   }| s"tdditjdS z*tt|j}tdd|jdtj	dW S  t
k
r } ztdt|itjd W Y S d}~X Y nX dS )zRetry a failed notification.r1   zNotification cannot be retriedr2   TzNotification queued for retryr/   r0   task_idN)r3   	can_retryr   r   r4   r   delayr6   idHTTP_202_ACCEPTEDr5   r7   )r&   r$   r8   notificationtaskr;   r(   r(   r)   retry   s0      zNotificationViewSet.retryFrN   c              	   C   s  t  }|tdd }|tdd }| j }| jj|d }| jjdd }| jjdd }| jjd	d }	d
}
|d
kr|| d }
| jjddd}d
}| rg }|D ]*}|jr|jr|j|j }|	|
  q|rt|t| }i }tjjddD ]T}| jj|d}| }|jdd }|||d
krH|| d nd
d||j< qt| jj|dddd ddddd}||||	t|
dt|d||d}t|}t|jS )z#Get notification system statistics.   )hours   )dayscreated_at__gte	completedr2   failedpendingr   d   F)r   Zsent_at__isnullT)r    )r9   )totalsentsuccess_rater`   N
   channel__nametemplate__namer   r"   r_   r   )total_notificationssent_notificationsfailed_notificationspending_notificationsdelivery_rateavg_delivery_timechannel_performancerecent_activity)r
   rX   r   rD   countfilterexistsr_   r"   appendtotal_secondssumlenr   rA   r!   listorder_byvaluesroundr   r   data)r&   r$   rX   Zlast_24hZlast_7drz   Znotifications_24hr{   r|   r}   r~   Zcompleted_notificationsr   Zdelivery_timesrg   deltar   r9   Zchannel_notificationsrt   ru   r   Z
stats_datar'   r(   r(   r)   
statistics   sv    
   
zNotificationViewSet.statistics)N)r=   r>   r?   r@   r   rA   rB   rC   rD   r   rE   r   rF   r   r   rG   r	   rH   rI   rJ   rK   r   ri   r   r(   r(   r(   r)   r^   {   s    
 
r^   c                   @   sn   e Zd ZdZej ddZe	Z
ejgZegZegZdddgZdddgZddgZed	d
gddddZdS )NotificationRuleViewSetz
    ViewSet for managing notification rules.
    
    Provides CRUD operations for rules with testing
    and activation capabilities.
    r9   r[   
event_typer    r!   priorityr"   Tr+   r,   Nc              
   C   s   |   }d|jt dd}z2tj|j|d}tdd|j |jdt	j
dW S  tk
r } ztdt|it	jd W Y S d	}~X Y nX d	S )
z*Test a notification rule with sample data.zTest ChannelT)rP   r   	timestamp	test_mode)r   contextz!Test notification sent for rule: ra   r2   r1   N)r3   r   r
   rX   r   rd   r   r!   re   r   rf   r5   r6   r7   )r&   r$   r8   rulerW   rh   r;   r(   r(   r)   r<     s2    
 zNotificationRuleViewSet.test)N)r=   r>   r?   r@   r   rA   rB   rC   rD   r   rE   r   rF   r   r   rG   r	   rH   rI   rJ   rK   r   r<   r(   r(   r(   r)   r      s   
 

r   POSTc              
   C   s>  dddg}|D ]*}|| j krtdd| itjd  S qztjj| j d d}tjj| j d d}tjj	||| j d | j dt
 d	}tt|j}td
t|j|jdtjdW S  tjtjfk
 r } ztdditjd W Y S d}~X Y n> tk
r8 } ztdt|itjd W Y S d}~X Y nX dS )z
    API endpoint to send custom notifications.
    
    Allows sending notifications with custom content through
    specified channels and templates.
    
channel_idtemplate_idr   r1   zMissing required field: r2   )re   scheduled_at)r9   r[   r   r   T)r/   Znotification_idrb   zChannel or template not foundN)r   r   r   r4   r   rA   rN   r   r   creater
   rX   r   rd   r6   re   rf   DoesNotExistHTTP_404_NOT_FOUNDr5   r7   )r$   required_fieldsfieldr9   r[   rg   rh   r;   r(   r(   r)   send_notification%  sP    	

   r   GETc                 C   sL   t  tdd }tjj|dddddd }t|d	d
}t	|j
S )z|
    API endpoint for live notification updates.
    
    Returns recent notifications for real-time dashboard updates.
       )minutesrn   r9   r[   r`   N   T)many)r
   rX   r   r   rA   r   rC   r   r   r   r   )r$   recent_timerecent_notificationsr'   r(   r(   r)   live_notificationsW  s    	 r   N).r@   rest_frameworkr   r   r   rest_framework.decoratorsr   r   r   rest_framework.responser   Zdjango_filters.rest_frameworkr	   django.utilsr
   django.db.modelsr   r   datetimer   modelsr   r   r   r   servicesr   tasksr   r   Zapps.core.throttlingr   serializersr   r   r   r   r   ModelViewSetr   rL   r^   r   rF   r   r   r(   r(   r(   r)   <module>   s,   01w3
0
