
    6ӴhI                         S r SSKJr  SSKJr  SSKJr  SSKJrJ	r	  SSK
JrJrJr  SSKJrJrJrJrJrJr  SSKr " S	 S
\\5      r " S S\\5      r " S S\\\5      r " S S\\5      rg)a  
Notification Models for Stream Processor Application

This module contains Django models for managing notifications,
including Telegram messages, email alerts, and other notification
channels. These models track notification history, delivery status,
and configuration settings.
    )models)User)timezone)MinValueValidatorMaxValueValidator)TimestampedModel	UUIDModelStatusModel)validate_name_formatvalidate_json_configurationvalidate_webhook_configvalidate_email_configvalidate_telegram_configvalidate_template_contentNc                      \ rS rSrSr\R                  " SS\/SS9r/ SQr	\R                  " S\	S	S
9r
\R                  " SSSS9r\R                  " \SS9r\R                   " S\" S5      \" S5      /SS9r\R                   " S\" S5      \" S5      /SS9r\R                   " S\" S5      \" S5      /SS9r\R,                  " \\R0                  SSS9r " S S5      rS  rS! rS" rS# rS$rg%)&NotificationChannel   a	  
Model representing a notification delivery channel.

Notification channels define how and where notifications should be sent,
including configuration for different service types like Telegram,
email, webhooks, and other messaging platforms.

Attributes:
    name (CharField): Human-readable name for the channel
    channel_type (CharField): Type of notification channel
    is_active (BooleanField): Whether the channel is currently active
    configuration (JSONField): Channel-specific configuration data
    rate_limit (PositiveIntegerField): Maximum messages per minute
    retry_attempts (PositiveIntegerField): Number of retry attempts
    timeout_seconds (PositiveIntegerField): Timeout for delivery attempts
    created_by (ForeignKey): User who created this channel
d   Tz0Human-readable name for the notification channel)
max_lengthunique
validators	help_text))telegramzTelegram Bot)emailEmail)webhookWebhook)slackSlack)discordDiscord)smsSMS   zType of notification channelr   choicesr   z+Whether this notification channel is activedefaultdb_indexr   z)Channel-specific configuration parametersr(   r         i  z%Maximum number of messages per minuter(   r   r      r   
   z.Number of retry attempts for failed deliveries   i,  z(Timeout for delivery attempts in secondsnotification_channelsz*User who created this notification channel	on_deleterelated_namer   c                   f    \ rS rSrSrSrS/r\R                  " S/S9\R                  " S/S9/r	Sr
g	)
NotificationChannel.Metai   zNotification ChannelzNotification Channelsnamechannel_typefields	is_active N__name__
__module____qualname____firstlineno__verbose_nameverbose_name_pluralorderingr   Indexindexes__static_attributes__r=       EC:\Users\brahi\OneDrive\Desktop\Code\src\apps\notifications\models.pyMetar6   i   s8    -58LL 01LL.
rI   rK   c                 :    U R                    SU R                   S3$ )z2String representation of the notification channel. ())r8   r9   selfs    rJ   __str__NotificationChannel.__str__r   s     ))Bt00133rI   c                     U R                   S:X  a9  U R                  R                  SS5      U R                  R                  SS5      S.$ 0 $ )z$Get Telegram-specific configuration.r   	bot_token chat_id)rT   rV   r9   configurationgetrO   s    rJ   get_telegram_config'NotificationChannel.get_telegram_configv   sM    
*!//33KD--11)R@  	rI   c                     U R                   S:X  a9  U R                  R                  S/ 5      U R                  R                  SS5      S.$ 0 $ )z!Get email-specific configuration.r   
recipientssubject_prefixz[Stream Processor])r]   r^   rW   rO   s    rJ   get_email_config$NotificationChannel.get_email_config   sO    '"0044\2F"&"4"4"8"89IK_"`  	rI   c                     U R                   S:X  aT  U R                  R                  SS5      U R                  R                  S0 5      U R                  R                  SS5      S.$ 0 $ )z#Get webhook-specific configuration.r   urlrU   headersmethodPOST)rb   rc   rd   rW   rO   s    rJ   get_webhook_config&NotificationChannel.get_webhook_config   sc    	)))--eR8--11)R@,,006B 
 	rI   r=   N) r?   r@   rA   rB   __doc__r   	CharFieldr   r8   CHANNEL_TYPESr9   BooleanFieldr<   	JSONFielddictrX   PositiveIntegerFieldr   r   
