# BAGIAN 2: INTEGRASI FE-BE
## (Frontend-Backend Integration Flow)

---

## 2.1 API Integration Map — 5 Fitur Utama

Diagram ini menunjukkan mapping lengkap antara Frontend modules, API endpoints, dan Backend services untuk setiap fitur utama.

```mermaid
flowchart LR
    subgraph FE["FRONTEND (React 19)"]
        direction TB
        FE1["🔐 Auth Pages<br/>sign-in, sign-up,<br/>forgot/reset password"]
        FE2["💬 Chat Pages<br/>82 files<br/>conversations, messages"]
        FE3["📢 Campaign Pages<br/>33 files<br/>templates, recipients"]
        FE4["🎫 Ticket Pages<br/>25 files<br/>CRUD, lifecycle"]
        FE5["⚙️ Settings Pages<br/>20+ pages<br/>admin configuration"]
    end

    subgraph API["API LAYER (Hono /api/v1)"]
        direction TB
        API1["/auth/*<br/>sign-in, sign-up,<br/>forget-password,<br/>change-password,<br/>admin/*, organization/*"]
        API2["/u/conversations<br/>/u/conversation-messages<br/>/u/channels<br/>/u/contacts<br/>/u/notes"]
        API3["/u/campaigns<br/>/u/campaign-recipient-lists<br/>/u/campaign-recipient-list-items<br/>/u/templates"]
        API4["/u/tickets<br/>/u/ticket-history"]
        API5["/u/workspaces<br/>/u/workspace-members<br/>/u/workspace-api-keys<br/>/u/channels<br/>/u/tags<br/>/u/user<br/>/u/role-permissions<br/>/u/message-templates<br/>/u/office-hour-*<br/>/u/conversation-resolve-category"]
    end

    subgraph BE["BACKEND SERVICES"]
        direction TB
        BS1["better-auth<br/>session, RBAC,<br/>API keys"]
        BS2["conversation<br/>conversation-message<br/>channel<br/>contact<br/>note<br/>tag"]
        BS3["campaign<br/>campaign-recipient-list<br/>template<br/>whatsapp-template"]
        BS4["ticket<br/>ticket-history<br/>ticket-attachment"]
        BS5["workspace<br/>workspace-members<br/>workspace-api-key<br/>role-permission<br/>channel<br/>tag<br/>message-template<br/>office-hour-schedule<br/>office-hour-response<br/>conv-resolve-category"]
    end

    FE1 -->|"POST /auth/sign-in<br/>POST /auth/forget-password<br/>POST /auth/change-password<br/>POST /auth/admin/*<br/>POST /auth/organization/*"| API1
    FE2 -->|"GET /conversations<br/>POST /conversation-messages<br/>PATCH /conversations/:id/status<br/>POST /conversations/:id/read<br/>GET /conversation-messages<br/>POST /conversation-messages/template<br/>POST /conversation-messages/upload-media"| API2
    FE3 -->|"CRUD /campaigns<br/>POST /campaigns/:id/execute<br/>CRUD /templates<br/>POST /templates/:id/sync<br/>CRUD /campaign-recipient-lists<br/>POST /templates/upload-media"| API3
    FE4 -->|"CRUD /tickets<br/>GET /ticket-history/ticket/:id<br/>POST /tickets/upload-media<br/>DELETE /tickets/remove-media/:id"| API4
    FE5 -->|"CRUD /workspaces<br/>CRUD /workspace-members<br/>CRUD /channels<br/>CRUD /tags<br/>PUT /user/update-user<br/>POST /auth/change-password<br/>CRUD /role-permissions<br/>CRUD /message-templates<br/>CRUD /office-hour-*<br/>CRUD /conversation-resolve-category<br/>CRUD /workspace-api-keys"| API5

    API1 --> BS1
    API2 --> BS2
    API3 --> BS3
    API4 --> BS4
    API5 --> BS5

    style FE fill:#E3F2FD,stroke:#1976D2
    style API fill:#FFF8E1,stroke:#F9A825
    style BE fill:#FCE4EC,stroke:#C2185B
```

---

## 2.2 Real-Time Integration Flow

Alur komunikasi real-time dari webhook masuk hingga update UI di browser agent.

