diff --git a/lemarche/siaes/models.py b/lemarche/siaes/models.py index e1f6eca0e..40f0f8b4a 100644 --- a/lemarche/siaes/models.py +++ b/lemarche/siaes/models.py @@ -1,3 +1,4 @@ +from datetime import timedelta from uuid import uuid4 from django.conf import settings @@ -496,37 +497,63 @@ def filter_with_tender_tendersiae_status(self, tender, tendersiae_status=None): return qs.distinct() - def with_tender_stats(self): + def with_tender_stats(self, days=0): """ - Enrich each Siae with stats on their linked Tender + Enrich each Siae with stats on their linked Tender. + Optionally, limit the stats to the last `days` days. """ + date_limit = timezone.now() - timedelta(days=days) if days > 0 else None + date_filter = Q() if date_limit is None else Q(tendersiae__email_send_date__gte=date_limit) + return self.annotate( - tender_count_annotated=Count("tenders", distinct=True), + tender_count_annotated=Count("tenders", distinct=True), # noqa tender_email_send_count_annotated=Sum( - Case(When(tendersiae__email_send_date__isnull=False, then=1), default=0, output_field=IntegerField()) + Case( + When(Q(tendersiae__email_send_date__isnull=False) & date_filter, then=1), + default=0, + output_field=IntegerField(), + ) ), tender_email_link_click_count_annotated=Sum( Case( - When(tendersiae__email_link_click_date__isnull=False, then=1), + When( + Q(tendersiae__email_link_click_date__isnull=False) + & (Q(tendersiae__email_link_click_date__gte=date_limit) if date_limit else Q()), + then=1, + ), default=0, output_field=IntegerField(), ) ), tender_detail_display_count_annotated=Sum( Case( - When(tendersiae__detail_display_date__isnull=False, then=1), default=0, output_field=IntegerField() + When( + Q(tendersiae__detail_display_date__isnull=False) + & (Q(tendersiae__detail_display_date__gte=date_limit) if date_limit else Q()), + then=1, + ), + default=0, + output_field=IntegerField(), ) ), tender_detail_contact_click_count_annotated=Sum( Case( - When(tendersiae__detail_contact_click_date__isnull=False, then=1), + When( + Q(tendersiae__detail_contact_click_date__isnull=False) + & (Q(tendersiae__detail_contact_click_date__gte=date_limit) if date_limit else Q()), + then=1, + ), default=0, output_field=IntegerField(), ) ), tender_detail_not_interested_count_annotated=Sum( Case( - When(tendersiae__detail_not_interested_click_date__isnull=False, then=1), + When( + Q(tendersiae__detail_not_interested_click_date__isnull=False) + & (Q(tendersiae__detail_not_interested_click_date__gte=date_limit) if date_limit else Q()), + then=1, + ), default=0, output_field=IntegerField(), )