o
    />dhb                     @   s  d Z ddlmZ ddlmZmZ ddlmZ ddl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 ddlmZ ddlmZ ddlmZmZ ddlm Z m!Z! ddl"m#Z# ddl$Z$e$%e&Z'G dd deZ(G dd deZ)G dd deZ*G dd deZ+G dd deZ,G dd deeZ-G dd deZ.G d d! d!eZ/G d"d# d#eZ0eed$d%d&G d'd( d(eZ1d)d* Z2d+d, Z3d-d. Z4d/d0 Z5dS )1z
Core Views Module

This module contains views for the core app including landing pages,
dashboard, error pages, and common functionality used across the application.
    )render)TemplateViewView)LoginRequiredMixin)JsonResponse)reverse_lazyreverse)method_decorator)
cache_page)cache)settings)gettext_lazy)timezone)	timedelta)UserRole)LoginAttemptUserSession)is_ajax_requestNc                       <   e Zd ZdZdZ fddZdd Zdd Zd	d
 Z  Z	S )HomeViewz
    Landing page view for the application.
    
    Displays the main landing page with application information,
    features, and call-to-action elements for visitors.
    zcore/home.htmlc              	      sN   t  jdi |}|td|  ttddttdd|  |  d |S )	z
        Add context data for the home page.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        ZHomeAPP_NAMEz
Django AppAPP_VERSION1.0.0)titletotal_usersapp_nameZapp_versionfeaturesZtestimonialsN )	superget_context_dataupdate_get_total_usersgetattrr   get_app_featuresget_testimonialsselfkwargscontext	__class__r   CC:\Users\vibe-look\OneDrive\Desktop\Adtlas_V\src\apps\core\views.pyr    )   s   


	zHomeView.get_context_datac              
   C   sL   z
t jjdd W S  ty% } ztd|  W Y d}~dS d}~ww )zs
        Get total number of registered users.
        
        Returns:
            int: Total user count
        T	is_activezError getting user count: Nr   )r   objectsfiltercount	Exceptionloggererror)r(   er   r   r-   r#   A   s   zHomeView.get_total_usersc                 C   sL   t dt dddt dt dddt dt d	d
dt dt dddgS )z
        Get list of application features for display.
        
        Returns:
            list: List of feature dictionaries
        zUser Managementz@Comprehensive user account management with roles and permissionszfas fa-users)r   descriptioniconzSecure AuthenticationzEAdvanced authentication with session management and security featureszfas fa-shield-altzRole-Based Accessz>Dynamic role and permission system for flexible access controlz
fas fa-keyzDashboard Analyticsz=Comprehensive dashboard with real-time analytics and insightszfas fa-chart-barN)r"   r(   r   r   r-   r%   N   s"   	zHomeView.get_app_featuresc                 C   s   ddddddddddgS )
z
        Get testimonials for the landing page.
        
        Returns:
            list: List of testimonial dictionaries
        zJohn DoezProject ManagerzKThis application has streamlined our user management process significantly.   )namerolecontentZratingz
Jane SmithzSystem AdministratorzEThe security features and role management are exactly what we needed.Nr   r9   r   r   r-   r&   l   s   	zHomeView.get_testimonials)
__name__
__module____qualname____doc__template_namer    r#   r%   r&   __classcell__r   r   r+   r-   r      s    r   c                       r   )	AboutViewzb
    About page view.
    
    Displays information about the application, team, and company.
    zcore/about.htmlc                    s:   t  jdi |}|td|  |  |  d |S )z
        Add about page context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        zAbout Us)r   Zapp_infoZteam_membersZcompany_infoNr   )r   r    r!   r"   get_app_infoget_team_membersget_company_infor'   r+   r   r-   r       s   
zAboutView.get_context_datac                 C   s$   t tddt tdddg dddS )
zr
        Get application information.
        
        Returns:
            dict: Application information
        r   zDjango Applicationr   r   zJA professional Django application with user management and authentication.)DjangoPythonZ
PostgreSQLZRedisZ	Bootstrap2024)r;   versionr7   ZtechnologiesZlaunch_dateN)r$   r   r9   r   r   r-   rE      s   

