# Instalacion: Custom App Freshworks Para Botones Reales

Esta es la ruta recomendada para que el cliente toque botones/listas/rating en WhatsApp sin escribir texto libre.

## Por Que No Usar Solo Advanced Automations

Advanced Automations API Library ejecuta APIs, pero en nuestras pruebas no resolvio placeholders como `conversation.id` o `conversationAlias` dentro del body. Sin ese ID, la API externa no puede enviar un mensaje interactivo a la conversacion correcta.

La solucion robusta es una Custom App de Freshworks que escuche eventos reales de Freshchat. Los eventos `onConversationCreate`, `onConversationUpdate` y, cuando este disponible, `onMessageCreate`, entregan el payload completo, incluyendo `data.conversation.conversation_id` y `data.conversation.user_id`.

Docs oficiales:

- https://developers.freshworks.com/docs/app-sdk/v3.0/chat_conversation/serverless-apps/product-events/onconversation/
- https://developers.freshworks.com/docs/app-sdk/v3.0/chat_conversation/serverless-apps/product-events/onmessage/

## Flujo Final

1. Cliente inicia conversacion en WhatsApp.
2. Freshchat dispara `onConversationCreate`.
3. Custom App reenvia el payload completo a:

```text
POST /freshchat/events/conversation
```

4. FastAPI extrae `conversation_id` y `user_id`.
5. FastAPI llama Freshchat Conversation API y envia un `quick_reply_dropdown`.
6. Cliente toca una opcion.
7. Freshchat dispara `onMessageCreate` u `onConversationUpdate`.
8. Custom App reenvia el payload a:

```text
POST /freshchat/events/message
```

9. FastAPI normaliza la opcion y responde con el siguiente mensaje.

## Archivos De La Custom App

La carpeta esta en:

```text
freshworks_custom_app/
```

Contiene:

```text
manifest.json
server.js
config/iparams.json
README.md
```

## Crear ZIP

Desde el proyecto:

```powershell
Compress-Archive -Path .\freshworks_custom_app\* -DestinationPath .\freshworks_custom_app.zip -Force
```

Sube `freshworks_custom_app.zip` en Developer Portal como `Custom App`.

## Si Estas En La Pantalla External App

Puedes usar esta URL como app page:

```text
http://129.80.4.9:8010/freshworks/app
```

Pero `External App` solo registra una ficha/instrucciones de instalacion. Para escuchar `onConversationCreate` y `onMessageCreate`, usa `Custom App` con el ZIP.

## Configuracion Al Instalar

La app pide:

```text
api_base_url = http://129.80.4.9:8010
api_token = valor de FRESHCHAT_API_TOKEN
```

Ejemplo:

```text
api_token = 5110ce720b8b400293ea74b43a9bd2425922e4eb43e544625728a0aabbd2305a
```

## Variables .env En FastAPI

En el servidor:

```env
APP_NAME=MacroBase Freshchat API
APP_ENV=production
FRESHCHAT_API_TOKEN=token-interno-para-custom-app
DEFAULT_RESPONSE_MODE=freshchat_simple

FRESHWORKS_API_BASE_URL=https://api.freshchat.com
FRESHWORKS_API_TOKEN=token-oficial-freshchat
FRESHWORKS_DEFAULT_ACTOR_TYPE=bot
FRESHWORKS_DEFAULT_ACTOR_ID=
FRESHWORKS_ASSUME_IDENTITY=false
EVENT_STORE_PATH=data/freshchat_events.db
```

## Endpoints Nuevos

### POST /freshchat/events/conversation

Recibe el evento `onConversationCreate`, envia el menu interactivo y marca la conversacion como atendida.

### POST /freshchat/events/message

Recibe `onMessageCreate`, ignora mensajes de `bot` o `agent`, normaliza la seleccion del usuario y responde con el texto correspondiente.

## Evitar Loops

La API ignora eventos donde:

```text
actor_type != user
```

Tambien guarda eventos procesados en SQLite para evitar respuestas duplicadas.

## Logs

FastAPI:

```bash
journalctl -u macrobase-freshchat-api -f
```

O si corre manual:

```bash
python -m uvicorn app.main:app --host 0.0.0.0 --port 8010
```

Freshworks Custom App:

```text
Developer Portal > App > Logs
```

## Prueba Esperada

1. Instala la Custom App.
2. Abre una conversacion nueva desde WhatsApp.
3. FastAPI debe registrar:

```text
POST /freshchat/events/conversation
Sending Freshchat interactive message conversation_id=...
```

4. En WhatsApp debe aparecer el menu interactivo.
5. Al tocar `Soporte`, FastAPI debe registrar:

```text
POST /freshchat/events/message
```

6. El cliente debe recibir el texto de soporte.
