o
    Wh;d                     @   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 ddlZddlmZ e ZG d	d
 d
ej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ZdS )a  
Analytics Models
================

Django models for the Adtlas Analytics module.
These models handle storage and management of analytics data, performance metrics,
and reporting information for the Dynamic Ad Insertion (DAI) system.

Models Overview:
- SfrAnalytics: SFR provider analytics data
- BouyguesAnalytics: Bouygues provider analytics data
- Impression: Individual ad impression tracking
- PerformanceMetric: Aggregated performance data
- VastResponse: VAST response tracking
- AnalyticsReport: Generated report metadata
- AdbreakPredict: Ad break prediction data
- RealTimeAdbreak: Real-time ad break information

Key Features:
- Multi-provider analytics support
- Real-time data collection
- Historical data preservation
- Performance optimization
- Data validation and integrity
- Automated cleanup policies

Relationships:
- Links to campaigns, channels, and ad spots
- User activity tracking
- Time-based data organization
- Geographic and demographic segmentation

Author: Adtlas Development Team
Version: 1.0.0
Last Updated: 2024
    )models)MinValueValidatorMaxValueValidator)gettext_lazy)timezone)get_user_modelN)Decimalc                   @   s   e Zd ZdZejdejdeddZ	ej
ddeddZej
ddedd	Zejdded
dZG dd dZdd Zdd ZdS )BaseAnalyticsModela  
    Abstract base model for all analytics models.
    
    Provides common fields and functionality for analytics data:
    - UUID primary key for better performance and security
    - Created and updated timestamps
    - Data validation helpers
    - Common query methods
    
    Attributes:
        id (UUIDField): Primary key using UUID4
        created_at (DateTimeField): Record creation timestamp
        updated_at (DateTimeField): Last update timestamp
        is_active (BooleanField): Soft delete flag
    TFz+Unique identifier for this analytics record)primary_keydefaulteditable	help_textz&Timestamp when this record was created)auto_now_adddb_indexr   z+Timestamp when this record was last updated)auto_nowr   r   z+Whether this record is active (soft delete)r   r   r   c                   @   s   e Zd ZdZdgZdS )zBaseAnalyticsModel.MetaTz-created_atN)__name__
__module____qualname__abstractordering r   r   VC:\Users\vibe-look\OneDrive\Desktop\Adtlas - Copy\New_Version\apps\analytics\models.pyMeta]   s    
r   c                 C      d| _ | jddgd dS )z,Mark record as inactive instead of deleting.F	is_active
updated_atupdate_fieldsNr   saveselfr   r   r   soft_deletea      zBaseAnalyticsModel.soft_deletec                 C   r   )zRestore a soft-deleted record.Tr   r   r   Nr   r!   r   r   r   restoref   r$   zBaseAnalyticsModel.restoreN)r   r   r   __doc__r   	UUIDFielduuiduuid4_idDateTimeFieldZ
created_atr   BooleanFieldr   r   r#   r%   r   r   r   r   r	   3   s4    r	   c                   @   s  e Zd ZdZejdejdeddZejdej	dddedd	Z
ejded
dZejededgeddZejdeddZejddedeedeedgeddZejddedeedgeddZejddedeedeedgeddZejddedeedgeddZejdeddZejededdZejededdZG dd  d Zd!d" Ze d#d$ Z!d%d& Z"d'S )(SfrAnalyticsa  
    SFR Analytics data model.
    
    Stores analytics data from SFR provider including audience metrics,
    viewing patterns, and performance indicators.
    
    Attributes:
        channel: Related channel for this analytics data
        campaign: Related campaign (optional)
        date: Date of the analytics data
        hour: Hour of the day (0-23)
        audience_count: Number of viewers
        market_share: Market share percentage
        rating: Audience rating
        reach: Reach percentage
        frequency: Average frequency
        duration: Average viewing duration in seconds
        demographics: JSON field for demographic data
        geographic_data: JSON field for geographic distribution
    channels.ChannelZsfr_analytics+Channel associated with this analytics data	on_deleterelated_namer   campaigns.CampaignT,Campaign associated with this analytics datar2   nullblankr3   r   Date of the analytics datar   r   r      Hour of the day (0-23)
