
    _khL                     $   d dl mZ d dlZd dlZd dlZd dlZd dlmZmZm	Z	m
Z
mZmZmZmZmZmZ d dlmZ d dlZd dlZd dlZd dl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#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZE  eeFd      ZGdeG_H        deGj                  d<    ed      eGj                  d<    ed      eGj                  d<    eeG       d ZJeJeGj                  j                  d<   eGj                  d        ZNeGj                  dddg      d        ZPeGj                  d      d         ZQeGj                  d!ddg      d"        ZReGj                  d#ddg      d$        ZSeGj                  d%ddg      d&        ZTeGj                  d'ddg      d(        ZUeGj                  d)ddg      d*        ZVeGj                  d+dg      d,        ZWeGj                  d-dg      d.        ZXeGj                  d/ddg      d0        ZYeGj                  d1ddg      d2        ZZeGj                  d3ddg      d4        Z[eGj                  d5ddg      d6        Z\eGj                  d7ddg      d8        Z]eGj                  d9dg      d:        Z^eGj                  d;dg      d<        Z_eGj                  d=      d>        Z`d? ZaeFd@k(  reGj                          yy)A    )	timedeltaN)
Flaskrender_templaterequestsessionflashredirectjsonifyurl_for	send_fileResponse)Session)datetime)ZoneInfo)	onduty_itlara_bot_idtranslationonduty_recruitment)init_db)secure_filename)get_login_userget_company_view_dataget_company_data_for_editget_data_from_fk_tableupdate_companyget_insert_descriptionupdate_contact_personinsert_contact_personinsert_company_and_get_idupdate_google_urlget_company_by_id_for_loginsert_audit_logget_logs_from_db#get_customer_interactions_view_data"get_customer_interactions_for_editupdate_customer_interactions,get_insert_description_customer_interactions'insert_customer_interactions_and_get_id-get_customer_contact_person_with_company_name'get_customer_interactions_by_id_for_log)send_msg_telegramallowed_filecompare_changesupload_files_to_google_drivelist_files_in_folderrename_fileget_country_dialing_codescreate_google_folderget_company_new_data_from_formget_change_diff,get_customer_interactions_new_data_from_form$get_change_diff_customer_interaction	parse_intz/crm/static)static_url_path
asndijnsauFSESSION_COOKIE_SECURE   )daysREMEMBER_COOKIE_DURATIONx   )minutesPERMANENT_SESSION_LIFETIMEc                     	 t        j                  | j                  dd            }|j                  t	        d            }|j                  d      S # t        $ r}| cY d }~S d }~ww xY w)NZz+00:00zEurope/Zurichz%d-%m-%Y %H:%M:%S)r   fromisoformatreplace
astimezoner   strftime	Exception)iso_dateutc_timezurich_timees       /var/www/html/crm/app.pyformat_iso_date_numericrM   1   sd    
))(*:*:3*IJ ))(?*CD ##$788 s   AA 	A'A"A'"A'format_iso_datec                 `   dgg dg dg dg dg dd}g }|j                         D ]*  \  }}|j                  | ddj                  |              , d	j                  |      | j                  d
<   d| j                  d<   d| j                  d<   d| j                  d<   d| j                  d<   | S )N'self')rP   https://cdn.jsdelivr.nethttps://cdnjs.cloudflare.comzhttps://fonts.googleapis.comz-https://cdn.jsdelivr.net/npm/select2/dist/csshttps://www.gstatic.com'unsafe-inline')rP   zhttps://code.jquery.comrQ   rR   z&https://cdn.jsdelivr.net/npm/popper.jsz&https://cdn.jsdelivr.net/npm/bootstrapz,https://cdn.jsdelivr.net/npm/select2/dist/jszhttps://translate.google.com https://translate.googleapis.com#https://translate-pa.googleapis.comrT   )rP   zdata:https://fonts.gstatic.comzhttps://www.google.comrS   rU   )rP   rR   rW   )rP   rU   rV   )zdefault-srcz	style-srcz
script-srczimg-srczfont-srczconnect-src z; zContent-Security-Policy
SAMEORIGINzX-Frame-OptionsnosniffzX-Content-Type-Optionszstrict-origin-when-cross-originzReferrer-Policyz<geolocation=(), microphone=(), camera=(), payment=(), usb=()zPermissions-Policy)itemsappendjoinheaders)responsecspcsp_directives	directivesourcess        rL   apply_security_headersrd   A   s     !z