```mermaid
flowchart TD
    subgraph EXTERNAL["EXTERNAL CHANNELS"]
        WA_MSG["📱 WhatsApp<br/>Message from Customer"]
        IG_MSG["📸 Instagram<br/>DM / Comment"]
        TG_MSG["✈️ Telegram<br/>Message from User"]
    end

    subgraph BE_RECEIVE["BACKEND - Webhook Receivers"]
        WH_WA["POST /api/webhook/whatsapp"]
        WH_IG["POST /api/webhook/instagram"]
        WH_TG["POST /api/webhook/telegram"]
    end

    subgraph BE_PROCESS["BACKEND - Processing"]
        RABBIT["RabbitMQ Queue<br/>omnichannel_work_queue"]
        PROCESSOR["Message Processor Service"]
        DB_WRITE["PostgreSQL<br/>INSERT conversations<br/>INSERT conversation_messages"]
        PUSHER_S["Pusher Server<br/>Trigger Events"]
        SOCKET_S["Socket.IO Server<br/>Emit Events"]
    end

    subgraph FE_RECEIVE["FRONTEND - Real-time Clients"]
        PUSHER_C["Pusher Client<br/>use-pusher-chat.ts<br/>Subscribe: private-room:*<br/>private-channel:*"]
        SOCKET_C["Socket.IO Client<br/>use-socket-io.ts<br/>Listen: new-message<br/>new-conversation"]
        SWR_CACHE["SWR Cache<br/>Automatic Revalidation<br/>mutate() on events"]
        UI["UI Components<br/>ChatNav, ChatMessageList<br/>Auto Update"]
    end

    WA_MSG -->|"HTTP POST"| WH_WA
    IG_MSG -->|"HTTP POST"| WH_IG
    TG_MSG -->|"HTTP POST"| WH_TG

    WH_WA -->|"Publish to Queue"| RABBIT
    WH_IG -->|"Direct Process"| PROCESSOR
    WH_TG -->|"Direct Process"| PROCESSOR
    RABBIT -->|"Consume"| PROCESSOR

    PROCESSOR --> DB_WRITE
    PROCESSOR --> PUSHER_S
    PROCESSOR --> SOCKET_S

    PUSHER_S -->|"private-room:{convId}<br/>Event: new-message"| PUSHER_C
    PUSHER_S -->|"private-channel:{chId}<br/>Event: new-conversation"| PUSHER_C
    SOCKET_S -->|"Event: new-message"| SOCKET_C
    SOCKET_S -->|"Event: conversation-updated"| SOCKET_C

    PUSHER_C --> SWR_CACHE
    SOCKET_C --> SWR_CACHE
    SWR_CACHE --> UI

    style EXTERNAL fill:#E8F5E9,stroke:#4CAF50
    style BE_RECEIVE fill:#FFF3E0,stroke:#FF9800
    style BE_PROCESS fill:#FCE4EC,stroke:#E91E63
    style FE_RECEIVE fill:#E3F2FD,stroke:#2196F3
```

---

## 2.3 Real-Time Event Types

Tabel event real-time yang digunakan dalam sistem.

```mermaid
flowchart TD
    subgraph EVENTS["Real-Time Events"]
        direction TB
        E1["new-message<br/>Pesan baru masuk/terkirim"]
        E2["new-conversation<br/>Conversation baru dibuat"]
        E3["message-updated<br/>Status pesan berubah<br/>(SENT → DELIVERED → READ)"]
        E4["conversation-updated<br/>Status/assignee conversation berubah"]
        E5["new-post-comment<br/>Komentar baru di Instagram post"]
        E6["post-updated<br/>Instagram post diupdate"]
    end

    subgraph CHANNELS["Pusher Channels"]
        C1["private-room:{conversationId}<br/>Event: new-message, message-updated"]
        C2["private-channel:{channelId}<br/>Event: new-conversation, conversation-updated"]
        C3["private-post:{postId}<br/>Event: new-post-comment, post-updated"]
    end

    E1 --> C1
    E2 --> C2
    E3 --> C1
    E4 --> C2
    E5 --> C3
    E6 --> C3

    style EVENTS fill:#F3E5F5,stroke:#9C27B0
    style CHANNELS fill:#E8EAF6,stroke:#3F51B5
```

---

## 2.4 Authentication Integration Flow

Alur integrasi autentikasi antara FE dan BE.

```mermaid
flowchart TD
    subgraph FE_AUTH["FRONTEND - Auth Context"]
        BA_CLIENT["better-auth client<br/>/src/lib/better-auth.ts<br/>Base URL: /api/v1/auth"]
        AUTH_PROVIDER["AuthProvider<br/>/src/auth/context/better-auth/"]
        AUTH_GUARD["AuthGuard<br/>GuestGuard<br/>WorkspaceGuard<br/>RouteRoleGuard"]
    end

    subgraph API_AUTH["API ENDPOINTS"]
        SIGN_IN["POST /api/v1/auth/sign-in/email-password"]
        SIGN_UP["POST /api/v1/auth/sign-up/email-password"]
        FORGOT["POST /api/v1/auth/forget-password"]
        RESET["POST /api/v1/auth/reset-password"]
        CHANGE["POST /api/v1/auth/change-password"]
        SESSION["GET /api/v1/auth/get-session"]
        ADMIN_API["POST /api/v1/auth/admin/*"]
        ORG_API["POST /api/v1/auth/organization/*"]
    end

    subgraph BE_AUTH["BACKEND - better-auth Engine"]
        BA_HANDLER["better-auth handler<br/>/src/services/better-auth/"]
        SESSION_MW["requireAuth Middleware<br/>Session verification"]
        PERM_MW["requirePermission Middleware<br/>RBAC check"]
        APIKEY_MW["requireWorkspaceApiKey Middleware<br/>x-api-key verification"]
    end

    BA_CLIENT -->|"HTTP Request"| API_AUTH
    AUTH_PROVIDER --> BA_CLIENT
    AUTH_GUARD --> AUTH_PROVIDER

    API_AUTH --> BA_HANDLER
    BA_HANDLER -->|"Set Session Cookie"| BA_CLIENT

    SESSION_MW -->|"Verify Session"| BA_HANDLER
    PERM_MW -->|"Check Role + Permission"| BA_HANDLER
    APIKEY_MW -->|"Verify API Key"| BA_HANDLER

    style FE_AUTH fill:#E3F2FD,stroke:#1976D2
    style API_AUTH fill:#FFF8E1,stroke:#F9A825
    style BE_AUTH fill:#FCE4EC,stroke:#C2185B
```

