# API Endpoint Documentation - Hak Akses

## Deskripsi

Dokumentasi ini menjelaskan semua API endpoint yang diperlukan untuk fitur **Hak Akses** di halaman `/pages/Setting/HakAkses.vue`. Endpoint-endpoint ini akan dihubungkan ke backend API yang disediakan oleh tim backend.

---

## Base URL

```
{API_BASE_URL}/api/v1
```

**Catatan:** Ganti `{API_BASE_URL}` dengan URL backend yang sebenarnya (contoh: `http://10.10.123.140:8089/`)

---

## 1. Get List Users

Mengambil daftar semua users beserta roles, groups, dan informasi lainnya yang diperlukan untuk form hak akses.

### Endpoint

```
GET /api/users/list
```

### Request

**Headers:**

```
Content-Type: application/json
Accept: application/json
```

**Query Parameters:** Tidak ad

### Response

**Success (200 OK):**

```json
[
  {
    "id": "user-123",
    "namaLengkap": "John Doe",
    "namaUser": "johndoe",
    "email": "john.doe@example.com",
    "tipeUser": "Super Admin",
    "lastLogin": 1704067200,
    "roles": ["superadmin", "admin"],
    "realmRoles": ["default-roles-sandbox"],
    "accountRoles": [],
    "resourceRoles": [],
    "groups": ["/Instalasi STIM/Devops/Superadmin", "/Instalasi STIM/Admin"],
    "given_name": "John",
    "family_name": "Doe",
    "createdAt": 1704067200,
    "updatedAt": 1704067200
  }
]
```

**Error (500 Internal Server Error):**

```json
{
  "statusCode": 500,
  "statusMessage": "Failed to fetch users"
}
```

### Field Description

- `id`: Unique identifier user
- `namaLengkap`: Nama lengkap user
- `namaUser`: Username untuk login
- `email`: Email user
- `tipeUser`: Tipe/jenis user (contoh: "Super Admin", "Admin Loket", dll)
- `lastLogin`: Timestamp terakhir login (Unix timestamp dalam detik)
- `roles`: Array of role names
- `realmRoles`: Array of realm roles dari Keycloak
- `accountRoles`: Array of account roles
- `resourceRoles`: Array of resource roles
- `groups`: Array of group paths (contoh: "/Instalasi STIM/Devops/Superadmin")
- `given_name`: Nama depan
- `family_name`: Nama belakang
- `createdAt`: Timestamp pembuatan (Unix timestamp dalam detik)
- `updatedAt`: Timestamp update terakhir (Unix timestamp dalam detik)

---

## 2. Get Permissions by Role and Group

Mengambil daftar permissions dari backend berdasarkan role dan group yang dipilih.

### Endpoint

```
GET /api/v1/permission
```

### Request

**Headers:**

```
Content-Type: application/json
Accept: application/json
```

**Query Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `roles` | string | Yes | Role name (contoh: "superadmin", "admin") |
| `groups` | string | Yes | Group name atau group path (contoh: "STIM", "/Instalasi STIM/Devops/Superadmin") |

**Example:**

```
GET /api/v1/permission?roles=superadmin&groups=STIM
```

### Response

**Success (200 OK):**

```json
{
  "message": "Data permission berhasil diambil",
  "data": [
    {
      "id": 1,
      "create": false,
      "read": true,
      "update": false,
      "disable": false,
      "delete": false,
      "active": true,
      "pagename": "Halaman Utama",
      "pagesID": 1,
      "level": 1,
      "sort": 1,
      "parent": null
    },
    {
      "id": 2,
      "create": false,
      "read": true,
      "update": false,
      "disable": false,
      "delete": false,
      "active": true,
      "pagename": "Pengaturan",
      "pagesID": 2,
      "level": 1,
      "sort": 2,
      "parent": null
    },
    {
      "id": 3,
      "create": true,
      "read": true,
      "update": true,
      "disable": true,
      "delete": false,
      "active": true,
      "pagename": "Hak Akses",
      "pagesID": 3,
      "level": 2,
      "sort": 3,
      "parent": 2
    }
  ],
  "meta": {
    "count": 3,
    "total": 3
  }
}
```

**Error (400 Bad Request):**

```json
{
  "statusCode": 400,
  "statusMessage": "roles or groups parameter is required"
}
```