K*CZ N!iik B	71SXXg->,?@AB 37))N2KH./ +7H&'1:H-.*KH&'F )* O    z/loginGETPOST)methodsc                  8   d} d}dt         vrdt         d<   dt         d<   t        j                  dk(  rt        j                  j	                  dd	      j                         }t        j                  j	                  d
      }|r|st        dd       t        d      S t        j                         }t         d   | k\  r]t         d   rB|t         d   z
  |k  r3||t         d   z
  z
  }t        dt        |       dd       t        d      S dt         d<   dt         d<   	 t        |      }|rt        j                  |j                  d      |d   j                  d            rHt        j                          |d   t         d<   dt         d<   dt         d<   t        d       t!        d      S t         dxx   dz  cc<   |t         d<   t        dd       t        d      S t        d      S # t"        $ r/}t        d|        t        dd       t        d      cY d}~S d}~ww xY w)zc
    Handles login requests using GET and POST methods with rate limiting for failed attempts.
       <   failed_attemptsr   Nlast_attempt_timerg   login passwordu   Bitte alle Felder ausfüllen!warning
login.htmlz$Zu viele Versuche. Bitte warten Sie z
 Sekunden.dangerzutf-8   username   adminTvalidxesz/crm/z$Falscher Benutzername oder Passwort!zLogin Fail: z4Etwas ist schief gelaufen. Bitte IT Team konaktieren)r   r   methodformgetlowerr   r   timeintr   bcryptcheckpwencodeclearprintr	   rG   )MAX_ATTEMPTSTIMEOUT_SECONDSlogin_emaillogin_passwordnowremaining_timeresultrK   s           rL   rn   rn      s   
 LO '%&!"'+#$~~ll&&w399; ))*5.19="<00 iik$%5*+g>Q6R0RUd0d!0C'BU:V4V!W<S=P<QQ[\^fg&|44 ./)*/3+,	1#K0F&..)>)>w)GPQIYIYZaIbc&,Qi
##$ #' e(( )*a/*/2+,<iH&|44 |,,  	1L$%H(S"<00		1s%   BG! %0G! !	H*$HHHz/logoutc                  X    t        j                          t        dd       t        d      S )z^
    Logs out the current user by clearing the session and redirecting to the login page.
    zErfolgreich ausgeloggt.successz
/crm/login)r   r   r   r	    re   rL   logoutr      s#    
 MMO	
#Y/L!!re   /c                     t        t               dt        v rat        d   du rVt        j                  j	                  d      xs t        j
                  j	                  d      } t        d| t        d   |       S t        d      S )a  
    Serves as the home page of the application.

    This endpoint checks if a user session is valid. If valid, it displays the home page which may
    include a table view or other user-specific information. If the session is not valid, it redirects
    the user to the login page.

    Returns:TranslateElementher display the home page if the user is logged in, 
        or redirect to the login page if not.
    rx   T	site_name
index.htmlru   )tableru   r   rr   )r   r   r   r{   r|   argsr   )statuss    rL   indexr      si     
'N'gg.$6!!+.O',,2B2B;2O|FwzGZhnoo<((re   z/customer_relations_viewc                  n   dt         v r't         d   du r	 t               \  } }t        | |d      S t        dd	       t        d
      S # t        $ rd t	        j
                         }t        |       t        j                  t        t        d| t                     t        dd       t        d      cY S w xY wNrx   T)columnsdataDatabase query failed: zDatenbankfehler!rs   r   Bitte einloggen!rq   rr   )r   r$   r
   rG   	traceback
