Last active
May 2, 2019 07:52
-
-
Save sumitmallick/2c68aea29b2a9b310981b2ddcb94b90b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
******************************************************************************************************************************* | |
# views.py | |
#imports | |
import json | |
import os | |
import pprint | |
import re | |
import copy | |
import math | |
import calendar | |
from django.core.management import call_command | |
from django.shortcuts import render,redirect, HttpResponse, Http404 | |
from .forms import RegisterForm,LoginForm | |
from django.contrib import messages | |
from django.contrib.auth.models import User | |
from django.contrib.auth import login,authenticate,logout | |
from django.contrib.auth.decorators import login_required, user_passes_test | |
from .models import * | |
from facebook_business import FacebookSession, FacebookAdsApi | |
from facebook_business.adobjects.campaign import Campaign as AdCampaign | |
from facebook_business.adobjects.adaccountuser import AdAccountUser as AdUser | |
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator | |
from django.db.models import Count, Sum, Avg, Q | |
from datetime import date, datetime, timedelta | |
from dateutil.relativedelta import relativedelta as relativedelta | |
from django.utils import timezone | |
from django.contrib.auth.models import User | |
from .fusioncharts import FusionCharts | |
from .middleware import login_exempt | |
from itertools import chain | |
import pandas as pd | |
from django.db.models import Q | |
@login_exempt | |
def register(request): | |
form = RegisterForm(request.POST or None) | |
if form.is_valid(): | |
username = form.cleaned_data.get("username") | |
first_name = form.cleaned_data.get("first_name") | |
last_name = form.cleaned_data.get("last_name") | |
email = form.cleaned_data.get("email") | |
password = form.cleaned_data.get("password") | |
newUser = User(username =username, email = email, first_name = first_name, last_name = last_name) | |
newUser.set_password(password) | |
newUser.save() | |
login(request,newUser) | |
messages.info(request,"You have successfully registered ...") | |
return redirect("dashboard") | |
context = { | |
"form" : form | |
} | |
return render(request,"dashboard/register.html",context) | |
# user login function | |
@login_exempt | |
def loginUser(request): | |
form = LoginForm(request.POST or None) | |
context = { | |
"form":form | |
} | |
if form.is_valid(): | |
username = form.cleaned_data.get("username") | |
password = form.cleaned_data.get("password") | |
user = authenticate(username = username,password = password) | |
if user is None: | |
messages.info(request,"Incorrect Credentials") | |
return render(request,"dashboard/login.html",context) | |
login(request,user) | |
return redirect("dashboard") | |
return render(request,"dashboard/login.html",context, {'redirect_authenticated_user' : True}) | |
# user logout fucntion | |
def logoutUser(request): | |
logout(request) | |
messages.success(request,"Successfully logged out") | |
return redirect("login") | |
# resultli campaign refresh func | |
def refresultli(request): | |
try: | |
ResultliCampaign.objects.all().delete() | |
call_command('camps') # calls resultli management command | |
except: | |
return Http404 | |
return redirect("campaigns") | |
# instarank campaign refresh func | |
def refinstarank(request): | |
try: | |
InstarankCampaign.objects.all().delete() | |
call_command('incamps') # calls instarank management command | |
except: | |
raise Http404 | |
return redirect("instalist") | |
# Adwords campaign refresh func | |
# @user_passes_test(lambda u: u.is_superuser) | |
def refadwords(request): | |
try: | |
AdwordsCampaign.objects.all().delete() | |
call_command('adwords') # calls adwords management command | |
except: | |
raise Http404 | |
return redirect("adcamps") | |
def insta_hub_refresh(request): | |
try: | |
HubInstarank.objects.all().delete() | |
call_command('hubin') # calls adwords management command | |
except: | |
raise Http404 | |
return redirect('instalist') | |
def resultli_hub_refresh(request): | |
try: | |
HubResultli.objects.all().delete() | |
call_command('hubres') | |
except: | |
raise Http404 | |
return redirect('campaign_list') | |
def adwords_hub_refresh(request): | |
try: | |
HubAdwords.objects.all().delete() | |
call_command('hubads') | |
except: | |
raise Http404 | |
return redirect('adcamps') | |
def clients(request): | |
app_tag = request.POST.get('app_tag') | |
if (request.GET.get('app_tag')): | |
app_tag = request.GET.get('app_tag') | |
if app_tag: | |
# client = Campaign.objects.values('client_name', 'client_id','status').annotate(Count('client_id'),Sum('target_impressions'),Sum('impressions'),Avg('percentage')).order_by().filter(app_tag=app_tag,client_id__count__gt=0).exclude(app_tag='instagent-nocamp') | |
# client = InstarankCampaign.objects.values('client_name', 'client_id','status').annotate(Sum('impressions')).filter(client_id=10203, bill_date__gte=0, bill_date__lte=0) | |
if app_tag == 'instarank': | |
client = HubInstarank.objects.all() | |
elif app_tag == 'resultli': | |
client = HubResultli.objects.all() | |
elif app_tag == 'adwords': | |
client = HubAdwords.objects.all() | |
else: | |
raise Http404 | |
clilen = len(client) | |
else: | |
# client = Campaign.objects.values('client_name', 'client_id','status').annotate(Count('client_id'),Sum('target_impressions'),Sum('impressions'),Avg('percentage')).order_by().filter(client_id__count__gt=0).exclude(app_tag='instagent-nocamp') | |
issu_status_list = ['CXL', 'CXL Today', 'CXL Today;CHBK;CXL', 'CXL Today;CXL;CHBK', 'CXL Today;CXL', 'CXL;CXL Today', 'FUT;CXL'] | |
# instaclient = HubInstarank.objects.all().exclude(issue_status__in=issu_status_list) | |
instaclient = HubInstarank.objects.all() | |
resultliclient = HubResultli.objects.all() | |
adwordsclient = HubAdwords.objects.all() | |
client = list(chain(instaclient, resultliclient, adwordsclient)) | |
# client = instaclient|resultliclient|adwordsclient | |
clilen = len(client) | |
template_name = "dashboard/clients.html" | |
query = request.GET.get("q") | |
if query: | |
client = client.filter( | |
Q(client_name__icontains=query)| | |
Q(client_id__icontains=query) | |
).distinct() | |
context = { | |
'clients' : client, | |
'app_tag' : app_tag, | |
'clilen' : clilen, | |
'qqq' : query | |
} | |
return render(request, template_name, context) | |
def client_campaigns(request, client_id): | |
STATUS_DICT = { | |
'ov': 'Over', | |
'co': 'Critical Over', | |
'cu': 'Critical Under', | |
'ot': 'On Track', | |
'un':'Under', | |
'na': 'NA' | |
} | |
final_campaign_list = [] | |
app_tag = request.GET.get('app_tag') | |
if request.POST.get('startdate'): | |
startd = request.POST.get('startdate') | |
else: | |
startd = date.today().isoformat() | |
startdd = startd.split("-") | |
startdd = startdd[1]+"/"+startdd[2]+"/"+startdd[0] | |
print(startd) | |
#startd = '2019-04-25' | |
if request.POST.get('enddate'): | |
endd = request.POST.get('enddate') | |
else: | |
endd = date.today().isoformat() | |
enddd = endd.split("-") | |
endddd = enddd[1]+"/"+enddd[2]+"/"+enddd[0] | |
#endd = '2019-04-30' | |
if app_tag == 'instarank': | |
client_camps = InstarankCampaign.objects.values('client_id', 'status', 'target_impressions', 'days', 'client_name', 'clientproperty__lastbd', 'clientproperty__nextbd' , 'clientproperty__gviews', 'clientproperty__nextbd').annotate(impressions=Sum('impressions')).filter(client_id = client_id, created_on__gte=startd,created_on__lte=endd) | |
elif app_tag == 'resultli': | |
client_camps = ResultliCampaign.objects.values('client_id', 'status', 'target_impressions', 'days', 'client_name', 'clientproperty__lastbd', 'clientproperty__nextbd' , 'clientproperty__gviews', 'clientproperty__nextbd').annotate(impressions=Sum('impressions')).filter(client_id = client_id, created_on__gte='2019-04-25',created_on__lte='2019-04-30') | |
elif app_tag == 'adwords': | |
client_camps = AdwordsCampaign.objects.values('client_id', 'status', 'target_impressions', 'days', 'client_name', 'clientproperty__lastbd', 'clientproperty__nextbd' , 'clientproperty__gviews', 'clientproperty__nextbd').annotate(impressions=Sum('impressions')).filter(client_id = client_id, created_on__gte='2019-04-25',created_on__lte='2019-04-30') | |
else: | |
raise Http404 | |
for value in client_camps: | |
final_campaign = {} | |
final_campaign['client_name'] = value['client_name'] | |
final_campaign['app_tag'] = 'instarank' | |
final_campaign['client_id'] = value['client_id'] | |
final_campaign['impressions'] = value['impressions'] | |
if value['status']: | |
final_campaign['status'] = value['status'] | |
final_campaign['status_name'] = STATUS_DICT[value['status']] | |
else: | |
final_campaign['status_name'] = None | |
final_campaign['days'] = value['days'] | |
final_campaign['last_bd'] = value['clientproperty__lastbd'] | |
final_campaign['bill_date'] = value['clientproperty__nextbd'] | |
final_campaign['target_impressions'] = value['clientproperty__gviews'] | |
cliname = [i.replace('"', '') for i in value['client_name'] ] | |
cliname = ''.join(map(str, cliname)) | |
final_campaign_list.append(final_campaign) | |
chartObj = FusionCharts( | |
'angulargauge', | |
'ex1', | |
'600', | |
'400', | |
'chart-1', | |
'json', | |
{ | |
"chart": { | |
"caption": cliname + " : " + " - " + "Campaign Performance Gauge", | |
"subcaption": datetime.now().strftime("%Y"), | |
"lowerlimit": "0", | |
"upperlimit": int(value['target_impressions']), | |
"showvalue": "1", | |
"theme": "fusion" | |
}, | |
"colorrange": { | |
"color": [ | |
{ | |
"minvalue": "0", | |
"maxvalue": int(value['target_impressions'])* 1/4, | |
"code": "#FFC533" | |
}, | |
{ | |
"minvalue": int(value['target_impressions'])* 1/4, | |
"maxvalue": int(value['target_impressions'])* 1/2, | |
"code": "#337ab7" | |
}, | |
{ | |
"minvalue": int(value['target_impressions'])* 1/2, | |
"maxvalue": int(value['target_impressions']) * 3/4, | |
"code": "#db15a9" | |
}, | |
{ | |
"minvalue": int(value['target_impressions']) * 3/4, | |
"maxvalue": int(value['target_impressions']), | |
"code": "#62B58F" | |
}, | |
{ | |
"minvalue": int(value['target_impressions']) , | |
"maxvalue": int(value['target_impressions']) , | |
"code": "#d73925" | |
}, | |
] | |
}, | |
"dials": { | |
"dial": [ | |
{ | |
"value": value['impressions'], | |
"tooltext": str(value['impressions']) + " Impressions" , | |
} | |
] | |
}, | |
"trendpoints": { | |
"point": [ | |
{ | |
"startvalue": int(value['target_impressions']), | |
"thickness": "5", | |
"color": "white", | |
"usemarker": "1", | |
"markerbordercolor": "#E15A26", | |
"markertooltext": "<b>Target Impressions </b>: " + str(value['target_impressions']), | |
} | |
] | |
} | |
}) | |
context = { | |
'startd': startd, | |
'endd': endd, | |
'client_camps' : final_campaign_list, | |
'output': chartObj.render() | |
} | |
print(context) | |
return render(request, "dashboard/client_campaigns.html", context) | |
def userprofile(request, pk=None): | |
if not request.user.is_authenticated: | |
return render(request, 'dashboard/login.html') | |
else: | |
if pk: | |
user = User.objects.get(pk=pk) | |
else: | |
user = request.user | |
args = {'user': user} | |
return render(request, 'dashboard/userprofile.html', args) | |
# dashboard function for adwords | |
def adwords_dashboard(request): | |
template_name = 'dashboard/adwords_index.html' | |
all_adcamps = AdwordsCampaign.objects.count() | |
a = cdash(request, 'adwords') | |
context = { | |
'all_adcamps': all_adcamps, | |
} | |
b = context.update(a) | |
return render(request,template_name, context) | |
# dashboard function for instarank | |
def dashinsta(request): | |
template_name = 'dashboard/instarank_index.html' | |
all_incamps = Campaign.objects.filter(app_tag='instarank').count() | |
a = cdash(request, 'instarank') | |
context = { | |
'all_incamps': all_incamps, | |
} | |
b = context.update(a) | |
return render(request,template_name, context) | |
# dashboard function for resultli | |
@login_required(login_url = "login") | |
def dasboardview(request): | |
template_name = 'dashboard/resultli_index.html' | |
# queries | |
a = cdash(request, 'resultli') | |
context = { | |
} | |
b = context.update(a) | |
return render(request,template_name, context) | |
def cdash(request, app_tag): | |
# clients = Campaign.objects.values('client_name', 'client_id').annotate(Count('client_id'),Sum('target_impressions'),Sum('impressions')) .order_by().filter(app_tag=app_tag, client_id__count__gt=0) | |
# queryset = Campaign.objects.all() | |
if app_tag == 'instarank': | |
rr = InstarankCampaign | |
clients = HubInstarank.objects.count() | |
elif app_tag == 'adwords': | |
rr = AdwordsCampaign | |
clients = HubAdwords.objects.count() | |
else: | |
rr = ResultliCampaign | |
clients = HubResultli.objects.count() | |
o_v = rr.objects.filter(status='ov').count() | |
c_u = rr.objects.filter( status='cu').count() | |
o_t = rr.objects.filter( status='ot').count() | |
n_a = rr.objects.filter( status='na').count() | |
c_o = rr.objects.filter( status='co').count() | |
u_n = rr.objects.filter( status='un').count() | |
datte = datetime.now().strftime('%Y-%m-%d ' ' ' ' %H:%M:%S') | |
pie3d = FusionCharts("pie3d", "ex2" , "100%", "600", "chart-1", "json", | |
{ | |
"chart": { | |
"caption": "Campaign Distribution", | |
"subCaption" : "from Facebook - updated -" + str(datte), | |
"showValues":"1", | |
"showPercentInTooltip" : "0", | |
"numberPrefix" : "Campaigns", | |
"enableMultiSlicing":"1", | |
"theme": "fusion" | |
}, | |
"data": [{ | |
"label": "Over", | |
"value": o_v | |
}, { | |
"label": "On - Track", | |
"value": o_t | |
}, { | |
"label": "Critical - Under", | |
"value": c_u | |
}, { | |
"label": "Critical - Over", | |
"value": c_o | |
}, { | |
"label": "Under", | |
"value": u_n | |
},{ | |
"label": "NA", | |
"value": n_a | |
}] | |
}) | |
camps = rr.objects.count() | |
if rr.objects.aggregate(Sum('spend'))['spend__sum']: | |
totalspends = round(rr.objects.aggregate(Sum('spend'))['spend__sum'], 2) | |
averagespends = round(totalspends/camps, 2) | |
else: | |
totalspends = None | |
averagespends = None | |
if rr.objects.aggregate(Sum('cpm'))['cpm__sum']: | |
totalcpm = round(rr.objects.aggregate(Sum('cpm'))['cpm__sum'], 2) | |
averagecpm = round(totalcpm/camps, 2) | |
else: | |
totalcpm = None | |
averagecpm = None | |
context = { | |
'totalcpm': totalcpm, | |
'totalspends': totalspends, | |
'averagecpm': averagecpm, | |
'averagespends': averagespends, | |
'total_campaigns' : camps, | |
'clients' : clients, | |
'o_v': o_v, | |
'c_u':c_u, | |
'o_t':o_t, | |
'n_a':n_a, | |
'u_n':u_n, | |
'c_o':c_o, | |
'output' : pie3d.render(), | |
'chartTitle': 'Pie 3D Chart' | |
} | |
return context | |
# campaign listing of resultli | |
def common_list(request, app_tag): | |
cchecks = request.POST.getlist('checks[]') | |
if(request.GET.get('cchecks')): | |
cchecks = request.GET.get('cchecks').split(',') | |
if len(cchecks) > 0: | |
if app_tag == 'instarank': | |
cata = InstarankCampaign.objects.filter(status__in=cchecks) | |
elif app_tag == 'resultli': | |
cata = ResultliCampaign.objects.filter(status__in=cchecks) | |
elif app_tag == 'adwords': | |
cata = AdwordsCampaign.objects.filter(status__in=cchecks) | |
else: | |
raise Http404 | |
else: | |
if app_tag == 'instarank': | |
cata = InstarankCampaign.objects.all() | |
elif app_tag == 'resultli': | |
cata = ResultliCampaign.objects.all() | |
elif app_tag == 'adwords': | |
cata = AdwordsCampaign.objects.all() | |
else: | |
raise Http404 | |
query = request.GET.get("q") | |
if query: | |
cata = cata.filter( | |
Q(client_id__icontains=query)| | |
Q(client_name__icontains=query) | |
).distinct() | |
STATUS_DICT = { | |
'ov': 'Over', | |
'co': 'Critical Over', | |
'cu': 'Critical Under', | |
'ot': 'On Track', | |
'un':'Under', | |
'na': 'NA', | |
None: ' ' | |
} | |
final_campaign_list = [] | |
for value in cata: | |
final_campaign = {} | |
final_campaign['client_name'] = value.client_name | |
final_campaign['client_id'] = value.client_id | |
final_campaign['impressions'] = value.impressions | |
final_campaign['date_start'] = value.date_start | |
final_campaign['date_stop'] = value.date_stop | |
final_campaign['nbill_date'] = value.bill_date | |
final_campaign['status'] = value.status | |
if value.status is None: | |
final_campaign['status_name'] = 'None' | |
else: | |
final_campaign['status_name'] = STATUS_DICT[value.status] | |
if value.clientproperty is None: | |
final_campaign['target_impressions'] = ' ' | |
else: | |
final_campaign['target_impressions'] = value.clientproperty.gviews | |
final_campaign['days'] = value.days | |
final_campaign['app_tag'] = value.app_tag | |
final_campaign_list.append(final_campaign) | |
context = { | |
"catas" : cata, | |
"final_campaign_list" : final_campaign_list, | |
"cchecks":cchecks, | |
} | |
return context | |
def campaign_list(request): | |
template_name = "dashboard/campaigns.html" | |
func = 'resultli' | |
a = common_list(request, 'resultli') | |
context = { | |
'resultli':func, | |
'fu' :func, | |
} | |
b = context.update(a) | |
return render(request,template_name, context) | |
def adcamps(request): | |
template_name = "dashboard/campaigns.html" | |
func = 'adwords' | |
a = common_list(request, 'adwords') | |
context = { | |
'adwords':func, | |
'fu' :func, | |
} | |
b = context.update(a) | |
return render(request,template_name, context) | |
def instalist(request): | |
template_name = "dashboard/campaigns.html" | |
func = 'instarank' | |
a = common_list(request, 'instarank') | |
context = { | |
'instarank':func, | |
'fu' :func, | |
} | |
b = context.update(a) | |
return render(request,template_name, context) | |
def hubndcamp(request, slug): | |
app_tag = 'instarank' | |
unmach = InstarankCampaign.objects.filter(datag='mismatch') | |
mach = InstarankCampaign.objects.filter(datag='match') | |
nocampp = HubInstarank.objects.filter(hubs=None) | |
noagent = InstarankCampaign.objects.filter(clientproperty=None) | |
if slug == 'noagent': | |
qs = noagent | |
if slug=='mismatch': | |
qs = unmach.difference(noagent) | |
if slug=='matches': | |
qs = mach | |
if slug=='nocamps': | |
qs = nocampp | |
return render(request, 'dashboard/hubndcamp.html', {'app_tag':app_tag, 'qs':qs, 'sluggy':slug}) | |
def resultli_mismatch(request, slug): | |
app_tag = 'resultli' | |
unmach = ResultliCampaign.objects.filter(datag='mismatch') | |
mach = ResultliCampaign.objects.filter(datag='match') | |
nocampp = HubResultli.objects.filter(resultlicampaign=None) | |
noagent = ResultliCampaign.objects.filter(clientproperty=None) | |
if slug == 'noagent': | |
qs = noagent | |
if slug=='mismatch': | |
qs = unmach.difference(noagent) | |
if slug=='matches': | |
qs = mach | |
if slug=='nocamps': | |
qs = nocampp | |
return render(request, 'dashboard/resultli_mismatch.html', {'app_tag':app_tag, 'qs':qs, 'sluggy':slug}) | |
def adwords_mismatch(request, slug): | |
app_tag = 'adwords' | |
unmach = AdwordsCampaign.objects.filter(datag='mismatch') | |
mach = AdwordsCampaign.objects.filter(datag='match') | |
nocampp = HubAdwords.objects.filter(adwordscampaign=None) | |
noagent = AdwordsCampaign.objects.filter(clientproperty=None) | |
if slug == 'noagent': | |
qs = noagent | |
if slug=='mismatch': | |
qs = unmach.difference(noagent) | |
if slug=='matches': | |
qs = mach | |
if slug=='nocamps': | |
qs = nocampp | |
return render(request, 'dashboard/adwords_mismatch.html', {'app_tag':app_tag ,'qs':qs, 'sluggy':slug}) | |
def over_spends(request, slug): | |
a = InstarankCampaign.objects.all() | |
five = math.ceil(a.count()/100 * 5) | |
spends = set(a.order_by('-spend')[:five]) | |
cpms = set(a.order_by('-cpm')[:five]) | |
if slug == 'all': | |
qs = spends.union(cpms) | |
if slug == 'high-spends': | |
qs = a.order_by('-spend')[:five] | |
if slug == 'high-cpm': | |
qs = a.order_by('-cpm')[:five] | |
if slug == 'high-spdcpm': | |
qs = spends.intersection(cpms) | |
return render(request, "dashboard/overspend.html", {'qs':qs, 'sluggy': slug}) | |
def resultli_over_spends(request, slug): | |
a = ResultliCampaign.objects.all() | |
five = math.ceil(a.count()/100 * 5) | |
spends = set(a.order_by('-spend')[:five]) | |
cpms = set(a.order_by('-cpm')[:five]) | |
if slug == 'all': | |
qs = spends.union(cpms) | |
if slug == 'high-spends': | |
qs = a.order_by('-spend')[:five] | |
if slug == 'high-cpm': | |
qs = a.order_by('-cpm')[:five] | |
if slug == 'high-spdcpm': | |
qs = spends.intersection(cpms) | |
return render(request, "dashboard/resultli_over_spends.html", {'qs':qs, 'sluggy': slug}) | |
def adwords_over_spends(request, slug): | |
a = AdwordsCampaign.objects.all() | |
five = math.ceil(a.count()/100 * 5) | |
spends = set(a.order_by('-spend')[:five]) | |
cpms = set(a.order_by('-cpm')[:five]) | |
if slug == 'all': | |
qs = spends.union(cpms) | |
if slug == 'high-spends': | |
qs = a.order_by('-spend')[:five] | |
if slug == 'high-cpm': | |
qs = a.order_by('-cpm')[:five] | |
if slug == 'high-spdcpm': | |
qs = spends.intersection(cpms) | |
return render(request, "dashboard/adwords_overspends.html", {'qs':qs, 'sluggy': slug}) | |
************************************************************************************************************************************ | |
# base.html | |
<script> | |
$(function () { | |
$('#example1').DataTable() | |
$('#example2').DataTable({ | |
'paging' : true, | |
'lengthChange': false, | |
'searching' : false, | |
'ordering' : true, | |
'info' : true, | |
'autoWidth' : false | |
}) | |
$('#filterdaterange').daterangepicker({ | |
ranges : { | |
'Today' : [moment(), moment()], | |
'Yesterday' : [moment().subtract(1, 'days'), moment().subtract(1, 'days')], | |
'Last 7 Days' : [moment().subtract(6, 'days'), moment()], | |
'Last 30 Days': [moment().subtract(29, 'days'), moment()], | |
'This Month' : [moment().startOf('month'), moment().endOf('month')], | |
'Last Month' : [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] | |
}, | |
autoUpdateInput: false | |
}, function (start, end) { | |
$('#startdate').val(start.format('YYYY-MM-DD')); | |
$('#enddate').val(end.format('YYYY-MM-DD')) | |
//window.alert('You chose: ' + start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); | |
}); | |
$('#filterdaterange').on('apply.daterangepicker', function(ev, picker) { | |
$(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY')); | |
}); | |
}) | |
</script> | |
************************************************************************************************************************ | |
#clients_campaigns.html | |
<div class="container"> | |
<div class="dash_filter"> | |
<form method="POST">{% csrf_token %} | |
<input type="text" id="filterdaterange" value="{{startd}} - {{endd}}"/> | |
<input type="hidden" name="startdate" id="startdate" /> | |
<input type="hidden" name="enddate" id="enddate" /> | |
| |
<input class="btn btn-primary" type="submit" value="Submit"> | |
</form> | |
</div> | |
************************************************************************************************************************ | |
#incamps.py | |
from django.core.management.base import BaseCommand | |
from django.utils import timezone | |
import json | |
import os | |
import pprint | |
import re | |
import copy | |
from django.contrib import messages | |
from facebook_business import FacebookSession | |
from facebook_business import FacebookAdsApi | |
from facebook_business.adobjects.campaign import Campaign as AdCampaign | |
from facebook_business.adobjects.adaccountuser import AdAccountUser as AdUser | |
from facebook_business.adobjects.adaccount import AdAccount | |
from django.db.models import Count, Sum, Avg | |
from django.db.models import Q | |
from dashboard.models import InstarankCampaign, HubInstarank | |
from datetime import date, datetime | |
from dateutil.relativedelta import relativedelta as relativedelta | |
pp = pprint.PrettyPrinter(indent=4) | |
this_dir = os.path.dirname(__file__) | |
config_filename = os.path.join(this_dir, '../../instaconfig.json') | |
config_file = open(config_filename) | |
config = json.load(config_file) | |
config_file.close() | |
### Setup session and api objects | |
session = FacebookSession( | |
config['app_id'], | |
config['app_secret'], | |
config['access_token'], | |
) | |
api = FacebookAdsApi(session) | |
class Command(BaseCommand): | |
help = 'Gets Instarank data from Facebook' | |
def handle(self, *args, **kwargs): | |
created_on = input(str("date>> ")) | |
FacebookAdsApi.set_default_api(api) | |
business_account = AdAccount(config['act_id']) | |
business_account.remote_read(fields=[AdAccount.Field.tos_accepted]) | |
camp = business_account.get_campaigns() | |
count = 0 | |
counterr = 0 | |
for campaign in camp: | |
check_bd_flag = 0 | |
get_camp_insights = campaign.get_insights(fields=[ | |
'campaign_name', | |
'impressions', | |
'clicks', | |
'unique_clicks', | |
'actions', | |
'spend', | |
'cpm', | |
], params= {'time_range':{'since': created_on, 'until': created_on}}) | |
print(get_camp_insights) | |
count = count+1 | |
if (bool(get_camp_insights)==True): | |
client = get_camp_insights[0]['campaign_name'] | |
imp_ressions = get_camp_insights[0]['impressions'] | |
spend = get_camp_insights[0]['spend'] | |
date_start = get_camp_insights[0]['date_start'] | |
date_stop = get_camp_insights[0]['date_stop'] | |
cpm = get_camp_insights[0]['cpm'] | |
client = client.replace(' - ','@@') | |
split_array = client.split('@@') | |
# damo = date.today() | |
# bill_month = '{:02}'.format(damo.month) | |
# bill_year = '{:04}'.format(damo.year) | |
# for value in split_array: | |
# if 'BD' in value: | |
# check_bd_flag = 0 | |
# if len(value)==3 or len(value)==4: | |
# bill_date = value.replace('BD','') | |
# if bill_month == '02' and bill_date > '28': | |
# bill_date = '28' | |
# elif bill_date > '31': | |
# bill_date = str(int(bill_date) - 31) | |
# bill_month = str(int(bill_month) + 1) | |
# bill_date = bill_year+'-'+bill_month+'-'+bill_date | |
# else: | |
# continue | |
# check_bd_flag = 1 | |
if split_array[0][0:2] == '[]': | |
continue | |
else: | |
client_id = (re.findall(r'\d+', client.split('@@')[0])[0]) | |
# client_id = (re.findall(r'\d+', client.split('@@')[0])[0]) | |
client_name = (client.split('@@')[0].split('] ')[1].strip()) | |
try: | |
if 'for ' in client: | |
target_impressions = int((re.findall(r'\d+',client.split('for ')[1])[0])) | |
else: | |
target_impressions = int((re.findall(r'\d+',client.split('@@')[1])[0])) | |
except: | |
target_impressions = 0 | |
if HubInstarank.objects.filter(kid=client_id): | |
if HubInstarank.objects.get(kid=client_id).nextbd: | |
bill_date = HubInstarank.objects.get(kid=client_id).nextbd | |
else: | |
bill_date = None | |
else: | |
bill_date = None | |
if bill_date is not None: | |
days = (bill_date.date() - datetime.now().date() ).days | |
else: | |
days = None | |
if days and days < 0: | |
# bill_datea = datetime.strptime(bill_date, "%Y-%m-%d") | |
bill_dateaa = bill_date + relativedelta(months=+1) | |
days = (bill_dateaa.date() - datetime.now().date()).days | |
# bill_datea = datetime.strptime(str(bill_dateaa), "%Y-%m-%d") | |
bill_date = bill_dateaa.strftime('%Y-%m-%d') | |
if target_impressions and target_impressions>0 and imp_ressions and days: | |
get_percent = (int(imp_ressions)/target_impressions)*100 | |
if get_percent>250: | |
status = 'co' | |
elif (get_percent>=150 and days>=0 and days<=7) or (get_percent>=50 and days>=22) or (get_percent>=100 and days>=15 and days<=21) or (get_percent>=125 and days>=8 and days<=14): | |
status = 'ov' | |
elif (get_percent>=120 and get_percent<=150 and days>=0 and days<=7) or (get_percent>=100 and get_percent<=125 and days==8) or (get_percent>=90 and get_percent<=125 and days==9) or (get_percent>=80 and get_percent<=125 and days==10) or (get_percent>=70 and get_percent<=125 and days==11) or (get_percent>=60 and get_percent<=125 and days==12) or (get_percent>=50 and get_percent<=125 and days==13) or (get_percent>=40 and get_percent<=125 and days==14) or (get_percent>=30 and get_percent<=100 and days==15) or (get_percent>=20 and get_percent<=100 and days==16) or (get_percent>=10 and get_percent<=100 and days>=17 and days<=21) or (get_percent>=1 and get_percent<=50 and days>=22 and days<=26) or (get_percent>=0 and get_percent<=50 and days>=27): | |
status = 'ot' | |
elif (get_percent<=120 and days>=0 and days<=7) or (get_percent<=100 and days==8) or (get_percent<=90 and days==9) or (get_percent<=80 and days==10) or (get_percent<=70 and days==11) or (get_percent<=60 and days==12) or (get_percent<=50 and days==13) or (get_percent<=40 and days==14) or (get_percent<=30 and days==15) or (get_percent<=20 and days==16) or (get_percent<=10 and days>=17 and days<=21) or (get_percent<=1 and days>=22 and days<=26): | |
status = 'un' | |
elif (get_percent<100 and days>=0 and days<=7) or (get_percent<=90 and days==8) or (get_percent<=80 and days==9) or (get_percent<=70 and days==10) or (get_percent<=60 and days==11) or (get_percent<=50 and days==12) or (get_percent<=40 and days==13) or (get_percent<=30 and days==14) or (get_percent<=20 and days==15) or (get_percent<=10 and days==16) or (get_percent<=1 and days>=17 and days<=21): | |
status = 'cu' | |
else: | |
status = 'na' | |
else: | |
get_percent = 0 | |
status = None | |
counterr += 1 | |
if target_impressions and HubInstarank.objects.filter(kid=client_id, gviews=int(target_impressions)).exists() is True: | |
data = { | |
'clientproperty': HubInstarank.objects.filter(kid=client_id).first(), | |
'spend' : spend, | |
'target_impressions' : int(target_impressions), | |
'date_start' : date_start, | |
'date_stop' :date_stop, | |
'impressions' : imp_ressions, | |
'client_id': client_id, | |
'client_name' : client_name, | |
'cpm': cpm, | |
'days':days, | |
'bill_date': bill_date, | |
'status':status, | |
'app_tag': 'instarank', | |
'datag': 'match', | |
'created_on': created_on | |
} | |
# print(counterr, "match>>>>>>>>", data) | |
InstarankCampaign.objects.create(**data) | |
# instance = InstarankCampaign(**data) | |
# print(instance) | |
# instance.save() | |
else: | |
data = { | |
'clientproperty': HubInstarank.objects.filter(kid=client_id).first(), | |
'spend' : spend, | |
'target_impressions' : target_impressions, | |
'date_start' : date_start, | |
'date_stop' :date_stop, | |
'impressions' : imp_ressions, | |
'client_id': client_id, | |
'client_name' : client_name, | |
'cpm': cpm, | |
'days':days, | |
'bill_date': bill_date, | |
'status':status, | |
'app_tag': 'instarank', | |
'datag': 'mismatch', | |
'created_on': created_on | |
} | |
# print(counterr, "match>>>>>>>>", data) | |
InstarankCampaign.objects.create(**data) | |
# instance = InstarankCampaign(**data) | |
# print(instance) | |
# instance.save() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment