# API Organization ID Update Plan

## Overview
This document outlines the comprehensive plan to update all API endpoints to support multi-organization functionality with `organization_id`.

## Phase 1: Authentication & Authorization

### 1.1 Update Authentication Controller
**File**: `src/controllers/authController.js`

**Changes Needed**:
- ✅ Add `organization_id` to JWT token payload
- ✅ Include `organization_id` in login response
- ✅ Update profile endpoint to include `organization_id`
- ✅ Update user data returned in all auth endpoints

**Code Changes**:
```javascript
// In login method - JWT token generation
const token = jwt.sign({
  id: user.id,
  organization_id: user.organization_id,  // ADD THIS
  login_id: user.login_id,
  email: user.email,
  role: user.role,
  role_id: user.role_id,
  name: user.designation
}, config.jwt.secret, { expiresIn: config.jwt.expiresIn });
```

### 1.2 Update Authentication Middleware
**File**: `src/middleware/auth.js`

**Changes Needed**:
- ✅ Extract `organization_id` from JWT token
- ✅ Add `organization_id` to `req.user` object
- ✅ Validate `organization_id` exists and is valid

**Code Changes**:
```javascript
// In authenticateToken middleware
req.user = {
  id: user.id,
  organization_id: user.organization_id,  // ADD THIS
  email: user.email,
  role: user.role,
  role_id: user.role_id,
  name: user.name
};
```

## Phase 2: Core Models

### 2.1 Update User Model
**File**: `src/models/User.js`

**Changes Needed**:
- ✅ Add `organization_id` filtering to all queries
- ✅ Update `findById` to include organization check
- ✅ Update `findByLoginId` to include organization check
- ✅ Update `findAll` to filter by organization
- ✅ Update `create` to require organization_id
- ✅ Update `update` to validate organization ownership

### 2.2 Update Unit Model
**File**: `src/models/Unit.js`

**Changes Needed**:
- ✅ Add `organization_id` to all SELECT queries
- ✅ Add `organization_id` to WHERE clauses
- ✅ Update `create` to require organization_id
- ✅ Update `update` to validate organization ownership
- ✅ Update `delete` to validate organization ownership

### 2.3 Update Department Model
**File**: `src/models/Department.js`

**Changes Needed**:
- ✅ Add `organization_id` filtering
- ✅ Update all CRUD operations
- ✅ Update tree/hierarchy queries

### 2.4 Update Designation Model
**File**: `src/models/Designation.js`

**Changes Needed**:
- ✅ Add `organization_id` filtering
- ✅ Update all CRUD operations
- ✅ Update hierarchy queries

### 2.5 Update Rank Model
**File**: `src/models/Rank.js`

**Changes Needed**:
- ✅ Add `organization_id` filtering
- ✅ Update all CRUD operations

### 2.6 Update Conversation Model
**File**: `src/models/Conversation.js`

**Changes Needed**:
- ✅ Add `organization_id` to all queries
- ✅ Update message queries to include organization filtering

### 2.7 Update Message Model
**File**: `src/models/Message.js`

**Changes Needed**:
- ✅ Add `organization_id` to all queries
- ✅ Ensure cross-organization messaging is prevented

## Phase 3: Controllers

### 3.1 User Controller
**File**: `src/controllers/userController.js`

**Endpoints to Update**:
- `GET /users` - Filter by req.user.organization_id
- `GET /users/:id` - Validate organization ownership
- `POST /users` - Include req.user.organization_id
- `PUT /users/:id` - Validate organization ownership
- `DELETE /users/:id` - Validate organization ownership
- `GET /users/search` - Filter by organization
- `POST /users/upload-excel` - Include organization_id for all users

### 3.2 Unit Controller
**File**: `src/controllers/unitController.js`

**Endpoints to Update**:
- `GET /units` - Filter by organization_id
- `GET /units/:id` - Validate organization ownership
- `POST /units` - Include organization_id
- `PUT /units/:id` - Validate organization ownership
- `DELETE /units/:id` - Validate organization ownership
- `GET /units/tree` - Filter by organization_id

