django-cfg 1.2.23__py3-none-any.whl → 1.2.27__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.
Files changed (85) hide show
  1. django_cfg/__init__.py +1 -1
  2. django_cfg/apps/knowbase/tasks/archive_tasks.py +6 -6
  3. django_cfg/apps/knowbase/tasks/document_processing.py +3 -3
  4. django_cfg/apps/knowbase/tasks/external_data_tasks.py +2 -2
  5. django_cfg/apps/knowbase/tasks/maintenance.py +3 -3
  6. django_cfg/apps/payments/config/__init__.py +15 -37
  7. django_cfg/apps/payments/config/module.py +30 -122
  8. django_cfg/apps/payments/config/providers.py +28 -16
  9. django_cfg/apps/payments/config/settings.py +53 -93
  10. django_cfg/apps/payments/config/utils.py +10 -156
  11. django_cfg/apps/payments/management/__init__.py +3 -0
  12. django_cfg/apps/payments/management/commands/README.md +178 -0
  13. django_cfg/apps/payments/management/commands/__init__.py +3 -0
  14. django_cfg/apps/payments/management/commands/currency_stats.py +323 -0
  15. django_cfg/apps/payments/management/commands/populate_currencies.py +246 -0
  16. django_cfg/apps/payments/management/commands/update_currencies.py +336 -0
  17. django_cfg/apps/payments/managers/currency_manager.py +65 -14
  18. django_cfg/apps/payments/middleware/api_access.py +33 -0
  19. django_cfg/apps/payments/migrations/0001_initial.py +94 -1
  20. django_cfg/apps/payments/models/payments.py +110 -0
  21. django_cfg/apps/payments/services/__init__.py +7 -1
  22. django_cfg/apps/payments/services/core/balance_service.py +14 -16
  23. django_cfg/apps/payments/services/core/fallback_service.py +432 -0
  24. django_cfg/apps/payments/services/core/payment_service.py +212 -29
  25. django_cfg/apps/payments/services/core/subscription_service.py +15 -17
  26. django_cfg/apps/payments/services/internal_types.py +31 -0
  27. django_cfg/apps/payments/services/monitoring/__init__.py +22 -0
  28. django_cfg/apps/payments/services/monitoring/api_schemas.py +222 -0
  29. django_cfg/apps/payments/services/monitoring/provider_health.py +372 -0
  30. django_cfg/apps/payments/services/providers/__init__.py +3 -0
  31. django_cfg/apps/payments/services/providers/cryptapi.py +14 -3
  32. django_cfg/apps/payments/services/providers/cryptomus.py +310 -0
  33. django_cfg/apps/payments/services/providers/registry.py +4 -0
  34. django_cfg/apps/payments/services/security/__init__.py +34 -0
  35. django_cfg/apps/payments/services/security/error_handler.py +637 -0
  36. django_cfg/apps/payments/services/security/payment_notifications.py +342 -0
  37. django_cfg/apps/payments/services/security/webhook_validator.py +475 -0
  38. django_cfg/apps/payments/signals/api_key_signals.py +10 -0
  39. django_cfg/apps/payments/signals/payment_signals.py +3 -2
  40. django_cfg/apps/payments/tasks/__init__.py +12 -0
  41. django_cfg/apps/payments/tasks/webhook_processing.py +177 -0
  42. django_cfg/apps/payments/utils/__init__.py +7 -4
  43. django_cfg/apps/payments/utils/billing_utils.py +342 -0
  44. django_cfg/apps/payments/utils/config_utils.py +2 -0
  45. django_cfg/apps/payments/views/payment_views.py +40 -2
  46. django_cfg/apps/payments/views/webhook_views.py +266 -0
  47. django_cfg/apps/payments/viewsets.py +65 -0
  48. django_cfg/cli/README.md +2 -2
  49. django_cfg/cli/commands/create_project.py +1 -1
  50. django_cfg/cli/commands/info.py +1 -1
  51. django_cfg/cli/main.py +1 -1
  52. django_cfg/cli/utils.py +5 -5
  53. django_cfg/core/config.py +18 -4
  54. django_cfg/models/payments.py +547 -0
  55. django_cfg/models/tasks.py +51 -2
  56. django_cfg/modules/base.py +11 -5
  57. django_cfg/modules/django_currency/README.md +104 -269
  58. django_cfg/modules/django_currency/__init__.py +99 -41
  59. django_cfg/modules/django_currency/clients/__init__.py +11 -0
  60. django_cfg/modules/django_currency/clients/coingecko_client.py +257 -0
  61. django_cfg/modules/django_currency/clients/yfinance_client.py +246 -0
  62. django_cfg/modules/django_currency/core/__init__.py +42 -0
  63. django_cfg/modules/django_currency/core/converter.py +169 -0
  64. django_cfg/modules/django_currency/core/exceptions.py +28 -0
  65. django_cfg/modules/django_currency/core/models.py +54 -0
  66. django_cfg/modules/django_currency/database/__init__.py +25 -0
  67. django_cfg/modules/django_currency/database/database_loader.py +507 -0
  68. django_cfg/modules/django_currency/utils/__init__.py +9 -0
  69. django_cfg/modules/django_currency/utils/cache.py +92 -0
  70. django_cfg/registry/core.py +10 -0
  71. django_cfg/template_archive/__init__.py +0 -0
  72. django_cfg/template_archive/django_sample.zip +0 -0
  73. {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.dist-info}/METADATA +10 -6
  74. {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.dist-info}/RECORD +77 -51
  75. django_cfg/apps/agents/examples/__init__.py +0 -3
  76. django_cfg/apps/agents/examples/simple_example.py +0 -161
  77. django_cfg/apps/knowbase/examples/__init__.py +0 -3
  78. django_cfg/apps/knowbase/examples/external_data_usage.py +0 -191
  79. django_cfg/apps/knowbase/mixins/examples/vehicle_model_example.py +0 -199
  80. django_cfg/modules/django_currency/cache.py +0 -430
  81. django_cfg/modules/django_currency/converter.py +0 -324
  82. django_cfg/modules/django_currency/service.py +0 -277
  83. {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.dist-info}/WHEEL +0 -0
  84. {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.dist-info}/entry_points.txt +0 -0
  85. {django_cfg-1.2.23.dist-info → django_cfg-1.2.27.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
- """