rate_limitretry_attemptstimeout_seconds
ForeignKeyr   CASCADE
created_byrK   rQ   rZ   r_   rf   rH   r=   rI   rJ   r   r      s>   & ()D	DM ##0L ##?I $$=M ,,%a(*;D*AB9J 00%a(*;B*?@BN 11%a(*;C*@A<O ""..,>	J
 
4rI   r   c                   :   \ rS rSrSr\R                  " SSSS9r/ SQr\R                  " S\S	S
9r	\R                  " SSSS9r
\R                  " SS9r\R                  " SSSS9r\R                  " \SS9r\R                  " \SS9r " S S5      rS rS rS rSrg)NotificationTemplate   a  
Model for notification message templates.

Templates define reusable message formats for different types
of notifications, allowing for consistent messaging and easy
customization of notification content.

Attributes:
    name (CharField): Name for the template
    template_type (CharField): Type of notification this template is for
    subject_template (CharField): Subject line template (for email)
    message_template (TextField): Main message content template
    is_active (BooleanField): Whether the template is active
    variables (JSONField): Available template variables
    channel_types (JSONField): Compatible channel types
r   Tz#Name for this notification templater   r   r   )jingle_detectedzJingle Detectedad_break_startedzAd Break Startedad_break_endedzAd Break Endedstream_startedzStream Startedstream_stoppedzStream Stoppedstream_errorzStream Error)system_alertzSystem Alert)health_checkzHealth Checkr+   z2Type of notification this template is designed forr%      z4Subject line template (used for email notifications)r   blankr   z8Main message content template with variable placeholdersr   z'Whether this template is active for user'   z-List of available variables for this templater*   z-List of compatible notification channel typesc                   h    \ rS rSrSrSrSS/r\R                  " S/S9\R                  " S/S9/r	Sr
g	)
NotificationTemplate.Meta   zNotification TemplatezNotification Templatestemplate_typer8   r:   r<   r=   Nr>   r=   rI   rJ   rK   r      s;    .6#V,LL 12LL.
rI   rK   c                 :    U R                    SU R                   S3$ )z3String representation of the notification template.rM   rN   )r8   r   rO   s    rJ   rQ   NotificationTemplate.__str__   s     ))Bt112!44rI   c                 t     U R                   R                  " S0 UD6$ ! [         a  nSU 3s SnA$ SnAff = f)z
Render the message template with provided context variables.

Args:
    context (dict): Variables to substitute in the template
    
Returns:
    str: Rendered message content
z!Template error: Missing variable Nr=   )message_templateformatKeyErrorrP   contextes      rJ   render_message#NotificationTemplate.render_message   s>    	;((//:':: 	;6qc::	;s    
7277c                     U R                   (       d  SU R                   S3$  U R                   R                  " S0 UD6$ ! [         a  nSU 3s SnA$ SnAff = f)z
Render the subject template with provided context variables.

Args:
    context (dict): Variables to substitute in the template
    
Returns:
    str: Rendered subject line
[z] Notificationz Subject error: Missing variable Nr=   )subject_templater   r   r   r   s      rJ   render_subject#NotificationTemplate.render_subject   s_     $$t))*.99	:((//:':: 	:5aS99	:s   ? 
A	AAAr=   N)r?   r@   rA   rB   rh   r   ri   r8   TEMPLATE_TYPESr   r   	TextFieldr   rk   r<   rl   list	variableschannel_typesrK   rQ   r   r   rH   r=   rI   rJ   rv   rv      s    $ 7D	N $$FM ''H ''L
 ##;I   AI
 $$AM

 
5;:rI   rv   c            	          \ rS rSrSr\R                  " \\R                  SSS9r	\R                  " \
\R                  SSSSS9r\R                  " S	S
S9r\R                  " S	SSS9r\R                   " SS9r\R$                  " \SSS9r\R*                  " \R.                  SS9r\R*                  " SSSS9r\R4                  " SSS9r\R                   " SSS9r\R                  " SSSS9r " S S5      rS rS r S  r!S! r"S'S# jr#S$ r$S% r%S&r&g")(Notificationi	  a  
Model representing an individual notification instance.

