# Codebase Structure

**Analysis Date:** 2026-05-07

## Directory Layout

```
qy_lty/
├── manage.py                    # Django management script
├── run.sh                       # Start development server (daphne)
├── requirements.txt             # Python dependencies
├── Dockerfile                   # Container image build
├── docker-compose.yml           # Docker compose for dev environment
├── .env                         # Environment variables (not committed)
│
├── qy_lty/                      # Project configuration package
│   ├── __init__.py
│   ├── settings.py              # Django settings (INSTALLED_APPS, middleware, auth, etc.)
│   ├── asgi.py                  # ASGI app entry (Channels + HTTP routing)
│   ├── wsgi.py                  # WSGI app entry (for traditional servers)
│   └── urls.py                  # Root URL router (includes all app URLs)
│
├── userapp/                     # User authentication & profile management
│   ├── models.py                # ParadiseUser (custom user model), AffinityRule, AffinityLevel
│   ├── views.py                 # MacAddressLoginView, PhoneLoginView, UserViewSet, ProfileView
│   ├── serializers.py           # ParadiseUserSerializer, ProfileUpdateSerializer
│   ├── urls.py                  # User API routes: /api/user/
│   ├── auth_urls.py             # Auth-specific routes (deprecated/legacy)
│   ├── admin_urls.py            # Admin API routes: /api/v1/admin/
│   ├── authentication.py        # RedisTokenAuthentication class
│   ├── utils.py                 # generate_token(), get_user_id_from_token(), send_sms()
│   ├── admin.py                 # Django admin customization
│   ├── apps.py                  # App configuration
│   ├── migrations/              # Database migrations
│   ├── management/              # Custom management commands
│   └── tests.py                 # Unit tests
│
├── aiapp/                       # AI chat & voice integration
│   ├── models.py                # ChatMessage, Bot, ConversationSubtitle
│   ├── views.py                 # BotViewSet, ChatView (Kimi API integration, multi-turn chat)
│   ├── serializers.py           # ChatMessageSerializer
│   ├── urls.py                  # AI API routes: /api/ai/
│   ├── kimi.py                  # Kimi API client (OpenAI compatible)
│   ├── audio/                   # Audio service abstraction
│   │   ├── AudioService.py      # Multi-provider audio (Aliyun/Volcengine/Tencent)
│   │   ├── aliyun_audio.py      # Aliyun NLS implementation
│   │   └── [other provider implementations]
│   ├── admin.py                 # Admin interface for Chat models
│   ├── apps.py                  # App configuration
│   ├── migrations/              # Database migrations
│   └── tests.py
│
├── device_interaction/          # WebSocket real-time device communication
│   ├── models.py                # Device, DeviceType, DeviceBatch, UserDevice
│   ├── views.py                 # DeviceTypeViewSet, DeviceViewSet, UserDeviceViewSet, RTC endpoints
│   ├── serializers.py           # DeviceSerializer, UserDeviceSerializer, DeviceBindSerializer
│   ├── urls.py                  # Device HTTP API routes: /api/device/
│   ├── routing.py               # WebSocket URL routing (ws://domain/ws/device/)
│   ├── consumers.py             # DeviceConsumer (AsyncWebsocketConsumer, message handlers)
│   ├── auth.py                  # TokenAuthMiddleware (WebSocket auth)
│   ├── amap_api.py              # Amap (高德地图) location/nearby search
│   ├── weather.py               # QWeather API for weather data
│   ├── volcengine_api.py        # Volcengine RTC token generation
│   ├── swagger.py               # Swagger schema definitions
│   ├── admin.py                 # Admin interface for Device models
│   ├── apps.py                  # App configuration
│   ├── middleware.py            # Custom middleware (if any)
│   ├── services.py              # Business logic services
│   ├── scheduler.py             # Async task scheduling (e.g., device heartbeat monitoring)
│   ├── management/              # Custom management commands
│   ├── migrations/              # Database migrations
│   └── tests.py
│
├── card/                        # Card management system
│   ├── models.py                # CardCategory, CardBatch, Card, CardUsageLog
│   ├── views.py                 # CardViewSet, batch generation, QR code endpoints
│   ├── serializers.py           # CardSerializer
│   ├── urls.py                  # Card API routes: /api/card/
│   ├── admin.py
│   ├── apps.py
│   ├── migrations/
│   └── tests.py
│
├── achievement_app/             # User achievements & progress tracking
│   ├── models.py                # Achievement, AchievementProgress, AchievementBadge
│   ├── views.py                 # AchievementViewSet, ProgressView
│   ├── serializers.py           # AchievementSerializer
│   ├── urls.py                  # Achievement API routes: /api/achievement/
│   ├── admin.py
│   ├── apps.py
│   ├── migrations/
│   └── tests.py
│
├── subscription_app/            # Subscription & billing management
│   ├── models.py                # Subscription, SubscriptionPlan, Payment
│   ├── views.py                 # SubscriptionViewSet
│   ├── serializers.py           # SubscriptionSerializer
│   ├── urls.py                  # Subscription API routes (if exposed)
│   ├── admin.py
│   ├── apps.py
│   ├── migrations/
│   ├── templates/               # Email templates for subscription notifications
│   └── tests.py
│
├── ali_vi_app/                  # Aliyun Visual Intelligence integration
│   ├── models.py                # VIRequest, VIResult
│   ├── views.py                 # Aliyun VI API wrappers
│   ├── urls.py                  # VI API routes (currently disabled in root urls.py line 52)
│   ├── admin.py
│   ├── apps.py
│   ├── migrations/
│   └── tests.py
│
├── food_app/                    # Food management system (new)
│   ├── models.py                # Food, FoodInventory
│   ├── views.py                 # FoodViewSet
│   ├── serializers.py
│   ├── urls.py                  # Food API routes: /api/food/
│   ├── admin.py
│   ├── apps.py
│   ├── migrations/
│   └── tests.py
│
├── workflow_app/                # Multi-tenant workflow management (dev)
│   ├── models.py                # Workflow, WorkflowStep, WorkflowTask
│   ├── views.py
│   ├── serializers.py
│   ├── urls.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations/
│   └── tests.py
│
├── common/                      # Shared utilities & middleware
│   ├── middleware.py            # StandardResponseMiddleware (standardizes all responses)
│   ├── pagination.py            # CustomPageNumberPagination (DRF pagination)
│   ├── responses.py             # Helper functions: success_response(), error_response()
│   ├── swagger_utils.py         # Swagger/OpenAPI utilities
│   ├── aliyun_logging.py        # Aliyun log service setup
│   ├── VolcEngineAccessToken.py # Volcengine RTC token generation
│   ├── admin.py
│   ├── apps.py
│   └── [other shared modules]
│
├── templates/                   # HTML templates for Django admin & error pages
│   └── [admin templates, error pages]
│
├── locale/                      # i18n translation catalogs
│   ├── en/                      # English translations
│   │   └── LC_MESSAGES/
│   │       ├── django.po        # Compiled message file
│   │       └── django.mo        # Binary compiled messages
│   └── zh_HAns/                 # Simplified Chinese translations
│       └── LC_MESSAGES/
│
├── static/                      # Static files (JS, CSS, images) — dev only
│   └── [served by STATIC_URL]
│
├── media/                       # User-uploaded files — dev only
│   └── [served by MEDIA_URL]
│
├── docs/                        # Documentation
│   ├── README.md                # Project overview
│   ├── 修改记录.md              # Change log (Chinese, auto-maintained)
│   ├── 设备动态绑定方案.md      # Device dynamic binding design
│   ├── 设备聊天记录_字幕落库方案.md # Chat transcript & subtitle storage design
│   ├── device_api.md            # WebSocket device API reference
│   ├── device_commands.md       # Device command reference
│   ├── device_errors.md         # Device error codes
│   ├── device_module.md         # Device module overview
│   ├── user_authentication_api.md # User auth API reference
│   ├── api/                     # API endpoint documentation
│   ├── development/             # Development guides
│   ├── features/                # Feature documentation
│   └── integrations/            # Integration guides
│
└── .planning/                   # GSD codebase mapping (auto-generated)
    └── codebase/
        ├── ARCHITECTURE.md      # Architecture patterns & data flows
        └── STRUCTURE.md         # This file
```

