django-cfg 1.2.29__py3-none-any.whl → 1.3.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- django_cfg/__init__.py +1 -1
- django_cfg/apps/api/health/views.py +4 -2
- django_cfg/apps/knowbase/config/settings.py +16 -15
- django_cfg/apps/payments/README.md +326 -0
- django_cfg/apps/payments/admin/__init__.py +20 -9
- django_cfg/apps/payments/admin/api_keys_admin.py +521 -237
- django_cfg/apps/payments/admin/balance_admin.py +592 -297
- django_cfg/apps/payments/admin/currencies_admin.py +600 -108
- django_cfg/apps/payments/admin/filters.py +306 -199
- django_cfg/apps/payments/admin/payments_admin.py +470 -64
- django_cfg/apps/payments/admin/subscriptions_admin.py +578 -128
- django_cfg/apps/payments/admin_interface/__init__.py +18 -0
- django_cfg/apps/payments/admin_interface/templates/payments/base.html +162 -0
- django_cfg/apps/payments/admin_interface/templates/payments/components/dev_tool_card.html +38 -0
- django_cfg/apps/payments/admin_interface/templates/payments/components/loading_spinner.html +16 -0
- django_cfg/apps/payments/admin_interface/templates/payments/components/notification.html +27 -0
- django_cfg/apps/payments/admin_interface/templates/payments/components/provider_card.html +86 -0
- django_cfg/apps/payments/admin_interface/templates/payments/components/status_card.html +39 -0
- django_cfg/apps/payments/admin_interface/templates/payments/currency_converter.html +382 -0
- django_cfg/apps/payments/admin_interface/templates/payments/payment_dashboard.html +300 -0
- django_cfg/apps/payments/admin_interface/templates/payments/payment_form.html +303 -0
- django_cfg/apps/payments/admin_interface/templates/payments/payment_list.html +382 -0
- django_cfg/apps/payments/admin_interface/templates/payments/payment_status.html +500 -0
- django_cfg/apps/payments/admin_interface/templates/payments/webhook_dashboard.html +594 -0
- django_cfg/apps/payments/admin_interface/views/__init__.py +23 -0
- django_cfg/apps/payments/admin_interface/views/payment_views.py +259 -0
- django_cfg/apps/payments/admin_interface/views/webhook_dashboard.py +37 -0
- django_cfg/apps/payments/apps.py +34 -9
- django_cfg/apps/payments/config/__init__.py +28 -51
- django_cfg/apps/payments/config/constance/__init__.py +22 -0
- django_cfg/apps/payments/config/constance/config_service.py +123 -0
- django_cfg/apps/payments/config/constance/fields.py +69 -0
- django_cfg/apps/payments/config/constance/settings.py +160 -0
- django_cfg/apps/payments/config/django_cfg_integration.py +202 -0
- django_cfg/apps/payments/config/helpers.py +130 -0
- django_cfg/apps/payments/management/__init__.py +1 -3
- django_cfg/apps/payments/management/commands/__init__.py +1 -3
- django_cfg/apps/payments/management/commands/manage_currencies.py +381 -0
- django_cfg/apps/payments/management/commands/manage_providers.py +408 -0
- django_cfg/apps/payments/middleware/__init__.py +3 -1
- django_cfg/apps/payments/middleware/api_access.py +329 -222
- django_cfg/apps/payments/middleware/rate_limiting.py +343 -163
- django_cfg/apps/payments/middleware/usage_tracking.py +250 -238
- django_cfg/apps/payments/migrations/0001_initial.py +708 -536
- django_cfg/apps/payments/models/__init__.py +16 -20
- django_cfg/apps/payments/models/api_keys.py +121 -43
- django_cfg/apps/payments/models/balance.py +150 -115
- django_cfg/apps/payments/models/base.py +68 -15
- django_cfg/apps/payments/models/currencies.py +207 -67
- django_cfg/apps/payments/models/managers/__init__.py +44 -0
- django_cfg/apps/payments/models/managers/api_key_managers.py +329 -0
- django_cfg/apps/payments/models/managers/balance_managers.py +599 -0
- django_cfg/apps/payments/models/managers/currency_managers.py +385 -0
- django_cfg/apps/payments/models/managers/payment_managers.py +511 -0
- django_cfg/apps/payments/models/managers/subscription_managers.py +641 -0
- django_cfg/apps/payments/models/payments.py +235 -284
- django_cfg/apps/payments/models/subscriptions.py +257 -177
- django_cfg/apps/payments/models/tariffs.py +147 -40
- django_cfg/apps/payments/services/__init__.py +209 -56
- django_cfg/apps/payments/services/cache/__init__.py +6 -6
- django_cfg/apps/payments/services/cache/{simple_cache.py → cache_service.py} +112 -12
- django_cfg/apps/payments/services/core/__init__.py +10 -6
- django_cfg/apps/payments/services/core/balance_service.py +435 -360
- django_cfg/apps/payments/services/core/base.py +166 -0
- django_cfg/apps/payments/services/core/currency_service.py +478 -0
- django_cfg/apps/payments/services/core/payment_service.py +344 -468
- django_cfg/apps/payments/services/core/subscription_service.py +425 -484
- django_cfg/apps/payments/services/core/webhook_service.py +410 -0
- django_cfg/apps/payments/services/integrations/__init__.py +29 -0
- django_cfg/apps/payments/services/integrations/ngrok_service.py +47 -0
- django_cfg/apps/payments/services/integrations/providers_config.py +107 -0
- django_cfg/apps/payments/services/providers/__init__.py +9 -14
- django_cfg/apps/payments/services/providers/base.py +232 -71
- django_cfg/apps/payments/services/providers/nowpayments.py +404 -219
- django_cfg/apps/payments/services/providers/registry.py +429 -80
- django_cfg/apps/payments/services/types/__init__.py +78 -0
- django_cfg/apps/payments/services/types/data.py +177 -0
- django_cfg/apps/payments/services/types/requests.py +150 -0
- django_cfg/apps/payments/services/types/responses.py +156 -0
- django_cfg/apps/payments/services/types/webhooks.py +232 -0
- django_cfg/apps/payments/signals/__init__.py +33 -8
- django_cfg/apps/payments/signals/api_key_signals.py +211 -130
- django_cfg/apps/payments/signals/balance_signals.py +174 -0
- django_cfg/apps/payments/signals/payment_signals.py +129 -98
- django_cfg/apps/payments/signals/subscription_signals.py +195 -143
- django_cfg/apps/payments/static/payments/css/components.css +380 -0
- django_cfg/apps/payments/static/payments/css/dashboard.css +188 -0
- django_cfg/apps/payments/static/payments/js/components.js +545 -0
- django_cfg/apps/payments/static/payments/js/utils.js +412 -0
- django_cfg/apps/payments/templatetags/__init__.py +1 -1
- django_cfg/apps/payments/templatetags/payment_tags.py +466 -0
- django_cfg/apps/payments/urls.py +46 -47
- django_cfg/apps/payments/urls_admin.py +49 -0
- django_cfg/apps/payments/views/api/__init__.py +101 -0
- django_cfg/apps/payments/views/api/api_keys.py +387 -0
- django_cfg/apps/payments/views/api/balances.py +381 -0
- django_cfg/apps/payments/views/api/base.py +298 -0
- django_cfg/apps/payments/views/api/currencies.py +402 -0
- django_cfg/apps/payments/views/api/payments.py +415 -0
- django_cfg/apps/payments/views/api/subscriptions.py +475 -0
- django_cfg/apps/payments/views/api/webhooks.py +476 -0
- django_cfg/apps/payments/views/serializers/__init__.py +99 -0
- django_cfg/apps/payments/views/serializers/api_keys.py +424 -0
- django_cfg/apps/payments/views/serializers/balances.py +300 -0
- django_cfg/apps/payments/views/serializers/currencies.py +335 -0
- django_cfg/apps/payments/views/serializers/payments.py +387 -0
- django_cfg/apps/payments/views/serializers/subscriptions.py +429 -0
- django_cfg/apps/payments/views/serializers/webhooks.py +137 -0
- django_cfg/apps/tasks/urls.py +0 -2
- django_cfg/apps/tasks/urls_admin.py +14 -0
- django_cfg/apps/urls.py +4 -4
- django_cfg/config.py +1 -1
- django_cfg/core/config.py +75 -4
- django_cfg/core/generation.py +25 -4
- django_cfg/core/integration/README.md +363 -0
- django_cfg/core/integration/__init__.py +47 -0
- django_cfg/core/integration/commands_collector.py +239 -0
- django_cfg/core/integration/display/__init__.py +15 -0
- django_cfg/core/integration/display/base.py +157 -0
- django_cfg/core/integration/display/ngrok.py +164 -0
- django_cfg/core/integration/display/startup.py +815 -0
- django_cfg/core/integration/url_integration.py +123 -0
- django_cfg/core/integration/version_checker.py +160 -0
- django_cfg/management/commands/auto_generate.py +4 -0
- django_cfg/management/commands/check_settings.py +6 -0
- django_cfg/management/commands/clear_constance.py +5 -2
- django_cfg/management/commands/create_token.py +6 -0
- django_cfg/management/commands/list_urls.py +6 -0
- django_cfg/management/commands/migrate_all.py +6 -0
- django_cfg/management/commands/migrator.py +3 -0
- django_cfg/management/commands/rundramatiq.py +6 -0
- django_cfg/management/commands/runserver_ngrok.py +51 -29
- django_cfg/management/commands/script.py +6 -0
- django_cfg/management/commands/show_config.py +12 -2
- django_cfg/management/commands/show_urls.py +4 -0
- django_cfg/management/commands/superuser.py +6 -0
- django_cfg/management/commands/task_clear.py +4 -1
- django_cfg/management/commands/task_status.py +3 -1
- django_cfg/management/commands/test_email.py +3 -0
- django_cfg/management/commands/test_telegram.py +6 -0
- django_cfg/management/commands/test_twilio.py +6 -0
- django_cfg/management/commands/tree.py +6 -0
- django_cfg/management/commands/validate_config.py +155 -149
- django_cfg/models/constance.py +31 -11
- django_cfg/models/payments.py +175 -498
- django_cfg/modules/django_currency/__init__.py +16 -11
- django_cfg/modules/django_currency/clients/__init__.py +4 -4
- django_cfg/modules/django_currency/clients/coinpaprika_client.py +289 -0
- django_cfg/modules/django_currency/clients/yahoo_client.py +157 -0
- django_cfg/modules/django_currency/core/__init__.py +1 -7
- django_cfg/modules/django_currency/core/converter.py +18 -23
- django_cfg/modules/django_currency/core/models.py +122 -11
- django_cfg/modules/django_currency/database/__init__.py +4 -4
- django_cfg/modules/django_currency/database/database_loader.py +190 -309
- django_cfg/modules/django_logger.py +160 -146
- django_cfg/modules/django_unfold/dashboard.py +65 -12
- django_cfg/registry/core.py +1 -0
- django_cfg/template_archive/django_sample.zip +0 -0
- django_cfg/templates/admin/components/action_grid.html +9 -9
- django_cfg/templates/admin/components/metric_card.html +5 -5
- django_cfg/templates/admin/components/status_badge.html +2 -2
- django_cfg/templates/admin/layouts/dashboard_with_tabs.html +152 -24
- django_cfg/templates/admin/snippets/components/quick_actions.html +3 -3
- django_cfg/templates/admin/snippets/components/system_health.html +1 -1
- django_cfg/templates/admin/snippets/tabs/overview_tab.html +49 -52
- django_cfg/utils/smart_defaults.py +222 -571
- django_cfg/utils/toolkit.py +51 -11
- {django_cfg-1.2.29.dist-info → django_cfg-1.3.1.dist-info}/METADATA +5 -4
- {django_cfg-1.2.29.dist-info → django_cfg-1.3.1.dist-info}/RECORD +172 -182
- django_cfg/apps/payments/__init__.py +0 -8
- django_cfg/apps/payments/admin/tariffs_admin.py +0 -199
- django_cfg/apps/payments/config/module.py +0 -70
- django_cfg/apps/payments/config/providers.py +0 -105
- django_cfg/apps/payments/config/settings.py +0 -96
- django_cfg/apps/payments/config/utils.py +0 -52
- django_cfg/apps/payments/decorators.py +0 -291
- django_cfg/apps/payments/management/commands/README.md +0 -178
- django_cfg/apps/payments/management/commands/currency_stats.py +0 -323
- django_cfg/apps/payments/management/commands/populate_currencies.py +0 -246
- django_cfg/apps/payments/management/commands/update_currencies.py +0 -336
- django_cfg/apps/payments/managers/__init__.py +0 -22
- django_cfg/apps/payments/managers/api_key_manager.py +0 -35
- django_cfg/apps/payments/managers/balance_manager.py +0 -361
- django_cfg/apps/payments/managers/currency_manager.py +0 -83
- django_cfg/apps/payments/managers/payment_manager.py +0 -44
- django_cfg/apps/payments/managers/subscription_manager.py +0 -37
- django_cfg/apps/payments/managers/tariff_manager.py +0 -29
- django_cfg/apps/payments/models/events.py +0 -73
- django_cfg/apps/payments/serializers/__init__.py +0 -56
- django_cfg/apps/payments/serializers/api_keys.py +0 -51
- django_cfg/apps/payments/serializers/balance.py +0 -59
- django_cfg/apps/payments/serializers/currencies.py +0 -55
- django_cfg/apps/payments/serializers/payments.py +0 -62
- django_cfg/apps/payments/serializers/subscriptions.py +0 -71
- django_cfg/apps/payments/serializers/tariffs.py +0 -56
- django_cfg/apps/payments/services/billing/__init__.py +0 -8
- django_cfg/apps/payments/services/cache/base.py +0 -30
- django_cfg/apps/payments/services/core/fallback_service.py +0 -432
- django_cfg/apps/payments/services/internal_types.py +0 -297
- django_cfg/apps/payments/services/middleware/__init__.py +0 -8
- django_cfg/apps/payments/services/monitoring/__init__.py +0 -22
- django_cfg/apps/payments/services/monitoring/api_schemas.py +0 -222
- django_cfg/apps/payments/services/monitoring/provider_health.py +0 -372
- django_cfg/apps/payments/services/providers/cryptapi.py +0 -273
- django_cfg/apps/payments/services/providers/cryptomus.py +0 -311
- django_cfg/apps/payments/services/security/__init__.py +0 -34
- django_cfg/apps/payments/services/security/error_handler.py +0 -637
- django_cfg/apps/payments/services/security/payment_notifications.py +0 -342
- django_cfg/apps/payments/services/security/webhook_validator.py +0 -475
- django_cfg/apps/payments/services/validators/__init__.py +0 -8
- django_cfg/apps/payments/static/payments/css/payments.css +0 -340
- django_cfg/apps/payments/static/payments/js/notifications.js +0 -202
- django_cfg/apps/payments/static/payments/js/payment-utils.js +0 -318
- django_cfg/apps/payments/static/payments/js/theme.js +0 -86
- django_cfg/apps/payments/tasks/__init__.py +0 -12
- django_cfg/apps/payments/tasks/webhook_processing.py +0 -177
- django_cfg/apps/payments/templates/payments/base.html +0 -182
- django_cfg/apps/payments/templates/payments/components/payment_card.html +0 -201
- django_cfg/apps/payments/templates/payments/components/payment_qr_code.html +0 -109
- django_cfg/apps/payments/templates/payments/components/progress_bar.html +0 -36
- django_cfg/apps/payments/templates/payments/components/provider_stats.html +0 -40
- django_cfg/apps/payments/templates/payments/components/status_badge.html +0 -27
- django_cfg/apps/payments/templates/payments/components/status_overview.html +0 -144
- django_cfg/apps/payments/templates/payments/dashboard.html +0 -346
- django_cfg/apps/payments/templatetags/payments_tags.py +0 -315
- django_cfg/apps/payments/urls_templates.py +0 -52
- django_cfg/apps/payments/utils/__init__.py +0 -45
- django_cfg/apps/payments/utils/billing_utils.py +0 -342
- django_cfg/apps/payments/utils/config_utils.py +0 -245
- django_cfg/apps/payments/utils/middleware_utils.py +0 -228
- django_cfg/apps/payments/utils/validation_utils.py +0 -94
- django_cfg/apps/payments/views/__init__.py +0 -62
- django_cfg/apps/payments/views/api_key_views.py +0 -164
- django_cfg/apps/payments/views/balance_views.py +0 -75
- django_cfg/apps/payments/views/currency_views.py +0 -111
- django_cfg/apps/payments/views/payment_views.py +0 -149
- django_cfg/apps/payments/views/subscription_views.py +0 -135
- django_cfg/apps/payments/views/tariff_views.py +0 -131
- django_cfg/apps/payments/views/templates/__init__.py +0 -25
- django_cfg/apps/payments/views/templates/ajax.py +0 -312
- django_cfg/apps/payments/views/templates/base.py +0 -204
- django_cfg/apps/payments/views/templates/dashboard.py +0 -60
- django_cfg/apps/payments/views/templates/payment_detail.py +0 -102
- django_cfg/apps/payments/views/templates/payment_management.py +0 -164
- django_cfg/apps/payments/views/templates/qr_code.py +0 -174
- django_cfg/apps/payments/views/templates/stats.py +0 -240
- django_cfg/apps/payments/views/templates/utils.py +0 -181
- django_cfg/apps/payments/views/webhook_views.py +0 -266
- django_cfg/apps/payments/viewsets.py +0 -65
- django_cfg/core/integration.py +0 -160
- django_cfg/modules/django_currency/clients/coingecko_client.py +0 -257
- django_cfg/modules/django_currency/clients/yfinance_client.py +0 -246
- django_cfg/template_archive/.gitignore +0 -1
- django_cfg/template_archive/__init__.py +0 -0
- django_cfg/urls.py +0 -33
- {django_cfg-1.2.29.dist-info → django_cfg-1.3.1.dist-info}/WHEEL +0 -0
- {django_cfg-1.2.29.dist-info → django_cfg-1.3.1.dist-info}/entry_points.txt +0 -0
- {django_cfg-1.2.29.dist-info → django_cfg-1.3.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,475 @@
|
|
1
|
+
"""
|
2
|
+
Subscription ViewSets for the Universal Payment System v2.0.
|
3
|
+
|
4
|
+
DRF ViewSets for subscription management with service integration.
|
5
|
+
"""
|
6
|
+
|
7
|
+
from rest_framework import viewsets, permissions, status
|
8
|
+
from rest_framework.decorators import action
|
9
|
+
from rest_framework.response import Response
|
10
|
+
from django_filters.rest_framework import DjangoFilterBackend
|
11
|
+
from django.contrib.auth import get_user_model
|
12
|
+
from django.db import models
|
13
|
+
from django.utils import timezone
|
14
|
+
|
15
|
+
from .base import PaymentBaseViewSet, NestedPaymentViewSet, ReadOnlyPaymentViewSet
|
16
|
+
from ...models import Subscription, EndpointGroup, Tariff
|
17
|
+
from ...services import get_subscription_service
|
18
|
+
from ..serializers.subscriptions import (
|
19
|
+
SubscriptionSerializer,
|
20
|
+
SubscriptionCreateSerializer,
|
21
|
+
SubscriptionListSerializer,
|
22
|
+
SubscriptionUpdateSerializer,
|
23
|
+
SubscriptionUsageSerializer,
|
24
|
+
SubscriptionStatsSerializer,
|
25
|
+
EndpointGroupSerializer,
|
26
|
+
TariffSerializer,
|
27
|
+
)
|
28
|
+
from django_cfg.modules.django_logger import get_logger
|
29
|
+
|
30
|
+
User = get_user_model()
|
31
|
+
logger = get_logger("subscription_viewsets")
|
32
|
+
|
33
|
+
|
34
|
+
class SubscriptionViewSet(PaymentBaseViewSet):
|
35
|
+
"""
|
36
|
+
Global subscription ViewSet: /api/subscriptions/
|
37
|
+
|
38
|
+
Provides admin-level access to all subscriptions with filtering and stats.
|
39
|
+
"""
|
40
|
+
|
41
|
+
queryset = Subscription.objects.all()
|
42
|
+
serializer_class = SubscriptionSerializer
|
43
|
+
permission_classes = [permissions.IsAdminUser] # Admin only for global access
|
44
|
+
filterset_fields = ['status', 'tier', 'tariff', 'endpoint_group', 'user']
|
45
|
+
search_fields = ['user__username', 'user__email', 'tariff__name']
|
46
|
+
ordering_fields = ['created_at', 'updated_at', 'expires_at', 'total_requests']
|
47
|
+
|
48
|
+
serializer_classes = {
|
49
|
+
'list': SubscriptionListSerializer,
|
50
|
+
'create': SubscriptionCreateSerializer,
|
51
|
+
'retrieve': SubscriptionSerializer,
|
52
|
+
'update': SubscriptionSerializer,
|
53
|
+
'partial_update': SubscriptionSerializer,
|
54
|
+
}
|
55
|
+
|
56
|
+
def get_queryset(self):
|
57
|
+
"""Optimized queryset with related objects."""
|
58
|
+
return super().get_queryset().select_related(
|
59
|
+
'user', 'tariff', 'endpoint_group'
|
60
|
+
).prefetch_related(
|
61
|
+
'tariff__endpoint_groups'
|
62
|
+
)
|
63
|
+
|
64
|
+
@action(detail=True, methods=['post'])
|
65
|
+
def update_status(self, request, pk=None):
|
66
|
+
"""
|
67
|
+
Update subscription status.
|
68
|
+
|
69
|
+
POST /api/subscriptions/{id}/update_status/
|
70
|
+
"""
|
71
|
+
subscription = self.get_object()
|
72
|
+
|
73
|
+
serializer = SubscriptionUpdateSerializer(
|
74
|
+
data=request.data,
|
75
|
+
context={
|
76
|
+
**self.get_serializer_context(),
|
77
|
+
'subscription_id': str(subscription.id)
|
78
|
+
}
|
79
|
+
)
|
80
|
+
|
81
|
+
if serializer.is_valid():
|
82
|
+
result = serializer.save()
|
83
|
+
return Response(result)
|
84
|
+
|
85
|
+
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
86
|
+
|
87
|
+
@action(detail=True, methods=['post'])
|
88
|
+
def increment_usage(self, request, pk=None):
|
89
|
+
"""
|
90
|
+
Increment subscription usage.
|
91
|
+
|
92
|
+
POST /api/subscriptions/{id}/increment_usage/
|
93
|
+
"""
|
94
|
+
subscription = self.get_object()
|
95
|
+
|
96
|
+
serializer = SubscriptionUsageSerializer(
|
97
|
+
data=request.data,
|
98
|
+
context={
|
99
|
+
**self.get_serializer_context(),
|
100
|
+
'subscription_id': str(subscription.id)
|
101
|
+
}
|
102
|
+
)
|
103
|
+
|
104
|
+
if serializer.is_valid():
|
105
|
+
result = serializer.save()
|
106
|
+
return Response(result)
|
107
|
+
|
108
|
+
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
109
|
+
|
110
|
+
@action(detail=False, methods=['get'])
|
111
|
+
def analytics(self, request):
|
112
|
+
"""
|
113
|
+
Get subscription analytics.
|
114
|
+
|
115
|
+
GET /api/subscriptions/analytics/?days=30
|
116
|
+
"""
|
117
|
+
serializer = SubscriptionStatsSerializer(data=request.query_params)
|
118
|
+
|
119
|
+
if serializer.is_valid():
|
120
|
+
result = serializer.save()
|
121
|
+
return Response(result)
|
122
|
+
|
123
|
+
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
124
|
+
|
125
|
+
@action(detail=False, methods=['get'])
|
126
|
+
def by_status(self, request):
|
127
|
+
"""
|
128
|
+
Get subscriptions grouped by status.
|
129
|
+
|
130
|
+
GET /api/subscriptions/by_status/
|
131
|
+
"""
|
132
|
+
try:
|
133
|
+
queryset = self.filter_queryset(self.get_queryset())
|
134
|
+
|
135
|
+
status_stats = {}
|
136
|
+
for status_choice in Subscription.SubscriptionStatus.choices:
|
137
|
+
status_code = status_choice[0]
|
138
|
+
status_name = status_choice[1]
|
139
|
+
|
140
|
+
status_subscriptions = queryset.filter(status=status_code)
|
141
|
+
|
142
|
+
status_stats[status_code] = {
|
143
|
+
'name': status_name,
|
144
|
+
'total_subscriptions': status_subscriptions.count(),
|
145
|
+
'total_requests': status_subscriptions.aggregate(
|
146
|
+
total=models.Sum('total_requests')
|
147
|
+
)['total'] or 0,
|
148
|
+
'active_users': status_subscriptions.values('user').distinct().count(),
|
149
|
+
}
|
150
|
+
|
151
|
+
return Response({
|
152
|
+
'status_stats': status_stats,
|
153
|
+
'generated_at': timezone.now().isoformat()
|
154
|
+
})
|
155
|
+
|
156
|
+
except Exception as e:
|
157
|
+
logger.error(f"Subscription status stats failed: {e}")
|
158
|
+
return Response(
|
159
|
+
{'error': f'Status stats failed: {e}'},
|
160
|
+
status=status.HTTP_500_INTERNAL_SERVER_ERROR
|
161
|
+
)
|
162
|
+
|
163
|
+
@action(detail=False, methods=['get'])
|
164
|
+
def by_tariff(self, request):
|
165
|
+
"""
|
166
|
+
Get subscriptions grouped by tariff.
|
167
|
+
|
168
|
+
GET /api/subscriptions/by_tariff/
|
169
|
+
"""
|
170
|
+
try:
|
171
|
+
queryset = self.filter_queryset(self.get_queryset())
|
172
|
+
|
173
|
+
tariff_stats = {}
|
174
|
+
for subscription in queryset.select_related('tariff'):
|
175
|
+
tariff_name = subscription.tariff.name if subscription.tariff else 'No Tariff'
|
176
|
+
tariff_id = subscription.tariff.id if subscription.tariff else None
|
177
|
+
|
178
|
+
if tariff_name not in tariff_stats:
|
179
|
+
tariff_stats[tariff_name] = {
|
180
|
+
'tariff_id': tariff_id,
|
181
|
+
'tariff_name': tariff_name,
|
182
|
+
'total_subscriptions': 0,
|
183
|
+
'active_subscriptions': 0,
|
184
|
+
'total_requests': 0,
|
185
|
+
}
|
186
|
+
|
187
|
+
tariff_stats[tariff_name]['total_subscriptions'] += 1
|
188
|
+
if subscription.is_active():
|
189
|
+
tariff_stats[tariff_name]['active_subscriptions'] += 1
|
190
|
+
tariff_stats[tariff_name]['total_requests'] += subscription.total_requests or 0
|
191
|
+
|
192
|
+
return Response({
|
193
|
+
'tariff_stats': tariff_stats,
|
194
|
+
'generated_at': timezone.now().isoformat()
|
195
|
+
})
|
196
|
+
|
197
|
+
except Exception as e:
|
198
|
+
logger.error(f"Subscription tariff stats failed: {e}")
|
199
|
+
return Response(
|
200
|
+
{'error': f'Tariff stats failed: {e}'},
|
201
|
+
status=status.HTTP_500_INTERNAL_SERVER_ERROR
|
202
|
+
)
|
203
|
+
|
204
|
+
|
205
|
+
class UserSubscriptionViewSet(NestedPaymentViewSet):
|
206
|
+
"""
|
207
|
+
User-specific subscription ViewSet: /api/users/{user_id}/subscriptions/
|
208
|
+
|
209
|
+
Provides user-scoped access to subscriptions with full CRUD operations.
|
210
|
+
"""
|
211
|
+
|
212
|
+
queryset = Subscription.objects.all()
|
213
|
+
serializer_class = SubscriptionSerializer
|
214
|
+
permission_classes = [permissions.IsAuthenticated]
|
215
|
+
filterset_fields = ['status', 'tier', 'tariff', 'endpoint_group']
|
216
|
+
search_fields = ['tariff__name']
|
217
|
+
ordering_fields = ['created_at', 'updated_at', 'expires_at']
|
218
|
+
|
219
|
+
# Nested ViewSet configuration
|
220
|
+
parent_lookup_field = 'user_pk'
|
221
|
+
parent_model_field = 'user'
|
222
|
+
|
223
|
+
serializer_classes = {
|
224
|
+
'list': SubscriptionListSerializer,
|
225
|
+
'create': SubscriptionCreateSerializer,
|
226
|
+
'retrieve': SubscriptionSerializer,
|
227
|
+
}
|
228
|
+
|
229
|
+
def get_queryset(self):
|
230
|
+
"""Filter by user and optimize queryset."""
|
231
|
+
queryset = super().get_queryset()
|
232
|
+
|
233
|
+
# Additional permission check: users can only see their own subscriptions
|
234
|
+
if not self.request.user.is_staff:
|
235
|
+
user_id = self.kwargs.get('user_pk')
|
236
|
+
if str(self.request.user.id) != str(user_id):
|
237
|
+
return queryset.none()
|
238
|
+
|
239
|
+
return queryset.select_related('tariff', 'endpoint_group')
|
240
|
+
|
241
|
+
@action(detail=True, methods=['post'])
|
242
|
+
def update_status(self, request, user_pk=None, pk=None):
|
243
|
+
"""
|
244
|
+
Update subscription status.
|
245
|
+
|
246
|
+
POST /api/users/{user_id}/subscriptions/{id}/update_status/
|
247
|
+
"""
|
248
|
+
subscription = self.get_object()
|
249
|
+
|
250
|
+
serializer = SubscriptionUpdateSerializer(
|
251
|
+
data=request.data,
|
252
|
+
context={
|
253
|
+
**self.get_serializer_context(),
|
254
|
+
'subscription_id': str(subscription.id)
|
255
|
+
}
|
256
|
+
)
|
257
|
+
|
258
|
+
if serializer.is_valid():
|
259
|
+
result = serializer.save()
|
260
|
+
return Response(result)
|
261
|
+
|
262
|
+
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
263
|
+
|
264
|
+
@action(detail=True, methods=['post'])
|
265
|
+
def increment_usage(self, request, user_pk=None, pk=None):
|
266
|
+
"""
|
267
|
+
Increment subscription usage.
|
268
|
+
|
269
|
+
POST /api/users/{user_id}/subscriptions/{id}/increment_usage/
|
270
|
+
"""
|
271
|
+
subscription = self.get_object()
|
272
|
+
|
273
|
+
serializer = SubscriptionUsageSerializer(
|
274
|
+
data=request.data,
|
275
|
+
context={
|
276
|
+
**self.get_serializer_context(),
|
277
|
+
'subscription_id': str(subscription.id)
|
278
|
+
}
|
279
|
+
)
|
280
|
+
|
281
|
+
if serializer.is_valid():
|
282
|
+
result = serializer.save()
|
283
|
+
return Response(result)
|
284
|
+
|
285
|
+
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
286
|
+
|
287
|
+
@action(detail=False, methods=['get'])
|
288
|
+
def active(self, request, user_pk=None):
|
289
|
+
"""
|
290
|
+
Get user's active subscription.
|
291
|
+
|
292
|
+
GET /api/users/{user_id}/subscriptions/active/
|
293
|
+
"""
|
294
|
+
try:
|
295
|
+
queryset = self.filter_queryset(self.get_queryset())
|
296
|
+
active_subscription = queryset.filter(
|
297
|
+
status=Subscription.SubscriptionStatus.ACTIVE
|
298
|
+
).first()
|
299
|
+
|
300
|
+
if active_subscription:
|
301
|
+
serializer = self.get_serializer(active_subscription)
|
302
|
+
return Response({
|
303
|
+
'success': True,
|
304
|
+
'subscription': serializer.data,
|
305
|
+
'message': 'Active subscription found'
|
306
|
+
})
|
307
|
+
else:
|
308
|
+
return Response({
|
309
|
+
'success': False,
|
310
|
+
'subscription': None,
|
311
|
+
'message': 'No active subscription found'
|
312
|
+
})
|
313
|
+
|
314
|
+
except Exception as e:
|
315
|
+
logger.error(f"Active subscription lookup failed: {e}")
|
316
|
+
return Response(
|
317
|
+
{'error': f'Active subscription lookup failed: {e}'},
|
318
|
+
status=status.HTTP_500_INTERNAL_SERVER_ERROR
|
319
|
+
)
|
320
|
+
|
321
|
+
@action(detail=False, methods=['get'])
|
322
|
+
def summary(self, request, user_pk=None):
|
323
|
+
"""
|
324
|
+
Get user subscription summary.
|
325
|
+
|
326
|
+
GET /api/users/{user_id}/subscriptions/summary/
|
327
|
+
"""
|
328
|
+
try:
|
329
|
+
queryset = self.filter_queryset(self.get_queryset())
|
330
|
+
|
331
|
+
summary = queryset.aggregate(
|
332
|
+
total_subscriptions=models.Count('id'),
|
333
|
+
active_subscriptions=models.Count(
|
334
|
+
'id',
|
335
|
+
filter=models.Q(status=Subscription.SubscriptionStatus.ACTIVE)
|
336
|
+
),
|
337
|
+
expired_subscriptions=models.Count(
|
338
|
+
'id',
|
339
|
+
filter=models.Q(expires_at__lt=timezone.now())
|
340
|
+
),
|
341
|
+
total_requests=models.Sum('total_requests'),
|
342
|
+
requests_used=models.Sum('requests_used'),
|
343
|
+
)
|
344
|
+
|
345
|
+
return Response({
|
346
|
+
'user_id': user_pk,
|
347
|
+
'summary': {
|
348
|
+
**summary,
|
349
|
+
'total_requests': summary['total_requests'] or 0,
|
350
|
+
'requests_used': summary['requests_used'] or 0,
|
351
|
+
'requests_remaining': (summary['total_requests'] or 0) - (summary['requests_used'] or 0),
|
352
|
+
},
|
353
|
+
'generated_at': timezone.now().isoformat()
|
354
|
+
})
|
355
|
+
|
356
|
+
except Exception as e:
|
357
|
+
logger.error(f"User subscription summary failed: {e}")
|
358
|
+
return Response(
|
359
|
+
{'error': f'Summary generation failed: {e}'},
|
360
|
+
status=status.HTTP_500_INTERNAL_SERVER_ERROR
|
361
|
+
)
|
362
|
+
|
363
|
+
|
364
|
+
class EndpointGroupViewSet(ReadOnlyPaymentViewSet):
|
365
|
+
"""
|
366
|
+
Endpoint Group ViewSet: /api/endpoint-groups/
|
367
|
+
|
368
|
+
Read-only access to endpoint group information.
|
369
|
+
"""
|
370
|
+
|
371
|
+
queryset = EndpointGroup.objects.filter(is_enabled=True)
|
372
|
+
serializer_class = EndpointGroupSerializer
|
373
|
+
permission_classes = [permissions.IsAuthenticated]
|
374
|
+
filterset_fields = ['is_enabled']
|
375
|
+
search_fields = ['name', 'description']
|
376
|
+
ordering_fields = ['name', 'created_at']
|
377
|
+
|
378
|
+
@action(detail=False, methods=['get'])
|
379
|
+
def available(self, request):
|
380
|
+
"""
|
381
|
+
Get available endpoint groups for subscription.
|
382
|
+
|
383
|
+
GET /api/endpoint-groups/available/
|
384
|
+
"""
|
385
|
+
try:
|
386
|
+
queryset = self.filter_queryset(self.get_queryset())
|
387
|
+
serializer = self.get_serializer(queryset, many=True)
|
388
|
+
|
389
|
+
return Response({
|
390
|
+
'endpoint_groups': serializer.data,
|
391
|
+
'count': len(serializer.data),
|
392
|
+
'generated_at': timezone.now().isoformat()
|
393
|
+
})
|
394
|
+
|
395
|
+
except Exception as e:
|
396
|
+
logger.error(f"Available endpoint groups failed: {e}")
|
397
|
+
return Response(
|
398
|
+
{'error': f'Available endpoint groups failed: {e}'},
|
399
|
+
status=status.HTTP_500_INTERNAL_SERVER_ERROR
|
400
|
+
)
|
401
|
+
|
402
|
+
|
403
|
+
class TariffViewSet(ReadOnlyPaymentViewSet):
|
404
|
+
"""
|
405
|
+
Tariff ViewSet: /api/tariffs/
|
406
|
+
|
407
|
+
Read-only access to tariff information for subscription selection.
|
408
|
+
"""
|
409
|
+
|
410
|
+
queryset = Tariff.objects.filter(is_active=True)
|
411
|
+
serializer_class = TariffSerializer
|
412
|
+
permission_classes = [permissions.IsAuthenticated]
|
413
|
+
filterset_fields = ['is_active']
|
414
|
+
search_fields = ['name', 'description']
|
415
|
+
ordering_fields = ['monthly_price', 'requests_per_month', 'created_at']
|
416
|
+
|
417
|
+
def get_queryset(self):
|
418
|
+
"""Optimize queryset with related objects."""
|
419
|
+
return super().get_queryset().prefetch_related('endpoint_groups')
|
420
|
+
|
421
|
+
@action(detail=False, methods=['get'])
|
422
|
+
def free(self, request):
|
423
|
+
"""
|
424
|
+
Get free tariffs.
|
425
|
+
|
426
|
+
GET /api/tariffs/free/
|
427
|
+
"""
|
428
|
+
free_tariffs = self.get_queryset().filter(monthly_price=0)
|
429
|
+
serializer = self.get_serializer(free_tariffs, many=True)
|
430
|
+
|
431
|
+
return Response({
|
432
|
+
'tariffs': serializer.data,
|
433
|
+
'count': len(serializer.data),
|
434
|
+
'type': 'free',
|
435
|
+
'generated_at': timezone.now().isoformat()
|
436
|
+
})
|
437
|
+
|
438
|
+
@action(detail=False, methods=['get'])
|
439
|
+
def paid(self, request):
|
440
|
+
"""
|
441
|
+
Get paid tariffs.
|
442
|
+
|
443
|
+
GET /api/tariffs/paid/
|
444
|
+
"""
|
445
|
+
paid_tariffs = self.get_queryset().filter(monthly_price__gt=0)
|
446
|
+
serializer = self.get_serializer(paid_tariffs, many=True)
|
447
|
+
|
448
|
+
return Response({
|
449
|
+
'tariffs': serializer.data,
|
450
|
+
'count': len(serializer.data),
|
451
|
+
'type': 'paid',
|
452
|
+
'generated_at': timezone.now().isoformat()
|
453
|
+
})
|
454
|
+
|
455
|
+
@action(detail=True, methods=['get'])
|
456
|
+
def endpoint_groups(self, request, pk=None):
|
457
|
+
"""
|
458
|
+
Get endpoint groups for specific tariff.
|
459
|
+
|
460
|
+
GET /api/tariffs/{id}/endpoint_groups/
|
461
|
+
"""
|
462
|
+
tariff = self.get_object()
|
463
|
+
endpoint_groups = tariff.endpoint_groups.filter(is_active=True)
|
464
|
+
serializer = EndpointGroupSerializer(endpoint_groups, many=True)
|
465
|
+
|
466
|
+
return Response({
|
467
|
+
'tariff': {
|
468
|
+
'id': tariff.id,
|
469
|
+
'name': tariff.name,
|
470
|
+
'monthly_price': tariff.monthly_price,
|
471
|
+
},
|
472
|
+
'endpoint_groups': serializer.data,
|
473
|
+
'count': len(serializer.data),
|
474
|
+
'generated_at': timezone.now().isoformat()
|
475
|
+
})
|