# API Documentation - Sistem Approval Artikel Dinamis

## Overview
Dokumentasi ini menjelaskan API endpoints yang tersedia untuk sistem approval artikel dinamis. Sistem ini memungkinkan pembuatan workflow approval yang fleksibel dengan multiple level dan proses revisi.

## Base URL
```
http://localhost:8800/api
```

## Authentication
Semua endpoint memerlukan Bearer token authentication:
```
Authorization: Bearer <your_jwt_token>
```

## 1. Approval Workflows Management

### 1.1 Get All Workflows
```http
GET /approval-workflows
```

**Query Parameters:**
- `page` (optional): Page number (default: 1)
- `limit` (optional): Items per page (default: 10)
- `search` (optional): Search by workflow name
- `is_active` (optional): Filter by active status (true/false)

**Response:**
```json
{
  "success": true,
  "messages": ["Workflows retrieved successfully"],
  "data": [
    {
      "id": 1,
      "name": "Standard 3-Level Approval",
      "description": "Default workflow with 3 approval levels",
      "is_active": true,
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:30:00Z",
      "steps": [
        {
          "id": 1,
          "step_order": 1,
          "user_level_id": 3,
          "user_level": {
            "id": 3,
            "level_name": "Approver Level 3",
            "level_number": 3
          },
          "is_required": true,
          "can_skip": false
        }
      ]
    }
  ],
  "pagination": {
    "current_page": 1,
    "per_page": 10,
    "total": 5,
    "total_pages": 1
  }
}
```

### 1.2 Get Workflow by ID
```http
GET /approval-workflows/{id}
```

**Response:**
```json
{
  "success": true,
  "messages": ["Workflow retrieved successfully"],
  "data": {
    "id": 1,
    "name": "Standard 3-Level Approval",
    "description": "Default workflow with 3 approval levels",
    "is_active": true,
    "steps": [
      {
        "id": 1,
        "step_order": 1,
        "user_level_id": 3,
        "is_required": true,
        "can_skip": false
      }
    ]
  }
}
```

### 1.3 Create New Workflow
```http
POST /approval-workflows
```

**Request Body:**
```json
{
  "name": "Custom 2-Level Approval",
  "description": "Fast track approval for urgent articles",
  "steps": [
    {
      "stepOrder": 1,
      "userLevelId": 2,
      "isRequired": true,
      "canSkip": false
    },
    {
      "stepOrder": 2,
      "userLevelId": 1,
      "isRequired": true,
      "canSkip": false
    }
  ]
}
```

**Validation Rules:**
- `name`: Required, max 255 characters
- `steps`: Required, minimum 1 step
- `stepOrder`: Must be sequential starting from 1
- `userLevelId`: Must exist in user_levels table

**Response:**
```json
{
  "success": true,
  "messages": ["Workflow created successfully"],
  "data": {
    "id": 5,
    "name": "Custom 2-Level Approval",
    "description": "Fast track approval for urgent articles",
    "is_active": true,
    "created_at": "2024-01-15T14:30:00Z"
  }
}
```

### 1.4 Update Workflow
```http
PUT /approval-workflows/{id}
```

**Request Body:**
```json
{
  "name": "Updated Workflow Name",
  "description": "Updated description",
  "is_active": true
}
```

### 1.5 Delete Workflow
```http
DELETE /approval-workflows/{id}
```

**Note:** Workflow can only be deleted if no articles are currently using it.

## 2. Article Approval Management

### 2.1 Submit Article for Approval
```http
POST /articles/{id}/submit-approval
```

**Request Body:**
```json
{
  "workflowId": 2
}
```

**Response:**
```json
{
  "success": true,
  "messages": ["Article submitted for approval successfully"],
  "data": {
    "id": 15,
    "article_id": 123,
    "workflow_id": 2,
    "current_step": 1,
    "status_id": 1,
    "created_at": "2024-01-15T15:00:00Z"
  }
}
```

### 2.2 Approve Current Step
```http
POST /articles/{id}/approve
```

**Request Body:**
```json
{
  "message": "Article content is excellent, approved for next level"
}
```

**Response:**
```json
{
  "success": true,
  "messages": ["Article approved successfully"],
  "data": {
    "next_step": 2,
    "status": "moved_to_next_level"
  }
}
```

### 2.3 Reject Article
```http
POST /articles/{id}/reject
```

