
     $i#(              
       $   d dl mZmZmZmZmZmZ d dlmZ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 d dlmZ d d	lmZ d d
lZd d
lZd dlmZ d d
lZ eddg      ZejA                  d       ed       eejB                        fdedefd       Z"ejA                  d       ed       ee      fde#de#dedefd       Z$ejA                  d       ee       ee      fdededefd       Z%ejM                  d      de'fd       Z(y
)     )	APIRouterstatus
UploadFileFileFormDepends)JSONResponseFileResponse)DocumentsClass)StudentClass)get_db)get_current_active_user)	UserLoginCreateDocumentRequestDocumentListRequestUploadDocumentRequest)Session)PathN)datetimez
/documents	Documents)prefixtagsz/create.filedocument_datac           	        K   d}	 | j                   j                  d      st        t        j                  dddd      S t        j                  dd      5 }| j                          d{   }|j                  |       |j                  }ddd       |j                  }|j                  }t        j                  ||	      }|r4t        j                  j!                  |      rt        j"                  |       |d
   dk(  r"t        t        j$                  d|d   dd      S t'        |d   |d   d      }t)        |      |j*                  d<   |S 7 # 1 sw Y   xY w# t,        $ rt}	|r=t        j                  j!                  |      r	 t        j"                  |       n#  Y nxY wt        t        j$                  ddt)        |	       dd      cY d}	~	S d}	~	ww xY ww)z
    Crea un documento procesado a partir de un PDF subido.
    Reemplaza [STUDENT_NAMES] con el nombre del estudiante proporcionado.
    Nz.pdfi  zEl archivo debe ser un PDFr   messagedatastatus_codecontentF)deletesuffix)original_file_pathstudent_namer   error  r   	file_pathfilenameapplication/pdfpathr)   
media_typezX-Document-Type-IdzError general: )r)   endswithr	   r   HTTP_400_BAD_REQUESTtempfileNamedTemporaryFilereadwritenamer%   document_type_idr   parent_authorizationosr,   existsunlinkHTTP_500_INTERNAL_SERVER_ERRORr
   strheaders	Exception)
r   r   temp_file_path	temp_filer!   r%   r5   resultresponsees
             [C:\Users\jesus\OneDrive\Escritorio\proyecto_pie360\backend\app\backend\routers\documents.pycreate_documentrD      s     NA
}}%%f-"77!;   ((fE 	, IIK'GOOG$&^^N	, %11(9944-%
 bggnn^<IIn%(w&"AA!%i0    $J'(

 255E1F-.E (	, 	,J  
bggnn^<		.)==,SVH5
 	

s   G 9E  G  E  E+E,!EBE  #G $-E  G EEE   	G)!GF! G!F%#/GGG GG z'/upload/{student_id}/{document_type_id}
student_idr5   dbc                   K   	 t        |      }|j                  |       }t        |t              rg|j                  d      s|j                  d      dk(  rBt	        t
        j                  d|j                  d      xs |j                  dd      dd      S |j                  d	i       }|j                  d
      xs t        |       }t        |      }|j                  |      }	t        |	t              rC|	j                  d      dk(  r/t	        t
        j                  d|	j                  dd      dd      S |	j                  d      }
