# System Settings Module

**Last Verified:** December 25, 2025  
**Status:** ✅ Active  
**Backend Path:** `backend/igny8_core/modules/system/`  
**Frontend Path:** `frontend/src/pages/Settings/`

---

## Quick Reference

| What | File | Key Items |
|------|------|-----------|
| Global Models | `modules/system/global_settings_models.py` | `GlobalIntegrationSettings`, `GlobalAIPrompt`, `GlobalAuthorProfile` |
| Account Models | `modules/system/settings_models.py` | `ModuleEnableSettings`, `IntegrationSettings`, `AISettings` |
| Views | `modules/system/settings_views.py` | Settings ViewSets |
| Integration Views | `modules/system/integration_views.py` | AI integration settings |
| Frontend | `pages/Settings/*.tsx` | Settings pages |

---

## Purpose

The System Settings module manages:
- Platform-wide global settings (API keys, defaults)
- Per-account settings overrides
- AI prompts and configurations
- Module enable/disable
- Author profiles and content strategies

---

## Settings Hierarchy

```
Global Settings (Platform-wide)
    ↓
Account Settings (Per-account overrides)
    ↓
User Settings (Per-user preferences)
```

**Priority:** User > Account > Global

---

## Global Settings Models

### GlobalIntegrationSettings (Singleton)

**Admin:** `/admin/system/globalintegrationsettings/`  
**Purpose:** Platform-wide API keys and defaults

| Field | Type | Purpose |
|-------|------|---------|
| openai_api_key | CharField | OpenAI API key (all accounts) |
| openai_model | CharField | Default model (gpt-4o-mini) |
| openai_temperature | Float | Default temperature (0.7) |
| openai_max_tokens | Integer | Default max tokens (8192) |
| dalle_api_key | CharField | DALL-E API key |
| dalle_model | CharField | Default model (dall-e-3) |
| dalle_size | CharField | Default size (1024x1024) |
| dalle_quality | CharField | Default quality (standard) |
| dalle_style | CharField | Default style (vivid) |
| anthropic_api_key | CharField | Anthropic API key |
| runware_api_key | CharField | Runware API key |

**Critical:** This is a singleton (only 1 record, pk=1). All accounts use these API keys.

### GlobalAIPrompt

**Admin:** `/admin/system/globalaiprompt/`  
**Purpose:** Default AI prompt templates

| Field | Type | Purpose |
|-------|------|---------|
| prompt_type | CharField | clustering/ideas/content_generation/etc. |
| prompt_value | TextField | The actual prompt text |
| description | TextField | What this prompt does |
| variables | JSON | Available variables ({keyword}, {industry}) |
| version | Integer | Prompt version |
| is_active | Boolean | Enable/disable |

### GlobalAuthorProfile

**Admin:** `/admin/system/globalauthorprofile/`  
**Purpose:** Default author persona templates

| Field | Type | Purpose |
|-------|------|---------|
| name | CharField | Profile name |
| description | TextField | Description |
| tone | CharField | professional/casual/technical |
| language | CharField | en/es/fr |
| structure_template | JSON | Content structure config |
| category | CharField | saas/ecommerce/blog/technical |
| is_active | Boolean | Enable/disable |

---

## Account Settings Models

### IntegrationSettings

**Purpose:** Per-account AI model overrides (NOT API keys)

| Field | Type | Purpose |
|-------|------|---------|
| account | FK | Owner account |
| integration_type | CharField | openai/runware/image_generation |
| config | JSON | Model, temperature, max_tokens overrides |
| is_active | Boolean | Enable/disable |

**Important:** 
- Free plan cannot create overrides
- Starter/Growth/Scale can override model/settings
- API keys ALWAYS come from GlobalIntegrationSettings

### ModuleEnableSettings

**Purpose:** Enable/disable modules per account

| Field | Type | Purpose |
|-------|------|---------|
| account | FK | Owner account |
| planner_enabled | Boolean | Enable Planner |
| writer_enabled | Boolean | Enable Writer |
| thinker_enabled | Boolean | Enable Thinker (AI settings) |
| automation_enabled | Boolean | Enable Automation |
| site_builder_enabled | Boolean | Enable Site Builder |
| linker_enabled | Boolean | Enable Linker |
| optimizer_enabled | Boolean | Enable Optimizer |
| publisher_enabled | Boolean | Enable Publisher |

