|
1 | 1 | import re
|
2 | 2 |
|
3 | 3 | import django.db.models
|
| 4 | +import django.shortcuts |
4 | 5 | import rest_framework.generics
|
5 | 6 | import rest_framework.permissions
|
6 | 7 | import rest_framework.response
|
7 | 8 | import rest_framework.status
|
| 9 | +import rest_framework.views |
8 | 10 | import rest_framework_simplejwt.views
|
9 | 11 |
|
10 | 12 | import business.models
|
|
13 | 15 | import business.serializers
|
14 | 16 | import business.utils.auth
|
15 | 17 | import business.utils.tokens
|
| 18 | +import user.models |
16 | 19 |
|
17 | 20 |
|
18 | 21 | class CompanySignUpView(rest_framework.generics.CreateAPIView):
|
@@ -153,3 +156,60 @@ class CompanyPromoDetailView(rest_framework.generics.RetrieveUpdateAPIView):
|
153 | 156 | # Use an enriched base queryset without pre-filtering by company,
|
154 | 157 | # so that ownership mismatches raise 403 Forbidden (not 404 Not Found).
|
155 | 158 | queryset = business.models.Promo.objects.with_related()
|
| 159 | + |
| 160 | + |
| 161 | +class CompanyPromoStatAPIView(rest_framework.views.APIView): |
| 162 | + """ |
| 163 | + API endpoint for retrieving promo code statistics. |
| 164 | + """ |
| 165 | + |
| 166 | + permission_classes = [ |
| 167 | + rest_framework.permissions.IsAuthenticated, |
| 168 | + business.permissions.IsPromoOwner, |
| 169 | + ] |
| 170 | + |
| 171 | + def get(self, request, id, *args, **kwargs): |
| 172 | + promo = django.shortcuts.get_object_or_404( |
| 173 | + business.models.Promo, |
| 174 | + id=id, |
| 175 | + ) |
| 176 | + |
| 177 | + self.check_object_permissions(self.request, promo) |
| 178 | + |
| 179 | + total_activations = promo.activations_history.count() |
| 180 | + |
| 181 | + countries_stats = ( |
| 182 | + user.models.PromoActivationHistory.objects.filter(promo=promo) |
| 183 | + .values( |
| 184 | + 'user__other__country', |
| 185 | + ) |
| 186 | + .annotate( |
| 187 | + activations_count=django.db.models.Count('id'), |
| 188 | + ) |
| 189 | + .order_by( |
| 190 | + 'user__other__country', |
| 191 | + ) |
| 192 | + ) |
| 193 | + |
| 194 | + countries_data = [ |
| 195 | + { |
| 196 | + 'country': item['user__other__country'], |
| 197 | + 'activations_count': item['activations_count'], |
| 198 | + } |
| 199 | + for item in countries_stats |
| 200 | + ] |
| 201 | + |
| 202 | + response_data = { |
| 203 | + 'activations_count': total_activations, |
| 204 | + 'countries': countries_data, |
| 205 | + } |
| 206 | + |
| 207 | + serializer = business.serializers.PromoStatSerializer( |
| 208 | + data=response_data, |
| 209 | + ) |
| 210 | + serializer.is_valid(raise_exception=True) |
| 211 | + |
| 212 | + return rest_framework.response.Response( |
| 213 | + serializer.validated_data, |
| 214 | + status=rest_framework.status.HTTP_200_OK, |
| 215 | + ) |
0 commit comments