
    i	3                     r    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Zd dl m Z m	Z	 ddZ
d	 Zd
 Zd Zy)    )	timedeltarequest)Flask)CORS)send_from_directoryN)datetimedatec                     | yt        | t        t        f      r| j                  |      S t        | t              r'	 t        j
                  |       }|j                  |      S | S # t        $ r | cY S w xY w)N )
isinstancer	   r
   strftimestrfromisoformat
ValueError)valueformatdts      app/__init__.pydatetimeformatr      sw    } %(D)*~~f%% %	''.B;;v&& L  	L	s   %A$ $A21A2c                     t        t              ddlm}  j                  j	                  |        t
        j                  j                  d<   j                         5  	 ddl	m
}  |        ddd       ddlm}m}m}m}m}m} |j)                         |j)                  |       |j)                         |j)                         d	|_        d
|_        d|_        t1               |j)                         |j)                         j                  j3                  dddt5        d             j7                  d      fd       }	j8                  d        }
j:                  d        }|j<                  d        }t?        |       ddl m!}m"}m#}m$} jK                  |       jK                  |       jK                  |       |j                  j                  d<   tM               ddl'm(}  |       jS                  d      d        }jS                  d      d        }S # t        $ r$}t        d|        t        d       Y d}~d}~ww xY w# 1 sw Y   xY w)z:Application factory for RateRight construction marketplace   )Configr   )validate_stripe_configz$[WARNING] Stripe validation failed: z)   Continuing without payment features...N)dbjwtmigratelogin_managerlimitercsrfloginz"Please log in to access this page.infoTLax   )hours)SESSION_COOKIE_SECURESESSION_COOKIE_HTTPONLYSESSION_COOKIE_SAMESITEPERMANENT_SESSION_LIFETIMEz/favicon.icoc                  p    t        t        j                  j                   j                  d      dd      S )Nstaticzfavicon.icozimage/vnd.microsoft.icon)mimetype)r   ospathjoin	root_path)apps   r   faviconzcreate_app.<locals>.faviconI   s,    "GGLL1/
 	
    c                 8   d| j                   d<   d| j                   d<   d| j                   d<   d| j                   d<   t        j                  j                  d	      rd
| j                   d<   | S d| j                   d<   d| j                   d<   d| j                   d<   | S )z7Add headers specifically for Edge browser compatibilityaU  default-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdnjs.cloudflare.com https://cdn.jsdelivr.net https://fonts.googleapis.com https://fonts.gstatic.com https://fonts.cdnfonts.com https://js.stripe.com https://unpkg.com blob: data:; img-src 'self' data: https: https://js.stripe.com; connect-src 'self' https: wss: https://js.stripe.comzContent-Security-PolicynosniffzX-Content-Type-Options
SAMEORIGINzX-Frame-Optionszstrict-origin-when-cross-originzReferrer-Policyz/static/zpublic, max-age=3600zCache-Controlz#no-cache, no-store, must-revalidatezno-cachePragma0Expires)headersr   r.   
startswith)responses    r   add_edge_compatibility_headersz2create_app.<locals>.add_edge_compatibility_headersR   s    C 	23 6?12 /;*+ /P*+ <<"":.0FH_- 	 1VH_-)3HX&*-HY'r3   c                  v   ddl m}  | j                  j                  dd      }d|v rkt	        d| j
                   d       | j                  j                  d      d	k(  rt	        d
       d| j                  j                  dd      v rt	        d       | j                  dk(  rt	        d| j
                          yy)z*Handle Edge-specific request preprocessingr   r   z
User-Agentr   zEdg/z[EDGE] Request to z from Edge browserDNT1z8[EDGE] DNT header detected - ensuring privacy complianceSameSiteCookiez[EDGE] SameSite cookie detectedOPTIONSz.[EDGE] Handling OPTIONS preflight request for N)flaskr   r:   getprintr.   method)r   
user_agents     r   handle_edge_requestsz(create_app.<locals>.handle_edge_requestsv   s     	" __((r:
Z&w||n4FGH ""5)S0PR W__002>>79 >>Y&B7<<.QR 'r3   c                 f   ddl m} t        d|         	 |j                  j	                  t        |             }|r6|j                  rt        d|  d       yt        d|j                          |S t        d|         y# t        $ r&}t        d	|        t        d
|         Y d}~yd}~ww xY w)z=Load user by ID for Flask-Login, excluding soft-deleted usersr   )Userz5[DEBUG] Flask-Login user_loader called with user_id: z[INFO] User z  is soft-deleted, denying accessNz[SUCCESS] User loaded: z[ERROR] No user found for id: z3[ERROR] Database connection failed in user_loader: z-[INFO] Clearing invalid session for user_id: )	modelsrK   rF   queryrE   int
is_deletedemail	Exception)user_idrK   useres       r   	load_userzcreate_app.<locals>.load_user   s     	!EgYOP	::>>#g,/D??L	1QRS/