This model tracks individual notification messages that have been
sent or are pending delivery, including their content, delivery
status, and any error information.

Attributes:
    channel (ForeignKey): Notification channel to use for delivery
    template (ForeignKey): Template used for this notification
    recipient (CharField): Target recipient identifier
    subject (CharField): Notification subject line
    message (TextField): Notification message content
    context_data (JSONField): Variables used for template rendering
    scheduled_at (DateTimeField): When the notification should be sent
    sent_at (DateTimeField): When the notification was actually sent
    delivery_attempts (PositiveIntegerField): Number of delivery attempts
    error_message (TextField): Last error message if delivery failed
    external_id (CharField): External service message ID
notificationsz(Notification channel to use for deliveryr2   Tz+Template used to generate this notification)r3   nullr   r4   r   r   z2Target recipient identifier (email, chat ID, etc.))r   r   zNotification subject liner   zNotification message contentr   z%Variables used for template rendering)r(   r   r   z%When this notification should be sentr*   z(When this notification was actually sentr   r   r   r   z Number of delivery attempts madez%Last error message if delivery failed)r   r   r   z(External service message ID for trackingc                       \ rS rSrSrSrS/r\R                  " SS/S9\R                  " S/S9\R                  " S	/S9\R                  " S/S9/r	S
r
g)Notification.Metaic  r   Notificationsz-scheduled_atchannelstatusr:   scheduled_atsent_atr=   Nr>   r=   rI   rJ   rK   r   c  sX    %-#$LLH 56LL 01LL,LL
+	
rI   rK   c                 x    U R                   R                   SU R                  =(       d    U R                  SS  3$ )z*String representation of the notification.z - N2   )r   r8   subjectmessagerO   s    rJ   rQ   Notification.__str__n  s3    ,,##$C(ISb8I'JKKrI   c                 P    U R                   S:H  =(       a    U R                  (       + $ )z.Check if the notification is pending delivery.pendingr   r   rO   s    rJ   
is_pendingNotification.is_pendingr  s    {{i'<,<<rI   c                 J    U R                   S:H  =(       a    U R                  SL$ )z5Check if the notification has been successfully sent.	completedNr   rO   s    rJ   is_sentNotification.is_sentv  s    {{k)Fdll$.FFrI   c                      U R                   S:H  $ )z.Check if the notification delivery has failed.failed)r   rO   s    rJ   	is_failedNotification.is_failedz  s    {{h&&rI   Nc                     SU l         [        R                  " 5       U l        U(       a  Xl        U R                  / SQS9  g)z+Mark the notification as successfully sent.r   )r   r   external_idupdate_fieldsN)r   r   nowr   r   save)rP   r   s     rJ   	mark_sentNotification.mark_sent~  s.    !||~*		 D	ErI   c                 j    SU l         Xl        U =R                  S-  sl        U R                  / SQS9  g)z3Mark the notification as failed with error message.r   r,   )r   error_messagedelivery_attemptsr   N)r   r   r   r   )rP   r   s     rJ   mark_failedNotification.mark_failed  s/    *!#		 P	QrI   c                 t    U R                   S:H  =(       a#    U R                  U R                  R                  :  $ )z)Check if the notification can be retried.r   )r   r   r   rp   rO   s    rJ   	can_retryNotification.can_retry  s3     KK8# A""T\\%@%@@	
rI   )r   r   r   r   )N)'r?   r@   rA   rB   rh   r   rr   r   rs   r   rv   SET_NULLtemplateri   	recipientr   r   r   rl   rm   context_dataDateTimeFieldr   r   r   r   rn   r   r   r   rK   rQ   r   r   r   r   r   r   rH   r=   rI   rJ   r   r   	  sh   , ..$<	G   //$?H   FI
 -G 0G
 ##9L ''9L
 ""<G 334
 $$9M
 ""<K	
 	