format_excr   asynciorunr+   r   r   r   r   column_namesrowsfull_tracebacks      rL   customer_interactions_viewr      s    'gg.$6	1!D!FL$|TBCC 

i(<((  	1&113N.!KK)+8OP^O_6`ajkl$h/"<00	1s   A A*B43B4z/company_viewc                     dt         v r3t         d   du r(	 t               \  } }t        | |       t        | |d      S t        dd	       t        d
      S # t        $ rd t        j                         }t        |       t        j                  t        t        d| t                     t        dd       t        d      cY S w xY wr   )r   r   r   r
   rG   r   r   r   r   r+   r   r   r   r   r   s      rL   company_viewr      s    'gg.$6		1!6!8L$,%|TBCC 

i(<((  	1&113N.!KK)+8OP^O_6`ajkl$h/"<00	1s   &A A*C ?C z/edit_form/company/<row_id>c                 L   dt         v rt         d   du r	 t        D ci c]  }|d   |d    }}t        |       \  }}t        ddd      }t	        |       }t               \  }}t        ddd      }	t        d	|	||||||| |t        j                  |      d
t         d         S t#        dd       t        d      S c c}w #  t        j                         }
t        |
       t        j                  t        t        d|
 dt                      t#        dd       t        d      cY S xY w)  
    Renders a form for editing specific user data. 
    Access to this form is restricted to logged-in users.
    The form includes dropdowns populated from foreign key tables and 
    fields for user data entry based on database schema.

    The function fetches existing user data from the database 
    and prepares dropdown lists with foreign key
    table data to facilitate user input corrections or updates.

    Args:
        user_id (str): The unique identifier for the user whose data needs to be edited.

    Returns:
        - Renders 'edit.html' with user data and dropdown options if the session is valid.
        - Redirects to 'login.html' with a warning message if the session is not valid.
        - Returns to 'index.html' with an error message if there is an exception during data fetching.
    Raises:
        - Exception: Captures any exceptions during data fetching or processing, 
        logs the error, and
        optionally notifies the IT team via Telegram. The user is then informed of a database error.

    Example Usage:
        - Accessing '/edit_form/12345' with a valid session will render 'edit.html'
        for editing the data of user 12345.
        - If a user is not logged in and tries to access this route, they will 
        be redirected to the login page.

    Notes:
        - This endpoint ensures all form submissions and edits are authenticated 
        to protect against unauthorized data manipulation.
        - It is vital to handle foreign key data carefully to ensure data integrity 
        and maintain consistency in dropdowns.
        - The function makes extensive use of database interactions to fetch currently relevant data

        user data and related foreign key information.
    rx   Tdbdecompany_industryrv   Fcompany_statusz	edit.html0ru   )r   country_namescompany_datacompany_contact_person_datafilesindustrytranslationsrow_idprefixprefix_jsonr   ru   r   z | Talentsphere&Datenbankfehler! Bitte IT Team melden.rs   r   r   rq   rr   )r   r   r   r   r/   r1   r   jsondumpsr   r   r   r   r   r+   r   r   r   )r   itemr   company_column_name_and_value,company_contact_person_column_name_and_valuer   r   country_dial_codesr   r   r   s              rL   company_edit_formr      sp   N 'gg.$6	1?JKtDJT
