# Plan Implementasi Sistem Approval Artikel Dinamis

## 1. Analisis Sistem Saat Ini

### Struktur Database yang Sudah Ada:
- **Articles**: Memiliki field `NeedApprovalFrom`, `HasApprovedBy`, `StatusId` untuk tracking approval
- **ArticleApprovals**: Menyimpan history approval dengan `ApprovalAtLevel`
- **Users**: Terhubung dengan `UserLevels` dan `UserRoles`
- **UserLevels**: Memiliki `LevelNumber`, `ParentLevelId`, `IsApprovalActive`
- **UserRoles**: Terhubung dengan `UserLevels` melalui `UserRoleLevelDetails`
- **UserRoleAccesses**: Memiliki `IsApprovalEnabled` untuk kontrol akses approval
- **MasterApprovalStatuses**: Status approval (pending, approved, rejected)

### Logika Approval Saat Ini:
- Hard-coded untuk 3 level (level 1, 2, 3)
- Approval naik ke parent level jika disetujui
- Kembali ke contributor jika ditolak
- Status: 1=Pending, 2=Approved, 3=Rejected

## 2. Kebutuhan Sistem Baru

### Functional Requirements:
1. **Dynamic Approval Levels**: Sistem harus mendukung 1-N level approval
2. **Flexible Workflow**: Approval flow bisa diubah sewaktu-waktu
3. **Role-based Access**: Approver dan Contributor dengan hak akses berbeda
4. **Revision Handling**: Artikel kembali ke contributor saat revisi diminta
5. **Audit Trail**: Tracking lengkap history approval

### User Stories:
- Sebagai **Contributor**: Saya bisa membuat artikel dan submit untuk approval
- Sebagai **Approver Level N**: Saya bisa approve/reject/request revision artikel
- Sebagai **Admin**: Saya bisa mengatur approval workflow secara dinamis

## 3. Desain Database Baru

### 3.1 Tabel Baru yang Diperlukan:

#### `approval_workflows`
```sql
CREATE TABLE approval_workflows (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    is_active BOOLEAN DEFAULT true,
    client_id UUID,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);
```

#### `approval_workflow_steps`
```sql
CREATE TABLE approval_workflow_steps (
    id SERIAL PRIMARY KEY,
    workflow_id INT REFERENCES approval_workflows(id),
    step_order INT NOT NULL,
    user_level_id INT REFERENCES user_levels(id),
    is_required BOOLEAN DEFAULT true,
    can_skip BOOLEAN DEFAULT false,
    client_id UUID,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);
```

#### `article_approval_flows`
```sql
CREATE TABLE article_approval_flows (
    id SERIAL PRIMARY KEY,
    article_id INT REFERENCES articles(id),
    workflow_id INT REFERENCES approval_workflows(id),
    current_step INT DEFAULT 1,
    status_id INT DEFAULT 1, -- 1=In Progress, 2=Completed, 3=Rejected
    client_id UUID,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);
```

#### `article_approval_step_logs`
```sql
CREATE TABLE article_approval_step_logs (
    id SERIAL PRIMARY KEY,
    article_flow_id INT REFERENCES article_approval_flows(id),
    step_order INT NOT NULL,
    user_level_id INT REFERENCES user_levels(id),
    approved_by INT REFERENCES users(id),
    action VARCHAR(50) NOT NULL, -- 'approved', 'rejected', 'revision_requested'
    message TEXT,
    approved_at TIMESTAMP,
    client_id UUID,
    created_at TIMESTAMP DEFAULT NOW()
);
```

### 3.2 Modifikasi Tabel Existing:

#### `articles` - Tambah field:
```sql
ALTER TABLE articles ADD COLUMN workflow_id INT REFERENCES approval_workflows(id);
ALTER TABLE articles ADD COLUMN current_approval_step INT DEFAULT 0;
-- Keep existing fields: need_approval_from, has_approved_by, status_id untuk backward compatibility
```

#### `user_roles` - Tambah field:
```sql
ALTER TABLE user_roles ADD COLUMN role_type VARCHAR(50) DEFAULT 'contributor'; -- 'contributor', 'approver', 'admin'
```

## 4. Implementasi Backend

### 4.1 Entities Baru:
- `ApprovalWorkflows`
- `ApprovalWorkflowSteps` 
- `ArticleApprovalFlows`
- `ArticleApprovalStepLogs`

### 4.2 Modules Baru:

#### `approval_workflows`
- **Repository**: CRUD operations untuk workflow management
- **Service**: Business logic untuk workflow creation/modification
- **Controller**: API endpoints untuk workflow management
- **Request/Response**: DTOs untuk workflow operations

#### `article_approval_flows`
- **Repository**: Tracking approval progress per artikel
- **Service**: Core approval logic, step progression
- **Controller**: API untuk approval actions
- **Request/Response**: DTOs untuk approval operations

### 4.3 Modifikasi Modules Existing:

#### `articles/service`
- Refactor `UpdateApproval()` method untuk menggunakan dynamic workflow
- Tambah method `InitiateApprovalFlow()` untuk memulai approval process
- Tambah method `ProcessApprovalStep()` untuk handle approval actions

#### `article_approvals`
- Extend untuk support dynamic workflow
- Integrate dengan `ArticleApprovalStepLogs`

## 5. API Design

