
    .i#                         d dl mZ d dlmZ d dlmZ ddlmZ d dlm	Z	 d dl
mZ d dlmZ d d	lmZ d d
lmZ d dlZ ej&                  e      Z G d d      Zy)    )get_channel_layer)async_to_sync)settings   )EmailService)UserRepository)UserService)NotificationRepository)NotificationSerializer)NotificationTypeNc                       e Zd Zedd       Zed        Zed        Zed        Zed        Zedd       Z	ede
d	efd
       Ze	 dd       Zed        Zy)NotificationServiceNc                     |t        j                         }| j                  r|j                  d      S t	        | dd       }t        j
                  | |      S )Nz-created_atactive_company)r
   base_querysetis_superuserorder_bygetattrlist_for_user_by_company)userqscompanys      Q/var/www/html/dp2/backend_v2.1/server/apps/calls/services/notification_service.pylist_notificationsz&NotificationService.list_notifications   sU    :'557B;;}--$ 0$7%>>
 	
    c                 .    t        j                  ||       S N)r
   	get_by_id)r   notif_ids     r   get_notificationz$NotificationService.get_notification"   s    %//$??r   c                 ^    t         j                  | |      }|y t        j                  |      S r   )r   r    r
   mark_as_read)r   r   notifs      r   r"   z NotificationService.mark_as_read&   s-    #44T8D=%22599r   c                    g }| D ]  }	|r|	j                   |j                   k(  r	 t        j                  |      }
|r|j                  nd}d|
 d| d| }t        j                  |	|t        j                  |||       |j                  |	       t        j                  d| d| d|	j                           |S # t        $ r;}t        j                  d	| d
|	j                   dt        |              Y d}~d}~ww xY w)z6Helper method to send notifications to managers/adminszUnknown CompanyzAdvisor z from z missed a call from 	recipientr   notification_typetitlemessagecallzMissed call z notification sent to : zError sending notification to  N)idr	   get_user_namenamer   create_and_push_notificationr   MISSED_CALLappendloggerinfoemail	Exceptionerrorstr)managersr   r*   display_namecustomer_phoner(   	role_namer   
recipientsmanageradvisor_namecompany_namer)   es                 r   _send_notification_to_managersz2NotificationService._send_notification_to_managers.   s    
G

dgg-e*88>/6w||<M$\N&FZ[gZhi#@@%#&6&B&B# A  !!'*l>*::PQZP[[]^e^k^k]lmn)  0   e=i['--XZ[^_`[aZbcddes   BB;;	C?1C::C?c           
         	 |r|nd}d| }d}g }|r]	 t         j                  ||t        j                  |||        t        j                  d|j                          |j                  |       t        j                  |      }
t         j                  |
|| |||d	|      }t        j                  |      }t         j                  ||| |||d
|      }|j                  |       |j                  |       |D cg c]  }|rt!        |dd      r|j                   }}t"        j$                  rt"        j$                  ng }t"        j&                  rt"        j&                  ng }t)        t+        ||z   |z               }|rPt         j-                  ||ddd||d      }t/        j0                  ||g |       t        j                  d|        yy# t        $ r9}	t        j                  d|j                   dt        |	              Y d}	~	d}	~	ww xY wc c}w # t        $ r+}	t        j                  dt        |	              Y d}	~	yd}	~	ww xY w)ap  
        Send missed call notifications to advisor, all chief admins, and service managers of the company.

        Args:
            call: Call object
            user: User object (the user who missed the call)
            company: Company object
            customer_name: str (customer name or None)
            customer_phone: str (customer phone number)
        zUnknown CustomerzMissed call from zMissed Callr%   z*Missed call notification sent to advisor: z&Error sending notification to advisor r+   Nzchief adminzservice managerr5   Teamu   📞)CustomerPhone)r(   r)   recipient_name
