U
    hr2                     @   s   d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
mZ eeG dd dejZee	G dd	 d	ejZee
G d
d dejZeeG dd dejZdS )z
Django Admin Configuration for Notifications Application

This module configures the Django admin interface for notification
management, channel configuration, and delivery monitoring.
    )admin)timezone)format_html)NotificationChannelNotificationTemplateNotificationNotificationRulec                       s   e Zd ZdZdddddddgZddddgZddgZd	d
difddddfdd
difddddffZddgZddgZ	dd Z
de
_ fddZ  ZS )NotificationChannelAdminz
    Admin interface for NotificationChannel model.
    
    Provides management of notification delivery channels including
    configuration, rate limiting, and status monitoring.
    namechannel_type	is_active
rate_limitget_recent_deliveries
created_by
created_atzChannel Informationfields)r
   r   r   Configuration)configurationz7Channel-specific configuration parameters (JSON format)r   descriptionzDelivery Settings)r   retry_attemptstimeout_secondsMetadata)r   collapser   classes
updated_atc           
      C   s   ddl m} t |dd }|jj|d}| }|jdd }|jdd }|dkr|| d	 }|d
krtdn|dkrdnd}	td|	|||S tdS )z0Get recent delivery statistics for this channel.r   )	timedelta   )hoursZcreated_at__gte	completedstatusfailedd   Z   greenF   orangeredz8<span style="color: {};">{}/{} sent<br/>({:.1f}%)</span>z4<span style="color: gray;">No recent activity</span>)datetimer   r   nownotificationsfiltercountr   )
selfobjr   Zrecent_timeZrecent_notificationstotalsentr%   Zsuccess_ratecolor r6   =/var/www/html/StreamProcessor/src/apps/notifications/admin.pyr   A   s"    z.NotificationChannelAdmin.get_recent_deliverieszRecent Deliveries (24h)c                    s   t  |dS )&Optimize queryset with select_related.r   superget_querysetselect_relatedr1   request	__class__r6   r7   r;   \   s    z%NotificationChannelAdmin.get_queryset)__name__
__module____qualname____doc__list_displaylist_filtersearch_fields	fieldsetsreadonly_fieldsorderingr   short_descriptionr;   __classcell__r6   r6   r?   r7   r	      sN   	           r	   c                   @   s   e Zd ZdZddddddgZdddgZdddd	gZd
ddifdddifddddffZddgZddgZ	dd Z
de
_dd Zde_dS )NotificationTemplateAdminz
    Admin interface for NotificationTemplate model.
    
    Provides management of notification message templates including
    content editing, variable management, and compatibility settings.
    r
   template_typer   get_usage_countget_compatible_channelsr   subject_templatemessage_templatezTemplate Informationr   )r
   rN   r   Message Content)rQ   rR   zTemplate Configuration)	variableschannel_typesz>Available variables and compatible channel types (JSON format)r   r   c                 C   sH   |j  }|j jt tjdd d }|dkr@td||S tdS )z4Get the number of notifications using this template.   )daysr!   r   z*{} total<br/><small>({} this week)</small>z*<span style="color: gray;">Not used</span>)r.   r0   r/   r   r-   r   r   )r1   r2   r0   Zrecent_countr6   r6   r7   rO      s    

