portal-sdk 1.0.0
SDK Python unificado para integração com serviços QCOS/SoftQuantus Portal
Requires Python: >=3.9
Keywords: qcos, softquantus, portal, licensing, billing, admin, api, sdk

# QCOS SDK - Python

SDK Python unificado para integração com todos os serviços QCOS/SoftQuantus:
- Licensing (geração, validação, renovação de licenças)
- Admin (gestão de clientes, contratos, funcionários)
- Billing (subscriptions, API keys, usage tracking, tiers)
- Portal (acesso de clientes aos recursos)

## Instalação

```bash
pip install qcos-sdk
```

## Uso Rápido

### Licensing Service

```python
from qcos_sdk import LicensingClient

client = LicensingClient(
    host="licensing.softquantus.com:50051",
    api_key="SERVICE_API_KEY"
)

# Criar licença
license = await client.create_license(
    customer_id=123,
    products=[
        {
            "product_id": "qcos-core",
            "features": ["qmc", "cc", "ofdft"],
            "max_nodes": 100
        }
    ],
    valid_until="2025-12-31"
)

# Validar licença
result = await client.validate_license(license_key)
if result.valid:
    print(f"Licença válida até {result.expires_at}")
```

### Billing Service (Tiers & Subscriptions)

```python
from qcos_sdk import BillingClient

billing = BillingClient(
    base_url="https://api.softquantus.com",
    api_key="SERVICE_API_KEY"
)

# Criar subscription com tier
subscription = await billing.create_subscription(
    customer_id=123,
    plan="pro",  # free, pro, enterprise
    auto_renew=True
)

# Verificar tier atual do cliente
tier = await billing.get_customer_tier(customer_id=123)
print(f"Tier: {tier.name}, Limite de API calls: {tier.api_limit}")

# Registrar uso de API (para cobrança)
await billing.log_api_usage(
    customer_id=123,
    api_key="customer_api_key",
    usage_type="llm_tokens",
    quantity=1500,
    metadata={"model": "gpt-4", "tokens": 1500}
)

# Verificar se cliente excedeu limites
quota = await billing.check_quota(customer_id=123)
if quota.exceeded:
    raise Exception("Quota excedida, upgrade necessário")
```

### Admin Service

```python
from qcos_sdk import AdminClient

admin = AdminClient(
    base_url="https://api.softquantus.com",
    token="EMPLOYEE_JWT_TOKEN"
)

# Criar cliente
customer = await admin.customers.create(
    company_name="ACME Corp",
    email="contact@acme.com",
    tier="pro"
)

# Criar contrato
contract = await admin.contracts.create(
    customer_id=customer.id,
    plan="enterprise",
    start_date="2025-01-01",
    end_date="2025-12-31"
)

# Listar licenças
licenses = await admin.licenses.list(customer_id=customer.id)
```

### Portal Service (para clientes)

```python
from qcos_sdk import PortalClient

portal = PortalClient(
    base_url="https://api.softquantus.com",
    token="CUSTOMER_JWT_TOKEN"
)

# Cliente vê suas próprias informações
profile = await portal.get_profile()
print(f"Tier atual: {profile.tier}")

# Cliente vê suas licenças
licenses = await portal.get_licenses()

# Cliente solicita upgrade de tier
await portal.request_tier_upgrade(
    target_tier="enterprise",
    notes="Precisamos de mais recursos"
)
```

## Integração com Chat Service (Exemplo)

```python
# chat-backend/app/main.py
from qcos_sdk import BillingClient
from fastapi import FastAPI, Depends, HTTPException

billing = BillingClient(
    base_url="https://api.softquantus.com",
    api_key=os.getenv("QCOS_SERVICE_API_KEY")
)

@app.post("/chat/completion")
async def chat_completion(
    prompt: str,
    user_id: int,
    api_key: str
):
    # 1. Verificar tier do cliente
    tier = await billing.get_customer_tier_by_api_key(api_key)
    
    # 2. Verificar quota
    quota = await billing.check_quota(
        api_key=api_key,
        usage_type="llm_tokens"
    )
    
    if quota.exceeded:
        if tier.name == "free":
            raise HTTPException(429, "Limite gratuito excedido. Faça upgrade!")
        else:
            raise HTTPException(429, "Quota mensal excedida")
    
    # 3. Processar chat
    response = await openai.chat.completions.create(
        model=tier.allowed_models[0],  # free: gpt-3.5, pro: gpt-4
        messages=[{"role": "user", "content": prompt}]
    )
    
    # 4. Registrar uso para billing
    await billing.log_api_usage(
        api_key=api_key,
        usage_type="llm_tokens",
        quantity=response.usage.total_tokens,
        metadata={
            "model": response.model,
            "prompt_tokens": response.usage.prompt_tokens,
            "completion_tokens": response.usage.completion_tokens
        }
    )
    
    return response.choices[0].message.content
```

## Estrutura do Pacote

```
qcos-sdk/
├── qcos_sdk/
│   ├── __init__.py
│   ├── licensing.py      # LicensingClient
│   ├── admin.py          # AdminClient
│   ├── billing.py        # BillingClient
│   ├── portal.py         # PortalClient
│   ├── models.py         # Pydantic models compartilhados
│   └── exceptions.py     # Exceções customizadas
├── setup.py
├── README.md
└── examples/
    ├── licensing_example.py
    ├── billing_example.py
    ├── chat_integration.py
    └── tier_management.py
```

## Planos/Tiers Disponíveis

| Tier | API Calls/mês | Storage | Support | Preço/mês |
|------|---------------|---------|---------|-----------|
| **free** | 1,000 | 1 GB | Community | $0 |
| **pro** | 50,000 | 100 GB | Email (48h) | $99 |
| **enterprise** | Ilimitado | Ilimitado | 24/7 Priority | Custom |

## Autenticação

### Service-to-Service (Backend)

```python
# Usar SERVICE_API_KEY (nunca expor ao cliente)
client = BillingClient(api_key=os.getenv("QCOS_SERVICE_API_KEY"))
```

### Employee (Admin Panel)

```python
# Usar JWT token do funcionário
admin = AdminClient(token=employee_jwt_token)
```

### Customer (Portal)

```python
# Usar JWT token do cliente
portal = PortalClient(token=customer_jwt_token)
```

## Documentação Completa

- [API Reference](./docs/api-reference.md)
- [Billing & Tiers Guide](./docs/billing-tiers.md)
- [Integration Examples](./examples/)
- [Error Handling](./docs/errors.md)

## Suporte

- Email: dev@softquantus.com
- Docs: https://docs.softquantus.com/sdk
- Issues: https://github.com/roytmanpiccoli/qcos_core/issues