o
    Ó:jîM  ã                   @   s¸  d dl Z d dlZd dlmZ d dlmZmZ d dlmZm	Z	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 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"m#Z#m$Z$m%Z%m&Z& e 'e(¡Z)eddgd�Z*G dd„ deƒZ+G dd„ deƒZ,G dd„ deƒZ-e* .d¡e	eƒfde
dede/e0ef fdd„ƒZ1dede0de/e0ef de2e0e3e/e0ef f fdd„Z4dede/e0ef fd d!„Z5e* 6d"¡e	eƒfdede/e0ef fd#d$„ƒZ7e* .d%¡de,de/e0ef fd&d'„ƒZ8e* .d(¡e	eƒfde+dede/e0ef fd)d*„ƒZ9e* .d+¡e	eƒfde-dede/e0ef fd,d-„ƒZ:d.e/e0e0f de/e0e0f fd/d0„Z;dedefd1d2„Z<d3e=de0fd4d5„Z>d3e=de?dB fd6d7„Z@d3e=de0dB fd8d9„ZAdS ):é    N)ÚAny)Ú	BaseModelÚField)Ú	APIRouterÚDependsÚRequest)ÚSettingsÚget_settings)Úbuild_reply_payload)Ú!build_closure_survey_answer_replyÚ build_closure_survey_start_replyÚis_resolution_eventÚmark_closure_survey_started)Úbuild_customer_intake_reply)ÚFreshchatAPIError)ÚFreshchatClient)Úextract_actor_idÚextract_actor_typeÚextract_channel_idÚextract_conversation_idÚextract_customer_idÚextract_event_typeÚ!extract_freshchat_conversation_idÚextract_message_idÚextract_message_textÚshould_ignore_eventÚvalidate_webhook_signaturez
/freshchatzfreshchat-webhook)ÚprefixÚtagsc                   @   s2   e Zd ZU edd�Zeed< edd�Zeed< dS )ÚTestSendMessageRequesté   ©Ú
min_lengthÚconversation_idÚmessageN)Ú__name__Ú
__module__Ú__qualname__r   r#   ÚstrÚ__annotations__r$   © r*   r*   ú</var/www/html/macrobase-freshchat-api/app/routers/webhook.pyr   &   s   
 r   c                   @   s    e Zd ZU edd�Zeed< dS )ÚTestBuildReplyRequestr    r!   r$   N)r%   r&   r'   r   r$   r(   r)   r*   r*   r*   r+   r,   +   s   
 r,   c                   @   sh   e Zd ZU edd�Zeed< edd�Zeed< edd�Ze	e ed< dZ
edB ed< dZedB ed< dS )	ÚTestSendQuickRepliesRequestr    r!   r#   r$   ÚbuttonsNÚ	help_textÚdisplay_order_style)r%   r&   r'   r   r#   r(   r)   r$   r.   Úlistr/   r0   r*   r*   r*   r+   r-   /   s   
 r-   z/webhookÚrequestÚsettingsÚreturnc                 Ã   sÔ  �t | jƒ}|  ¡ I d H }z|rt | d¡¡ni }W n tjy.   d|jddd�i}Y nw t|||ƒ}t|ƒ}t	|ƒ}t
