﻿# 📘 EIP Conversation Engine — Full Technical Documentation

---

# 🧭 1. System Overview

The **EIP Conversation Engine** is a **multi-channel, DB-driven workflow engine** that processes incoming messages, routes them dynamically, executes business logic, and sends responses across multiple communication channels.

---

# 🏗️ 2. High-Level Architecture

```plaintext
Client / Channel (WhatsApp / Slack / SMS / etc.)
            ↓
   EIPConversationBLL (Orchestrator)
            ↓
   EIPConversationEngine
            ↓
 ┌──────────────────────────────────────┐
 │ Phase 1 → Channel Normalization      │
 │ Phase 2 → Routing                   │
 │ Phase 3 → Flow Execution            │
 │ Phase 4 → Capability Execution      │
 │ Phase 5 → Action Execution          │
 │ Phase 6 → Response Generation       │
 └──────────────────────────────────────┘
            ↓
     Channel Handlers (Webhook Delivery)
            ↓
   External Systems (Slack / WhatsApp / etc.)
```

---

# 🔄 3. End-to-End Message Flow

## 📥 Message Receive Flow

```plaintext
External Channel → API → BLL → Engine
```

### Steps:

1. Incoming request hits API
2. `EIPConversationBLL.HandleIncomingConversationAsync`
3. Payload + Login validated
4. Forwarded to `EIPConversationEngine`

---

## 📤 Message Delivery Flow

```plaintext
Engine → ResponseEngine → ChannelHandler → Webhook/API → External Platform
```

---

# 🧠 4. Phase-wise Deep Analysis

---

# 🔹 PHASE 1 — CHANNEL NORMALIZATION

## 🎯 Purpose

Convert incoming payload into a **standard internal format**

## ⚙️ Responsibilities

* Normalize message structure
* Identify:

  * ChannelType
  * UserIdentifier
  * TenantId
  * Message

## ✅ Validations

* Payload must not be null
* LoginDTO must not be null
* TenantId fallback from payload → loginDTO
* UserId must be valid

## 🔁 Output

```plaintext
NormalizedContext
```

---

# 🔹 PHASE 2 — ROUTING ENGINE

## 🎯 Purpose

Decide **which flow to execute**

## ⚙️ Responsibilities

* Fetch routing rules from DB
* Match conditions
* Assign FlowCode

## ✅ Validations

* Tenant must exist
* ChannelType must be valid
* Routing rules must be available

## 🔁 Output

```plaintext
FlowCode (or DEFAULT_FLOW)
```

---

# 🔹 PHASE 3 — FLOW ENGINE

## 🎯 Purpose

Execute **conversation workflow**

## ⚙️ Responsibilities

* Fetch flow definition (JSON)
* Parse steps
* Execute step-by-step

## 🧩 Flow Structure

```json
{
  "StartStepCode": "START",
  "Steps": {
    "START": {
      "StepType": "MESSAGE",
      "NextStepCode": "STEP2"
    }
  }
}
```

## ✅ Validations

* Flow must exist
* StartStepCode required
* Steps must not be empty
* No duplicate StepCodes

## 🔁 Output

```plaintext
FlowResult:
- ResponseMessage
- NextStepCode
- CapabilityCode
- ActionCode
```

---

# 🔹 PHASE 4 — CAPABILITY ENGINE

## 🎯 Purpose

Execute **business logic layer**

## ⚙️ Responsibilities

* Run domain logic (e.g., validation, OTP, risk)
* Fetch capability config

## 🔗 Uses

* `EIPCapabilityDAL`
* `EIPCapabilityActionMapDAL`

## ✅ Validations

* CapabilityCode must exist
* Capability must be mapped

---

# 🔹 PHASE 5 — ACTION ENGINE

## 🎯 Purpose

Execute **system actions**

## ⚙️ Responsibilities

* Perform operations:

  * DB updates
  * External API calls
  * Workflow triggers

## 🔗 Uses