**Current Implementation:**
- Controls sidebar navigation visibility
- ⚠️ **Pending:** Extend to other pages and references

### AIPrompt (Account-Level)

**Purpose:** Per-account prompt customizations

| Field | Type | Purpose |
|-------|------|---------|
| account | FK | Owner account |
| prompt_type | CharField | Prompt type |
| prompt_value | TextField | Current prompt (custom or default) |
| default_prompt | TextField | Original default (for reset) |
| is_customized | Boolean | True if user modified |

---

## API Endpoints

### Integration Settings

| Method | Path | Handler | Purpose |
|--------|------|---------|---------|
| GET | `/api/v1/system/settings/integrations/openai/` | Get OpenAI settings | Get current model/params |
| PUT | `/api/v1/system/settings/integrations/openai/` | Save OpenAI settings | Save overrides |
| GET | `/api/v1/system/settings/integrations/image_generation/` | Get image settings | Get DALL-E/Runware settings |
| PUT | `/api/v1/system/settings/integrations/image_generation/` | Save image settings | Save overrides |
| POST | `/api/v1/system/settings/integrations/test/` | Test connection | Test API connectivity |

### Prompts

| Method | Path | Handler | Purpose |
|--------|------|---------|---------|
| GET | `/api/v1/system/prompts/` | List prompts | Get all prompts |
| GET | `/api/v1/system/prompts/{type}/` | Get prompt | Get specific prompt |
| PUT | `/api/v1/system/prompts/{type}/` | Save prompt | Save customization |
| POST | `/api/v1/system/prompts/{type}/reset/` | Reset prompt | Reset to default |

### Module Settings

| Method | Path | Handler | Purpose |
|--------|------|---------|---------|
| GET | `/api/v1/system/modules/` | Get module settings | Get enable/disable state |
| PUT | `/api/v1/system/modules/` | Save module settings | Update enabled modules |

---

## Settings Flow (Frontend → Backend)

### Getting OpenAI Settings

1. Frontend requests: `GET /system/settings/integrations/openai/`
2. Backend checks account's `IntegrationSettings`
3. Gets global defaults from `GlobalIntegrationSettings`
4. Merges: account overrides > global defaults
5. Returns (NEVER includes API keys):
```json
{
  "model": "gpt-4o-mini",
  "temperature": 0.7,
  "max_tokens": 8192,
  "using_global": true
}
```

### Saving OpenAI Settings

1. Frontend sends: `PUT /system/settings/integrations/openai/`
2. Backend STRIPS any API key fields (security)
3. Validates account plan allows overrides
4. Saves to `IntegrationSettings.config`
5. Returns updated settings

---

## Module Enable/Disable

### How It Works (Current)

1. On app load, frontend fetches module settings
2. `useModuleStore.isModuleEnabled(name)` checks state
3. `AppSidebar.tsx` conditionally renders menu items:

```typescript
if (isModuleEnabled('linker')) {
  workflowItems.push({
    name: "Linker",
    path: "/linker/content",
  });
}
```

### Current Limitations (⚠️ Pending Implementation)

- Only hides sidebar menu items
- Direct URL access still works
- Other page references still show module links
- Dashboard cards may still show disabled modules

### Required Extension

Need to add `ModuleGuard` component to:
- Route-level protection
- Dashboard cards/widgets
- Cross-module references
- Settings page links

---

## Frontend Pages

### AI Settings (`/settings/ai`)

- OpenAI model selection
- Temperature and max tokens
- Image generation settings
- Test connection button

### Prompts (`/thinker/prompts`)

- List all prompt types
- Edit prompt text
- Reset to default
- Variable reference

### Module Settings (Admin Only)

- Enable/disable modules
- Per-account configuration

---

## Common Issues

| Issue | Cause | Fix |
|-------|-------|-----|
| Settings not saving | Plan restriction | Upgrade plan |
| API key exposed | Security flaw | Should never happen - check code |
| Module still visible | Cache stale | Clear cache, reload |
| Prompt reset not working | default_prompt missing | Re-run migration |

---

## Planned Changes

| Feature | Status | Description |
|---------|--------|-------------|
| Module guard extension | 🔜 Pending | Extend disable to all pages, not just sidebar |
| AIModelConfig database | 🔜 Planned | Move model pricing to database |
| Strategy templates | 🔜 Planned | Global strategy library |
| Per-user preferences | 🔜 Planned | User-level setting overrides |