### 3.3 Department Controller
**File**: `src/controllers/departmentController.js`

**Endpoints to Update**:
- `GET /departments` - Filter by organization_id
- `GET /departments/:id` - Validate organization ownership
- `POST /departments` - Include organization_id
- `PUT /departments/:id` - Validate organization ownership
- `DELETE /departments/:id` - Validate organization ownership
- `GET /departments/by-unit/:unitId` - Filter by organization_id

### 3.4 Organizational Controller (Designations)
**File**: `src/controllers/organizationalController.js`

**Endpoints to Update**:
- `GET /designations` - Filter by organization_id
- `GET /designations/:id` - Validate organization ownership
- `POST /designations` - Include organization_id
- `PUT /designations/:id` - Validate organization ownership
- `DELETE /designations/:id` - Validate organization ownership

### 3.5 Rank Controller
**File**: `src/controllers/rankController.js`

**Endpoints to Update**:
- `GET /ranks` - Filter by organization_id
- `GET /ranks/:id` - Validate organization ownership
- `POST /ranks` - Include organization_id
- `PUT /ranks/:id` - Validate organization ownership
- `DELETE /ranks/:id` - Validate organization ownership

### 3.6 Contact Controller
**File**: `src/controllers/contactController.js`

**Endpoints to Update**:
- All contact-related endpoints
- Contact directory filtering

### 3.7 Message Controller
**File**: `src/controllers/messageController.js`

**Endpoints to Update**:
- `GET /messages` - Filter by organization_id
- `POST /messages` - Include organization_id and validate participants
- Prevent cross-organization messaging

### 3.8 Conversation Controller
**File**: `src/controllers/conversationController.js`

**Endpoints to Update**:
- `GET /conversations` - Filter by organization_id
- `POST /conversations` - Include organization_id
- `GET /conversations/:id/messages` - Validate organization ownership

### 3.9 Notification Controller
**File**: `src/controllers/notificationController.js`

**Endpoints to Update**:
- `GET /notifications` - Filter by organization_id
- `POST /notifications` - Include organization_id
- `PUT /notifications/:id` - Validate organization ownership

### 3.10 Dashboard Controller
**File**: `src/controllers/dashboardController.js`

**Endpoints to Update**:
- `GET /dashboard/stats` - Filter all statistics by organization_id
- `GET /dashboard/charts` - Filter chart data by organization_id
- All analytics endpoints

## Phase 4: New Organization Management API

### 4.1 Create Organization Controller
**File**: `src/controllers/organizationController.js` (NEW)

**Endpoints to Create**:
- `GET /organizations` - List all organizations (Super Admin only)
- `GET /organizations/:id` - Get organization details
- `POST /organizations` - Create new organization (Super Admin only)
- `PUT /organizations/:id` - Update organization (Super Admin only)
- `DELETE /organizations/:id` - Delete organization (Super Admin only)
- `GET /organizations/:id/stats` - Organization statistics

### 4.2 Create Organization Routes
**File**: `src/routes/organizations.js` (NEW)

## Phase 5: Database Queries Update Pattern

### Standard Query Pattern

**BEFORE**:
```javascript
const users = await db.query('SELECT * FROM users WHERE is_active = ?', [1]);
```

**AFTER**:
```javascript
const users = await db.query(
  'SELECT * FROM users WHERE organization_id = ? AND is_active = ?',
  [req.user.organization_id, 1]
);
```

### Standard Create Pattern

**BEFORE**:
```javascript
const result = await db.query(
  'INSERT INTO units (name, code, description) VALUES (?, ?, ?)',
  [name, code, description]
);
```

**AFTER**:
```javascript
const result = await db.query(
  'INSERT INTO units (organization_id, name, code, description) VALUES (?, ?, ?, ?)',
  [req.user.organization_id, name, code, description]
);
```

### Standard Update Pattern