**Request Body:**
```json
{
  "message": "Article does not meet quality standards"
}
```

**Response:**
```json
{
  "success": true,
  "messages": ["Article rejected successfully"]
}
```

### 2.4 Request Revision
```http
POST /articles/{id}/request-revision
```

**Request Body:**
```json
{
  "message": "Please fix grammar issues in paragraph 3 and add more references"
}
```

**Response:**
```json
{
  "success": true,
  "messages": ["Revision requested successfully"]
}
```

### 2.5 Resubmit After Revision
```http
POST /articles/{id}/resubmit
```

**Request Body:**
```json
{
  "message": "Fixed all requested issues"
}
```

**Response:**
```json
{
  "success": true,
  "messages": ["Article resubmitted successfully"],
  "data": {
    "current_step": 1,
    "status": "back_in_approval_flow"
  }
}
```

## 3. Approval Dashboard

### 3.1 Get Pending Approvals for Current User
```http
GET /approvals/pending
```

**Query Parameters:**
- `page` (optional): Page number (default: 1)
- `limit` (optional): Items per page (default: 10, max: 50)
- `priority` (optional): Filter by priority (high, medium, low)
- `category_id` (optional): Filter by article category
- `search` (optional): Search in article title or author name
- `date_from` (optional): Filter articles submitted from date (YYYY-MM-DD)
- `date_to` (optional): Filter articles submitted to date (YYYY-MM-DD)
- `sort_by` (optional): Sort by field (waiting_time, created_at, title, priority)
- `sort_order` (optional): Sort order (asc, desc) - default: desc
- `workflow_id` (optional): Filter by specific workflow

**Response:**
```json
{
  "success": true,
  "messages": ["Pending approvals retrieved successfully"],
  "data": [
    {
      "id": 15,
      "article": {
        "id": 123,
        "title": "Understanding Machine Learning",
        "excerpt": "This article explores the fundamentals of machine learning...",
        "author": {
          "id": 45,
          "name": "John Doe",
          "email": "john@example.com",
          "profile_picture": "https://example.com/avatar.jpg"
        },
        "category": {
          "id": 5,
          "name": "Technology",
          "color": "#3B82F6"
        },
        "word_count": 1250,
        "estimated_read_time": "5 min",
        "created_at": "2024-01-15T10:00:00Z",
        "submitted_at": "2024-01-15T14:30:00Z"
      },
      "workflow": {
        "id": 2,
        "name": "Standard 3-Level Approval",
        "total_steps": 3
      },
      "current_step": 2,
      "my_step_order": 2,
      "waiting_since": "2024-01-15T14:30:00Z",
      "waiting_duration_hours": 6.5,
      "priority": "medium",
      "previous_approvals": [
        {
          "step_order": 1,
          "approver_name": "Jane Smith",
          "approved_at": "2024-01-15T14:30:00Z",
          "message": "Content looks good"
        }
      ],
      "urgency_score": 7.5,
      "can_approve": true,
      "can_reject": true,
      "can_request_revision": true
    }
  ],
  "pagination": {
    "current_page": 1,
    "per_page": 10,
    "total": 5,
    "total_pages": 1
  },
  "summary": {
    "total_pending": 5,
    "high_priority": 2,
    "medium_priority": 2,
    "low_priority": 1,
    "overdue_count": 1,
    "avg_waiting_hours": 8.2
  }
}
```

### 3.2 Get Approval History for Article
```http
GET /articles/{id}/approval-history
```

**Response:**
```json
{
  "success": true,
  "messages": ["Approval history retrieved successfully"],
  "data": {
    "article_id": 123,
    "workflow": {
      "id": 2,
      "name": "Standard 3-Level Approval"
    },
    "current_step": 2,
    "status": "in_progress",
    "history": [
      {
        "id": 1,
        "step_order": 1,
        "action": "approved",
        "message": "Good content, approved",
        "approver": {
          "id": 67,
          "name": "Jane Smith",
          "level": "Approver Level 3"
        },
        "approved_at": "2024-01-15T14:30:00Z"
      }
    ]
  }
}
```

### 3.3 Get My Approval Statistics
```http
GET /approvals/my-stats
```