---

## 2.5 File Upload Integration Flow

```mermaid
flowchart TD
    FE_UPLOAD["Frontend<br/>File Upload Component<br/>(multipart/form-data)"] --> ROUTE_CHECK{Upload Type?}

    ROUTE_CHECK -->|"Chat Media"| CHAT_API["POST /api/v1/u/conversation-messages/upload-media<br/>body: {file, mediaType, conversationId}"]
    ROUTE_CHECK -->|"Ticket Media"| TICKET_API["POST /api/v1/u/tickets/upload-media<br/>body: {file, ticketId?}"]
    ROUTE_CHECK -->|"Template Media"| TEMPL_API["POST /api/v1/u/templates/upload-media<br/>body: {file, mediaType, channelId}<br/>(Meta Resumable API)"]
    ROUTE_CHECK -->|"Channel Icon"| ICON_API["POST /api/v1/u/channels/:id/upload-icon<br/>body: {file}"]
    ROUTE_CHECK -->|"Profile Photo"| PROF_API["PUT /api/v1/u/user/update-user<br/>body: {photo}"]

    CHAT_API --> FILE_SERVICE["File Storage Service"]
    TICKET_API --> FILE_SERVICE
    TEMPL_API --> META_API["Meta Graph API<br/>Resumable Upload"]
    ICON_API --> FILE_SERVICE
    PROF_API --> FILE_SERVICE

    FILE_SERVICE --> STORAGE_CHECK{Storage Type?}
    STORAGE_CHECK -->|"LOCAL"| LOCAL["Local Filesystem<br/>/uploads/*"]
    STORAGE_CHECK -->|"S3"| S3["AWS S3"]
    STORAGE_CHECK -->|"GCS"| GCS["Google Cloud Storage"]
    STORAGE_CHECK -->|"AZURE"| AZURE["Azure Blob Storage"]

    META_API --> META_STORE["Meta Servers"]

    style FE_UPLOAD fill:#E3F2FD,stroke:#1976D2
    style STORAGE_CHECK fill:#FFF8E1,stroke:#F9A825
```

---

## 2.6 Middleware Stack (Request Lifecycle)

Diagram ini menunjukkan urutan middleware yang dilalui setiap request dari FE ke BE.

```mermaid
flowchart TD
    REQUEST["Incoming HTTP Request"] --> CORS["① CORS Middleware<br/>cors.config.ts<br/>Allowed origins validation"]
    CORS --> TIMING["② Timing Middleware<br/>Response time header"]
    TIMING --> REQ_ID["③ Request ID<br/>Unique request identifier"]
    REQ_ID --> LOGGER["④ Logger Middleware<br/>Request logging"]
    LOGGER --> BODY_LIMIT["⑤ Body Limit Middleware<br/>5MB default<br/>100MB WhatsApp uploads"]
    BODY_LIMIT --> TIMEOUT["⑥ Timeout Middleware<br/>5min default<br/>15min uploads"]
    TIMEOUT --> ROUTE_MATCH{Route Match?}

    ROUTE_MATCH -->|"/api/v1/auth/*"| AUTH_ROUTE["better-auth handler<br/>(self-handled)"]
    ROUTE_MATCH -->|"/api/webhook/*"| WEBHOOK_ROUTE["Webhook Routes<br/>(WhatsApp CORS only)"]
    ROUTE_MATCH -->|"/api/v1/u/*"| PROTECTED["Protected Route Chain"]
    ROUTE_MATCH -->|"/uploads/*"| UPLOAD_ROUTE["File Storage Route<br/>(+ upload timeout)"]
    ROUTE_MATCH -->|"/api/v1/swagger"| SWAGGER["Swagger UI"]

    PROTECTED --> AUTH_MW["⑦ requireAuth<br/>Session verification"]
    AUTH_MW --> PERM_MW["⑧ requirePermission<br/>RBAC: resource:action"]
    PERM_MW --> HANDLER["Route Handler<br/>→ Service → Repository → DB"]

    AUTH_ROUTE --> HANDLER2["better-auth internal handler"]
    WEBHOOK_ROUTE --> HANDLER3["Webhook processor"]

    style REQUEST fill:#C8E6C9,stroke:#4CAF50
    style HANDLER fill:#BBDEFB,stroke:#2196F3
    style HANDLER2 fill:#BBDEFB,stroke:#2196F3
    style HANDLER3 fill:#BBDEFB,stroke:#2196F3
```
