django-cfg 1.2.22__py3-none-any.whl → 1.2.25__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/knowbase/tasks/archive_tasks.py +6 -6
- django_cfg/apps/knowbase/tasks/document_processing.py +3 -3
- django_cfg/apps/knowbase/tasks/external_data_tasks.py +2 -2
- django_cfg/apps/knowbase/tasks/maintenance.py +3 -3
- django_cfg/apps/payments/admin/__init__.py +23 -0
- django_cfg/apps/payments/admin/api_keys_admin.py +347 -0
- django_cfg/apps/payments/admin/balance_admin.py +434 -0
- django_cfg/apps/payments/admin/currencies_admin.py +186 -0
- django_cfg/apps/payments/admin/filters.py +259 -0
- django_cfg/apps/payments/admin/payments_admin.py +142 -0
- django_cfg/apps/payments/admin/subscriptions_admin.py +227 -0
- django_cfg/apps/payments/admin/tariffs_admin.py +199 -0
- django_cfg/apps/payments/config/__init__.py +65 -0
- django_cfg/apps/payments/config/module.py +70 -0
- django_cfg/apps/payments/config/providers.py +115 -0
- django_cfg/apps/payments/config/settings.py +96 -0
- django_cfg/apps/payments/config/utils.py +52 -0
- django_cfg/apps/payments/decorators.py +291 -0
- django_cfg/apps/payments/management/__init__.py +3 -0
- django_cfg/apps/payments/management/commands/README.md +178 -0
- django_cfg/apps/payments/management/commands/__init__.py +3 -0
- django_cfg/apps/payments/management/commands/currency_stats.py +323 -0
- django_cfg/apps/payments/management/commands/populate_currencies.py +246 -0
- django_cfg/apps/payments/management/commands/update_currencies.py +336 -0
- django_cfg/apps/payments/managers/currency_manager.py +65 -14
- django_cfg/apps/payments/middleware/api_access.py +294 -0
- django_cfg/apps/payments/middleware/rate_limiting.py +216 -0
- django_cfg/apps/payments/middleware/usage_tracking.py +296 -0
- django_cfg/apps/payments/migrations/0001_initial.py +125 -11
- django_cfg/apps/payments/models/__init__.py +18 -0
- django_cfg/apps/payments/models/api_keys.py +2 -2
- django_cfg/apps/payments/models/balance.py +2 -2
- django_cfg/apps/payments/models/base.py +16 -0
- django_cfg/apps/payments/models/events.py +2 -2
- django_cfg/apps/payments/models/payments.py +112 -2
- django_cfg/apps/payments/models/subscriptions.py +2 -2
- django_cfg/apps/payments/services/__init__.py +64 -7
- django_cfg/apps/payments/services/billing/__init__.py +8 -0
- django_cfg/apps/payments/services/cache/__init__.py +15 -0
- django_cfg/apps/payments/services/cache/base.py +30 -0
- django_cfg/apps/payments/services/cache/simple_cache.py +135 -0
- django_cfg/apps/payments/services/core/__init__.py +17 -0
- django_cfg/apps/payments/services/core/balance_service.py +447 -0
- django_cfg/apps/payments/services/core/fallback_service.py +432 -0
- django_cfg/apps/payments/services/core/payment_service.py +576 -0
- django_cfg/apps/payments/services/core/subscription_service.py +614 -0
- django_cfg/apps/payments/services/internal_types.py +297 -0
- django_cfg/apps/payments/services/middleware/__init__.py +8 -0
- django_cfg/apps/payments/services/monitoring/__init__.py +22 -0
- django_cfg/apps/payments/services/monitoring/api_schemas.py +222 -0
- django_cfg/apps/payments/services/monitoring/provider_health.py +372 -0
- django_cfg/apps/payments/services/providers/__init__.py +22 -0
- django_cfg/apps/payments/services/providers/base.py +137 -0
- django_cfg/apps/payments/services/providers/cryptapi.py +273 -0
- django_cfg/apps/payments/services/providers/cryptomus.py +310 -0
- django_cfg/apps/payments/services/providers/nowpayments.py +293 -0
- django_cfg/apps/payments/services/providers/registry.py +103 -0
- django_cfg/apps/payments/services/security/__init__.py +34 -0
- django_cfg/apps/payments/services/security/error_handler.py +637 -0
- django_cfg/apps/payments/services/security/payment_notifications.py +342 -0
- django_cfg/apps/payments/services/security/webhook_validator.py +475 -0
- django_cfg/apps/payments/services/validators/__init__.py +8 -0
- django_cfg/apps/payments/signals/__init__.py +13 -0
- django_cfg/apps/payments/signals/api_key_signals.py +160 -0
- django_cfg/apps/payments/signals/payment_signals.py +128 -0
- django_cfg/apps/payments/signals/subscription_signals.py +196 -0
- django_cfg/apps/payments/tasks/__init__.py +12 -0
- django_cfg/apps/payments/tasks/webhook_processing.py +177 -0
- django_cfg/apps/payments/urls.py +5 -5
- django_cfg/apps/payments/utils/__init__.py +45 -0
- django_cfg/apps/payments/utils/billing_utils.py +342 -0
- django_cfg/apps/payments/utils/config_utils.py +245 -0
- django_cfg/apps/payments/utils/middleware_utils.py +228 -0
- django_cfg/apps/payments/utils/validation_utils.py +94 -0
- django_cfg/apps/payments/views/payment_views.py +40 -2
- django_cfg/apps/payments/views/webhook_views.py +266 -0
- django_cfg/apps/payments/viewsets.py +65 -0
- django_cfg/apps/support/signals.py +16 -4
- django_cfg/apps/support/templates/support/chat/ticket_chat.html +1 -1
- django_cfg/cli/README.md +2 -2
- django_cfg/cli/commands/create_project.py +1 -1
- django_cfg/cli/commands/info.py +1 -1
- django_cfg/cli/main.py +1 -1
- django_cfg/cli/utils.py +5 -5
- django_cfg/core/config.py +18 -4
- django_cfg/models/payments.py +546 -0
- django_cfg/models/revolution.py +1 -1
- django_cfg/models/tasks.py +51 -2
- django_cfg/modules/base.py +12 -6
- django_cfg/modules/django_currency/README.md +104 -269
- django_cfg/modules/django_currency/__init__.py +99 -41
- django_cfg/modules/django_currency/clients/__init__.py +11 -0
- django_cfg/modules/django_currency/clients/coingecko_client.py +257 -0
- django_cfg/modules/django_currency/clients/yfinance_client.py +246 -0
- django_cfg/modules/django_currency/core/__init__.py +42 -0
- django_cfg/modules/django_currency/core/converter.py +169 -0
- django_cfg/modules/django_currency/core/exceptions.py +28 -0
- django_cfg/modules/django_currency/core/models.py +54 -0
- django_cfg/modules/django_currency/database/__init__.py +25 -0
- django_cfg/modules/django_currency/database/database_loader.py +507 -0
- django_cfg/modules/django_currency/utils/__init__.py +9 -0
- django_cfg/modules/django_currency/utils/cache.py +92 -0
- django_cfg/modules/django_email.py +42 -4
- django_cfg/modules/django_unfold/dashboard.py +20 -0
- django_cfg/registry/core.py +10 -0
- django_cfg/template_archive/__init__.py +0 -0
- django_cfg/template_archive/django_sample.zip +0 -0
- {django_cfg-1.2.22.dist-info → django_cfg-1.2.25.dist-info}/METADATA +11 -6
- {django_cfg-1.2.22.dist-info → django_cfg-1.2.25.dist-info}/RECORD +113 -50
- django_cfg/apps/agents/examples/__init__.py +0 -3
- django_cfg/apps/agents/examples/simple_example.py +0 -161
- django_cfg/apps/knowbase/examples/__init__.py +0 -3
- django_cfg/apps/knowbase/examples/external_data_usage.py +0 -191
- django_cfg/apps/knowbase/mixins/examples/vehicle_model_example.py +0 -199
- django_cfg/apps/payments/services/base.py +0 -68
- django_cfg/apps/payments/services/nowpayments.py +0 -78
- django_cfg/apps/payments/services/providers.py +0 -77
- django_cfg/apps/payments/services/redis_service.py +0 -215
- django_cfg/modules/django_currency/cache.py +0 -430
- django_cfg/modules/django_currency/converter.py +0 -324
- django_cfg/modules/django_currency/service.py +0 -277
- {django_cfg-1.2.22.dist-info → django_cfg-1.2.25.dist-info}/WHEEL +0 -0
- {django_cfg-1.2.22.dist-info → django_cfg-1.2.25.dist-info}/entry_points.txt +0 -0
- {django_cfg-1.2.22.dist-info → django_cfg-1.2.25.dist-info}/licenses/LICENSE +0 -0
@@ -1,191 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Примеры использования нового ExternalDataManager.
|
3
|
-
|
4
|
-
Этот файл показывает, как легко интегрировать внешние данные в knowbase
|
5
|
-
после рефакторинга.
|
6
|
-
"""
|
7
|
-
|
8
|
-
from django.contrib.auth import get_user_model
|
9
|
-
from django_cfg.apps.knowbase.utils.external_data_manager import ExternalDataManager, quick_add_model, quick_search
|
10
|
-
from django_cfg.apps.knowbase.models.external_data import ExternalDataType
|
11
|
-
|
12
|
-
User = get_user_model()
|
13
|
-
|
14
|
-
|
15
|
-
def example_add_django_model():
|
16
|
-
"""Пример добавления Django модели как внешнего источника данных."""
|
17
|
-
|
18
|
-
# Получаем пользователя
|
19
|
-
user = User.objects.first()
|
20
|
-
if not user:
|
21
|
-
print("❌ No users found")
|
22
|
-
return
|
23
|
-
|
24
|
-
# Создаем менеджер
|
25
|
-
manager = ExternalDataManager(user)
|
26
|
-
|
27
|
-
# Добавляем модель Vehicle (если она существует)
|
28
|
-
try:
|
29
|
-
from apps.vehicles_data.models import Vehicle
|
30
|
-
|
31
|
-
external_data = manager.add_django_model(
|
32
|
-
model_class=Vehicle,
|
33
|
-
title="Vehicle Database",
|
34
|
-
fields=['brand__name', 'model', 'year', 'description'],
|
35
|
-
description="All vehicles from the database",
|
36
|
-
search_fields=['brand__name', 'model'],
|
37
|
-
chunk_size=800,
|
38
|
-
overlap_size=150,
|
39
|
-
auto_vectorize=True
|
40
|
-
)
|
41
|
-
|
42
|
-
print(f"✅ Added Vehicle model as external data: {external_data.id}")
|
43
|
-
print(f" Status: {external_data.status}")
|
44
|
-
print(f" Total chunks: {external_data.total_chunks}")
|
45
|
-
|
46
|
-
except ImportError:
|
47
|
-
print("⚠️ Vehicle model not found, using example data instead")
|
48
|
-
|
49
|
-
# Добавляем произвольные данные
|
50
|
-
external_data = manager.add_custom_data(
|
51
|
-
title="Sample Car Data",
|
52
|
-
identifier="sample_cars",
|
53
|
-
content="""
|
54
|
-
Toyota Camry 2023: Reliable sedan with excellent fuel economy
|
55
|
-
Honda Civic 2023: Compact car perfect for city driving
|
56
|
-
BMW X5 2023: Luxury SUV with advanced features
|
57
|
-
Tesla Model 3 2023: Electric vehicle with autopilot
|
58
|
-
""",
|
59
|
-
description="Sample car data for testing",
|
60
|
-
tags=['cars', 'vehicles', 'sample']
|
61
|
-
)
|
62
|
-
|
63
|
-
print(f"✅ Added sample car data: {external_data.id}")
|
64
|
-
|
65
|
-
|
66
|
-
def example_search_external_data():
|
67
|
-
"""Пример поиска по внешним данным."""
|
68
|
-
|
69
|
-
user = User.objects.first()
|
70
|
-
if not user:
|
71
|
-
print("❌ No users found")
|
72
|
-
return
|
73
|
-
|
74
|
-
manager = ExternalDataManager(user)
|
75
|
-
|
76
|
-
# Поиск по запросу
|
77
|
-
results = manager.search(
|
78
|
-
query="reliable car with good fuel economy",
|
79
|
-
limit=3,
|
80
|
-
threshold=0.6
|
81
|
-
)
|
82
|
-
|
83
|
-
print(f"🔍 Search results ({len(results)} found):")
|
84
|
-
for i, result in enumerate(results, 1):
|
85
|
-
print(f" {i}. {result['source_title']} (similarity: {result['similarity']:.3f})")
|
86
|
-
print(f" Content: {result['content'][:100]}...")
|
87
|
-
print()
|
88
|
-
|
89
|
-
|
90
|
-
def example_get_statistics():
|
91
|
-
"""Пример получения статистики."""
|
92
|
-
|
93
|
-
user = User.objects.first()
|
94
|
-
if not user:
|
95
|
-
print("❌ No users found")
|
96
|
-
return
|
97
|
-
|
98
|
-
manager = ExternalDataManager(user)
|
99
|
-
stats = manager.get_statistics()
|
100
|
-
|
101
|
-
print("📊 External Data Statistics:")
|
102
|
-
print(f" Total sources: {stats.total_sources}")
|
103
|
-
print(f" Active sources: {stats.active_sources}")
|
104
|
-
print(f" Processed sources: {stats.processed_sources}")
|
105
|
-
print(f" Failed sources: {stats.failed_sources}")
|
106
|
-
print(f" Total chunks: {stats.total_chunks}")
|
107
|
-
print(f" Total tokens: {stats.total_tokens}")
|
108
|
-
print(f" Total cost: ${stats.total_cost:.4f}")
|
109
|
-
print(f" Source types: {stats.source_type_counts}")
|
110
|
-
|
111
|
-
|
112
|
-
def example_health_check():
|
113
|
-
"""Пример проверки здоровья системы."""
|
114
|
-
|
115
|
-
user = User.objects.first()
|
116
|
-
if not user:
|
117
|
-
print("❌ No users found")
|
118
|
-
return
|
119
|
-
|
120
|
-
manager = ExternalDataManager(user)
|
121
|
-
health = manager.health_check()
|
122
|
-
|
123
|
-
print("🏥 System Health Check:")
|
124
|
-
print(f" Status: {health.status}")
|
125
|
-
print(f" Healthy: {'✅' if health.healthy else '❌'}")
|
126
|
-
print(f" Database: {'✅' if health.database_healthy else '❌'}")
|
127
|
-
print(f" Embedding Service: {'✅' if health.embedding_service_healthy else '❌'}")
|
128
|
-
print(f" Processing: {'✅' if health.processing_healthy else '❌'}")
|
129
|
-
print(f" Response time: {health.response_time_ms:.2f}ms")
|
130
|
-
print(f" Active sources: {health.active_sources}")
|
131
|
-
print(f" Pending processing: {health.pending_processing}")
|
132
|
-
print(f" Failed processing: {health.failed_processing}")
|
133
|
-
|
134
|
-
if health.issues:
|
135
|
-
print(f" Issues: {health.issues}")
|
136
|
-
if health.warnings:
|
137
|
-
print(f" Warnings: {health.warnings}")
|
138
|
-
|
139
|
-
|
140
|
-
def example_quick_functions():
|
141
|
-
"""Пример использования быстрых функций."""
|
142
|
-
|
143
|
-
user = User.objects.first()
|
144
|
-
if not user:
|
145
|
-
print("❌ No users found")
|
146
|
-
return
|
147
|
-
|
148
|
-
# Быстрый поиск
|
149
|
-
results = quick_search(
|
150
|
-
user=user,
|
151
|
-
query="electric vehicle",
|
152
|
-
limit=2
|
153
|
-
)
|
154
|
-
|
155
|
-
print(f"⚡ Quick search results: {len(results)} found")
|
156
|
-
for result in results:
|
157
|
-
print(f" - {result['source_title']}: {result['similarity']:.3f}")
|
158
|
-
|
159
|
-
|
160
|
-
def run_all_examples():
|
161
|
-
"""Запустить все примеры."""
|
162
|
-
|
163
|
-
print("🚀 Running External Data Manager Examples")
|
164
|
-
print("=" * 50)
|
165
|
-
|
166
|
-
try:
|
167
|
-
print("\n1. Adding Django Model:")
|
168
|
-
example_add_django_model()
|
169
|
-
|
170
|
-
print("\n2. Searching External Data:")
|
171
|
-
example_search_external_data()
|
172
|
-
|
173
|
-
print("\n3. Getting Statistics:")
|
174
|
-
example_get_statistics()
|
175
|
-
|
176
|
-
print("\n4. Health Check:")
|
177
|
-
example_health_check()
|
178
|
-
|
179
|
-
print("\n5. Quick Functions:")
|
180
|
-
example_quick_functions()
|
181
|
-
|
182
|
-
print("\n✅ All examples completed successfully!")
|
183
|
-
|
184
|
-
except Exception as e:
|
185
|
-
print(f"\n❌ Error running examples: {e}")
|
186
|
-
import traceback
|
187
|
-
traceback.print_exc()
|
188
|
-
|
189
|
-
|
190
|
-
if __name__ == "__main__":
|
191
|
-
run_all_examples()
|
@@ -1,199 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Example of using ExternalDataMixin with VehicleModel.
|
3
|
-
|
4
|
-
This shows how to integrate VehicleModel with knowbase using the mixin.
|
5
|
-
"""
|
6
|
-
|
7
|
-
from django.db import models
|
8
|
-
from django_cfg.apps.knowbase.mixins import ExternalDataMixin
|
9
|
-
from django_cfg.apps.knowbase.models.external_data import ExternalDataType
|
10
|
-
|
11
|
-
|
12
|
-
class VehicleModelWithMixin(ExternalDataMixin, models.Model):
|
13
|
-
"""
|
14
|
-
Example VehicleModel with ExternalDataMixin integration.
|
15
|
-
|
16
|
-
This replaces the manual integration we had before with automatic
|
17
|
-
tracking and vectorization.
|
18
|
-
"""
|
19
|
-
|
20
|
-
# Original VehicleModel fields
|
21
|
-
brand = models.ForeignKey('vehicles_data.Brand', on_delete=models.CASCADE)
|
22
|
-
code = models.CharField(max_length=20)
|
23
|
-
name = models.CharField(max_length=100)
|
24
|
-
body_type = models.CharField(max_length=20, blank=True)
|
25
|
-
segment = models.CharField(max_length=50, blank=True)
|
26
|
-
is_active = models.BooleanField(default=True)
|
27
|
-
total_vehicles = models.PositiveIntegerField(default=0)
|
28
|
-
created_at = models.DateTimeField(auto_now_add=True)
|
29
|
-
updated_at = models.DateTimeField(auto_now=True)
|
30
|
-
|
31
|
-
class Meta:
|
32
|
-
abstract = True # This is just an example
|
33
|
-
|
34
|
-
class ExternalDataMeta:
|
35
|
-
# Fields to watch for changes - only update when these change
|
36
|
-
watch_fields = ['name', 'body_type', 'segment', 'is_active']
|
37
|
-
|
38
|
-
# Lower threshold for multilingual vehicle data
|
39
|
-
similarity_threshold = 0.4
|
40
|
-
|
41
|
-
# Vehicle models are model type
|
42
|
-
source_type = ExternalDataType.MODEL
|
43
|
-
|
44
|
-
# Enable auto-sync
|
45
|
-
auto_sync = True
|
46
|
-
|
47
|
-
# Make public for search
|
48
|
-
is_public = True
|
49
|
-
|
50
|
-
# Required: content generation method
|
51
|
-
def get_external_content(self):
|
52
|
-
"""Generate content for vectorization."""
|
53
|
-
content_parts = [
|
54
|
-
f"# {self.brand.name} {self.name}",
|
55
|
-
"",
|
56
|
-
"## Basic Information",
|
57
|
-
f"- **Brand**: {self.brand.name} ({self.brand.code})",
|
58
|
-
f"- **Model**: {self.name} ({self.code})",
|
59
|
-
]
|
60
|
-
|
61
|
-
if self.body_type:
|
62
|
-
content_parts.append(f"- **Body Type**: {self.body_type}")
|
63
|
-
|
64
|
-
if self.segment:
|
65
|
-
content_parts.append(f"- **Market Segment**: {self.segment}")
|
66
|
-
|
67
|
-
content_parts.extend([
|
68
|
-
f"- **Status**: {'Active' if self.is_active else 'Inactive'}",
|
69
|
-
"",
|
70
|
-
"## Market Statistics",
|
71
|
-
f"- **Total Listings**: {self.total_vehicles:,} vehicles available",
|
72
|
-
])
|
73
|
-
|
74
|
-
if hasattr(self, 'vehicles') and self.vehicles.exists():
|
75
|
-
# Add some vehicle statistics if available
|
76
|
-
vehicles = self.vehicles.filter(is_active=True)
|
77
|
-
if vehicles.exists():
|
78
|
-
content_parts.extend([
|
79
|
-
"",
|
80
|
-
"## Available Vehicles",
|
81
|
-
f"- **Active Listings**: {vehicles.count():,} vehicles",
|
82
|
-
])
|
83
|
-
|
84
|
-
# Add price range if available
|
85
|
-
if hasattr(vehicles.first(), 'price'):
|
86
|
-
prices = vehicles.exclude(price__isnull=True).values_list('price', flat=True)
|
87
|
-
if prices:
|
88
|
-
min_price = min(prices)
|
89
|
-
max_price = max(prices)
|
90
|
-
content_parts.append(f"- **Price Range**: ${min_price:,} - ${max_price:,}")
|
91
|
-
|
92
|
-
content_parts.extend([
|
93
|
-
"",
|
94
|
-
f"## Model History",
|
95
|
-
f"- **First Listed**: {self.created_at.strftime('%Y-%m-%d')}",
|
96
|
-
f"- **Last Updated**: {self.updated_at.strftime('%Y-%m-%d')}",
|
97
|
-
])
|
98
|
-
|
99
|
-
return "\n".join(content_parts)
|
100
|
-
|
101
|
-
# Optional: custom title
|
102
|
-
def get_external_title(self):
|
103
|
-
"""Generate title for ExternalData."""
|
104
|
-
return f"Vehicle Model: {self.brand.name} {self.name}"
|
105
|
-
|
106
|
-
# Optional: custom description
|
107
|
-
def get_external_description(self):
|
108
|
-
"""Generate description for ExternalData."""
|
109
|
-
parts = [f"Comprehensive information about {self.brand.name} {self.name}"]
|
110
|
-
|
111
|
-
if self.body_type:
|
112
|
-
parts.append(f"({self.body_type})")
|
113
|
-
|
114
|
-
parts.append("including specifications, market data, and vehicle listings.")
|
115
|
-
|
116
|
-
return " ".join(parts)
|
117
|
-
|
118
|
-
# Optional: metadata
|
119
|
-
def get_external_metadata(self):
|
120
|
-
"""Generate metadata for ExternalData."""
|
121
|
-
return {
|
122
|
-
'vehicle_model_id': str(self.id),
|
123
|
-
'brand_code': self.brand.code,
|
124
|
-
'brand_name': self.brand.name,
|
125
|
-
'model_code': self.code,
|
126
|
-
'model_name': self.name,
|
127
|
-
'body_type': self.body_type,
|
128
|
-
'segment': self.segment,
|
129
|
-
'total_vehicles': self.total_vehicles,
|
130
|
-
'is_active': self.is_active,
|
131
|
-
'created_at': self.created_at.isoformat(),
|
132
|
-
'updated_at': self.updated_at.isoformat(),
|
133
|
-
'integration_type': 'vehicle_model_mixin_auto'
|
134
|
-
}
|
135
|
-
|
136
|
-
# Optional: tags
|
137
|
-
def get_external_tags(self):
|
138
|
-
"""Generate tags for ExternalData."""
|
139
|
-
tags = [
|
140
|
-
'vehicle',
|
141
|
-
'model',
|
142
|
-
self.brand.code.lower(),
|
143
|
-
self.code.lower(),
|
144
|
-
self.brand.name.lower().replace(' ', '_'),
|
145
|
-
self.name.lower().replace(' ', '_'),
|
146
|
-
]
|
147
|
-
|
148
|
-
if self.body_type:
|
149
|
-
tags.append(self.body_type.lower().replace(' ', '_'))
|
150
|
-
|
151
|
-
if self.segment:
|
152
|
-
tags.append(self.segment.lower().replace(' ', '_'))
|
153
|
-
|
154
|
-
return tags
|
155
|
-
|
156
|
-
@property
|
157
|
-
def full_name(self):
|
158
|
-
"""Get full model name with brand."""
|
159
|
-
return f"{self.brand.name} {self.name}"
|
160
|
-
|
161
|
-
def __str__(self):
|
162
|
-
return self.full_name
|
163
|
-
|
164
|
-
|
165
|
-
# Usage example:
|
166
|
-
"""
|
167
|
-
# To use this mixin in your existing VehicleModel:
|
168
|
-
|
169
|
-
1. Add the mixin to your model:
|
170
|
-
class VehicleModel(ExternalDataMixin, models.Model):
|
171
|
-
# ... your existing fields ...
|
172
|
-
|
173
|
-
class ExternalDataMeta:
|
174
|
-
watch_fields = ['name', 'body_type', 'segment', 'is_active']
|
175
|
-
similarity_threshold = 0.4
|
176
|
-
source_type = ExternalDataType.MODEL
|
177
|
-
auto_sync = True
|
178
|
-
is_public = True
|
179
|
-
|
180
|
-
def get_external_content(self):
|
181
|
-
# ... content generation logic ...
|
182
|
-
return content
|
183
|
-
|
184
|
-
2. Run migrations to add the mixin fields:
|
185
|
-
python manage.py makemigrations
|
186
|
-
python manage.py migrate
|
187
|
-
|
188
|
-
3. That's it! The mixin will automatically:
|
189
|
-
- Create ExternalData when VehicleModel is created
|
190
|
-
- Update ExternalData when watched fields change
|
191
|
-
- Delete ExternalData when VehicleModel is deleted
|
192
|
-
- Handle vectorization and search integration
|
193
|
-
|
194
|
-
4. Manual operations (if needed):
|
195
|
-
vehicle_model.regenerate_external_data() # Force regeneration
|
196
|
-
vehicle_model.delete_external_data() # Remove integration
|
197
|
-
vehicle_model.has_external_data # Check if linked
|
198
|
-
vehicle_model.external_data_status # Get processing status
|
199
|
-
"""
|
@@ -1,68 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Base payment service classes.
|
3
|
-
"""
|
4
|
-
|
5
|
-
from abc import ABC, abstractmethod
|
6
|
-
from typing import Dict, Any, Optional
|
7
|
-
from decimal import Decimal
|
8
|
-
|
9
|
-
|
10
|
-
class PaymentProvider(ABC):
|
11
|
-
"""Abstract base class for payment providers."""
|
12
|
-
|
13
|
-
def __init__(self, config: Dict[str, Any]):
|
14
|
-
"""Initialize provider with config."""
|
15
|
-
self.config = config
|
16
|
-
self.name = self.__class__.__name__.lower().replace('provider', '')
|
17
|
-
|
18
|
-
@abstractmethod
|
19
|
-
def create_payment(self, amount: Decimal, currency: str, **kwargs) -> Dict[str, Any]:
|
20
|
-
"""Create a payment request."""
|
21
|
-
pass
|
22
|
-
|
23
|
-
@abstractmethod
|
24
|
-
def check_payment_status(self, payment_id: str) -> Dict[str, Any]:
|
25
|
-
"""Check payment status."""
|
26
|
-
pass
|
27
|
-
|
28
|
-
@abstractmethod
|
29
|
-
def process_webhook(self, payload: Dict[str, Any]) -> Dict[str, Any]:
|
30
|
-
"""Process webhook payload."""
|
31
|
-
pass
|
32
|
-
|
33
|
-
@abstractmethod
|
34
|
-
def get_supported_currencies(self) -> list[str]:
|
35
|
-
"""Get list of supported currencies."""
|
36
|
-
pass
|
37
|
-
|
38
|
-
|
39
|
-
class PaymentService:
|
40
|
-
"""Main payment service with provider management."""
|
41
|
-
|
42
|
-
def __init__(self):
|
43
|
-
"""Initialize payment service."""
|
44
|
-
self.providers: Dict[str, PaymentProvider] = {}
|
45
|
-
|
46
|
-
def register_provider(self, provider: PaymentProvider) -> None:
|
47
|
-
"""Register a payment provider."""
|
48
|
-
self.providers[provider.name] = provider
|
49
|
-
|
50
|
-
def get_provider(self, name: str) -> Optional[PaymentProvider]:
|
51
|
-
"""Get provider by name."""
|
52
|
-
return self.providers.get(name)
|
53
|
-
|
54
|
-
def create_payment(self, provider_name: str, amount: Decimal, currency: str, **kwargs) -> Dict[str, Any]:
|
55
|
-
"""Create payment using specified provider."""
|
56
|
-
provider = self.get_provider(provider_name)
|
57
|
-
if not provider:
|
58
|
-
raise ValueError(f"Provider {provider_name} not found")
|
59
|
-
|
60
|
-
return provider.create_payment(amount, currency, **kwargs)
|
61
|
-
|
62
|
-
def process_webhook(self, provider_name: str, payload: Dict[str, Any]) -> Dict[str, Any]:
|
63
|
-
"""Process webhook for specified provider."""
|
64
|
-
provider = self.get_provider(provider_name)
|
65
|
-
if not provider:
|
66
|
-
raise ValueError(f"Provider {provider_name} not found")
|
67
|
-
|
68
|
-
return provider.process_webhook(payload)
|
@@ -1,78 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
NowPayments provider implementation.
|
3
|
-
"""
|
4
|
-
|
5
|
-
from typing import Dict, Any
|
6
|
-
from decimal import Decimal
|
7
|
-
import requests
|
8
|
-
from .base import PaymentProvider
|
9
|
-
|
10
|
-
|
11
|
-
class NowPaymentsProvider(PaymentProvider):
|
12
|
-
"""NowPayments crypto payment provider."""
|
13
|
-
|
14
|
-
def __init__(self, config: Dict[str, Any]):
|
15
|
-
"""Initialize NowPayments provider."""
|
16
|
-
super().__init__(config)
|
17
|
-
self.api_key = config.get('api_key')
|
18
|
-
self.base_url = config.get('base_url', 'https://api.nowpayments.io/v1')
|
19
|
-
self.headers = {'x-api-key': self.api_key}
|
20
|
-
|
21
|
-
def create_payment(self, amount: Decimal, currency: str, **kwargs) -> Dict[str, Any]:
|
22
|
-
"""Create payment via NowPayments API."""
|
23
|
-
payload = {
|
24
|
-
'price_amount': float(amount),
|
25
|
-
'price_currency': 'USD',
|
26
|
-
'pay_currency': currency.upper(),
|
27
|
-
'order_id': kwargs.get('order_id'),
|
28
|
-
'order_description': kwargs.get('description', 'Payment'),
|
29
|
-
'ipn_callback_url': kwargs.get('callback_url'),
|
30
|
-
'success_url': kwargs.get('success_url'),
|
31
|
-
'cancel_url': kwargs.get('cancel_url'),
|
32
|
-
}
|
33
|
-
|
34
|
-
response = requests.post(
|
35
|
-
f"{self.base_url}/payment",
|
36
|
-
json=payload,
|
37
|
-
headers=self.headers,
|
38
|
-
timeout=30
|
39
|
-
)
|
40
|
-
response.raise_for_status()
|
41
|
-
return response.json()
|
42
|
-
|
43
|
-
def check_payment_status(self, payment_id: str) -> Dict[str, Any]:
|
44
|
-
"""Check payment status via NowPayments API."""
|
45
|
-
response = requests.get(
|
46
|
-
f"{self.base_url}/payment/{payment_id}",
|
47
|
-
headers=self.headers,
|
48
|
-
timeout=30
|
49
|
-
)
|
50
|
-
response.raise_for_status()
|
51
|
-
return response.json()
|
52
|
-
|
53
|
-
def process_webhook(self, payload: Dict[str, Any]) -> Dict[str, Any]:
|
54
|
-
"""Process NowPayments webhook."""
|
55
|
-
# Extract important fields from webhook
|
56
|
-
return {
|
57
|
-
'payment_id': payload.get('payment_id'),
|
58
|
-
'payment_status': payload.get('payment_status'),
|
59
|
-
'pay_address': payload.get('pay_address'),
|
60
|
-
'pay_amount': payload.get('pay_amount'),
|
61
|
-
'pay_currency': payload.get('pay_currency'),
|
62
|
-
'price_amount': payload.get('price_amount'),
|
63
|
-
'price_currency': payload.get('price_currency'),
|
64
|
-
'order_id': payload.get('order_id'),
|
65
|
-
'outcome_amount': payload.get('outcome_amount'),
|
66
|
-
'outcome_currency': payload.get('outcome_currency'),
|
67
|
-
}
|
68
|
-
|
69
|
-
def get_supported_currencies(self) -> list[str]:
|
70
|
-
"""Get supported cryptocurrencies from NowPayments."""
|
71
|
-
response = requests.get(
|
72
|
-
f"{self.base_url}/currencies",
|
73
|
-
headers=self.headers,
|
74
|
-
timeout=30
|
75
|
-
)
|
76
|
-
response.raise_for_status()
|
77
|
-
data = response.json()
|
78
|
-
return data.get('currencies', [])
|
@@ -1,77 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
Payment provider integrations using Pydantic for external data validation.
|
3
|
-
Only for provider responses and internal service communication.
|
4
|
-
"""
|
5
|
-
|
6
|
-
from pydantic import BaseModel, Field, ConfigDict, field_validator
|
7
|
-
from decimal import Decimal
|
8
|
-
from datetime import datetime, timezone
|
9
|
-
from typing import Optional, Dict, Any
|
10
|
-
|
11
|
-
|
12
|
-
class NowPaymentsWebhook(BaseModel):
|
13
|
-
"""NowPayments webhook data validation."""
|
14
|
-
model_config = ConfigDict(validate_assignment=True, extra="forbid")
|
15
|
-
|
16
|
-
payment_id: str
|
17
|
-
payment_status: str
|
18
|
-
pay_address: str
|
19
|
-
pay_amount: Decimal
|
20
|
-
pay_currency: str
|
21
|
-
order_id: str
|
22
|
-
order_description: Optional[str] = None
|
23
|
-
ipn_callback_url: Optional[str] = None
|
24
|
-
created_at: Optional[datetime] = None
|
25
|
-
updated_at: Optional[datetime] = None
|
26
|
-
|
27
|
-
@field_validator('pay_amount')
|
28
|
-
@classmethod
|
29
|
-
def validate_amount(cls, v: Decimal) -> Decimal:
|
30
|
-
if v <= 0:
|
31
|
-
raise ValueError("Payment amount must be positive")
|
32
|
-
return v
|
33
|
-
|
34
|
-
|
35
|
-
class NowPaymentsCreateResponse(BaseModel):
|
36
|
-
"""NowPayments payment creation response."""
|
37
|
-
model_config = ConfigDict(validate_assignment=True, extra="forbid")
|
38
|
-
|
39
|
-
payment_id: str
|
40
|
-
payment_status: str
|
41
|
-
pay_address: str
|
42
|
-
pay_amount: Decimal
|
43
|
-
pay_currency: str
|
44
|
-
order_id: str
|
45
|
-
order_description: Optional[str] = None
|
46
|
-
ipn_callback_url: Optional[str] = None
|
47
|
-
created_at: datetime
|
48
|
-
updated_at: datetime
|
49
|
-
|
50
|
-
|
51
|
-
class NowPaymentsStatusResponse(BaseModel):
|
52
|
-
"""NowPayments payment status response."""
|
53
|
-
model_config = ConfigDict(validate_assignment=True, extra="forbid")
|
54
|
-
|
55
|
-
payment_id: str
|
56
|
-
payment_status: str
|
57
|
-
pay_address: str
|
58
|
-
pay_amount: Decimal
|
59
|
-
actually_paid: Optional[Decimal] = None
|
60
|
-
pay_currency: str
|
61
|
-
order_id: str
|
62
|
-
outcome_amount: Optional[Decimal] = None
|
63
|
-
outcome_currency: Optional[str] = None
|
64
|
-
|
65
|
-
|
66
|
-
class ProviderWebhookData(BaseModel):
|
67
|
-
"""Generic webhook data for any provider."""
|
68
|
-
model_config = ConfigDict(validate_assignment=True, extra="forbid")
|
69
|
-
|
70
|
-
provider: str
|
71
|
-
payment_id: str
|
72
|
-
status: str
|
73
|
-
amount: Optional[Decimal] = None
|
74
|
-
currency: Optional[str] = None
|
75
|
-
raw_data: Dict[str, Any] = Field(default_factory=dict)
|
76
|
-
signature: Optional[str] = None
|
77
|
-
received_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|