### 5.1 Workflow Management APIs:
```
GET    /api/approval-workflows              # List all workflows
POST   /api/approval-workflows              # Create new workflow
GET    /api/approval-workflows/{id}         # Get workflow details
PUT    /api/approval-workflows/{id}         # Update workflow
DELETE /api/approval-workflows/{id}         # Delete workflow

GET    /api/approval-workflows/{id}/steps   # Get workflow steps
POST   /api/approval-workflows/{id}/steps   # Add workflow step
PUT    /api/approval-workflow-steps/{id}    # Update workflow step
DELETE /api/approval-workflow-steps/{id}    # Delete workflow step
```

### 5.2 Article Approval APIs:
```
POST   /api/articles/{id}/submit-approval   # Submit article for approval
POST   /api/articles/{id}/approve            # Approve current step
POST   /api/articles/{id}/reject             # Reject article
POST   /api/articles/{id}/request-revision   # Request revision
GET    /api/articles/{id}/approval-history  # Get approval history
GET    /api/articles/pending-approval       # Get articles pending approval for current user
```

### 5.3 Request/Response Models:

#### Workflow Creation:
```json
{
  "name": "Standard Article Approval",
  "description": "3-level approval process",
  "steps": [
    {
      "stepOrder": 1,
      "userLevelId": 3,
      "isRequired": true,
      "canSkip": false
    },
    {
      "stepOrder": 2,
      "userLevelId": 2,
      "isRequired": true,
      "canSkip": false
    },
    {
      "stepOrder": 3,
      "userLevelId": 1,
      "isRequired": true,
      "canSkip": false
    }
  ]
}
```

#### Approval Action:
```json
{
  "action": "approved", // "approved", "rejected", "revision_requested"
  "message": "Article looks good, approved for next level"
}
```

## 6. Business Logic Flow

### 6.1 Article Submission Flow:
1. Contributor creates article (status: draft)
2. Contributor submits for approval
3. System creates `ArticleApprovalFlow` record
4. System sets article status to "pending approval"
5. System notifies first level approver

### 6.2 Approval Process Flow:
1. Approver receives notification
2. Approver reviews article
3. Approver takes action:
   - **Approve**: Move to next step or publish if final step
   - **Reject**: Set article status to rejected, end flow
   - **Request Revision**: Send back to contributor

### 6.3 Revision Flow:
1. Article returns to contributor
2. Contributor makes revisions
3. Contributor resubmits
4. Approval flow restarts from step 1

## 7. Implementation Phases

### Phase 1: Database & Core Entities
- [ ] Create new database tables
- [ ] Implement new entities
- [ ] Create migration scripts
- [ ] Update existing entities

### Phase 2: Workflow Management
- [ ] Implement `approval_workflows` module
- [ ] Create workflow CRUD operations
- [ ] Implement workflow step management
- [ ] Create admin interface for workflow setup

### Phase 3: Dynamic Approval Engine
- [ ] Implement `article_approval_flows` module
- [ ] Refactor articles service for dynamic approval
- [ ] Create approval processing logic
- [ ] Implement notification system

### Phase 4: API & Integration
- [ ] Create approval APIs
- [ ] Update existing article APIs
- [ ] Implement role-based access control
- [ ] Create approval dashboard

### Phase 5: Testing & Migration
- [ ] Unit tests for all new modules
- [ ] Integration tests for approval flows
- [ ] Data migration from old system
- [ ] Performance testing

## 8. Backward Compatibility

### Migration Strategy:
1. **Dual System**: Run old and new system parallel
2. **Default Workflow**: Create default workflow matching current 3-level system
3. **Gradual Migration**: Migrate existing articles to new system
4. **Fallback**: Keep old approval logic as fallback

### Data Migration:
```sql
-- Create default workflow
INSERT INTO approval_workflows (name, description) 
VALUES ('Legacy 3-Level Approval', 'Default 3-level approval system');

-- Create workflow steps
INSERT INTO approval_workflow_steps (workflow_id, step_order, user_level_id) 
VALUES 
(1, 1, 3), -- Level 3 approver
(1, 2, 2), -- Level 2 approver  
(1, 3, 1); -- Level 1 approver

-- Update existing articles
UPDATE articles SET workflow_id = 1 WHERE workflow_id IS NULL;
```

## 9. Security Considerations

### Access Control:
- **Contributor**: Can only create and edit own articles
- **Approver**: Can only approve articles at their assigned level
- **Admin**: Can manage workflows and override approvals

### Validation:
- Validate user has permission for approval level
- Prevent approval of own articles
- Validate workflow step sequence
- Audit all approval actions

## 10. Performance Considerations

### Optimization:
- Index on `article_approval_flows.article_id`
- Index on `article_approval_flows.workflow_id`
- Index on `article_approval_step_logs.article_flow_id`
- Cache active workflows
- Batch notification processing

### Monitoring:
- Track approval processing time
- Monitor workflow bottlenecks
- Alert on stuck approvals
- Dashboard for approval metrics

## 11. Future Enhancements

### Possible Extensions:
1. **Conditional Workflows**: Different workflows based on article type/category
2. **Parallel Approvals**: Multiple approvers at same level
3. **Time-based Escalation**: Auto-escalate if approval takes too long
4. **External Integrations**: Email/Slack notifications
5. **Approval Templates**: Pre-defined approval messages
6. **Bulk Approvals**: Approve multiple articles at once

---

**Estimasi Waktu Implementasi**: 4-6 minggu
**Kompleksitas**: Medium-High
**Risk Level**: Medium (karena perubahan core business logic)

**Next Steps**: 
1. Review dan approval plan ini
2. Setup development environment
3. Mulai implementasi Phase 1
4. Regular progress review setiap minggu