* `EIPActionRegistryDAL`

## ✅ Validations

* ActionCode must exist
* Action must be valid

---

# 🔹 PHASE 6 — RESPONSE ENGINE

## 🎯 Purpose

Send message to user via correct channel

## ⚙️ Responsibilities

* Build response payload
* Select correct channel handler
* Deliver message

---

# 📡 5. Channel Handling System

---

## 🧩 Design Pattern

```plaintext
IEIPChannelHandler
   ↓
Multiple Implementations
```

---

## 📦 Supported Channels

| Channel  | Type       | Description     |
| -------- | ---------- | --------------- |
| POSTMAN  | Simulation | Debug/testing   |
| SLACK    | Webhook    | Slack messages  |
| SMS      | Provider   | Text messages   |
| TEAMS    | Webhook    | Microsoft Teams |
| TELEGRAM | Bot API    | Telegram bot    |
| WHATSAPP | API        | Meta/Celitix    |

---

## 🔁 Channel Selection Logic

```csharp
handler.CanHandle(channel)
```

---

# 📬 6. Webhook Delivery Flow

---

## Example: Slack

```plaintext
ResponseEngine
   ↓
SlackChannelHandler
   ↓
HTTP POST → Slack Webhook URL
```

### Payload:

```json
{
  "channel": "#general",
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "Message"
      }
    }
  ]
}
```

---

## Example: WhatsApp

### Flow:

```plaintext
ResponseEngine
   ↓
WhatsAppChannelHandler
   ↓
Provider Selection:
   → Celitix API
   → Meta API
```

### Features:

* Retry using Polly
* Supports:

  * Text
  * Media
  * Buttons
* CorrelationId tracking

---

# 🔐 7. Supporting Services

---

## 🔹 OTP Service

### Responsibilities:

* Generate OTP
* Verify OTP

### Current Behavior:

* Random 6-digit OTP
* Logging only (no persistence yet)

---

## 🔹 Risk Assessment

### Responsibilities:

* Evaluate risk level
* Decide OTP requirement

### Example:

```plaintext
PAYMENT → HIGH RISK → OTP REQUIRED
```

---

# 🗄️ 8. Data Layer Responsibilities

---

## 🔹 Flow DAL

* Fetch JSON flow definition
* Deserialize safely

## 🔹 Routing DAL

* Fetch routing rules
* Validate tenant

## 🔹 Capability DAL

* Fetch business logic config

## 🔹 Action DAL

* Fetch action definitions

---

# 🔄 9. Complete Execution Flow

```plaintext
1. Message Received
2. Normalize Payload
3. Resolve Routing
4. Load Flow
5. Execute Step
6. Execute Capability
7. Execute Action
8. Generate Response
9. Send via Channel Handler
```

---

# ⚠️ 10. Validations Summary

| Phase   | Validation            |
| ------- | --------------------- |
| Phase 1 | Payload, LoginDTO     |
| Phase 2 | Tenant, Channel       |
| Phase 3 | Flow existence, Steps |
| Phase 4 | CapabilityCode        |
| Phase 5 | ActionCode            |
| Phase 6 | Channel availability  |

---

# 🚀 11. Key Strengths

* ✅ Fully DB-driven workflows
* ✅ Multi-channel support
* ✅ Scalable architecture
* ✅ Retry mechanisms (WhatsApp)
* ✅ Multi-tenant support
* ✅ Flow versioning

---

# ⚠️ 12. Improvement Areas

* Add caching (Flows, Routing)
* Store OTP in DB
* Add audit logging
* Replace JSON string returns with DTO
* Add monitoring dashboard

---

# 🧠 13. Final Summary

This system acts as:

```plaintext
Workflow Engine + Chatbot Engine + Integration Layer
```

It enables:

* Dynamic conversation flows
* Multi-channel communication
* Business rule execution
* External system integration

---

# ✅ Conclusion

Your architecture is **enterprise-grade**, highly extensible, and production-ready with minor improvements.

---
