# Django-CFG Apps Development Guide

Quick guide for AI agents developing apps in django-cfg.

---

## 🎯 Core Principles

### 1. App Registration
**All apps MUST be registered through:**
- `django_cfg/core/builders/apps_builder.py` - automatic `INSTALLED_APPS` registration
- `django_cfg/apps/urls.py` - automatic URL patterns registration
- **NEVER through** local project configs
 
**Example:**
```python
# django_cfg/core/builders/apps_builder.py
if app == "django.contrib.admin":
    apps.append("django_cfg.apps.system.accounts")
    apps.append("django_cfg.apps.system.totp")  # ✅ Correct

# django_cfg/apps/urls.py
urlpatterns = [
    path('cfg/2fa/', include('django_cfg.apps.system.totp.urls')),  # ✅ Correct
]
```

---

## 🛠 Technology Stack

### Required Patterns

#### **DRF (Django Rest Framework)**
- **Only:** `drf-spectacular` for OpenAPI
- **Only:** `drf-nested-routers` for nested routes
- **Only:** `GenericViewSet` + `@action` pattern
- **Forbidden:** Custom routers, ViewSets without Generic

**Example:**
```python
from rest_framework import viewsets
from rest_framework.decorators import action

class MyViewSet(viewsets.GenericViewSet):
    @action(detail=False, methods=['post'])
    def my_action(self, request):
        # ✅ Correct
        pass
```

#### **Django Admin**
- **Required:** `PydanticAdmin` + `AdminConfig` (declarative approach)
- **Documentation:** `../../solution/frontend/apps/docs/content/features/modules/django-admin/`
- **Forbidden:** Old style with `list_display`, `fieldsets` directly in class

**Example:**
```python
from django_cfg.modules.django_admin import AdminConfig, BadgeField
from django_cfg.modules.django_admin.base import PydanticAdmin

config = AdminConfig(
    model=MyModel,
    list_display=["field1", "field2"],
    display_fields=[
        BadgeField(name="status", label_map={"active": "success"}),
    ],
)

@admin.register(MyModel)
class MyModelAdmin(PydanticAdmin):
    config = config  # ✅ Correct
```

---

## 🧪 Testing Requirements

### Test Execution
```bash
# From django-cfg solution directory
cd ../../solution/django
poetry run python manage.py test django_cfg.apps.app_name.tests
```

### Test Coverage
**Required tests for each app:**
- ✅ **Models:** constraints, validations, methods
- ✅ **Services:** critical business logic
- ✅ **Security:** authentication, authorization, rate limiting

**Not required:**
- ❌ API endpoint tests (use `check_endpoints` command)
- ❌ View tests (covered by `check_endpoints`)
- ❌ Serializer tests (covered by integration)

**Example structure:**
```
app_name/
├── tests/
│   ├── __init__.py
│   ├── conftest.py        # Django test config
│   ├── test_models.py     # Model tests
│   └── test_services.py   # Service tests (critical!)
```

---

## 📚 Documentation Requirements

### When to Update Documentation
**Must update when:**
- ✅ Adding new app
- ✅ Changing API endpoints
- ✅ Changing configuration (AdminConfig, DjangoConfig)
- ✅ Adding new features

### Documentation Structure
```
app_name/
├── @docs/
│   ├── README.md           # Quick start + overview
│   ├── ARCHITECTURE.md     # Technical design
│   ├── API.md             # API endpoints reference
│   └── INTEGRATION.md     # Integration guide
└── README.md              # Main entry point
```

### Target Audience
**Documentation is written for:**
- 🎯 **Django-CFG package clients** (framework users)
- 🎯 **High-level description** (not implementation details)
- 🎯 **Examples-first approach** (usage examples)

---

## ✅ Checklist for New App

- [ ] Models created with proper constraints
- [ ] Services with critical business logic
- [ ] DRF serializers + views (GenericViewSet)
- [ ] URLs registered in `django_cfg/apps/urls.py`
- [ ] App added to `django_cfg/core/builders/apps_builder.py`
- [ ] Admin interface using `PydanticAdmin` + `AdminConfig`
- [ ] Admin added to navigation (`django_cfg/modules/django_unfold/navigation.py`)
- [ ] Tests written (models + services)
- [ ] Migrations created and applied:
  ```bash
  cd ../../solution/django
  poetry run python manage.py makemigrations django_cfg_app_name
  poetry run python manage.py migrate
  ```
- [ ] Documentation written (`@docs/` + `README.md`)
- [ ] `check_endpoints` command passes

---

## 📖 Reference Documentation

### User Documentation
- **Django Admin Patterns:** `../../solution/frontend/apps/docs/content/features/modules/django-admin/`
- **Testing Guide:** `../../solution/frontend/apps/docs/content/cli/commands/testing-monitoring.mdx`
- **Core Concepts:** `../../solution/frontend/apps/docs/content/core-concepts/`
- **API Patterns:** `../../solution/frontend/apps/docs/content/api/`

### Internal Documentation
For advanced patterns and edge cases, see `../../@doc-internal/`:
- **DRF patterns** - pagination, array responses, nested serializers
- **Integration guides** - detailed technical patterns

---

## 🚫 Common Mistakes

### ❌ DON'T
```python
# Register in local config
project_apps = ["my_new_app"]  # ❌ WRONG

# Old admin style
class MyAdmin(admin.ModelAdmin):
    list_display = ["field"]  # ❌ WRONG

# Custom DRF router
router = CustomRouter()  # ❌ WRONG
```

### ✅ DO
```python
# Register through core
# django_cfg/core/builders/apps_builder.py
apps.append("django_cfg.apps.system.my_app")  # ✅ RIGHT

# PydanticAdmin
config = AdminConfig(model=MyModel, list_display=["field"])
class MyAdmin(PydanticAdmin):
    config = config  # ✅ RIGHT

# DefaultRouter + nested-routers
from rest_framework.routers import DefaultRouter  # ✅ RIGHT
```

---

## 🔗 Quick Links

| Topic | Path |
|-------|------|
| Apps Builder | `django_cfg/core/builders/apps_builder.py` |
| URLs Registry | `django_cfg/apps/urls.py` |
| Admin Navigation | `django_cfg/modules/django_unfold/navigation.py` |
| Admin Docs | `../../solution/frontend/apps/docs/content/features/modules/django-admin/` |
| Testing Docs | `../../solution/frontend/apps/docs/content/cli/commands/testing-monitoring.mdx` |

---

**Last Updated:** 2025-12-20