|j                  r-t        |j                        j                  j                         nd}|j                  dd      j                  dd      }d| d|
 | }t        d      }|j                  dd       ||z  }|j                          d{   }t!        |d      5 }|j#                  |       ddd       |j%                  | ||      }t        |t              ri|j                  d      dk(  rU|j'                         r	 t)        j*                  |       t	        t
        j,                  d|j                  dd      dd      S t	        t
        j.                  dd|j                  d      |j                  d      | ||t        |      |j                  dd      S 7 # 1 sw Y   xY w#  Y xY w# t0        $ rE}|j3                          t	        t
        j,                  ddt        |       dd      cY d}~S d}~ww xY ww)z+
    Sube un documento (PDF o imagen).
    r&   r     r   zEstudiante no encontradoNr   r   student_dataidentification_numberzDocumento no encontradoid .-	document__zfiles/system/studentsT)parentsexist_okwb)rE   r5   r(   r'   z&Error guardando registro del documento   zDocumento subido exitosamentedocument_id
version_id)rK   rV   rE   r5   r)   r(   original_filenamezError subiendo archivo: )r   get
isinstancedictr	   r   HTTP_404_NOT_FOUNDr;   r   r)   r   r#   lowerreplacemkdirr2   openr3   storer8   r7   r9   r:   HTTP_201_CREATEDr=   rollback)rE   r5   r   rF   student_servicestudent_resultrI   student_identification_numberdocumentdocument_resultrU   file_extension	clean_rutunique_filename
upload_dirr(   r!   fstore_resultrB   s                       rC   upload_documentrn   f   sN    g
&r*(,,Z8nd+1C1CG1LP^PbPbckPlpwPw"55!-11':wn>P>PQZ\v>w   &))."=(4(8(89P(Q(dUXYcUd% ""%",,'78ot,1D1DX1NRY1Y"55!.229>WX   &))$/ @D}}dmm,3399;RT 299#rBJJ3PRS	 &i[+~>NO 12
50	 		#)T" 	aGGG	  ~~!-% & 
 lD)l.>.>x.HG.S!IIi(  "AA!+//	;cd   //:&**=9"."2"2<"@",(8 /!$Y)-
 	
7 $	 	6  	

==5c!fX>
 	
	
s   MBL
 MBL
 5M6B.L
 $K4%L
 5K7AL
 L -.L
 MAL
 3M4L
 7L <L
 LL
 
	M:MMMMMz/listfilterssession_userc           	        K   	 t        |      }|j                  | j                        }t        |t              rC|j                  d      dk(  r/t        t        j                  d|j                  dd      dd      S t        t        j                  d	|rd
nd|d      S # t        $ r5}t        t        j                  ddt        |       dd      cY d}~S d}~ww xY ww)zZ
    Lista los documentos configurados, devolviendo solo document_type_id y document.
    r   r&   r'   r   zError listando documentosNr   r      zDocumentos encontradoszNo hay documentos registradoszError listando documentos: )r   get_allr5   rY   rZ   rX   r	   r   r:   HTTP_200_OKr=   r;   )ro   rp   rF   	documentsr   rB   s         rC   list_documentsrv      s     
"2&	  !9!9:dD!dhhx&8G&C"AA!#xx	3NO   **7;3A`
 	
  
==8QA
 	

sA   C!A8B  <C!="B  C! 	C)*CCC!CC!z/download/{filename}r)   c           	      6  K   	 t        d      | z  }|j                         st        t        j                  ddd d      S t        t        |      | d      S # t        $ r5}t        t        j                  dd	t        |       d d      cY d }~S d }~ww xY ww)
Nzfiles/original_student_filesrH   zArchivo no encontrador   r   r*   r+   r'   zError descargando archivo: )	r   r8   r	   r   r[   r
   r;   r=   r:   )r)   r(   rB   s      rC   download_documentrx     s     
788C	!"55!6   Y(
 	
  
==8QA
 	

s@   B<A  BA B	B!*BBBBB))fastapir   r   r   r   r   r   fastapi.responsesr	   r
   #app.backend.classes.documents_classr   !app.backend.classes.student_classr   app.backend.db.databaser   app.backend.auth.auth_userr   app.backend.schemasr   r   r   r   sqlalchemy.ormr   pathlibr   r0   r7   r   uuidru   postas_formrD   intrn   rv   rX   r;   rx        rC   <module>r      s[   F F 8 > : * >  #   	  
	
 	Cy+23H3P3P+QJ

J
(J
 J
X 9: Cy&/	p
p
p
 p
 		p
 ;p
d  &&=>&/'
 '
'
 	'
 '
R %&

 '
r   