root 5740d94295 feat: real ERPNext Healthcare integration + setup tooling
- Replace all mock tools with real ERPNext Healthcare operations
- ERPNextHealthcare class: patients, practitioners, appointments, schedules
- check_availability queries real practitioner schedules from ERPNext
- create_appointment finds/creates patient + validates conflicts + books in ERPNext
- Add /api/v1/config/test endpoint to validate all service connections
- Add scripts/validate_setup.py for CLI validation of Meta/OpenAI/ERPNext/DB
- Add scripts/seed_knowledge.py with full SKEEN catalog (services, products, packages, FAQ)
- Add tests for webhook, health, and WhatsApp client
- Update main.py to include config router
2026-04-29 05:37:22 +00:00

SKEEN CRM AI Agent

Agente de inteligencia artificial para WhatsApp Business API + ERPNext Healthcare.

Arquitectura

┌─────────────┐     ┌─────────────────────┐     ┌─────────────┐
│   Paciente  │────▶│  WhatsApp Business  │────▶│  Meta API   │
│  (WhatsApp) │◀────│       API           │◀────│  Webhooks   │
└─────────────┘     └─────────────────────┘     └──────┬──────┘
                                                       │
                              ┌────────────────────────┘
                              ▼
                    ┌─────────────────────┐
                    │   SKEEN AI Agent    │  FastAPI + Python 3.12
                    │   (Este Repo)       │
                    │                     │
                    │  • OpenAI GPT-4o    │
                    │  • RAG (pgvector)   │
                    │  • Celery + Redis   │
                    │  • PostgreSQL       │
                    └──────────┬──────────┘
                               │
                    ┌──────────┴──────────┐
                    ▼                     ▼
            ┌─────────────┐      ┌─────────────┐
            │   ERPNext   │      │  PostgreSQL │
            │  Healthcare │      │  + pgvector │
            └─────────────┘      └─────────────┘

Stack Tecnológico

Capa Tecnología
Web Framework FastAPI + Uvicorn (HTTP/2)
Base de datos PostgreSQL 16 + pgvector
Cola de tareas Celery + Redis
IA / LLM OpenAI GPT-4o + Embeddings
WhatsApp Meta Business API (oficial)
CRM ERPNext (Frappe Framework)
Observabilidad Structlog + Prometheus
Deploy Docker Compose

Estructura del Proyecto

Skeen-CRM/
├── src/
│   ├── main.py                    # Entry point FastAPI
│   ├── config.py                  # Pydantic Settings
│   ├── api/
│   │   ├── v1/
│   │   │   ├── webhooks.py        # Meta WhatsApp webhooks
│   │   │   ├── messages.py        # API envío manual
│   │   │   └── health.py          # Health checks
│   │   └── deps.py                # Dependency injection
│   ├── domain/
│   │   ├── models/
│   │   │   └── conversation.py    # Entidades SQLAlchemy
│   │   └── services/
│   ├── use_cases/
│   │   └── handle_incoming_message.py  # Pipeline AI
│   ├── infrastructure/
│   │   ├── db.py                  # PostgreSQL async
│   │   ├── redis.py               # Redis client
│   │   ├── whatsapp/
│   │   │   ├── client.py          # Meta Graph API client
│   │   │   └── webhook.py         # Webhook parser/validator
│   │   ├── ai/
│   │   │   ├── openai_client.py   # OpenAI async client
│   │   │   ├── rag.py             # Vector store pgvector
│   │   │   └── prompts.py         # Tools & prompts
│   │   └── erpnext/
│   │       └── client.py          # Frappe REST API client
│   └── workers/
│       ├── celery_app.py          # Celery configuration
│       └── tasks.py               # Background tasks
├── alembic/                       # Database migrations
├── docker-compose.yml             # Full stack local
├── Dockerfile                     # Production image
└── pyproject.toml                 # Dependencies (uv)

Requisitos

  • Python 3.12+
  • Docker + Docker Compose
  • Cuenta de WhatsApp Business API (Meta)
  • API Key de OpenAI
  • Instancia de ERPNext (para integración completa)

Instalación Local

1. Clonar y entrar al directorio

cd Skeen-CRM

2. Copiar variables de entorno

cp .env.example .env
# Editar .env con tus credenciales de Meta, OpenAI y ERPNext

3. Levantar infraestructura (PostgreSQL + Redis)

docker compose up -d postgres redis

4. Instalar dependencias con uv

pip install uv
uv venv .venv
source .venv/bin/activate
uv pip install -e ".[dev]"

5. Ejecutar migraciones

alembic upgrade head

6. Iniciar servidor de desarrollo

uvicorn src.main:app --reload --host 0.0.0.0 --port 8000

7. Iniciar worker de Celery (en otra terminal)

celery -A src.workers.celery_app worker --loglevel=info -Q default,whatsapp,erpnext,ai

Deploy con Docker Compose (Producción)

docker compose up -d --build

Esto levanta:

  • api: FastAPI (2 workers)
  • worker: Celery worker (4 concurrentes)
  • scheduler: Celery beat
  • postgres: PostgreSQL + pgvector
  • redis: Redis persistente

Configuración de Webhook en Meta

  1. Ir a Meta Developers
  2. Seleccionar tu app de WhatsApp Business
  3. En Webhooks, configurar:
    • Callback URL: https://tu-dominio.com/api/v1/webhooks/whatsapp
    • Verify Token: El valor de META_WEBHOOK_VERIFY_TOKEN en .env
    • Suscripción: messages

Tools / Funciones del Agente

El agente usa OpenAI Function Calling para ejecutar acciones:

Tool Descripción
search_catalog Busca servicios/productos en catálogo vía RAG
check_availability Consulta disponibilidad de citas en ERPNext
create_appointment Crea cita médica en ERPNext Healthcare
get_patient_info Consulta historial del paciente
get_wallet_balance Consulta saldo de monedero
escalate_to_human Escalar a agente humano

Endpoints API

Método Endpoint Descripción
GET /health Liveness probe
GET /ready Readiness probe (incluye DB)
GET /metrics Métricas Prometheus
GET /api/v1/webhooks/whatsapp Verificación Meta
POST /api/v1/webhooks/whatsapp Recepción mensajes
POST /api/v1/messages/text Enviar texto manual
POST /api/v1/messages/template Enviar plantilla
POST /api/v1/messages/buttons Enviar botones

Testing

# Unit tests
pytest tests/ -v

# With coverage
pytest tests/ --cov=src --cov-report=html

Seguridad

  • Verificación de firma HMAC en webhooks (producción)
  • Tokens JWT no usados (usa API Keys de Meta)
  • Rate limiting implementado por número de teléfono
  • Sanitización de inputs antes de enviar a LLM
  • Logging sin exponer datos PHI (solo últimos 4 dígitos de teléfono)

Licencia

Propietario - SKEEN Clínica de Belleza

Description
SKEEN CRM AI Agent para WhatsApp + ERPNext
Readme 249 KiB
Languages
Python 98.4%
Dockerfile 1.1%
Mako 0.5%