linkbay-marketing 0.1.0
Marketing automation for LinkBay CMS - email campaigns, abandoned cart recovery, customer segmentation, coupons and AI-powered A/B testing
License: MIT
Requires Python: >=3.8
Keywords: linkbay, marketing, email-campaigns, automation, fastapi, a-b-testing

# LinkBay Marketing v0.1.0

[![License](https://img.shields.io/badge/license-MIT-blue)]() [![Python](https://img.shields.io/badge/python-3.8+-blue)]() [![FastAPI](https://img.shields.io/badge/FastAPI-0.110+-green)]()

Marketing automation per l'ecosistema LinkBay CMS. Gestione campagne email, recupero carrelli abbandonati, segmentazione clienti, coupon e A/B testing con AI.

## 🚀 Caratteristiche

- **📧 Email Campaigns**: Creazione, scheduling e invio bulk con tracking (opens, clicks, unsubscribes)
- **🛒 Abandoned Cart Recovery**: Recupero automatico carrelli abbandonati con email e coupon
- **👥 Customer Segmentation**: Segmentazione dinamica (high_value, at_risk, new customers)
- **🎟️ Coupons & Discounts**: Gestione codici sconto (fissi, percentuali, spedizione gratuita)
- **🧪 A/B Testing**: Test automatici con predizione AI del vincitore

## Prima di iniziare

LinkBay Marketing è una libreria **leggera e riusabile** progettata per:

✅ **Perfetta se hai bisogno di:**
- Automazione marketing per e-commerce
- Sistema multi-tenant
- Flessibilità totale su database e infrastruttura
- Integrazione con altri pacchetti LinkBay
- Background jobs per invio bulk
- A/B testing con AI

❌ **Non adatta se:**
- Cerchi una soluzione all-in-one con database incluso
- Non vuoi implementare repository personalizzati
- Hai bisogno di un sistema non asincrono

## 📦 Installazione

```bash
pip install linkbay-marketing
```

Oppure l'ultima versione dal repository:

```bash
pip install git+https://github.com/AlessioQuagliara/LinkBay-Marketing
```

## 🏗️ Architettura

LinkBay Marketing usa il pattern **Protocol** per dependency injection. NON include database o modelli ORM.

### Principi chiave:
- ✅ Nessun database integrato
- ✅ Protocol-based dependency injection
- ✅ Completamente asincrono
- ✅ Facilmente estendibile
- ✅ Multi-tenant ready

## 🎯 Quick Start

### 1. Implementa i Repository

```python
from linkbay_marketing.services.campaigns import CampaignRepository
from typing import Dict, Any, Optional, List

class MyCampaignRepository:
    """Implementa con il tuo database (SQLAlchemy, MongoDB, etc.)"""
    
    async def create(self, tenant_id: str, data: Dict[str, Any]) -> Dict[str, Any]:
        campaign = await db.campaigns.insert_one(data)
        return {**data, "id": str(campaign.inserted_id)}
    
    async def get(self, tenant_id: str, campaign_id: str) -> Optional[Dict[str, Any]]:
        return await db.campaigns.find_one({"id": campaign_id, "tenant_id": tenant_id})
    
    async def update(self, tenant_id: str, campaign_id: str, data: Dict[str, Any]) -> Dict[str, Any]:
        await db.campaigns.update_one(
            {"id": campaign_id, "tenant_id": tenant_id},
            {"$set": data}
        )
        return await self.get(tenant_id, campaign_id)
    
    async def list(self, tenant_id: str, skip: int = 0, limit: int = 100) -> List[Dict[str, Any]]:
        cursor = db.campaigns.find({"tenant_id": tenant_id}).skip(skip).limit(limit)
        return await cursor.to_list(length=limit)
```

### 2. Configura FastAPI

```python
from fastapi import FastAPI
from linkbay_marketing import marketing_router, CampaignService

app = FastAPI()

# Inizializza servizi
campaign_repo = MyCampaignRepository()
email_provider = MyEmailProvider()
campaign_service = CampaignService(campaign_repo, email_provider)

# Monta router
app.include_router(marketing_router)
```

### 3. Usa i Servizi

```python
from linkbay_marketing.schemas import CampaignCreate

# Crea campagna
campaign = await campaign_service.create_campaign(
    tenant_id="tenant_123",
    data=CampaignCreate(
        name="Black Friday 2024",
        segment_id="high_value",
        template_id="promo_template",
        subject="🔥 50% Off Everything!"
    )
)

# Programma invio
await campaign_service.schedule_campaign(
    tenant_id="tenant_123",
    campaign_id=campaign.id,
    scheduled_at=datetime(2024, 12, 1, 10, 0)
)

# Statistiche
stats = await campaign_service.get_stats("tenant_123", campaign.id)
print(f"Open rate: {stats.open_rate}%")
```

## 📚 Esempi Completi

### Customer Segmentation

```python
from linkbay_marketing.services import SegmentService
from linkbay_marketing.schemas import SegmentCreate, SegmentRule

# Segmento "high value"
segment = await segment_service.create_segment(
    tenant_id="tenant_123",
    data=SegmentCreate(
        name="High Value Customers",
        rules=[
            SegmentRule(field="clv", operator="gt", value=1000)
        ]
    )
)

# Usa preset predefiniti
rules = SegmentService.create_preset_rules("at_risk")
# Ritorna: [SegmentRule(field="last_purchase_days", operator="gt", value=90)]
```

### Coupons & Discounts

```python
from linkbay_marketing.services import CouponService
from linkbay_marketing.schemas import CouponCreate

# Crea coupon
coupon = await coupon_service.create_coupon(
    tenant_id="tenant_123",
    data=CouponCreate(
        code="BLACKFRIDAY2024",
        type="percentage",
        value=50.0,
        min_purchase=100.0,
        max_uses=1000,
        expires_at=datetime.utcnow() + timedelta(days=7)
    )
)

# Valida e riscatta
validation = await coupon_service.validate_coupon("tenant_123", "BLACKFRIDAY2024", 150.0)
if validation["valid"]:
    await coupon_service.redeem_coupon("tenant_123", "BLACKFRIDAY2024", 150.0)
```

### Abandoned Cart Recovery

```python
from linkbay_marketing.services import AbandonedCartService
from linkbay_marketing.schemas import AbandonedCartCreate, CartItem

# Traccia carrello
cart = await abandoned_cart_service.track_abandoned_cart(
    tenant_id="tenant_123",
    data=AbandonedCartCreate(
        session_id="session_xyz",
        customer_email="customer@example.com",
        cart_items=[
            CartItem(product_id="prod_1", name="T-Shirt", quantity=2, price=29.99)
        ]
    )
)

# Invia recovery email con sconto 10%
result = await abandoned_cart_service.send_recovery_email(
    tenant_id="tenant_123",
    cart_id=cart.id,
    discount_percentage=10.0
)
```

### A/B Testing con AI

```python
from linkbay_marketing.services import ABTestingService
from linkbay_marketing.schemas import ABTestCreate, ABTestVariant

# Crea test
test = await ab_testing_service.create_test(
    tenant_id="tenant_123",
    data=ABTestCreate(
        campaign_id="campaign_123",
        variants=[
            ABTestVariant(name="A", subject="Get 50% off today!"),
            ABTestVariant(name="B", subject="Limited time: Half price sale")
        ],
        sample_size=0.2,  # Test su 20%
        metric="open_rate"
)
)

# Registra risultati
await ab_testing_service.record_result("tenant_123", test.id, "A", 100, 0.25)
await ab_testing_service.record_result("tenant_123", test.id, "B", 100, 0.32)

# Predizione AI
result = await ab_testing_service.predict_winner_with_ai("tenant_123", test.id)
print(f"Vincitore: {result.winner}")
```

## ⚙️ Background Jobs (Celery)

```python
from linkbay_marketing.tasks import create_marketing_tasks, setup_beat_schedule

# Setup Celery
tasks = create_marketing_tasks(
    broker_url="redis://localhost:6379/0",
    backend_url="redis://localhost:6379/0"
)

# Configura job periodici
setup_beat_schedule(tasks.app, tenant_id="tenant_123")

# Avvia worker e beat
# celery -A your_module.tasks.app worker --loglevel=info
# celery -A your_module.tasks.app beat --loglevel=info
```

## 🔌 Protocol da Implementare

### Repositories
- `CampaignRepository` - CRUD campagne
- `SegmentRepository` - CRUD segmenti
- `CouponRepository` - CRUD coupon
- `AbandonedCartRepository` - CRUD carrelli abbandonati
- `ABTestRepository` - CRUD A/B test

### Providers
- `EmailProvider` - Invio email (SendGrid, Mailgun, etc.)
- `CustomerQuery` - Query clienti per segmentazione
- `AIPredictor` - Predizioni AI (LinkBay-AI)

Vedi [Documentazione Completa](docs/protocols.md) per dettagli.

## 📊 API Endpoints

Una volta montato il router, hai accesso a:

- `POST /marketing/campaigns` - Crea campagna
- `POST /marketing/campaigns/{id}/send` - Invia/programma
- `GET /marketing/campaigns/{id}/stats` - Statistiche
- `POST /marketing/segments` - Crea segmento
- `POST /marketing/coupons` - Crea coupon
- `POST /marketing/coupons/{code}/validate` - Valida coupon
- `POST /marketing/abandoned-carts/recover` - Recovery email
- `POST /marketing/ab-tests` - Crea A/B test
- `POST /marketing/ab-tests/{id}/predict-winner` - Predizione AI

Vedi [API Reference](docs/api.md) per lista completa.

## 🧩 Integrazione con LinkBay Ecosystem

```python
from linkbay_ai import AIService
from linkbay_customers import CustomerService

# Integra con altri pacchetti
ai_service = AIService()
customer_service = CustomerService()

# Usa per A/B testing
class LinkBayAIPredictor:
    async def predict_winner(self, variants, metric):
        return await ai_service.predict_ab_test_winner(variants, metric)

# Usa per segmentazione
class LinkBayCustomerQuery:
    async def count_by_rules(self, tenant_id, rules):
        return await customer_service.count_customers(tenant_id, rules)
```

## 🧪 Testing

```python
# Mock repository per test
class MockCampaignRepository:
    def __init__(self):
        self.campaigns = {}
    
    async def create(self, tenant_id: str, data: Dict[str, Any]):
        campaign_id = f"campaign_{len(self.campaigns)}"
        campaign = {**data, "id": campaign_id}
        self.campaigns[campaign_id] = campaign
        return campaign

# Test
campaign_service = CampaignService(
    repository=MockCampaignRepository(),
    email_provider=MockEmailProvider()
)

campaign = await campaign_service.create_campaign("test_tenant", data)
assert campaign.name == "Test Campaign"
```

## 📝 License

MIT

## 👥 Contributors

Alessio Quagliara - LinkBay CMS

## 🔗 Links

- [LinkBay Core](https://github.com/linkbay/linkbay-core)
- [LinkBay AI](https://github.com/linkbay/linkbay-ai)
- [LinkBay Customers](https://github.com/linkbay/linkbay-customers)

---

**LinkBay Marketing** - Marketing automation semplice e potente per e-commerce 🚀


## Testing



## Limitazioni note


## Roadmap consigliata


## Licenza

MIT. Puoi usarla e modificarla liberamente, assicurandoti di valutarne i rischi nel tuo contesto.

## Supporto

- Issues: https://github.com/AlessioQuagliara/----/issues
- Email: quagliara.alessio@gmail.com

Contribuisci, apri una issue o raccontaci come stai usando la libreria 🧡