Parcourir la source

Merge branch 'offer-subscription-count' of opi/coin into master

jocelyn il y a 8 ans
Parent
commit
900bc2fc47
3 fichiers modifiés avec 60 ajouts et 4 suppressions
  1. 24 1
      coin/offers/models.py
  2. 2 1
      coin/offers/urls.py
  3. 34 2
      coin/offers/views.py

+ 24 - 1
coin/offers/models.py

@@ -5,7 +5,7 @@ import datetime
 
 from django.conf import settings
 from django.db import models
-from django.db.models import Q
+from django.db.models import Count, Q
 from django.core.validators import MinValueValidator
 
 
@@ -79,6 +79,27 @@ class Offer(models.Model):
         verbose_name = 'offre'
 
 
+class OfferSubscriptionQuerySet(models.QuerySet):
+    def running(self, at_date=None):
+        """ Only the running contracts at a given date.
+
+        Running mean already started and not stopped yet
+        """
+
+        if at_date is None:
+            at_date = datetime.date.today()
+
+        return self.filter(Q(subscription_date__lte=at_date) &
+                           (Q(resign_date__gt=at_date) |
+                            Q(resign_date__isnull=True)))
+
+    def offer_summary(self):
+        """ Agregates as a count of subscriptions per offer
+        """
+        return self.values('offer__name', 'offer__reference').annotate(
+            num_subscriptions=Count('offer'))
+
+
 class OfferSubscription(models.Model):
     """Only contains administrative details about a subscription, not
     technical.  Nothing here should end up into the LDAP backend.
@@ -107,6 +128,8 @@ class OfferSubscription(models.Model):
     member = models.ForeignKey('members.Member', verbose_name='membre')
     offer = models.ForeignKey('Offer', verbose_name='offre')
 
+    objects = OfferSubscriptionQuerySet().as_manager()
+
     def get_subscription_reference(self):
         return settings.SUBSCRIPTION_REFERENCE.format(subscription=self)
     get_subscription_reference.short_description = 'Référence'

+ 2 - 1
coin/offers/urls.py

@@ -2,10 +2,11 @@
 from __future__ import unicode_literals
 
 from django.conf.urls import patterns, url
-from coin.offers.views import ConfigurationRedirectView
+from coin.offers.views import ConfigurationRedirectView, subscription_count_json
 
 urlpatterns = patterns(
     '',
     # Redirect to the appropriate configuration backend.
     url(r'^configuration/(?P<id>.+)$', ConfigurationRedirectView.as_view(), name="configuration-redirect"),
+    url(r'^api/v1/count$', subscription_count_json),
 )

+ 34 - 2
coin/offers/views.py

@@ -1,12 +1,17 @@
 # -*- coding: utf-8 -*-
 from __future__ import unicode_literals
 
+import datetime
+import json
+
+from django.db.models import Q, Count
 from django.views.generic.base import RedirectView
 from django.shortcuts import get_object_or_404
 from django.core.urlresolvers import reverse
+from django.http import JsonResponse, HttpResponseServerError
+# from django.views.decorators.cache import cache_control
 
-from coin.offers.models import OfferSubscription
-
+from coin.offers.models import Offer, OfferSubscription
 
 class ConfigurationRedirectView(RedirectView):
     """Redirects to the appropriate view for the configuration backend of the
@@ -19,3 +24,30 @@ class ConfigurationRedirectView(RedirectView):
                                          member=self.request.user)
         return reverse(subscription.configuration.url_namespace + ':' + subscription.configuration.backend_name,
                        args=[subscription.configuration.pk])
+
+
+# @cache_control(max_age=7200)
+def subscription_count_json(request):
+    output = []
+
+    # Get date form url, or set default
+    date = request.GET.get('date', datetime.date.today())
+
+    # Validate date type
+    if not isinstance(date, datetime.date):
+        try:
+            datetime.datetime.strptime(date, '%Y-%m-%d')
+        except ValueError, TypeError:
+            return HttpResponseServerError("Incorrect date format, should be YYYY-MM-DD")
+
+    # Get current offer subscription
+    offersubscriptions = list(OfferSubscription.objects.running(date).offer_summary())
+    for offersub in offersubscriptions:
+        output.append({
+            'reference' : offersub['offer__reference'],
+            'name' : offersub['offer__name'],
+            'subscriptions_count' : offersub['num_subscriptions']
+        })
+
+    # Return JSON
+    return JsonResponse(output, safe=False)