alert_icon
alert_typedetails)subjecthtml_contentrecipient_listbcczSingle BCC email sent to: z(Error in send_missed_call_notification: )r   r0   r   r1   r3   r4   r5   r6   r7   r8   r2   r   get_chief_admins_for_companyrB    get_service_managers_for_companyextendr   r   	EMAIL_BCC%ALL_DEALERSHIPS_BOOKING_NOTIFY_EMAILSlistsetrender_alert_emailr   
send_email)r*   r   r   customer_namer;   r:   r)   r(   all_email_recipientsrA   chief_adminschief_admin_recipientsservice_managersservice_manager_recipientsuuser_emailsstatic_bcc_emailsall_dealership_emailsunique_emailsrL   s                       r   send_missed_call_notificationz1NotificationService.send_missed_call_notificationP   s   Q	N,9=?QL *,8G!E#% b'DD"& '*:*F*F# '! E  KK"LTZZL YZ %++D1)FFwOL%8%W%WdD,}g&"
  .NNwW)<)[)[ $l'8'*&
 !''(>? ''(BC "6!5AGT2 !5  
 7?6H6H 2 2b ?? >>EG " !//2GG" M 2EE##)%,$0!/  F 
  ''!!-#%%	 8HI) K ! bLL#I$**UWX[\]X^W_!`aab,J  	NLLCCF8LMM	NsO   H AG BH 8"HB1H 	H.H
H 
HH 	I !IIc                 J   | t         j                  d       y	 t        j                  | |t        j
                  ||       t         j                  d| j                          y# t        $ r4}t         j                  d| j                  t        |             Y d}~yd}~ww xY w)a%  
        Send message notifications to advisor of company.

        Args:
            user: User object (the user who missed the call)
            title: str (notification title)
            message: str (notification message)
            company: Company object (the company of user)
        Nu)   Cannot send notification — user is None)r&   r   r'   r(   r)   zMessage notification sent to z-Failed to send message notification to %s: %s)r3   r7   r   r0   r   MESSAGEr4   r5   r6   	exceptionr8   )r   r   r(   r)   rA   s        r   send_message_notificationz-NotificationService.send_message_notification   s     <LLDE	<<"2":": =  KK7

|DE 	?

CF 	s   A
A% %	B".*BB"user_idpayloadc           	         t               }	  t        |j                        d|  d|d       t        j	                  d|         y # t
        $ r.}t        j                  d|  dt        |              Y d }~y d }~ww xY w)Nuser_send_notification)typedatazNotification sent to user z$Failed sending notification to user r+   )r   r   
group_sendr3   r4   r6   r7   r8   )rh   ri   channel_layerrA   s       r   push_realtime_notificationz.NotificationService.push_realtime_notification   s     *+
	U3M-223y!/# KK4WI>? 	ULL?y3q6(STT	Us   :A 	A>$A99A>c           	      0   	 t        j                  | |||||      }t        |      j                  }t        j                  | j                  |       |S # t        $ r8}t        j                  d| j                   dt        |              Y d}~yd}~ww xY w)z2Create a new notification and push it in real-timer%   z,Error creating/pushing notification to user r+   N)r
   create_notificationr   rn   r   rq   r-   r6   r3   r7   r8   )	r&   r   r'   r(   r)   r*   r#   ri   rA   s	            r   r0   z0NotificationService.create_and_push_notification   s    	*>>#"3E -U388G::g L 	LLG	~UWX[\]X^W_`a	s   AA 	B.BBc                 l    ddl m} ddlm} | ||j	                         j
                  d|} |d|      S )Nr   )render_to_string)timezone)alert_titlealert_messagecurrent_yearzalerts/general_alert.html)django.template.loaderru   django.utilsrv   nowyear)r(   r)   kwargsru   rv   contexts         r   rV   z&NotificationService.render_alert_email   s@    ;) !$$LLN//
 	
   ;WEEr   r   ) r   )__name__
__module____qualname__staticmethodr   r    r"   rB   rc   rg   intdictrq   r0   rV    r   r   r   r      s    
 
 @ @ : :  B \N \N|  > UC U$ U U   < F Fr   r   )channels.layersr   asgiref.syncr   django.confr   email_servicer   apps.core.repositoriesr   apps.core.servicesr	   apps.calls.repositoriesr
   apps.calls.serializersr   apps.calls.constantsr   logging	getLoggerr   r3   r   r   r   r   <module>r      sE    - &   ' 1 * : 9 1  
		8	$yF yFr   