**Error (500 Internal Server Error):**

```json
{
  "message": "Failed to fetch permissions",
  "data": [],
  "meta": {
    "count": 0,
    "total": 0
  }
}
```

### Field Description

- `id`: Unique identifier permission
- `create`: Boolean, permission untuk create/tambah data
- `read`: Boolean, permission untuk read/lihat data
- `update`: Boolean, permission untuk update/edit data
- `disable`: Boolean, permission untuk disable/nonaktifkan
- `delete`: Boolean, permission untuk delete/hapus data
- `active`: Boolean, status aktif permission
- `pagename`: Nama halaman/menu (akan di-mapping ke menu sidebar)
- `pagesID`: ID halaman di sistem backend
- `level`: Level hierarki menu (1 = parent, 2 = child, dll)
- `sort`: Urutan tampil
- `parent`: ID parent menu (null jika parent menu)

---

## 3. Get List Hak Akses

Mengambil daftar semua hak akses yang sudah tersimpan.

### Endpoint

```
GET /api/v1/hak-akses
```

### Request

**Headers:**

```
Content-Type: application/json
Accept: application/json
```

**Query Parameters:** Tidak ada

### Response

**Success (200 OK):**

```json
[
  {
    "id": 1,
    "userId": "user-123",
    "namaLengkap": "John Doe",
    "namaUser": "johndoe",
    "tipeUser": "Super Admin",
    "role": "superadmin",
    "group": "STIM",
    "groupPath": "/Instalasi STIM/Devops/Superadmin",
    "namaTipeUser": "Super Admin",
    "hakAksesMenu": [
      {
        "name": "Dashboard",
        "canAccess": true,
        "canView": true,
        "canAdd": false,
        "canEdit": false,
        "canDelete": false
      },
      {
        "name": "Master Data",
        "canAccess": true,
        "canView": true,
        "canAdd": true,
        "canEdit": true,
        "canDelete": false
      }
    ],
    "isGroupBased": true,
    "createdAt": 1704067200,
    "updatedAt": 1704067200
  }
]
```

**Error (500 Internal Server Error):**

```json
{
  "statusCode": 500,
  "statusMessage": "Failed to fetch hak akses"
}
```

### Field Description

- `id`: Unique identifier hak akses
- `userId`: ID user (optional, untuk backward compatibility)
- `namaLengkap`: Nama lengkap user (optional)
- `namaUser`: Username (optional)
- `tipeUser`: Tipe user (optional)
- `role`: Role name (required)
- `group`: Group name (required)
- `groupPath`: Full group path (optional, untuk group-based access)
- `namaTipeUser`: Nama tipe user (optional)
- `hakAksesMenu`: Array of menu permissions
  - `name`: Nama menu
  - `canAccess`: Boolean, apakah bisa akses menu
  - `canView`: Boolean, apakah bisa lihat data
  - `canAdd`: Boolean, apakah bisa tambah data
  - `canEdit`: Boolean, apakah bisa edit data
  - `canDelete`: Boolean, apakah bisa hapus data
- `isGroupBased`: Boolean, apakah hak akses ini group-based (true) atau individual (false)
- `createdAt`: Timestamp pembuatan (Unix timestamp dalam detik)
- `updatedAt`: Timestamp update terakhir (Unix timestamp dalam detik)

---

## 4. Create Hak Akses

Membuat hak akses baru (group-based atau individual).

### Endpoint

```
POST /api/v1/hak-akses
```

### Request

**Headers:**

```
Content-Type: application/json
Accept: application/json
```

**Body:**

```json
{
  "role": "superadmin",
  "group": "STIM",
  "groupPath": "/Instalasi STIM/Devops/Superadmin",
  "namaTipeUser": "Super Admin",
  "hakAksesMenu": [
    {
      "name": "Dashboard",
      "canAccess": true,
      "canView": true,
      "canAdd": false,
      "canEdit": false,
      "canDelete": false
    },
    {
      "name": "Master Data",
      "canAccess": true,
      "canView": true,
      "canAdd": true,
      "canEdit": true,
      "canDelete": false
    }
  ],
  "isGroupBased": true
}
```

### Response

**Success (201 Created):**

