linkbay-orders 0.1.0
FastAPI package for e-commerce order management with multi-tenant support
License: MIT
Requires Python: >=3.8

# LinkBay Orders v0.1.0

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

FastAPI package for e-commerce order management with multi-tenant support and Stripe payment integration.

## Features

- 🛒 **Order Management**: Complete CRUD operations for orders
- 💳 **Payment Integration**: Stripe webhook handling and payment processing
- 🏢 **Multi-tenant**: Integrates with `linkbay-multitenant` for tenant isolation
- 📦 **Order Fulfillment**: Tracking numbers and shipping status updates
- 🔄 **Status Workflow**: Validated order status transitions
- 💰 **Refund Processing**: Automated refund handling through Stripe
- 🎯 **Dynamic Models**: Bring your own SQLAlchemy models

## Prima di iniziare

Questa libreria è ideale per:
- Applicazioni e-commerce con gestione ordini
- Sistemi multi-tenant che necessitano di isolamento degli ordini
- Integrazione con pagamenti Stripe
- Applicazioni che richiedono flessibilità nei modelli di database

**NON È ADATTA** se:
- Necessiti di modelli rigidi e predefiniti
- Non usi SQLAlchemy o FastAPI
- Non hai bisogno di multi-tenancy

## Installazione

```bash
pip install linkbay-orders
```

Oppure l'ultima versione dal repository:

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

## Quick Start (3 passi)

### 1. Definisci i tuoi Models

La libreria è **super dinamica** - definisci i tuoi modelli nella tua app:

```python
from sqlalchemy import Column, Integer, String, Numeric, DateTime, ForeignKey, Text
from sqlalchemy.orm import relationship
from datetime import datetime
from your_app.database import Base

class Order(Base):
    __tablename__ = "orders"
    
    id = Column(Integer, primary_key=True, index=True)
    tenant_id = Column(Integer, nullable=False, index=True)
    order_number = Column(String(50), unique=True, nullable=False)
    customer_id = Column(Integer, nullable=True)
    
    status = Column(String(50), nullable=False, default="pending")
    payment_status = Column(String(50), nullable=False, default="pending")
    fulfillment_status = Column(String(50), nullable=True)
    
    subtotal = Column(Numeric(10, 2), nullable=False, default=0)
    discount = Column(Numeric(10, 2), nullable=False, default=0)
    shipping = Column(Numeric(10, 2), nullable=False, default=0)
    tax = Column(Numeric(10, 2), nullable=False, default=0)
    total = Column(Numeric(10, 2), nullable=False, default=0)
    
    notes = Column(Text, nullable=True)
    tracking_number = Column(String(100), nullable=True)
    
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    items = relationship("OrderItem", back_populates="order", cascade="all, delete-orphan")
    status_history = relationship("OrderStatusHistory", back_populates="order")

# Definisci anche OrderItem e OrderStatusHistory (vedi models_example.py)
```

### 2. Configura il Service e i Router

```python
from linkbay_orders import OrderService, create_order_router, create_stripe_webhook_router
from your_app.models import Order, OrderItem, OrderStatusHistory
from your_app.database import get_db
from your_app.auth import get_tenant_id

# Inizializza OrderService con i tuoi modelli
order_service = OrderService(
    order_model=Order,
    order_item_model=OrderItem,
    order_status_history_model=OrderStatusHistory,
    stripe_api_key="sk_test_your_stripe_key"
)

# Crea i router FastAPI
from fastapi import FastAPI

app = FastAPI()

order_router = create_order_router(
    get_db=get_db,
    get_tenant_id=get_tenant_id,
    order_service=order_service,
    prefix="/api/orders"
)

webhook_router = create_stripe_webhook_router(
    get_db=get_db,
    order_service=order_service,
    webhook_secret="whsec_your_webhook_secret",
    prefix="/api/webhooks"
)

app.include_router(order_router)
app.include_router(webhook_router)
```

### 3. Usa le API

```python
from linkbay_orders import OrderCreate, OrderItemCreate
from decimal import Decimal

# Crea ordine
order_data = OrderCreate(
    customer_id=123,
    items=[
        OrderItemCreate(
            product_id=1,
            name="Product A",
            sku="SKU-001",
            quantity=2,
            price=Decimal("29.99"),
            discount=Decimal("5.00")
        )
    ],
    discount=Decimal("10.00"),
    shipping=Decimal("5.00"),
    tax=Decimal("8.50")
)

# POST /api/orders
# GET /api/orders
# GET /api/orders/{id}
# PATCH /api/orders/{id}
# POST /api/orders/{id}/cancel
# POST /api/orders/{id}/refund
```

## API Endpoints

### Order Management
- `POST /orders` - Crea nuovo ordine
- `GET /orders` - Lista ordini (con paginazione e filtri)
- `GET /orders/{id}` - Ottieni ordine per ID
- `GET /orders/number/{order_number}` - Ottieni ordine per numero
- `PATCH /orders/{id}` - Aggiorna ordine
- `POST /orders/{id}/cancel` - Cancella ordine
- `POST /orders/{id}/status` - Aggiorna stato ordine
- `POST /orders/{id}/fulfill` - Segna come evaso
- `POST /orders/{id}/refund` - Processa rimborso

### Webhooks
- `POST /webhooks/stripe` - Webhook pagamenti Stripe

## Workflow Stati Ordine

```
pending → confirmed → processing → shipped → delivered
    ↓         ↓            ↓
cancelled  cancelled  cancelled
```

Stati validi:
- `pending`: In attesa di conferma
- `confirmed`: Confermato
- `processing`: In elaborazione
- `shipped`: Spedito
- `delivered`: Consegnato
- `cancelled`: Cancellato

## Integrazione Stripe

### Crea Payment Intent

```python
from linkbay_orders import create_stripe_payment_intent

payment_intent = create_stripe_payment_intent(
    amount=99.99,
    currency="usd",
    order_id=order.id,
    tenant_id=tenant_id,
    customer_email="customer@example.com"
)

# Invia payment_intent.client_secret al frontend
```

### Eventi Webhook

Il webhook handler processa automaticamente:
- `payment_intent.succeeded` - Aggiorna stato pagamento a "paid"
- `payment_intent.payment_failed` - Aggiorna stato pagamento a "failed"

**Importante**: Includi `order_id` e `tenant_id` nei metadata del PaymentIntent!

## Caratteristiche Principali

- ✅ **Dynamic Models**: Nessun vincolo sui modelli - usa i tuoi
- ✅ **Multi-tenant**: Isolamento completo per tenant
- ✅ **Stripe Integration**: Webhooks e payment processing
- ✅ **Status Workflow**: Transizioni validate
- ✅ **Order Fulfillment**: Tracking e stato spedizioni
- ✅ **Refund Processing**: Rimborsi automatici
- ✅ **Filtering & Pagination**: Lista ordini con filtri avanzati
- ✅ **Status History**: Tracciamento completo modifiche stato

## 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 🧡