# MKT X/Twitter Service

> **EN**: [English Documentation](docs/en/README.md)  
> **VI**: [Tài liệu Tiếng Việt](docs/vi/README.md)

Comprehensive marketing automation and customer engagement service for X/Twitter.

[![.NET](https://img.shields.io/badge/.NET-8.0-512BD4)](https://dotnet.microsoft.com/)
[![PostgreSQL](https://img.shields.io/badge/PostgreSQL-15+-336791)](https://www.postgresql.org/)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

---

## Overview

The Twitter Marketing Service provides three core capabilities for social media marketing through X/Twitter:

- **CHATBOT Automation** - Template-based messaging with workflows and scheduling
- **CHATBOT AI** - AI-powered conversations using OpenAI integration
- **Customer Management** - Contact database, segmentation, and analytics

---

## Features

### 🤖 Automation Messenger

- ✅ Message template library
- ✅ Visual workflow designer
- ✅ Event-triggered messaging
- ✅ Scheduled campaigns
- ✅ A/B testing
- ✅ Rate limiting compliance

### 🧠 AI Messenger

- ✅ Natural language understanding
- ✅ Context-aware conversations
- ✅ Intent detection
- ✅ Integration with merchant data
- ✅ Auto escalation to human
- ✅ Sentiment analysis

### 👥 Customer Management

- ✅ Contact profile management
- ✅ Conversation history
- ✅ Customer segmentation
- ✅ Tag management
- ✅ Custom attributes
- ✅ Engagement analytics

---

## Prerequisites

| Requirement | Version | Notes |
|-------------|---------|-------|
| **.NET SDK** | 8.0+ | [Download](https://dotnet.microsoft.com/download) |
| **PostgreSQL** | 15+ | For data storage |
| **Redis** | 7+ | For caching |
| **RabbitMQ** | 3.12+ | For message bus |
| **Twitter Developer Account** | - | Required for API |
| **OpenAI API Key** | - | Optional for AI |

---

## Quick Start

### 1. Clone Repository

```bash
cd services/mkt-x-service-net
```

### 2. Configure Environment

Create `appsettings.Development.json`:

```json
{
  "ConnectionStrings": {
    "DefaultConnection": "Host=localhost;Database=mkt_x_service;Username=postgres;Password=postgres"
  },
  "Twitter": {
    "ApiKey": "your_twitter_api_key",
    "ApiKeySecret": "your_twitter_api_secret",
    "BearerToken": "your_bearer_token",
    "WebhookUrl": "https://your-domain.com/api/v1/mkt-x/webhooks/twitter"
  },
  "OpenAI": {
    "ApiKey": "your_openai_api_key",
    "Model": "gpt-4"
  },
  "RabbitMQ": {
    "Host": "localhost",
    "Username": "guest",
    "Password": "guest"
  },
  "Redis": {
    "ConnectionString": "localhost:6379"
  }
}
```

### 3. Run Migrations

```bash
dotnet ef database update --project src/MktXService.Infrastructure
```

### 4. Run Service

```bash
dotnet run --project src/MktXService.API
```

**Access Points**:
- API: http://localhost:5000
- Swagger: http://localhost:5000/swagger

---

## Documentation

> **EN**: [English Documentation](docs/en/README.md)  
> **VI**: [Tài liệu Tiếng Việt](docs/vi/README.md)

### English Documentation

- **[Architecture](docs/en/ARCHITECTURE.md)** - System architecture and domain model
- **[API Reference](docs/en/API.md)** - Complete API documentation with examples
- **[Twitter Setup Guide](docs/en/TWITTER_SETUP.md)** - Step-by-step Twitter API setup

### Vietnamese Documentation

- **[Kiến Trúc](docs/vi/ARCHITECTURE.md)** - Kiến trúc hệ thống và mô hình domain
- **[Tài Liệu API](docs/vi/API.md)** - Tài liệu API đầy đủ với ví dụ
- **[Hướng Dẫn Thiết Lập Twitter](docs/vi/TWITTER_SETUP.md)** - Hướng dẫn thiết lập Twitter API từng bước

---

## API Endpoints

### Core Endpoints

```
# Account Management
POST   /api/v1/mkt-x/accounts              # Connect Twitter account
GET    /api/v1/mkt-x/accounts              # List accounts
DELETE /api/v1/mkt-x/accounts/{id}         # Disconnect

# Contact Management
GET    /api/v1/mkt-x/contacts              # List contacts
POST   /api/v1/mkt-x/contacts/{id}/tags    # Add tags
PUT    /api/v1/mkt-x/contacts/{id}/attributes # Update attributes

# Conversations
GET    /api/v1/mkt-x/conversations         # List conversations
POST   /api/v1/mkt-x/conversations/{id}/messages # Send message

# Campaigns
POST   /api/v1/mkt-x/campaigns             # Create campaign
POST   /api/v1/mkt-x/campaigns/{id}/start  # Start campaign
GET    /api/v1/mkt-x/campaigns/{id}/metrics # View metrics

# Automation
POST   /api/v1/mkt-x/automation/flows      # Create workflow
POST   /api/v1/mkt-x/automation/flows/{id}/activate # Activate

# AI Chatbot
POST   /api/v1/mkt-x/ai/conversations/{id}/message # AI chat
GET    /api/v1/mkt-x/analytics/overview    # Dashboard analytics
```

**Full API documentation**: See [API.md](docs/API.md)

---

## Project Structure

```
mkt-x-service-net/
├── src/
│   ├── MktXService.API/              # Controllers, Swagger
│   │   ├── Controllers/              # API Controllers
│   │   └── Application/              # Commands, Queries, DTOs
│   ├── MktXService.Domain/           # Domain model
│   │   ├── AggregatesModel/          # Aggregates
│   │   ├── Events/                   # Domain events
│   │   └── SeedWork/                 # Base classes
│   └── MktXService.Infrastructure/   # EF Core, Repositories
│       ├── Data/                     # DbContext
│       ├── Repositories/             # Data access
│       ├── Services/                 # External clients
│       └── BackgroundJobs/           # Background workers
├── tests/
│   ├── MktXService.UnitTests/
│   └── MktXService.IntegrationTests/
├── docs/                             # Documentation
├── Dockerfile
└── docker-compose.yml
```

---

## Development

### Build

```bash
dotnet build
```

### Run Tests

```bash
dotnet test
```

### Create Migration

```bash
dotnet ef migrations add MigrationName --project src/MktXService.Infrastructure
```

### Docker Deployment

```bash
# Build
docker-compose -f deployments/local/docker-compose.yml build mkt-x-service-net

# Run
docker-compose -f deployments/local/docker-compose.yml up -d mkt-x-service-net

# Logs
docker-compose -f deployments/local/docker-compose.yml logs -f mkt-x-service-net
```

---

## Architecture

### Clean Architecture Layers

```
┌─────────────────────────────────────┐
│         API Layer (Controllers)      │
├─────────────────────────────────────┤
│  Application Layer (CQRS + MediatR) │
├─────────────────────────────────────┤
│      Domain Layer (Aggregates)       │
├─────────────────────────────────────┤
│  Infrastructure (EF Core, Twitter)   │
└─────────────────────────────────────┘
```

### Key Patterns

- **CQRS** with MediatR for command/query separation
- **DDD** with 9 aggregate roots
- **Repository Pattern** for data access
- **Event-Driven** with RabbitMQ

**Details**: See [ARCHITECTURE.md](docs/en/ARCHITECTURE.md)

---

## Configuration

### Environment Variables

```bash
# Database
ConnectionStrings__DefaultConnection="Host=localhost;Database=mkt_x_service"

# Twitter API
Twitter__ApiKey="your_api_key"
Twitter__ApiKeySecret="your_api_secret"
Twitter__WebhookUrl="https://your-domain.com/api/v1/mkt-x/webhooks/twitter"

# OpenAI
OpenAI__ApiKey="sk-..."
OpenAI__Model="gpt-4"

# RabbitMQ
RabbitMQ__Host="localhost"

# Redis
Redis__ConnectionString="localhost:6379"
```

---

## Monitoring

### Health Check

```bash
curl http://localhost:5000/health
```

### Metrics

- **Prometheus**: `http://localhost:5000/metrics`
- **Grafana Dashboard**: Available in production

### Logging

Structured logging with Serilog, sent to Loki:

```json
{
  "timestamp": "2026-01-18T10:00:00Z",
  "level": "Information",
  "message": "Campaign started",
  "properties": {
    "campaignId": "...",
    "merchantId": "..."
  }
}
```

---

##Troubleshooting

### Common Issues

#### 1. Twitter API 401 Unauthorized

**Solution**:
- Verify API credentials in configuration
- Check OAuth token expiration
- Ensure app has Direct Messages permission

#### 2. Database Connection Error

**Solution**:
- Check PostgreSQL is running
- Verify connection string
- Ensure database exists: `createdb mkt_x_service`

#### 3. Webhook Events Not Received

**Solution**:
- Verify webhook is registered in Twitter
- Check HTTPS certificate is valid
- Ensure firewall allows inbound traffic
- Review webhook signature validation

**Details**: See [TWITTER_SETUP.md](docs/en/TWITTER_SETUP.md)

---

## Performance

### Targets

| Metric | Target |
|--------|--------|
| API Response (P95) | < 500ms |
| Message Processing | 100 msg/sec |
| Campaign Throughput | 10,000 contacts/min |
| Database Query (P95) | < 100ms |

### Caching

```
Contact Profiles: 1 hour TTL
Templates: 10 minutes TTL
Segments: 5 minutes TTL
```

---

## Security

- ✅ OAuth tokens encrypted at rest
- ✅ JWT authentication for API
- ✅ RBAC for merchant isolation
- ✅ Input validation with FluentValidation
- ✅ GDPR compliance (data retention, deletion)

---

## Contributing

See [GoodGo Contributing Guide](../../docs/CONTRIBUTING.md)

---

## Support

- **Documentation Issues**: Open issue on GitHub
- **API Support**: api-support@goodgo.com
- **Twitter Integration**: See [TWITTER_SETUP.md](docs/en/TWITTER_SETUP.md)

---

## License

MIT License - See LICENSE file for details

---

## Related Services

- [MKT Facebook Service](../mkt-facebook-service-net) - Facebook Messenger marketing
- [MKT Zalo Service](../mkt-zalo-service-net) - Zalo OA marketing
- [MKT WhatsApp Service](../mkt-whatsapp-service-net) - WhatsApp Business marketing

---

## Technology Stack

| Component | Technology | Version |
|-----------|-----------|---------|
| Runtime | .NET | 8.0+ |
| Framework | ASP.NET Core | 8.0+ |
| ORM | Entity Framework Core | 8.0+ |
| Database | PostgreSQL | 15+ |
| Cache | Redis | 7+ |
| Message Broker | RabbitMQ | 3.12+ |
| Mediator | MediatR | 12+ |
| API Gateway | Traefik | 2.10+ |
| Monitoring | Prometheus + Grafana | - |

---

##References

- [Twitter API v2 Documentation](https://developer.twitter.com/en/docs/twitter-api)
- [OpenAI API Documentation](https://platform.openai.com/docs)
- [Clean Architecture](https://docs.microsoft.com/en-us/dotnet/architecture/modern-web-apps-azure/common-web-application-architectures)
- [Domain-Driven Design](https://domainlanguage.com/ddd/)