```json
{
  "success": true,
  "message": "Hak akses berhasil dibuat",
  "data": {
    "id": 1,
    "role": "superadmin",
    "group": "STIM",
    "groupPath": "/Instalasi STIM/Devops/Superadmin",
    "namaTipeUser": "Super Admin",
    "hakAksesMenu": [
      {
        "name": "Dashboard",
        "canAccess": true,
        "canView": true,
        "canAdd": false,
        "canEdit": false,
        "canDelete": false
      }
    ],
    "isGroupBased": true,
    "createdAt": 1704067200,
    "updatedAt": 1704067200
  }
}
```

**Error (400 Bad Request):**

```json
{
  "statusCode": 400,
  "statusMessage": "role and group are required"
}
```

**Error (409 Conflict):**

```json
{
  "statusCode": 409,
  "statusMessage": "Hak akses untuk group dan role ini sudah ada"
}
```

### Field Description

**Required Fields:**

- `role`: Role name (string, required)
- `group`: Group name (string, required)
- `hakAksesMenu`: Array of menu permissions (array, required)

**Optional Fields:**

- `userId`: ID user (string, optional)
- `namaLengkap`: Nama lengkap (string, optional)
- `namaUser`: Username (string, optional)
- `tipeUser`: Tipe user (string, optional)
- `groupPath`: Full group path (string, optional)
- `namaTipeUser`: Nama tipe user (string, optional)
- `isGroupBased`: Boolean, default true (boolean, optional)

---

## 5. Update Hak Akses

Mengupdate hak akses yang sudah ada.

### Endpoint

```
PATCH /api/v1/hak-akses/{id}
```

### Request

**Headers:**

```
Content-Type: application/json
Accept: application/json
```

**Path Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | integer | Yes | ID hak akses yang akan diupdate |

**Body (semua field optional, hanya kirim field yang ingin diupdate):**

```json
{
  "role": "admin",
  "group": "LOKET",
  "namaTipeUser": "Admin Loket",
  "hakAksesMenu": [
    {
      "name": "Dashboard",
      "canAccess": true,
      "canView": true,
      "canAdd": false,
      "canEdit": false,
      "canDelete": false
    }
  ]
}
```

### Response

**Success (200 OK):**

```json
{
  "success": true,
  "message": "Hak akses berhasil diperbarui",
  "data": {
    "id": 1,
    "role": "admin",
    "group": "LOKET",
    "groupPath": "/Instalasi STIM/Loket",
    "namaTipeUser": "Admin Loket",
    "hakAksesMenu": [
      {
        "name": "Dashboard",
        "canAccess": true,
        "canView": true,
        "canAdd": false,
        "canEdit": false,
        "canDelete": false
      }
    ],
    "isGroupBased": true,
    "createdAt": 1704067200,
    "updatedAt": 1704067300
  }
}
```

**Error (400 Bad Request):**

```json
{
  "statusCode": 400,
  "statusMessage": "ID is required"
}
```

**Error (404 Not Found):**

```json
{
  "statusCode": 404,
  "statusMessage": "Hak akses not found"
}
```

**Error (500 Internal Server Error):**

```json
{
  "statusCode": 500,
  "statusMessage": "Failed to update hak akses"
}
```

---

## 6. Delete Hak Akses

Menghapus hak akses.

### Endpoint

```
DELETE /api/v1/hak-akses/{id}
```

### Request

**Headers:**

```
Content-Type: application/json
Accept: application/json
```

**Path Parameters:**
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | integer | Yes | ID hak akses yang akan dihapus |

### Response

**Success (200 OK):**

```json
{
  "success": true,
  "message": "Hak akses berhasil dihapus"
}
```

**Error (400 Bad Request):**

```json
{
  "statusCode": 400,
  "statusMessage": "ID is required"
}
```

**Error (404 Not Found):**

```json
{
  "statusCode": 404,
  "statusMessage": "Hak akses not found"
}
```

**Error (500 Internal Server Error):**

```json
{
  "statusCode": 500,
  "statusMessage": "Failed to delete hak akses"
}
```

---

## Mapping Permissions ke Menu Sidebar

Sistem akan otomatis memetakan `pagename` dari API permission ke nama menu di sidebar. Mapping dilakukan dengan:

1. **Exact match**: `pagename.toLowerCase() === menu.name.toLowerCase()`
2. **Partial match**: `pagename.toLowerCase().includes(menu.name.toLowerCase())` atau sebaliknya

