django-cfg 1.3.7__py3-none-any.whl → 1.3.9__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 (251) hide show
  1. django_cfg/__init__.py +1 -1
  2. django_cfg/apps/accounts/admin/__init__.py +24 -8
  3. django_cfg/apps/accounts/admin/activity_admin.py +146 -0
  4. django_cfg/apps/accounts/admin/filters.py +98 -22
  5. django_cfg/apps/accounts/admin/group_admin.py +86 -0
  6. django_cfg/apps/accounts/admin/inlines.py +42 -13
  7. django_cfg/apps/accounts/admin/otp_admin.py +115 -0
  8. django_cfg/apps/accounts/admin/registration_admin.py +173 -0
  9. django_cfg/apps/accounts/admin/resources.py +123 -19
  10. django_cfg/apps/accounts/admin/twilio_admin.py +327 -0
  11. django_cfg/apps/accounts/admin/user_admin.py +362 -0
  12. django_cfg/apps/agents/admin/__init__.py +17 -4
  13. django_cfg/apps/agents/admin/execution_admin.py +204 -183
  14. django_cfg/apps/agents/admin/registry_admin.py +230 -255
  15. django_cfg/apps/agents/admin/toolsets_admin.py +274 -321
  16. django_cfg/apps/agents/core/__init__.py +1 -1
  17. django_cfg/apps/agents/core/django_agent.py +221 -0
  18. django_cfg/apps/agents/core/exceptions.py +14 -0
  19. django_cfg/apps/agents/core/orchestrator.py +18 -3
  20. django_cfg/apps/knowbase/admin/__init__.py +1 -1
  21. django_cfg/apps/knowbase/admin/archive_admin.py +352 -640
  22. django_cfg/apps/knowbase/admin/chat_admin.py +258 -192
  23. django_cfg/apps/knowbase/admin/document_admin.py +269 -262
  24. django_cfg/apps/knowbase/admin/external_data_admin.py +271 -489
  25. django_cfg/apps/knowbase/config/settings.py +21 -4
  26. django_cfg/apps/knowbase/views/chat_views.py +3 -0
  27. django_cfg/apps/leads/admin/__init__.py +3 -1
  28. django_cfg/apps/leads/admin/leads_admin.py +235 -35
  29. django_cfg/apps/maintenance/admin/__init__.py +2 -2
  30. django_cfg/apps/maintenance/admin/api_key_admin.py +125 -63
  31. django_cfg/apps/maintenance/admin/log_admin.py +143 -61
  32. django_cfg/apps/maintenance/admin/scheduled_admin.py +212 -301
  33. django_cfg/apps/maintenance/admin/site_admin.py +213 -352
  34. django_cfg/apps/newsletter/admin/__init__.py +29 -2
  35. django_cfg/apps/newsletter/admin/newsletter_admin.py +531 -193
  36. django_cfg/apps/payments/admin/__init__.py +18 -27
  37. django_cfg/apps/payments/admin/api_keys_admin.py +179 -546
  38. django_cfg/apps/payments/admin/balance_admin.py +166 -632
  39. django_cfg/apps/payments/admin/currencies_admin.py +235 -607
  40. django_cfg/apps/payments/admin/endpoint_groups_admin.py +127 -0
  41. django_cfg/apps/payments/admin/filters.py +83 -3
  42. django_cfg/apps/payments/admin/networks_admin.py +258 -0
  43. django_cfg/apps/payments/admin/payments_admin.py +171 -461
  44. django_cfg/apps/payments/admin/subscriptions_admin.py +119 -636
  45. django_cfg/apps/payments/admin/tariffs_admin.py +248 -0
  46. django_cfg/apps/payments/admin_interface/serializers/payment_serializers.py +105 -34
  47. django_cfg/apps/payments/admin_interface/templates/payments/payment_form.html +12 -16
  48. django_cfg/apps/payments/admin_interface/views/__init__.py +2 -0
  49. django_cfg/apps/payments/admin_interface/views/api/webhook_admin.py +13 -18
  50. django_cfg/apps/payments/management/commands/manage_currencies.py +236 -274
  51. django_cfg/apps/payments/management/commands/manage_providers.py +4 -1
  52. django_cfg/apps/payments/middleware/api_access.py +32 -6
  53. django_cfg/apps/payments/migrations/0002_currency_usd_rate_currency_usd_rate_updated_at.py +26 -0
  54. django_cfg/apps/payments/migrations/0003_remove_provider_currency_fields.py +28 -0
  55. django_cfg/apps/payments/migrations/0004_add_reserved_usd_field.py +30 -0
  56. django_cfg/apps/payments/models/balance.py +12 -0
  57. django_cfg/apps/payments/models/currencies.py +106 -32
  58. django_cfg/apps/payments/models/managers/currency_managers.py +65 -0
  59. django_cfg/apps/payments/services/core/currency_service.py +35 -28
  60. django_cfg/apps/payments/services/core/payment_service.py +1 -1
  61. django_cfg/apps/payments/services/providers/__init__.py +3 -0
  62. django_cfg/apps/payments/services/providers/base.py +95 -39
  63. django_cfg/apps/payments/services/providers/models/__init__.py +40 -0
  64. django_cfg/apps/payments/services/providers/models/base.py +122 -0
  65. django_cfg/apps/payments/services/providers/models/providers.py +87 -0
  66. django_cfg/apps/payments/services/providers/models/universal.py +48 -0
  67. django_cfg/apps/payments/services/providers/nowpayments/__init__.py +31 -0
  68. django_cfg/apps/payments/services/providers/nowpayments/config.py +70 -0
  69. django_cfg/apps/payments/services/providers/nowpayments/models.py +150 -0
  70. django_cfg/apps/payments/services/providers/nowpayments/parsers.py +879 -0
  71. django_cfg/apps/payments/services/providers/{nowpayments.py → nowpayments/provider.py} +240 -209
  72. django_cfg/apps/payments/services/providers/nowpayments/sync.py +196 -0
  73. django_cfg/apps/payments/services/providers/registry.py +4 -32
  74. django_cfg/apps/payments/services/providers/sync_service.py +277 -0
  75. django_cfg/apps/payments/static/payments/js/api-client.js +23 -5
  76. django_cfg/apps/payments/static/payments/js/payment-form.js +65 -8
  77. django_cfg/apps/payments/tasks/__init__.py +39 -0
  78. django_cfg/apps/payments/tasks/types.py +73 -0
  79. django_cfg/apps/payments/tasks/usage_tracking.py +308 -0
  80. django_cfg/apps/payments/templates/admin/payments/_components/dashboard_header.html +23 -0
  81. django_cfg/apps/payments/templates/admin/payments/_components/stats_card.html +25 -0
  82. django_cfg/apps/payments/templates/admin/payments/_components/stats_grid.html +16 -0
  83. django_cfg/apps/payments/templates/admin/payments/apikey/change_list.html +39 -0
  84. django_cfg/apps/payments/templates/admin/payments/balance/change_list.html +50 -0
  85. django_cfg/apps/payments/templates/admin/payments/currency/change_list.html +40 -0
  86. django_cfg/apps/payments/templates/admin/payments/payment/change_list.html +48 -0
  87. django_cfg/apps/payments/templates/admin/payments/subscription/change_list.html +48 -0
  88. django_cfg/apps/payments/urls_admin.py +1 -1
  89. django_cfg/apps/payments/views/api/currencies.py +5 -5
  90. django_cfg/apps/payments/views/overview/services.py +2 -2
  91. django_cfg/apps/payments/views/serializers/currencies.py +4 -3
  92. django_cfg/apps/support/admin/__init__.py +10 -1
  93. django_cfg/apps/support/admin/support_admin.py +338 -141
  94. django_cfg/apps/tasks/admin/__init__.py +11 -0
  95. django_cfg/apps/tasks/admin/tasks_admin.py +430 -0
  96. django_cfg/config.py +1 -1
  97. django_cfg/core/config.py +10 -5
  98. django_cfg/core/generation.py +1 -1
  99. django_cfg/management/commands/__init__.py +13 -1
  100. django_cfg/management/commands/app_agent_diagnose.py +470 -0
  101. django_cfg/management/commands/app_agent_generate.py +342 -0
  102. django_cfg/management/commands/app_agent_info.py +308 -0
  103. django_cfg/management/commands/migrate_all.py +9 -3
  104. django_cfg/management/commands/migrator.py +11 -6
  105. django_cfg/management/commands/rundramatiq.py +3 -2
  106. django_cfg/middleware/__init__.py +0 -2
  107. django_cfg/models/api_keys.py +115 -0
  108. django_cfg/modules/django_admin/__init__.py +64 -0
  109. django_cfg/modules/django_admin/decorators/__init__.py +13 -0
  110. django_cfg/modules/django_admin/decorators/actions.py +106 -0
  111. django_cfg/modules/django_admin/decorators/display.py +106 -0
  112. django_cfg/modules/django_admin/mixins/__init__.py +14 -0
  113. django_cfg/modules/django_admin/mixins/display_mixin.py +81 -0
  114. django_cfg/modules/django_admin/mixins/optimization_mixin.py +41 -0
  115. django_cfg/modules/django_admin/mixins/standalone_actions_mixin.py +202 -0
  116. django_cfg/modules/django_admin/models/__init__.py +20 -0
  117. django_cfg/modules/django_admin/models/action_models.py +33 -0
  118. django_cfg/modules/django_admin/models/badge_models.py +20 -0
  119. django_cfg/modules/django_admin/models/base.py +26 -0
  120. django_cfg/modules/django_admin/models/display_models.py +31 -0
  121. django_cfg/modules/django_admin/utils/badges.py +159 -0
  122. django_cfg/modules/django_admin/utils/displays.py +247 -0
  123. django_cfg/modules/django_app_agent/__init__.py +87 -0
  124. django_cfg/modules/django_app_agent/agents/__init__.py +40 -0
  125. django_cfg/modules/django_app_agent/agents/base/__init__.py +24 -0
  126. django_cfg/modules/django_app_agent/agents/base/agent.py +354 -0
  127. django_cfg/modules/django_app_agent/agents/base/context.py +236 -0
  128. django_cfg/modules/django_app_agent/agents/base/executor.py +430 -0
  129. django_cfg/modules/django_app_agent/agents/generation/__init__.py +12 -0
  130. django_cfg/modules/django_app_agent/agents/generation/app_generator/__init__.py +15 -0
  131. django_cfg/modules/django_app_agent/agents/generation/app_generator/config_validator.py +147 -0
  132. django_cfg/modules/django_app_agent/agents/generation/app_generator/main.py +99 -0
  133. django_cfg/modules/django_app_agent/agents/generation/app_generator/models.py +32 -0
  134. django_cfg/modules/django_app_agent/agents/generation/app_generator/prompt_manager.py +290 -0
  135. django_cfg/modules/django_app_agent/agents/interfaces.py +376 -0
  136. django_cfg/modules/django_app_agent/core/__init__.py +33 -0
  137. django_cfg/modules/django_app_agent/core/config.py +300 -0
  138. django_cfg/modules/django_app_agent/core/exceptions.py +359 -0
  139. django_cfg/modules/django_app_agent/models/__init__.py +71 -0
  140. django_cfg/modules/django_app_agent/models/base.py +283 -0
  141. django_cfg/modules/django_app_agent/models/context.py +496 -0
  142. django_cfg/modules/django_app_agent/models/enums.py +481 -0
  143. django_cfg/modules/django_app_agent/models/requests.py +500 -0
  144. django_cfg/modules/django_app_agent/models/responses.py +585 -0
  145. django_cfg/modules/django_app_agent/pytest.ini +6 -0
  146. django_cfg/modules/django_app_agent/services/__init__.py +42 -0
  147. django_cfg/modules/django_app_agent/services/app_generator/__init__.py +30 -0
  148. django_cfg/modules/django_app_agent/services/app_generator/ai_integration.py +133 -0
  149. django_cfg/modules/django_app_agent/services/app_generator/context.py +40 -0
  150. django_cfg/modules/django_app_agent/services/app_generator/main.py +202 -0
  151. django_cfg/modules/django_app_agent/services/app_generator/structure.py +316 -0
  152. django_cfg/modules/django_app_agent/services/app_generator/validation.py +125 -0
  153. django_cfg/modules/django_app_agent/services/base.py +437 -0
  154. django_cfg/modules/django_app_agent/services/context_builder/__init__.py +34 -0
  155. django_cfg/modules/django_app_agent/services/context_builder/code_extractor.py +141 -0
  156. django_cfg/modules/django_app_agent/services/context_builder/context_generator.py +276 -0
  157. django_cfg/modules/django_app_agent/services/context_builder/main.py +272 -0
  158. django_cfg/modules/django_app_agent/services/context_builder/models.py +40 -0
  159. django_cfg/modules/django_app_agent/services/context_builder/pattern_analyzer.py +85 -0
  160. django_cfg/modules/django_app_agent/services/project_scanner/__init__.py +31 -0
  161. django_cfg/modules/django_app_agent/services/project_scanner/app_discovery.py +311 -0
  162. django_cfg/modules/django_app_agent/services/project_scanner/main.py +221 -0
  163. django_cfg/modules/django_app_agent/services/project_scanner/models.py +59 -0
  164. django_cfg/modules/django_app_agent/services/project_scanner/pattern_detection.py +94 -0
  165. django_cfg/modules/django_app_agent/services/questioning_service/__init__.py +28 -0
  166. django_cfg/modules/django_app_agent/services/questioning_service/main.py +273 -0
  167. django_cfg/modules/django_app_agent/services/questioning_service/models.py +111 -0
  168. django_cfg/modules/django_app_agent/services/questioning_service/question_generator.py +251 -0
  169. django_cfg/modules/django_app_agent/services/questioning_service/response_processor.py +347 -0
  170. django_cfg/modules/django_app_agent/services/questioning_service/session_manager.py +356 -0
  171. django_cfg/modules/django_app_agent/services/report_service.py +332 -0
  172. django_cfg/modules/django_app_agent/services/template_manager/__init__.py +18 -0
  173. django_cfg/modules/django_app_agent/services/template_manager/jinja_engine.py +236 -0
  174. django_cfg/modules/django_app_agent/services/template_manager/main.py +159 -0
  175. django_cfg/modules/django_app_agent/services/template_manager/models.py +36 -0
  176. django_cfg/modules/django_app_agent/services/template_manager/template_loader.py +100 -0
  177. django_cfg/modules/django_app_agent/services/template_manager/templates/admin.py.j2 +105 -0
  178. django_cfg/modules/django_app_agent/services/template_manager/templates/apps.py.j2 +31 -0
  179. django_cfg/modules/django_app_agent/services/template_manager/templates/cfg_config.py.j2 +44 -0
  180. django_cfg/modules/django_app_agent/services/template_manager/templates/cfg_module.py.j2 +81 -0
  181. django_cfg/modules/django_app_agent/services/template_manager/templates/forms.py.j2 +107 -0
  182. django_cfg/modules/django_app_agent/services/template_manager/templates/models.py.j2 +139 -0
  183. django_cfg/modules/django_app_agent/services/template_manager/templates/serializers.py.j2 +91 -0
  184. django_cfg/modules/django_app_agent/services/template_manager/templates/tests.py.j2 +195 -0
  185. django_cfg/modules/django_app_agent/services/template_manager/templates/urls.py.j2 +35 -0
  186. django_cfg/modules/django_app_agent/services/template_manager/templates/views.py.j2 +211 -0
  187. django_cfg/modules/django_app_agent/services/template_manager/variable_processor.py +200 -0
  188. django_cfg/modules/django_app_agent/services/validation_service/__init__.py +25 -0
  189. django_cfg/modules/django_app_agent/services/validation_service/django_validator.py +333 -0
  190. django_cfg/modules/django_app_agent/services/validation_service/main.py +242 -0
  191. django_cfg/modules/django_app_agent/services/validation_service/models.py +66 -0
  192. django_cfg/modules/django_app_agent/services/validation_service/quality_validator.py +352 -0
  193. django_cfg/modules/django_app_agent/services/validation_service/security_validator.py +272 -0
  194. django_cfg/modules/django_app_agent/services/validation_service/syntax_validator.py +203 -0
  195. django_cfg/modules/django_app_agent/ui/__init__.py +25 -0
  196. django_cfg/modules/django_app_agent/ui/cli.py +419 -0
  197. django_cfg/modules/django_app_agent/ui/rich_components.py +622 -0
  198. django_cfg/modules/django_app_agent/utils/__init__.py +38 -0
  199. django_cfg/modules/django_app_agent/utils/logging.py +360 -0
  200. django_cfg/modules/django_app_agent/utils/validation.py +417 -0
  201. django_cfg/modules/django_currency/__init__.py +2 -2
  202. django_cfg/modules/django_currency/clients/__init__.py +2 -2
  203. django_cfg/modules/django_currency/clients/hybrid_client.py +587 -0
  204. django_cfg/modules/django_currency/core/converter.py +12 -12
  205. django_cfg/modules/django_currency/database/__init__.py +2 -2
  206. django_cfg/modules/django_currency/database/database_loader.py +93 -42
  207. django_cfg/modules/django_llm/llm/client.py +10 -2
  208. django_cfg/modules/django_unfold/callbacks/actions.py +1 -1
  209. django_cfg/modules/django_unfold/callbacks/statistics.py +1 -1
  210. django_cfg/modules/django_unfold/dashboard.py +14 -13
  211. django_cfg/modules/django_unfold/models/config.py +1 -1
  212. django_cfg/registry/core.py +3 -0
  213. django_cfg/registry/third_party.py +2 -2
  214. django_cfg/template_archive/django_sample.zip +0 -0
  215. {django_cfg-1.3.7.dist-info → django_cfg-1.3.9.dist-info}/METADATA +2 -1
  216. {django_cfg-1.3.7.dist-info → django_cfg-1.3.9.dist-info}/RECORD +223 -117
  217. django_cfg/apps/accounts/admin/activity.py +0 -96
  218. django_cfg/apps/accounts/admin/group.py +0 -17
  219. django_cfg/apps/accounts/admin/otp.py +0 -59
  220. django_cfg/apps/accounts/admin/registration_source.py +0 -97
  221. django_cfg/apps/accounts/admin/twilio_response.py +0 -227
  222. django_cfg/apps/accounts/admin/user.py +0 -300
  223. django_cfg/apps/agents/core/agent.py +0 -281
  224. django_cfg/apps/payments/admin_interface/old/payments/base.html +0 -175
  225. django_cfg/apps/payments/admin_interface/old/payments/components/dev_tool_card.html +0 -125
  226. django_cfg/apps/payments/admin_interface/old/payments/components/loading_spinner.html +0 -16
  227. django_cfg/apps/payments/admin_interface/old/payments/components/ngrok_status_card.html +0 -113
  228. django_cfg/apps/payments/admin_interface/old/payments/components/notification.html +0 -27
  229. django_cfg/apps/payments/admin_interface/old/payments/components/provider_card.html +0 -86
  230. django_cfg/apps/payments/admin_interface/old/payments/components/status_card.html +0 -35
  231. django_cfg/apps/payments/admin_interface/old/payments/currency_converter.html +0 -382
  232. django_cfg/apps/payments/admin_interface/old/payments/payment_dashboard.html +0 -309
  233. django_cfg/apps/payments/admin_interface/old/payments/payment_form.html +0 -303
  234. django_cfg/apps/payments/admin_interface/old/payments/payment_list.html +0 -382
  235. django_cfg/apps/payments/admin_interface/old/payments/payment_status.html +0 -500
  236. django_cfg/apps/payments/admin_interface/old/payments/webhook_dashboard.html +0 -518
  237. django_cfg/apps/payments/admin_interface/old/static/payments/css/components.css +0 -619
  238. django_cfg/apps/payments/admin_interface/old/static/payments/css/dashboard.css +0 -188
  239. django_cfg/apps/payments/admin_interface/old/static/payments/js/components.js +0 -545
  240. django_cfg/apps/payments/admin_interface/old/static/payments/js/ngrok-status.js +0 -163
  241. django_cfg/apps/payments/admin_interface/old/static/payments/js/utils.js +0 -412
  242. django_cfg/apps/tasks/admin.py +0 -320
  243. django_cfg/middleware/static_nocache.py +0 -55
  244. django_cfg/modules/django_currency/clients/yahoo_client.py +0 -157
  245. /django_cfg/modules/{django_unfold → django_admin}/icons/README.md +0 -0
  246. /django_cfg/modules/{django_unfold → django_admin}/icons/__init__.py +0 -0
  247. /django_cfg/modules/{django_unfold → django_admin}/icons/constants.py +0 -0
  248. /django_cfg/modules/{django_unfold → django_admin}/icons/generate_icons.py +0 -0
  249. {django_cfg-1.3.7.dist-info → django_cfg-1.3.9.dist-info}/WHEEL +0 -0
  250. {django_cfg-1.3.7.dist-info → django_cfg-1.3.9.dist-info}/entry_points.txt +0 -0
  251. {django_cfg-1.3.7.dist-info → django_cfg-1.3.9.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,133 @@
1
+ """
2
+ AI Integration Module for Django App Agent Generation.
3
+
4
+ This module handles integration with AI agents for intelligent
5
+ code generation based on user requirements and project context.
6
+ """
7
+
8
+ from typing import List, Dict, Any
9
+ from pathlib import Path
10
+
11
+ from ..base import ServiceDependencies
12
+ from ...core.config import AgentConfig
13
+ from ...models.responses import GeneratedFile
14
+ from ...models.enums import AppFeature, FileType
15
+ from ...agents.generation.app_generator import AppGeneratorAgent, FileGenerationRequest
16
+ from .context import GenerationContext
17
+
18
+
19
+ class AIGenerationManager:
20
+ """Manages AI-powered code generation process."""
21
+
22
+ def __init__(self, config: AgentConfig):
23
+ """Initialize AI generation manager."""
24
+ self.config = config
25
+
26
+ async def run_ai_generation(
27
+ self,
28
+ context: GenerationContext,
29
+ dependencies: ServiceDependencies
30
+ ) -> None:
31
+ """Run AI agents for intelligent code generation."""
32
+ dependencies.log_operation("Running AI generation agents")
33
+
34
+ try:
35
+ # Create AI agent
36
+ print("🔍 Creating AI agent with config...")
37
+ print(f"🔍 Config type: {type(self.config)}")
38
+ try:
39
+ ai_agent = AppGeneratorAgent(self.config)
40
+ print("✅ AI agent created successfully")
41
+ except Exception as e:
42
+ print(f"❌ Failed to create AI agent: {e}")
43
+ print(f"❌ Exception type: {type(e)}")
44
+ import traceback
45
+ print(f"❌ Traceback: {traceback.format_exc()}")
46
+ raise
47
+
48
+ # Generate files for each requested feature using AI
49
+ generated_files = []
50
+ for feature in context.request.features:
51
+ try:
52
+ # Create request for this feature
53
+ file_request = FileGenerationRequest(
54
+ app_name=context.request.app_name,
55
+ description=context.request.description,
56
+ feature=feature,
57
+ app_type=context.request.app_type,
58
+ complexity=context.request.complexity
59
+ )
60
+
61
+ # Generate file using AI
62
+ ai_response = await ai_agent.generate_file(file_request)
63
+
64
+ # Create file path
65
+ file_path = context.app_directory / ai_response.filename
66
+
67
+ # Create generated file record
68
+ generated_file = GeneratedFile(
69
+ relative_path=str(file_path.relative_to(context.target_directory)),
70
+ absolute_path=file_path,
71
+ content=ai_response.content,
72
+ line_count=len(ai_response.content.split('\n')),
73
+ file_type=self._get_file_type(ai_response.filename),
74
+ type_safety_score=8.5, # AI-generated files typically have good type safety
75
+ complexity_score=6.0, # AI-generated files can be moderately complex
76
+ description=ai_response.description
77
+ )
78
+
79
+ # Write file to disk
80
+ file_path.parent.mkdir(parents=True, exist_ok=True)
81
+ file_path.write_text(ai_response.content)
82
+
83
+ # Add to context
84
+ context.add_generated_file(generated_file)
85
+ generated_files.append(ai_response)
86
+
87
+ dependencies.log_operation(f"Generated {feature.value} file", filename=ai_response.filename)
88
+
89
+ except Exception as e:
90
+ dependencies.log_error(f"Failed to generate {feature.value} with AI", e)
91
+ # Continue with other features
92
+ continue
93
+
94
+ # Record AI generation results
95
+ context.agent_outputs["generation"] = {
96
+ "status": "completed",
97
+ "message": f"AI generation completed successfully for {len(generated_files)} features",
98
+ "ai_files_count": len(generated_files),
99
+ "features_generated": [gf.filename for gf in generated_files],
100
+ "recommendations": [f"Generated {gf.filename} for {context.request.app_name}" for gf in generated_files]
101
+ }
102
+
103
+ except Exception as e:
104
+ dependencies.log_error("AI generation failed", e)
105
+ context.agent_outputs["generation"] = {
106
+ "status": "error",
107
+ "message": f"Agent communication failed: {e}",
108
+ "recommendations": []
109
+ }
110
+
111
+ def _get_file_type(self, filename: str) -> FileType:
112
+ """Determine file type from filename."""
113
+ # Map specific Django files to their types
114
+ if filename == "__init__.py":
115
+ return FileType.INIT
116
+ elif filename == "models.py":
117
+ return FileType.MODEL
118
+ elif filename == "views.py":
119
+ return FileType.VIEW
120
+ elif filename == "admin.py":
121
+ return FileType.ADMIN
122
+ elif filename == "urls.py":
123
+ return FileType.URL
124
+ elif filename == "forms.py":
125
+ return FileType.FORM
126
+ elif filename == "tests.py":
127
+ return FileType.TEST
128
+ elif filename.endswith('.html'):
129
+ return FileType.TEMPLATE
130
+ elif filename.endswith('.py'):
131
+ return FileType.CONFIG # Default for other Python files
132
+ else:
133
+ return FileType.CONFIG # Default fallback
@@ -0,0 +1,40 @@
1
+ """
2
+ Generation Context for Django App Agent Module.
3
+
4
+ This module contains the GenerationContext class that manages state
5
+ and data throughout the application generation process.
6
+ """
7
+
8
+ from typing import List, Dict, Any
9
+ from pathlib import Path
10
+
11
+ from pydantic import BaseModel, Field, ConfigDict
12
+
13
+ from ...models.requests import AppGenerationRequest
14
+ from ...models.responses import GeneratedFile
15
+
16
+
17
+ class GenerationContext(BaseModel):
18
+ """Context for application generation process."""
19
+
20
+ model_config = ConfigDict(extra='forbid', validate_assignment=True)
21
+
22
+ request: AppGenerationRequest = Field(description="Original generation request")
23
+ target_directory: Path = Field(description="Target directory for generated app")
24
+ template_variables: Dict[str, Any] = Field(default_factory=dict, description="Template variables")
25
+ generated_files: List[GeneratedFile] = Field(default_factory=list, description="Generated files")
26
+ validation_results: Dict[str, Any] = Field(default_factory=dict, description="Validation results")
27
+ agent_outputs: Dict[str, Any] = Field(default_factory=dict, description="AI agent outputs")
28
+
29
+ @property
30
+ def app_directory(self) -> Path:
31
+ """Get the application directory path."""
32
+ return self.target_directory / self.request.app_name
33
+
34
+ def add_generated_file(self, file: GeneratedFile) -> None:
35
+ """Add a generated file to the context."""
36
+ self.generated_files.append(file)
37
+
38
+ def get_files_by_type(self, file_type: str) -> List[GeneratedFile]:
39
+ """Get generated files by type."""
40
+ return [f for f in self.generated_files if f.file_type == file_type]
@@ -0,0 +1,202 @@
1
+ """
2
+ Main Application Generator Service for Django App Agent Module.
3
+
4
+ This service orchestrates the complete application generation process,
5
+ coordinating validation, structure creation, AI generation, and quality validation.
6
+ """
7
+
8
+ from typing import Dict, Any
9
+ from pathlib import Path
10
+ from datetime import datetime, timezone
11
+ import uuid
12
+
13
+ from ..base import BaseService, ServiceDependencies
14
+ from ...models.requests import AppGenerationRequest
15
+ from ...models.responses import AppGenerationResult, QualityMetrics, ValidationIssue
16
+ from ...models.enums import ValidationSeverity
17
+ from ...core.config import AgentConfig
18
+
19
+ from .context import GenerationContext
20
+ from .validation import GenerationValidator
21
+ from .structure import StructureGenerator
22
+ from .ai_integration import AIGenerationManager
23
+
24
+
25
+ class AppGeneratorService(BaseService[AppGenerationRequest, AppGenerationResult]):
26
+ """
27
+ Main service for generating Django applications with AI assistance.
28
+
29
+ This service coordinates the entire generation process:
30
+ 1. Validation of requirements and compatibility
31
+ 2. Basic structure creation
32
+ 3. AI-powered code generation
33
+ 4. Quality validation and metrics calculation
34
+ """
35
+
36
+ def __init__(self, config: AgentConfig):
37
+ """Initialize the application generator service."""
38
+ super().__init__("app_generator", config)
39
+ self.config = config
40
+
41
+ # Initialize sub-components
42
+ self.validator = GenerationValidator()
43
+ self.structure_generator = StructureGenerator()
44
+ self.ai_manager = AIGenerationManager(config)
45
+
46
+ async def process(
47
+ self,
48
+ request: AppGenerationRequest,
49
+ dependencies: ServiceDependencies
50
+ ) -> AppGenerationResult:
51
+ """
52
+ Process application generation request.
53
+
54
+ Args:
55
+ request: Application generation request
56
+ dependencies: Service dependencies for logging and operations
57
+
58
+ Returns:
59
+ AppGenerationResult with generation details and metrics
60
+ """
61
+ start_time = datetime.now(timezone.utc)
62
+ generation_id = str(uuid.uuid4())
63
+
64
+ try:
65
+ dependencies.log_operation(
66
+ f"Starting application generation for '{request.app_name}'",
67
+ app_name=request.app_name,
68
+ app_type=request.app_type.value,
69
+ features=[f.value for f in request.features]
70
+ )
71
+
72
+ # Create generation context
73
+ context = await self._create_generation_context(request, dependencies)
74
+
75
+ # Validate generation requirements
76
+ await self.validator.validate_generation_requirements(context, dependencies)
77
+
78
+ # Generate basic app structure
79
+ await self.structure_generator.generate_app_structure(context, dependencies)
80
+
81
+ # Generate feature files using templates (fallback)
82
+ await self.structure_generator.generate_feature_files(context, dependencies)
83
+
84
+ # Run AI agents for intelligent code generation
85
+ await self.ai_manager.run_ai_generation(context, dependencies)
86
+
87
+ # Validate generated code
88
+ quality_metrics = await self.validator.validate_generated_code(context, dependencies)
89
+
90
+ # Calculate execution time
91
+ end_time = datetime.now(timezone.utc)
92
+ execution_time = (end_time - start_time).total_seconds()
93
+
94
+ # Extract AI dialogue for reporting
95
+ ai_dialogue = self._extract_ai_dialogue(context)
96
+
97
+ # Create successful result
98
+ return AppGenerationResult(
99
+ app_name=request.app_name,
100
+ generation_id=generation_id,
101
+ success=True,
102
+ total_execution_time_seconds=execution_time,
103
+ files_count=len(context.generated_files),
104
+ lines_of_code=sum(len(f.content.splitlines()) for f in context.generated_files),
105
+ quality_score=quality_metrics.overall_score,
106
+ type_safety_score=quality_metrics.type_safety_score,
107
+ pattern_consistency_score=quality_metrics.pattern_consistency,
108
+ test_coverage_percentage=quality_metrics.test_coverage,
109
+ integration_successful=True,
110
+ generated_files=context.generated_files,
111
+ patterns_followed=["django_best_practices", "pep8", "type_hints"],
112
+ dependencies_resolved=["django", "django_cfg"],
113
+ errors=[],
114
+ warnings=[],
115
+ report_directory=context.target_directory / request.app_name / "@report",
116
+ generation_report_path=context.target_directory / request.app_name / "@report" / "generation_report.md"
117
+ )
118
+
119
+ except Exception as e:
120
+ # Calculate execution time even on failure
121
+ end_time = datetime.now(timezone.utc)
122
+ execution_time = (end_time - start_time).total_seconds()
123
+
124
+ # Create error result
125
+ error_message = str(e)
126
+ if len(error_message) > 500:
127
+ error_message = error_message[:497] + "..."
128
+
129
+ error_issue = ValidationIssue(
130
+ file_path="generation_process",
131
+ line_number=1,
132
+ severity=ValidationSeverity.ERROR,
133
+ message=error_message,
134
+ rule_id="generation_error"
135
+ )
136
+
137
+ return AppGenerationResult(
138
+ app_name=request.app_name if 'request' in locals() else "unknown",
139
+ generation_id=generation_id,
140
+ success=False,
141
+ total_execution_time_seconds=execution_time,
142
+ files_count=0,
143
+ lines_of_code=0,
144
+ quality_score=0.0,
145
+ type_safety_score=0.0,
146
+ pattern_consistency_score=0.0,
147
+ test_coverage_percentage=0.0,
148
+ integration_successful=False,
149
+ generated_files=[],
150
+ patterns_followed=[],
151
+ dependencies_resolved=[],
152
+ errors=[error_issue],
153
+ warnings=[],
154
+ report_directory=Path("/tmp"),
155
+ generation_report_path=Path("/tmp/error.md")
156
+ )
157
+
158
+ async def _create_generation_context(
159
+ self,
160
+ request: AppGenerationRequest,
161
+ dependencies: ServiceDependencies
162
+ ) -> GenerationContext:
163
+ """Create generation context from request."""
164
+ # Determine target directory
165
+ if request.output_directory:
166
+ target_directory = Path(request.output_directory)
167
+ else:
168
+ target_directory = Path.cwd() / "apps"
169
+
170
+ # Create template variables
171
+ template_variables = {
172
+ "app_name": request.app_name,
173
+ "description": request.description,
174
+ "app_type": request.app_type.value,
175
+ "complexity": request.complexity.value,
176
+ "features": [f.value for f in request.features],
177
+ "timestamp": datetime.now(timezone.utc).isoformat()
178
+ }
179
+
180
+ return GenerationContext(
181
+ request=request,
182
+ target_directory=target_directory,
183
+ template_variables=template_variables
184
+ )
185
+
186
+ def _extract_ai_dialogue(self, context: GenerationContext) -> list[Dict[str, Any]]:
187
+ """Extract AI dialogue from generation context."""
188
+ dialogue = []
189
+
190
+ # Extract from agent outputs
191
+ generation_output = context.agent_outputs.get("generation", {})
192
+ if generation_output:
193
+ dialogue.append({
194
+ "agent": "generation_agent",
195
+ "timestamp": datetime.now(timezone.utc).isoformat(),
196
+ "message": generation_output.get("message", ""),
197
+ "status": generation_output.get("status", "unknown"),
198
+ "files_generated": generation_output.get("ai_files_count", 0),
199
+ "recommendations": generation_output.get("recommendations", [])
200
+ })
201
+
202
+ return dialogue
@@ -0,0 +1,316 @@
1
+ """
2
+ Structure Generator for Django App Agent Module.
3
+
4
+ This module handles creation of basic application structure
5
+ and feature-specific files using templates.
6
+ """
7
+
8
+ from typing import Dict, List
9
+ from pathlib import Path
10
+
11
+ from ..base import ServiceDependencies
12
+ from ...core.exceptions import FileSystemError
13
+ from ...models.responses import GeneratedFile
14
+ from ...models.enums import AppFeature, FileType
15
+ from .context import GenerationContext
16
+
17
+
18
+ class StructureGenerator:
19
+ """Handles generation of application structure and files."""
20
+
21
+ def __init__(self):
22
+ """Initialize structure generator with feature file mappings."""
23
+ self.feature_files: Dict[AppFeature, List[str]] = {
24
+ AppFeature.MODELS: ["models.py"],
25
+ AppFeature.VIEWS: ["views.py"],
26
+ AppFeature.URLS: ["urls.py"],
27
+ AppFeature.ADMIN: ["admin.py"],
28
+ AppFeature.FORMS: ["forms.py"],
29
+ AppFeature.TESTS: ["tests.py"],
30
+ AppFeature.API: ["serializers.py", "viewsets.py"],
31
+ AppFeature.SERIALIZERS: ["serializers.py"],
32
+ AppFeature.VIEWSETS: ["viewsets.py"],
33
+ AppFeature.FILTERS: ["filters.py"],
34
+ AppFeature.PAGINATION: ["pagination.py"],
35
+ AppFeature.SECURITY: ["security.py"],
36
+ AppFeature.AUTHENTICATION: ["authentication.py"],
37
+ AppFeature.TASKS: ["tasks.py"],
38
+ AppFeature.DOCS: ["docs.py"],
39
+ AppFeature.SERVICES: ["services/"],
40
+ AppFeature.CFG_CONFIG: ["config.py"],
41
+ AppFeature.CFG_MODULES: ["modules/"],
42
+ }
43
+
44
+ async def generate_app_structure(
45
+ self,
46
+ context: GenerationContext,
47
+ dependencies: ServiceDependencies
48
+ ) -> None:
49
+ """Generate basic application directory structure."""
50
+ try:
51
+ # Create app directory
52
+ context.app_directory.mkdir(parents=True, exist_ok=True)
53
+
54
+ # Create basic structure
55
+ basic_dirs = ["migrations", "templates", "static", "tests"]
56
+ for dir_name in basic_dirs:
57
+ (context.app_directory / dir_name).mkdir(exist_ok=True)
58
+
59
+ # Create __init__.py
60
+ init_file = context.app_directory / "__init__.py"
61
+ init_content = f'"""Django app: {context.request.app_name}"""'
62
+
63
+ generated_file = GeneratedFile(
64
+ relative_path=str(init_file.relative_to(context.target_directory)),
65
+ absolute_path=init_file,
66
+ content=init_content,
67
+ line_count=len(init_content.split('\n')),
68
+ file_type=FileType.INIT,
69
+ type_safety_score=8.0,
70
+ complexity_score=2.0, # Simple __init__.py file
71
+ description="Application initialization file"
72
+ )
73
+
74
+ init_file.write_text(init_content)
75
+ context.add_generated_file(generated_file)
76
+
77
+ except Exception as e:
78
+ raise FileSystemError(
79
+ f"Failed to create app structure: {e}",
80
+ file_path=str(context.app_directory),
81
+ operation="create_app_structure"
82
+ )
83
+
84
+ async def generate_feature_files(
85
+ self,
86
+ context: GenerationContext,
87
+ dependencies: ServiceDependencies
88
+ ) -> None:
89
+ """Generate files for requested features."""
90
+ for feature in context.request.features:
91
+ await self.generate_feature(feature, context, dependencies)
92
+
93
+ async def generate_feature(
94
+ self,
95
+ feature: AppFeature,
96
+ context: GenerationContext,
97
+ dependencies: ServiceDependencies
98
+ ) -> None:
99
+ """Generate files for a specific feature."""
100
+ files_to_create = self.feature_files.get(feature, [])
101
+
102
+ for file_pattern in files_to_create:
103
+ if file_pattern.endswith("/"):
104
+ # Directory
105
+ dir_path = context.app_directory / file_pattern.rstrip("/")
106
+ dir_path.mkdir(parents=True, exist_ok=True)
107
+ else:
108
+ # File
109
+ await self.generate_feature_file(feature, file_pattern, context, dependencies)
110
+
111
+ async def generate_feature_file(
112
+ self,
113
+ feature: AppFeature,
114
+ filename: str,
115
+ context: GenerationContext,
116
+ dependencies: ServiceDependencies
117
+ ) -> None:
118
+ """Generate a specific feature file."""
119
+ file_path = context.app_directory / filename
120
+
121
+ # Generate basic template content
122
+ content = self.get_template_content(feature, filename, context)
123
+
124
+ # Create generated file record
125
+ generated_file = GeneratedFile(
126
+ relative_path=str(file_path.relative_to(context.target_directory)),
127
+ absolute_path=file_path,
128
+ content=content,
129
+ line_count=len(content.split('\n')),
130
+ file_type=self.get_file_type(filename),
131
+ type_safety_score=7.0, # Default score for generated files
132
+ complexity_score=5.0, # Moderate complexity for feature files
133
+ description=f"{feature.value} implementation file"
134
+ )
135
+
136
+ # Write file
137
+ file_path.parent.mkdir(parents=True, exist_ok=True)
138
+ file_path.write_text(content)
139
+
140
+ context.add_generated_file(generated_file)
141
+
142
+ def get_template_content(
143
+ self,
144
+ feature: AppFeature,
145
+ filename: str,
146
+ context: GenerationContext
147
+ ) -> str:
148
+ """Get template content for a feature file."""
149
+ app_name = context.request.app_name
150
+ description = context.request.description
151
+
152
+ templates = {
153
+ "models.py": f'''"""
154
+ Models for {app_name} application.
155
+
156
+ {description}
157
+ """
158
+
159
+ from django.db import models
160
+
161
+
162
+ class {app_name.title().replace('_', '')}Model(models.Model):
163
+ """Main model for {app_name} application."""
164
+
165
+ name = models.CharField(max_length=100, help_text="Name of the item")
166
+ description = models.TextField(blank=True, help_text="Description of the item")
167
+ created_at = models.DateTimeField(auto_now_add=True)
168
+ updated_at = models.DateTimeField(auto_now=True)
169
+
170
+ class Meta:
171
+ verbose_name = "{app_name.replace('_', ' ').title()}"
172
+ verbose_name_plural = "{app_name.replace('_', ' ').title()}s"
173
+ ordering = ['-created_at']
174
+
175
+ def __str__(self):
176
+ return self.name
177
+ ''',
178
+ "views.py": f'''"""
179
+ Views for {app_name} application.
180
+
181
+ {description}
182
+ """
183
+
184
+ from django.shortcuts import render
185
+ from django.views.generic import ListView, DetailView
186
+
187
+
188
+ class {app_name.title().replace('_', '')}ListView(ListView):
189
+ """List view for {app_name} items."""
190
+
191
+ template_name = '{app_name}/list.html'
192
+ context_object_name = 'items'
193
+ paginate_by = 10
194
+
195
+
196
+ class {app_name.title().replace('_', '')}DetailView(DetailView):
197
+ """Detail view for {app_name} items."""
198
+
199
+ template_name = '{app_name}/detail.html'
200
+ context_object_name = 'item'
201
+ ''',
202
+ "urls.py": f'''"""
203
+ URL configuration for {app_name} application.
204
+
205
+ {description}
206
+ """
207
+
208
+ from django.urls import path
209
+ from . import views
210
+
211
+ app_name = '{app_name}'
212
+
213
+ urlpatterns = [
214
+ path('', views.{app_name.title().replace('_', '')}ListView.as_view(), name='list'),
215
+ path('<int:pk>/', views.{app_name.title().replace('_', '')}DetailView.as_view(), name='detail'),
216
+ ]
217
+ ''',
218
+ "admin.py": f'''"""
219
+ Admin configuration for {app_name} application.
220
+
221
+ {description}
222
+ """
223
+
224
+ from django.contrib import admin
225
+ from .models import {app_name.title().replace('_', '')}Model
226
+
227
+
228
+ @admin.register({app_name.title().replace('_', '')}Model)
229
+ class {app_name.title().replace('_', '')}Admin(admin.ModelAdmin):
230
+ """Admin interface for {app_name} model."""
231
+
232
+ list_display = ['name', 'created_at', 'updated_at']
233
+ list_filter = ['created_at', 'updated_at']
234
+ search_fields = ['name', 'description']
235
+ readonly_fields = ['created_at', 'updated_at']
236
+ ''',
237
+ "forms.py": f'''"""
238
+ Forms for {app_name} application.
239
+
240
+ {description}
241
+ """
242
+
243
+ from django import forms
244
+ from .models import {app_name.title().replace('_', '')}Model
245
+
246
+
247
+ class {app_name.title().replace('_', '')}Form(forms.ModelForm):
248
+ """Form for {app_name} model."""
249
+
250
+ class Meta:
251
+ model = {app_name.title().replace('_', '')}Model
252
+ fields = ['name', 'description']
253
+ widgets = {{
254
+ 'description': forms.Textarea(attrs={{'rows': 4}}),
255
+ }}
256
+ ''',
257
+ "tests.py": f'''"""
258
+ Tests for {app_name} application.
259
+
260
+ {description}
261
+ """
262
+
263
+ from django.test import TestCase
264
+ from .models import {app_name.title().replace('_', '')}Model
265
+
266
+
267
+ class {app_name.title().replace('_', '')}TestCase(TestCase):
268
+ """Test cases for {app_name} application."""
269
+
270
+ def test_placeholder(self):
271
+ """Placeholder test."""
272
+ self.assertTrue(True)
273
+ ''',
274
+ "apps.py": f'''"""
275
+ App configuration for {app_name}.
276
+
277
+ {description}
278
+ """
279
+
280
+ from django.apps import AppConfig
281
+
282
+
283
+ class {app_name.title().replace('_', '')}Config(AppConfig):
284
+ """Configuration for {app_name} application."""
285
+
286
+ default_auto_field = 'django.db.models.BigAutoField'
287
+ name = '{app_name}'
288
+ verbose_name = '{app_name.replace("_", " ").title()}'
289
+ '''
290
+ }
291
+
292
+ return templates.get(filename, f"# {filename} for {app_name}\n# Generated by Django App Agent\n")
293
+
294
+ def get_file_type(self, filename: str) -> FileType:
295
+ """Determine file type from filename."""
296
+ # Map specific Django files to their types
297
+ if filename == "__init__.py":
298
+ return FileType.INIT
299
+ elif filename == "models.py":
300
+ return FileType.MODEL
301
+ elif filename == "views.py":
302
+ return FileType.VIEW
303
+ elif filename == "admin.py":
304
+ return FileType.ADMIN
305
+ elif filename == "urls.py":
306
+ return FileType.URL
307
+ elif filename == "forms.py":
308
+ return FileType.FORM
309
+ elif filename == "tests.py":
310
+ return FileType.TEST
311
+ elif filename.endswith('.html'):
312
+ return FileType.TEMPLATE
313
+ elif filename.endswith('.py'):
314
+ return FileType.CONFIG # Default for other Python files
315
+ else:
316
+ return FileType.CONFIG # Default fallback