zAboutView.get_app_infoc                 C      dddddgS )z{
        Get team member information.
        
        Returns:
            list: List of team member dictionaries
        zSenior Django DeveloperzLead DeveloperzRExperienced Django developer with expertise in building scalable web applications.z!/static/images/team/developer.jpg)r;   r<   bioavatarNr   r9   r   r   r-   rF         	zAboutView.get_team_membersc                 C   s   dddg ddS )zj
        Get company information.
        
        Returns:
            dict: Company information
        zYour Company NamerJ   zBTo provide excellent software solutions that help businesses grow.)Z
InnovationZQualityzCustomer FocusZ	Integrity)r;   ZfoundedZmissionvaluesNr   r9   r   r   r-   rG      s
   zAboutView.get_company_info)
r>   r?   r@   rA   rB   r    rE   rF   rG   rC   r   r   r+   r-   rD      s    rD   c                       s4   e Zd ZdZdZ fddZdd Zdd Z  ZS )	ContactViewzT
    Contact page view.
    
    Displays contact information and contact form.
    zcore/contact.htmlc                    s0   t  jdi |}||  |  dd |S )z
        Add contact page context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        z
Contact Us)Zcontact_infoZoffice_locationsr   Nr   )r   r    r!   get_contact_infoget_office_locationsr'   r+   r   r-   r       s   
zContactView.get_context_datac                 C   s   dddddS )zj
        Get contact information.
        
        Returns:
            dict: Contact information
        zcontact@yourcompany.com+1 (555) 123-4567&123 Business Street, City, State 12345z"Monday - Friday: 9:00 AM - 6:00 PM)emailphoneaddressZbusiness_hoursNr   r9   r   r   r-   rR      s
   zContactView.get_contact_infoc                 C   rL   )zw
        Get office location information.
        
        Returns:
            list: List of office locations
        zMain OfficerU   rT   zmain@yourcompany.com)r;   rX   rW   rV   Nr   r9   r   r   r-   rS      rO   z ContactView.get_office_locations)	r>   r?   r@   rA   rB   r    rR   rS   rC   r   r   r+   r-   rQ      s    rQ   c                       $   e Zd ZdZdZ fddZ  ZS )PrivacyViewzo
    Privacy policy page view.
    
    Displays the privacy policy and information about data protection.
    zcore/privacy.htmlc                    (   t  jdi |}|dtdi |S )z
        Add privacy page context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        r   zPrivacy PolicyNr   r   r    r!   r"   r'   r+   r   r-   r      s
   
zPrivacyView.get_context_datar>   r?   r@   rA   rB   r    rC   r   r   r+   r-   rZ         rZ   c                       rY   )TOSViewzk
    Terms of Service page view.
    
    Displays the terms and conditions for using the application.
    zcore/tos.htmlc                    r[   )z9
        Add terms of service page context data.
        r   zTerms of ServiceNr   r\   r'   r+   r   r-   r    .  s
   zTOSView.get_context_datar]   r   r   r+   r-   r_   &  r^   r_   c                       s\   e Zd ZdZdZedZ fddZdd Zdd	 Z	d
d Z
dd Zdd Zdd Z  ZS )DashboardViewz
    Main dashboard view for authenticated users.
    
    Displays user-specific dashboard with statistics, recent activity,
    and quick access to common functions.
    zcore/dashboard.htmlz
