# Marketing Facebook Service

> Facebook Messenger Marketing Service with Automation Chatbot, AI-Powered Chatbot, and Customer Management

[![.NET Version](https://img.shields.io/badge/.NET-8.0-512BD4)](https://dotnet.microsoft.com/)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

## Features

### 1. 🤖 CHATBOT Automation Messenger

Rules-based chatbot with predefined conversation flows:
- Visual flow builder with nodes (Message, Question, Condition, Action)
- Keyword triggers and postback handlers
- Quick replies and button templates
- Multi-language support
- A/B testing for flows

### 2. 🧠 CHATBOT AI Messenger

Intelligent chatbot powered by OpenAI/Azure OpenAI:
- Natural language understanding and generation
- Context-aware conversations
- Customizable system prompts
- Multi-turn dialogue support
- Fallback to automation rules
- Cost tracking and optimization

### 3. 👥 Customer Management

Comprehensive customer data management:
- Customer profiles with Facebook user info
- Conversation history tracking
- Custom fields and tags
- Segmentation by behavior
- Export customer data
- GDPR compliance

## Quick Start

### Prerequisites

- .NET 8.0 SDK
- PostgreSQL 15+ (or Neon serverless)
- Redis 7+
- RabbitMQ 3.12+
- Docker & Docker Compose (for local development)
- **Facebook Page** and **Facebook App** with Messenger Platform
- **OpenAI API Key** or **Azure OpenAI** (for AI Chatbot)

### Configuration

```bash
# Copy environment template
cp .env.example .env

# Update configuration
# - DATABASE_URL (PostgreSQL connection string)
# - REDIS_URL
# - RABBITMQ_URL
# - FACEBOOK_VERIFY_TOKEN (webhook verification)
# - FACEBOOK_PAGE_ACCESS_TOKEN (send messages)
# - OPENAI_API_KEY (AI chatbot)
```

### Local Development

```bash
# Restore dependencies
dotnet restore

# Apply migrations
dotnet ef database update --project src/MktFacebookService.Infrastructure

# Run service
dotnet run --project src/MktFacebookService.API

# Service available at http://localhost:5000
# Swagger UI: http://localhost:5000/swagger
```

### Docker Deployment

```bash
# Build and run with Docker Compose
cd deployments/local
docker-compose up -d mkt-facebook-service-net

# View logs
docker-compose logs -f mkt-facebook-service-net

# Access via Traefik
# http://localhost/api/v1/mkt-facebook
```

## Architecture

```mermaid
graph TD
    subgraph "External"
        FB[Facebook Messenger Platform]
        OAI[OpenAI / Azure OpenAI]
        User[End User on Messenger]
    end
    
    subgraph "mkt-facebook-service-net"
        WH[Webhooks Controller]
        API[REST API Controllers]
        APP[Application Layer CQRS]
        DOM[Domain Layer]
        INFRA[Infrastructure Layer]
    end
    
    subgraph "Data Stores"
        PG[(PostgreSQL)]
        RD[(Redis Cache)]
        RMQ[RabbitMQ]
    end
    
    User -->|Send Message| FB
    FB -->|Webhook Event| WH
    WH -->|Process Message Command| APP
    API -->|Commands/Queries| APP
    APP -->|Business Logic| DOM
    APP -->|Persistence| INFRA
    INFRA -->|EF Core| PG
    INFRA -->|Caching| RD
    INFRA -->|Events| RMQ
    APP -->|Send Message| INFRA
    INFRA -->|API Call| FB
    APP -->|AI Completion| INFRA
    INFRA -->|API Call| OAI
    
    style User fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:2px
    style FB fill:#7F8C8D,color:#ECF0F1,stroke:#5D6D7E,stroke-width:2px
    style OAI fill:#7F8C8D,color:#ECF0F1,stroke:#5D6D7E,stroke-width:2px
    style WH fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:3px
    style API fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:3px
    style APP fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
    style DOM fill:#E67E22,color:#ECF0F1,stroke:#D35400,stroke-width:2px
    style INFRA fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
    style PG fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
    style RD fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
    style RMQ fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
```

### Technology Stack

| Layer | Technology |
|-------|------------|
| **Backend** | .NET 8, ASP.NET Core 8 |
| **Architecture** | Clean Architecture, DDD, CQRS |
| **Database** | PostgreSQL 15+, EF Core 8 |
| **Cache** | Redis, StackExchange.Redis |
| **Messaging** | RabbitMQ, MassTransit |
| **HTTP Client** | HttpClient Factory, Polly |
| **AI** | OpenAI SDK, Azure.AI.OpenAI |
| **API Gateway** | Traefik |
| **Documentation** | Swagger/OpenAPI 3.0 |

## API Endpoints

### Public API

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/v1/webhooks/facebook` | GET | Facebook webhook verification |
| `/api/v1/webhooks/facebook` | POST | Receive Facebook Messenger events |
| `/api/v1/conversations` | GET | List conversations |
| `/api/v1/conversations/{id}` | GET | Get conversation by ID |
| `/api/v1/conversations/{id}/messages` | POST | Send message |
| `/api/v1/customers` | GET | List customers |
| `/api/v1/customers/{id}` | GET | Customer details |
| `/api/v1/customers/{id}` | PUT | Update customer info |

### Admin API

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/v1/chatbots/flows` | GET | List automation flows |
| `/api/v1/chatbots/flows` | POST | Create chatbot flow |
| `/api/v1/chatbots/flows/{id}` | PUT | Update flow |
| `/api/v1/chatbots/flows/{id}` | DELETE | Delete flow |
| `/api/v1/chatbots/ai-config` | GET | Get AI chatbot config |
| `/api/v1/chatbots/ai-config` | PUT | Update AI config |

### Health & Monitoring

| Endpoint | Description |
|----------|-------------|
| `/health` | Health check endpoint |
| `/swagger` | Swagger UI documentation |

## Documentation

- [Architecture Documentation](./ARCHITECTURE.md) - System design and domain model
- [API Documentation](./API.md) - Complete API reference with examples
- [Facebook Messenger Setup](./FACEBOOK_SETUP.md) - Facebook App setup guide
- [AI Chatbot Configuration](./AI_CHATBOT.md) - AI integration guide

## Project Structure

```
mkt-facebook-service-net/
├── src/
│   ├── MktFacebookService.API/           # API Layer
│   │   ├── Controllers/                  # REST Controllers
│   │   ├── Application/                  # CQRS Commands/Queries
│   │   └── Program.cs                    # Entry point
│   ├── MktFacebookService.Domain/        # Domain Layer
│   │   ├── AggregatesModel/              # Aggregates, Entities
│   │   │   ├── ConversationAggregate/
│   │   │   ├── CustomerAggregate/
│   │   │   └── ChatbotAggregate/
│   │   └── SeedWork/                     # Base classes
│   └── MktFacebookService.Infrastructure/ # Infrastructure Layer
│       ├── Data/                         # EF Core DbContext
│       ├── Repositories/                 # Repository implementations
│       └── ExternalServices/             # Facebook, OpenAI clients
├── tests/
│   ├── MktFacebookService.UnitTests/
│   └── MktFacebookService.FunctionalTests/
├── docs/                                 # Documentation
├── Dockerfile
└── MktFacebookService.slnx
```

## Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `DATABASE_URL` | PostgreSQL connection string | - |
| `REDIS_URL` | Redis connection string | `localhost:6379` |
| `RABBITMQ_URL` | RabbitMQ connection string | `localhost:5672` |
| `FACEBOOK_VERIFY_TOKEN` | Webhook verification token | - |
| `FACEBOOK_PAGE_ACCESS_TOKEN` | Page access token for sending messages | - |
| `FACEBOOK_API_VERSION` | Facebook API version | `v21.0` |
| `OPENAI_API_KEY` | OpenAI API key | - |
| `OPENAI_MODEL` | OpenAI model name | `gpt-4-turbo` |
| `AZURE_OPENAI_ENDPOINT` | Azure OpenAI endpoint (optional) | - |
| `ASPNETCORE_ENVIRONMENT` | Environment (Development/Production) | `Development` |

## Development Workflow

### Phase 1: Domain Layer
1. Create Aggregates (Conversation, Customer, ChatbotFlow, AIChatbotConfig)
2. Define Entities and Value Objects
3. Implement business rules in domain methods
4. Raise Domain Events

### Phase 2: Infrastructure Layer
1. Setup EF Core DbContext and entity configurations
2. Create repositories implementing domain interfaces
3. Implement FacebookMessengerClient
4. Implement OpenAIClient with Polly resilience
5. Apply database migrations

### Phase 3: Application Layer (CQRS)
1. Create Commands (ProcessIncomingMessage, SendMessage, CreateChatbotFlow)
2. Create Queries (GetConversations, GetCustomers)
3. Implement MediatR Handlers
4. Add FluentValidation validators
5. Setup Pipeline Behaviors

### Phase 4: API Layer
1. Implement WebhooksController for Facebook events
2. Create REST API Controllers
3. Add Swagger annotations
4. Configure authentication & authorization
5. Setup health checks

## Testing

```bash
# Run all tests
dotnet test

# Run unit tests only
dotnet test tests/MktFacebookService.UnitTests/

# Run with coverage
dotnet test /p:CollectCoverage=true /p:CoverageReportsFormat=opencover
```

## Contributing

Please follow the [GoodGo Project Rules](../../.agent/skills/project-rules/SKILL.md) and [.NET Microservice Workflow](../../.agent/skills/dotnet-microservice-workflow/SKILL.md).

## License

MIT License

## Resources

### Facebook Messenger Platform
- [Messenger Platform Overview](https://developers.facebook.com/docs/messenger-platform/)
- [Webhook Reference](https://developers.facebook.com/docs/messenger-platform/webhooks)
- [Send API Reference](https://developers.facebook.com/docs/messenger-platform/send-messages)

### OpenAI
- [OpenAI API Documentation](https://platform.openai.com/docs/introduction)
- [Chat Completions Guide](https://platform.openai.com/docs/guides/chat-completions)

### Internal Skills
- [API Design Skill](../../.agent/skills/api-design/SKILL.md)
- [CQRS MediatR Skill](../../.agent/skills/cqrs-mediatr/SKILL.md)
- [Domain-Driven Design Skill](../../.agent/skills/domain-driven-design/SKILL.md)
