# IGNY8 Development Rules & Standards

**Project:** IGNY8 - AI-Powered Content Platform  
**Version:** v1.0.0  
**Last Updated:** December 12, 2025

---

## 📋 General Development Principles

### 1. **Always Read Documentation First**
Before making changes, consult these critical docs:
- `ARCHITECTURE-KNOWLEDGE-BASE.md` - System architecture and design patterns
- `CHANGELOG.md` - Recent changes and version history
- `IGNY8-COMPLETE-FEATURES-GUIDE.md` - Complete feature set and capabilities
- `docs/00-SYSTEM/` - Core system architecture
- `docs/10-BACKEND/` - Backend models, services, APIs
- `docs/20-API/` - API endpoint documentation
- `docs/30-FRONTEND/` - Frontend components and architecture
- `docs/40-WORKFLOWS/` - Business workflows and processes

### 2. **Maintain Consistency**
- **API Design:** Follow existing RESTful patterns in `backend/igny8_core/*/views.py`
- **Models:** Use existing base classes (`SoftDeletableModel`, `AccountBaseModel`, `SiteSectorBaseModel`)
- **Services:** Follow service pattern in `backend/igny8_core/business/*/services/`
- **AI Functions:** Use AI framework in `backend/igny8_core/ai/` (not legacy `utils/ai_processor.py`)
- **Frontend Components:** Use existing component library in `frontend/src/components/`
- **Styling:** Use TailwindCSS classes, follow existing design system in `frontend/DESIGN_SYSTEM.md`
- **State Management:** Use Zustand stores in `frontend/src/store/`

### 3. **Multi-Tenancy Rules**
- **ALWAYS scope by account:** Every query must filter by account
- **Site/Sector scoping:** Use `SiteSectorBaseModel` for site-specific data
- **Permissions:** Check permissions via `IsAuthenticatedAndActive`, `HasTenantAccess`, role-based permissions
- **No cross-tenant access:** Validate account ownership before operations

### 4. **API Endpoint Rules**
- **Use existing API structure:** All user-facing endpoints under `/api/v1/<module>/`, admin endpoints under `/api/v1/<module>/admin/`
- **No parallel API systems:** Register all endpoints in module's `urls.py`, test via Swagger at `/api/docs/` before documenting
- **Document in Swagger:** Ensure drf-spectacular auto-generates docs; verify endpoint appears at `/api/docs/` and `/api/schema/`

---

## 📝 Change Management & Versioning

alwys udpated changelog with incremental updates, as fixed aded or modified for each version update, dotn remove or modify teh exsitng version changes
### Versioning Scheme: `v<MAJOR>.<MINOR>.<PATCH>`

**Example:** v1.2.5
- `MAJOR when asked` (1.x.x): Breaking changes, major features, architecture changes
- `MAJOR` (x.2.x): New features, modules, significant enhancements
- `MINOR/PATCH` (x.x.5): Bug fixes, small improvements, refactors

### Changelog Update Rules

#### **For EVERY Change:**
1. **Update version number** in `CHANGELOG.md`
2. **Increment PATCH** (v1.0.x → v1.0.1) for:
   - Bug fixes
   - Small improvements
   - Code refactors
   - Documentation updates
   - UI/UX tweaks

3. **Increment MINOR** (v1.x.0 → v1.1.0) for:
   - New features
   - New API endpoints
   - New components
   - New services
   - Significant enhancements

4. **Increment MAJOR** (vx.0.0 → v2.0.0) for:
   - Breaking API changes
   - Database schema breaking changes
   - Architecture overhauls
   - Major refactors affecting multiple modules

#### **Changelog Entry Format:**
```markdown
## v1.2.5 - December 12, 2025

### Fixed
- User logout issue when switching accounts
- Payment confirmation modal amount display

### Changed
- Updated session storage from database to Redis
- Enhanced credit balance widget UI

### Added
- Plan limits enforcement system
- Monthly reset task for usage tracking
```