2KLK[tu{[|W)+W-.@5IH(0E0I0K-34DaON";an  @]  |h+0XVbms  Q  ^b  ^h  ^h  i{  ^|  JM  Za  bl  Zmn n 

i(<(( L	1&113N.!KK)+8OP^O__n6opyz{:HE"<00s   B= B8A3B= 8B= =A$D#z)/edit_form/customer_interactions/<row_id>c                    dt         v rt         d   du rz	 t        D ci c]  }|d   |d    }}t        |       }t        ddd      }t        ddd      }t	        |d	 
      }t        |d   d         }t        d|||||| dt         d   	      S t        dd       t        d      S c c}w #  t        j                         }t        j                  t        t        d| dt                     t        dd       t        d      cY S xY w)r   rx   Tr   r   communication_methodrv   Fcompanyc                 (    | d   j                         S )Ndescription)r}   )xs    rL   <lambda>z1customer_interactions_edit_form.<locals>.<lambda>a  s    Am4D4J4J4L re   )keyr   zinteraction_edit.html1ru   )company_contact_personr   +customer_interactions_column_name_and_valuer   r   r   r   ru   r    | CRMr   rs   r   r   rq   rr   )r   r   r%   r   sortedr)   r   r   r   r   r   r+   r   r   r   )r   r   r   r   r   r   r   r   s           rL   customer_interactions_edit_formr   3  sS   N 'gg.$6	1?JKtDJT
2KLK;]^d;e7#9:PQRSX#Y ,Yq?GW*LMG%RS~  @A  TB  CL  TM  &N""#:Tjv}  nY7K\hsy  HK  X_  `j  Xkl l 

i(<(( L	1&113NKK)+8OP^O__e6fgpqr:HE"<00s   B* B%A B* %B* *ADz /edit_data/customer_interactionsc            	         dt         v rWt         d   rM	 t        j                  j                  d      } t        j                  j	                         D ci c]4  \  }}|dvr+|j                  d      s|j                  d      s	||dv rd n|6 }}}dj                  |D cg c]  }| d	 c}      }t        |j                               }t        |       }t        t              }t        ||      }t        d	| t         d
   |       t        |||        t        dd       t        j                  d   dk(  rt        ddt         d
         S t!        t#        d|             S t        dd       t        d      S c c}}w c c}w # t$        $ rc t'        j(                         }	t+        j,                  t/        t0        d|	 dt2                     t        dd       t        dt         d
         cY S w xY w)Nrx   r   r   idsubmitActioncontact_r   Nonero   ,  = %scustomer_interactionsru   Erfolgreich editiert!r   r   closer   r   r   ru   r   r   r   r   r   rs   ru   r   rq   rr   )r   r   r{   r|   r[   
startswithr]   listvaluesr*   r5   r6   r"   r&   r   r   r	   r   rG   r   r   r   r   r+   r   r   )
customer_interactions_idr   valupdate_data
update_setr   customer_interactions_old_datacustomer_interactions_new_datachangesr   s
             rL   customer_interactions_edit_datar   m  s   'gg.	O'.||'7'7'A$
 !( 2 2 4C>>z2w/	 c\1ds:K  [#Icse5M#IJJ+,,./F-TUm-n*-YZa-b*:;Y[yzG46NPWXbPcelm(V=UV )95||N+w6&|wWaObcc(IRj kll 

i(<((= $J  	O&113NKK)+8OP^O__e6fgpqr:HE"<'*:MNN		Os8   A F 9E8F  E>,BF F 8F A)G/.G/z/edit_data/companyc            	         dt         v r$t         d   r	 t        j                  j                  d      } t        j                  j	                         D ci c]4  \  }}|dvr+|j                  d      s|j                  d      s	||dv rd n|6 }}}t        |       }t        t              }t        ||      }t        d| t         d   |       d	j                  |D cg c]  }| d
	 c}      }t        |j                               }t        |||        g }	d}
t        j                  j                  d|
       rt        j                  j                  d|
       t        j                  j                  d|
       t        j                  j                  d|
       t        j                  j                  d|
       t        j                  j                  d|
       t        j                  j                  d|
       | d}|	j                  |       |
dz  }
t        j                  j                  d|
       r|	D ]  }|j                  d      rt        |j                  d            j!                         j#                         rIg d}d	j                  |D cg c]  }| d
	 c}      }|D cg c]  }||   	 }}t%        |||d          t'        |        t)        dd       t        j                  d   dk(  rt+        ddt         d         S t-        t/        d|             S t)        d#d$       t+        d%      S c c}}w c c}w c c}w c c}w # t0        $ rc t3        j4                         }t7        j8                  t;        t<        d| dt>                     t)        d d!       t+        dt         d   "      cY S w xY w)&Nrx   r   r   r   r   r   r   ru   r   r   rv   contact_name_contact_id_contact_email_contact_phone_contact_job_title_contact_prefix_)r   nameemailphone	job_titler   