L=G'FR
rI   r   c                      \ rS rSrSr\R                  " SSSS9r/ SQr\R                  " S\S	S
9r	\R                  " \\R                  SSS9r\R                  " \\R                  SSS9r\R                   " SSSS9r\R$                  " \SS9r\R*                  " S\" S5      \" S5      /SS9r\R2                  " SSSS9r\R6                  " SSS9r " S S5      rS rS rS r S  r!S!r"g")#NotificationRulei  a.  
Model for automatic notification rules.

Rules define when and how notifications should be automatically
triggered based on system events, allowing for automated alerting
and monitoring without manual intervention.

Attributes:
    name (CharField): Name for the notification rule
    event_type (CharField): Type of event that triggers this rule
    channel (ForeignKey): Default channel for notifications
    template (ForeignKey): Default template for notifications
    is_active (BooleanField): Whether the rule is currently active
    conditions (JSONField): Conditions that must be met for triggering
    throttle_minutes (PositiveIntegerField): Minimum time between notifications
    last_triggered (DateTimeField): When this rule was last triggered
    priority (IntegerField): Rule priority for ordering
r   TzName for this notification rulerx   )	ry   r{   r}   r   r   r   )high_error_ratezHigh Error Rate)system_startupzSystem Startup)system_shutdownzSystem Shutdownr+   z2Type of event that triggers this notification ruler%   rulesz*Default notification channel for this ruler2   z+Default notification template for this rulez(Whether this notification rule is activer'   z5Additional conditions that must be met for triggeringr*   r0   r   i  z4Minimum minutes between notifications from this ruler-   z!When this rule was last triggeredr   z=Rule priority for ordering (higher numbers = higher priority)c                       \ rS rSrSrSrSS/r\R                  " S/S9\R                  " S/S9\R                  " S	/S9/r	S
r
g)NotificationRule.Metai  zNotification RulezNotification Rulesz	-priorityr8   
event_typer:   r<   priorityr=   Nr>   r=   rI   rJ   rK   r     sH    *2(LL/LL.LL-
rI   rK   c                 :    U R                    SU R                   S3$ )z/String representation of the notification rule.rM   rN   )r8   r   rO   s    rJ   rQ   NotificationRule.__str__  s    ))Bt/q11rI   c                     U R                   (       d  gU R                  (       d  g[        R                  " 5       U R                  -
  nUR	                  5       U R
                  S-  :  $ )z7Check if the rule can be triggered based on throttling.FT<   )r<   last_triggeredr   r   total_secondsthrottle_minutes)rP   time_since_lasts     rJ   can_triggerNotificationRule.can_trigger  sM    ~~""",,.4+>+>>,,.43H3H23MNNrI   c                 X    [         R                  " 5       U l        U R                  S/S9  g)z0Mark the rule as triggered and update timestamp.r   r   N)r   r   r   r   rO   s    rJ   mark_triggeredNotificationRule.mark_triggered	  s"    &lln		!1 2	3rI   c                     U R                   (       d  gU R                   R                  5        H  u  p#X!;  a    gX   U:w  d  M    g   g)z
Check if event data meets the rule conditions.

Args:
    event_data (dict): Event data to check against conditions
    
Returns:
    bool: True if conditions are met, False otherwise
TF)
conditionsitems)rP   
event_datakeyexpected_values       rJ   check_conditions!NotificationRule.check_conditions  sE      $(??#8#8#:C$.0	 $; rI   )r   N)#r?   r@   rA   rB   rh   r   ri   r8   EVENT_TYPESr   rr   r   rs   r   rv   r   rk   r<   rl   rm   r   rn   r   r   r   r   r   IntegerFieldr   rK   rQ   r   r   r   rH   r=   rI   rJ   r   r     s9   ( 3D
K !!FJ ..>	G   ..?	H ##<I !!IJ 22%a(*;D*ABH ))5N ""QH

 
2	O4
rI   r   )rh   	django.dbr   django.contrib.auth.modelsr   django.utilsr   django.core.validatorsr   r   apps.core.modelsr   r	   r
   apps.core.validatorsr   r   r   r   r   r   jsonr   rv   r   r   r=   rI   rJ   <module>r      sv     + ! G E E  z*I zzs:+Y s:lI
#Y I
XN' NrI   