### **For Major Refactors:**
1. **Create detailed TODO list** before starting
2. **Document current state** in CHANGELOG
3. **Create implementation checklist** (markdown file in root or docs/)
4. **Track progress** with checklist updates
5. **Test thoroughly** before committing
6. **Update CHANGELOG** with all changes made
7. **Update version** to next MINOR or MAJOR

---

## 🏗️ Code Organization Standards

### Backend Structure
```
backend/igny8_core/
├── auth/              # Authentication, users, accounts, plans
├── business/          # Business logic services
│   ├── automation/    # Automation pipeline
│   ├── billing/       # Billing, credits, invoices
│   ├── content/       # Content generation
│   ├── integration/   # External integrations
│   ├── linking/       # Internal linking
│   ├── optimization/  # Content optimization
│   ├── planning/      # Keywords, clusters, ideas
│   └── publishing/    # WordPress publishing
├── ai/                # AI framework (NEW - use this)
├── utils/             # Utility functions
├── tasks/             # Celery tasks
└── modules/           # Legacy modules (being phased out)
```

### Frontend Structure
```
frontend/src/
├── components/        # Reusable components
├── pages/             # Page components
├── store/             # Zustand state stores
├── services/          # API service layer
├── hooks/             # Custom React hooks
├── utils/             # Utility functions
├── types/             # TypeScript types
└── marketing/         # Marketing site
```

---

## 🔧 Development Workflow

### 1. **Planning Phase**
- [ ] Read relevant documentation
- [ ] Understand existing patterns
- [ ] Create TODO list for complex changes
- [ ] Identify affected components/modules
- [ ] Plan database changes (if any)

### 2. **Implementation Phase**
- [ ] Follow existing code patterns
- [ ] Use proper base classes and mixins
- [ ] Add proper error handling
- [ ] Validate input data
- [ ] Check permissions and scope
- [ ] Write clean, documented code
- [ ] Use type hints (Python) and TypeScript types

### 3. **Testing Phase**
- [ ] Test locally with development data
- [ ] Test multi-tenancy isolation
- [ ] Test permissions and access control
- [ ] Test error cases
- [ ] Verify no breaking changes
- [ ] Check frontend-backend integration

### 4. **Documentation Phase**
- [ ] Update CHANGELOG.md
- [ ] Update version number
- [ ] Update relevant docs (if architecture/API changes)
- [ ] Add code comments for complex logic
- [ ] Update API documentation (if endpoints changed)

---

## 🎯 Specific Development Rules

### Backend Development

#### **Models:**
```python
# ALWAYS inherit from proper base classes
from igny8_core.auth.models import SiteSectorBaseModel

class MyModel(SoftDeletableModel, SiteSectorBaseModel):
    # Your fields here
    pass
```

#### **Services:**
```python
# Follow service pattern
class MyService:
    def __init__(self):
        self.credit_service = CreditService()
        self.limit_service = LimitService()
    
    def my_operation(self, account, site, **kwargs):
        # 1. Validate permissions
        # 2. Check limits/credits
        # 3. Perform operation
        # 4. Track usage
        # 5. Return result
        pass
```

#### **API Views:**
```python
# Use proper permission classes
class MyViewSet(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticatedAndActive, HasTenantAccess]
    
    def get_queryset(self):
        # ALWAYS scope by account
        return MyModel.objects.filter(
            site__account=self.request.user.account
        )
```

#### **Migrations:**
- Run `python manage.py makemigrations` after model changes
- Test migrations: `python manage.py migrate --plan`
- Never edit existing migrations
- Use data migrations for complex data changes

### Frontend Development

#### **Components:**
```typescript
// Use existing component library
import { Card } from '@/components/ui/card';
import Button from '@/components/ui/button/Button';

// Follow naming conventions
export default function MyComponent() {
  // Component logic
}
```

#### **State Management:**
```typescript
// Use Zustand stores
import { useAuthStore } from '@/store/authStore';

const { user, account } = useAuthStore();
```