company_idr   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rs   r   r   rq   rr   ) r   r   r{   r|   r[   r   r!   r3   r4   r"   r]   r   r   r   r\   strstripisdigitr   r   r   r   r	   r   rG   r   r   r   r   r+   r   r   )r   r   r   r   old_companynew_companyr   r   r   contact_personsicontactpersonfieldskupdater   s                    rL   company_edit_datar    s^   'gg.6	O ))(3J
 !( 2 2 4C>>z2w/	 c\1ds:K  4J?K8AK%k;?GY
GJ4GQ[#Icse5M#IJJ+,,./F:vz: !OA,,""]1##67!,,**[+<=#LL,,}QC-@A$\\--qc.BC$\\--qc.BC!(!1!14Fqc2J!K%ll../DE",  &&w/Q ,,""]1##67 * 2::d#FJJt,<(=(C(C(E(M(M(ONF!YYV'D1#U'DEF178AfQi8F8)&&&,G)&12 )95||N+w6&|wWaObcc(;J OPP 

i(<((k $J0 (E8  	O&113NKK)+8OP^O__e6fgpqr:HE"<'*:MNN		OsY   A M 9MAM M'EM ?AM M
*M 5MAM M M A)OOz/insert_form/companyc                  J   dt         v rt         d   du r{	 t               } t        D ci c]  }|d   |d    }}t        ddd      }t        ddd      }t	               \  }}t        d	|||d
|| |t        j                  |      t         d   
      S t#        dd       t        d      S c c}w # t        $ rn t        j                         }t        |       t        j                  t        t        d| dt                      t#        dd       t        dt         d         cY S w xY w)  
    Zeigt ein Formular zum Erfassen einer neuen Firma mit Kontaktpersonen an.
    Nur für eingeloggte Benutzer zugänglich.

    - Lädt Feldübersetzungen.
    - Holt Branchen (FK-Daten) für Dropdown.
    - Gibt alle Daten an das HTML-Template weiter.
    rx   Tr   r   r   rv   Fr   zinsert.htmlr   ru   )	r   r   r   r   r   r   r   r   ru   r   r   r   rs   r   r   r   rq   rr   )r   r   r   r   r1   r   r   r   rG   r   r   r   r   r   r+   r   r   r   )r   r   r   r   r   r   r   r   s           rL   company_insert_formr    s=    'gg.$6	O13L @KKtDJT
2KLK ..@!UKH+,<aGF 1J0K-"+!))) JJ'9: , & 

i(<((9 L(  	O&113N.!KK)+8OP^O__e6fgpqr:HE"<'*:MNN	Os#   B+ B&AB+ &B+ +A4D"!D"z#/insert_form/costumer_interactioonsc            	         dt         v rbt         d   du rW	 t               } t        D ci c]  }|d   |d    }}t        ddd      }t        ddd      }t	        d	|||| t         d
         S t        dd       t	        d      S c c}w # t
        $ rn t        j                         }t        |       t        j                  t        t        d| dt                     t        dd       t	        dt         d
         cY S w xY w)r  rx   Tr   r   r   rv   Fr   zinteraction_insert.htmlru   )r   r   r   r   ru   r   r   r   rs   r   r   r   rq   rr   )r   r'   r   r   r   rG   r   r   r   r   r   r+   r   r   r   )r   r   r   r   r   r   s         rL   !customer_interactions_insert_formr     s    'gg.$6	OGIL @KKtDJT
