U
    h2                     @   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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NotificationRuleNotificationPreferenceNotificationSubscriptionNotificationHistoryc                       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 r9   </var/www/html/JingleDetector/src/apps/notifications/admin.pyr   B   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r4   request	__class__r9   r:   r>   ]   s    z%NotificationChannelAdmin.get_queryset)__name__
__module____qualname____doc__list_displaylist_filtersearch_fields	fieldsetsreadonly_fieldsorderingr   short_descriptionr>   __classcell__r9   r9   rB   r:   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   rQ   r   Message Content)rT   rU   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>)r1   r3   r2   r   r0   r!   r   )r4   r5   r3   Zrecent_countr9   r9   r:   rR      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>)rX   joinr   len)r4   r5   Zchannel_listr9   r9   r:   rS      s    (z1NotificationTemplateAdmin.get_compatible_channelszCompatible ChannelsN)rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rR   rN   rS   r9   r9   r9   r:   rP   b   sH   	           rP   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   )ra   rc   rb   r'   rV   )rg   rh   Z
Scheduling)rd   re   zDelivery Tracking)rf   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blackr[   Nr\   z:<strong>{}</strong><br/><span style="color: {};">{}</span>)getr'   r^   rg   r   rh   title)r4   r5   status_colorZsubject_previewr9   r9   r:   r`      s      &z'NotificationAdmin.get_notification_infor   c                    s   t  |ddS r;   ra   rc   r<   r@   rB   r9   r:   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   rp      Queued z notifications for retry.N)r2   	can_retryr'   savemessage_user)r4   rA   querysetZfailed_notificationsZretry_countnotificationr9   r9   r:   rx      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.rp   r&   rr   z
Cancelled z pending notifications.N)r2   updater~   )r4   rA   r   Zpending_notificationsZcancelled_countr9   r9   r:   ry     s    
z#NotificationAdmin.mark_as_cancelledzCancel pending notifications)rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   r`   rN   admin_order_fieldr>   actionsrx   ry   rO   r9   r9   rB   r:   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_typera   rc   r   throttle_minutesget_trigger_countlast_triggeredri   rj   zRule Informationr   )r   r   r   priorityzNotification Configuration)ra   rc   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)r4   r5   r9   r9   r:   r   L  s    
z'NotificationRuleAdmin.get_trigger_countzTrigger Statusc                    s   t  |ddS rw   r<   r@   rB   r9   r:   r>   Z  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.rz   )send_notification_via_ruler   T)r   )Z	test_modeZ	rule_name	timestampzFailed to test rule z: ERROR)levelNr{   z test notifications.)tasksr   r2   r   r   r0   	isoformatdelayr   	Exceptionr~   )r4   rA   r   r   Z
test_countZruleZtest_contexter9   r9   r:   r   a  s*    

z,NotificationRuleAdmin.test_notification_rulezSend test notifications)rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   r   rN   r>   r   r   rO   r9   r9   rB   r:   r     s\   	                
r   N)rG   Zdjango.contribr   django.utilsr   django.utils.htmlr   Zapps.notifications.modelsr   r   r   r   r	   r
   r   register
ModelAdminr   rP   r_   r   r9   r9   r9   r:   <module>   s   $PGq