auth:loginc                    s`   t  jdi |}| jj}|td| || || || 	|| 
|| |d |S )z
        Add dashboard context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        Z	Dashboard)r   
user_statssystem_statsrecent_activityZquick_actionsnotificationsZdashboard_widgetsNr   )r   r    requestuserr!   r"   get_user_statsget_system_statsget_recent_activityget_quick_actionsget_user_notificationsget_dashboard_widgets)r(   r)   r*   rf   r+   r   r-   r    D  s   

zDashboardView.get_context_datac              
   C   s   z3t jj|dt tdd d }tjj|dd }||t  |j	  j
|j |jdW S  tyO } ztd|  i W  Y d}~S d}~ww )	z
        Get statistics specific to the current user.
        
        Args:
            user: Current user instance
            
        Returns:
            dict: User-specific statistics
        T   daysrf   is_successfulcreated_at__gte)rf   r/   )Zlogin_count_30_daysactive_sessionsZaccount_age_daysroles_count
last_loginzError getting user stats: N)r   r0   r1   r   nowr   r2   r   datedate_joinedro   rolesru   r3   r4   r5   )r(   rf   Zlogin_attemptsrs   r6   r   r   r-   rg   ^  s2   
zDashboardView.get_user_statsc              
   C   s   |j si S zAt  }|tdd }|tdd }tj tjjdd tjj|d tjj|d t	j t
jjd|d d	W S  tyb } ztd
|  i W  Y d}~S d}~ww )z
        Get system-wide statistics (for admin users).
        
        Args:
            user: Current user instance
            
        Returns:
            dict: System statistics
           rn   rm   Tr.   )date_joined__gteF)rq   Zcreated_at__date)r   active_usersZnew_users_weekZnew_users_monthtotal_rolesZfailed_logins_todayzError getting system stats: N)is_staffr   rv   rw   r   r   r0   r2   r1   r   r   r3   r4   r5   )r(   rf   todayZweek_agoZ	month_agor6   r   r   r-   rh     s8   
zDashboardView.get_system_statsc              
   C   s   z=g }t jj|t tdd dddd }|D ]}|dd|j |j	|j
d	 q|jd
d dd |dd W S  tyY } ztd|  g W  Y d}~S d}~ww )z
        Get recent activity for the user.
        
        Args:
            user: Current user instance
            
        Returns:
            list: List of recent activity items
        rz   rn   )rf   rr   z-created_atNr:   loginzLogged in from )typer7   	timestampsuccessc                 S   s   | d S )Nr   r   )xr   r   r-   <lambda>  s    z3DashboardView.get_recent_activity.<locals>.<lambda>T)keyr   
   zError getting recent activity: )r   r0   r1   r   rv   r   order_byappend
ip_address
created_atrq   sortr3   r4   r5   )r(   rf   Z
activitiesZrecent_loginsr   r6   r   r   r-   ri     s,   


z!DashboardView.get_recent_activityc                 C   sh   t dtddddt dtddd	dg}|jr2|t d
tddddt dtddddg |S )z
        Get quick action buttons for the user.
        
        Args:
            user: Current user instance
            
        Returns:
            list: List of quick action dictionaries
        zEdit Profilezaccounts:profile_editzfas fa-user-editZprimary)r   urlr8   colorzAccount Settingszaccounts:settingsz
fas fa-cogZ	secondaryzManage Userszaccounts:user_listzfas fa-users-coginfozManage Roleszaccounts:role_listzfas fa-user-tagwarningN)r"   r   r~   extend)r(   rf   actionsr   r   r-   rj     s2   zDashboardView.get_quick_actionsc                 C   s   g }|j s|dtdtdtdtdd tjj|dt t	dd	 d

 }|dkrB|dtd| dtdtdd |S )z
        Get notifications for the user.
        
        Args:
            user: Current user instance
            
        Returns:
            list: List of notification dictionaries
        r   zEmail Not Verifiedz8Please verify your email address to access all features.zaccounts:resend_verificationzResend Verification)r   r   messageZ
action_urlZaction_textF   )hoursrp      ZdangerzSecurity Alertz, failed login attempts in the last 24 hours.zauth:user_sessionszReview SessionsN)is_verifiedr   r"   r   r   r0   r1   r   rv   r   r2   )r(   rf   rd   Zrecent_failed_loginsr   r   r-   rk     s2   
	z$DashboardView.get_user_notificationsc              	   C   sh   dt dddddt ddddg}|jr2|d	t d
d	dddt dddddt ddddg |S )z
        Get dashboard widgets configuration.
        
        Args:
            user: Current user instance
            
        Returns:
            list: List of widget configurations
        ra   zAccount Statisticsstatszcol-md-6)idr   r   sizerc   zRecent ActivityZactivityrb   zSystem Statisticsz	col-md-12Z
user_chartzUser GrowthZchartZsecurity_alertszSecurity AlertssecurityN)r"   r~   r   )r(   rf   widgetsr   r   r-   rl     s<   z#DashboardView.get_dashboard_widgets)r>   r?   r@   rA   rB   r   	login_urlr    rg   rh   ri   rj   rk   rl   rC   r   r   r+   r-   r`   9  s    #&#,(r`   c                       rY   )Error404Viewzo
    Custom 404 error page view.
    
    Displays a user-friendly 404 error page with navigation options.
    errors/404.htmlc              
      sb   t  jdi |}|dtdtdtdtddtdtddtd	td