|ƒ}t|ƒ}	t|ƒ}
t|ƒ}t|ƒ}t|ƒ}t|ƒ}t|ƒ}t dt|ƒ¡ t d|¡ t d||||	|
||||||¡ d|||||	|
||||d	œ}|j�r*t||ƒ�r*|
s©t d
¡ dddi |¥ddddœ¥dœS zFt|ƒ}t|j|
|jt|ƒ|	d�}|d u rÕt d|
¡ dddi |¥ddddœ¥dœW S t||
|ƒI d H \}}}t|j|
|jt|ƒ|	d� W n( t �y } zt !d¡ dddi |¥dt"|ƒdœ¥dœW  Y d }~S d }~ww dddi |¥dd||||dœ¥dœS |�r;t d||¡ ddd|dœS t dt|ƒ¡ t d|¡ t d||||	|
||||||¡ |j�skdddi |¥dddœ¥dœS z¯t|ƒ}|	�p}|�p}|�p}|
�p}d}t#|j|
�p…d|�p‰d|jt|ƒ|d�}|d u �r§t$|j||�pŸd|jt|ƒd �}|d u �r³t%|�p±dƒ}t&|d! ƒ}t d"|
|||t'| (d#¡ƒt'| (d$¡ƒ| (d%¡| (d&¡¡	 t||
�pÜd|ƒI d H \}}}d }| (d'¡d(v �r|
�rz
| )|
¡I d H }W n t �y } zt d)|
t"|ƒ¡ W Y d }~nd }~ww W n3 t �yM } z&t !d*¡ dd+di |¥dt*ƒ  (d,¡t*ƒ  (d-d¡t"|ƒd.œ¥dœW  Y d }~S d }~ww dd/di |¥dd||t*ƒ  (d0¡||t*ƒ  (d1¡d2œ¥dœS )3Nzutf-8Ú	_raw_bodyÚreplace)ÚerrorszFreshchat webhook headers=%szFreshchat webhook payload=%szÌFreshchat webhook extracted event_type=%s actor_type=%s actor_id=%s customer_id=%s conversation_id=%s freshchat_conversation_id=%s message_id=%s channel_id=%s message_text=%r ignored=%s signature_valid=%sT)ÚreceivedÚignoredÚ
event_typeÚactor_idÚ
actor_typeÚcustomer_idr#   Úfreshchat_conversation_idÚ
message_idÚ
channel_idÚmessage_textz9Closure survey skipped because conversation_id is missingÚfalsez.Webhook de cierre recibido sin conversation_idÚtextF)r9   Ú
reply_sentÚmissing_conversation_id©ÚerrorÚmensajeÚresponse_typeÚdata)ÚbackendÚmysql_configÚcustomer_keyz.Closure survey already sent conversation_id=%sz/Webhook de cierre recibido; encuesta ya enviada)r9   rD   Úclosure_survey_already_sentz'Freshchat closure survey sending failedÚtruez;Webhook de cierre recibido, pero no se pudo enviar encuesta)rD   Ú
send_errorz-Webhook de cierre recibido y encuesta enviada)r9   rD   Ú
reply_typeÚfallback_usedÚreply_payloadÚfreshchat_responsez/Ignored Freshchat event action=%s actor_type=%szWebhook recibido e ignoradoz#Webhook recibido sin auto respuesta)rD   Úauto_reply_enabledÚ )rK   rL   Útypez‡Freshchat webhook reply generated conversation_id=%s customer_key=%s message_text=%r reply_type=%s intake=%s survey=%s flow=%s field=%sÚintakeÚsurveyÚflowÚfieldÚsurvey_action>   ÚdeclinedÚ	completedzFFreshchat auto resolve after survey failed conversation_id=%s error=%sz<Freshchat webhook received event but response sending failedz2Webhook recibido, pero no se pudo enviar respuestarQ   rR   )rD   rQ   rR   rP   z$Webhook recibido y respuesta enviadarM   Úauto_resolve_response)r9   rD   rQ   rR   rM   rS   rT   r_   )+ÚdictÚheadersÚbodyÚjsonÚloadsÚdecodeÚJSONDecodeErrorr   r   r   r   r   r   r   r   r   r   r   ÚloggerÚdebugÚ_headers_for_logÚfreshchat_auto_reply_enabledr   ÚwarningÚ_build_clientr   Úcustomer_state_store_pathÚcustomer_state_backendÚ_customer_state_mysql_configÚinfoÚ_send_reply_payloadr   Ú	ExceptionÚ	exceptionÚ_format_send_errorr   r   r
   r(   ÚboolÚgetÚresolve_conversationÚlocals)r2   r3   ra   Úraw_bodyÚpayloadÚsignature_validr:   r;   r<   r=   r#   r>   r?   r@   rA   r9   Ú	base_dataÚclientrS   rQ   rR   rT   ÚexcrM   r_   Úresolve_excr*   r*   r+   Úfreshchat_webhook7   sà  €
ÿðõ
ÿüüûÿüüý
û
ÿýü€þÿùüüðÿýüú
û
ôýý€ÿ€
ÿ
ûü€þÿ

÷ür€   r}   r#   rS   c                 Ã   sŒ  �t |d ƒ}d}|dkr_z| j|t |d ƒt|d ƒt | d¡p"dƒdd	�I d H }W n• ty^   t d
|¡ d}t | d¡pC|d ƒ}|  ||¡I d H }d}| ¡  | 	d|dœ¡ Y ncw |dkr´z| j
|t |d ƒt|d ƒt | d¡pxdƒd�I d H }W n@ ty³   t d|¡ d}t | d¡p˜|d ƒ}|  ||¡I d H }d}| ¡  | 	d|dœ¡ Y nw |  |t |d ƒ¡I d H }|||fS )NrW   FÚquick_repliesrC   r.   r/   zSelecciona una opcionÚsnake)r#   rC   r.   r/   r0   zHFreshchat quick replies failed, sending text fallback conversation_id=%sTÚfallback_text)rW   rC   Údropdown)r#   rC   Úoptionsr/   zCFreshchat dropdown failed, sending text fallback conversation_id=%s)r(   Úsend_quick_reply_messager1   rv   rr   rg   rs   Úsend_text_messageÚclearÚupdateÚsend_dropdown_message)r}   r#   rS   rQ   rR   rT   rƒ   r*   r*   r+   rq   @  sb   €

ûþö

üþö

