-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathtasks.py
More file actions
1491 lines (1285 loc) · 52.8 KB
/
tasks.py
File metadata and controls
1491 lines (1285 loc) · 52.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Celery tasks for the ad server."""
import datetime
import logging
from collections import defaultdict
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core import mail
from django.core.cache import cache
from django.db.models import Count
from django.db.models import F
from django.db.models import FloatField
from django.db.models import Q
from django.db.models import Sum
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from django_slack import slack_message
from config.celery_app import app
from .constants import FLIGHT_STATE_CURRENT
from .constants import FLIGHT_STATE_UPCOMING
from .constants import PAID_CAMPAIGN
from .constants import PUBLISHER_HOUSE_CAMPAIGN
from .importers import psf
from .models import AdImpression
from .models import Advertisement
from .models import Advertiser
from .models import AdvertiserImpression
from .models import DomainImpression
from .models import Flight
from .models import GeoImpression
from .models import KeywordImpression
from .models import Offer
from .models import PlacementImpression
from .models import Publisher
from .models import PublisherImpression
from .models import PublisherPaidImpression
from .models import Region
from .models import RegionImpression
from .models import RegionTopicImpression
from .models import RotationImpression
from .models import Topic
from .models import UpliftImpression
from .reports import PublisherReport
from .utils import calculate_ctr
from .utils import calculate_percent_diff
from .utils import generate_absolute_url
from .utils import get_ad_day
from .utils import get_day
from .utils import offers_dump_exists
log = logging.getLogger(__name__) # noqa
@app.task()
def daily_update_geos(day=None, geo=True, region=True):
"""
Update the Geo & region index each day.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
if not geo and not region:
log.error("geo or region required, please pass one as True")
return
log.info(
"Updating RegionImpressions and/or GeoImpressions for %s-%s",
start_date,
end_date,
)
if region:
# Delete all previous Region impressions
RegionImpression.objects.using("default").filter(
date__gte=start_date,
date__lt=end_date,
).delete()
if geo:
# Delete all previous Geo impressions
GeoImpression.objects.using("default").filter(
date__gte=start_date,
date__lt=end_date,
).delete()
if offers_dump_exists(start_date):
# Use the optimized aggregation that requires a daily dump of offers to cloud storage
from ethicalads_ext.etl.aggregations import GeoAggregation
from ethicalads_ext.etl.aggregations import RegionAggregation
if geo:
agg = GeoAggregation(start_date, end_date)
agg.aggregate()
if region:
agg = RegionAggregation(start_date, end_date)
agg.aggregate()
return
topic_mapping = defaultdict(
lambda: {
"decisions": 0,
"offers": 0,
"views": 0,
"clicks": 0,
}
)
queryset = Offer.objects.using(settings.REPLICA_SLUG).filter(
# For region and topic reports, we are excluding ads that were ineligible to be paid
# from the aggregations unless the publisher isn't approved for paid ads.
# This will give us more accurate KPIs on fill rates for paid publishers.
Q(paid_eligible=True) | Q(publisher__allow_paid_campaigns=False),
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
for values in (
queryset.values("advertisement", "country", "publisher")
.annotate(
total_decisions=Count("country"),
total_offers=Count("country", filter=Q(advertisement__isnull=False)),
total_views=Count("country", filter=Q(viewed=True)),
total_clicks=Count("country", filter=Q(clicked=True)),
)
.filter(total_decisions__gt=0)
.order_by("-total_decisions")
.iterator()
):
country = values["country"]
if geo:
impression, _ = GeoImpression.objects.using("default").get_or_create(
publisher_id=values["publisher"],
advertisement_id=values["advertisement"],
country=country,
date=start_date,
)
GeoImpression.objects.using("default").filter(pk=impression.pk).update(
decisions=values["total_decisions"],
offers=values["total_offers"],
views=values["total_views"],
clicks=values["total_clicks"],
)
if region:
_region = Region.get_region_from_country_code(country)
publisher = values["publisher"]
advertisement = values["advertisement"]
topic_mapping[f"{advertisement}:{publisher}:{_region}"]["decisions"] += (
values["total_decisions"]
)
topic_mapping[f"{advertisement}:{publisher}:{_region}"]["offers"] += values[
"total_offers"
]
topic_mapping[f"{advertisement}:{publisher}:{_region}"]["views"] += values[
"total_views"
]
topic_mapping[f"{advertisement}:{publisher}:{_region}"]["clicks"] += values[
"total_clicks"
]
if region:
for data, value in topic_mapping.items():
ad, publisher, _region = data.split(":")
# Handle the conversion of None
if ad == "None":
ad = None
impression, _ = RegionImpression.objects.using("default").get_or_create(
publisher_id=publisher,
advertisement_id=ad,
region=_region,
date=start_date,
)
RegionImpression.objects.using("default").filter(pk=impression.pk).update(
decisions=F("decisions") + value["decisions"],
offers=F("offers") + value["offers"],
views=F("views") + value["views"],
clicks=F("clicks") + value["clicks"],
)
@app.task()
def daily_update_placements(day=None):
"""
Update the Placement index each day.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
log.info("Updating PlacementImpressions for %s-%s", start_date, end_date)
queryset = Offer.objects.using(settings.REPLICA_SLUG).filter(
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
for values in (
queryset.values("publisher", "advertisement", "div_id", "ad_type_slug")
.annotate(
total_decisions=Count("div_id"),
total_offers=Count("div_id", filter=Q(advertisement__isnull=False)),
total_views=Count("div_id", filter=Q(viewed=True)),
total_clicks=Count("div_id", filter=Q(clicked=True)),
)
.filter(total_decisions__gt=0)
.filter(publisher__record_placements=True)
.exclude(div_id__regex=r"(rtd-\w{4}|ad_\w{4}).*")
.order_by("-total_decisions")
.iterator()
):
impression, _ = PlacementImpression.objects.using("default").get_or_create(
publisher_id=values["publisher"],
advertisement_id=values["advertisement"],
div_id=values["div_id"],
ad_type_slug=values["ad_type_slug"],
date=start_date,
)
PlacementImpression.objects.using("default").filter(pk=impression.pk).update(
decisions=values["total_decisions"],
offers=values["total_offers"],
views=values["total_views"],
clicks=values["total_clicks"],
)
@app.task()
def daily_update_impressions(day=None):
"""
Update the AdImpression index each day.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
log.info("Updating AdImpressions for %s-%s", start_date, end_date)
queryset = Offer.objects.using(settings.REPLICA_SLUG).filter(
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
for values in (
queryset.values("publisher", "advertisement")
# This needs to be publisher and not advertisement to gets decisions properly
.annotate(
total_decisions=Count("publisher"),
total_offers=Count("publisher", filter=Q(advertisement__isnull=False)),
total_views=Count("publisher", filter=Q(viewed=True)),
total_clicks=Count("publisher", filter=Q(clicked=True)),
view_time=Sum("view_time"),
)
.filter(total_decisions__gt=0)
.order_by("-total_decisions")
.iterator()
):
impression, _ = AdImpression.objects.using("default").get_or_create(
publisher_id=values["publisher"],
advertisement_id=values["advertisement"],
date=start_date,
)
AdImpression.objects.using("default").filter(pk=impression.pk).update(
decisions=values["total_decisions"],
offers=values["total_offers"],
views=values["total_views"],
clicks=values["total_clicks"],
view_time=values["view_time"],
)
@app.task()
def daily_update_keywords(day=None):
"""
Update the KeywordImpression index each day.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
log.info("Updating KeywordImpression for %s-%s", start_date, end_date)
# Remove all old keyword impressions, because they are cumulative
KeywordImpression.objects.using("default").filter(
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
).delete()
keyword_mapping = defaultdict(
lambda: {
"decisions": 0,
"offers": 0,
"views": 0,
"clicks": 0,
}
)
queryset = Offer.objects.using(settings.REPLICA_SLUG).filter(
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
all_topics = Topic.load_from_cache()
for values in (
queryset.values("publisher", "advertisement", "keywords", "viewed", "clicked")
.annotate(
# NOTE: decisions and offers will be wrong on this table (they'll match views)
# because the table is already joined against advertisement/flight
total_decisions=Count("keywords"),
total_offers=Count("keywords", filter=Q(advertisement__isnull=False)),
total_views=Count("keywords", filter=Q(viewed=True)),
total_clicks=Count("keywords", filter=Q(clicked=True)),
)
.exclude(advertisement__isnull=True)
# We don't record empty keyword lists in the DB - just NULLs
.exclude(keywords__isnull=True)
.order_by("-total_decisions")
.values(
"publisher",
"advertisement",
"keywords",
"advertisement__flight__targeting_parameters",
"total_decisions",
"total_offers",
"total_views",
"total_clicks",
)
.iterator()
):
if not (
values["keywords"] and values["advertisement__flight__targeting_parameters"]
):
continue
page_keywords = set(values["keywords"])
flight_targeting = values["advertisement__flight__targeting_parameters"]
flight_keywords = set(flight_targeting.get("include_keywords", {}))
flight_topics = set(flight_targeting.get("include_topics", {}))
# If this flight targeted topics, add those as well
for topic in flight_topics:
if topic in all_topics:
for kw in all_topics[topic]:
flight_keywords.add(kw)
# Only store keywords where the advertiser targeting
# matched the keywords on the offer
matched_keywords = page_keywords & flight_keywords
for keyword in matched_keywords:
advertisement_id = values["advertisement"]
publisher_id = values["publisher"]
index = f"{advertisement_id}:{publisher_id}:{keyword}"
keyword_mapping[index]["decisions"] += values["total_decisions"]
keyword_mapping[index]["offers"] += values["total_offers"]
keyword_mapping[index]["views"] += values["total_views"]
keyword_mapping[index]["clicks"] += values["total_clicks"]
keyword_imps = []
for data, value in keyword_mapping.items():
ad, publisher, keyword = data.split(":")
keyword_imps.append(
KeywordImpression(
date=start_date,
publisher_id=publisher,
advertisement_id=ad,
keyword=keyword,
decisions=value["decisions"],
offers=value["offers"],
views=value["views"],
clicks=value["clicks"],
)
)
# Create all the keyword impressions in single batch
KeywordImpression.objects.bulk_create(keyword_imps)
@app.task()
def daily_update_regiontopic(day=None):
"""
Update the RegionTopicImpression index each day.
Each data point will have one region, but multiple possible topics.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
log.info("Updating RegionTopic's for %s-%s", start_date, end_date)
# Remove all old impressions, because they are cumulative
RegionTopicImpression.objects.using("default").filter(
date__gte=start_date, date__lt=end_date
).delete()
all_topics = Topic.load_from_cache()
topic_mapping = defaultdict(
lambda: {
"decisions": 0,
"offers": 0,
"views": 0,
"clicks": 0,
}
)
queryset = Offer.objects.using(settings.REPLICA_SLUG).filter(
# For region and topic reports, we are excluding ads that were ineligible to be paid
# from the aggregations unless the publisher isn't approved for paid ads.
# This will give us more accurate KPIs on fill rates for paid publishers.
Q(paid_eligible=True) | Q(publisher__allow_paid_campaigns=False),
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
for values in (
queryset.values("advertisement", "keywords", "country")
.annotate(
total_decisions=Count("country"),
total_offers=Count("country", filter=Q(advertisement__isnull=False)),
total_views=Count("country", filter=Q(viewed=True)),
total_clicks=Count("country", filter=Q(clicked=True)),
)
.filter(total_decisions__gt=0)
.order_by("-total_decisions")
.values(
"keywords",
"advertisement",
"country",
"total_decisions",
"total_offers",
"total_views",
"total_clicks",
)
.iterator()
):
if not (values["keywords"] and values["country"]):
continue
keywords = values["keywords"]
country = values["country"]
ad = values["advertisement"]
publisher_keywords = set(keywords)
topics = set()
for keyword in publisher_keywords:
for topic in all_topics:
if keyword in all_topics[topic]:
topics.add(topic)
# If nothing gets set as a topic, assign it other
if not topics:
topics.add("other")
region = Region.get_region_from_country_code(country)
# Aggregate data into topic_mapping to save doing queries until we have everything counted
# This is important because we can't query on keywords, so we have a lot of records that increment
# the total count on the region & topic.
for topic in topics:
topic_mapping[f"{ad}:{region}:{topic}"]["decisions"] += values[
"total_decisions"
]
topic_mapping[f"{ad}:{region}:{topic}"]["offers"] += values["total_offers"]
topic_mapping[f"{ad}:{region}:{topic}"]["views"] += values["total_views"]
topic_mapping[f"{ad}:{region}:{topic}"]["clicks"] += values["total_clicks"]
for data, value in topic_mapping.items():
ad, region, topic = data.split(":")
# Handle the conversion of
if ad == "None":
ad = None
impression, _ = RegionTopicImpression.objects.using("default").get_or_create(
date=start_date, advertisement_id=ad, region=region, topic=topic
)
# these are a sum because we can't query for specific keywords from postgres,
# so a specific publisher and advertisement set could return the same keyword:
# ['python', 'django'] and ['python, 'flask'] both are `python` in this case.
RegionTopicImpression.objects.using("default").filter(pk=impression.pk).update(
decisions=F("decisions") + value["decisions"],
offers=F("offers") + value["offers"],
views=F("views") + value["views"],
clicks=F("clicks") + value["clicks"],
)
@app.task()
def daily_update_uplift(day=None):
"""
Generate the daily index of UpliftImpressions.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
log.info("Updating uplift for %s-%s", start_date, end_date)
# Delete any previous uplift data for this day
UpliftImpression.objects.using("default").filter(
date__gte=start_date,
date__lt=end_date,
).delete()
if offers_dump_exists(start_date):
# Use the optimized aggregation that requires a daily dump of offers to cloud storage
from ethicalads_ext.etl.aggregations import UpliftAggregation
agg = UpliftAggregation(start_date, end_date)
agg.aggregate()
return
queryset = Offer.objects.using(settings.REPLICA_SLUG).filter(
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
for values in (
queryset.values("publisher", "advertisement")
.annotate(
total_decisions=Count("uplifted"),
total_offers=Count("uplifted", filter=Q(advertisement__isnull=False)),
total_views=Count("uplifted", filter=Q(viewed=True)),
total_clicks=Count("uplifted", filter=Q(clicked=True)),
)
.filter(total_decisions__gt=0)
.order_by("-total_decisions")
.values(
"publisher",
"advertisement",
"total_decisions",
"total_offers",
"total_views",
"total_clicks",
)
.iterator()
):
impression, _ = UpliftImpression.objects.using("default").get_or_create(
publisher_id=values["publisher"],
advertisement_id=values["advertisement"],
date=start_date,
)
UpliftImpression.objects.using("default").filter(pk=impression.pk).update(
decisions=values["total_decisions"],
offers=values["total_offers"],
views=values["total_views"],
clicks=values["total_clicks"],
)
@app.task()
def daily_update_domains(day=None):
"""
Generate the daily index of DomainImpressions.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
log.info("Updating domains for %s-%s", start_date, end_date)
# Delete any previous domain data for this day
DomainImpression.objects.using("default").filter(
date__gte=start_date,
date__lt=end_date,
).delete()
if offers_dump_exists(start_date):
# Use the optimized aggregation that requires a daily dump of offers to cloud storage
from ethicalads_ext.etl.aggregations import DomainAggregation
agg = DomainAggregation(start_date, end_date)
agg.aggregate()
return
queryset = Offer.objects.using(settings.REPLICA_SLUG).filter(
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
for values in (
queryset.values("advertisement", "domain")
.annotate(
total_decisions=Count("domain"),
total_offers=Count("domain", filter=Q(advertisement__isnull=False)),
total_views=Count("domain", filter=Q(viewed=True)),
total_clicks=Count("domain", filter=Q(clicked=True)),
)
.exclude(domain__isnull=True)
.filter(total_views__gt=0)
.order_by("-total_decisions")
.values(
"advertisement",
"domain",
"total_decisions",
"total_offers",
"total_views",
"total_clicks",
)
.iterator()
):
impression, _ = DomainImpression.objects.using("default").get_or_create(
advertisement_id=values["advertisement"],
domain=values["domain"],
date=start_date,
)
DomainImpression.objects.using("default").filter(pk=impression.pk).update(
decisions=values["total_decisions"],
offers=values["total_offers"],
views=values["total_views"],
clicks=values["total_clicks"],
)
@app.task()
def daily_update_rotations(day=None):
"""
Generate the daily index of RotationImpressions.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
log.info("Updating rotation data for %s-%s", start_date, end_date)
# Delete any previous rotations for this day
RotationImpression.objects.using("default").filter(
date__gte=start_date,
date__lt=end_date,
).delete()
if offers_dump_exists(start_date):
# Use the optimized aggregation that requires a daily dump of offers to cloud storage
from ethicalads_ext.etl.aggregations import RotationAggregation
agg = RotationAggregation(start_date, end_date)
agg.aggregate()
return
queryset = Offer.objects.using(settings.REPLICA_SLUG).filter(
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
for values in (
queryset.values("publisher", "advertisement")
.filter(rotations__gt=1)
.annotate(
total_decisions=Count("publisher"),
total_offers=Count("publisher", filter=Q(advertisement__isnull=False)),
total_views=Count("publisher", filter=Q(viewed=True)),
total_clicks=Count("publisher", filter=Q(clicked=True)),
)
.filter(total_decisions__gt=0)
.order_by("-total_decisions")
.values(
"publisher",
"advertisement",
"total_decisions",
"total_offers",
"total_views",
"total_clicks",
)
.iterator()
):
impression, _ = RotationImpression.objects.using("default").get_or_create(
publisher_id=values["publisher"],
advertisement_id=values["advertisement"],
date=start_date,
)
RotationImpression.objects.using("default").filter(pk=impression.pk).update(
decisions=values["total_decisions"],
offers=values["total_offers"],
views=values["total_views"],
clicks=values["total_clicks"],
)
@app.task()
def daily_update_advertisers(day=None):
"""
Generate the daily index of AdvertiserImpressions.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
log.info("Updating advertiser impressions for %s-%s", start_date, end_date)
# Important: uses the *already calculated* AdImpression index
# This should make this much faster than using the Offers table
queryset = AdImpression.objects.using(settings.REPLICA_SLUG).filter(
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
for values in (
queryset.values(
"advertisement__flight__campaign__advertiser__name",
"advertisement__flight__campaign__advertiser_id",
)
.annotate(
total_decisions=Sum("decisions"),
total_offers=Sum("offers"),
total_views=Sum("views"),
total_clicks=Sum("clicks"),
total_spend=Sum(
(F("clicks") * F("advertisement__flight__cpc"))
+ (F("views") * F("advertisement__flight__cpm") / 1000),
output_field=FloatField(),
),
)
.filter(advertisement__isnull=False)
.order_by("advertisement__flight__campaign__advertiser__name")
.iterator()
):
advertiser_id = values["advertisement__flight__campaign__advertiser_id"]
impression, _ = AdvertiserImpression.objects.using("default").get_or_create(
advertiser_id=advertiser_id,
date=start_date,
)
AdvertiserImpression.objects.using("default").filter(pk=impression.pk).update(
decisions=values["total_decisions"],
offers=values["total_offers"],
views=values["total_views"],
clicks=values["total_clicks"],
spend=values["total_spend"],
)
@app.task()
def daily_update_publishers(day=None):
"""
Generate the daily index of PublisherImpressions.
:arg day: An optional datetime object representing a day
"""
start_date, end_date = get_day(day)
log.info("Updating publisher impressions for %s-%s", start_date, end_date)
# Important: uses the *already calculated* AdImpression index
# This should make this much faster than using the Offers table
queryset = AdImpression.objects.using(settings.REPLICA_SLUG).filter(
date__gte=start_date,
date__lt=end_date, # Things at UTC midnight should count towards tomorrow
)
for model, filters in (
(PublisherImpression, {}),
(
PublisherPaidImpression,
{"advertisement__flight__campaign__campaign_type": PAID_CAMPAIGN},
),
):
for values in (
queryset.filter(**filters)
.values("publisher__name", "publisher_id")
.annotate(
total_decisions=Sum("decisions"),
total_offers=Sum(
"offers", filter=Q(advertisement__isnull=False), default=0
),
total_views=Sum("views"),
total_clicks=Sum("clicks"),
total_revenue=Sum(
(F("clicks") * F("advertisement__flight__cpc"))
+ (F("views") * F("advertisement__flight__cpm") / 1000),
output_field=FloatField(),
default=0,
),
)
.order_by("publisher__name")
.iterator()
):
impression, _ = model.objects.using("default").get_or_create(
publisher_id=values["publisher_id"],
date=start_date,
)
model.objects.using("default").filter(pk=impression.pk).update(
decisions=values["total_decisions"],
offers=values["total_offers"],
views=values["total_views"],
clicks=values["total_clicks"],
revenue=values["total_revenue"],
)
@app.task(time_limit=60 * 60 * 4)
def daily_update_reports():
"""Update today's report data rather than the previous day."""
day, _ = get_day()
update_previous_day_reports(day)
@app.task(time_limit=60 * 60 * 4)
def update_previous_day_reports(day=None):
"""
Complete all report data for the previous day.
:arg day: An optional datetime object representing a day.
"""
start_date, _ = get_day(day)
if not day:
# If not specified,
# do the previous day now that the day is complete
start_date -= datetime.timedelta(days=1)
slack_message(
"adserver/slack/generic-message.slack",
{
"text": f"Started aggregating report data for yesterday ({start_date:%Y-%m-%d})."
},
)
# Do all reports
daily_update_geos(start_date)
daily_update_placements(start_date)
daily_update_impressions(start_date)
daily_update_advertisers(start_date) # Important: after daily_update_impressions
daily_update_publishers(start_date) # Important: after daily_update_impressions
daily_update_keywords(start_date)
daily_update_uplift(start_date)
daily_update_domains(start_date)
daily_update_rotations(start_date)
daily_update_regiontopic(start_date)
# Updates an aggregation on each paid flight
update_flight_traffic_fill.apply_async()
if not day:
# Send notification to Slack about previous day's reports
# Don't send this notification if run manually
slack_message(
"adserver/slack/generic-message.slack",
{
"text": f"Completed aggregating report data for yesterday ({start_date:%Y-%m-%d}). :page_with_curl:"
},
)
@app.task()
def remove_old_report_data(days=366):
"""
Remove old report data for selected reports from the database.
Removes:
- geo breakdown data
- placement data
- keyword data
- uplift data
- regiontopic data
"""
old_cutoff = get_ad_day() - datetime.timedelta(days=days)
models = (
GeoImpression,
PlacementImpression,
KeywordImpression,
UpliftImpression,
RegionTopicImpression,
)
for model in models:
model_name = model.__name__
log.info("Deleting old %s before %s", model_name, old_cutoff)
model.objects.filter(date__lt=old_cutoff).delete()
@app.task()
def remove_old_client_ids(days=90):
"""Remove old Client IDs which are used for short periods for fraud prevention."""
old_cutoff = get_ad_day() - datetime.timedelta(days=days)
while True:
offer_ids = Offer.objects.filter(
date__lt=old_cutoff, client_id__isnull=False
).values("pk")[:1000]
offers_changed = Offer.objects.filter(pk__in=offer_ids).update(client_id=None)
if not offers_changed:
break
@app.task()
def calculate_publisher_ctrs(days=7):
"""Calculate average CTRs for paid ads on a publisher for the last X days."""
sample_cutoff = get_ad_day() - datetime.timedelta(days=days)
for publisher in Publisher.objects.filter(allow_paid_campaigns=True):
queryset = AdImpression.objects.filter(
date__gte=sample_cutoff,
publisher=publisher,
advertisement__flight__campaign__campaign_type=PAID_CAMPAIGN,
)
report = PublisherReport(queryset)
report.generate()
if report.total["views"] > 0:
publisher.sampled_ctr = report.total["ctr"]
publisher.save()
@app.task()
def calculate_ad_ctrs(days=7, min_views=1_000):
"""Calculate sampled CTRs for all active ads for the last X days."""
sample_cutoff = get_ad_day() - datetime.timedelta(days=days)
for ad in Advertisement.objects.filter(live=True, flight__live=True):
result = AdImpression.objects.filter(
date__gte=sample_cutoff,
advertisement=ad,
).aggregate(
total_views=Sum("views"),
total_clicks=Sum("clicks"),
)
# These can be `None` if there are NO results in the timeframe
total_views = result["total_views"] or 0
total_clicks = result["total_clicks"] or 0
if total_views >= min_views:
ad.sampled_ctr = calculate_ctr(total_clicks, total_views)
ad.save()
@app.task()
def refresh_flight_denormalized_totals():
"""
Refresh denormalized total_views and total_clicks fields for all live flights.
This task should be run periodically (e.g., every 5-10 minutes) to update
the denormalized fields without causing lock contention on the Flight table.
"""
start_time = timezone.now()
log.info("Starting refresh of denormalized totals for live flights")
# Only refresh active flights to avoid unnecessary work
flights = Flight.objects.filter(live=True).exclude(
campaign__campaign_type=PUBLISHER_HOUSE_CAMPAIGN
)
total_flights = flights.count()
for flight in flights:
flight.refresh_denormalized_totals()
# Update cache with last successful run timestamp
cache.set(
"flight_totals_last_refresh",
timezone.now().isoformat(),
timeout=None, # Never expire
)
duration = (timezone.now() - start_time).total_seconds()
log.info(
"Finished refreshing denormalized totals: %d flights, took %.2fs",
total_flights,
duration,
)
@app.task()
def notify_on_ad_image_change(advertisement_id):
ad = Advertisement.objects.filter(id=advertisement_id).first()
if not ad or not ad.image:
log.warning("Invalid ad passed to 'notify_on_ad_image_change'")
return
ad_url = generate_absolute_url(ad.get_absolute_url())
message = f"{ad.name} ({ad_url}) image uploaded: {ad.image.url}"
log.info(message)
slack_message(
"adserver/slack/generic-message.slack",
{"text": message},
)
@app.task()
def notify_of_first_flight_launched():
"""Notify when an advertiser's first ever flight launches."""
start_date = get_ad_day().date() - datetime.timedelta(days=1)
site = get_current_site(request=None)
# Get advertisers who launched today and
# exclude advertisers with flights launched before today
advertisers_launched_today = Flight.objects.filter(
live=True,
start_date=start_date,
).values("campaign__advertiser")
advertisers_launched_before_today = Flight.objects.filter(
start_date__lt=start_date,
).values("campaign__advertiser")
for advertiser in Advertiser.objects.filter(
pk__in=advertisers_launched_today
).exclude(pk__in=advertisers_launched_before_today):
log.debug(