2KLK#9:PQRSX#Y ,Yq?G")';)) ,  

i(<((' L  	O&113N.!KK)+8OP^O__e6fgpqr:HE"<'*:MNN	Os"   B B3B B A4C>=C>z"/insert_data/customer_interactionsc            	      `   dt         v r6t         d   r+	 t        j                  j                  d      t        j                  j                  d      t	        t        j                  j                  d            t	        t        j                  j                  d            t	        t        j                  j                  d            t        j                  j                  d      d} t        |       }t        d	d
       t        j                  d   dk(  rt        ddt         d         S t        t        d|            S y y # t        $ rc t        j                         }t        j                  t        t         d| dt"                     t        dd       t        dt         d         cY S w xY w)Nrx   date	follow_upcommunicated_overr   company_usernote)r  r	  r
  r   r  r  z(Kunden Interaktion erfolgreich erstellt!r   r   r   r   r   ru   r   r   r   r   r   r   rs   r   )r   r   r{   r|   r7   r(   r   r   r	   r   rG   r   r   r   r   r+   r   r   )customer_interactions_datar   r   s      rL   !customer_interactions_insert_datar  %  sZ   'gg.	O((0$\\--k:%.w||/?/?@S/T%U$W\\%5%5i%@A )',,*:*:>*J K((0*& AA[\J <iH||N+w6&|wWaObcc(IR\ ]^^+ /,  	O&113NKK)+8OP^O__e6fgpqr:HE"<'*:MNN		Os   DE )E A)F-,F-z/insert_data/companyc            	      F   dt         v rt         d   r	 t        j                  j                  d      } | r| j	                         dk(  rd } nt        |       } t        j                  j                  d      t        j                  j                  d      t        j                  j                  d      t        j                  j                  d      t        j                  j                  d      t        j                  j                  d	      | d
}t        |      }g }d}t        j                  j                  d|       rt        j                  j                  d|       t        j                  j                  d|       t        j                  j                  d|       t        j                  j                  d|       t        j                  j                  d|       |d}|j                  |       |dz  }t        j                  j                  d|       r|D ]  }t        |        t        t        |      }t        ||       t        dd       t        j                  d   dk(  rt        ddt         d         S t        t        d|            S t        d!d"       t        d#      S # t         $ rc t#        j$                         }t'        j(                  t+        t,        d| dt.                     t        dd       t        dt         d          cY S w xY w)$Nrx   r   noner   r   r   r   addresspostal_code)r   r   r   r   r  r  r   rv   r   r   r   r   r   )r   r   r   r   r   r   zFirma erfolgreich erstellt!r   r   r   r   r   ru   r   r   r   r   r   r   rs   r   r   rq   rr   )r   r   r{   r|   r}   r   r   r\   r   handle_account_creationr2   r    r   r   r	   r   rG   r   r   r   r   r+   r   r   )industry_valuer   r   r   r   r   	folder_idr   s           rL   company_insert_datar  C  s   'gg.4	O$\\--j9N!^%9%9%;v%E!%!$^!4((0 ))'2!,,**84 ))'2"<<++I6&||//>*L 3<@J !OA,,""]1##67#LL,,}QC-@A$\\--qc.BC%ll../DE$\\--qc.BC!(!1!14Fqc2J!K",  &&v.Q ,,""]1##67 * .%f-. 00DjQIi
3/;||N+w6&|wWaObcc(;J OPP 

i(<((  	O&113NKK)+8OP^O__e6fgpqr:HE"<'*:MNN		Os    HJ4 "A$J4 J4 4A)L L z/logs/<table>/<row_id>c           	         dt         v rVt         d   du rK	 t        D ci c]  }|d   |d    }}t        | |      }|r|d   d   nd}t        d| |||t         d	   
      S t        dd       t        d      S c c}w # t        $ rc t        j                         }t        j                  t        t        d| dt                     t        dd       t        dt         d	         cY S w xY w)a  
    Handles requests to display log details for a specific user based on the provided `table` and `user_id`.
    This function retrieves and processes log data, highlighting changes and resolving foreign key values for readability.
    The details are displayed on 'logs.html'.

    Processes:
        - Verifies if the user session is valid. If not, prompts the user to log in.
        - If the session is valid, fetches and processes log data associated with the user.
        - Processes the log data to highlight changes between records, making it easier for users to understand modifications.
        - Resolves foreign key data into readable values using helper functions for better context.

    Args:
        - table (str): Specifies the database table to query (e.g., "employee" or "administration").
        - user_id (str): The unique identifier of the user for whom log details are being fetched.

    Returns:
        - Renders 'logs.html' with processed log data, translations, and additional context for a valid session.
        - Redirects to 'login.html' with a warning message if the session is not valid.
        - Renders 'index.html' with an error message if there is an exception during data retrieval or processing.

    Raises:
        - Exception: Catches exceptions related to data fetching and processing, logs the traceback, and optionally notifies
          the IT team via Telegram. Displays a generic database error message to the user.

    Notes:
        - This endpoint requires active session validation to ensure that only authenticated users can view log details.
        - Error handling includes full traceback logging for diagnostics and user-friendly error messaging.
        - External function `log_view` is used to fetch initial log data.
        - The `compare_detailed_changes_*` functions are used to identify and process changes between logs for display.
        - Foreign key data is resolved using `get_fk_data_from_dict` for readability.
    rx   Tr   r   r   r   	Unbekanntz	logs.htmlru   )r   r   r   r   ru   r   r   r   rs   r   r   r   rq   rr   )r   r   r#   r   rG   r   r   r   r   r+   r   r   r   )r   r   r   r   logsr   r   s          rL   get_logsr    s   F 'gg.$6	O?JKtDJT
2KLK#E62D&*476?D #) , " 

i(<((1 L  	O&113NKK)+8OP^O__e6fgpqr:HE"<'*:MNN	Os"   A; A61A; 6A; ;A)C'&C'z/uploadc                     t         j                  j                  d      } t         j                  j	                  d      }| st        ddd      dfS g }t        j                  dd	       	 | D ]i  }|s|j                  st        |j                        }t        j                  j                  d|      }|j                  |       |j                  |       k t        |t        |      
      }t        d|d      |D ]7  }t        j                  j!                  |      s#t        j"                  |       9 S # |D ]7  }t        j                  j!                  |      s#t        j"                  |       9 w xY w)Nfiler   errorzNo files uploadedr   message  tmpT)exist_ok)folder_namer   )r   results)r   r   getlistr{   r|   r
   osmakedirsfilenamer   pathr]   saver\   r.   r   existsremove)r   r   local_pathsr  r(  
local_pathupload_resultsr)  s           rL   upload_filesr0    s&   MM!!&)E\\h'F'6IJKSPPKKK%  	/D*4==9WW\\%:
		*%"":.	/ 6ksSY{[)GH   	 Dww~~d#		$	 K 	 Dww~~d#		$	 s   +D9 3D9  A<D9 9%E7E7z/delete_gdrive_filec                     t         j                  j                  dd      } t         j                  j                  dd      }t         j                  j                  dd      }t        j                  j                  |      \  }}| st        ddd      dfS |r| d	| }n| d	}t        | |      }|rt        d
dd      S t        ddd      S )ao  
    Handles requests to delete or mark a Google Drive file as deleted.
    This function renames the specified file to indicate deletion and logs the change.

    Process:
        - Retrieves file details (file ID, file name, user ID) from the form data.
        - Checks if the file ID is provided; if not, returns an error response.
        - Creates a new name for the file, appending "_DELETED" to the original name.
        - Calls a helper function to rename the file on Google Drive.
        - Updates the log to reflect the file deletion and maintains a record of all prior files.

    Args:
        - None (relies on POST request data)

    Returns:
        - JSON response indicating success or failure.
        - If the file ID is missing, returns a 400 status with an error message.
        - Logs the deletion action for auditing and tracking purposes.

    Raises:
        - None (handled via return statements with JSON error responses).

    Example Usage:
        - Submitting a POST request to '/delete_gdrive_file' with valid file data will mark the specified
          Google Drive file as deleted, log the action, and return a success response.

    Notes:
        - This function assumes access to helper functions for file renaming, logging, and data retrieval.
        - Error handling includes clear user feedback for missing file IDs or failed rename actions.
    file_idN	file_namer   r  zFile ID missingr  r   _DELETEDr   zFile deletedzFile could not be deleted)r   r{   r|   r&  r)  splitextr
   r0   )r2  r3  r   	base_name	extensionnew_namer   s          rL   delete_gdrive_filer9    s    D lly$/G  d3I\\h-F 77++I6Iy '6GHI3NN [4[) (+F )GHH'6QRSSre   z/list_files/<row_id>c                     	 t        |       }t        D ci c]  }|d   |d    }}t        d|||       S c c}w # t        $ r}t	        d|       Y d }~yd }~ww xY w)Nr   r   zpartials/file_table.html)r   r   r   z Fehler beim Abrufen der Dateien:)zFehler beim Abrufen der Dateieni  )r/   r   r   rG   r   )r   r   r   r   rK   s        rL   list_files_ajaxr;    si    6$V,;FG4T
DJ.GG9Uajpqq H 60!456s!   ; 6; ; 	AAAc                      | | }|S )a`  
    Executes a given account creation function with the specified arguments.

    This function is designed to abstract the account creation process, allowing for flexibility in
    the account creation logic by passing different functions as arguments. It directly passes any 
    received arguments to the account creation function and returns the result.

    Args:
        create_account_func (callable): A function intended to handle the creation of an account.
                                        It should accept any number of arguments as required for the account creation.
        *args: Variable length argument list to be passed to the create_account_func.

    Returns:
        The return value from the create_account_func, which could be any data type based on the
        implementation of the function 
        (e.g., boolean indicating success/failure, a new account object, etc.).

    Example Usage:
        - result = handle_account_creation(create_user_account, 'john.doe@example.com', 'password123')
          This would attempt to create a user account with the provided email and password.

    Note:
        - This function does not handle exceptions that may be raised by 
        create_account_func. It is recommended to implement error handling within the passed 
        function or at the point where handle_account_creation is called.
    r   )create_account_funcr   r   s      rL   r  r  #  s    6 t
$CJre   __main__)cr   r   r   r&  requestsr   flaskr   r   r   r   r   r	   r
   r   r   r   flask_sessionr   r~   tr   astzoneinfor   setupr   r   r   r   r   r   werkzeug.utilsr   r   modelsr   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   
standaloner+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   __name__app
secret_keyconfigrM   	jinja_envfiltersafter_requestrd   routern   r   r   r   r   r   r   r   r  r  r  r  r  r  r0  r9  r;  r  r   r   re   rL   <module>rQ     s     	   r r r !    
   H H  *          Hm4 &+

" #)2):

% &+4S+A

' (  ,C  ' ( = =~ 8eV_-7- .7-r 9" " 365/*) +)& %&%A) B) ?vuo6) 7) (5&/B8) C8)t 6P7) Q7)r -x@$) A$)L &2;) 3;)z !E6?;+) <+)Z 05&/J") K")H /%IO JO: !E6?;9) <9)v #eV_=<) ><)~ 9vh'  ( :  6(39T 49Tv !"6 #6< zGGI re   