U
    LhU                     @   s  d 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mZ d
dlmZmZmZmZmZmZmZmZmZmZ G dd deZG dd deZG dd dejZG dd dejZ G dd dejZ!e"eG dd dej#Z$e"eG dd dej#Z%e"eG dd dej#Z&e"eG dd dej#Z'e"eG dd dej#Z(e"eG d d! d!ej#Z)e"eG d"d# d#ej#Z*e"eG d$d% d%ej#Z+e"eG d&d' d'ej#Z,d(ej-_.d)ej-_/d*ej-_0G d+d, d,ej1Z2d-S ).a  
Django Admin Configuration for Campaign Management System

This module provides comprehensive admin interface configurations for all campaign-related models.
It includes custom admin classes with enhanced functionality, filters, search capabilities,
and proper field organization for efficient campaign management.

Author: Campaign Management Team
Created: 2025
Last Modified: 2025-07-28
    )admin)models)	TextInputTextarea)format_html)reverse)	mark_safe)SimpleListFilter)datetime	timedelta   )
	CampaignsAdspotsCampaignTimeIntervalsCampaignairtimelogCampaignPriorityScoresAdSpotExclusionPendingDayTime	PlacementCampaignStatusc                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )	CampaignStatusFilterz<Custom filter for campaign status with improved readability.zCampaign Statusstatusc                 C   s   t jS )N)r   choicesselfrequestmodel_admin r   //var/www/html/Focus/src/apps/campaigns/admin.pylookups-   s    zCampaignStatusFilter.lookupsc                 C   s   |   r|j|   dS |S )N)r   )valuefilter)r   r   querysetr   r   r   r#   0   s    zCampaignStatusFilter.querysetN__name__
__module____qualname____doc__titleparameter_namer    r#   r   r   r   r   r   (   s
   r   c                   @   s(   e Zd ZdZdZdZdd Zdd ZdS )	DateRangeFilterzAFilter campaigns by date ranges for better temporal organization.zCampaign Periodperiodc                 C   s   dS )N))currentzCurrently Active)upcomingzUpcoming (Next 30 days))pastzPast Campaigns)Z
this_monthz
This Month)
next_monthz
Next Monthr   r   r   r   r   r    ;   s    zDateRangeFilter.lookupsc                 C   s   t   }|  dkr2|j|d|ddS |  dkrf|tdd d}|j|d|dS |  dkr|j|dd	S |S )
Nr-   z%Y-%m-%d)start_day__lteZend_day__gter.      days)Zstart_day__gtr1   r/   )Zend_day__lt)r
   nowdater!   r"   strftimer   )r   r   r#   todayZfuture_dater   r   r   r#   D   s    zDateRangeFilter.querysetNr$   r   r   r   r   r+   6   s
   	r+   c                       s8   e Zd ZdZeZdZdddgZdgZ fddZ	  Z
S )	AdspotsInlinez
    Inline admin for Adspots within Campaign admin.
    
    Allows editing of ad spots directly from the campaign page,
    providing a streamlined workflow for campaign management.
    r   namedurationr   idc                    s   t  |ddS )z*Optimize queryset to reduce database hits.brandchannel)superget_querysetselect_related)r   r   	__class__r   r   r@   c   s    zAdspotsInline.get_queryset)r%   r&   r'   r(   r   modelextrafieldsreadonly_fieldsr@   __classcell__r   r   rB   r   r9   W   s   
r9   c                   @   s.   e Zd ZdZeZdZddgZG dd dZdS )CampaignTimeIntervalsInlinez
    Inline admin for Campaign Time Intervals.
    
    Manages time slots when advertisements can be displayed,
    crucial for scheduling and pacing control.
    r   
start_timeend_timec                   @   s   e Zd ZddiZdS )z!CampaignTimeIntervalsInline.Mediaall)zadmin/css/widgets.cssN)r%   r&   r'   cssr   r   r   r   Medias   s    rN   N)	r%   r&   r'   r(   r   rD   rE   rF   rN   r   r   r   r   rI   h   s
   rI   c                   @   s4   e Zd ZdZeZdZddgZdddgZd	ddZ	dS )
CampaignPriorityScoresInlinez
    Inline admin for Campaign Priority Scores.
    
    Displays priority scoring history for campaigns,
    helping with campaign optimization and performance tracking.
    r   