**BEFORE**:
```javascript
const result = await db.query(
  'UPDATE units SET name = ?, code = ? WHERE id = ?',
  [name, code, id]
);
```

**AFTER**:
```javascript
const result = await db.query(
  'UPDATE units SET name = ?, code = ? WHERE id = ? AND organization_id = ?',
  [name, code, id, req.user.organization_id]
);
```

### Standard Delete Pattern

**BEFORE**:
```javascript
const result = await db.query('DELETE FROM units WHERE id = ?', [id]);
```

**AFTER**:
```javascript
const result = await db.query(
  'DELETE FROM units WHERE id = ? AND organization_id = ?',
  [id, req.user.organization_id]
);
```

## Phase 6: Validation Updates

### Update Validation Middleware

All validation middleware files need to ensure:
- Organization ownership is validated
- Cross-organization references are prevented
- Organization_id is included in create operations

**Files to Update**:
- `src/middleware/userValidation.js`
- `src/middleware/unitValidation.js`
- `src/middleware/departmentValidation.js`
- `src/middleware/designationValidation.js`
- `src/middleware/rankValidation.js`
- `src/middleware/contactValidation.js`
- `src/middleware/messageValidation.js`
- `src/middleware/conversationValidation.js`

## Phase 7: Special Cases

### 7.1 Roles & Permissions
**Note**: Roles and permissions are GLOBAL (no organization_id)
- No changes needed to role/permission queries
- Users still have role_id (references global roles)
- Permission checks remain the same

### 7.2 Super Admin Access
**Special Handling Required**:
- Super Admin (role_id = 1) may need cross-organization access
- Add special check in middleware:
```javascript
// Allow Super Admin to access all organizations
const isSuperAdmin = req.user.role_id === 1;
const organizationFilter = isSuperAdmin ? '' : 'AND organization_id = ?';
const params = isSuperAdmin ? [id] : [id, req.user.organization_id];
```

### 7.3 Audit Logs
**File**: Update audit log creation to include organization_id
```javascript
await db.query(
  'INSERT INTO audit_logs (organization_id, user_id, action, details) VALUES (?, ?, ?, ?)',
  [req.user.organization_id, req.user.id, action, details]
);
```

## Phase 8: Testing Requirements

### 8.1 Unit Tests
- Test organization data isolation
- Test cross-organization access prevention
- Test Super Admin cross-organization access

### 8.2 Integration Tests
- Test complete user flow within organization
- Test multi-organization scenario
- Test organization switching (if supported)

### 8.3 Security Tests
- Attempt cross-organization data access
- Verify JWT token includes organization_id
- Verify all queries filter by organization_id

## Implementation Order

1. ✅ **Phase 1**: Auth & Middleware (Critical - Foundation)
2. ✅ **Phase 2**: Core Models (Critical - Data Layer)
3. ✅ **Phase 3**: Controllers (High Priority - API Layer)
4. ✅ **Phase 4**: Organization Management (Medium Priority)
5. ✅ **Phase 5**: Apply Query Patterns (High Priority)
6. ✅ **Phase 6**: Validation Updates (Medium Priority)
7. ✅ **Phase 7**: Special Cases (High Priority)
8. ✅ **Phase 8**: Testing (Critical - Verification)

## Rollback Plan

If issues arise:
1. Revert database changes using backup
2. Revert code changes using git
3. Test with single organization setup
4. Gradually enable multi-organization support

## Migration Strategy

For existing installations:
1. Add default organization (ID = 1)
2. Update all existing records with organization_id = 1
3. Update API to use new organization-aware queries
4. Test thoroughly before enabling multiple organizations

## Success Criteria

- ✅ All API endpoints filter by organization_id
- ✅ JWT token includes organization_id
- ✅ No cross-organization data leakage
- ✅ Super Admin can access all organizations
- ✅ Regular users limited to their organization
- ✅ All CRUD operations include organization validation
- ✅ Audit logs include organization_id
- ✅ Performance acceptable with organization filtering

---
**Created**: October 20, 2025
**Status**: In Progress
**Priority**: Critical