þ
rq   c                 C   s   | j | j| j| j| j| jdœS )N)ÚhostÚportÚdatabaseÚuserÚpasswordÚtable)Úcustomer_state_mysql_hostÚcustomer_state_mysql_portÚcustomer_state_mysql_databaseÚcustomer_state_mysql_userÚcustomer_state_mysql_passwordÚcustomer_state_mysql_table©r3   r*   r*   r+   ro   w  s   úro   z/test/configc                 C   sN   dt | jƒt | jo| jdkƒ| j| j| j| jt | jƒt | jƒt | j	ƒ| j
dœS )NÚokú	change-me)ÚstatusÚ!freshchat_api_base_url_configuredÚfreshchat_api_token_configuredrj   Úfreshchat_send_as_actor_typern   rm   Ú$customer_state_mysql_host_configuredÚ(customer_state_mysql_database_configuredÚ$customer_state_mysql_user_configuredr–   )ru   Úfreshchat_api_base_urlÚfreshchat_api_tokenrj   r�   rn   rm   r‘   r“   r”   r–   r—   r*   r*   r+   Úfreshchat_test_config‚  s   õr£   z/test/build-replyc                 C   s   t | jƒ}dddd|idœS )NrB   zRespuesta construidarC   rS   rF   )r
   r$   )r2   rS   r*   r*   r+   Úfreshchat_test_build_reply“  s   
ÿür¤   z/test/send-messagec              
   Ã   sŒ   �zt |ƒ}| | j| j¡I d H }W n& ty8 } zt d¡ ddd| j| jt|ƒdœdœW  Y d }~S d }~ww ddd| j| j|d	œdœS )
Nz)Manual Freshchat send-message test failedrO   zNo se pudo enviar mensajerC   )r#   r$   rP   rF   rB   zMensaje enviado)r#   r$   rT   )rl   r‡   r#   r$   rr   rg   rs   rt   )r2   r3   r}   Úresponser~   r*   r*   r+   Úfreshchat_test_send_message   s0   €
ýü€þýür¦   z/test/send-quick-repliesc                 Ã   sê   �dd„ | j D ƒd d… }| jr| j ¡ nd}|sd}| jpd}|dvr&d}zt|ƒ}| | j| j|||¡I d H }W n* tyd } zt	 
d¡ dd	d
| jt|ƒt|ƒt|ƒdœdœW  Y d }~S d }~ww ddd
| j| j||||dœdœS )Nc                 S   s    g | ]}|r|  ¡ r|  ¡ ‘qS r*   )Ústrip)Ú.0Úbuttonr*   r*   r+   Ú
<listcomp>Æ  s     z5freshchat_test_send_quick_replies.<locals>.<listcomp>é   u   Selecciona una opciÃ³nr‚   >   Úcamelr‚   z/Manual Freshchat send-quick-replies test failedrO   z+No se pudo enviar mensaje con quick repliesrC   )r#   rP   Ústatus_codeÚresponse_bodyrF   rB   z!Mensaje con quick replies enviado)r#   r$   r/   r0   r.   rT   )r.   r/   r§   r0   rl   r†   r#   r$   rr   rg   rs   rt   Ú_error_status_codeÚ_error_response_body)r2   r3   Úclean_buttonsÚclean_help_textr0   r}   r¥   r~   r*   r*   r+   Ú!freshchat_test_send_quick_repliesÁ  sR   €
û
üü€þúür³   ra   c                    s   h d£‰ ‡ fdd„|   ¡ D ƒS )N>   ú	x-api-keyú
set-cookieÚcookieÚauthorizationc                    s&   i | ]\}}||  ¡ ˆ v rd n|“qS )z
<redacted>)Úlower)r¨   ÚkeyÚvalue©Ú	sensitiver*   r+   Ú
<dictcomp>õ  s    ÿÿz$_headers_for_log.<locals>.<dictcomp>)Úitems)ra   r*   r»   r+   ri   ó  s   
þri   c                 C   s:   | j stdƒ‚| jr| jdkrtdƒ‚t| j | j| jd�S )Nz+FRESHCHAT_API_BASE_URL no esta configurado.r™   z(FRESHCHAT_API_TOKEN no esta configurado.)Úbase_urlÚtokenr<   )r¡   r   r¢   r   r�   r—   r*   r*   r+   rl   û  s   ýrl   r~   c                 C   s`   t | tƒr,| jg}| jd ur| d| j› �¡ | jr'| d| jd d… › �¡ d |¡S t| ƒS )Nzstatus_code=zresponse_body=iè  z | )Ú
isinstancer   r$   r­   Úappendr®   Újoinr(   )r~   Údetailsr*   r*   r+   rt     s   


rt   c                 C   ó   t | tƒr| jS d S ©N)rÁ   r   r­   ©r~   r*   r*   r+   r¯     ó   
r¯   c                 C   rÅ   rÆ   )rÁ   r   r®   rÇ   r*   r*   r+   r°     rÈ   r°   )Brc   ÚloggingÚtypingr   Úpydanticr   r   Úfastapir   r   r   Úapp.core.configr   r	   Úapp.services.auto_reply_servicer
   Ú#app.services.closure_survey_servicer   r   r   r   Ú#app.services.customer_state_servicer   Úapp.services.exceptionsr   Úapp.services.freshchat_clientr   Ú&app.services.freshchat_webhook_servicer   r   r   r   r   r   r   r   r   r   r   Ú	getLoggerr%   rg   Úrouterr   r,   r-   Úpostr`   r(   r€   Útupleru   rq   ro   rv   r£   r¤   r¦   r³   ri   rl   rr   rt   Úintr¯   r°   r*   r*   r*   r+   Ú<module>   s‚    4
þÿþ
ý  
ÿþ
ý
ü7$þÿþ
ý þÿþ
ý"1