## Directory Purposes

**qy_lty/ (Project Config):**
- Purpose: Django project configuration and root URL routing
- Contains: Settings, ASGI/WSGI entry points, URL dispatcher
- Key files: 
  - `settings.py` (line 1-400+): All Django configuration, app list, middleware, DB, cache, auth
  - `urls.py` (line 49-60): Centralizes all API routes via `include()`
  - `asgi.py` (line 19-26): ProtocolTypeRouter for HTTP + WebSocket

**userapp/:**
- Purpose: User authentication, profile management, affinity system
- Contains: ParadiseUser model, MAC/phone login, token generation, user info endpoints
- Key files:
  - `models.py` (line 8-145): ParadiseUser, AffinityRule, AffinityLevel (favorability system)
  - `authentication.py` (line 10-34): RedisTokenAuthentication class
  - `utils.py` (line 33-37): `generate_token()` stores in Redis with 30-day TTL

**device_interaction/:**
- Purpose: Real-time device communication via WebSocket, device management
- Contains: WebSocket consumer, device CRUD, user-device binding, RTC token endpoints
- Key files:
  - `consumers.py` (line 10-320+): DeviceConsumer handles connect/receive/disconnect, group messaging
  - `routing.py` (line 4-7): WebSocket URL patterns
  - `auth.py` (line 4-50): TokenAuthMiddleware authenticates WebSocket connections
  - `models.py` (line 43-145): Device, UserDevice with "last-bind-wins" ordering