created_at
updated_atpriority_scoreNc                 C   s   |j dS )z5Limit adding new priority scores to authorized users.z$campaigns.add_campaignpriorityscores)userhas_perm)r   r   objr   r   r   has_add_permission   s    z/CampaignPriorityScoresInline.has_add_permission)N)
r%   r&   r'   r(   r   rD   rE   rG   rF   rV   r   r   r   r   rO   y   s   
rO   c                	   @   s   e Zd ZdZdddddddd	d
g	Zeed
dddddgZddddddgZddddfddddfddddfddddffZ	e
eegZddd gZd!Zd"d# Zd$e_de_d%d& Zd'e_de_d(d) Zd*e_d+S ),CampaignsAdmina  
    Comprehensive admin interface for Campaign management.
    
    Features:
    - Advanced filtering and search capabilities
    - Organized fieldsets for better UX
    - Inline editing of related models
    - Custom actions for bulk operations
    - Performance optimizations
    r:   get_brand_nameget_agency_name
start_dateend_datebudgetcpmget_delivery_statusexclusivitypacingis_vast
media_typeagencyr=   productcategorycountrybrand__nameagency__nameBasic Information)r:   r=   rc   campaign_manager)widerF   classeszCampaign Details)rd   re   rf   rb   general_rotationzScheduling & Budget))rZ   r[   )r\   r]   )volumedeliverybroadcasts_dayzSettings & Preferences))r`   r   r_   )ra   	vast_dataprogram_categoryshows_preferenceposition_preferencecollapserj      c                 C   s,   |j r(td|j jgd}td||j jS dS )z,Display brand name with link to brand admin.zadmin:agencies_brand_changeargs<a href="{}">{}</a>-)r=   r   r<   r   r:   r   rU   urlr   r   r   rX      s    zCampaignsAdmin.get_brand_nameBrandc                 C   s,   |j r(td|j jgd}td||j jS dS )z.Display agency name with link to agency admin.zadmin:agencies_agency_changery   r{   r|   )rc   r   r<   r   r:   r}   r   r   r   rY      s    zCampaignsAdmin.get_agency_nameAgencyc                 C   sP   |j rL|jrL|j|j  d }|dkr(dn|dkr4dnd}|d}td||S d	S )
z'Visual indicator for delivery progress.d   P   green2   orangeredz.1fz#<span style="color: {};">{}%</span>r|   )ro   rp   r   )r   rU   Z
percentagecolorZpercentage_strr   r   r   r^      s    z"CampaignsAdmin.get_delivery_statusz
Delivery %N)r%   r&   r'   r(   list_displayr   r+   list_filtersearch_fields	fieldsetsrI   r9   rO   inlineslist_select_relatedlist_per_pagerX   short_descriptionadmin_order_fieldrY   r^   r   r   r   r   rW      sn                    	 

rW   c                   @   s   e Zd ZdZddddddgZddd	d
gZddddgZdddifdddifddddffZdd	d
gZdd Z	de	_
de	_dd Zde_
de_dd Zd e_
d!S )"AdspotsAdminz
    Admin interface for Advertisement Spots management.
    
    Provides comprehensive tools for managing individual ad creatives,
    their file paths, durations, and associated campaigns.
    r:   get_campaign_namerX   r;   r   get_file_infocampaign__statusr=   r>   url_from_vastcampaign__namerg   ri   rF   )r:   campaignr=   r>   zFile Information)original_fileencoded_filer;   r   zVAST Integration)r   rv   rl   r   c                 C   s6   |j r2dddddd|j jd}td||j jS d	S )
z,Display campaign name with status indicator.bluer   r   r   Zgray)	PrebookedBookedIn_progress
TerminatedCanceledblackz"<span style="color: {};">{}</span>r|   )r   getr   r   r:   )r   rU   Zstatus_colorr   r   r   r     s       zAdspotsAdmin.get_campaign_nameCampaignc                 C   s   |j r|j jS dS )zDisplay brand name.r|   )r=   r:   r   rU   r   r   r   rX   ,  s    zAdspotsAdmin.get_brand_namer   c                 C   sJ   g }|j r|d|j   |jr4|d|j  |rFtd|S dS )z0Display file information with visual indicators.u   📄 Original u   🔄 Encoded z<br>r|   )r   appendr   r   join)r   rU   infor   r   r   r   2  s    zAdspotsAdmin.get_file_infoZFilesN)r%   r&   r'   r(   r   r   r   r   r   r   r   r   rX   r   r   r   r   r   r      sP               
r   c                   @   sd   e Zd ZdZddddgZdddgZdgZdd	d
dffZdgZdd Z	de	_
de	_dd Zde_
dS )CampaignTimeIntervalsAdminz
    Admin interface for Campaign Time Intervals.
    
    Manages time slots for ad spot availability, critical for
    campaign scheduling and pacing control.
    r   rJ   rK   get_durationr   r   zTime Interval Configuration)r   rJ   rK   z<Define time slots when this campaign's ads can be displayed.rF   descriptionr   c                 C   s   |j r|j jS dS )zDisplay campaign name.r|   r   r:   r   r   r   r   r   S  s    z,CampaignTimeIntervalsAdmin.get_campaign_namer   c           	      C   s|   |j rx|jrxtt |j }tt |j}||k rF|tdd7 }|| }t|jd\}}t|d\}}d||S dS )z(Calculate and display interval duration.r   r3     <   {}h {}mr|   )	rJ   rK   r
   combiner8   r   divmodsecondsformat)	r   rU   startendr;   hours	remainderminutes_r   r   r   r   Y  s    z'CampaignTimeIntervalsAdmin.get_durationDurationN)r%   r&   r'   r(   r   r   r   r   r   r   r   r   r   r   r   r   r   r   =  s   
r   c                   @   s   e Zd ZdZddddddgZddd	d
gZdddgZdZdddgZdddifdddifdddiffZ	dd Z
de
_dd Zde_dd Zd e_d!d" Zde_d#S )$CampaignairtimelogAdminz
    Admin interface for Campaign Airtime Logs.
    
    Tracks actual broadcast times and insertion status for
    campaign performance monitoring and reporting.
    r   get_spot_nameget_adbreak_infoairtime_startairtime_endget_insertion_statusinsertion_statusr   Zad_break__channelr   Zspot__adspot_nameZad_break__channel__namer   spotad_breakzBroadcast InformationrF   )r   r   r   ZTiming)r   r   Status)r   c                 C   s   |j r|j jS dS Nr|   r   r   r   r   r   r     s    z)CampaignairtimelogAdmin.get_campaign_namer   c                 C   s   |j r|j jS dS r   )r   adspot_namer   r   r   r   r     s    z%CampaignairtimelogAdmin.get_spot_namezAd Spotc                 C   s&   |j r"d|j jr|j jjndS dS )Nz{}Unknownr|   )r   r   r>   r:   r   r   r   r   r     s    z(CampaignairtimelogAdmin.get_adbreak_infoChannelc                 C   s,   |j dkrtdS |j r tdS tdS dS )zVisual status indicator.Nu-   <span style="color: gray;">⏳ Pending</span>u.   <span style="color: green;">✅ Success</span>u+   <span style="color: red;">❌ Failed</span>)r   r   r   r   r   r   r     s
    
z,CampaignairtimelogAdmin.get_insertion_statusN)r%   r&   r'   r(   r   r   r   date_hierarchyr   r   r   r   r   r   r   r   r   r   r   r   h  sP          
   r   c                   @   sf   e Zd ZdZddddgZdddgZdgZddgZdZdd	d
ifddddffZ	dd Z
de
_de
_dS )CampaignPriorityScoresAdminz
    Admin interface for Campaign Priority Scores.
    
    Manages priority scoring system for campaign optimization
    and automated decision making.
    r   rR   rP   rQ   r   r   zPriority Score InformationrF   )r   rR   
Timestamps)rP   rQ   rv   rl   c                 C   s   |j r|j jS dS r   r   r   r   r   r   r     s    z-CampaignPriorityScoresAdmin.get_campaign_namer   N)r%   r&   r'   r(   r   r   r   rG   r   r   r   r   r   r   r   r   r   r     s,      
 
r   c                   @   sp   e Zd ZdZddddgZdddd	gZd
dddffZdd Zde_dd Z	de	_dd Z
de
_dd Zde_dS )AdSpotExclusionAdminz
    Admin interface for Ad Spot Exclusions.
    
    Manages competitive exclusions and scheduling conflicts
    between different advertisement spots.
    
get_spot_1
get_spot_2
get_brandsget_campaignsZad_spot_1__adspot_nameZad_spot_2__adspot_nameZad_spot_1__id_brand__nameZad_spot_2__id_brand__namezExclusion Configuration)	ad_spot_1	ad_spot_2z3Define which ad spots cannot be scheduled together.r   c                 C   s   |j r|j jS dS r   )r   r   r   r   r   r   r     s    zAdSpotExclusionAdmin.get_spot_1z	Ad Spot 1c                 C   s   |j r|j jS dS r   )r   r   r   r   r   r   r     s    zAdSpotExclusionAdmin.get_spot_2z	Ad Spot 2c                 C   sV   g }|j r"|j jr"||j jj |jr@|jjr@||jjj |rRdt|S dS Nu    ↔ r|   )r   id_brandr   r:   r   r   set)r   rU   brandsr   r   r   r     s    zAdSpotExclusionAdmin.get_brandsBrandsc                 C   sV   g }|j r"|j jr"||j jj |jr@|jjr@||jjj |rRdt|S dS r   )r   id_campaignr   r:   r   r   r   )r   rU   	campaignsr   r   r   r     s    z"AdSpotExclusionAdmin.get_campaignsr   N)r%   r&   r'   r(   r   r   r   r   r   r   r   r   r   r   r   r   r     s(     r   c                   @   s@   e Zd ZdZddddgZddgZddd	iffZd
d Zde_dS )PendingAdminz
    Admin interface for Pending advertisements.
    
    Manages advertisements waiting for approval or processing,
    with quick action capabilities for workflow management.
    creative_idget_url_displayr;   
id_pendingr~   zPending AdvertisementrF   )r   r~   r;   c                 C   sH   |j rD|j drtd|j S t|j dkr>|j dd d S |j S dS )zDisplay URL with link if valid.)zhttp://zhttps://u*   <a href="{}" target="_blank">🔗 View</a>r   Nz...r|   )r~   
startswithr   lenr   r   r   r   r     s
    &zPendingAdmin.get_url_displayURLN)	r%   r&   r'   r(   r   r   r   r   r   r   r   r   r   r     s    r   c                   @   s>   e Zd ZdZddddgZdgZdddiffZd	d
 Zde_dS )DayTimeAdminz
    Admin interface for Day Time configurations.
    
    Manages time slot definitions used across the system
    for scheduling and time-based filtering.
    r:   r   r   get_duration_displayzTime Slot ConfigurationrF   )r:   r   r   c              	   C   s   zt |jd }t |jd }t t  |}t t  |}||k r\|tdd7 }|| }t|j	d\}}t|d\}	}
d
||	W S  ttfk
r   Y dS X dS )	z)Calculate and display time slot duration.z%H:%Mr   r3   r   r   r   zInvalid formatN)r
   strptimer   timer   r   r8   r   r   r   r   
ValueErrorAttributeError)r   rU   rJ   rK   start_dtend_dtr;   r   r   r   r   r   r   r   r   )  s    z!DayTimeAdmin.get_duration_displayr   N)	r%   r&   r'   r(   r   r   r   r   r   r   r   r   r   r     s    r   c                   @   st   e Zd ZdZddddgZdddgZd	d
dgZddddffZdddgZdd Z	de	_
dd Zde_
dd Zde_
dS )PlacementAdminz
    Admin interface for Advertisement Placements.
    
    Manages the relationship between campaigns, time slots,
    and channels for optimal ad placement strategies.
    r   get_channel_nameget_time_slotid_placementid_time
id_channelZid_campaign__statusZid_campaign__nameZid_channel__nameZid_time__namezPlacement Configuration)r   r   r   z5Configure where and when campaign ads will be placed.r   r   c                 C   s   |j r|j jS dS r   )r   r:   r   r   r   r   r   Y  s    z PlacementAdmin.get_campaign_namer   c                 C   s   |j r|j jS dS r   )r   r:   r   r   r   r   r   ]  s    zPlacementAdmin.get_channel_namer   c                 C   s$   |j r d|j j|j j|j jS dS )Nz
{} ({}-{})r|   )r   r   r:   r   r   r   r   r   r   r   a  s    zPlacementAdmin.get_time_slotz	Time SlotN)r%   r&   r'   r(   r   r   r   r   r   r   r   r   r   r   r   r   r   r   >  s.      
  
r   zCampaign Management Systemz	CMS AdminzCampaign Management Dashboardc                   @   s   e Zd ZdZdd ZdS )CampaignAdminSitez:Custom admin site with enhanced styling and functionality.c                 C   s   |  |}| D ]}|d jdd d qddddg}g }|D ]}||kr@|||  q@| D ]\}}||krd|| qd|S )	zp
        Return a sorted list of all the installed apps that have been
        registered in this site.
        r   c                 S   s   | d S )Nr:   r   )xr   r   r   <lambda>~      z0CampaignAdminSite.get_app_list.<locals>.<lambda>)keyr   agencieschannelsaccounts)_build_app_dictvaluessortr   items)r   r   app_dictappZ	app_orderapp_listapp_namer   r   r   get_app_listu  s    
zCampaignAdminSite.get_app_listN)r%   r&   r'   r(   r   r   r   r   r   r   r  s   r   N)3r(   Zdjango.contribr   	django.dbr   Zdjango.formsr   r   django.utils.htmlr   django.urlsr   django.utils.safestringr   django.contrib.adminr	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r+   TabularInliner9   rI   rO   register
ModelAdminrW   r   r   r   r   r   r   r   r   sitesite_header
site_titleindex_title	AdminSiter   r   r   r   r   <module>   sH   0!bK*?!0&.