U
    H:h4                     @   sh  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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(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,Z0edgeej1gdd Z2edgeej1gdd Z3d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NotificationPreferenceNotificationSubscriptionNotificationHistory)NotificationService)process_notificationsend_notification_via_rule)NotificationAPIThrottle   )NotificationChannelSerializerNotificationTemplateSerializerNotificationSerializerNotificationRuleSerializerNotificationStatsSerializer NotificationPreferenceSerializer"NotificationSubscriptionSerializerNotificationHistorySerializerc                   @   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.   @/var/www/html/JingleDetector/src/apps/notifications/api/views.pyperform_create0   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)r5   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_servicer5   er.   r.   r/   test4   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orderingr0   r   rB   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getr2   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)subjectr6   sample_contextr7   zTemplate rendering failed: r8   N)
r9   r
   nowrender_subjectrender_messager   r;   r<   r   r:   )r,   r*   r>   templater]   Zrendered_subjectZrendered_messagerA   r.   r.   r/   previewa   s.    	


 z#NotificationTemplateViewSet.preview)N)rC   rD   rE   rF   r   rG   rH   rJ   r   rK   r   rL   r   r   rM   r	   rN   rO   search_fieldsrP   rQ   r   rb   r.   r.   r.   r/   rR   O   s   
rR   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.
    r?   ra   r   r(   sent_at-created_atTr1   r2   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.r7   zNotification cannot be retriedr8   TzNotification queued for retryr5   r6   task_idN)r9   	can_retryr   r   r:   r   delayr<   idHTTP_202_ACCEPTEDr;   r=   )r,   r*   r>   notificationtaskrA   r.   r.   r/   retry   s0      zNotificationViewSet.retryFrT   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	completedr8   failedpendingr   d   F)r   Zsent_at__isnullT)r&   )r?   )totalsentsuccess_raterf   N
   channel__nametemplate__namer   r(   re   r   )total_notificationssent_notificationsfailed_notificationspending_notificationsdelivery_rateavg_delivery_timechannel_performancerecent_activity)r
   r^   r   rJ   countfilterexistsre   r(   appendtotal_secondssumlenr   rG   r'   listorder_byvaluesroundr   r   data)r,   r*   r^   Zlast_24hZlast_7dr   Znotifications_24hr   r   r   r   Zcompleted_notificationsr   Zdelivery_timesrm   deltar   r?   Zchannel_notificationsrz   r{   r   Z
stats_datar-   r.   r.   r/   
statistics   sv    
   
zNotificationViewSet.statistics)N)rC   rD   rE   rF   r   rG   rH   rI   rJ   r   rK   r   rL   r   r   rM   r	   rN   rO   rP   rQ   r   ro   r   r.   r.   r.   r/   rd      s    
 
rd   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.
    r?   ra   
event_typer&   r'   priorityr(   Tr1   r2   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)rV   r   	timestamp	test_mode)r   contextz!Test notification sent for rule: rg   r8   r7   N)r9   r   r
   r^   r   rj   r   r'   rk   r   rl   r;   r<   r=   )r,   r*   r>   ruler]   rn   rA   r.   r.   r/   rB   
  s2    
 zNotificationRuleViewSet.test)N)rC   rD   rE   rF   r   rG   rH   rI   rJ   r   rK   r   rL   r   r   rM   r	   rN   rO   rP   rQ   r   rB   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   r7   zMissing required field: r8   )rk   scheduled_at)r?   ra   r   r   T)r5   notification_idrh   zChannel or template not foundN)r   r   r   r:   r   rG   rT   r   r   creater
   r^   r   rj   r<   rk   rl   DoesNotExistHTTP_404_NOT_FOUNDr;   r=   )r*   required_fieldsfieldr?   ra   rm   rn   rA   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.
       )minutesrt   r?   ra   rf   N   T)many)r
   r^   r   r   rG   r   rI   r   r   r   r   )r*   recent_timerecent_notificationsr-   r.   r.   r/   live_notifications\  s    	 r   N)4rF   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   r   r   r   servicesr   tasksr   r   Zapps.core.throttlingr   serializersr   r   r   r   r   r    r!   r"   ModelViewSetr#   rR   rd   r   rL   r   r   r.   r.   r.   r/   <module>   s,   $(01w3
0