**aiapp/:**
- Purpose: AI chat (Kimi), multi-provider audio services
- Contains: Chat message models, Kimi API client, audio synthesis/recognition
- Key files:
  - `views.py` (line 1-60+): BotViewSet, ChatView for multi-turn conversations
  - `audio/` (submodule): AudioService factory + provider implementations

**card/:**
- Purpose: Card management (categories, batches, QR codes, usage tracking)
- Contains: Card CRUD, batch generation, QR code generation/scanning
- Key files: models.py, views.py (batch endpoints), serializers.py

**achievement_app/:**
- Purpose: User achievements, progress tracking, badges
- Contains: Achievement definitions, user progress models
- Key files: models.py, views.py (progress endpoints)

**subscription_app/:**
- Purpose: Billing and subscription management
- Contains: Subscription plans, payment records
- Key files: models.py

**ali_vi_app/, food_app/, workflow_app/:**
- Purpose: Specialized modules (Aliyun Visual Intelligence, Food management, Workflow automation)
- Contains: Domain-specific models, views, serializers
- Note: ali_vi_app routes disabled in qy_lty/urls.py line 52

**common/:**
- Purpose: Shared utilities across all apps
- Contains: Middleware, pagination, response helpers, external API clients
- Key files:
  - `middleware.py` (line 6-145): StandardResponseMiddleware wraps all responses
  - `pagination.py` (line 1-9): CustomPageNumberPagination for DRF list views
  - `responses.py`: Helper functions for standardized responses

**locale/:**
- Purpose: i18n translation catalogs (Chinese/English)
- Contains: Django message files (.po/.mo)
- Generated by: `django-admin makemessages -l en`, `compilemessages`

**docs/:**
- Purpose: Human-readable documentation
- Contains: Design docs, API references, development guides
- Key files:
  - `修改记录.md`: Auto-maintained change log (new entries at top)
  - `设备动态绑定方案.md`: Device binding strategy & semantics
  - `device_api.md`: WebSocket message types & format

## Key File Locations

**Entry Points:**
- `qy_lty/urls.py`: HTTP root router (line 63-73)
- `qy_lty/asgi.py`: ASGI app with Channels (line 19-26)
- `device_interaction/routing.py`: WebSocket URL patterns (line 4-7)
- `device_interaction/consumers.py`: WebSocket message handler (line 10+)

**Configuration:**
- `qy_lty/settings.py`: All Django configuration (INSTALLED_APPS, middleware, auth, databases)
- `.env`: Environment variables (NEVER committed; copy from `.env.bak` if it exists)
- `requirements.txt`: Python package dependencies

**Authentication & Authorization:**
- `userapp/authentication.py`: RedisTokenAuthentication (HTTP)
- `device_interaction/auth.py`: TokenAuthMiddleware (WebSocket)
- `userapp/utils.py`: Token generation/lookup with Redis
- `userapp/models.py`: ParadiseUser (custom user model)

**Core Models:**
- `userapp/models.py`: ParadiseUser, AffinityRule, AffinityLevel
- `device_interaction/models.py`: Device, DeviceType, DeviceBatch, UserDevice
- `aiapp/models.py`: ChatMessage, Bot, ConversationSubtitle
- `card/models.py`: CardCategory, CardBatch, Card, CardUsageLog
- `achievement_app/models.py`: Achievement, AchievementProgress
- `subscription_app/models.py`: Subscription, SubscriptionPlan

**Middleware & Cross-Cutting:**
- `common/middleware.py`: StandardResponseMiddleware (response wrapper)
- `common/pagination.py`: CustomPageNumberPagination (DRF pagination)
- `common/responses.py`: `success_response()`, `error_response()` helpers
- `qy_lty/settings.py` line 82-95: All middleware configured

**API Documentation:**
- Swagger UI: Generated from code, served at `/swagger/`
- ReDoc: Alternative documentation UI at `/redoc/`
- drf-yasg integration: Configured in qy_lty/urls.py line 22-46

**Logging:**
- Configuration: `qy_lty/settings.py` (logging config, or via `common/aliyun_logging.py`)
- Entry point: `setup_logging()` in common/aliyun_logging.py (called from settings.py line 16)

**i18n Catalogs:**
- English: `locale/en/LC_MESSAGES/django.{po,mo}`
- Chinese: `locale/zh_HAns/LC_MESSAGES/django.{po,mo}`
- Generation: `django-admin makemessages -l {lang}`
- Compilation: `django-admin compilemessages`

## Naming Conventions