**Response:**
```json
{
  "success": true,
  "messages": ["Statistics retrieved successfully"],
  "data": {
    "pending_count": 5,
    "overdue_count": 1,
    "approved_today": 3,
    "approved_this_week": 15,
    "approved_this_month": 45,
    "rejected_this_month": 2,
    "revision_requests_this_month": 8,
    "average_approval_time_hours": 4.5,
    "fastest_approval_minutes": 15,
    "slowest_approval_hours": 48,
    "approval_rate_percentage": 85.2,
    "categories_breakdown": [
      {
        "category_name": "Technology",
        "pending": 2,
        "approved_this_month": 12
      },
      {
        "category_name": "Health",
        "pending": 3,
        "approved_this_month": 8
      }
    ]
  }
}
```

### 3.4 Get Articles Requiring My Approval (Detailed View)
```http
GET /approvals/my-queue
```

**Query Parameters:**
- Same as `/approvals/pending` but specifically filtered for current user's level
- `include_preview` (optional): Include article content preview (true/false)
- `urgency_only` (optional): Show only urgent articles (true/false)

**Response:**
```json
{
  "success": true,
  "messages": ["My approval queue retrieved successfully"],
  "data": [
    {
      "id": 15,
      "article": {
        "id": 123,
        "title": "Understanding Machine Learning",
        "content_preview": "Machine learning is a subset of artificial intelligence that enables computers to learn and improve from experience without being explicitly programmed...",
        "full_content_available": true,
        "author": {
          "id": 45,
          "name": "John Doe",
          "reputation_score": 8.5,
          "articles_published": 25,
          "approval_success_rate": 92.3
        },
        "submission_notes": "This is an updated version based on previous feedback",
        "tags": ["AI", "Technology", "Education"],
        "seo_score": 85,
        "readability_score": "Good"
      },
      "approval_context": {
        "my_role_in_workflow": "Senior Editor Review",
        "step_description": "Review content quality and technical accuracy",
        "expected_action": "Approve or request technical revisions",
        "deadline": "2024-01-16T18:00:00Z",
        "is_overdue": false,
        "escalation_available": true
      },
      "workflow_progress": {
        "completed_steps": 1,
        "total_steps": 3,
        "progress_percentage": 33.3,
        "next_approver": "Chief Editor"
      }
    }
  ]
}
```

### 3.5 Get Approval Workload Distribution
```http
GET /approvals/workload
```

**Response:**
```json
{
  "success": true,
  "messages": ["Workload distribution retrieved successfully"],
  "data": {
    "my_level": {
      "level_name": "Senior Editor",
      "level_number": 2,
      "pending_articles": 5,
      "avg_daily_approvals": 8.5
    },
    "team_comparison": [
      {
        "approver_name": "Jane Smith",
        "level_name": "Senior Editor",
        "pending_articles": 3,
        "avg_response_time_hours": 2.5
      },
      {
        "approver_name": "Mike Johnson",
        "level_name": "Senior Editor",
        "pending_articles": 7,
        "avg_response_time_hours": 4.2
      }
    ],
    "bottlenecks": [
      {
        "level_name": "Chief Editor",
        "pending_count": 12,
        "avg_waiting_time_hours": 18.5,
        "is_bottleneck": true
      }
    ]
  }
}
```

### 3.6 Bulk Approval Actions
```http
POST /approvals/bulk-action
```

**Request Body:**
```json
{
  "article_ids": [123, 124, 125],
  "action": "approve",
  "message": "Bulk approval for similar content type",
  "apply_to_similar": false
}
```

**Response:**
```json
{
  "success": true,
  "messages": ["Bulk action completed successfully"],
  "data": {
    "processed_count": 3,
    "successful_count": 3,
    "failed_count": 0,
    "results": [
      {
        "article_id": 123,
        "status": "success",
        "next_step": 3
      },
      {
        "article_id": 124,
        "status": "success",
        "next_step": 3
      },
      {
        "article_id": 125,
        "status": "success",
        "next_step": "published"
      }
    ]
  }
}
```

## 4. User Level Management

### 4.1 Get Available User Levels
```http
GET /user-levels
```

**Response:**
```json
{
  "success": true,
  "messages": ["User levels retrieved successfully"],
  "data": [
    {
      "id": 1,
      "level_name": "Chief Editor",
      "level_number": 1,
      "parent_level_id": null,
      "is_approval_active": true
    },
    {
      "id": 2,
      "level_name": "Senior Editor",
      "level_number": 2,
      "parent_level_id": 1,
      "is_approval_active": true
    },
    {
      "id": 3,
      "level_name": "Junior Editor",
      "level_number": 3,
      "parent_level_id": 2,
      "is_approval_active": true
    }
  ]
}
```