#### **API Calls:**
```typescript
// Use fetchAPI from services/api.ts
import { fetchAPI } from '@/services/api';

const data = await fetchAPI('/v1/my-endpoint/');
```

#### **Styling:**
```typescript
// Use TailwindCSS classes
<div className="p-6 bg-white dark:bg-gray-800 rounded-lg shadow">
  <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
    My Heading
  </h1>
</div>
```

---

## 🚫 Common Pitfalls to Avoid

### **DON'T:**
- ❌ Skip account scoping in queries
- ❌ Use legacy AI processor (`utils/ai_processor.py`) - use `ai/` framework
- ❌ Hardcode values - use settings or constants
- ❌ Forget error handling
- ❌ Skip permission checks
- ❌ Create duplicate components - reuse existing
- ❌ Use inline styles - use TailwindCSS
- ❌ Forget to update CHANGELOG
- ❌ Use workarounds - fix the root cause
- ❌ Skip migrations after model changes

### **DO:**
- ✅ Read documentation before coding
- ✅ Follow existing patterns
- ✅ Use proper base classes
- ✅ Check permissions and limits
- ✅ Handle errors gracefully
- ✅ Return valid errors, not fallbacks
- ✅ Update CHANGELOG for every change
- ✅ Test multi-tenancy isolation
- ✅ Use TypeScript types
- ✅ Write clean, documented code

---

## 🔍 Code Review Checklist

Before committing code, verify:
- [ ] Follows existing code patterns
- [ ] Properly scoped by account/site
- [ ] Permissions checked
- [ ] Error handling implemented
- [ ] No breaking changes
- [ ] CHANGELOG.md updated
- [ ] Version number incremented
- [ ] Documentation updated (if needed)
- [ ] Tested locally
- [ ] No console errors or warnings
- [ ] TypeScript types added/updated
- [ ] Migrations created (if model changes)

---

## 📚 Key Architecture Concepts

### **Credit System:**
- All AI operations cost credits
- Check credits before operation: `CreditService.check_credits()`
- Deduct after operation: `CreditService.deduct_credits()`
- Track in `CreditUsageLog` table

### **Limit System:**
- Hard limits: Persistent (sites, users, keywords, clusters)
- Monthly limits: Reset on billing cycle (ideas, words, images)
- Track in `PlanLimitUsage` table
- Check before operation: `LimitService.check_limit()`

### **AI Framework:**
- Use `ai/engine.py` for AI operations
- Use `ai/functions/` for specific AI tasks
- Use `ai/models.py` for tracking
- Don't use legacy `utils/ai_processor.py`

### **Multi-Tenancy:**
- Every request has `request.user.account`
- All models scope by account directly or via site
- Use `AccountBaseModel` or `SiteSectorBaseModel`
- Validate ownership before mutations

---

## 🎨 Design System

### **Colors:**
- Primary: Blue (#0693e3)
- Success: Green (#0bbf87)
- Error: Red (#ef4444)
- Warning: Yellow (#f59e0b)
- Info: Blue (#3b82f6)

### **Typography:**
- Headings: font-bold
- Body: font-normal
- Small text: text-sm
- Large text: text-lg, text-xl, text-2xl

### **Spacing:**
- Padding: p-4, p-6 (standard)
- Margin: mt-4, mb-6 (standard)
- Gap: gap-4, gap-6 (standard)

### **Components:**
- Card: `<Card>` with padding and shadow
- Button: `<Button>` with variants (primary, secondary, danger)
- Input: `<Input>` with proper validation
- Badge: `<Badge>` with color variants

---

## 📞 Support & Questions

- Architecture questions → Check `ARCHITECTURE-KNOWLEDGE-BASE.md`
- Feature questions → Check `IGNY8-COMPLETE-FEATURES-GUIDE.md`
- API questions → Check `docs/20-API/`
- Recent changes → Check `CHANGELOG.md`

---

**Remember:** Quality over speed. Take time to understand existing patterns before implementing new features.
