
    ~iwi                         d Z ddl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 ddlZddlZddlmZ dd	Zd
 Zd Zd Zd ZdS )z<
app_init.py
===========
Flask application factory pattern.
    )Flaskgrender_template)CORS)Session)AuthService)auth_bpN)datetimec                    t          t          dd          t          j        dd          dk    j        d<   t          j        dd	          j        d
<   t          j        dd          j        d<   dj        d<   dj        d<   dj        d<   t                     t          dddii           t                     t                      j	        fd            }
                    t                     ddlm} 
                    |           ddlm} 
                    |           ddlm} 
                    |           ddlm} 
                    |           t)                     t+                                         d          d             }                    d           d!             }                    d"          d#             }                    d$d%d&g'          fd(            }	                    d)d%g'          fd*            }
                    d+d%g'          fd,            }                    d-d&g'          fd.            }j                            d/           S )0z(Factory function per creare l'app Flask.	templatesstatic)template_folderstatic_folderFLASK_DEBUGFalseTrueDEBUG	FLASK_ENV
productionENVFLASK_SECRET_KEYzdev-secret-key
SECRET_KEY
filesystemSESSION_TYPEFSESSION_PERMANENTz/tmp/enigma_sessionsSESSION_FILE_DIRz/api/*origins*)	resourcesc                        t           _        d S N)r   auth_service)r"   s   1/var/www/tmov.alphamb/tmov_inventario/app_init.pybefore_requestz"create_app.<locals>.before_request/   s    %    r   )inventory_bp)warehouse_bp)items_bp)	export_bpz/loginc                       t          d          S )Nz
login.htmlr    r%   r#   
login_pagezcreate_app.<locals>.login_pageP   s    |,,,r%   z
/dashboardc                       t          d          S )Nzdashboard.htmlr+   r,   r%   r#   	dashboardzcreate_app.<locals>.dashboardT   s    /000r%   z/inventory/scannerc                       t          d          S )Nzscanner.htmlr+   r,   r%   r#   scannerzcreate_app.<locals>.scannerX   s    ~...r%   z/auth/loginPOSTGETmethodsc                      ddl m} m}m}m} | j        dk    r | |d                    S j                            d          }|r
 |            S  |ddi          dfS )	z1Alias per /api/v1/auth/login - usato dal frontendr   )requestjsonifyredirecturl_forr3   r-   z
auth.loginerrorAuth endpoint not found  )flaskr7   r8   r9   r:   methodview_functionsget)r7   r8   r9   r:   auth_login_funcapps        r#   auth_login_aliasz$create_app.<locals>.auth_login_aliasb   s     	>===========>U""8GGL11222 ,00>> 	F"?$$$7G%>?@@#EEr%   z/auth/logoutc                  z    j                             d          } | r
 |             S ddlm}  |ddi          dfS )zAlias per /api/v1/auth/logoutzauth.logoutr   r8   r;   r<   r=   r@   rA   r>   r8   )auth_logout_funcr8   rC   s     r#   auth_logout_aliasz%create_app.<locals>.auth_logout_aliasr   sa     -11-@@ 	F##%%%%%%%%%7G%>?@@#EEr%   z/auth/refresh-tokenc                  z    j                             d          } | r
 |             S ddlm}  |ddi          dfS )z$Alias per /api/v1/auth/refresh-tokenzauth.refresh_tokenr   rF   r;   r<   r=   rG   )auth_refresh_funcr8   rC   s     r#   auth_refresh_aliasz&create_app.<locals>.auth_refresh_alias|   sb      .223GHH 	F$$&&&%%%%%%7G%>?@@#EEr%   z/auth/mec                  z    j                             d          } | r
 |             S ddlm}  |ddi          dfS )zAlias per /api/v1/auth/mezauth.get_current_userr   rF   r;   r<   r=   rG   )auth_me_funcr8   rC   s     r#   auth_me_aliasz!create_app.<locals>.auth_me_alias   s^     )--.EFF 	F<>>!%%%%%%7G%>?@@#EEr%   u   ✅ Flask app initialized)r   __name__osgetenvconfigr   r   setup_logging_create_auth_servicer$   register_blueprintr	   app.routes.inventoryr&   app.routes.warehouse_reportr'   app.routes.inventory_itemsr(   app.routes.exportr)   register_system_routessetup_error_handlersrouteloggerinfo)rS   r$   r&   r'   r(   r)   r-   r/   r1   rD   rI   rL   rO   rC   r"   s                @@r#   
create_appr`      sm     +&( ( (C
 )M7;;vECJw	+|<<CJu!y);=MNNCJ| ".CJ~&+CJ"#%;CJ!" CLLL 	Y$456666 # ())L& & & & & 7### 211111<((( 988888<((( 4333338$$$ ,+++++9%%% 3  	YYx- - - 	YY|1 1 1 	YY#$$/ / %$/ 	YY}vuoY66F F F F 76F 	YY~xY00F F F F 10F 	YY$vhY77F F F F 87F 	YYzE7Y++F F F F ,+F JOO/000Jr%   c                  <   t          j        dd          t          j        dd          t          j        dd          t          j        dd          d	} t          j        d
d          }t          t          j        dd                    }t          | |d|          S )zCrea istanza AuthService.DB_HOST	localhostDB_USERenigma_userDB_PASSWORD
arcana2026DB_NAMEenigma)hostuserpassworddatabaseJWT_SECRET_KEYEnigmaProjectJWT_EXPIRATION_HOURS   HS256)	db_config
jwt_secretjwt_algorithmjwt_expiration_hours)rQ   rR   intr   )rs   rt   jwt_expirations      r#   rU   rU      s     	)[11	)]33Im\::Ii22	 I +_==J#92>>??N+	   r%   c                                            ddg           fd            }                      ddg          d             }dS )zRegistra routes di sistema.z/healthr3   r4   c            	         ddl } d}d}	 |                     t          j        dd          t          j        dd          t          j        dd	          t          j        d
d          d          }|                                 d}n&# t
          $ r}t          |          }Y d}~nd}~ww xY wdj        d         ||dt          j	                    
                                dS )zHealth check endpointr   Nu   ❌rb   rc   rd   re   rf   rg   rh   ri   utf8mb4)rj   rk   rl   rm   charsetu   ✅u   🟢 ENIGMA runningr   z
0.1.0-demo)statusenvironmentrm   database_errorversion	timestamp)pymysqlconnectrQ   rR   close	ExceptionstrrS   r
   utcnow	isoformat)r   db_okdb_errorconnerC   s        r#   healthz&register_system_routes.<locals>.health   s     		??Yy+66Yy-88=,??9h77! #  D JJLLLEE 	 	 	1vvHHHHHH	 ,:e,&#!**4466
 
 	
s   A<B 
B+B&&B+/c                  :    ddl m} m}  |  |d                    S )z!Root endpoint - redirect to loginr   r9   r:   r-   )r>   r9   r:   r   s     r#   indexz%register_system_routes.<locals>.index   s6     	,+++++++x--...r%   N)r]   )rC   r   r   s   `  r#   r[   r[      ss     	YYy5'Y**
 
 
 
 +*
: 	YYsUGY$$/ / %$/ / /r%   c                    t          j        dd          }t          j        dd          }t          j                    }|                    |           |                    |           	 d}t           j                            |          st          j	        |d           t          j
        | d	          }|                    |           |                    |           | j                            |           n)# t          $ r}t          d
|            Y d}~nd}~ww xY w| j                            |           | j                            |           dS )zSetup logging per l'app.	LOG_LEVELINFOz6[%(asctime)s] %(levelname)s in %(module)s: %(message)sz%Y-%m-%d %H:%M:%S)datefmtz/var/log/enigma_inventarioT)exist_okz/app.logz'Warning: Could not setup file logging: N)rQ   rR   logging	FormatterStreamHandlersetLevelsetFormatterpathexistsmakedirsFileHandlerr^   
addHandlerr   print)rC   	log_level	formatterconsole_handlerlog_dirfile_handlerr   s          r#   rT   rT      sp   	+v..I!@#  I
 +--OY'''  +++
=.w~~g&& 	0K$////*g+?+?+?@@i(((!!),,,
l++++ = = =;;;<<<<<<<<= J/***J	"""""s   *BC= =
D#DD#c                                            d          d             }                      d          d             }                      d           fd            }dS )zSetup custom error handlers.  c                 ,    ddt          |           ddfS )Nz	Not found	NOT_FOUND)r;   coder   r   )r   r;   s    r#   	not_foundz'setup_error_handlers.<locals>.not_found   s,     !JJ
 
 	 	r%     c                     ddddfS )NzMethod not allowedMETHOD_NOT_ALLOWEDr;   r   r   r,   r   s    r#   method_not_allowedz0setup_error_handlers.<locals>.method_not_allowed   s#     *(
 
  	r%   r=   c                 L    j                             d|             ddddfS )NzInternal error: zInternal server errorINTERNAL_ERRORr   r=   )r^   r;   )r;   rC   s    r#   internal_errorz,setup_error_handlers.<locals>.internal_error   sA    
3E33444,$
 
  	r%   N)errorhandler)rC   r   r   r   s   `   r#   r\   r\      s     	c   	c   	c      r%   r!   )__doc__r>   r   r   r   
flask_corsr   flask_sessionr   services_auth_servicer   routes_authr	   r   rQ   r
   r`   rU   r[   rT   r\   r,   r%   r#   <module>r      s     , + + + + + + + + +       ! ! ! ! ! ! - - - - - -        				      A A A AH  (%/ %/ %/P# # #:    r%   