validatorsr   Number of viewersr   r         0.00100.00Market share percentage (0-100)
max_digitsdecimal_placesr   r>   r   zAudience ratingReach percentage (0-100)Average frequencyz#Average viewing duration in secondszDemographic breakdown datar   r8   r   zGeographic distribution datac                   @   V   e Zd ZdZedZedZg dZej	ddgdej	ddgdej	ddgdgZ
d	S )
zSfrAnalytics.MetaZanalytics_sfrzSFR AnalyticschanneldatehourrO   rP   fieldsrN   campaignNr   r   r   db_tabler*   verbose_nameverbose_name_pluralunique_togetherr   Indexindexesr   r   r   r   r          r   c                 C       d| j j d| j d| j dS )NzSFR Analytics -  -  :00rN   namerO   rP   r!   r   r   r   __str__       zSfrAnalytics.__str__c                 C   s   t j| jt j| jdS )z.Get datetime object for this analytics record.)rP   N)r   datetimecombinerO   timerP   r!   r   r   r   rd         zSfrAnalytics.datetimec                 C   sH   t | jd t | jd  t | jd  tt | jdd  }t|dS )z5Calculate overall performance score based on metrics.g333333?g      ?
   g?rB   N)floatratingreachmarket_sharemin	frequencyround)r"   scorer   r   r   get_performance_score   s   
z"SfrAnalytics.get_performance_scoreN)#r   r   r   r&   r   
ForeignKeyCASCADEr*   rN   SET_NULLrS   	DateFieldrO   PositiveSmallIntegerFieldr   r   rP   PositiveIntegerFieldZaudience_countDecimalFieldr   rl   rj   rk   rn   duration	JSONFielddictZdemographicsZgeographic_datar   rb   propertyrd   rq   r   r   r   r   r.   l   s    

r.   c                   @   s  e Zd ZdZejdejdeddZejdej	dddedd	Z
ejded
dZejededgeddZejdeddZejddedeedeedgeddZejddedeedgeddZejddedeedeedgeddZejddedeedgeddZejdeddZejededdZejededdZG dd  d Zd!d" Zd#S )$BouyguesAnalyticsa  
    Bouygues Analytics data model.
    
    Stores analytics data from Bouygues provider with similar structure
    to SFR but potentially different metrics and data points.
    
    Attributes:
        channel: Related channel for this analytics data
        campaign: Related campaign (optional)
        date: Date of the analytics data
        hour: Hour of the day (0-23)
        viewers: Number of viewers
        share: Market share percentage
        rating_value: Audience rating value
        reach_percentage: Reach percentage
        avg_frequency: Average frequency
        watch_time: Average watch time in minutes
        device_data: JSON field for device breakdown
        age_groups: JSON field for age group data
    r/   Zbouygues_analyticsr0   r1   r4   Tr5   r6   r9   r:   r   r;   r<   r=   r?   r@   rA   rB   rC   rD   rE   rF   zAudience rating valuerI   rJ   zAverage watch time in minuteszDevice breakdown datarK   zAge group distribution datac                   @   rL   )