**Files:**
- Django app folders: lowercase_underscore (e.g., `device_interaction`, `user_app`)
- Python modules: lowercase_underscore (e.g., `models.py`, `serializers.py`, `auth.py`)
- Migrations: auto-generated format `000X_auto_YYYYMMDD_HHMM.py`
- Documentation: Chinese filename or English snake_case

**Directories:**
- Apps: snake_case (userapp, device_interaction, achievement_app)
- Packages: lowercase without underscores (audio/, management/, migrations/)

**URL Prefixes:**
- `/api/user/` → userapp endpoints
- `/api/device/` → device_interaction endpoints
- `/api/ai/` → aiapp endpoints
- `/api/card/` → card endpoints
- `/api/achievement/` → achievement_app endpoints
- `/api/food/` → food_app endpoints
- `/api/v1/admin/` → admin endpoints (via userapp.admin_urls)
- `/ws/device/` → WebSocket endpoint

**Database Models:**
- User model: `ParadiseUser` (extends AbstractUser)
- Device-related: `Device`, `DeviceBatch`, `DeviceType`, `UserDevice`
- Message models: `ChatMessage`, `ConversationSubtitle`
- Achievement models: `Achievement`, `AchievementProgress`, `AchievementBadge`

## Where to Add New Code

**New Feature (e.g., "Affinity Decay Task"):**
- Models: `device_interaction/models.py` (if device-related) or `userapp/models.py` (if user-related)
- Views/API: `device_interaction/views.py` or `userapp/views.py` → new ViewSet or APIView
- Serializers: `device_interaction/serializers.py` or `userapp/serializers.py` → new ModelSerializer
- URLs: Edit `device_interaction/urls.py` or `userapp/urls.py` → add path/route
- Async tasks: `device_interaction/scheduler.py` or new `tasks.py` file
- Tests: `device_interaction/tests.py` or `userapp/tests.py`

**New Component/Module (e.g., "Chat Analytics"):**
- Create new Django app: `python manage.py startapp analytics`
- Standard files: `models.py`, `views.py`, `serializers.py`, `urls.py`, `admin.py`, `apps.py`, `tests.py`
- Register in `qy_lty/settings.py` INSTALLED_APPS (line 43+)
- Include URLs in `qy_lty/urls.py` (line 49-60)

**Shared Utilities:**
- Common middleware/helpers: Add to `common/` directory
- Examples: `common/responses.py`, `common/swagger_utils.py`
- New integration (e.g., API client): Create in `common/` or within relevant app (e.g., `device_interaction/amap_api.py`)

**WebSocket Message Handler:**
- Edit `device_interaction/consumers.py:DeviceConsumer.receive()` (line 171+)
- Add new `elif message_type == 'new_type':` branch
- Call appropriate handler or `group_send()` to broadcast

**Serializer Customization:**
- Override `to_representation()` for custom output
- Override `to_internal_value()` for custom input processing
- Add `validate_<field>()` for field-specific validation
- Add `validate()` for cross-field validation

## Special Directories

**migrations/:**
- Purpose: Track database schema changes
- Generated: `python manage.py makemigrations`
- Applied: `python manage.py migrate`
- Committed: Yes (part of version control)

**.planning/codebase/:**
- Purpose: GSD (Generate Specification Documents) auto-generated codebase maps
- Generated: By `/gsd-map-codebase` orchestrator
- Committed: Yes (reference docs for other GSD commands)
- Contents: ARCHITECTURE.md, STRUCTURE.md, CONVENTIONS.md, TESTING.md, CONCERNS.md, INTEGRATIONS.md, STACK.md

**docs/:**
- Purpose: Human documentation
- Committed: Yes
- Auto-maintained: `修改记录.md` (change log, appended by developers after each commit)

**locale/:**
- Purpose: i18n translation catalogs
- Generated: `django-admin makemessages` (creates .po files)
- Compiled: `django-admin compilemessages` (creates .mo files)
- Committed: Yes (both .po and .mo)

**static/ & media/:**
- Purpose: Served files (CSS, JS, images; user uploads)
- Generated: No (user-managed)
- Committed: No (in .gitignore)
- Dev only: Yes (production uses CloudStorage/OSS)

## Management Commands

**Standard Django:**
```bash
python manage.py migrate              # Apply database migrations
python manage.py makemigrations       # Create new migration files
python manage.py createsuperuser      # Create admin user
python manage.py shell                # Interactive Python shell
python manage.py dbshell              # Interactive database shell
```

**i18n:**
```bash
django-admin makemessages -l en       # Extract translatable strings (English)
django-admin makemessages -l zh_HAns  # Extract translatable strings (Simplified Chinese)
django-admin compilemessages          # Compile .po to .mo files
```

**Custom Commands (if any):**
- Location: `<app>/management/commands/<command_name>.py`
- Run: `python manage.py <command_name>`

---

*Structure analysis: 2026-05-07*