|<=6wi@A 	GsKLA'KL		s$   AB B 2B 	B0
B++B0)inject_notification_countsinject_user_contextinject_app_globalsformat_job_durationformat_duration)register_main_routes  c                      y)N)zU<h1>404 - Page Not Found</h1><p>RateRight is running but this page doesn't exist.</p>r\    errors    r   	not_foundzcreate_app.<locals>.not_found   s    kr3     c                 $    dt        |        ddfS )NzG<h1>500 - Internal Server Error</h1><p>RateRight encountered an error: z</p>rb   )r   r_   s    r   internal_errorz"create_app.<locals>.internal_error   s     XY\]bYcXddhiknnnr3   )*r   __name__configr   from_objectr   	jinja_envfiltersapp_contextservices.stripe_servicer   rQ   rF   
extensionsr   r   r   r   r   r    init_app
login_viewlogin_messagelogin_message_categoryr   updater   routeafter_requestbefore_requestuser_loaderconfigure_jwt_handlerscontext_processorsrV   rW   rX   rY   context_processorregister_blueprintsmain_routesr[   errorhandler)r   r   rT   r   r   r   r   r   r    r2   r=   rI   rU   rV   rW   rX   rY   r[   ra   rd   r1   s                       @r   
create_appr|      s`   
/C JJ6" /=CMM*+ 
	 ?	?G"$? KJKKS"LL3&M"FM+1M(ISMM# JJ" $ %#,2#6	   	YY~
 
 	 F 	S S.  . 3 }|45-.,- 0CCMM+,  2 	cl l 	co o Je  	?8<==>>	?	? ?s0   I!!H11	I:II!II!!I+c                     ddl m | j                  fd       }| j                  fd       }| j                  fd       }y)zConfigure JWT error handlersr   )jsonifyc                      ddi      dfS )Nr`   zToken has expired  r^   )