zBouyguesAnalytics.MetaZanalytics_bouygueszBouygues AnalyticsrM   rO   rP   rQ   rN   rS   NrT   r   r   r   r   r   _  r[   r   c                 C   r\   )NzBouygues Analytics - r]   r^   r_   r`   r!   r   r   r   rb   j  rc   zBouyguesAnalytics.__str__N) r   r   r   r&   r   rr   rs   r*   rN   rt   rS   ru   rO   rv   r   r   rP   rw   Zviewersrx   r   shareZrating_valueZreach_percentageZavg_frequencyZ
watch_timerz   r{   Zdevice_dataZ
age_groupsr   rb   r   r   r   r   r}      s    
r}   c                   @   sZ  e Zd ZdZejdejdeddZejdejdeddZ	ejdejded	dZ
ejd
eddZejd
d
eddZejejd
eddZejdeddZejddedeedeedgeddZejdeddZejdejd
d
deddZejed
edd Z ejed
ed!d Z!G d"d# d#Z"d$d% Z#e$d&d' Z%e$d(d) Z&d*S )+
Impressiona  
    Individual ad impression tracking model.
    
    Records each individual ad impression with detailed tracking information
    for performance analysis and billing purposes.
    
    Attributes:
        campaign: Related campaign
        adspot: Related ad spot
        channel: Channel where impression occurred
        user_agent: User agent string
        ip_address: Client IP address (anonymized)
        timestamp: Exact timestamp of impression
        duration: How long the ad was viewed
        completion_rate: Percentage of ad completed
        click_through: Whether user clicked through
        vast_response: Related VAST response
        geographic_info: Geographic information
        device_info: Device information
    r4   Zimpressionsz(Campaign associated with this impressionr1   adspots.AdSpotz'Ad spot associated with this impressionr/   z!Channel where impression occurredTzUser agent string (anonymized)r8   r   z*Client IP address (anonymized for privacy)r7   r8   r   zExact timestamp of impressionr   r   z%How long the ad was viewed in secondsr@   rA   rB   rC   rD   z"Percentage of ad completed (0-100)rF   Fz#Whether user clicked through the adVastResponsezRelated VAST responser6   z#Geographic information (anonymized)rK   zDevice and browser informationc                   @   sZ   e Zd ZdZedZedZejdgdejddgdejddgdejddgdgZ	d	S )
zImpression.MetaZanalytics_impressionsr   ZImpressions	timestamprQ   rS   rN   adspotN
r   r   r   rU   r*   rV   rW   r   rY   rZ   r   r   r   r   r     s    r   c                 C      d| j j d| j S )NzImpression - r]   )rS   ra   r   r!   r   r   r   rb        zImpression.__str__c                 C   s   | j tdkS )z0Check if impression was completed (>75% viewed).z75.00N)completion_rater   r!   r   r   r   is_completed  s   zImpression.is_completedc                 C   s   | j tdko| jdkS )zFCheck if impression meets viewability standards (>50% for 2+ seconds).z50.00rB   N)r   r   ry   r!   r   r   r   is_viewable  s   zImpression.is_viewableN)'r   r   r   r&   r   rr   rs   r*   rS   r   rN   	TextFieldZ
user_agentGenericIPAddressField
ip_addressr,   r   nowr   rw   ry   rx   r   r   r   r   r-   Zclick_throughrt   Zvast_responserz   r{   Zgeographic_infoZdevice_infor   rb   r|   r   r   r   r   r   r   r   n  s    

r   c                   @   s  e Zd ZdZejdejdeddZejdejdeddZ	ej
edd	Zejd
eddZejdeddZejdeddZejdeddZejededdZejededdZejejdeddZG dd dZdd Zedd Zedd Zd S )!r   ai  
    VAST response tracking model.
    
    Stores information about VAST (Video Ad Serving Template) responses
    for tracking ad delivery and performance.
    
    Attributes:
        campaign: Related campaign
        adspot: Related ad spot
        vast_url: VAST XML URL
        response_time: Response time in milliseconds
        status_code: HTTP status code
        error_message: Error message if any
        xml_content: VAST XML content (truncated)
        tracking_urls: JSON field with tracking URLs
        creative_info: Information about the creative
        served_at: When the VAST was served
    r4   Zvast_responsesz+Campaign associated with this VAST responser1   r   z*Ad spot associated with this VAST responsezVAST XML URL)r   r   zResponse time in millisecondsr@      zHTTP status codeTzError message if anyr   z(VAST XML content (truncated for storage)z Tracking URLs from VAST responserK   zInformation about the creativezWhen the VAST was servedr   c                   @   sJ   e Zd ZdZedZedZejdgdejddgdejdgdgZ	dS )	zVastResponse.MetaZanalytics_vast_responseszVAST ResponsezVAST Responses	served_atrQ   rS   status_codeNr   r   r   r   r   r   >  s    r   c                 C   r   )NzVAST Response - r]   )rS   ra   r   r!   r   r   r   rb   H  r   zVastResponse.__str__c                 C   s   d| j   ko
dk S   S )z&Check if VAST response was successful.r   i,  N)r   r!   r   r   r   is_successfulK  rg   zVastResponse.is_successfulc                 C   s
   | j dk S )z/Check if response time was acceptable (<500ms).  N)response_timer!   r   r   r   is_fast_responseP  s   
zVastResponse.is_fast_responseN) r   r   r   r&   r   rr   rs   r*   rS   r   URLFieldZvast_urlrw   r   rv   r   r   error_messageZxml_contentrz   r{   Ztracking_urlsZcreative_infor,   r   r   r   r   rb   r|   r   r   r   r   r   r   r     sl    

r   c                   @   s  e Zd ZdZdedfdedfdedfded	fd
edfgZejdejdeddZ	ejdejdddeddZ
ejdeddZejdededdZejdeddZejdeddZejddedeedeed ged!d"Zejddedeedged#d"Zejd$dedeedged%d"Zejd&dedeedged'd"Zejd&dedeedged(d"Zejd)deded*d+ZG d,d- d-Zd.d/ Zd0d1 Zd2d3 Zd4S )5PerformanceMetricah  
    Aggregated performance metrics model.
    
    Stores pre-calculated performance metrics for faster reporting
    and dashboard display.
    
    Attributes:
        campaign: Related campaign
        channel: Related channel (optional)
        date: Date of metrics
        metric_type: Type of metric (daily, weekly, monthly)
        impressions_count: Total impressions
        clicks_count: Total clicks
        completion_rate: Average completion rate
        ctr: Click-through rate
        cpm: Cost per mille
        revenue: Total revenue
        cost: Total cost
        roi: Return on investment
    ZdailyZDailyZweeklyZWeeklyZmonthlyZMonthlyZ	quarterlyZ	QuarterlyZyearlyZYearlyr4   Zperformance_metricsz&Campaign associated with these metricsr1   r/   Tz0Channel associated with these metrics (optional)r6   zDate of metricsr:      zType of metric aggregation)
max_lengthchoicesr   r   r   zTotal impressionsr@   zTotal clicksrA   rB   rC   rD   zAverage completion rate (0-100)rF   zClick-through rate percentagerh   zCost per mille (CPM)   zTotal revenuez
Total cost   zReturn on investment percentage)rG   rH   r   r   c                   @   sH   e Zd ZdZedZedZg dZej	ddgdej	ddgdgZ
d	S )
zPerformanceMetric.MetaZanalytics_performance_metricszPerformance MetriczPerformance Metrics)rS   rN   rO   metric_typerO   r   rQ   rS   NrT   r   r   r   r   r     s    r   c                 C   s.   | j r| j jnd}d| jj d| d| j S )NzAll ChannelszPerformance - r]   )rN   ra   rS   rO   )r"   channel_namer   r   r   rb     s   zPerformanceMetric.__str__c                 C   s6   | j dkrtt| j| j  d | _dS td| _dS )z9Calculate and update CTR based on impressions and clicks.r   d   rC   N)impressions_countr   strclicks_countctrr!   r   r   r   calculate_ctr  s   
zPerformanceMetric.calculate_ctrc                 C   s<   | j dkrtt| j| j  | j  d | _dS td| _dS )z3Calculate and update ROI based on revenue and cost.r   r   rC   N)costr   r   revenueroir!   r   r   r   calculate_roi  s   
$zPerformanceMetric.calculate_roiN) r   r   r   r&   r*   ZMETRIC_TYPESr   rr   rs   rS   rN   ru   rO   	CharFieldr   rw   r   r   rx   r   r   r   r   r   Zcpmr   r   r   r   rb   r   r   r   r   r   r   r   V  s    




	

r   c                   @   s@  e Zd ZdZdedfdedfdedfded	fd
edfdedfgZejdeddZejdeeddZ	ej
eeddZejddeddZejdeddZejeejddeddZejejdedd Zejdded!d"Zejded#dZejd$ed%dZG d&d' d'Zd(d) Zed*d+ Zd,d- Z d.S )/AnalyticsReporta[  
    Generated analytics report metadata model.
    
    Stores information about generated reports for tracking and caching purposes.
    
    Attributes:
        name: Report name
        report_type: Type of report
        parameters: Report parameters (JSON)
        file_path: Path to generated report file
        file_size: Size of report file
        generated_by: User who generated the report
        generated_at: When report was generated
        expires_at: When report expires
        download_count: Number of times downloaded
        is_public: Whether report is publicly accessible
    Zcampaign_performancezCampaign PerformanceZchannel_analyticszChannel AnalyticsZimpression_summaryzImpression SummaryZvast_performancezVAST PerformanceZrevenue_reportzRevenue ReportZcustomzCustom Report   zReport name)r   r   2   zType of report)r   r   r   zReport parameters and filtersr@   r   TzPath to generated report file)r   r8   r   r   zSize of report file in bytesZgenerated_reportszUser who generated the report)r2   r7   r3   r   zWhen report was generatedr   zWhen report expiresr   zNumber of times downloadedFz%Whether report is publicly accessiblec                   @   sH   e Zd ZdZedZedZejdgdejdgdejdgdgZ	dS )	zAnalyticsReport.MetaZanalytics_reportszAnalytics ReportzAnalytics Reportsgenerated_atrQ   report_typegenerated_byNr   r   r   r   r   r   B  s    r   c                 C   s   d| j  d| j S )Nz	Report - r]   )ra   r   r!   r   r   r   rb   L  s   zAnalyticsReport.__str__c                 C   s   | j r
t | j kS dS )zCheck if report has expired.FN)
expires_atr   r   r!   r   r   r   
is_expiredO  s   zAnalyticsReport.is_expiredc                 C   s    |  j d7  _ | jdgd dS )zIncrement download counter.   download_countr   N)r   r    r!   r   r   r   increment_download_countV  s   z(AnalyticsReport.increment_download_countN)!r   r   r   r&   r*   ZREPORT_TYPESr   r   ra   r   rz   r{   
parameters	file_pathrw   	file_sizerr   Userrt   r   r,   r   r   r   r   r   r-   Z	is_publicr   rb   r|   r   r   r   r   r   r   r     sz    








r   )r&   	django.dbr   django.core.validatorsr   r   django.utils.translationr   r*   django.utilsr   django.contrib.authr   r(   decimalr   r   Modelr	   r.   r}   r   r   r   r   r   r   r   r   <module>   s&   %9 
y g 