o
    s+Âi,#  ã                   @  s¤   d 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mZmZmZmZ ddlmZmZ dd	lmZmZ dd
lmZmZ edd„ ƒZdd„ ZdS )z4Mailbox processing service for wp_invoices_mail_app.é    )Úannotations)Úcontextmanager)Ú	parseaddr)Úis_authorized_from_message)Ú
MailConfig)Úextract_invoice_attachmentsÚfetch_unseen_messagesÚhas_inline_imagesÚsave_attachmentsÚsend_processed_invoices_email)Úbuild_email_body_for_resultsÚ$process_attachments_with_wp_invoices)Úrender_no_attachments_htmlÚrender_results_email_html)Úensure_tenant_mail_pathsÚresolve_tenant_idc           
      c  s   t |ƒ}tjtjtjtjtjtjtjtj	tj
tjdœ
}z`|  d¡p$tj}t|  d¡p-tjƒ}|  d¡p6tj}|  d¡p>tj}|t_|t_|t_|t_|pOtjt_|pUtjt_|p[tj	t_	|patj
t_
|d t_d V  W | ¡ D ]
\}}	tt||	ƒ qpd S | ¡ D ]
\}}	tt||	ƒ qw )N)
Ú	IMAP_HOSTÚ	IMAP_PORTÚIMAP_USERNAMEÚIMAP_PASSWORDÚ	SMTP_HOSTÚ	SMTP_PORTÚSMTP_USERNAMEÚSMTP_PASSWORDÚFROM_ADDRESSÚ	INBOX_DIRÚhostÚportÚusernameÚpasswordÚinbox)r   r   r   r   r   r   r   r   r   r   r   r   ÚgetÚintÚitemsÚsetattr)
ÚmailboxÚ	tenant_idÚtenant_pathsÚoriginalr   r   r   r   ÚkeyÚvalue© r+   ú4apps/wp_invoices_mail_app/services/mail_processor.pyÚ_mailbox_config   sB   €ö
ÿÿr-   c           "   	   C  sr  t |ƒ}|  d¡p|  d¡pd}|  d¡pd}|  dd¡}td|  d¡› d	|  d¡› d
ƒ td|  d¡› d|  d¡› ƒ t| |ƒê t|d\}}|s_td|› dƒ 	 W d   ƒ d S tdƒ |sr| ¡  	 W d   ƒ d S |D ]¨\}}	|	 dd¡}
t|
ƒ\}}|	 dd¡}t|	|d\}}|dv r	td|› d|› d|› ƒ t|	ƒ}|sîtd|› d|› ƒ t	|	ƒ}g d¢}|rÅ| 
d¡ n| 
d¡ | g d ¢¡ d! |¡}t|d"}|ræt|||g |d# | |d$d%¡ qtt|tjƒ}td&ƒ |D ]}td'|ƒ qút||d}g }|pg D ]'}d(|v pd)|v pd*|v }|r5| d(¡d+u s0| d)¡r5| 
|¡ qt|ƒp=d}t|ƒ}|rÅdd,g}|D ]$}| d-¡pZ| d.¡pZd/}| d)¡pbd0}| 
d1|› d2|› ¡ qK| g d3¢¡ |D ]@}| d*¡p‚d ¡ } | sŠqyt| ƒd4kr—| d5d … } | d-¡p¤| d.¡p¤d/}| 
d6|› d7¡ | 
| ¡ | 
d¡ qy|d! d! |¡  ¡ }g }!|pËg D ]}| d8¡pØ| d9¡}|rá|! 
|¡ qÌtd:ƒ |!D ]}td'|ƒ qé|r|rt|||||!d; | |d$d%¡ qttd|› d|› d|› ƒ | |d$d%¡ qt| ¡  | ¡  W d   ƒ d S 1 s2w   Y  d S )<NÚidr   ÚdefaultÚfolderÚINBOXÚsend_response_emailTz[MAIL] Processing mailbox: z (ú)z[IMAP] Connecting to r   ú:r   )r0   z(No se pudo conectar a IMAP para mailbox=Ú.z[IMAP] Connected successfullyÚFromÚ ÚSubjectz(sin asunto))Úcontext)TÚAUTHz[AUTH] z Desde: z
, asunto: u#   Correo sin adjuntos vÃ¡lidos desde )zHi,r7   zdWe received your email but could not process any invoice because we did not find a valid attachment.r7   z¤It looks like you inserted a photo inside the email body. Please attach the invoice as a file using the paper-clip icon instead of pasting it into the message text.zmPlease attach at least one invoice as a PDF or a clear image file (JPG, PNG, etc.) so the bot can process it.)r7   z6This email was not processed and no PDF was generated.r7   zRegards,u   Invoice Bot â€“ AbsolutemsÚ
)Úinline_photos)Ú
to_addressÚoriginal_subjectÚ	body_textÚ	pdf_pathsÚ	body_htmlz+FLAGSz\SeenzAdjuntos crudos guardados en:z  -ÚokÚerrorÚ	tracebackFu>   âš ï¸ Algunas facturas no se pudieron procesar correctamente:ÚfilenameÚoriginal_filenamez(sin nombre)zError desconocidoz  - z: )r7   uŒ   Si quieres que investiguemos el problema, reenvÃ­a este correo a soporte incluyendo el bloque de detalles tÃ©cnicos que ves a continuaciÃ³n.r7   uQ   â”€â”€â”€â”€â”€â”€â”€â”€ Detalles tÃ©cnicos para soporte â”€â”€â”€â”€â”€â”€â”€â”€iÐ  i0øÿÿú[ú]Úrevision_pdf_pathÚpdf_pathu   PDFs de revisiÃ³n a adjuntar:)r=   r>   r?   rA   r@   )r   r!   Úprintr-   r   Úlogoutr   r   r   r	   ÚappendÚextendÚjoinr   r   Ústorer
   r   r   r   r   r   ÚstripÚlenÚclose)"r%   r9   r&   Ú
mailbox_idr0   r2   ÚimapÚmessagesÚmsg_idÚmsgÚfrom_headerÚ_Ú
from_emailÚsubjectÚ
authorizedÚauth_msgÚattachmentsr<   Ú
text_linesr?   rA   Úsaved_raw_pathsÚpÚresultsÚerror_resultsÚrÚhas_error_flagÚbodyÚextra_linesÚerÚfnameÚerr_textÚtbr@   r+   r+   r,   Úprocess_mailboxA   sÞ   " üö

ÿÿÿ
	
û"
€þÿ


€û
 $érm   N)Ú__doc__Ú
__future__r   Ú
contextlibr   Úemail.utilsr   Úapps.wp_invoices_mail_app.authr   Ú apps.wp_invoices_mail_app.configr   Ú&apps.wp_invoices_mail_app.email_clientr   r   r	   r
   r   Ú#apps.wp_invoices_mail_app.processorr   r   Ú#apps.wp_invoices_mail_app.renderersr   r   Ú'apps.wp_invoices_mail_app.storage_pathsr   r   r-   rm   r+   r+   r+   r,   Ú<module>   s    
$