z)NotificationTemplateAdmin.get_usage_countZUsagec                 C   sB   |j r:d|j }td|t|dkr4|dd d n|S tdS )z!Display compatible channel types.z, z<span title="{}">{}</span>   N...z.<span style="color: gray;">All channels</span>)rU   joinr   len)r1   r2   Zchannel_listr6   r6   r7   rP      s    (z1NotificationTemplateAdmin.get_compatible_channelszCompatible ChannelsN)rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rO   rK   rP   r6   r6   r6   r7   rM   a   sH   	           rM   c                       s   e Zd ZdZdddddddd	gZdddddgZdd
dddgZdddifdddifdddifdddifddddffZdddd	gZdgZ	dd Z
d e
_d
e
_ fd!d"Zd#d$gZd%d& Zd'e_d(d) Zd*e_  ZS )+NotificationAdminz
    Admin interface for Notification model.
    
    Provides detailed monitoring of individual notifications including
    delivery status, error tracking, and retry management.
    get_notification_infochannel	recipienttemplater$   scheduled_atsent_atdelivery_attemptssubjectmessagechannel__nametemplate__namezNotification Detailsr   )r^   r`   r_   r$   rS   )rd   re   Z
Scheduling)ra   rb   zDelivery Tracking)rc   error_messageexternal_idzTemplate Context)context_datar   r   r   r   z-scheduled_atc                 C   sf   dddddd |jd}t|jdkr:|jd	d d
 n|j}td|pX|jd	d d
 ||j S )z'Get formatted notification information.r*   bluer(   r+   gray)pending
processingr"   r%   	cancelledblackrX   NrY   z:<strong>{}</strong><br/><span style="color: {};">{}</span>)getr$   r[   rd   r   re   title)r1   r2   status_colorZsubject_previewr6   r6   r7   r]      s      &z'NotificationAdmin.get_notification_infor   c                    s   t  |ddS r8   r^   r`   r9   r=   r?   r6   r7   r;      s    zNotificationAdmin.get_querysetretry_failed_notificationsmark_as_cancelledc                 C   sP   |j dd}d}|D ]"}| rd|_|  |d7 }q| |d| d dS )	z,Custom action to retry failed notifications.r%   r#   r   rm      Queued z notifications for retry.N)r/   	can_retryr$   savemessage_user)r1   r>   querysetZfailed_notificationsZretry_countZnotificationr6   r6   r7   ru      s    

z,NotificationAdmin.retry_failed_notificationszRetry failed notificationsc                 C   s0   |j dd}|jdd}| |d| d dS )z.Custom action to cancel pending notifications.rm   r#   ro   z
Cancelled z pending notifications.N)r/   updater{   )r1   r>   r|   Zpending_notificationsZcancelled_countr6   r6   r7   rv     s    
z#NotificationAdmin.mark_as_cancelledzCancel pending notifications)rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   r]   rK   admin_order_fieldr;   actionsru   rv   rL   r6   r6   r?   r7   r\      st   	                     
r\   c                       s   e Zd ZdZdddddddd	gZddddd	gZddd
dgZdddifdddifddddfdddiffZddd	gZddgZ	dd Z
de
_ fddZdgZd d! Zd"e_  ZS )#NotificationRuleAdminz
    Admin interface for NotificationRule model.
    
    Provides management of automatic notification rules including
    event triggering, conditions, and throttling configuration.
    r
   
event_typer^   r`   r   throttle_minutesget_trigger_countlast_triggeredrf   rg   zRule Informationr   )r
   r   r   priorityzNotification Configuration)r^   r`   zTriggering Conditions)
conditionsz7Additional conditions for rule triggering (JSON format)r   Z
Throttling)r   r   r   r   z	-priorityc                 C   s    |j rtd|j dS tdS )z5Get the number of times this rule has been triggered.zE<span style="color: green;">Active</span><br/><small>Last: {}</small>z%m/%d %H:%Mz1<span style="color: gray;">Never triggered</span>)r   r   strftime)r1   r2   r6   r6   r7   r   K  s    
z'NotificationRuleAdmin.get_trigger_countzTrigger Statusc                    s   t  |ddS rt   r9   r=   r?   r6   r7   r;   Y  s    z"NotificationRuleAdmin.get_querysettest_notification_rulec                 C   s   ddl m} d}|jddD ]v}d|jt  d}z||j| |d7 }W q t	k
r } z"| j
|d|j d| d	d
 W 5 d}~X Y qX q|dkr| 
|d| d dS )z)Custom action to test notification rules.rw   )send_notification_via_ruler   T)r   )Z	test_modeZ	rule_name	timestampzFailed to test rule z: ERROR)levelNrx   z test notifications.)tasksr   r/   r
   r   r-   	isoformatdelayr   	Exceptionr{   )r1   r>   r|   r   Z
test_countZruleZtest_contexter6   r6   r7   r   `  s*    

z,NotificationRuleAdmin.test_notification_rulezSend test notifications)rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   r   rK   r;   r   r   rL   r6   r6   r?   r7   r     s\   	                
r   N)rD   Zdjango.contribr   django.utilsr   django.utils.htmlr   Zapps.notifications.modelsr   r   r   r   register
ModelAdminr	   rM   r\   r   r6   r6   r6   r7   <module>   s   PGq