## 5. Error Responses

### 5.1 Validation Error (400)
```json
{
  "success": false,
  "messages": ["Validation failed"],
  "errors": {
    "name": ["Name is required"],
    "steps": ["At least one step is required"]
  }
}
```

### 5.2 Unauthorized (401)
```json
{
  "success": false,
  "messages": ["Unauthorized access"]
}
```

### 5.3 Forbidden (403)
```json
{
  "success": false,
  "messages": ["You don't have permission to approve this article"]
}
```

### 5.4 Not Found (404)
```json
{
  "success": false,
  "messages": ["Article not found"]
}
```

### 5.5 Business Logic Error (422)
```json
{
  "success": false,
  "messages": ["Article already has active approval flow"]
}
```

### 5.6 Internal Server Error (500)
```json
{
  "success": false,
  "messages": ["Internal server error occurred"]
}
```

## 6. Webhook Events (Optional)

Sistem dapat mengirim webhook notifications untuk event-event penting:

### 6.1 Article Submitted for Approval
```json
{
  "event": "article.submitted_for_approval",
  "timestamp": "2024-01-15T15:00:00Z",
  "data": {
    "article_id": 123,
    "workflow_id": 2,
    "submitted_by": {
      "id": 45,
      "name": "John Doe"
    },
    "next_approver_level": 3
  }
}
```

### 6.2 Article Approved
```json
{
  "event": "article.approved",
  "timestamp": "2024-01-15T16:00:00Z",
  "data": {
    "article_id": 123,
    "approved_by": {
      "id": 67,
      "name": "Jane Smith",
      "level": 3
    },
    "current_step": 2,
    "is_final_approval": false
  }
}
```

### 6.3 Article Published
```json
{
  "event": "article.published",
  "timestamp": "2024-01-15T17:00:00Z",
  "data": {
    "article_id": 123,
    "final_approver": {
      "id": 89,
      "name": "Chief Editor",
      "level": 1
    },
    "total_approval_time_hours": 6.5
  }
}
```

### 6.4 Revision Requested
```json
{
  "event": "article.revision_requested",
  "timestamp": "2024-01-15T16:30:00Z",
  "data": {
    "article_id": 123,
    "requested_by": {
      "id": 67,
      "name": "Jane Smith",
      "level": 2
    },
    "message": "Please fix grammar issues",
    "author": {
      "id": 45,
      "name": "John Doe"
    }
  }
}
```

## 7. Rate Limiting

API menggunakan rate limiting untuk mencegah abuse:
- **General endpoints**: 100 requests per minute per user
- **Approval actions**: 50 requests per minute per user
- **Workflow management**: 20 requests per minute per user

## 8. Pagination

Semua endpoint yang mengembalikan list menggunakan pagination:
- Default `limit`: 10
- Maximum `limit`: 100
- Default `page`: 1

## 9. Filtering dan Sorting

Beberapa endpoint mendukung filtering dan sorting:

### Query Parameters untuk Filtering:
- `status`: Filter by status
- `user_level`: Filter by user level
- `date_from`: Filter from date (YYYY-MM-DD)
- `date_to`: Filter to date (YYYY-MM-DD)
- `search`: Search in title/content

### Query Parameters untuk Sorting:
- `sort_by`: Field to sort by (created_at, updated_at, title, etc.)
- `sort_order`: asc atau desc (default: desc)

Contoh:
```
GET /articles?status=pending&sort_by=created_at&sort_order=asc&page=1&limit=20
```

## 10. Bulk Operations

### 10.1 Bulk Approve Articles
```http
POST /articles/bulk-approve
```

**Request Body:**
```json
{
  "article_ids": [123, 124, 125],
  "message": "Bulk approval for similar articles"
}
```

### 10.2 Bulk Assign Workflow
```http
POST /articles/bulk-assign-workflow
```

**Request Body:**
```json
{
  "article_ids": [123, 124, 125],
  "workflow_id": 2
}
```

Dokumentasi API ini memberikan panduan lengkap untuk mengintegrasikan sistem approval artikel dinamis dengan frontend atau sistem eksternal lainnya.