### Contoh Mapping:

- `pagename: "Halaman Utama"` → Menu: "Dashboard"
- `pagename: "Pengaturan"` → Menu: "Master Data"
- `pagename: "Hak Akses"` → Menu: "Hak Akses"

### Permission Mapping:

- `read: true` → `canView: true`
- `create: true` → `canAdd: true`
- `update: true` → `canEdit: true`
- `delete: true` → `canDelete: true`
- `active: true || read: true` → `canAccess: true`

---

## Group-Based Access

Sistem mendukung **Group-Based Access** dimana:

- Satu hak akses dapat diberikan ke semua user yang memiliki group dan role yang sama
- Setiap user dapat memiliki multiple hak akses dari berbagai group
- Hak akses disimpan dengan flag `isGroupBased: true` dan `groupPath` untuk identifikasi

### Contoh:

Jika hak akses dibuat dengan:

- `role: "superadmin"`
- `groupPath: "/Instalasi STIM/Devops/Superadmin"`
- `isGroupBased: true`

Maka semua user yang memiliki:

- Role: "superadmin" **DAN**
- Group: "/Instalasi STIM/Devops/Superadmin"

Akan otomatis mendapatkan hak akses tersebut.

---

## Error Handling

Semua endpoint harus mengembalikan error dengan format konsisten:

```json
{
  "statusCode": 400|404|409|500,
  "statusMessage": "Error message description"
}
```

**HTTP Status Codes:**

- `200 OK`: Request berhasil
- `201 Created`: Resource berhasil dibuat
- `400 Bad Request`: Request tidak valid (missing required fields, invalid format)
- `404 Not Found`: Resource tidak ditemukan
- `409 Conflict`: Resource sudah ada (untuk create duplicate)
- `500 Internal Server Error`: Server error

---

## Authentication

**Catatan:** Tim backend perlu menentukan apakah endpoint-endpoint ini memerlukan authentication token atau tidak. Jika diperlukan, tambahkan:

**Headers:**

```
Authorization: Bearer {access_token}
```

---

## Testing

### Contoh Request dengan cURL:

**1. Get Users List:**

```bash
curl -X GET "http://{API_BASE_URL}/api/users/list" \
  -H "Content-Type: application/json"
```

**2. Get Permissions:**

```bash
curl -X GET "http://{API_BASE_URL}/api/v1/permission?roles=superadmin&groups=STIM" \
  -H "Content-Type: application/json"
```

**3. Create Hak Akses:**

```bash
curl -X POST "http://{API_BASE_URL}/api/v1/hak-akses" \
  -H "Content-Type: application/json" \
  -d '{
    "role": "superadmin",
    "group": "STIM",
    "groupPath": "/Instalasi STIM/Devops/Superadmin",
    "namaTipeUser": "Super Admin",
    "hakAksesMenu": [
      {
        "name": "Dashboard",
        "canAccess": true,
        "canView": true,
        "canAdd": false,
        "canEdit": false,
        "canDelete": false
      }
    ],
    "isGroupBased": true
  }'
```

**4. Update Hak Akses:**

```bash
curl -X PATCH "http://{API_BASE_URL}/api/v1/hak-akses/1" \
  -H "Content-Type: application/json" \
  -d '{
    "namaTipeUser": "Updated Admin",
    "hakAksesMenu": [...]
  }'
```

**5. Delete Hak Akses:**

```bash
curl -X DELETE "http://{API_BASE_URL}/api/v1/hak-akses/1" \
  -H "Content-Type: application/json"
```

---

## Catatan Penting

1. **Base URL**: Ganti `{API_BASE_URL}` dengan URL backend yang sebenarnya
2. **Timestamps**: Semua timestamp menggunakan format Unix timestamp (detik sejak epoch)
3. **Group Path**: Group path harus full path (contoh: "/Instalasi STIM/Devops/Superadmin") untuk group-based access
4. **Menu Permissions**: Array `hakAksesMenu` harus sesuai dengan struktur menu sidebar
5. **Validation**: Backend harus melakukan validasi untuk:
   - Required fields (role, group, hakAksesMenu)
   - Duplicate check untuk group+role combination (jika isGroupBased = true)
   - Format data yang valid

---

## Kontak

Jika ada pertanyaan atau perubahan requirement, silakan hubungi tim frontend.