jwt_headerjwt_payloadr~   s     r   expired_token_callbackz6configure_jwt_handlers.<locals>.expired_token_callback   s    !456;;r3   c                      ddi      dfS )Nr`   zInvalid tokenr   r^   r`   r~   s    r   invalid_token_callbackz6configure_jwt_handlers.<locals>.invalid_token_callback   s    12C77r3   c                      ddi      dfS )Nr`   zAuthorization token is requiredr   r^   r   s    r   missing_token_callbackz6configure_jwt_handlers.<locals>.missing_token_callback   s    !BCDcIIr3   N)rD   r~   expired_token_loaderinvalid_token_loaderunauthorized_loader)r   r   r   r   r~   s       @r   rv   rv      sT    < < 	8 8 	J Jr3   c                     ddl m} ddlm} ddlm} ddlm} ddlm	} ddl
m} ddlm} dd	lm} 	 dd
lm}	  j%                  |	d       t'        d       	 ddlm}  j%                  |d       t'        d       	 ddlm}  j%                  |d       t'        d       	 ddlm}  j%                  |d       t'        d       	 ddlm}  j%                  |d       t'        d       	 d d!lm}  j%                  |       t'        d"        j%                  |d$        j%                  |d%        j%                  |d&        j%                  |d'        j%                  |d(        j%                  |d)        j%                  |d*        j%                  |d+       	 dd,lm }  j%                  |       t'        d-       	 dd/l!m"}  j%                  |       t'        d0       dd2l#m$}  j%                  |d3        jK                  d4      d5        } jK                  d6       fd7       }y# t(        $ r}
t'        d|
        Y d}
~
d}
~
ww xY w# t(        $ r}
t'        d|
        Y d}
~
d}
~
ww xY w# t(        $ r}
t'        d|
        Y d}
~
d}
~
ww xY w# t(        $ r}
t'        d|
        Y d}
~
d}
~
ww xY w# t(        $ r}
t'        d|
        Y d}
~
d}
~
ww xY w# t(        $ r}
t'        d#|
        Y d}
~
d}
~
ww xY w# t(        $ r}
t'        d.|
        Y d}
~
hd}
~
ww xY w# t(        $ r}
t'        d1|
        Y d}
~
jd}
~
ww xY w)8zRegister all Flask blueprintsr   )auth_bp)marketplace_bp)legal_bp)	safety_bp)gamification_bp)analytics_bp)closeout_bp)files_bp)admin_bpz
/api/admin)
url_prefixz$[SUCCESS] Registered admin blueprintz,[WARNING] Could not import admin blueprint: N)scheduling_bpz/api/schedulingz)[SUCCESS] Registered scheduling blueprintz1[WARNING] Could not import scheduling blueprint: )messages_bpz/api/messagesz'[SUCCESS] Registered messages blueprintz/[WARNING] Could not import messages blueprint: )notifications_bpz/api/notificationsz,[SUCCESS] Registered notifications blueprintz4[WARNING] Could not import notifications blueprint: )contract_dispute_bpz/api/contract-disputez/[SUCCESS] Registered contract dispute blueprintz7[WARNING] Could not import contract dispute blueprint: r   )contracts_bpz([SUCCESS] Registered contracts blueprintz0[WARNING] Could not import contracts blueprint: z	/api/authz/api/marketplacez
/api/legalz/api/safetyz/api/gamificationz
/analyticsz/api/closeoutz
/api/files)matching_bpz'[SUCCESS] Registered matching blueprintz/[WARNING] Could not import matching blueprint: )portfolio_bpz([SUCCESS] Registered portfolio blueprintz0[WARNING] Could not import portfolio blueprint: )public_legal_bpr   z/apic                       ddddddddd	d
ddS )Nz3RateRight - Australian Construction Marketplace APIfully_operationalz1.0.0z/Australian WHS Act 2011, Fair Work Act, Tax Lawz/api/auth/*z/api/marketplace/*z/api/legal/*z/api/safety/*z/api/gamification/*/api/health)authenticationmarketplacelegal_compliancesafety_systemgamificationsystem_health)servicestatusversion
complianceapi_endpointsr^   r^   r3   r   api_infoz%register_blueprints.<locals>.api_info(  s2     M)K"/3$2!0 5!.
 	
r3   r   c                      ddl m }  ddd | j                         j                         j                  j	                  di       dg dd	d	d	d	d	d
j                  d   j	                  dd      d	S )Nr   )r	   healthyz-RateRight Australian Construction Marketplace	connectedFEATURES   )rK   CategoryJobApplicationContractPaymentInvoiceWHSAssessmentJobProgressReviewDisputeAuditLogLeaderboardAchievementPointActivityT)whs_act_2011fair_work_actaustralian_tax_lawabn_validationgst_invoicinggamification_leaderboardsF)	r   r   database	timestampfeaturesmodels_countrL   compliance_systemsgamification_active)r	   utcnow	isoformatrf   rE   )r	   r1   s    r   health_checkz)register_blueprints.<locals>.health_check9  s{    %F#(*446

z26 !%!%&*"&!%# $'::j#9#=#=>Y[`#a)
 	
r3   )&blueprints.authr   blueprints.marketplacer   blueprints.legalr   blueprints.safetyr   blueprints.gamificationr   blueprints.analyticsr   closeout_routesr   routes.filesr   blueprints.adminr   register_blueprintrF   ImportErrorblueprints.schedulingr   blueprints.messagesr   blueprints.notificationsr   blueprints.contract_disputer   app.blueprints.contractsr   blueprints.matchingr   blueprints.portfolior   blueprints.legal.public_routesr   rr   )r1   r   r   r   r   r   r   r   r   r   rT   r   r   r   r   r   r   r   r   r   r   s   `                    r   ry   ry      sZ   (6*,82,&B.xLA45
G8}9JK9:E4{G78J>/<PQ<=MD2?VW?@F9|,89 7{;>6HI8=9??7JK<LA;?C8=E4{+78
F6|,89
 @?r: 	YYv
 
  	YY}
 
o  B<QC@AAB  GA!EFFG  E?sCDDE  JDQCHIIJ  MGsKLLM  F@DEEF"  E?sCDDE  F@DEEFs   $H6 $I =$J  "$J% $K
 ,"K/ '"L 
"L9 6	I?II	I=$I88I= 	J"	JJ"%	K.KK
	K,K''K,/	L8LL	L6L11L69	MMM)z%d-%m-%Y)r	   r   rD   r   r   
flask_corsr   r   r-   r
   r   r|   rv   ry   r^   r3   r   <module>r      s4        % 	 $&cJJ ~
r3   