dgd |S )z
        Add 404 error context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        Z404zPage Not Foundz,The page you are looking for does not exist.zGo to Homepagez	core:home)textr   zGo to Dashboardzcore:dashboardzContact Supportzcore:contact)
error_codeerror_titleerror_messageZsuggestionsNr   )r   r    r!   r"   r   r'   r+   r   r-   r    [  s   
zError404View.get_context_datar]   r   r   r+   r-   r   R      r   c                       rY   )Error500Viewzp
    Custom 500 error page view.
    
    Displays a user-friendly 500 error page with support information.
    errors/500.htmlc                    s2   t  jdi |}|dtdtddd |S )z
        Add 500 error context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        500zInternal Server Errorz8Something went wrong on our end. Please try again later.zsupport@yourcompany.com)r   r   r   Zsupport_emailNr   r\   r'   r+   r   r-   r    ~  s   
zError500View.get_context_datar]   r   r   r+   r-   r   u  r   r   c                       rY   )Error403Viewzm
    Custom 403 error page view.
    
    Displays a user-friendly 403 error page for permission denied.
    errors/403.htmlc                    s0   t  jdi |}|dtdtdd |S )z
        Add 403 error context data.
        
        Args:
            **kwargs: Additional keyword arguments
            
        Returns:
            dict: Context data for template rendering
        Z403zAccess Forbiddenz3You do not have permission to access this resource.)r   r   r   Nr   r\   r'   r+   r   r-   r      s   
zError403View.get_context_datar]   r   r   r+   r-   r     r   r   i  dispatch)r;   c                   @   s   e Zd ZdZdd ZdS )HealthCheckViewzm
    Health check endpoint for monitoring.
    
    Returns application health status and basic metrics.
    c              
   C   s   z/t j }d}t|dd t|}dt  d|dkr!dnd|t	t
ddd	}t|W S  tyY } ztd
|  tdt|t  dddW  Y d}~S d}~ww )z
        Handle GET request for health check.
        
        Args:
            request: HTTP request object
            
        Returns:
            JsonResponse: Health check data
        Zhealth_check_testtest<   Zhealthy	connecteddisconnectedr   r   )statusr   databaser   
user_countrK   zHealth check failed: Z	unhealthy)r   r5   r     r   N)r   r0   r2   r   setgetr   rv   	isoformatr$   r   r   r3   r4   r5   str)r(   re   r   	cache_keyZ
cache_testZhealth_datar6   r   r   r-   r     s0   





	
zHealthCheckView.getN)r>   r?   r@   rA   r   r   r   r   r-   r     s    r   c                 C   &   t | rttdddS t| dddS )z
    Custom 404 error handler.
    
    Args:
        request: HTTP request object
        exception: Exception that caused 404
        
    Returns:
        HttpResponse: 404 error page
    zPage not foundi  r   r   r   r   Nr   error_responser"   r   re   	exceptionr   r   r-   
handler404     r   c                 C   r   )z
    Custom 500 error handler.
    
    Args:
        request: HTTP request object
        
    Returns:
        HttpResponse: 500 error page
    zInternal server errorr   r   r   r   Nr   )re   r   r   r-   
handler500  s   r   c                 C   r   )z
    Custom 403 error handler.
    
    Args:
        request: HTTP request object
        exception: Exception that caused 403
        
    Returns:
        HttpResponse: 403 error page
    	Forbiddeni  r   r   r   Nr   r   r   r   r-   
handler403  r   r   c                 C   r   )z
    Custom 400 error handler.
    
    Args:
        request: HTTP request object
        exception: Exception that caused 400
        
    Returns:
        HttpResponse: 400 error page
    zBad requesti  r   zerrors/400.htmlr   Nr   r   r   r   r-   
handler400#  r   r   )6rA   django.shortcutsr   django.views.genericr   r   django.contrib.auth.mixinsr   django.httpr   django.urlsr   r   django.utils.decoratorsr	   django.views.decorators.cacher
   django.core.cacher   django.confr   django.utils.translationr   r"   django.utilsr   datetimer   Zapps.accounts.modelsr   r   Zapps.authentication.modelsr   r   Zapps.common.utilsr   logging	getLoggerr>   r4   r   rD   rQ   rZ   r_   r`   r   r   r   r   r   r   r   r   r   r   r   r-   <module>   sF   
dL<  #2