{
  "openapi": "3.1.0",
  "servers": [
    {
      "url": "https://app.mercately.com",
      "description": "Production server"
    },
    {
      "url": "https://mercately.shop",
      "description": "Shops API Production server"
    }
  ],
  "info": {
    "license": {
      "name": "MIT",
      "url": "https://opensource.org/licenses/MIT"
    },
    "version": "1.0.0",
    "title": "Mercately Retailers API",
    "termsOfService": "https://mercately.com/terms/",
    "contact": {
      "email": "soporte@mercately.com",
      "url": "http://mercately.com/"
    },
    "description": "La plataforma para desarrolladores de Mercately, está creada para ayudar a todos nuestros clientes y empoderarlos para que crezcan mejor. Nuestras API están diseñadas para permitir que los equipos de cualquier forma o tamaño construyan integraciones y aprovechar al máximo Mercately.\nTodas las API de Mercately se construyen usando convenciones REST y están diseñadas para tener una estructura de URL predecible. U tilizan muchas funciones HTTP estándar, incluidos métodos (POST, GET, PUT, DELETE) y códigos de respuesta de error."
  },
  "tags": [
    {
      "name": "Agents",
      "description": "En Mercately, los agentes son conocidos como las personas que están en tu equipo de trabajo. Los agentes pueden estar atados a varios otros objetos como conversaciones, notas, tratos del embudo u órdenes."
    },
    {
      "name": "Customers",
      "description": "En Mercately, todo contacto proveniente de conversaciones, compras o creados directamente se clasifica como cliente."
    },
    {
      "name": "Deals",
      "description": "En Mercately, los embudos permiten visualizar el recorrido que sigues a tus clientes a traves de las negociaciones."
    },
    {
      "name": "Funnels",
      "description": "Embudos y etapas del retailer dueño de la Api-Key. Permite listar, ver, crear, editar y borrar embudos, y listar, crear, editar y borrar sus etapas. Borrar un embudo o una etapa que tiene negocios responde 422 y no borra ningún negocio. No incluye razones de ganado o perdido, reordenar etapas, automatizaciones, favoritos ni exportaciones."
    },
    {
      "name": "Messenger",
      "description": "En Mercately, una vez vinculado con Messenger, este api permite realizar múltiples operaciones para acceder a las conversaciones de Messenger."
    },
    {
      "name": "WhatsApp",
      "description": "En Mercately, una vez vinculado con WhatsApp, este api permite realizar múltiples operaciones para acceder a las conversaciones de WhatsApp y enviar mensajes."
    },
    {
      "name": "WhatsApp Templates",
      "description": "En Mercately, este api permite crear plantillas de WhatsApp, enviarlas a aprobación de Meta y consultar su estado."
    },
    {
      "name": "Flows",
      "description": "En Mercately, una vez creado uno o más flows, esta api permite realizar múltiples operaciones para obtener todos los flows."
    },
    {
      "name": "Integrations",
      "description": "Consulta las integraciones conectadas del retailer y el identificador que se envía a los endpoints de envío."
    },
    {
      "name": "Orders",
      "description": "Crea, actualiza y elimina órdenes en Mercately"
    },
    {
      "name": "Products",
      "description": "Crea, actualiza y elimina productos en Mercately"
    },
    {
      "name": "Product Variants",
      "description": "Actualiza variantes de productos en Mercately"
    },
    {
      "name": "Categories",
      "description": "Obtén todas las categorías creadas en Mercately"
    }
  ],
  "paths": {
    "/retailers/api/v1/agents": {
      "get": {
        "summary": "List all agents",
        "operationId": "listAgents",
        "tags": [
          "Agents"
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "Lista todos los agentes",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "agents": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/agents"
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/retailers/api/v1/customers": {
      "get": {
        "tags": [
          "Customers"
        ],
        "summary": "Customers",
        "description": "Obtén los datos de tus clientes",
        "operationId": "getCustomers",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Busca la página específica de clientes",
            "required": false,
            "schema": {
              "type": "number",
              "example": 1
            }
          },
          {
            "name": "start_date",
            "in": "query",
            "description": "Fecha inicial de búsqueda en formato YYYY-MM-DD",
            "required": false,
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2024-01-01"
            }
          },
          {
            "name": "end_date",
            "in": "query",
            "description": "Fecha final de búsqueda en formato YYYY-MM-DD",
            "required": false,
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2024-12-31"
            }
          },
          {
            "name": "id_type",
            "in": "query",
            "description": "Especifica el tipo de documento a buscar",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "cedula",
                "pasaporte",
                "ruc",
                "rut",
                "otro"
              ]
            }
          },
          {
            "name": "id_number",
            "in": "query",
            "description": "Número de documento a buscar",
            "required": false,
            "schema": {
              "type": "string",
              "example": "1234567890"
            }
          },
          {
            "name": "platform",
            "in": "query",
            "description": "Plataforma de interacción",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "whatsapp",
                "messenger",
                "instagram"
              ]
            }
          },
          {
            "name": "order_by_last_interaction",
            "in": "query",
            "description": "Ordena los clientes por la última interacción según la plataforma",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "asc",
                "desc"
              ]
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "results": {
                      "type": "integer",
                      "description": "Número total de resultados",
                      "example": 1
                    },
                    "total_pages": {
                      "type": "integer",
                      "description": "Número total de páginas",
                      "example": 1
                    },
                    "customers": {
                      "type": "array",
                      "description": "Lista de clientes",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "integer",
                            "description": "ID interno del cliente",
                            "example": 12345
                          },
                          "first_name": {
                            "type": "string",
                            "description": "Nombre del cliente",
                            "example": "Juan"
                          },
                          "last_name": {
                            "type": "string",
                            "description": "Apellido del cliente",
                            "example": "Pérez"
                          },
                          "username": {
                            "type": "string",
                            "description": "Usuario o identificador social del cliente",
                            "example": "jdoe"
                          },
                          "email": {
                            "type": "string",
                            "format": "email",
                            "description": "Correo electrónico del cliente",
                            "example": "juan@example.com"
                          },
                          "phone": {
                            "type": "string",
                            "description": "Teléfono del cliente en formato internacional",
                            "example": "+593999999999"
                          },
                          "id_type": {
                            "type": "string",
                            "description": "Tipo de documento de identidad",
                            "enum": [
                              "cedula",
                              "pasaporte",
                              "ruc",
                              "rut",
                              "otro"
                            ],
                            "example": "cedula"
                          },
                          "id_number": {
                            "type": "string",
                            "description": "Número de documento de identidad",
                            "example": "1234567890"
                          },
                          "address": {
                            "type": "string",
                            "description": "Dirección del cliente",
                            "example": "Av. Principal 123"
                          },
                          "city": {
                            "type": "string",
                            "description": "Ciudad del cliente",
                            "example": "Quito"
                          },
                          "state": {
                            "type": "string",
                            "description": "Estado/Provincia del cliente",
                            "example": "Pichincha"
                          },
                          "zip_code": {
                            "type": "string",
                            "description": "Código postal",
                            "example": "170101"
                          },
                          "notes": {
                            "type": "string",
                            "description": "Notas adicionales del cliente",
                            "example": "Cliente preferencial"
                          },
                          "created_at": {
                            "type": "string",
                            "format": "date-time",
                            "description": "Fecha de creación del cliente",
                            "example": "2024-01-15T10:30:00.000Z"
                          },
                          "updated_at": {
                            "type": "string",
                            "format": "date-time",
                            "description": "Fecha de última actualización",
                            "example": "2024-01-20T15:45:00.000Z"
                          },
                          "inbox_chats": {
                            "type": "array",
                            "description": "Conversaciones del microservicio en las que está indexado el cliente",
                            "items": {
                              "type": "object",
                              "properties": {
                                "chat_id": {
                                  "type": "string",
                                  "example": "6ab18f514477dd0bcd313ab5"
                                },
                                "platform": {
                                  "type": "string",
                                  "example": "whatsapp_gupshup_messages"
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                },
                "examples": {
                  "response": {
                    "value": {
                      "results": 1,
                      "total_pages": 1,
                      "customers": [
                        {
                          "id": 12345,
                          "first_name": "Juan",
                          "last_name": "Pérez",
                          "username": "jdoe",
                          "email": "juan@example.com",
                          "phone": "+593999999999",
                          "id_type": "cedula",
                          "id_number": "1234567890",
                          "address": "Av. Principal 123",
                          "city": "Quito",
                          "state": "Pichincha",
                          "zip_code": "170101",
                          "notes": "Cliente preferencial",
                          "created_at": "2024-01-15T10:30:00.000Z",
                          "updated_at": "2024-01-20T15:45:00.000Z",
                          "inbox_chats": [
                            {
                              "chat_id": "6ab18f514477dd0bcd313ab5",
                              "platform": "whatsapp_gupshup_messages"
                            }
                          ]
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad Request - Parámetros inválidos",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Bad Request"
                    }
                  }
                },
                "examples": {
                  "bad_request": {
                    "value": {
                      "message": "Bad Request"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "Customers"
        ],
        "summary": "Create Customers",
        "description": "Crea un nuevo cliente",
        "operationId": "createCustomer",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "customer": {
                    "type": "object",
                    "description": "Datos del cliente",
                    "properties": {
                      "first_name": {
                        "type": "string",
                        "description": "Nombre del cliente",
                        "example": "Juan"
                      },
                      "last_name": {
                        "type": "string",
                        "description": "Apellido del cliente",
                        "example": "Pérez"
                      },
                      "email": {
                        "type": "string",
                        "format": "email",
                        "description": "Correo electrónico del cliente",
                        "example": "juan@example.com"
                      },
                      "phone": {
                        "type": "string",
                        "description": "Teléfono del cliente en formato internacional",
                        "example": "+593999999999"
                      },
                      "id_type": {
                        "type": "string",
                        "description": "Tipo de documento de identidad",
                        "enum": [
                          "cedula",
                          "pasaporte",
                          "ruc",
                          "rut",
                          "otro"
                        ],
                        "example": "cedula"
                      },
                      "id_number": {
                        "type": "string",
                        "description": "Número de documento de identidad",
                        "example": "1234567890"
                      },
                      "address": {
                        "type": "string",
                        "description": "Dirección del cliente",
                        "example": "Av. Principal 123"
                      },
                      "city": {
                        "type": "string",
                        "description": "Ciudad del cliente",
                        "example": "Quito"
                      },
                      "state": {
                        "type": "string",
                        "description": "Estado/Provincia del cliente",
                        "example": "Pichincha"
                      },
                      "zip_code": {
                        "type": "string",
                        "description": "Código postal",
                        "example": "170101"
                      },
                      "customer_addresses_attributes": {
                        "type": "array",
                        "description": "Direcciones adicionales del cliente",
                        "items": {
                          "type": "object",
                          "properties": {
                            "address": {
                              "type": "string",
                              "description": "Dirección",
                              "example": "Calle Secundaria 456"
                            },
                            "city": {
                              "type": "string",
                              "description": "Ciudad",
                              "example": "Guayaquil"
                            },
                            "state": {
                              "type": "string",
                              "description": "Estado/Provincia",
                              "example": "Guayas"
                            },
                            "zip_code": {
                              "type": "string",
                              "description": "Código postal",
                              "example": "090101"
                            },
                            "country_id": {
                              "type": "integer",
                              "description": "ID del país",
                              "example": 1
                            },
                            "latitude": {
                              "type": "string",
                              "description": "Latitud de la dirección",
                              "example": "-2.1894"
                            },
                            "longitude": {
                              "type": "string",
                              "description": "Longitud de la dirección",
                              "example": "-79.8891"
                            },
                            "description": {
                              "type": "string",
                              "description": "Descripción de la dirección",
                              "example": "Oficina principal"
                            },
                            "main": {
                              "type": "boolean",
                              "description": "Indica si es la dirección principal",
                              "example": true
                            }
                          }
                        }
                      },
                      "notes": {
                        "type": "string",
                        "description": "Notas adicionales del cliente",
                        "example": "Cliente VIP"
                      }
                    }
                  },
                  "agent_id": {
                    "type": "integer",
                    "description": "ID del agente asignado al cliente (puede estar en nivel raíz o dentro de customer)",
                    "example": 1
                  },
                  "tags": {
                    "type": "array",
                    "description": "Array de etiquetas del cliente (puede estar en nivel raíz o dentro de customer)",
                    "items": {
                      "type": "object",
                      "properties": {
                        "name": {
                          "type": "string",
                          "description": "Nombre de la etiqueta",
                          "example": "VIP"
                        },
                        "value": {
                          "type": "boolean",
                          "description": "Valor de la etiqueta",
                          "example": true
                        }
                      }
                    }
                  },
                  "custom_fields": {
                    "type": "array",
                    "description": "Array de campos personalizados del cliente (puede estar en nivel raíz o dentro de customer)",
                    "items": {
                      "type": "object",
                      "properties": {
                        "field_name": {
                          "type": "string",
                          "description": "Nombre del campo personalizado",
                          "example": "preferencia_contacto"
                        },
                        "field_content": {
                          "type": "string",
                          "description": "Contenido del campo personalizado",
                          "example": "WhatsApp"
                        }
                      }
                    }
                  }
                }
              },
              "examples": {
                "create_customer": {
                  "value": {
                    "customer": {
                      "first_name": "Juan",
                      "last_name": "Pérez",
                      "email": "juan@example.com",
                      "phone": "+593999999999",
                      "id_type": "cedula",
                      "id_number": "1234567890",
                      "address": "Av. Principal 123",
                      "city": "Quito",
                      "state": "Pichincha",
                      "zip_code": "170101",
                      "customer_addresses_attributes": [
                        {
                          "address": "Calle Secundaria 456",
                          "city": "Guayaquil",
                          "state": "Guayas",
                          "zip_code": "090101",
                          "country_id": 1,
                          "latitude": "-2.1894",
                          "longitude": "-79.8891",
                          "description": "Oficina principal",
                          "main": true
                        }
                      ],
                      "notes": "Cliente VIP"
                    },
                    "agent_id": 1,
                    "tags": [
                      {
                        "name": "VIP",
                        "value": true
                      }
                    ],
                    "custom_fields": [
                      {
                        "field_name": "preferencia_contacto",
                        "field_content": "WhatsApp"
                      }
                    ]
                  }
                }
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK - Cliente creado con éxito",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Customer created successfully"
                    },
                    "customer": {
                      "type": "object",
                      "properties": {
                        "id": {
                          "type": "integer",
                          "example": 12345
                        },
                        "first_name": {
                          "type": "string",
                          "example": "Juan"
                        },
                        "last_name": {
                          "type": "string",
                          "example": "Pérez"
                        },
                        "email": {
                          "type": "string",
                          "example": "juan@example.com"
                        },
                        "phone": {
                          "type": "string",
                          "example": "+593999999999"
                        },
                        "id_type": {
                          "type": "string",
                          "example": "cedula"
                        },
                        "id_number": {
                          "type": "string",
                          "example": "1234567890"
                        },
                        "address": {
                          "type": "string",
                          "example": "Av. Principal 123"
                        },
                        "city": {
                          "type": "string",
                          "example": "Quito"
                        },
                        "state": {
                          "type": "string",
                          "example": "Pichincha"
                        },
                        "zip_code": {
                          "type": "string",
                          "example": "170101"
                        },
                        "notes": {
                          "type": "string",
                          "example": "Cliente VIP"
                        },
                        "created_at": {
                          "type": "string",
                          "format": "date-time",
                          "example": "2024-01-15T10:30:00.000Z"
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad Request - Datos inválidos",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Bad Request"
                    },
                    "errors": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  }
                },
                "examples": {
                  "bad_request": {
                    "value": {
                      "message": "Bad Request",
                      "errors": [
                        "Phone can't be blank",
                        "Email is invalid"
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/customers/:id": {
      "get": {
        "tags": [
          "Customers"
        ],
        "summary": "Customer/:id",
        "description": "Obtén los datos de un cliente en especifico buscado por ID",
        "operationId": "customer/:id",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/customer"
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/retailers/api/v1/customers/:email": {
      "get": {
        "tags": [
          "Customers"
        ],
        "summary": "Customer/:email",
        "description": "Obtén los datos de un cliente en especifico buscado por email",
        "operationId": "customer/email",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/get_customer"
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/retailers/api/v1/customers/:phone": {
      "get": {
        "tags": [
          "Customers"
        ],
        "summary": "Customer/:phone",
        "description": "Obtén los datos de un cliente en especifico buscado por phone",
        "operationId": "customer/phone",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/get_customer"
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      },
      "put": {
        "tags": [
          "Customers"
        ],
        "summary": "Update Customer by email, id or phone",
        "description": "Actualiza un nuevo customer buscado por email, id o phone. Puedes realizar la busqueda igual que los métodos get",
        "operationId": "updateCustomer/email",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/update_customer"
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/update_customer-2"
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/retailers/api/v1/customers/:id/events": {
      "post": {
        "tags": [
          "Customer events"
        ],
        "summary": "Create Customer Event",
        "description": "Crea un nuevo evento para el cliente",
        "operationId": "customer/:id/events",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/customer_event"
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "201": {
            "description": "CREATED",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/create_customer_event"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/retailers/api/v1/customers/:id/whatsapp_conversations": {
      "get": {
        "tags": [
          "Customers"
        ],
        "summary": "Customer/:id/whatsapp_conversations",
        "description": "Obtén la conversación de Whatsapp del cliente por ID",
        "operationId": "customer/id/whatsapp_conversations",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Busca la página específica de conversaciónes",
            "schema": {
              "type": "number"
            }
          },
          {
            "name": "results_per_page",
            "in": "query",
            "description": "Selecciona el número de mensajes que serán visualizados por página",
            "schema": {
              "type": "number"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "whatsapp_conversations": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/whatsapp_api_message"
                      }
                    },
                    "total_pages": {
                      "type": "integer",
                      "example": 1
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/retailers/api/v1/customers/:phone/whatsapp_conversations": {
      "get": {
        "tags": [
          "Customers"
        ],
        "summary": "Customer/:phone/whatsapp_conversations",
        "description": "Obtén la conversación de Whatsapp del cliente por número de teléfono",
        "operationId": "customer/phone/whatsapp_conversations",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Busca la página específica de conversaciónes",
            "schema": {
              "type": "number"
            }
          },
          {
            "name": "results_per_page",
            "in": "query",
            "description": "Selecciona el número de mensajes que serán visualizados por página",
            "schema": {
              "type": "number"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "whatsapp_conversations": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/whatsapp_api_message"
                      }
                    },
                    "total_pages": {
                      "type": "integer",
                      "example": 1
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/retailers/api/v1/customers/:id/messenger_conversations": {
      "get": {
        "tags": [
          "Customers"
        ],
        "summary": "Customer/:id/messenger_conversations",
        "description": "Obtén la conversación de Messenger del cliente",
        "operationId": "customer/id/messenger_conversations",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Busca la página específica de conversaciónes",
            "schema": {
              "type": "number"
            }
          },
          {
            "name": "results_per_page",
            "in": "query",
            "description": "Selecciona el número de mensajes que serán visualizados por página",
            "schema": {
              "type": "number"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "messenger_conversations": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/messenger_message"
                      }
                    },
                    "total_pages": {
                      "type": "integer",
                      "example": 1
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/retailers/api/v1/customers/:id/instagram_conversations": {
      "get": {
        "tags": [
          "Customers"
        ],
        "summary": "Customer/:id/instagram_conversations",
        "description": "Obtén la conversación de Instagram del cliente",
        "operationId": "customer/id/instagram_conversations",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Busca la página específica de conversaciónes",
            "schema": {
              "type": "number"
            }
          },
          {
            "name": "results_per_page",
            "in": "query",
            "description": "Selecciona el número de mensajes que serán visualizados por página",
            "schema": {
              "type": "number"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "instagram_messages": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/messenger_message"
                      }
                    },
                    "total_pages": {
                      "type": "integer",
                      "example": 1
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/retailers/api/v1/customers/:id/customer_events_history": {
      "get": {
        "tags": [
          "Customer events"
        ],
        "summary": "Get Customer Events",
        "description": "Obtiene los eventos del cliente",
        "operationId": "customers/:id/customer_events",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Busca la página específica de eventos",
            "schema": {
              "type": "number"
            }
          },
          {
            "name": "results_per_page",
            "in": "query",
            "description": "Selecciona el número de eventos que serán visualizados por página",
            "schema": {
              "type": "number"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/get_customer_event"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/retailers/api/v1/deals": {
      "get": {
        "summary": "Obtener deals",
        "tags": [
          "Deals"
        ],
        "description": "Obtén la lista de negociaciones",
        "operationId": "ListDeal",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "funnel_name",
            "in": "query",
            "description": "Nombre del embudo",
            "required": true,
            "schema": {
              "type": "string",
              "example": "Negociaciones"
            }
          },
          {
            "name": "stage",
            "in": "query",
            "description": "Nombre de la etapa",
            "required": true,
            "schema": {
              "type": "string",
              "example": "Calificado"
            }
          },
          {
            "name": "page",
            "in": "query",
            "description": "número de pagina",
            "schema": {
              "type": "integer",
              "example": 1
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/index"
                }
              }
            }
          },
          "404": {
            "description": "not found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "stage not found"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "Create deal",
        "tags": [
          "Deals"
        ],
        "description": "Crea una nueva negociación",
        "operationId": "CreateDeal",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "funnel_name": {
                    "type": "string",
                    "example": "Negociaciones"
                  },
                  "stage": {
                    "type": "string",
                    "example": "Calificado"
                  },
                  "deal": {
                    "type": "object",
                    "properties": {
                      "amount": {
                        "type": "string",
                        "example": "150000"
                      },
                      "name": {
                        "type": "string"
                      },
                      "customer_id": {
                        "type": "string",
                        "example": "91989a87"
                      },
                      "agent_id": {
                        "type": "integer"
                      },
                      "lead_status": {
                        "type": "string",
                        "enum": [
                          "cold",
                          "warm",
                          "hot"
                        ],
                        "example": "cold"
                      },
                      "opening_date": {
                        "type": "string",
                        "format": "date",
                        "example": "2024-05-16"
                      },
                      "expected_close_date": {
                        "type": "string",
                        "format": "date",
                        "example": "2024-05-23"
                      }
                    }
                  }
                },
                "required": [
                  "funnel_name",
                  "stage",
                  "deal"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/create"
                }
              }
            }
          },
          "422": {
            "description": "No se pudo procesar el recurso",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "errors": {
                      "type": "string",
                      "example": "unprocessable entity"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/deals/{id}": {
      "get": {
        "summary": "deals/:id",
        "tags": [
          "Deals"
        ],
        "description": "Obtén una negociacion",
        "operationId": "GetDeal",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "ID de la negociación",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/get"
                }
              }
            }
          },
          "404": {
            "description": "La negociación no existe",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "deal not found"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "put": {
        "summary": "deals/:id",
        "tags": [
          "Deals"
        ],
        "description": "Actualiza una negociación",
        "operationId": "UpdateDeal",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "ID de la negociación",
            "schema": {
              "type": "string",
              "example": "9c6d04017"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "funnel_name": {
                    "type": "string",
                    "example": "Negociaciones"
                  },
                  "stage": {
                    "type": "string",
                    "example": "Calificado"
                  },
                  "deal": {
                    "type": "object",
                    "properties": {
                      "amount": {
                        "type": "string",
                        "example": "150000"
                      },
                      "name": {
                        "type": "string",
                        "example": "Ricardo - pavo"
                      },
                      "customer_id": {
                        "type": "string",
                        "example": "91989a87"
                      },
                      "lead_status": {
                        "type": "string",
                        "example": "cold"
                      },
                      "opening_date": {
                        "type": "string",
                        "format": "date",
                        "example": "2024-05-16"
                      },
                      "expected_close_date": {
                        "type": "string",
                        "format": "date",
                        "example": "2024-05-23"
                      },
                      "funnel_name": {
                        "type": "string",
                        "example": "Negociaciones"
                      },
                      "stage": {
                        "type": "string",
                        "example": "Calificado"
                      }
                    }
                  }
                },
                "required": [
                  "funnel_name",
                  "stage",
                  "deal"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/update"
                }
              }
            }
          },
          "404": {
            "description": "La negociación no existe",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "deal not found"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "No se pudo procesar el recurso",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "errors": {
                      "type": "string",
                      "example": "unprocessable entity"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "delete": {
        "summary": "deals/:id",
        "tags": [
          "Deals"
        ],
        "description": "Elimina una negociación",
        "operationId": "deleteDeal",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "ID de la negociación",
            "schema": {
              "type": "string",
              "example": 93390836
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "deal was deleted successfully"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "negociación no existe",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "deal not found"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Error al procesar el recurso",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Error deleting deal"
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/funnels": {
      "get": {
        "summary": "Obtener embudos",
        "description": "Lista los embudos del retailer con sus etapas, ordenadas por posición.",
        "tags": [
          "Funnels"
        ],
        "operationId": "ListFunnels",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel_list"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/funnels_unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/funnels_invalid_api_key"
          }
        }
      },
      "post": {
        "summary": "Crear embudo",
        "description": "Crea un embudo sin etapas. El nombre es obligatorio, de hasta 40 caracteres y único por retailer (sin distinguir mayúsculas).",
        "tags": [
          "Funnels"
        ],
        "operationId": "CreateFunnel",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/funnel_input"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel"
                },
                "example": {
                  "id": "1c4f2a9b7e3d5a1-8b2e-4c6d-9f0a-3e5b7d9c1a2f",
                  "name": "Embudo API prueba",
                  "stages": []
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/funnels_unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/funnels_invalid_api_key"
          },
          "422": {
            "$ref": "#/components/responses/funnel_validation_error"
          }
        }
      }
    },
    "/retailers/api/v1/funnels/{id}": {
      "parameters": [
        {
          "name": "id",
          "in": "path",
          "required": true,
          "description": "ID del embudo",
          "schema": {
            "type": "string",
            "example": "1c4f2a9b7e3d5a1-8b2e-4c6d-9f0a-3e5b7d9c1a2f"
          }
        }
      ],
      "get": {
        "summary": "Obtener embudo",
        "description": "Obtiene un embudo del retailer con sus etapas.",
        "tags": [
          "Funnels"
        ],
        "operationId": "GetFunnel",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/funnels_unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/funnel_not_found"
          }
        }
      },
      "put": {
        "summary": "Editar embudo",
        "description": "Cambia el nombre del embudo. Mismas reglas que al crear: obligatorio, hasta 40 caracteres y único por retailer.",
        "tags": [
          "Funnels"
        ],
        "operationId": "UpdateFunnel",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/funnel_input"
              },
              "example": {
                "funnel": {
                  "name": "Embudo API editado"
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel"
                },
                "example": {
                  "id": "1c4f2a9b7e3d5a1-8b2e-4c6d-9f0a-3e5b7d9c1a2f",
                  "name": "Embudo API editado",
                  "stages": []
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/funnels_unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/funnel_not_found"
          },
          "422": {
            "$ref": "#/components/responses/funnel_validation_error"
          }
        }
      },
      "delete": {
        "summary": "Borrar embudo",
        "description": "Borra el embudo y sus etapas. Si alguna etapa tiene negocios, responde 422 y no borra el embudo, las etapas ni los negocios.",
        "tags": [
          "Funnels"
        ],
        "operationId": "DeleteFunnel",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel_message"
                },
                "example": {
                  "message": "Funnel was deleted"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/funnels_unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/funnel_not_found"
          },
          "422": {
            "description": "El embudo tiene negocios",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel_message"
                },
                "example": {
                  "message": "Cannot delete a funnel that has deals"
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/funnels/{funnel_id}/stages": {
      "parameters": [
        {
          "name": "funnel_id",
          "in": "path",
          "required": true,
          "description": "ID del embudo",
          "schema": {
            "type": "string",
            "example": "1c4f2a9b7e3d5a1-8b2e-4c6d-9f0a-3e5b7d9c1a2f"
          }
        }
      ],
      "get": {
        "summary": "Obtener etapas",
        "description": "Lista las etapas del embudo, ordenadas por posición.",
        "tags": [
          "Funnels"
        ],
        "operationId": "ListFunnelStages",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel_stage_list"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/funnels_unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/funnel_not_found"
          }
        }
      },
      "post": {
        "summary": "Crear etapa",
        "description": "Agrega una etapa al final del embudo. El nombre es obligatorio y único dentro del embudo. `type` puede ser `step`, `won` o `lost`; si no se envía, queda `step`. No acepta razones de ganado o perdido ni posición.",
        "tags": [
          "Funnels"
        ],
        "operationId": "CreateFunnelStage",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/funnel_stage_create"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel_stage"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/funnels_unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/funnel_not_found"
          },
          "422": {
            "$ref": "#/components/responses/funnel_stage_validation_error"
          }
        }
      }
    },
    "/retailers/api/v1/funnels/{funnel_id}/stages/{id}": {
      "parameters": [
        {
          "name": "funnel_id",
          "in": "path",
          "required": true,
          "description": "ID del embudo",
          "schema": {
            "type": "string",
            "example": "1c4f2a9b7e3d5a1-8b2e-4c6d-9f0a-3e5b7d9c1a2f"
          }
        },
        {
          "name": "id",
          "in": "path",
          "required": true,
          "description": "ID de la etapa",
          "schema": {
            "type": "string",
            "example": "19d8e7c6b5a4f3e-2d1c-4b0a-9e8f-7a6b5c4d3e2f"
          }
        }
      ],
      "put": {
        "summary": "Editar etapa",
        "description": "Actualiza los campos enviados de la etapa. Mismas reglas que al crear.",
        "tags": [
          "Funnels"
        ],
        "operationId": "UpdateFunnelStage",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/funnel_stage_update"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel_stage"
                },
                "example": {
                  "id": "19d8e7c6b5a4f3e-2d1c-4b0a-9e8f-7a6b5c4d3e2f",
                  "name": "Contactado",
                  "probability": 40,
                  "stagnation_time": 3,
                  "type": "won"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/funnels_unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/funnel_stage_not_found"
          },
          "422": {
            "$ref": "#/components/responses/funnel_stage_validation_error"
          }
        }
      },
      "delete": {
        "summary": "Borrar etapa",
        "description": "Borra la etapa. Si tiene negocios, responde 422 y no borra la etapa ni los negocios.",
        "tags": [
          "Funnels"
        ],
        "operationId": "DeleteFunnelStage",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel_message"
                },
                "example": {
                  "message": "Stage was deleted"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/funnels_unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/funnel_stage_not_found"
          },
          "422": {
            "description": "La etapa tiene negocios",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/funnel_message"
                },
                "example": {
                  "message": "Cannot delete a stage that has deals"
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/messenger_conversations": {
      "get": {
        "tags": [
          "Messenger"
        ],
        "summary": "Messenger conversations",
        "description": "Obtén los clients que te han escrito por messenger",
        "operationId": "messengerClients",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "title": "Messenger conversations",
                "properties": {
                  "page": {
                    "type": "number"
                  },
                  "results_per_page": {
                    "type": "number"
                  },
                  "unassigned": {
                    "type": "boolean"
                  }
                }
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "results": {
                      "type": "integer",
                      "example": 155
                    },
                    "total_pages": {
                      "type": "integer",
                      "example": 2
                    },
                    "facebook_messages": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string",
                            "example": "621osgzy4696283"
                          },
                          "first_name": {
                            "type": "string",
                            "example": "Claudia"
                          },
                          "last_name": {
                            "type": "string",
                            "example": "Funnel"
                          },
                          "email": {
                            "type": [
                              "string",
                              "null"
                            ],
                            "example": "null"
                          },
                          "message_count": {
                            "type": "integer",
                            "example": 3
                          },
                          "last_interaction": {
                            "type": "string",
                            "example": "2023-04-17T05:08:17.085Z"
                          },
                          "agent_id": {
                            "type": "integer",
                            "example": 4637
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/retailers/api/v1/integrations": {
      "get": {
        "tags": [
          "Integrations"
        ],
        "summary": "List connected integrations",
        "description": "Lista las integraciones conectadas del retailer. El `id` de cada integración es el\n`platform_retailer_id` que se envía a los endpoints de envío cuando el retailer tiene\nmás de una integración. `platform` es la plataforma general (`whatsapp`, `messenger`,\n`instagram`, `tiktok_messages`, `tiktok_comments`, `facebook_comments`,\n`instagram_comments`).\n",
        "operationId": "listIntegrations",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "platform",
            "in": "query",
            "required": false,
            "description": "Clave específica de la plataforma (por ejemplo, `whatsapp_gupshup_messages`).",
            "schema": {
              "type": "string",
              "example": "whatsapp_gupshup_messages"
            }
          },
          {
            "name": "connected_only",
            "in": "query",
            "required": false,
            "description": "Devuelve solo las integraciones conectadas (por defecto `true`).",
            "schema": {
              "type": "boolean",
              "example": true
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "integrations": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string",
                            "description": "Identificador de la integración (`platform_retailer_id`).",
                            "example": "6aa831f6f3c34b7e791c9b96"
                          },
                          "platform": {
                            "type": "string",
                            "description": "Plataforma general.",
                            "example": "whatsapp"
                          },
                          "external_id": {
                            "type": "string",
                            "example": "771994542673863"
                          },
                          "name": {
                            "type": "string",
                            "example": "Ventas"
                          },
                          "status": {
                            "type": "string",
                            "example": "active"
                          }
                        }
                      },
                      "example": [
                        {
                          "id": "6aa831f6f3c34b7e791c9b96",
                          "platform": "whatsapp",
                          "external_id": "771994542673863",
                          "name": "Ventas",
                          "status": "active"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Falta el header `Api-Key`"
          },
          "404": {
            "description": "La `Api-Key` es desconocida"
          },
          "502": {
            "description": "No se pudieron consultar las integraciones; reintenta"
          }
        }
      }
    },
    "/retailers/api/v1/whatsapp/send_notification_by_id": {
      "post": {
        "tags": [
          "WhatsApp"
        ],
        "summary": "Send WhatsApp Message for WhatsApp Business API",
        "description": "Para enviar una plantilla de WhatsApp cuando se tiene una conexión oficial al API de WhatsApp, se requieren\ninternal_id y template_params, además de phone_number o customer_id (al menos uno); los demás son opcionales.\nSi se envían ambos, se usa customer_id; si ese customer_id no existe, se usa phone_number.\n\nPara enviar un mensaje libre (texto o media) que no sea plantilla, usa\n`POST /retailers/api/v1/whatsapp/send_open_message`. Si se tiene una conexión vía QR, revisa también\nla sección de envío de mensajes vía QR.\n",
        "operationId": "sendWhatsAppApi",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/send_api_message"
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/whatsapp_api_message"
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Customer not found"
          },
          "422": {
            "description": "Unprocessable Entity. El cliente resuelto no tiene teléfono ni user_id, o la plantilla no es válida."
          },
          "500": {
            "description": "Internal Server Error"
          }
        }
      }
    },
    "/retailers/api/v1/whatsapp/send_message": {
      "post": {
        "tags": [
          "WhatsApp"
        ],
        "summary": "Send WhatsApp Message for WhatsApp Business QR",
        "description": "Enviar un mensaje de WhatsApp cuando tienes una conexión oficial por QR.\nSe requiere phone_number o customer_id (al menos uno) y message (o media_url), el resto de parámetros son opcionales.\nSi se envían ambos, se usa customer_id; si ese customer_id no existe, se usa phone_number.\nEl cliente debe tener teléfono o user_id; si no, responde 422.\n\nEste endpoint es **solo para QR** y solo acepta imágenes JPG/JPEG/PNG y documentos PDF.\nPara enviar texto o media (imagen, documento, audio o video) por cualquier línea, oficial (BSP/Gupshup) o QR,\nusa `POST /retailers/api/v1/whatsapp/send_open_message`.\n",
        "operationId": "sendWhatsAppQr",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/send_qr_message"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/whatsapp_api_message"
                }
              }
            }
          },
          "400": {
            "description": "Bad Request"
          },
          "404": {
            "description": "Customer not found"
          },
          "422": {
            "description": "Unprocessable Entity. El cliente resuelto no tiene teléfono ni user_id, o el envío legacy no pudo procesarse."
          },
          "500": {
            "description": "Internal Server Error"
          }
        }
      }
    },
    "/retailers/api/v1/whatsapp/send_open_message": {
      "post": {
        "tags": [
          "WhatsApp"
        ],
        "summary": "Send a free-form WhatsApp message",
        "description": "Envía un mensaje de WhatsApp que **no es una plantilla**: texto, o media de tipo imagen, documento,\naudio o video, con texto opcional como caption. Funciona tanto con la conexión oficial (BSP/Gupshup)\ncomo con una línea QR.\n\n- El destinatario se identifica con `phone_number` o `customer_id`. Si se envían ambos, se usa\n  `customer_id`; si ese `customer_id` no existe, se usa `phone_number`. Si el cliente no existe, se crea.\n- El cliente debe tener teléfono o `user_id`; si no, responde 422.\n- La línea se elige con `integration_id`, el mismo `id` que devuelve\n  `GET /retailers/api/v1/whatsapp_templates/integrations` (que incluye BSP, Gupshup y QR).\n  Con una sola línea no es necesario; con varias es obligatorio un `integration_id` válido.\n- Media permitida: imágenes JPG/JPEG/PNG, documentos PDF/DOC/DOCX/XLS/XLSX,\n  audio MP3/OGG/OGA/OPUS/M4A/AAC/WAV y video MP4/3GP/MOV/M4V.\n- Mercately **no** valida la ventana de 24 horas: intenta el envío y, si el proveedor lo rechaza,\n  devuelve su mensaje de error tal cual. En QR no existe esa ventana.\n- `POST /retailers/api/v1/whatsapp/send_message` (QR, JPG/PNG/PDF) y\n  `POST /retailers/api/v1/whatsapp/send_notification_by_id` (plantillas) mantienen su contrato.\n",
        "operationId": "sendWhatsAppOpenMessage",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/send_open_message"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/whatsapp_api_message"
                }
              }
            }
          },
          "400": {
            "description": "Falta el contenido, el cliente, o el tipo de media no está permitido"
          },
          "401": {
            "description": "Falta el header Api-Key"
          },
          "404": {
            "description": "Customer not found, o integration_id inexistente"
          },
          "422": {
            "description": "Varias líneas sin `integration_id` válido, el cliente no tiene teléfono ni `user_id`, o el proveedor rechazó el envío (se devuelve su mensaje)."
          },
          "502": {
            "description": "No se pudo contactar al proveedor"
          }
        }
      }
    },
    "/retailers/api/v1/whatsapp_templates": {
      "get": {
        "tags": [
          "WhatsApp Templates"
        ],
        "summary": "WhatsApp Business Api Templates",
        "description": "Obtén los templates/plantillas creadas en WhatsApp Business API",
        "operationId": "whatsappTemplates",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "title": "WhatsApp Business Api templates"
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "templates": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "text": {
                            "type": "string",
                            "example": "Hola *! ✋"
                          },
                          "status": {
                            "type": "string",
                            "example": "accepted"
                          },
                          "template_type": {
                            "type": "string",
                            "example": "text"
                          },
                          "internal_id": {
                            "type": "string",
                            "example": "c0c040f6-9809-404a-961c-637b109ef410"
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          }
        }
      },
      "post": {
        "tags": [
          "WhatsApp Templates"
        ],
        "summary": "Create a WhatsApp template",
        "description": "Crea una plantilla y la envía a Meta para su aprobación. La respuesta indica que fue **enviada**, no aprobada: consulta el resultado con `GET /retailers/api/v1/whatsapp_templates/{id}`.\n\nSoporta texto, imagen, video, documento, botones, carrusel, oferta limitada y autenticación (OTP).\n\nCrea y consulta las plantillas de WhatsApp (HSM) desde la API. Esta sección explica **cómo se arma el contenido de una plantilla** (variables, ejemplos, imágenes, formato) y qué errores devuelve la API cuando una regla no se cumple.\n\n> Versión actual: texto, imagen, video y documento; botones de respuesta rápida y de llamado a la acción; **carrusel**; **oferta limitada**; plantillas de **autenticación (código OTP)**; y soporte para cuentas con varios números de WhatsApp. La ubicación (`location`) aún no está disponible por API.\n\n### Autenticación de las peticiones\n\nTodas las peticiones llevan el header `Api-Key` del retailer.\n\n| Caso | Respuesta |\n|---|---|\n| Sin header `Api-Key` | `401` |\n| `Api-Key` desconocida | `404 Resource not found` |\n\nEl límite global es de 10 peticiones por segundo por IP.\n\n### Endpoints\n\n| Método | Ruta | Descripción |\n|---|---|---|\n| `POST` | `/retailers/api/v1/whatsapp_templates` | Crea la plantilla y la envía a Meta para su aprobación |\n| `GET` | `/retailers/api/v1/whatsapp_templates/:id` | Consulta una plantilla en **cualquier** estado. `:id` es el `id` numérico o el `internal_id` |\n| `GET` | `/retailers/api/v1/whatsapp_templates` | Lista solo las plantillas `accepted` y `disabled` (las utilizables para enviar) |\n| `GET` | `/retailers/api/v1/whatsapp_templates/integrations` | Lista los números de WhatsApp activos (cuentas con varios números). Incluye la línea QR, que sirve para mensajes libres pero no para crear plantillas |\n\nLa creación es asíncrona de cara a Meta: la respuesta indica que la plantilla fue **enviada**, no aprobada. Consulta el resultado con `GET /whatsapp_templates/:id`.\n\n### Campos del `POST`\n\n| Campo | Obligatorio | Descripción |\n|---|---|---|\n| `name` | Sí | Nombre de la plantilla. Se normaliza: minúsculas, espacios → `_` y solo `a-z`, `0-9`, `_`. Único por retailer (sin distinguir mayúsculas). Máx. 512 |\n| `language` | Sí | `spanish` o `english` (también se aceptan `es_ES` y `en_US`) |\n| `category` | Sí | `MARKETING`, `UTILITY` o `AUTHENTICATION` (ver Autenticación) |\n| `template_type` | Sí (salvo autenticación) | `text`, `image`, `video`, `document` o `carousel` |\n| `text` | Sí (salvo autenticación) | Cuerpo del mensaje (en un carrusel, el texto principal sobre las tarjetas). Máx. 1024 caracteres sin contar las variables |\n| `body_examples` | Sí, si `text` tiene variables | Un valor de ejemplo por variable, en orden |\n| `header_text` | No | Encabezado de texto. Solo con `template_type: text`. Máx. 60 caracteres, sin HTML |\n| `media_url` | Sí en `image`, `video` y `document` | URL `https` pública del archivo (ver Imágenes, video y documentos). No se permite en `text` |\n| `buttons` | No | Lista de botones (ver Botones). No va en carruseles ni con una oferta |\n| `offer` | No | Oferta limitada (ver Oferta limitada) |\n| `cards` y `cards_media_type` | Solo en `carousel` | Tarjetas y tipo de media común (ver Carrusel) |\n| `add_security_recommendation`, `code_expiry_minutes`, `code_example` | Solo en `AUTHENTICATION` | Opciones del código (ver Autenticación) |\n| `team_id` | No | Equipo del retailer al que se asigna la plantilla |\n| `integration_id` | Solo si hay más de un número activo | Número de WhatsApp con el que se crea (ver Varios números) |\n| `integration_platform` | No | Solo para confirmar la plataforma de `integration_id`; se deduce sola |\n\n### Variables en el texto\n\nLas variables son los huecos que se rellenan al enviar el mensaje (nombre del cliente, número de pedido…).\n\n- Sintaxis: `{{1}}`, `{{2}}`, `{{3}}`… — número entero mayor que 0 entre dobles llaves.\n- Deben ser **correlativas desde `{{1}}`** y **no repetirse**. `{{1}} … {{3}}` (salta el 2) o `{{1}} … {{1}}` se rechazan.\n- El texto **no puede empezar ni terminar con una variable** (regla de Meta): `Hola {{1}}, gracias` es válido; `{{1}} gracias` no.\n- No se permiten nombres: `{{nombre}}` es inválido.\n\n#### Ejemplos obligatorios\n\nMeta revisa la plantilla con valores de muestra. Envía en `body_examples` **un valor por variable, en el mismo orden**, sin vacíos:\n\n```json\n{\n  \"text\": \"Hola {{1}}, tu pedido {{2}} va en camino\",\n  \"body_examples\": [\"Ana\", \"ORD-1042\"]\n}\n```\n\nMercately construye el ejemplo que ve Meta reemplazando cada variable: `Hola [Ana], tu pedido [ORD-1042] va en camino`. Estos valores **solo sirven para la revisión**; los valores reales se indican al enviar el mensaje (`template_params`).\n\nSi el texto no tiene variables, `body_examples` debe omitirse o ir vacío.\n\n#### Qué se guarda y qué ves en `GET`\n\nAl ser aprobada, Mercately guarda internamente el `text` con cada `{{n}}` convertido en `*` y escapa los `*` literales como `\\*`. Por eso, en una plantilla `accepted`, `text` se ve así: `Hola *, tu pedido * va en camino`.\n\nPara no tener que interpretar eso, las respuestas incluyen **`body`**: el mismo texto con las variables restauradas como `{{1}}`, `{{2}}`… y los asteriscos de formato (`*negrita*`) como los escribiste. **Usa `body` para leer el contenido de una plantilla**; `text` se conserva solo por compatibilidad con el listado existente. En plantillas aún no aprobadas, `body` y `text` coinciden.\n\n### Formato del texto\n\nWhatsApp admite formato con marcas dentro de `text`:\n\n| Marca | Resultado |\n|---|---|\n| `*texto*` | **negrita** |\n| `_texto_` | *cursiva* |\n| `~texto~` | ~~tachado~~ |\n| `` `texto` `` | `monoespaciado` |\n\nEl texto se envía tal cual a Meta, que valida el formato. Evita HTML.\n\n### Encabezado (header)\n\nUna plantilla tiene **un solo encabezado**:\n\n| `template_type` | Encabezado |\n|---|---|\n| `text` | Opcional: `header_text` (máx. 60, **no admite variables**, sin HTML) |\n| `image` | La imagen indicada en `media_url` |\n| `video` | El video indicado en `media_url` |\n| `document` | El PDF indicado en `media_url` |\n\n`header_text` no se permite junto a `image`, `video` o `document`.\n\n### Imágenes, video y documentos\n\nPara incrustar un archivo en la plantilla indica su URL en `media_url`. Mercately lo **descarga**, lo sube al proveedor de WhatsApp y usa esa referencia como ejemplo de cabecera en la revisión de Meta.\n\n| Tipo | Formato | Tamaño máximo |\n|---|---|---|\n| `image` | JPG, PNG | 5 MB |\n| `video` | MP4 | 16 MB |\n| `document` | PDF | 40 MB |\n\nRequisitos de la URL:\n\n- Debe ser `https` (puerto 443), sin usuario ni contraseña, y accesible públicamente **sin autenticación**.\n- El tipo se valida por el **contenido real del archivo**, no por la extensión ni por el `Content-Type`.\n- Se siguen hasta 3 redirecciones, cada una debe ser `https` y pública.\n- Por seguridad se rechazan direcciones privadas, locales o de infraestructura interna.\n- La descarga tiene tiempos de espera cortos: el servidor debe responder en pocos segundos.\n\nEl archivo **no se almacena** en Mercately: se usa solo durante la creación.\n\n### Botones\n\nUna plantilla puede llevar **botones de respuesta rápida** o **botones de llamado a la acción**, pero **no ambos a la vez**. No envíes `interactive_action`: se deduce de los botones (`quick_reply` o `call_to_action`) y, si lo envías, se rechaza.\n\nCada botón es un objeto con `type` en **mayúsculas** y un `text` de **máx. 20 caracteres**. Los textos no pueden repetirse (sin distinguir mayúsculas). Un botón solo admite los campos de su tipo; cualquier otro se rechaza con `unknown_field`.\n\n| `type` | Campos | Límite |\n|---|---|---|\n| `QUICK_REPLY` | `text` | Hasta 3 botones |\n| `URL` | `text`, `url`, `example` (solo si la URL es dinámica) | Hasta 1 por plantilla |\n| `PHONE_NUMBER` | `text`, `phone_number` | Hasta 1 por plantilla |\n\nLos botones `URL` y `PHONE_NUMBER` pueden combinarse entre sí (máx. 2 en total). No se pueden mezclar con `QUICK_REPLY`.\n\n#### Teléfono\n\n`phone_number` va en formato internacional con `+` y sin espacios: `+573001234567`.\n\n#### URL estática y dinámica\n\n- **Estática**: una URL completa `http(s)://…`, sin variables y **sin** `example`.\n- **Dinámica**: la URL **termina en `{{1}}`** (la única variable permitida, y solo al final). Se completa al enviar el mensaje. Exige `example` con **una URL completa de muestra** que empiece igual que la parte fija:\n\n```json\n{\n  \"type\": \"URL\",\n  \"text\": \"Rastrear pedido\",\n  \"url\": \"https://tienda.com/track/{{1}}\",\n  \"example\": [\"https://tienda.com/track/ORD-1042\"]\n}\n```\n\n`example` también puede enviarse como texto simple. La URL admite hasta 2000 caracteres.\n\n### Carrusel\n\nUn carrusel es un mensaje principal (`text`) con **2 a 10 tarjetas** deslizables. Se crea con `template_type: \"carousel\"`.\n\n| Campo | Obligatorio | Descripción |\n|---|---|---|\n| `text` / `body_examples` | Sí | Mensaje principal sobre las tarjetas, con las mismas reglas de variables que cualquier cuerpo |\n| `cards_media_type` | Sí | `image` o `video`: es el mismo tipo en **todas** las tarjetas |\n| `cards` | Sí | Lista de 2 a 10 tarjetas |\n\nCada tarjeta es un objeto con estos campos (cualquier otro se rechaza con `unknown_field`):\n\n| Campo de la tarjeta | Obligatorio | Descripción |\n|---|---|---|\n| `body` | Sí | Texto de la tarjeta, máx. **160** caracteres, con las mismas reglas de variables (`{{1}}`, `{{2}}`…, correlativas y sin empezar ni terminar en variable) |\n| `body_examples` | Si el `body` tiene variables | Un ejemplo por variable de **esa** tarjeta |\n| `media_url` | Sí | URL `https` del archivo de la tarjeta (mismas reglas, formatos y tamaños que los archivos) |\n| `buttons` | Sí | **1 o 2** botones (`QUICK_REPLY`, `URL` o `PHONE_NUMBER`), texto de hasta **25** caracteres |\n\nReglas del conjunto:\n- Todas las tarjetas deben tener **los mismos tipos de botón en el mismo orden** (si la primera lleva `URL`, todas llevan `URL`); los textos y las URL pueden diferir. Si no, `cards[n].buttons / mismatch`.\n- En un carrusel los botones pueden mezclarse (por ejemplo `QUICK_REPLY` + `URL`), a diferencia de una plantilla normal.\n- El carrusel no admite `header_text`, `media_url` ni `buttons` en el nivel principal.\n- Los errores indican la tarjeta: `cards[1].body`, `cards[0].media_url`, `cards[2].buttons[0].text`…\n\n```json\n{\n  \"name\": \"coleccion_octubre\", \"language\": \"spanish\", \"category\": \"MARKETING\", \"template_type\": \"carousel\",\n  \"text\": \"Hola {{1}}, mira nuestra colección\", \"body_examples\": [\"Ana\"],\n  \"cards_media_type\": \"image\",\n  \"cards\": [\n    { \"body\": \"Camisa azul\", \"media_url\": \"https://cdn.mitienda.com/azul.png\",\n      \"buttons\": [{ \"type\": \"URL\", \"text\": \"Comprar\", \"url\": \"https://tienda.com/azul\" }] },\n    { \"body\": \"Pantalón {{1}} nuevo\", \"body_examples\": [\"rojo\"], \"media_url\": \"https://cdn.mitienda.com/rojo.png\",\n      \"buttons\": [{ \"type\": \"URL\", \"text\": \"Comprar\", \"url\": \"https://tienda.com/rojo\" }] }\n  ]\n}\n```\n\n### Oferta limitada\n\nUna **oferta limitada** es una plantilla de marketing con un encabezado de oferta (por ejemplo «Solo hoy»), un botón para ir a la tienda y, opcionalmente, una cuenta regresiva con un código de cupón.\n\nRequisitos: `category: \"MARKETING\"`, `template_type` `image` o `video` (con su `media_url`) y el objeto `offer`. **No** se envía `buttons`: la oferta define los suyos.\n\n| Campo de `offer` | Obligatorio | Descripción |\n|---|---|---|\n| `title` | Sí | Título de la oferta, máx. **16** caracteres |\n| `url` | Sí | Botón `{ \"text\", \"url\", \"example\" }`, con las mismas reglas que un botón `URL` (estática o dinámica con `{{1}}` al final y `example`) |\n| `expires_in_minutes` | No | Duración de la oferta en minutos desde el envío, entero ≥ 1. Activa la cuenta regresiva |\n| `code` | Si hay `expires_in_minutes` | Código de cupón de ejemplo que se copia con el botón. No se permite sin expiración |\n| `code_button_text` | No | Texto del botón de copiar (máx. 25). Por defecto «Copiar código de oferta» / «Copy offer code» |\n\n```json\n{\n  \"name\": \"oferta_viernes\", \"language\": \"spanish\", \"category\": \"MARKETING\", \"template_type\": \"image\",\n  \"media_url\": \"https://cdn.mitienda.com/oferta.png\",\n  \"text\": \"Hola {{1}}, solo por hoy tenemos un descuento para ti\", \"body_examples\": [\"Ana\"],\n  \"offer\": {\n    \"title\": \"Solo hoy\",\n    \"url\": { \"text\": \"Comprar\", \"url\": \"https://tienda.com/oferta\" },\n    \"expires_in_minutes\": 120,\n    \"code\": \"VIP10\"\n  }\n}\n```\n\n> `expires_in_minutes` se cuenta desde el momento en que Mercately envía la plantilla al proveedor.\n\n### Plantillas de autenticación (código OTP)\n\nCon `category: \"AUTHENTICATION\"` la plantilla sirve para enviar códigos de verificación. **Mercately genera el texto y el botón**, igual que la pantalla de creación: no envíes `text`, `body_examples`, `header_text`, `media_url`, `buttons`, `offer` ni `cards` (se rechazan con `not_allowed`).\n\n| Campo | Obligatorio | Descripción |\n|---|---|---|\n| `name`, `language`, `category` | Sí | `language`: `spanish` o `english` |\n| `template_type` | No | Si se envía, debe ser `text` |\n| `code_example` | No | Código de muestra que aparece en el texto (por defecto `123456`), máx. 30 |\n| `add_security_recommendation` | No | `true` agrega «Por tu seguridad, no lo compartas.» (en inglés: «For your security, do not share this code.») |\n| `code_expiry_minutes` | No | Entero de 1 a 90. Agrega «Este código caduca en N minutos.» (en inglés: «This code expires in N minutes.») |\n\nEl texto resultante en español, con ambas opciones, es:\n\n```\nTu código de verificación es: 123456\nPor tu seguridad, no lo compartas.\nEste código caduca en 10 minutos.\n```\n\ny el botón es **Copiar código** (`Copy code` en inglés), de tipo `OTP / COPY_CODE`. Puedes leer ambos en la respuesta (`body` y `buttons`).\n\n```json\n{ \"name\": \"codigo_login\", \"language\": \"spanish\", \"category\": \"AUTHENTICATION\",\n  \"add_security_recommendation\": true, \"code_expiry_minutes\": 10 }\n```\n\n### Cuentas con varios números de WhatsApp\n\nSi la cuenta tiene varios números, cada plantilla se crea para **uno** de ellos.\n\n1. Consulta los disponibles: `GET /retailers/api/v1/whatsapp_templates/integrations`. Devuelve los activos con `id`, `platform`, `name`, `phone_number` y `status`.\n2. Envía el `id` elegido como `integration_id` al crear la plantilla. La plataforma se deduce sola.\n\n```json\n{ \"integrations\": [\n  { \"id\": \"int-1\", \"platform\": \"whatsapp_gupshup_messages\", \"name\": \"Ventas\", \"phone_number\": \"+573001234567\", \"status\": \"active\" },\n  { \"id\": \"int-2\", \"platform\": \"whatsapp_qr_messages\", \"name\": \"QR\", \"status\": \"active\" }\n] }\n```\n\nLa lista también incluye la línea QR para que pueda usarse como `integration_id` en\n`POST /retailers/api/v1/whatsapp/send_open_message` (mensajes libres). Una integración QR **no**\npuede alojar plantillas: al crear una plantilla, la API la rechaza con `not_active`.\n\n- Si solo hay **un** número activo, `integration_id` es opcional y se usa ese.\n- Si hay **varios** y no lo envías, la API responde `422 integration_id / required` y lista los ids disponibles.\n- En cuentas con un solo número, `integration_id` **no aplica** y se rechaza con `not_applicable`.\n- Una plantilla pertenece al número con el que se creó: no se comparte entre números.\n\n### Ciclo de vida de una plantilla\n\n```\nPOST → submitted → accepted        (Meta la aprobó: ya se puede usar para enviar)\n                 → rejected        (Meta la rechazó: ver `reason`)\naccepted ↔ disabled\n```\n\n| `status` | Significado |\n|---|---|\n| `pending` | Creada, aún sin enviar a Meta |\n| `submitted` | Enviada a Meta, a la espera de aprobación |\n| `accepted` | Aprobada. Aparece en el listado y se puede usar en `send_notification_by_id` con su `internal_id` |\n| `rejected` | Rechazada. El motivo está en `reason` |\n| `disabled` | Desactivada |\n| `deleted` | Eliminada |\n\nPara saber cuándo se aprueba, consulta periódicamente `GET /whatsapp_templates/:id` (por ejemplo cada minuto; Meta suele resolver en minutos u horas).\n\n### Respuestas\n\n**Éxito (`201`)**\n\n```json\n{\n  \"template\": {\n    \"id\": 1234,\n    \"internal_id\": \"7f3f0c1e-1f6b-4a43-9a25-0d1a5f0f0a11\",\n    \"name\": \"order_update\",\n    \"status\": \"submitted\",\n    \"category\": \"UTILITY\",\n    \"language\": \"spanish\",\n    \"template_type\": \"text\",\n    \"text\": \"Hola {{1}}, tu pedido {{2}} va en camino\",\n    \"body\": \"Hola {{1}}, tu pedido {{2}} va en camino\",\n    \"header_text\": \"Tu pedido\",\n    \"reason\": null,\n    \"created_at\": \"2026-10-07T12:40:37.636Z\"\n  }\n}\n```\n\n`id` es estable desde el primer momento. `internal_id` es el identificador de Meta/proveedor y puede ser `null` mientras la plantilla está `pending`.\n\n**Error**\n\n```json\n{\n  \"message\": \"Template could not be created\",\n  \"errors\": [\n    { \"field\": \"text\", \"code\": \"variables_not_sequential\", \"detail\": \"variables must be sequential starting at {{1}}\" }\n  ]\n}\n```\n\nCuando Meta rechaza la plantilla se responde `422` con `code: provider_rejected`, el motivo en `detail` y la plantilla guardada en `template` (con `status: rejected`).\n\n### Recetas\n\n#### Solo texto con variables y encabezado\n\n```bash\ncurl -X POST https://app.mercately.com/retailers/api/v1/whatsapp_templates \\\n  -H \"Api-Key: $API_KEY\" -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"order_update\", \"language\": \"spanish\", \"category\": \"UTILITY\", \"template_type\": \"text\",\n    \"header_text\": \"Tu pedido\",\n    \"text\": \"Hola {{1}}, tu pedido {{2}} va en camino\",\n    \"body_examples\": [\"Ana\", \"ORD-1042\"]\n  }'\n```\n\n#### Plantilla con imagen\n\n```bash\ncurl -X POST https://app.mercately.com/retailers/api/v1/whatsapp_templates \\\n  -H \"Api-Key: $API_KEY\" -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"promo_octubre\", \"language\": \"spanish\", \"category\": \"MARKETING\", \"template_type\": \"image\",\n    \"media_url\": \"https://cdn.mitienda.com/promos/octubre.png\",\n    \"text\": \"Hola {{1}}, tenemos una promo para ti: *20% de descuento* hasta el viernes\",\n    \"body_examples\": [\"Ana\"]\n  }'\n```\n\n#### Plantilla con documento PDF\n\n```bash\ncurl -X POST https://app.mercately.com/retailers/api/v1/whatsapp_templates \\\n  -H \"Api-Key: $API_KEY\" -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"catalogo_2026\", \"language\": \"spanish\", \"category\": \"MARKETING\", \"template_type\": \"document\",\n    \"media_url\": \"https://cdn.mitienda.com/catalogo.pdf\",\n    \"text\": \"Hola, aquí tienes nuestro catálogo actualizado\"\n  }'\n```\n\n#### Quick replies\n\n```bash\ncurl -X POST https://app.mercately.com/retailers/api/v1/whatsapp_templates \\\n  -H \"Api-Key: $API_KEY\" -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"confirmar_cita\", \"language\": \"spanish\", \"category\": \"UTILITY\", \"template_type\": \"text\",\n    \"text\": \"Hola {{1}}, ¿confirmas tu cita del {{2}}?\",\n    \"body_examples\": [\"Ana\", \"viernes 10 de octubre\"],\n    \"buttons\": [\n      { \"type\": \"QUICK_REPLY\", \"text\": \"Sí, confirmo\" },\n      { \"type\": \"QUICK_REPLY\", \"text\": \"Reprogramar\" }\n    ]\n  }'\n```\n\n#### Imagen con URL dinámica y botón de llamada\n\n```bash\ncurl -X POST https://app.mercately.com/retailers/api/v1/whatsapp_templates \\\n  -H \"Api-Key: $API_KEY\" -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"pedido_enviado\", \"language\": \"spanish\", \"category\": \"UTILITY\", \"template_type\": \"image\",\n    \"media_url\": \"https://cdn.mitienda.com/envio.png\",\n    \"text\": \"Hola {{1}}, tu pedido salió hoy\",\n    \"body_examples\": [\"Ana\"],\n    \"integration_id\": \"int-1\",\n    \"buttons\": [\n      { \"type\": \"URL\", \"text\": \"Rastrear\", \"url\": \"https://tienda.com/track/{{1}}\",\n        \"example\": [\"https://tienda.com/track/ORD-1042\"] },\n      { \"type\": \"PHONE_NUMBER\", \"text\": \"Llámanos\", \"phone_number\": \"+573001234567\" }\n    ]\n  }'\n```\n\n#### Consultar el estado\n\n```bash\ncurl https://app.mercately.com/retailers/api/v1/whatsapp_templates/7f3f0c1e-1f6b-4a43-9a25-0d1a5f0f0a11 \\\n  -H \"Api-Key: $API_KEY\"\n```\n\n### Campos aún no soportados\n\nEstos campos se **rechazan** con `422` y `code: field_not_supported` (no se ignoran en silencio): `interactive_action` (se deduce de `buttons`) y `footer`. Además, `template_type: location` responde `not_supported_yet`: la creación de plantillas de ubicación aún no está disponible por API.\n\n### Catálogo de errores\n\n| HTTP | `field` | `code` | Qué hacer |\n|---|---|---|---|\n| 422 | cualquiera | `required` | Falta un campo obligatorio |\n| 422 | `name` | `invalid`, `too_long` | El nombre debe tener letras o números y máx. 512 caracteres |\n| 422 | `name` | (mensaje del modelo) | Ya existe una plantilla con ese nombre |\n| 422 | `language` / `category` / `template_type` | `invalid` | Usa uno de los valores permitidos |\n| 422 | `template_type` | `not_supported_yet` | `location` aún no está disponible por API |\n| 422 | `text` | `too_long` | Máx. 1024 caracteres sin contar variables |\n| 422 | `text` | `variables_invalid` | Usa `{{1}}`, `{{2}}`… (solo enteros) |\n| 422 | `text` | `variables_repeated` | No repitas una variable |\n| 422 | `text` | `variables_not_sequential` | Numera desde `{{1}}` sin saltos |\n| 422 | `text` | `variable_at_edge` | El texto no puede empezar ni terminar con variable |\n| 422 | `body_examples` | `mismatch` | Un ejemplo no vacío por variable |\n| 422 | `body_examples` | `unexpected` | Quita los ejemplos si no hay variables |\n| 422 | `header_text` | `too_long`, `invalid`, `not_allowed` | Máx. 60, sin HTML, solo en `text` |\n| 422 | `media_url` | `required`, `not_allowed` | Obligatoria en image/video/document; no en text |\n| 422 | `media_url` | `invalid_url` | Usa una URL `https` válida, sin credenciales |\n| 422 | `media_url` | `blocked_host` | La URL debe apuntar a un servidor público |\n| 422 | `media_url` | `too_many_redirects` | Reduce las redirecciones |\n| 413 | `media_url` | `file_too_large` | El archivo supera el máximo de su tipo |\n| 415 | `media_url` | `unsupported_media_type` | Formato no permitido para ese tipo |\n| 502 | `media_url` | `download_failed` | No se pudo descargar el archivo; revisa que sea público |\n| 504 | `media_url` | `download_timeout` | El servidor del archivo tardó demasiado |\n| 422 | `team_id` | `invalid` | El equipo no pertenece al retailer |\n| 422 | `buttons` | `invalid` | Debe ser una lista de objetos |\n| 422 | `buttons` | `mixed_types` | No mezcles `QUICK_REPLY` con `URL`/`PHONE_NUMBER` |\n| 422 | `buttons` | `too_many` | Máx. 3 quick replies o 2 botones de llamado a la acción |\n| 422 | `buttons` | `duplicate_type` | Solo un botón `URL` y uno `PHONE_NUMBER` |\n| 422 | `buttons` | `duplicate_text` | Los textos de los botones deben ser únicos |\n| 422 | `buttons[n]` | `unknown_field` | El botón trae un campo que no corresponde a su tipo |\n| 422 | `buttons[n].type` | `invalid` | `QUICK_REPLY`, `URL` o `PHONE_NUMBER` en mayúsculas |\n| 422 | `buttons[n].text` | `required`, `too_long` | Obligatorio, máx. 20 caracteres |\n| 422 | `buttons[n].url` | `required`, `invalid`, `too_long` | URL `http(s)` válida; `{{1}}` solo al final; máx. 2000 |\n| 422 | `buttons[n].example` | `mismatch`, `not_allowed` | La URL dinámica exige un ejemplo completo; la estática no lleva `example` |\n| 422 | `buttons[n].phone_number` | `invalid` | Formato internacional, p. ej. `+573001234567` |\n| 422 | `cards` | `required`, `invalid`, `too_few`, `too_many` | Un carrusel necesita de 2 a 10 tarjetas (lista de objetos) |\n| 422 | `cards[n]` | `unknown_field` | La tarjeta trae un campo no permitido (solo `body`, `body_examples`, `media_url`, `buttons`) |\n| 422 | `cards[n].body` / `.body_examples` | (reglas de variables) | Mismas reglas que el cuerpo, con máx. 160 caracteres |\n| 422 | `cards[n].media_url` | `required` | Toda tarjeta lleva su archivo (también `download_failed`, `unsupported_media_type`, `file_too_large`… indicando la tarjeta) |\n| 422 | `cards[n].buttons` | `required`, `too_many`, `mismatch` | 1 o 2 botones, con los mismos tipos que la primera tarjeta |\n| 422 | `cards_media_type` | `required`, `invalid`, `not_allowed` | `image` o `video`, solo en carruseles |\n| 422 | `offer` | `requires_marketing`, `not_allowed`, `invalid`, `unknown_field` | La oferta es solo de marketing, no va con carrusel y es un objeto con sus claves |\n| 422 | `template_type` | `invalid_for_offer` | Una oferta necesita `image` o `video` |\n| 422 | `offer.title` | `required`, `too_long` | Obligatorio, máx. 16 caracteres |\n| 422 | `offer.url`… | (reglas de botón URL) | Se reporta como `offer.url.text`, `offer.url.url`, `offer.url.example` |\n| 422 | `offer.expires_in_minutes` | `invalid` | Entero de al menos 1 |\n| 422 | `offer.code` | `required`, `too_long`, `not_allowed` | Obligatorio si la oferta expira; no se permite sin expiración |\n| 422 | `offer.code_button_text` | `too_long`, `not_allowed` | Máx. 25 y solo con expiración |\n| 422 | `text`, `buttons`, `media_url`… | `not_allowed` | En `AUTHENTICATION` esos campos los genera Mercately |\n| 422 | `code_expiry_minutes` | `invalid` | Entero de 1 a 90 |\n| 422 | `code_example` | `invalid`, `too_long` | Texto no vacío, máx. 30 |\n| 422 | `add_security_recommendation` | `invalid` | `true` o `false` |\n| 422 | `integration_id` | `required` | Hay varios números activos: elige uno |\n| 422 | `integration_id` | `not_found`, `not_active` | No existe o no está activo para plantillas |\n| 422 | `integration_id` | `unavailable` | No hay ningún número activo |\n| 422 | `integration_id` / `integration_platform` | `not_applicable`, `mismatch` | La cuenta tiene un solo número, o la plataforma no coincide |\n| 502 | `integrations` | `integrations_unavailable` | No se pudieron consultar los números; reintenta\n| 422 | cualquiera | `field_not_supported` | Campo aún no disponible |\n| 422 | `template` | `provider_rejected` | Meta/proveedor rechazó la plantilla; ver `detail` |\n",
        "operationId": "createWhatsappTemplate",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "name",
                  "language",
                  "category"
                ],
                "properties": {
                  "name": {
                    "type": "string",
                    "maxLength": 512,
                    "description": "Se normaliza (minúsculas, espacios a `_`, solo `a-z`, `0-9`, `_`). Único por retailer.",
                    "example": "order_update"
                  },
                  "language": {
                    "type": "string",
                    "enum": [
                      "spanish",
                      "english",
                      "es_ES",
                      "en_US"
                    ]
                  },
                  "category": {
                    "type": "string",
                    "enum": [
                      "MARKETING",
                      "UTILITY",
                      "AUTHENTICATION"
                    ]
                  },
                  "template_type": {
                    "type": "string",
                    "enum": [
                      "text",
                      "image",
                      "video",
                      "document",
                      "carousel"
                    ],
                    "description": "Obligatorio salvo en `AUTHENTICATION`."
                  },
                  "text": {
                    "type": "string",
                    "description": "Cuerpo del mensaje, máx. 1024 caracteres sin contar variables. Obligatorio salvo en `AUTHENTICATION`.",
                    "example": "Hola {{1}}, tu pedido {{2}} va en camino"
                  },
                  "body_examples": {
                    "type": "array",
                    "items": {
                      "type": "string"
                    },
                    "description": "Un valor de ejemplo por variable, en orden. Obligatorio si `text` tiene variables.",
                    "example": [
                      "Ana",
                      "ORD-1042"
                    ]
                  },
                  "header_text": {
                    "type": "string",
                    "maxLength": 60,
                    "description": "Solo con `template_type` `text`."
                  },
                  "media_url": {
                    "type": "string",
                    "format": "uri",
                    "description": "URL `https` pública del archivo. Obligatoria en `image`, `video` y `document`."
                  },
                  "buttons": {
                    "type": "array",
                    "description": "`QUICK_REPLY` (hasta 3) o `URL` / `PHONE_NUMBER` (hasta 1 de cada uno). No se mezclan los dos grupos.\n",
                    "items": {
                      "type": "object",
                      "required": [
                        "type",
                        "text"
                      ],
                      "properties": {
                        "type": {
                          "type": "string",
                          "enum": [
                            "QUICK_REPLY",
                            "URL",
                            "PHONE_NUMBER"
                          ]
                        },
                        "text": {
                          "type": "string",
                          "maxLength": 20
                        },
                        "url": {
                          "type": "string",
                          "description": "URL estática, o dinámica terminada en `{{1}}`."
                        },
                        "example": {
                          "type": "array",
                          "items": {
                            "type": "string"
                          },
                          "description": "URL completa de muestra. Solo con URL dinámica."
                        },
                        "phone_number": {
                          "type": "string",
                          "example": "+573001234567"
                        }
                      }
                    }
                  },
                  "offer": {
                    "type": "object",
                    "description": "Oferta limitada. Solo `MARKETING` con `template_type` `image` o `video`; no se envía `buttons`.",
                    "required": [
                      "title",
                      "url"
                    ],
                    "properties": {
                      "title": {
                        "type": "string",
                        "maxLength": 16
                      },
                      "url": {
                        "type": "object",
                        "required": [
                          "text",
                          "url"
                        ],
                        "properties": {
                          "text": {
                            "type": "string"
                          },
                          "url": {
                            "type": "string"
                          },
                          "example": {
                            "type": "array",
                            "items": {
                              "type": "string"
                            }
                          }
                        }
                      },
                      "expires_in_minutes": {
                        "type": "integer",
                        "minimum": 1
                      },
                      "code": {
                        "type": "string",
                        "description": "Obligatorio si hay `expires_in_minutes`."
                      },
                      "code_button_text": {
                        "type": "string",
                        "maxLength": 25
                      }
                    }
                  },
                  "cards_media_type": {
                    "type": "string",
                    "enum": [
                      "image",
                      "video"
                    ],
                    "description": "Solo en `carousel`."
                  },
                  "cards": {
                    "type": "array",
                    "minItems": 2,
                    "maxItems": 10,
                    "description": "Solo en `carousel`. Todas las tarjetas llevan los mismos tipos de botón en el mismo orden.",
                    "items": {
                      "type": "object",
                      "required": [
                        "body",
                        "media_url",
                        "buttons"
                      ],
                      "properties": {
                        "body": {
                          "type": "string",
                          "maxLength": 160
                        },
                        "body_examples": {
                          "type": "array",
                          "items": {
                            "type": "string"
                          }
                        },
                        "media_url": {
                          "type": "string",
                          "format": "uri"
                        },
                        "buttons": {
                          "type": "array",
                          "minItems": 1,
                          "maxItems": 2,
                          "items": {
                            "type": "object"
                          }
                        }
                      }
                    }
                  },
                  "add_security_recommendation": {
                    "type": "boolean",
                    "description": "Solo en `AUTHENTICATION`."
                  },
                  "code_expiry_minutes": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 90,
                    "description": "Solo en `AUTHENTICATION`."
                  },
                  "code_example": {
                    "type": "string",
                    "maxLength": 30,
                    "description": "Solo en `AUTHENTICATION`. Por defecto `123456`."
                  },
                  "team_id": {
                    "type": "integer",
                    "description": "Equipo del retailer al que se asigna la plantilla."
                  },
                  "integration_id": {
                    "type": "string",
                    "description": "Número de WhatsApp con el que se crea. Obligatorio si hay más de uno activo (ver `GET .../integrations`)."
                  },
                  "integration_platform": {
                    "type": "string",
                    "description": "Solo para confirmar la plataforma de `integration_id`; se deduce sola."
                  }
                }
              },
              "examples": {
                "text": {
                  "summary": "Texto con variables y encabezado",
                  "value": {
                    "name": "order_update",
                    "language": "spanish",
                    "category": "UTILITY",
                    "template_type": "text",
                    "header_text": "Tu pedido",
                    "text": "Hola {{1}}, tu pedido {{2}} va en camino",
                    "body_examples": [
                      "Ana",
                      "ORD-1042"
                    ]
                  }
                },
                "image_buttons": {
                  "summary": "Imagen con URL dinámica y botón de llamada",
                  "value": {
                    "name": "pedido_enviado",
                    "language": "spanish",
                    "category": "UTILITY",
                    "template_type": "image",
                    "media_url": "https://cdn.mitienda.com/envio.png",
                    "text": "Hola {{1}}, tu pedido salió hoy",
                    "body_examples": [
                      "Ana"
                    ],
                    "integration_id": "int-1",
                    "buttons": [
                      {
                        "type": "URL",
                        "text": "Rastrear",
                        "url": "https://tienda.com/track/{{1}}",
                        "example": [
                          "https://tienda.com/track/ORD-1042"
                        ]
                      },
                      {
                        "type": "PHONE_NUMBER",
                        "text": "Llámanos",
                        "phone_number": "+573001234567"
                      }
                    ]
                  }
                },
                "carousel": {
                  "summary": "Carrusel",
                  "value": {
                    "name": "coleccion_octubre",
                    "language": "spanish",
                    "category": "MARKETING",
                    "template_type": "carousel",
                    "text": "Hola {{1}}, mira nuestra colección",
                    "body_examples": [
                      "Ana"
                    ],
                    "cards_media_type": "image",
                    "cards": [
                      {
                        "body": "Camisa azul",
                        "media_url": "https://cdn.mitienda.com/azul.png",
                        "buttons": [
                          {
                            "type": "URL",
                            "text": "Comprar",
                            "url": "https://tienda.com/azul"
                          }
                        ]
                      },
                      {
                        "body": "Pantalón {{1}} nuevo",
                        "body_examples": [
                          "rojo"
                        ],
                        "media_url": "https://cdn.mitienda.com/rojo.png",
                        "buttons": [
                          {
                            "type": "URL",
                            "text": "Comprar",
                            "url": "https://tienda.com/rojo"
                          }
                        ]
                      }
                    ]
                  }
                },
                "offer": {
                  "summary": "Oferta limitada",
                  "value": {
                    "name": "oferta_viernes",
                    "language": "spanish",
                    "category": "MARKETING",
                    "template_type": "image",
                    "media_url": "https://cdn.mitienda.com/oferta.png",
                    "text": "Hola {{1}}, solo por hoy tenemos un descuento para ti",
                    "body_examples": [
                      "Ana"
                    ],
                    "offer": {
                      "title": "Solo hoy",
                      "url": {
                        "text": "Comprar",
                        "url": "https://tienda.com/oferta"
                      },
                      "expires_in_minutes": 120,
                      "code": "VIP10"
                    }
                  }
                },
                "authentication": {
                  "summary": "Autenticación (código OTP)",
                  "value": {
                    "name": "codigo_login",
                    "language": "spanish",
                    "category": "AUTHENTICATION",
                    "add_security_recommendation": true,
                    "code_expiry_minutes": 10
                  }
                }
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Plantilla creada y enviada a Meta",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "template": {
                      "$ref": "#/components/schemas/template"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Falta el header `Api-Key`"
          },
          "404": {
            "description": "La `Api-Key` es desconocida"
          },
          "413": {
            "description": "El archivo de `media_url` supera el máximo de su tipo (`file_too_large`)"
          },
          "415": {
            "description": "Formato no permitido para ese tipo de media (`unsupported_media_type`)"
          },
          "422": {
            "description": "Validación fallida. `errors[].code` indica la causa (`required`, `invalid`, `variables_not_sequential`,\n`integration_id / required`, `field_not_supported`…). Si Meta rechaza la plantilla, `code` es\n`provider_rejected` y `template` trae la plantilla con `status: rejected`.\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/template_error"
                }
              }
            }
          },
          "502": {
            "description": "No se pudo descargar el archivo de `media_url` (`download_failed`)"
          },
          "504": {
            "description": "El servidor del archivo tardó demasiado (`download_timeout`)"
          }
        }
      }
    },
    "/retailers/api/v1/whatsapp_templates/integrations": {
      "get": {
        "tags": [
          "WhatsApp Templates"
        ],
        "summary": "List the WhatsApp numbers available",
        "description": "Devuelve los números de WhatsApp activos del retailer. Es útil en cuentas con **varios números**:\nel `id` elegido se envía como `integration_id` al crear una plantilla o al enviar un mensaje libre con\n`POST /retailers/api/v1/whatsapp/send_open_message`.\n\nLa lista incluye la línea **QR**, que sirve para mensajes libres pero **no** puede alojar plantillas;\nal crear una plantilla con una integración QR la API responde con `not_active`.\n",
        "operationId": "listWhatsappTemplateIntegrations",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "integrations": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string",
                            "example": "int-1"
                          },
                          "platform": {
                            "type": "string",
                            "example": "whatsapp_gupshup_messages"
                          },
                          "name": {
                            "type": "string",
                            "example": "Ventas"
                          },
                          "phone_number": {
                            "type": "string",
                            "example": "+573001234567"
                          },
                          "status": {
                            "type": "string",
                            "example": "active"
                          }
                        }
                      },
                      "example": [
                        {
                          "id": "int-1",
                          "platform": "whatsapp_gupshup_messages",
                          "name": "Ventas",
                          "phone_number": "+573001234567",
                          "status": "active"
                        },
                        {
                          "id": "int-2",
                          "platform": "whatsapp_qr_messages",
                          "name": "QR",
                          "status": "active"
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Falta el header `Api-Key`"
          },
          "404": {
            "description": "La `Api-Key` es desconocida"
          },
          "502": {
            "description": "No se pudieron consultar los números; reintenta"
          }
        }
      }
    },
    "/retailers/api/v1/whatsapp_templates/{id}": {
      "get": {
        "tags": [
          "WhatsApp Templates"
        ],
        "summary": "Get a WhatsApp template",
        "description": "Consulta una plantilla en **cualquier** estado (`pending`, `submitted`, `accepted`, `rejected`, `disabled`, `deleted`).\nÚsalo para saber cuándo Meta aprobó o rechazó una plantilla creada por API.\n",
        "operationId": "getWhatsappTemplate",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "El `id` numérico o el `internal_id` de la plantilla.",
            "schema": {
              "type": "string"
            },
            "examples": {
              "numeric": {
                "value": "1234"
              },
              "internal_id": {
                "value": "7f3f0c1e-1f6b-4a43-9a25-0d1a5f0f0a11"
              }
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "template": {
                      "$ref": "#/components/schemas/template"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Falta el header `Api-Key`"
          },
          "404": {
            "description": "La `Api-Key` es desconocida o la plantilla no existe",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Resource not found"
                    },
                    "errors": {
                      "type": "array",
                      "items": {}
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/flows": {
      "get": {
        "tags": [
          "Flows"
        ],
        "summary": "Get all flows",
        "description": "Obtén todos los flows",
        "operationId": "flows",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Busca la página específica de flows",
            "schema": {
              "type": "number"
            }
          },
          {
            "name": "results_per_page",
            "in": "query",
            "description": "Selecciona el número de flows que serán visualizados por página",
            "schema": {
              "type": "number"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/get_flows"
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/retailers/api/v1/flow_deactivation": {
      "post": {
        "tags": [
          "Flows"
        ],
        "summary": "Deactivate flows by platform",
        "description": "Desactiva los flows activos del customer para una plataforma. Si el customer tiene más de una integración para esa plataforma, `chat_id` es obligatorio para identificar la conversación a desactivar; con una sola integración se resuelve automáticamente.",
        "operationId": "flow_deactivation",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "customer_id": {
                    "type": "string",
                    "example": "d126hhh",
                    "description": "ID del customer (web_id). Requerido si no se proporciona customer_phone"
                  },
                  "customer_phone": {
                    "type": "string",
                    "example": "+573201548587",
                    "description": "Teléfono del customer (formato internacional con +). Requerido si no se proporciona customer_id"
                  },
                  "platform": {
                    "type": "string",
                    "enum": [
                      "whatsapp",
                      "messenger",
                      "instagram"
                    ],
                    "example": "whatsapp",
                    "description": "Plataforma sobre la cual se realizará la búsqueda para desactivar flows específicos para el customer. Valores permitidos: 'whatsapp', 'messenger' o 'instagram'"
                  },
                  "chat_id": {
                    "type": "string",
                    "example": "6ab18f514477dd0bcd313ab5",
                    "description": "ID de la conversación en el inbox. Obligatorio cuando el customer tiene más de una integración para la plataforma."
                  }
                },
                "required": [
                  "platform"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/deactivate_flows"
                }
              }
            }
          },
          "400": {
            "description": "Bad Request (parámetros inválidos o falta `chat_id` con varias integraciones)"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Customer not found, o Chat not found"
          }
        }
      }
    },
    "/retailers/api/v1/flow_pre_activation": {
      "post": {
        "tags": [
          "Flows"
        ],
        "summary": "Pre-activate flow by platform",
        "description": "Pre-activa un flow en específico para un customer y plataforma específica, siempre y cuando el flow esté activo, tenga un paso inicial configurado y la plataforma para dicho flow esté activa. Esta operación solo está habilitada para flows con versión 2. Si deseas usar un flow con versión 1, debes hacer upgrade del mismo.",
        "operationId": "flow_pre_activation",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "customer_id": {
                    "type": "string",
                    "example": "d126hhh",
                    "description": "ID del customer (web_id). Opcional si se envía customer_phone; se requiere al menos uno de los dos."
                  },
                  "customer_phone": {
                    "type": "string",
                    "example": "+573201548587",
                    "description": "Teléfono del customer (formato internacional con +). Opcional si se envía customer_id; se requiere al menos uno de los dos."
                  },
                  "flow_id": {
                    "type": "string",
                    "example": "d82ijd8",
                    "description": "Id del flow"
                  },
                  "platform": {
                    "type": "string",
                    "example": "whatsapp",
                    "description": "Plataforma sobre la cual se realizará la búsqueda para pre-activar un flow específico para el customer. Sólo se permiten los valores de 'whatsapp', 'messenger' o 'instagram'"
                  },
                  "platform_retailer_id": {
                    "type": "string",
                    "example": "6aa831f6f3c34b7e791c9b96",
                    "description": "Identificador de la integración (el `id` de GET /retailers/api/v1/integrations). Obligatorio cuando el retailer tiene varias integraciones de la plataforma."
                  }
                },
                "required": [
                  "flow_id",
                  "platform"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/pre_activate_flow"
                }
              }
            }
          },
          "400": {
            "description": "Bad Request"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not Found"
          }
        }
      }
    },
    "/retailers/api/v1/stats": {
      "get": {
        "tags": [
          "Analítica"
        ],
        "summary": "Estadísticas de leads por canal",
        "description": "Obtiene el conteo y métricas de los leads generados agrupados por canal dentro de un rango de fechas. Si no se especifican las fechas, retorna los datos del último mes.",
        "operationId": "getLeadsStats",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "start_date",
            "in": "query",
            "required": false,
            "description": "Fecha de inicio del reporte (Formato YYYY-MM-DD). Por defecto se calcula como el inicio del último mes.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-06-01"
            }
          },
          {
            "name": "end_date",
            "in": "query",
            "required": false,
            "description": "Fecha de fin del reporte (Formato YYYY-MM-DD). Por defecto corresponde a la fecha actual.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-07-01"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Estadísticas de leads obtenidas exitosamente.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "start_date": {
                      "type": "string",
                      "example": "2026-06-01"
                    },
                    "end_date": {
                      "type": "string",
                      "example": "2026-07-01"
                    },
                    "total_leads": {
                      "type": "integer",
                      "example": 30
                    },
                    "by_platform": {
                      "type": "object",
                      "description": "Desglose de los leads generados clasificados por cada plataforma/canal.",
                      "properties": {
                        "whatsapp": {
                          "type": "integer",
                          "example": 5
                        },
                        "instagram": {
                          "type": "integer",
                          "example": 1
                        },
                        "messenger": {
                          "type": "integer",
                          "example": 2
                        },
                        "no_channel": {
                          "type": "integer",
                          "example": 22
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Solicitud incorrecta (parámetros inválidos o formato de fecha erróneo).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "error"
                    },
                    "message": {
                      "type": "string",
                      "example": "El formato de fecha provisto en start_date es inválido."
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/stats/funnel_stats": {
      "get": {
        "tags": [
          "Analítica"
        ],
        "summary": "Estadísticas de oportunidades por embudo (Funnel)",
        "description": "Obtiene las métricas de conversión pasadas por las distintas etapas del embudo de ventas. Si no se especifican las fechas, retorna los datos del último mes.",
        "operationId": "getFunnelStats",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "start_date",
            "in": "query",
            "required": false,
            "description": "Fecha de inicio para evaluar el embudo (Formato YYYY-MM-DD). Por defecto se calcula como el inicio del último mes.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-06-01"
            }
          },
          {
            "name": "end_date",
            "in": "query",
            "required": false,
            "description": "Fecha de fin para evaluar el embudo (Formato YYYY-MM-DD). Por defecto corresponde a la fecha actual.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-07-01"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Métricas del embudo obtenidas exitosamente.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "start_date": {
                      "type": "string",
                      "example": "2026-06-01"
                    },
                    "end_date": {
                      "type": "string",
                      "example": "2026-07-01"
                    },
                    "funnels": {
                      "type": "array",
                      "description": "Lista de embudos de venta disponibles con sus respectivas etapas.",
                      "items": {
                        "type": "object",
                        "properties": {
                          "id": {
                            "type": "string",
                            "description": "Identificador único del embudo.",
                            "example": "1dcb040ecbcbe33-e0e3-47dc-ae23-db4013174384"
                          },
                          "name": {
                            "type": "string",
                            "example": "Enbudo 1"
                          },
                          "total_opportunities": {
                            "type": "integer",
                            "example": 2
                          },
                          "by_stage": {
                            "type": "array",
                            "description": "Desglose del rendimiento por cada etapa del embudo.",
                            "items": {
                              "type": "object",
                              "properties": {
                                "step_id": {
                                  "type": "string",
                                  "description": "Identificador único de la etapa.",
                                  "example": "1afea89142a5ab0-d76e-44a7-b4d5-bd322dba1548"
                                },
                                "name": {
                                  "type": "string",
                                  "example": "Etapa 1"
                                },
                                "type_step": {
                                  "type": "string",
                                  "example": "step"
                                },
                                "position": {
                                  "type": "integer",
                                  "example": 1
                                },
                                "count": {
                                  "type": "integer",
                                  "example": 2
                                },
                                "amount": {
                                  "type": "number",
                                  "format": "float",
                                  "example": 378
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Solicitud incorrecta (parámetros inválidos o formato de fecha erróneo).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "error"
                    },
                    "message": {
                      "type": "string",
                      "example": "El formato de fecha provisto en start_date es inválido."
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/stats/response_time_by_agent": {
      "get": {
        "tags": [
          "Analítica"
        ],
        "summary": "Tiempos de respuesta por agente",
        "description": "Obtiene las métricas y promedios de tiempos de respuesta agrupados por cada agente de soporte/ventas. Si no se especifican las fechas, retorna los datos del último mes.",
        "operationId": "getAgentResponseTimeStats",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "start_date",
            "in": "query",
            "required": false,
            "description": "Fecha de inicio del reporte (Formato YYYY-MM-DD). Por defecto se calcula como el inicio del último mes.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-06-01"
            }
          },
          {
            "name": "end_date",
            "in": "query",
            "required": false,
            "description": "Fecha de fin del reporte (Formato YYYY-MM-DD). Por defecto corresponde a la fecha actual.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-07-01"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Tiempos de respuesta por agente obtenidos exitosamente.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "response_time_by_agent": {
                      "type": "array",
                      "description": "Listado de agentes con sus respectivos promedios de tiempo de respuesta (en minutos o segundos según la configuración).",
                      "items": {
                        "type": "object",
                        "properties": {
                          "first_name": {
                            "type": "string",
                            "example": "Jhon"
                          },
                          "last_name": {
                            "type": "string",
                            "example": "Doe"
                          },
                          "tiempo_promedio_primera_respuesta": {
                            "type": [
                              "number",
                              "null"
                            ],
                            "format": "float",
                            "example": 110.25
                          },
                          "tiempo_promedio_primera_respuesta_mia": {
                            "type": [
                              "number",
                              "null"
                            ],
                            "format": "float",
                            "example": null
                          },
                          "tiempo_promedio_respuesta_promedio": {
                            "type": [
                              "number",
                              "null"
                            ],
                            "format": "float",
                            "example": 123.7
                          },
                          "tiempo_respuesta_horario_laboral": {
                            "type": [
                              "number",
                              "null"
                            ],
                            "format": "float",
                            "example": null
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Solicitud incorrecta (parámetros inválidos o formato de fecha erróneo).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "error"
                    },
                    "message": {
                      "type": "string",
                      "example": "El formato de fecha provisto en start_date es inválido."
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/ads_stats/leads_by_source": {
      "get": {
        "tags": [
          "Analítica"
        ],
        "summary": "Leads por fuente de origen (Ads)",
        "description": "Obtiene el conteo de leads generados agrupados por su fuente de atribución (pago, orgánico, etc.) dentro de un rango de fechas. Si no se especifican las fechas, retorna los datos del último mes.",
        "operationId": "getAdsLeadsBySource",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "start_date",
            "in": "query",
            "required": false,
            "description": "Fecha de inicio del reporte (Formato YYYY-MM-DD). Por defecto se calcula como el inicio del último mes.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2025-07-01"
            }
          },
          {
            "name": "end_date",
            "in": "query",
            "required": false,
            "description": "Fecha de fin del reporte (Formato YYYY-MM-DD). Por defecto corresponde a la fecha actual.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-08-01"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Estadísticas de leads por origen obtenidas exitosamente.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "start_date": {
                      "type": "string",
                      "example": "2025-07-01"
                    },
                    "end_date": {
                      "type": "string",
                      "example": "2026-08-01"
                    },
                    "total_leads": {
                      "type": "integer",
                      "example": 30
                    },
                    "by_source": {
                      "type": "object",
                      "description": "Desglose de leads agrupados por su fuente de atribución.",
                      "properties": {
                        "paid_social": {
                          "type": "integer",
                          "example": 0
                        },
                        "organic": {
                          "type": "integer",
                          "example": 0
                        },
                        "no_attribution": {
                          "type": "integer",
                          "example": 0
                        },
                        "no_channel": {
                          "type": "integer",
                          "example": 30
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Solicitud incorrecta (parámetros inválidos o formato de fecha erróneo).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "error"
                    },
                    "message": {
                      "type": "string",
                      "example": "El formato de fecha provisto en start_date es inválido."
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/ads_stats/campaign_funnel": {
      "get": {
        "tags": [
          "Analítica"
        ],
        "summary": "Embudo por campaña de anuncios (Ads)",
        "description": "Obtiene las métricas del embudo desglosadas por cada campaña publicitaria dentro de un rango de fechas. Si no se especifican las fechas, retorna los datos del último mes.",
        "operationId": "getAdsCampaignFunnelStats",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "start_date",
            "in": "query",
            "required": false,
            "description": "Fecha de inicio del reporte (Formato YYYY-MM-DD). Por defecto se calcula como el inicio del último mes.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-05-01"
            }
          },
          {
            "name": "end_date",
            "in": "query",
            "required": false,
            "description": "Fecha de fin del reporte (Formato YYYY-MM-DD). Por defecto corresponde a la fecha actual.",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-06-01"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Métricas del embudo por campaña obtenidas exitosamente.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "start_date": {
                      "type": "string",
                      "example": "2026-06-01"
                    },
                    "end_date": {
                      "type": "string",
                      "example": "2026-07-01"
                    },
                    "total_leads": {
                      "type": "integer",
                      "example": 30
                    },
                    "by_campaing": {
                      "type": "object",
                      "description": "Métricas desglosadas por campaña (las claves representan el nombre de cada campaña).",
                      "additionalProperties": {
                        "type": "object",
                        "description": "Conteos de prospectos por cada etapa del embudo.",
                        "additionalProperties": {
                          "type": "integer"
                        }
                      },
                      "example": {
                        "Campaña 1": {
                          "etapa_1": 5,
                          "etapa_2": 23,
                          "ganados": 3
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Solicitud incorrecta (parámetros inválidos o formato de fecha erróneo).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "error"
                    },
                    "message": {
                      "type": "string",
                      "example": "El formato de fecha provisto en start_date es inválido."
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/retailers/api/v1/stats/leads_report": {
      "get": {
        "tags": [
          "Analítica"
        ],
        "summary": "Reporte detallado de leads",
        "description": "Obtiene el listado paginado y detallado de leads registrados con métricas de agente, canal de origen, embudo, IA (MIA) y conversación.",
        "operationId": "getLeadsReportStats",
        "security": [
          {
            "api-key": []
          }
        ],
        "parameters": [
          {
            "name": "date",
            "in": "query",
            "required": false,
            "description": "Fecha específica para filtrar el reporte de leads (Formato YYYY-MM-DD).",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-06-03"
            }
          },
          {
            "name": "page",
            "in": "query",
            "required": false,
            "description": "Número de página. Paginación fija de 10 clientes por página (no se acepta per_page; el tamaño de página no es configurable).",
            "schema": {
              "type": "integer",
              "example": 1
            }
          },
          {
            "name": "agent_id",
            "in": "query",
            "required": false,
            "description": "Identificador único del agente para filtrar los leads.",
            "schema": {
              "type": "integer",
              "example": 1204
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Reporte de leads obtenido exitosamente.",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "date": {
                      "type": "string",
                      "example": "2026-08-01"
                    },
                    "pagination": {
                      "type": "object",
                      "properties": {
                        "page": {
                          "type": "integer",
                          "example": 1
                        },
                        "per_page": {
                          "type": "integer",
                          "example": 10
                        },
                        "total": {
                          "type": "integer",
                          "example": 84
                        },
                        "total_pages": {
                          "type": "integer",
                          "example": 9
                        }
                      }
                    },
                    "leads": {
                      "type": "array",
                      "description": "Lista detallada de leads del periodo.",
                      "items": {
                        "type": "object",
                        "properties": {
                          "customer": {
                            "type": "object",
                            "properties": {
                              "web_id": {
                                "type": "string",
                                "example": "483abc920"
                              },
                              "phone": {
                                "type": "string",
                                "example": "+593991234567"
                              },
                              "id_number": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "example": "1712345678"
                              },
                              "first_name": {
                                "type": "string",
                                "example": "Ana"
                              },
                              "last_name": {
                                "type": "string",
                                "example": "Ramírez"
                              },
                              "whatsapp_name": {
                                "type": "string",
                                "example": "Ana R."
                              },
                              "email": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "example": "ana@gmail.com"
                              },
                              "city": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "example": "Quito"
                              },
                              "created_at": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2026-05-15T20:10:35-05:00"
                              }
                            }
                          },
                          "agent": {
                            "type": [
                              "object",
                              "null"
                            ],
                            "properties": {
                              "id": {
                                "type": "integer",
                                "example": 1204
                              },
                              "name": {
                                "type": "string",
                                "example": "Sonia Patiño"
                              },
                              "email": {
                                "type": "string",
                                "example": "sonia@mastermoto.com"
                              },
                              "assigned_at": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2026-05-15T20:14:02-05:00"
                              },
                              "assignment_reason": {
                                "type": "string",
                                "example": "automatic"
                              }
                            }
                          },
                          "agent_metrics": {
                            "type": "object",
                            "properties": {
                              "avg_response_after_mia_seconds": {
                                "type": [
                                  "integer",
                                  "null"
                                ],
                                "example": 1218
                              },
                              "responded_after_assignment": {
                                "type": [
                                  "boolean",
                                  "null"
                                ],
                                "example": true
                              },
                              "first_agent_message_at": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "format": "date-time",
                                "example": "2026-05-15T20:34:20-05:00"
                              },
                              "last_agent_message_at": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "format": "date-time",
                                "example": "2026-05-16T09:45:12-05:00"
                              },
                              "agent_management_seconds": {
                                "type": [
                                  "integer",
                                  "null"
                                ],
                                "example": 47452
                              }
                            }
                          },
                          "lead_source": {
                            "type": "object",
                            "properties": {
                              "channel": {
                                "type": "string",
                                "example": "ctwa"
                              },
                              "utm_source": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "example": null
                              },
                              "campaign_name": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "example": "MM || Tráfico Abril 26"
                              },
                              "ad_name": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "example": "Sukida Joy 150 - Crédito Fácil"
                              },
                              "ad_headline": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "example": "Estrena tu Sukida Joy 150 con $99 de entrada"
                              }
                            }
                          },
                          "funnel": {
                            "type": "array",
                            "items": {
                              "type": "object",
                              "properties": {
                                "funnel_name": {
                                  "type": "string",
                                  "example": "Ventas Motos"
                                },
                                "step_name": {
                                  "type": "string",
                                  "example": "Oportunidad / Lead"
                                },
                                "step_changed_at": {
                                  "type": "string",
                                  "format": "date-time",
                                  "example": "2026-05-16T10:02:44-05:00"
                                },
                                "deal_created_at": {
                                  "type": "string",
                                  "format": "date-time",
                                  "example": "2026-05-15T20:11:08-05:00"
                                }
                              }
                            }
                          },
                          "mia": {
                            "type": "object",
                            "properties": {
                              "first_mia_message_at": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "format": "date-time",
                                "example": "2026-05-15T20:10:41-05:00"
                              },
                              "last_mia_message_at": {
                                "type": [
                                  "string",
                                  "null"
                                ],
                                "format": "date-time",
                                "example": "2026-05-15T20:31:55-05:00"
                              },
                              "mia_management_seconds": {
                                "type": [
                                  "integer",
                                  "null"
                                ],
                                "example": 1274
                              },
                              "buy_intention": {
                                "type": "boolean",
                                "example": true
                              },
                              "human_help": {
                                "type": "boolean",
                                "example": false
                              },
                              "active": {
                                "type": "boolean",
                                "example": false
                              }
                            }
                          },
                          "conversation_metrics": {
                            "type": "object",
                            "properties": {
                              "customer_messages_count": {
                                "type": "integer",
                                "example": 18
                              },
                              "mia_messages_count": {
                                "type": "integer",
                                "example": 9
                              },
                              "agent_messages_count": {
                                "type": "integer",
                                "example": 14
                              },
                              "total_messages_count": {
                                "type": "integer",
                                "example": 41
                              },
                              "first_customer_message_at": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2026-05-15T20:10:35-05:00"
                              },
                              "last_message_at": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2026-05-16T09:45:12-05:00"
                              }
                            }
                          },
                          "tags": {
                            "type": "array",
                            "items": {
                              "type": "string"
                            },
                            "example": [
                              "MODELO ESPECÍFICO",
                              "ASESORÍA",
                              "CRÉDITO"
                            ]
                          },
                          "custom_fields": {
                            "type": "object",
                            "additionalProperties": {
                              "type": [
                                "string",
                                "null"
                              ]
                            },
                            "example": {
                              "modelo_interes_final": "Pulsar 125 N",
                              "marca_interes": "Bajaj",
                              "forma_pago": "Crédito"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Solicitud incorrecta (parámetros inválidos o formato de fecha erróneo).",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "status": {
                      "type": "string",
                      "example": "error"
                    },
                    "message": {
                      "type": "string",
                      "example": "El formato de fecha provisto en date es inválido."
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/orders": {
      "servers": [
        {
          "url": "https://mercately.shop",
          "description": "Shops API Production server"
        }
      ],
      "get": {
        "tags": [
          "Orders"
        ],
        "summary": "Orders",
        "description": "Obtén los datos de tus órdenes",
        "operationId": "orders",
        "parameters": [
          {
            "name": "created_from",
            "in": "query",
            "description": "busca las órdenes creadas desde una fecha en especifico",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2023-05-17"
            }
          },
          {
            "name": "created_to",
            "in": "query",
            "description": "busca las órdenes creadas hasta una fecha en especifico",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2023-05-17"
            }
          },
          {
            "name": "page",
            "in": "query",
            "description": "busca la pagina específica de órdenes",
            "schema": {
              "type": "integer",
              "default": 1
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "orders": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "web_id": {
                            "type": "string"
                          },
                          "status": {
                            "type": "string"
                          },
                          "subtotal": {
                            "type": "string"
                          },
                          "tax_amount": {
                            "type": "string"
                          },
                          "total": {
                            "type": "string"
                          },
                          "shipping_value": {
                            "type": "string"
                          },
                          "notes": {
                            "type": "string"
                          },
                          "sales_channel": {
                            "type": "string"
                          },
                          "created_at": {
                            "type": "string",
                            "format": "date-time"
                          },
                          "archived": {
                            "type": "boolean"
                          },
                          "customer": {
                            "type": "object",
                            "properties": {
                              "first_name": {
                                "type": "string"
                              },
                              "last_name": {
                                "type": "string"
                              },
                              "email": {
                                "type": "string"
                              },
                              "phone": {
                                "type": "string"
                              },
                              "address": {
                                "type": "string"
                              },
                              "city": {
                                "type": "string"
                              },
                              "state": {
                                "type": "string"
                              },
                              "country_id": {
                                "type": "string"
                              },
                              "zip_code": {
                                "type": "string"
                              },
                              "id_number": {
                                "type": "string"
                              },
                              "document_label": {
                                "type": "string"
                              },
                              "web_id": {
                                "type": "string"
                              }
                            }
                          },
                          "order_items": {
                            "type": "array",
                            "items": {
                              "type": "object",
                              "properties": {
                                "quantity": {
                                  "type": "integer"
                                },
                                "unit_price": {
                                  "type": "string"
                                },
                                "total": {
                                  "type": "string"
                                },
                                "title": {
                                  "type": "string"
                                },
                                "sku": {
                                  "type": "string"
                                },
                                "image_url": {
                                  "oneOf": [
                                    {
                                      "type": "string",
                                      "description": "Cadena vacía cuando no hay producto asociado",
                                      "example": ""
                                    },
                                    {
                                      "type": "object",
                                      "description": "Objeto vacío cuando hay producto pero sin imágenes, o objeto con url y fileName cuando hay imágenes",
                                      "properties": {
                                        "url": {
                                          "type": "string"
                                        },
                                        "fileName": {
                                          "type": "string"
                                        }
                                      }
                                    }
                                  ]
                                }
                              }
                            }
                          }
                        }
                      }
                    },
                    "total_pages": {
                      "type": "integer"
                    }
                  }
                },
                "examples": {
                  "response": {
                    "value": {
                      "orders": [
                        {
                          "web_id": "EzLGaK0YZa",
                          "status": "pending",
                          "subtotal": "200.0",
                          "tax_amount": "0.0",
                          "total": "200.0",
                          "shipping_value": "0.0",
                          "notes": "",
                          "sales_channel": null,
                          "created_at": "2023-05-17T01:42:57.624Z",
                          "archived": false,
                          "customer": {
                            "first_name": "Henry ",
                            "last_name": "Tonato",
                            "email": "henry@gmail.com",
                            "phone": "593995141472",
                            "address": "",
                            "city": "",
                            "state": "",
                            "country_id": "EC",
                            "zip_code": "",
                            "id_number": "",
                            "document_label": null,
                            "web_id": "EleO7OTOer"
                          },
                          "order_items": [
                            {
                              "quantity": 1,
                              "unit_price": "200.0",
                              "total": "200.0",
                              "title": "Mensajes",
                              "sku": "Col.2556",
                              "image_url": {}
                            }
                          ]
                        }
                      ],
                      "total_pages": 1
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad Request"
          },
          "401": {
            "description": "Unauthorized"
          }
        }
      },
      "post": {
        "tags": [
          "Orders"
        ],
        "summary": "Create Order",
        "description": "Crea una nueva órden, puedes enviar el número de teléfono o email del cliente si ya esta creado en mercately, si no existe, creará el cliente.",
        "operationId": "createOrder",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "title": "Order",
                "properties": {
                  "order": {
                    "type": "object",
                    "properties": {
                      "sales_channel": {
                        "type": "string"
                      },
                      "notes": {
                        "type": "string"
                      },
                      "address": {
                        "type": "string"
                      },
                      "city": {
                        "type": "string"
                      },
                      "state": {
                        "type": "string"
                      },
                      "zip_code": {
                        "type": "string"
                      },
                      "delivery_method": {
                        "type": "string",
                        "enum": [
                          "send_order",
                          "store_pickup"
                        ]
                      },
                      "status": {
                        "type": "string",
                        "enum": [
                          "pending",
                          "canceled",
                          "success"
                        ]
                      },
                      "shipping_value": {
                        "type": "number",
                        "format": "float"
                      },
                      "customer_attributes": {
                        "type": "object",
                        "properties": {
                          "first_name": {
                            "type": "string"
                          },
                          "last_name": {
                            "type": "string"
                          },
                          "email": {
                            "type": "string"
                          },
                          "phone": {
                            "type": "string"
                          }
                        }
                      },
                      "order_items_attributes": {
                        "type": "array",
                        "items": {
                          "type": "object",
                          "properties": {
                            "product_id": {
                              "type": "string"
                            },
                            "quantity": {
                              "type": "integer"
                            },
                            "unit_price": {
                              "type": "number",
                              "format": "float"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "201": {
            "description": "Created",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string"
                    },
                    "order": {
                      "type": "object",
                      "properties": {
                        "web_id": {
                          "type": "string"
                        },
                        "status": {
                          "type": "string"
                        },
                        "subtotal": {
                          "type": "string"
                        },
                        "tax_amount": {
                          "type": "string"
                        },
                        "total": {
                          "type": "string"
                        },
                        "shipping_value": {
                          "type": "string"
                        },
                        "sales_channel": {
                          "type": "string"
                        },
                        "notes": {
                          "type": "string"
                        },
                        "created_at": {
                          "type": "string",
                          "format": "date-time"
                        },
                        "archived": {
                          "type": "boolean"
                        },
                        "customer": {
                          "type": "object"
                        },
                        "order_items": {
                          "type": "array",
                          "items": {
                            "type": "object"
                          }
                        }
                      }
                    }
                  }
                },
                "examples": {
                  "response": {
                    "value": {
                      "message": "Órden creada con éxito",
                      "order": {
                        "web_id": "aAKpT9laN5",
                        "status": "pending",
                        "subtotal": "400.0",
                        "tax_amount": "0.0",
                        "total": "405.0",
                        "shipping_value": "5.0",
                        "sales_channel": null,
                        "notes": "New notes",
                        "created_at": "2023-06-12T18:26:58.534Z",
                        "archived": false,
                        "customer": {
                          "first_name": "Juan",
                          "last_name": "Campos",
                          "email": "juan@email42.com",
                          "phone": "593996459124",
                          "address": "",
                          "city": "",
                          "state": "",
                          "country_id": "EC",
                          "zip_code": "",
                          "id_number": "",
                          "document_label": "cedula",
                          "web_id": "bReccZpRjO"
                        },
                        "order_items": [
                          {
                            "quantity": 2,
                            "unit_price": "200.0",
                            "total": "400.0",
                            "title": "Mensajes",
                            "sku": "Col.2556",
                            "image_url": {}
                          }
                        ]
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Bad Request"
          },
          "401": {
            "description": "Unauthorized"
          },
          "422": {
            "description": "Unprocessable Entity",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "errors": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/orders/web_id": {
      "servers": [
        {
          "url": "https://mercately.shop",
          "description": "Shops API Production server"
        }
      ],
      "put": {
        "tags": [
          "Orders"
        ],
        "summary": "Order",
        "description": "Actualiza una órden buscada su id",
        "operationId": "updateOrder",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "title": "Order",
                "properties": {
                  "order": {
                    "type": "object",
                    "properties": {
                      "sales_channel": {
                        "type": "string"
                      },
                      "notes": {
                        "type": "string"
                      },
                      "address": {
                        "type": "string"
                      },
                      "city": {
                        "type": "string"
                      },
                      "state": {
                        "type": "string"
                      },
                      "zip_code": {
                        "type": "string"
                      },
                      "delivery_method": {
                        "type": "string",
                        "enum": [
                          "send_order",
                          "store_pickup"
                        ]
                      },
                      "status": {
                        "type": "string",
                        "enum": [
                          "pending",
                          "canceled",
                          "success"
                        ]
                      },
                      "shipping_value": {
                        "type": "number",
                        "format": "float"
                      },
                      "customer_attributes": {
                        "type": "object",
                        "properties": {
                          "first_name": {
                            "type": "string"
                          },
                          "last_name": {
                            "type": "string"
                          },
                          "email": {
                            "type": "string"
                          },
                          "phone": {
                            "type": "string",
                            "description": "Must be in international format, including the international dialing code."
                          }
                        },
                        "required": [
                          "email",
                          "phone"
                        ]
                      },
                      "order_items_attributes": {
                        "type": "array",
                        "items": {
                          "type": "object",
                          "properties": {
                            "product_id": {
                              "type": "string"
                            },
                            "quantity": {
                              "type": "integer"
                            },
                            "unit_price": {
                              "type": "number",
                              "format": "float"
                            }
                          },
                          "required": [
                            "product_id",
                            "quantity"
                          ]
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "string"
                },
                "examples": {
                  "response": {
                    "value": {
                      "message": "Órden actualizada con éxito",
                      "order": {
                        "web_id": "4Bs2mKblN3",
                        "status": "success",
                        "subtotal": "60.0",
                        "tax_amount": "0.0",
                        "total": "65.0",
                        "shipping_value": "5.0",
                        "sales_channel": null,
                        "notes": "New notes",
                        "created_at": "2023-06-13T03:31:06.825Z",
                        "archived": false,
                        "customer": {
                          "first_name": "Henry",
                          "last_name": "Campos",
                          "email": null,
                          "phone": null,
                          "address": null,
                          "city": null,
                          "state": null,
                          "country_id": null,
                          "zip_code": null,
                          "id_number": null,
                          "document_label": null,
                          "web_id": "sVnez19hSa"
                        },
                        "order_items": [
                          {
                            "quantity": 3,
                            "unit_price": "20.0",
                            "total": "60.0",
                            "title": "Mensajes",
                            "sku": "Col.2556",
                            "image_url": {}
                          }
                        ]
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      },
      "delete": {
        "tags": [
          "Orders"
        ],
        "summary": "Orders",
        "description": "Borra una órden",
        "operationId": "deleteOrder",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "string"
                },
                "examples": {
                  "response": {
                    "value": {
                      "message": "Órden borrada con éxito"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/api/v1/products": {
      "servers": [
        {
          "url": "https://mercately.shop",
          "description": "Shops API Production server"
        }
      ],
      "get": {
        "tags": [
          "Products"
        ],
        "summary": "Products",
        "description": "Obtén los datos de tus productos",
        "operationId": "products",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "busca la pagina específica de productos",
            "schema": {
              "type": "integer",
              "default": 1
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "products": {
                      "type": "array",
                      "items": {
                        "type": "object"
                      }
                    },
                    "total_pages": {
                      "type": "integer"
                    }
                  }
                },
                "example": {
                  "products": [
                    {
                      "web_id": "CRasFSldo7",
                      "title": "Camiseta Gráfica Premium",
                      "description": "Camiseta con diseño gráfico exclusivo",
                      "quantity": 85,
                      "price": "39.99",
                      "active": true,
                      "url": null,
                      "sku": "CAM-GRA-010",
                      "wholesale_price": "20.0",
                      "images": [],
                      "subcategory": {
                        "name": "Camisetas",
                        "web_id": "GETPvRKnBD"
                      },
                      "category": {
                        "name": "Ropa",
                        "web_id": "ljsJpi0fTR"
                      },
                      "product_variants": [
                        {
                          "name": "Color",
                          "web_id": "pv123abc",
                          "product_variant_options": [
                            {
                              "name": "Negro",
                              "web_id": "BEYaSU7yTH"
                            },
                            {
                              "name": "Blanco",
                              "web_id": "vftzaNsoI3"
                            }
                          ]
                        },
                        {
                          "name": "Talla",
                          "web_id": "pv456def",
                          "product_variant_options": [
                            {
                              "name": "S",
                              "web_id": "nCbIHF5EGT"
                            },
                            {
                              "name": "M",
                              "web_id": "QboGUaqrOl"
                            }
                          ]
                        }
                      ],
                      "product_variant_combinations": [
                        {
                          "web_id": "xa6d2qprcI",
                          "name": "Negro/S",
                          "price": "45.86",
                          "wholesale_price": "22.94",
                          "sku": "CAM-GRA-010-NEGRO-S",
                          "quantity": 8,
                          "variant_option_web_ids": [
                            "BEYaSU7yTH",
                            "nCbIHF5EGT"
                          ],
                          "image": "",
                          "variant_url": null
                        },
                        {
                          "web_id": "aD8EI424Tx",
                          "name": "Negro/M",
                          "price": "43.60",
                          "wholesale_price": "21.81",
                          "sku": "CAM-GRA-010-NEGRO-M",
                          "quantity": 20,
                          "variant_option_web_ids": [
                            "BEYaSU7yTH",
                            "QboGUaqrOl"
                          ],
                          "image": "",
                          "variant_url": null
                        }
                      ]
                    }
                  ],
                  "total_pages": 4
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          }
        }
      },
      "post": {
        "tags": [
          "Products"
        ],
        "summary": "Create Product",
        "description": "Crea un nuevo producto.  \nEnvía máximo 3 opciones.  \n\n**Ejemplo de `options`:**\n\"options\": [\n  { \"name\": \"Talla\", \"values\": [\"SM\", \"LG\", \"XL\", \"MD\"] },\n  { \"name\": \"Color\", \"values\": [\"Red\", \"Blue\"] }\n]\n    Para las variantes, combina los valores de las opciones.\n\n**Ejemplo de `variants`:**\n\"variants\": [\n  { \"price\": 12, \"wholesale_price\": 10, \"sku\": \"VAR-001\", \"option1\": \"SM\", \"option2\": \"Red\" },\n  { \"price\": 14, \"wholesale_price\": 10, \"sku\": \"VAR-002\", \"option1\": \"LG\", \"option2\": \"Red\" },\n  { \"price\": 25, \"wholesale_price\": 13, \"sku\": \"VAR-003\", \"option1\": \"XL\", \"option2\": \"Blue\" }\n]\n  operationId: createProduct\n",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "product": {
                    "type": "object",
                    "properties": {
                      "title": {
                        "type": "string"
                      },
                      "description": {
                        "type": "string"
                      },
                      "sku": {
                        "type": "string"
                      },
                      "quantity": {
                        "type": "integer"
                      },
                      "active": {
                        "type": "boolean"
                      },
                      "price": {
                        "type": "number"
                      },
                      "subcategory_id": {
                        "type": "string"
                      },
                      "image_urls": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        }
                      },
                      "options": {
                        "type": "array",
                        "description": "Máximo 3 opciones",
                        "items": {
                          "type": "object",
                          "properties": {
                            "name": {
                              "type": "string"
                            },
                            "values": {
                              "type": "array",
                              "items": {
                                "type": "string"
                              }
                            }
                          }
                        }
                      },
                      "variants": {
                        "type": "array",
                        "items": {
                          "type": "object",
                          "properties": {
                            "price": {
                              "type": "number"
                            },
                            "wholesale_price": {
                              "type": "number"
                            },
                            "sku": {
                              "type": "string"
                            },
                            "quantity": {
                              "type": "number"
                            },
                            "image": {
                              "type": "string"
                            },
                            "variant_url": {
                              "type": "string"
                            },
                            "option1": {
                              "type": "string"
                            },
                            "option2": {
                              "type": "string"
                            },
                            "option3": {
                              "type": "string"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                },
                "example": {
                  "message": "Producto creado con éxito",
                  "product": {
                    "web_id": "FzOWVvUwbC",
                    "title": "Product 001",
                    "description": "Product 001",
                    "quantity": 20,
                    "price": "1.5",
                    "active": true,
                    "url": null,
                    "sku": "p004",
                    "wholesale_price": "0.0",
                    "images": [
                      "https://d3a4wxp51vazl1.cloudfront.net/uploads/506/product_attachment/FzOWVvUwbC/qrewrwYdhfNDCqW3hv4MTiwFq.jpg"
                    ],
                    "subcategory": {
                      "name": "Alámbricos",
                      "web_id": "GETPvRKnBD"
                    },
                    "category": {
                      "name": "Tecnología",
                      "web_id": "ljsJpi0fTR"
                    },
                    "product_variants": [
                      {
                        "name": "Talla",
                        "web_id": "AbHj6GqcMF",
                        "product_variant_options": [
                          {
                            "name": "SM",
                            "web_id": "3I6zc3DGMY"
                          },
                          {
                            "name": "LG",
                            "web_id": "57gl2i88SZ"
                          },
                          {
                            "name": "XL",
                            "web_id": "J7PFMLX9wA"
                          }
                        ]
                      },
                      {
                        "name": "Color",
                        "web_id": "vVlmXsA2Bm",
                        "product_variant_options": [
                          {
                            "name": "Azul",
                            "web_id": "Xe9QkMiD1i"
                          },
                          {
                            "name": "Negro",
                            "web_id": "Y8zjQ7BPY4"
                          }
                        ]
                      }
                    ],
                    "product_variant_combinations": [
                      {
                        "web_id": "x0wsCBTIMI",
                        "name": "SM/Azul",
                        "price": "33.0",
                        "wholesale_price": null,
                        "sku": "SKU-EX1",
                        "quantity": 10,
                        "variant_option_web_ids": [
                          "3I6zc3DGMY",
                          "Xe9QkMiD1i"
                        ],
                        "image": "https://dc2p3rqc7bvrd.cloudfront.net/uploads/1/product_variant_combination/x0wsCBTIMI/camisa-del-producto_40x403x.webp",
                        "variant_url": null
                      },
                      {
                        "web_id": "y1xtDUITNJ",
                        "name": "XL/Azul",
                        "price": "33.0",
                        "wholesale_price": null,
                        "sku": "SKU-EX5",
                        "quantity": 10,
                        "variant_option_web_ids": [
                          "J7PFMLX9wA",
                          "Xe9QkMiD1i"
                        ],
                        "image": "",
                        "variant_url": null
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          }
        }
      }
    },
    "/api/v1/products/:id_or_sku": {
      "servers": [
        {
          "url": "https://mercately.shop",
          "description": "Shops API Production server"
        }
      ],
      "get": {
        "tags": [
          "Products"
        ],
        "summary": "Product",
        "description": "Obtén los datos de un producto en especifico buscado su id",
        "operationId": "searchProduct",
        "parameters": [
          {
            "name": "web_id",
            "in": "query",
            "description": "The web_id of the product",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "sku",
            "in": "query",
            "description": "The SKU of the product",
            "required": false,
            "schema": {
              "type": "string"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                },
                "example": {
                  "web_id": "CRasFSldo7",
                  "title": "Camiseta Gráfica Premium",
                  "description": "Camiseta con diseño gráfico exclusivo",
                  "quantity": 85,
                  "price": "39.99",
                  "active": true,
                  "url": null,
                  "sku": "CAM-GRA-010",
                  "wholesale_price": "20.0",
                  "images": [],
                  "subcategory": {
                    "web_id": "GETPvRKnBD",
                    "name": "Camisetas",
                    "description": "",
                    "products_count": 5,
                    "active_products_count": 2
                  },
                  "category": {
                    "web_id": "ljsJpi0fTR",
                    "name": "Ropa",
                    "description": "",
                    "products_count": 11,
                    "active_products_count": 6
                  },
                  "product_variants": [
                    {
                      "name": "Color",
                      "web_id": "pv123abc",
                      "product_variant_options": [
                        {
                          "name": "Negro",
                          "web_id": "BEYaSU7yTH"
                        },
                        {
                          "name": "Blanco",
                          "web_id": "vftzaNsoI3"
                        }
                      ]
                    },
                    {
                      "name": "Talla",
                      "web_id": "pv456def",
                      "product_variant_options": [
                        {
                          "name": "S",
                          "web_id": "nCbIHF5EGT"
                        },
                        {
                          "name": "M",
                          "web_id": "QboGUaqrOl"
                        }
                      ]
                    }
                  ],
                  "product_variant_combinations": [
                    {
                      "web_id": "xa6d2qprcI",
                      "name": "Negro/S",
                      "price": "45.86",
                      "wholesale_price": "22.94",
                      "sku": "CAM-GRA-010-NEGRO-S",
                      "quantity": 8,
                      "variant_option_web_ids": [
                        "BEYaSU7yTH",
                        "nCbIHF5EGT"
                      ],
                      "image": "",
                      "variant_url": null
                    },
                    {
                      "web_id": "aD8EI424Tx",
                      "name": "Negro/M",
                      "price": "43.60",
                      "wholesale_price": "21.81",
                      "sku": "CAM-GRA-010-NEGRO-M",
                      "quantity": 20,
                      "variant_option_web_ids": [
                        "BEYaSU7yTH",
                        "QboGUaqrOl"
                      ],
                      "image": "",
                      "variant_url": null
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/api/v1/products/web_id": {
      "servers": [
        {
          "url": "https://mercately.shop",
          "description": "Shops API Production server"
        }
      ],
      "put": {
        "tags": [
          "Products"
        ],
        "summary": "Product",
        "description": "Actualiza un producto buscado su id.  \nEnvía máximo 3 opciones.\n\n### Comportamiento de actualización parcial\n\nEste endpoint soporta **actualizaciones parciales** (partial updates):\n\n- Si **no envías** los keys `\"options\"` ni `\"variants\"`, las variantes existentes **se preservan**.\n- Si envías `\"options\": []` o `\"variants\": []`, las variantes existentes **también se preservan** (no se eliminan por omisión).\n- Si envías nuevas opciones o variantes, estas se **agregan** a las existentes sin eliminar las anteriores.\n\n### Ejemplos\n\n**Actualizar solo precio y título (preserva variantes):**\n\n{\n  \"product\": {\n    \"title\": \"Nuevo título\",\n    \"price\": 29.99\n  }\n}\n    **Agregar nueva opción sin eliminar existentes:**\n{\n  \"product\": {\n    \"options\": [\n      { \"name\": \"Material\", \"values\": [\"Algodón\", \"Poliéster\"] }\n    ]\n  }\n}\n    **Ejemplo completo de `options`:**\n\"options\": [\n  { \"name\": \"Talla\", \"values\": [\"SM\", \"LG\", \"XL\", \"MD\"] },\n  { \"name\": \"Color\", \"values\": [\"Red\", \"Blue\"] }\n]\n    Para las variantes, combina los valores de las opciones.\n\n**Ejemplo completo de `variants`:**\n\n\"variants\": [\n  { \"price\": 12, \"wholesale_price\": 10, \"sku\": \"VAR-001\", \"option1\": \"SM\", \"option2\": \"Red\" },\n  { \"price\": 14, \"wholesale_price\": 10, \"sku\": \"VAR-002\", \"option1\": \"LG\", \"option2\": \"Red\" },\n  { \"price\": 25, \"wholesale_price\": 13, \"sku\": \"VAR-003\", \"option1\": \"XL\", \"option2\": \"Blue\" }\n]\n    **Agregar nueva combinación sin eliminar existentes:**\n{\n  \"product\": {\n    \"options\": [\n      { \"name\": \"Talla\", \"values\": [\"SM\", \"LG\", \"XL\", \"XXL\"] }\n    ],\n    \"variants\": [\n      { \"option1\": \"XXL\", \"sku\": \"VAR-XXL\", \"price\": 35, \"quantity\": 10 }\n    ]\n  }\n}\n  operationId: updateProduct\n",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "product": {
                    "type": "object",
                    "properties": {
                      "title": {
                        "type": "string"
                      },
                      "description": {
                        "type": "string"
                      },
                      "sku": {
                        "type": "string"
                      },
                      "quantity": {
                        "type": "integer"
                      },
                      "active": {
                        "type": "boolean"
                      },
                      "price": {
                        "type": "number"
                      },
                      "subcategory_id": {
                        "type": "string"
                      },
                      "image_urls": {
                        "type": "array",
                        "items": {
                          "type": "string"
                        }
                      },
                      "options": {
                        "type": "array",
                        "description": "Opciones del producto (ej: Talla, Color). Si se envía, las nuevas opciones se agregan a las existentes.",
                        "items": {
                          "type": "object",
                          "properties": {
                            "name": {
                              "type": "string"
                            },
                            "values": {
                              "type": "array",
                              "items": {
                                "type": "string"
                              }
                            }
                          }
                        }
                      },
                      "variants": {
                        "type": "array",
                        "description": "Combinaciones de variantes. Si se envía, las nuevas combinaciones se agregan a las existentes.",
                        "items": {
                          "type": "object",
                          "properties": {
                            "price": {
                              "type": "number"
                            },
                            "wholesale_price": {
                              "type": "number"
                            },
                            "sku": {
                              "type": "string"
                            },
                            "quantity": {
                              "type": "number"
                            },
                            "image": {
                              "type": "string"
                            },
                            "variant_url": {
                              "type": "string"
                            },
                            "option1": {
                              "type": "string"
                            },
                            "option2": {
                              "type": "string"
                            },
                            "option3": {
                              "type": "string"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                },
                "example": {
                  "message": "Producto actualizado con éxito",
                  "product": {
                    "web_id": "FzOWVvUwbC",
                    "title": "Product 001",
                    "description": "Product 001",
                    "quantity": 20,
                    "price": "1.5",
                    "active": true,
                    "url": null,
                    "sku": "p004",
                    "wholesale_price": "0.0",
                    "images": [
                      "https://d3a4wxp51vazl1.cloudfront.net/uploads/506/product_attachment/FzOWVvUwbC/qrGZwYdhfewrW3hv4MTiwFq.jpg"
                    ],
                    "subcategory": {
                      "name": "Alámbricos",
                      "web_id": "GETPvRKnBD"
                    },
                    "category": {
                      "name": "Tecnología",
                      "web_id": "ljsJpi0fTR"
                    },
                    "product_variants": [
                      {
                        "name": "Talla",
                        "web_id": "AbHj6GqcMF",
                        "product_variant_options": [
                          {
                            "name": "SM",
                            "web_id": "3I6zc3DGMY"
                          },
                          {
                            "name": "LG",
                            "web_id": "57gl2i88SZ"
                          },
                          {
                            "name": "XL",
                            "web_id": "J7PFMLX9wA"
                          }
                        ]
                      },
                      {
                        "name": "Color",
                        "web_id": "vVlmXsA2Bm",
                        "product_variant_options": [
                          {
                            "name": "Azul",
                            "web_id": "Xe9QkMiD1i"
                          },
                          {
                            "name": "Negro",
                            "web_id": "Y8zjQ7BPY4"
                          }
                        ]
                      }
                    ],
                    "product_variant_combinations": [
                      {
                        "web_id": "x0wsCBTIMI",
                        "name": "SM/Azul",
                        "price": "33.0",
                        "wholesale_price": null,
                        "sku": "SKU-EX1",
                        "quantity": 10,
                        "variant_option_web_ids": [
                          "3I6zc3DGMY",
                          "Xe9QkMiD1i"
                        ],
                        "image": "https://dc2p3rqc7bvrd.cloudfront.net/uploads/1/product_variant_combination/x0wsCBTIMI/camisa-del-producto_40x403x.webp",
                        "variant_url": null
                      },
                      {
                        "web_id": "y1xtDUITNJ",
                        "name": "XL/Azul",
                        "price": "33.0",
                        "wholesale_price": null,
                        "sku": "SKU-EX5",
                        "quantity": 10,
                        "variant_option_web_ids": [
                          "J7PFMLX9wA",
                          "Xe9QkMiD1i"
                        ],
                        "image": "",
                        "variant_url": null
                      }
                    ]
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      },
      "delete": {
        "tags": [
          "Products"
        ],
        "summary": "Product",
        "description": "Borra un producto buscado su id",
        "operationId": "deleteProduct",
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                },
                "example": {
                  "message": "Producto eliminado con éxito",
                  "product": {
                    "web_id": "tUCJZrCUs5",
                    "title": "Abrigo borrego",
                    "description": "Abrigo crema con lana de borrego.\r\nTallas: XS, S, M, L, XL, XXL.",
                    "quantity": 41,
                    "price": "8.0",
                    "active": true,
                    "url": null,
                    "sku": "AB.577",
                    "wholesale_price": "6.0",
                    "images": [
                      "https://d3a4wxp51vazl1.cloudfront.net/uploads/506/product_attachment/tUCJZrCUs5/7-01.jpg",
                      "https://d3a4wxp51vazl1.cloudfront.net/uploads/506/product_attachment/tUCJZrCUs5/8-01.jpg",
                      "https://d3a4wxp51vazl1.cloudfront.net/uploads/506/product_attachment/tUCJZrCUs5/9-01.jpg"
                    ],
                    "subcategory": {
                      "name": "Abrigos",
                      "web_id": "EM5FJCF7sY"
                    },
                    "category": {
                      "name": "Abrigos y chaquetas",
                      "web_id": "maFDOHylFB"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Not found"
          }
        }
      }
    },
    "/api/v1/products/product_web_id/variants": {
      "servers": [
        {
          "url": "https://mercately.shop",
          "description": "Shops API Production server"
        }
      ],
      "post": {
        "operationId": "createVariant",
        "tags": [
          "Product Variants"
        ],
        "summary": "Create Variant",
        "description": "Crea una nueva variante (ProductVariantCombination) para un producto existente.\n\n### Creación incremental\n\nEste endpoint permite agregar **una sola variante** a un producto sin afectar las variantes existentes.\n\n**Ideal para integraciones POS** que necesitan agregar SKUs uno por uno sin reenviar todo el catálogo.\n\n### Ejemplo: Crear variante con una opción\n{\n  \"variant\": {\n    \"option1\": \"XXL\",\n    \"price\": 35.00,\n    \"quantity\": 10,\n    \"sku\": \"CAMISETA-XXL\"\n  }\n}\n    ### Ejemplo: Crear variante con múltiples opciones\n{\n  \"variant\": {\n    \"option1\": \"XXL\",\n    \"option2\": \"Azul\",\n    \"price\": 35.00,\n    \"quantity\": 10,\n    \"sku\": \"CAMISETA-XXL-AZUL\"\n  }\n}\n    ### Notas importantes\n- Los valores de `option1`, `option2`, `option3` deben existir en las opciones del producto.\n- Si la combinación ya existe, retorna error `409 Conflict`.\n- Las variantes existentes no se ven afectadas.\n",
        "parameters": [
          {
            "name": "product_web_id",
            "in": "path",
            "required": true,
            "description": "El web_id del producto al que se agregará la variante",
            "schema": {
              "type": "string"
            },
            "example": "FzOWVvUwbC"
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "variant"
                ],
                "properties": {
                  "variant": {
                    "type": "object",
                    "required": [
                      "option1"
                    ],
                    "properties": {
                      "option1": {
                        "type": "string",
                        "description": "Valor de la primera opción (debe existir en el producto)",
                        "example": "XXL"
                      },
                      "option2": {
                        "type": "string",
                        "description": "Valor de la segunda opción (opcional)",
                        "example": "Azul"
                      },
                      "option3": {
                        "type": "string",
                        "description": "Valor de la tercera opción (opcional)",
                        "example": "Algodón"
                      },
                      "price": {
                        "type": "number",
                        "description": "Precio de venta",
                        "example": 35
                      },
                      "wholesale_price": {
                        "type": "number",
                        "description": "Precio mayorista",
                        "example": 28
                      },
                      "quantity": {
                        "type": "integer",
                        "description": "Cantidad en stock",
                        "example": 10
                      },
                      "sku": {
                        "type": "string",
                        "description": "Código SKU único",
                        "example": "CAMISETA-XXL-AZUL"
                      },
                      "selling_without_stock": {
                        "type": "boolean",
                        "description": "Permitir venta sin stock",
                        "example": false
                      },
                      "variant_url": {
                        "type": "string",
                        "description": "URL de la variante",
                        "example": "https://example.com/product?variant=123"
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "201": {
            "description": "Created",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                },
                "example": {
                  "message": "Variante creada con éxito",
                  "variant": {
                    "web_id": "newVariantId",
                    "name": "XXL/Azul",
                    "price": "35.0",
                    "wholesale_price": "28.0",
                    "sku": "CAMISETA-XXL-AZUL",
                    "quantity": 10,
                    "variant_option_web_ids": [
                      "optionWebId1",
                      "optionWebId2"
                    ],
                    "image": "",
                    "variant_url": "https://example.com/product?variant=123"
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "example": {
                  "message": "Unauthorized"
                }
              }
            }
          },
          "404": {
            "description": "Not found",
            "content": {
              "application/json": {
                "example": {
                  "message": "Producto no encontrado"
                }
              }
            }
          },
          "409": {
            "description": "Conflict - Combination already exists",
            "content": {
              "application/json": {
                "example": {
                  "message": "La combinación ya existe",
                  "errors": [
                    "Una variante con el nombre 'XXL/Azul' ya existe para este producto"
                  ]
                }
              }
            }
          },
          "422": {
            "description": "Unprocessable Entity",
            "content": {
              "application/json": {
                "examples": {
                  "invalid_options": {
                    "summary": "Opciones inválidas",
                    "value": {
                      "message": "Opciones inválidas",
                      "errors": [
                        "option1 'XXL' no existe en las opciones del producto"
                      ]
                    }
                  },
                  "validation_error": {
                    "summary": "Error de validación",
                    "value": {
                      "message": "No fue posible crear la variante",
                      "errors": [
                        "Sku Ya está en uso"
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/variants/{web_id}": {
      "servers": [
        {
          "url": "https://mercately.shop",
          "description": "Shops API Production server"
        }
      ],
      "get": {
        "operationId": "getVariant",
        "tags": [
          "Product Variants"
        ],
        "summary": "Get Variant",
        "description": "Obtiene una variante (ProductVariantCombination) por su web_id.\n\n### Consulta individual\n\nEste endpoint retorna **una sola variante** sin traer el producto completo.\n\n**Ideal para integraciones POS** que necesitan verificar el estado de una variante específica.\n",
        "parameters": [
          {
            "name": "web_id",
            "in": "path",
            "required": true,
            "description": "El web_id de la variante a consultar",
            "schema": {
              "type": "string"
            },
            "example": "x0wsCBTIMI"
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                },
                "example": {
                  "variant": {
                    "web_id": "x0wsCBTIMI",
                    "name": "SM/Azul",
                    "price": "100.0",
                    "wholesale_price": "80.0",
                    "sku": "VAR-SM-001",
                    "quantity": 50,
                    "variant_option_web_ids": [
                      "3I6zc3DGMY",
                      "Xe9QkMiD1i"
                    ],
                    "image": "https://example.com/image.webp",
                    "variant_url": "https://example.com/variant"
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "example": {
                  "message": "Unauthorized"
                }
              }
            }
          },
          "404": {
            "description": "Not found",
            "content": {
              "application/json": {
                "example": {
                  "message": "Variante no encontrada"
                }
              }
            }
          }
        }
      },
      "patch": {
        "operationId": "updateVariant",
        "tags": [
          "Product Variants"
        ],
        "summary": "Update Variant",
        "description": "Actualiza una variante (ProductVariantCombination) de forma parcial.\n\n### Actualización parcial\n\nEste endpoint permite actualizar **solo los campos enviados** sin afectar otros atributos de la variante, otras variantes del producto, ni el producto padre.\n\n**Ideal para integraciones POS** que necesitan actualizar precio o stock de una variante específica sin reenviar el producto completo.\n\n### Ejemplo: Actualizar solo el precio\n{\n  \"variant\": {\n    \"price\": 150.00\n  }\n}\n    ### Ejemplo: Actualizar precio y stock\n{\n  \"variant\": {\n    \"price\": 150.00,\n    \"quantity\": 25\n  }\n}\n    ### Ejemplo: Actualizar múltiples atributos\n{\n  \"variant\": {\n    \"price\": 200.00,\n    \"wholesale_price\": 150.00,\n    \"quantity\": 100,\n    \"sku\": \"NEW-SKU-001\",\n    \"selling_without_stock\": true\n  }\n}\n  parameters:\n- name: web_id\n  in: path\n  required: true\n  description: El web_id de la variante a actualizar\n  schema:\n    type: string\n  example: \"x0wsCBTIMI\"\n",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "variant": {
                    "type": "object",
                    "description": "Solo envía los campos que deseas actualizar",
                    "properties": {
                      "price": {
                        "type": "number",
                        "description": "Precio de venta",
                        "example": 150
                      },
                      "wholesale_price": {
                        "type": "number",
                        "description": "Precio mayorista",
                        "example": 120
                      },
                      "quantity": {
                        "type": "integer",
                        "description": "Cantidad en stock",
                        "example": 50
                      },
                      "sku": {
                        "type": "string",
                        "description": "Código SKU único",
                        "example": "VAR-SM-001"
                      },
                      "selling_without_stock": {
                        "type": "boolean",
                        "description": "Permitir venta sin stock",
                        "example": false
                      },
                      "variant_url": {
                        "type": "string",
                        "description": "URL de la variante",
                        "example": "https://example.com/product?variant=123"
                      },
                      "image": {
                        "type": "string",
                        "format": "binary",
                        "description": "Imagen de la variante"
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                },
                "example": {
                  "message": "Variante actualizada con éxito",
                  "variant": {
                    "web_id": "x0wsCBTIMI",
                    "name": "SM/Azul",
                    "price": "150.0",
                    "wholesale_price": "120.0",
                    "sku": "VAR-SM-001",
                    "quantity": 50,
                    "variant_option_web_ids": [
                      "3I6zc3DGMY",
                      "Xe9QkMiD1i"
                    ],
                    "image": "https://dc2p3rqc7bvrd.cloudfront.net/uploads/1/product_variant_combination/x0wsCBTIMI/image.webp",
                    "variant_url": "https://example.com/product?variant=123"
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "example": {
                  "message": "Unauthorized"
                }
              }
            }
          },
          "404": {
            "description": "Not found",
            "content": {
              "application/json": {
                "example": {
                  "message": "Variante no encontrada"
                }
              }
            }
          },
          "422": {
            "description": "Unprocessable Entity",
            "content": {
              "application/json": {
                "example": {
                  "message": "No fue posible actualizar la variante",
                  "errors": [
                    "Sku Ya está en uso"
                  ]
                }
              }
            }
          }
        }
      },
      "delete": {
        "operationId": "deleteVariant",
        "tags": [
          "Product Variants"
        ],
        "summary": "Delete Variant",
        "description": "Elimina una variante (ProductVariantCombination) de forma explícita.\n\n### Borrado inteligente\n\nEste endpoint elimina **solo la variante indicada** sin afectar otras variantes del producto ni el producto padre.\n\n**Comportamiento según integridad:**\n- Si la variante **no tiene** órdenes asociadas → **Hard delete** (eliminación permanente)\n- Si la variante **tiene** órdenes asociadas → **Soft delete** (marca `deleted_at`, preserva historial)\n\n**Ideal para integraciones POS** que necesitan eliminar SKUs descontinuados sin afectar el catálogo completo.\n\n### Notas importantes\n- El producto padre permanece intacto\n- Las demás variantes no se ven afectadas\n- Los `ProductVariant` y `ProductVariantOption` no se eliminan\n- El borrado es **explícito**, nunca por omisión\n",
        "parameters": [
          {
            "name": "web_id",
            "in": "path",
            "required": true,
            "description": "El web_id de la variante a eliminar",
            "schema": {
              "type": "string"
            },
            "example": "x0wsCBTIMI"
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "204": {
            "description": "No Content - Variante eliminada exitosamente"
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "example": {
                  "message": "Unauthorized"
                }
              }
            }
          },
          "404": {
            "description": "Not found",
            "content": {
              "application/json": {
                "example": {
                  "message": "Variante no encontrada"
                }
              }
            }
          },
          "422": {
            "description": "Unprocessable Entity - No se pudo eliminar por restricciones de integridad",
            "content": {
              "application/json": {
                "example": {
                  "message": "No fue posible eliminar la variante",
                  "errors": [
                    "La variante tiene dependencias que impiden su eliminación"
                  ]
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/categories": {
      "servers": [
        {
          "url": "https://mercately.shop",
          "description": "Shops API Production server"
        }
      ],
      "get": {
        "tags": [
          "Categories"
        ],
        "summary": "List Categories",
        "description": "Obtén los datos de tus categorías con sus subcategorías",
        "operationId": "listCategories",
        "parameters": [
          {
            "name": "page",
            "in": "query",
            "description": "Número de página para la paginación",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 1,
              "default": 1
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "categories": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "web_id": {
                            "type": "string",
                            "description": "Identificador único de la categoría",
                            "example": "ljsJpi0fTR"
                          },
                          "name": {
                            "type": "string",
                            "description": "Nombre de la categoría",
                            "example": "Tecnología"
                          },
                          "description": {
                            "type": "string",
                            "description": "Descripción de la categoría",
                            "example": ""
                          },
                          "products_count": {
                            "type": "integer",
                            "description": "Número de productos activos en la categoría",
                            "example": 7
                          },
                          "order": {
                            "type": "integer",
                            "description": "Orden de visualización de la categoría",
                            "example": 1
                          },
                          "subcategories": {
                            "type": "array",
                            "description": "Lista de subcategorías",
                            "items": {
                              "type": "object",
                              "properties": {
                                "web_id": {
                                  "type": "string",
                                  "description": "Identificador único de la subcategoría",
                                  "example": "GETPvRKnBD"
                                },
                                "name": {
                                  "type": "string",
                                  "description": "Nombre de la subcategoría",
                                  "example": "Alámbricos"
                                },
                                "description": {
                                  "type": "string",
                                  "description": "Descripción de la subcategoría",
                                  "example": ""
                                },
                                "products_count": {
                                  "type": "integer",
                                  "description": "Número de productos activos en la subcategoría",
                                  "example": 3
                                },
                                "order": {
                                  "type": "integer",
                                  "description": "Orden de visualización de la subcategoría",
                                  "example": 1
                                }
                              }
                            }
                          }
                        }
                      }
                    },
                    "total_pages": {
                      "type": "integer",
                      "description": "Total de páginas disponibles",
                      "example": 1
                    }
                  }
                },
                "examples": {
                  "response": {
                    "value": {
                      "categories": [
                        {
                          "web_id": "ljsJpi0fTR",
                          "name": "Tecnología",
                          "description": "",
                          "products_count": 7,
                          "order": 1,
                          "subcategories": [
                            {
                              "web_id": "GETPvRKnBD",
                              "name": "Alámbricos",
                              "description": "",
                              "products_count": 3,
                              "order": 1
                            },
                            {
                              "web_id": "8Kncn44rQD",
                              "name": "3 en 1",
                              "description": "",
                              "products_count": 4,
                              "order": 2
                            }
                          ]
                        }
                      ],
                      "total_pages": 1
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Not Found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Resource not found"
                    }
                  }
                }
              }
            }
          }
        }
      },
      "post": {
        "tags": [
          "Categories"
        ],
        "summary": "Create Category",
        "description": "Crea una nueva categoría con sus subcategorías",
        "operationId": "createCategory",
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "category"
                ],
                "properties": {
                  "category": {
                    "type": "object",
                    "required": [
                      "name"
                    ],
                    "properties": {
                      "name": {
                        "type": "string",
                        "description": "Nombre de la categoría (requerido)",
                        "example": "Electrónica"
                      },
                      "description": {
                        "type": "string",
                        "maxLength": 250,
                        "description": "Descripción de la categoría (máximo 250 caracteres)",
                        "example": "Productos electrónicos y dispositivos tecnológicos"
                      },
                      "order": {
                        "type": "integer",
                        "description": "Orden de visualización. Si no se proporciona, se asigna automáticamente",
                        "example": 1
                      },
                      "subcategories_attributes": {
                        "type": "array",
                        "description": "Array de subcategorías a crear",
                        "items": {
                          "type": "object",
                          "required": [
                            "name"
                          ],
                          "properties": {
                            "name": {
                              "type": "string",
                              "description": "Nombre de la subcategoría (requerido)",
                              "example": "Smartphones"
                            },
                            "description": {
                              "type": "string",
                              "description": "Descripción de la subcategoría",
                              "example": "Teléfonos inteligentes y accesorios"
                            },
                            "order": {
                              "type": "integer",
                              "description": "Orden de visualización",
                              "example": 1
                            }
                          }
                        }
                      }
                    }
                  }
                }
              },
              "examples": {
                "create_with_subcategories": {
                  "value": {
                    "category": {
                      "name": "Electrónica",
                      "description": "Productos electrónicos y dispositivos tecnológicos",
                      "order": 1,
                      "subcategories_attributes": [
                        {
                          "name": "Smartphones",
                          "description": "Teléfonos inteligentes y accesorios",
                          "order": 1
                        },
                        {
                          "name": "Laptops",
                          "description": "Computadoras portátiles",
                          "order": 2
                        }
                      ]
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Category created successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "web_id": {
                      "type": "string",
                      "description": "Identificador único de la categoría",
                      "example": "I7ROmS7Jui"
                    },
                    "name": {
                      "type": "string",
                      "description": "Nombre de la categoría",
                      "example": "Electrónica"
                    },
                    "description": {
                      "type": "string",
                      "description": "Descripción de la categoría",
                      "example": "Productos electrónicos y dispositivos tecnológicos"
                    },
                    "products_count": {
                      "type": "integer",
                      "description": "Número de productos activos en la categoría",
                      "example": 0
                    },
                    "order": {
                      "type": "integer",
                      "description": "Orden de visualización de la categoría",
                      "example": 1
                    },
                    "subcategories": {
                      "type": "array",
                      "description": "Lista de subcategorías",
                      "items": {
                        "type": "object",
                        "properties": {
                          "web_id": {
                            "type": "string",
                            "example": "bas9UxSaUq"
                          },
                          "name": {
                            "type": "string",
                            "example": "Smartphones"
                          },
                          "description": {
                            "type": "string",
                            "example": "Teléfonos inteligentes y accesorios"
                          },
                          "products_count": {
                            "type": "integer",
                            "example": 0
                          },
                          "order": {
                            "type": "integer",
                            "example": 1
                          }
                        }
                      }
                    }
                  }
                },
                "examples": {
                  "success": {
                    "value": {
                      "web_id": "I7ROmS7Jui",
                      "name": "Electrónica",
                      "description": "Productos electrónicos y dispositivos tecnológicos",
                      "products_count": 0,
                      "order": 1,
                      "subcategories": [
                        {
                          "web_id": "bas9UxSaUq",
                          "name": "Smartphones",
                          "description": "Teléfonos inteligentes y accesorios",
                          "products_count": 0,
                          "order": 1
                        },
                        {
                          "web_id": "VqpkV7TLd5",
                          "name": "Laptops",
                          "description": "Computadoras portátiles",
                          "products_count": 0,
                          "order": 2
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "errors": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  }
                },
                "examples": {
                  "validation_error": {
                    "value": {
                      "errors": [
                        "Name can't be blank"
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/v1/categories/web_id": {
      "servers": [
        {
          "url": "https://mercately.shop",
          "description": "Shops API Production server"
        }
      ],
      "put": {
        "tags": [
          "Categories"
        ],
        "summary": "Update Category",
        "description": "Actualiza una categoría existente y sus subcategorías. Puedes actualizar, crear o eliminar subcategorías.",
        "operationId": "updateCategory",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Web ID de la categoría",
            "schema": {
              "type": "string",
              "example": "I7ROmS7Jui"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "category"
                ],
                "properties": {
                  "category": {
                    "type": "object",
                    "properties": {
                      "name": {
                        "type": "string",
                        "description": "Nombre de la categoría",
                        "example": "Electrónica"
                      },
                      "description": {
                        "type": "string",
                        "maxLength": 250,
                        "description": "Descripción de la categoría (máximo 250 caracteres)",
                        "example": "Productos electrónicos actualizados"
                      },
                      "order": {
                        "type": "integer",
                        "description": "Orden de visualización",
                        "example": 1
                      },
                      "subcategories_attributes": {
                        "type": "array",
                        "description": "Array de subcategorías. \n- Para actualizar: incluye el campo 'id' con el web_id de la subcategoría\n- Para crear: omite el campo 'id'\n- Para eliminar: incluye el campo 'id' y '_destroy: true'\n",
                        "items": {
                          "type": "object",
                          "properties": {
                            "id": {
                              "type": "string",
                              "description": "Web ID de la subcategoría (requerido para actualizar o eliminar)",
                              "example": "bas9UxSaUq"
                            },
                            "name": {
                              "type": "string",
                              "description": "Nombre de la subcategoría",
                              "example": "Smartphones"
                            },
                            "description": {
                              "type": "string",
                              "description": "Descripción de la subcategoría",
                              "example": "Teléfonos inteligentes actualizados"
                            },
                            "order": {
                              "type": "integer",
                              "description": "Orden de visualización",
                              "example": 1
                            },
                            "_destroy": {
                              "type": "boolean",
                              "description": "Si es true, elimina la subcategoría",
                              "example": false
                            }
                          }
                        }
                      }
                    }
                  }
                }
              },
              "examples": {
                "update_with_subcategories": {
                  "value": {
                    "category": {
                      "name": "Electrónica",
                      "description": "Productos electrónicos actualizados",
                      "order": 1,
                      "subcategories_attributes": [
                        {
                          "web_id": "bas9UxSaUq",
                          "name": "Smartphones",
                          "description": "Teléfonos inteligentes actualizados",
                          "order": 1
                        },
                        {
                          "web_id": "VqpkV7TLd5",
                          "name": "Laptops",
                          "description": "Computadoras portátiles actualizadas",
                          "order": 2
                        }
                      ]
                    }
                  }
                },
                "delete_subcategory": {
                  "value": {
                    "category": {
                      "name": "Electrónica",
                      "subcategories_attributes": [
                        {
                          "id": "bas9UxSaUq",
                          "_destroy": true
                        }
                      ]
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Category updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "web_id": {
                      "type": "string",
                      "description": "Identificador único de la categoría",
                      "example": "I7ROmS7Jui"
                    },
                    "name": {
                      "type": "string",
                      "description": "Nombre de la categoría",
                      "example": "Electrónica"
                    },
                    "description": {
                      "type": "string",
                      "description": "Descripción de la categoría",
                      "example": "Productos electrónicos actualizados"
                    },
                    "products_count": {
                      "type": "integer",
                      "description": "Número de productos activos en la categoría",
                      "example": 7
                    },
                    "order": {
                      "type": "integer",
                      "description": "Orden de visualización de la categoría",
                      "example": 1
                    },
                    "subcategories": {
                      "type": "array",
                      "description": "Lista de subcategorías",
                      "items": {
                        "type": "object",
                        "properties": {
                          "web_id": {
                            "type": "string",
                            "example": "bas9UxSaUq"
                          },
                          "name": {
                            "type": "string",
                            "example": "Smartphones"
                          },
                          "description": {
                            "type": "string",
                            "example": "Teléfonos inteligentes actualizados"
                          },
                          "products_count": {
                            "type": "integer",
                            "example": 3
                          },
                          "order": {
                            "type": "integer",
                            "example": 1
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Category not found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Resource not found"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "errors": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  }
                },
                "examples": {
                  "validation_error": {
                    "value": {
                      "errors": [
                        "Name can't be blank"
                      ]
                    }
                  }
                }
              }
            }
          }
        }
      },
      "patch": {
        "tags": [
          "Categories"
        ],
        "summary": "Update Category (Partial)",
        "description": "Actualiza parcialmente una categoría existente",
        "operationId": "patchCategory",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Web ID de la categoría",
            "schema": {
              "type": "string",
              "example": "I7ROmS7Jui"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "category"
                ],
                "properties": {
                  "category": {
                    "type": "object",
                    "properties": {
                      "name": {
                        "type": "string",
                        "description": "Nombre de la categoría",
                        "example": "Electrónica"
                      },
                      "description": {
                        "type": "string",
                        "maxLength": 250,
                        "description": "Descripción de la categoría (máximo 250 caracteres)",
                        "example": "Productos electrónicos actualizados"
                      },
                      "order": {
                        "type": "integer",
                        "description": "Orden de visualización",
                        "example": 1
                      },
                      "subcategories_attributes": {
                        "type": "array",
                        "description": "Array de subcategorías",
                        "items": {
                          "type": "object",
                          "properties": {
                            "web_id": {
                              "type": "string",
                              "description": "Web ID de la subcategoría",
                              "example": "bas9UxSaUq"
                            },
                            "name": {
                              "type": "string",
                              "description": "Nombre de la subcategoría",
                              "example": "Smartphones"
                            },
                            "description": {
                              "type": "string",
                              "description": "Descripción de la subcategoría",
                              "example": "Teléfonos inteligentes actualizados"
                            },
                            "order": {
                              "type": "integer",
                              "description": "Orden de visualización",
                              "example": 1
                            },
                            "_destroy": {
                              "type": "boolean",
                              "description": "Si es true, elimina la subcategoría",
                              "example": false
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Category updated successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "web_id": {
                      "type": "string",
                      "example": "I7ROmS7Jui"
                    },
                    "name": {
                      "type": "string",
                      "example": "Electrónica"
                    },
                    "description": {
                      "type": "string",
                      "example": "Productos electrónicos actualizados"
                    },
                    "products_count": {
                      "type": "integer",
                      "example": 7
                    },
                    "order": {
                      "type": "integer",
                      "example": 1
                    },
                    "subcategories": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "web_id": {
                            "type": "string",
                            "example": "bas9UxSaUq"
                          },
                          "name": {
                            "type": "string",
                            "example": "Smartphones"
                          },
                          "description": {
                            "type": "string",
                            "example": "Teléfonos inteligentes actualizados"
                          },
                          "products_count": {
                            "type": "integer",
                            "example": 3
                          },
                          "order": {
                            "type": "integer",
                            "example": 1
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Category not found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Resource not found"
                    }
                  }
                }
              }
            }
          },
          "422": {
            "description": "Validation Error",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "errors": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "Categories"
        ],
        "summary": "Delete Category",
        "description": "Elimina una categoría y todas sus subcategorías",
        "operationId": "deleteCategory",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "description": "Web ID de la categoría",
            "schema": {
              "type": "string",
              "example": "I7ROmS7Jui"
            }
          }
        ],
        "security": [
          {
            "api-key": []
          }
        ],
        "responses": {
          "200": {
            "description": "Category deleted successfully",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "web_id": {
                      "type": "string",
                      "example": "I7ROmS7Jui"
                    },
                    "name": {
                      "type": "string",
                      "example": "Electrónica"
                    },
                    "description": {
                      "type": "string",
                      "example": "Productos electrónicos y dispositivos tecnológicos"
                    },
                    "products_count": {
                      "type": "integer",
                      "example": 0
                    },
                    "order": {
                      "type": "integer",
                      "example": 1
                    },
                    "subcategories": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "web_id": {
                            "type": "string",
                            "example": "bas9UxSaUq"
                          },
                          "name": {
                            "type": "string",
                            "example": "Smartphones"
                          },
                          "description": {
                            "type": "string",
                            "example": "Teléfonos inteligentes y accesorios"
                          },
                          "products_count": {
                            "type": "integer",
                            "example": 0
                          },
                          "order": {
                            "type": "integer",
                            "example": 1
                          }
                        }
                      }
                    }
                  }
                },
                "examples": {
                  "response": {
                    "value": {
                      "web_id": "I7ROmS7Jui",
                      "name": "Electrónica",
                      "description": "Productos electrónicos y dispositivos tecnológicos",
                      "products_count": 0,
                      "order": 1,
                      "subcategories": [
                        {
                          "web_id": "bas9UxSaUq",
                          "name": "Smartphones",
                          "description": "Teléfonos inteligentes y accesorios",
                          "products_count": 0,
                          "order": 1
                        }
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Unauthorized",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Unauthorized"
                    }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Category not found",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "message": {
                      "type": "string",
                      "example": "Resource not found"
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "funnel_stage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "19d8e7c6b5a4f3e-2d1c-4b0a-9e8f-7a6b5c4d3e2f"
          },
          "name": {
            "type": "string",
            "example": "Calificado"
          },
          "probability": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0,
            "maximum": 100,
            "example": 20
          },
          "stagnation_time": {
            "type": [
              "integer",
              "null"
            ],
            "description": "Días sin movimiento para marcar un negocio como estancado",
            "exclusiveMinimum": 0,
            "example": 5
          },
          "type": {
            "type": "string",
            "enum": [
              "step",
              "won",
              "lost"
            ],
            "example": "step"
          }
        }
      },
      "funnel": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "1c4f2a9b7e3d5a1-8b2e-4c6d-9f0a-3e5b7d9c1a2f"
          },
          "name": {
            "type": "string",
            "maxLength": 40,
            "example": "Ventas B2B"
          },
          "stages": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/funnel_stage"
            }
          }
        }
      },
      "funnel_list": {
        "type": "object",
        "properties": {
          "funnels": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/funnel"
            }
          }
        }
      },
      "funnel_stage_list": {
        "type": "object",
        "properties": {
          "stages": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/funnel_stage"
            }
          }
        }
      },
      "funnel_input": {
        "type": "object",
        "required": [
          "funnel"
        ],
        "properties": {
          "funnel": {
            "type": "object",
            "required": [
              "name"
            ],
            "properties": {
              "name": {
                "type": "string",
                "maxLength": 40,
                "example": "Embudo API prueba"
              }
            }
          }
        }
      },
      "funnel_stage_create": {
        "type": "object",
        "required": [
          "stage"
        ],
        "properties": {
          "stage": {
            "type": "object",
            "required": [
              "name"
            ],
            "properties": {
              "name": {
                "type": "string",
                "example": "Calificado"
              },
              "probability": {
                "type": "integer",
                "minimum": 0,
                "maximum": 100,
                "example": 20
              },
              "stagnation_time": {
                "type": "integer",
                "exclusiveMinimum": 0,
                "example": 5
              },
              "type": {
                "type": "string",
                "enum": [
                  "step",
                  "won",
                  "lost"
                ],
                "default": "step",
                "example": "step"
              }
            }
          }
        }
      },
      "funnel_stage_update": {
        "type": "object",
        "required": [
          "stage"
        ],
        "properties": {
          "stage": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string",
                "example": "Contactado"
              },
              "probability": {
                "type": "integer",
                "minimum": 0,
                "maximum": 100,
                "example": 40
              },
              "stagnation_time": {
                "type": "integer",
                "exclusiveMinimum": 0,
                "example": 3
              },
              "type": {
                "type": "string",
                "enum": [
                  "step",
                  "won",
                  "lost"
                ],
                "example": "won"
              }
            }
          }
        }
      },
      "funnel_message": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string"
          }
        }
      },
      "funnel_auth_error": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string"
          },
          "info": {
            "type": "object",
            "properties": {
              "data": {
                "type": "object"
              }
            }
          }
        }
      },
      "agents": {
        "type": "object",
        "title": "Agent",
        "properties": {
          "id": {
            "type": "integer",
            "example": 9
          },
          "first_name": {
            "type": "string",
            "example": "Nicolas"
          },
          "last_name": {
            "type": "string",
            "example": "Mena Garzon"
          },
          "email": {
            "type": "string",
            "example": "nicolas@mercately.com"
          },
          "active": {
            "type": "boolean",
            "example": true
          },
          "agent": {
            "type": "boolean",
            "example": false
          },
          "admin": {
            "type": "boolean",
            "example": true
          },
          "supervisor": {
            "type": "boolean",
            "example": true
          }
        }
      },
      "customer": {
        "type": "object",
        "title": "Customer",
        "properties": {
          "id": {
            "type": "string",
            "description": "ID único del cliente (web_id)"
          },
          "first_name": {
            "type": "string"
          },
          "last_name": {
            "type": "string"
          },
          "email": {
            "type": "string"
          },
          "phone": {
            "type": "string"
          },
          "id_type": {
            "type": "string",
            "enum": [
              "cedula",
              "pasaporte",
              "ruc",
              "rut",
              "otro"
            ]
          },
          "id_number": {
            "type": "string"
          },
          "address": {
            "type": "string",
            "description": "Dirección individual del cliente"
          },
          "city": {
            "type": "string",
            "description": "Ciudad individual del cliente"
          },
          "state": {
            "type": "string",
            "description": "Estado/Provincia individual del cliente"
          },
          "zip_code": {
            "type": "string",
            "description": "Código postal individual del cliente"
          },
          "country_id": {
            "type": "string",
            "description": "ID del país del cliente"
          },
          "notes": {
            "type": "string"
          },
          "whatsapp_opt_in": {
            "type": "boolean",
            "description": "Si el cliente ha optado por recibir mensajes de WhatsApp"
          },
          "whatsapp_name": {
            "type": "string",
            "description": "Nombre del cliente en WhatsApp"
          },
          "username": {
            "type": "string",
            "description": "Usuario o identificador social del cliente"
          },
          "customer_addresses": {
            "type": "array",
            "description": "Array de direcciones adicionales del cliente",
            "items": {
              "type": "object",
              "properties": {
                "address": {
                  "type": "string"
                },
                "city": {
                  "type": "string"
                },
                "state": {
                  "type": "string"
                },
                "zip_code": {
                  "type": "string"
                },
                "latitude": {
                  "type": "string"
                },
                "longitude": {
                  "type": "string"
                },
                "description": {
                  "type": "string"
                },
                "main": {
                  "type": "boolean"
                }
              }
            }
          },
          "tags": {
            "type": "array",
            "description": "Array de etiquetas del cliente",
            "items": {
              "type": "object",
              "properties": {
                "tag": {
                  "type": "string",
                  "description": "Nombre de la etiqueta"
                },
                "web_id": {
                  "type": "string",
                  "description": "ID único de la etiqueta"
                }
              }
            }
          },
          "custom_fields": {
            "type": "array",
            "description": "Array de campos personalizados del cliente",
            "items": {
              "type": "object",
              "properties": {
                "field_name": {
                  "type": "string",
                  "description": "Identificador del campo personalizado"
                },
                "field_content": {
                  "type": "string",
                  "description": "Contenido del campo personalizado"
                }
              }
            }
          },
          "agent": {
            "type": "object",
            "description": "Agente asignado al cliente",
            "properties": {
              "id": {
                "type": "integer",
                "description": "ID del agente"
              },
              "email": {
                "type": "string",
                "description": "Email del agente"
              }
            }
          },
          "outbound_status": {
            "type": "string",
            "enum": [
              "error",
              "submitted",
              "enqueued",
              "sent",
              "delivered",
              "read"
            ],
            "description": "Estado del último mensaje outbound enviado al cliente"
          },
          "campaign_id": {
            "type": "integer",
            "description": "ID de la campaña asociada al cliente"
          },
          "error_message": {
            "type": "string",
            "description": "Mensaje de error si hubo un problema con el último mensaje enviado"
          },
          "campaign_url": {
            "type": "string",
            "description": "URL de la campaña asociada (vacío si no hay campaña)"
          },
          "creation_date": {
            "type": "string",
            "format": "date-time",
            "description": "Fecha de creación del cliente"
          },
          "sent_at": {
            "type": "string",
            "format": "date-time",
            "description": "Fecha en que se envió el último mensaje outbound"
          },
          "delivered_at": {
            "type": "string",
            "format": "date-time",
            "description": "Fecha en que se entregó el último mensaje outbound"
          },
          "read_at": {
            "type": "string",
            "format": "date-time",
            "description": "Fecha en que se leyó el último mensaje outbound"
          },
          "last_chat_interaction": {
            "type": "string",
            "format": "date-time",
            "description": "Fecha de la última interacción en el chat"
          },
          "inbox_chats": {
            "type": "array",
            "description": "Conversaciones del microservicio en las que está indexado el cliente",
            "items": {
              "type": "object",
              "properties": {
                "chat_id": {
                  "type": "string",
                  "description": "ID de la conversación en el microservicio"
                },
                "platform": {
                  "type": "string",
                  "description": "Clave específica de la plataforma (whatsapp_bsp_messages, whatsapp_qr_messages, whatsapp_gupshup_messages, facebook_messages, instagram_messages, ...)"
                }
              }
            }
          }
        }
      },
      "get_customer": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "example": "Customer found successfully"
          },
          "customer": {
            "$ref": "#/components/schemas/customer"
          }
        }
      },
      "update_customer": {
        "type": "object",
        "title": "UpdateCustomerRequest",
        "properties": {
          "customer": {
            "type": "object",
            "title": "Customer",
            "properties": {
              "first_name": {
                "type": "string",
                "description": "Nombre del cliente"
              },
              "last_name": {
                "type": "string",
                "description": "Apellido del cliente"
              },
              "email": {
                "type": "string",
                "description": "Email del cliente"
              },
              "phone": {
                "type": "string",
                "description": "Teléfono del cliente"
              },
              "id_type": {
                "type": "string",
                "enum": [
                  "cedula",
                  "pasaporte",
                  "ruc",
                  "rut",
                  "otro"
                ],
                "description": "Tipo de documento de identificación"
              },
              "id_number": {
                "type": "string",
                "description": "Número de documento de identificación"
              },
              "address": {
                "type": "string",
                "description": "Dirección del cliente"
              },
              "city": {
                "type": "string",
                "description": "Ciudad del cliente"
              },
              "state": {
                "type": "string",
                "description": "Estado/Provincia del cliente"
              },
              "zip_code": {
                "type": "string",
                "description": "Código postal del cliente"
              },
              "customer_addresses_attributes": {
                "type": "array",
                "description": "Array de direcciones adicionales del cliente",
                "items": {
                  "type": "object",
                  "properties": {
                    "address": {
                      "type": "string"
                    },
                    "city": {
                      "type": "string"
                    },
                    "state": {
                      "type": "string"
                    },
                    "zip_code": {
                      "type": "string"
                    },
                    "country_id": {
                      "type": "integer"
                    },
                    "latitude": {
                      "type": "string"
                    },
                    "longitude": {
                      "type": "string"
                    },
                    "description": {
                      "type": "string"
                    },
                    "main": {
                      "type": "boolean"
                    }
                  }
                }
              },
              "notes": {
                "type": "string",
                "description": "Notas sobre el cliente"
              }
            }
          },
          "agent_id": {
            "type": "integer",
            "description": "ID del agente asignado al cliente (puede estar en nivel raíz o dentro de customer)"
          },
          "tags": {
            "type": "array",
            "description": "Array de etiquetas del cliente (puede estar en nivel raíz o dentro de customer)",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string",
                  "description": "Nombre de la etiqueta"
                },
                "value": {
                  "type": "boolean",
                  "description": "true para asignar la etiqueta, false para removerla"
                }
              }
            }
          },
          "custom_fields": {
            "type": "array",
            "description": "Array de campos personalizados del cliente (puede estar en nivel raíz o dentro de customer)",
            "items": {
              "type": "object",
              "properties": {
                "field_name": {
                  "type": "string",
                  "description": "Identificador del campo personalizado"
                },
                "field_content": {
                  "type": "string",
                  "description": "Contenido del campo personalizado"
                }
              }
            }
          }
        }
      },
      "update_customer-2": {
        "type": "object",
        "title": "UpdateCustomerResponse",
        "properties": {
          "message": {
            "type": "string",
            "description": "Mensaje de confirmación",
            "example": "Customer updated successfully"
          },
          "customer": {
            "type": "object",
            "title": "Customer",
            "properties": {
              "id": {
                "type": "string",
                "description": "ID único del cliente (web_id)"
              },
              "first_name": {
                "type": "string"
              },
              "last_name": {
                "type": "string"
              },
              "email": {
                "type": "string"
              },
              "phone": {
                "type": "string"
              },
              "id_type": {
                "type": "string",
                "enum": [
                  "cedula",
                  "pasaporte",
                  "ruc",
                  "rut",
                  "otro"
                ]
              },
              "id_number": {
                "type": "string"
              },
              "address": {
                "type": "string",
                "description": "Dirección individual del cliente"
              },
              "city": {
                "type": "string",
                "description": "Ciudad individual del cliente"
              },
              "state": {
                "type": "string",
                "description": "Estado/Provincia individual del cliente"
              },
              "zip_code": {
                "type": "string",
                "description": "Código postal individual del cliente"
              },
              "country_id": {
                "type": "string",
                "description": "ID del país del cliente"
              },
              "notes": {
                "type": "string"
              },
              "whatsapp_opt_in": {
                "type": "boolean",
                "description": "Si el cliente ha optado por recibir mensajes de WhatsApp"
              },
              "whatsapp_name": {
                "type": "string",
                "description": "Nombre del cliente en WhatsApp"
              },
              "customer_addresses": {
                "type": "array",
                "description": "Array de direcciones adicionales del cliente",
                "items": {
                  "type": "object",
                  "properties": {
                    "address": {
                      "type": "string"
                    },
                    "city": {
                      "type": "string"
                    },
                    "state": {
                      "type": "string"
                    },
                    "zip_code": {
                      "type": "string"
                    },
                    "latitude": {
                      "type": "string"
                    },
                    "longitude": {
                      "type": "string"
                    },
                    "description": {
                      "type": "string"
                    },
                    "main": {
                      "type": "boolean"
                    }
                  }
                }
              },
              "tags": {
                "type": "array",
                "description": "Array de etiquetas del cliente",
                "items": {
                  "type": "object",
                  "properties": {
                    "tag": {
                      "type": "string",
                      "description": "Nombre de la etiqueta"
                    },
                    "web_id": {
                      "type": "string",
                      "description": "ID único de la etiqueta"
                    }
                  }
                }
              },
              "custom_fields": {
                "type": "array",
                "description": "Array de campos personalizados del cliente",
                "items": {
                  "type": "object",
                  "properties": {
                    "field_name": {
                      "type": "string",
                      "description": "Identificador del campo personalizado"
                    },
                    "field_content": {
                      "type": "string",
                      "description": "Contenido del campo personalizado"
                    }
                  }
                }
              },
              "agent": {
                "type": "object",
                "description": "Agente asignado al cliente",
                "properties": {
                  "id": {
                    "type": "integer",
                    "description": "ID del agente"
                  },
                  "email": {
                    "type": "string",
                    "description": "Email del agente"
                  }
                }
              },
              "outbound_status": {
                "type": "string",
                "enum": [
                  "error",
                  "submitted",
                  "enqueued",
                  "sent",
                  "delivered",
                  "read"
                ],
                "description": "Estado del último mensaje outbound enviado al cliente"
              },
              "campaign_id": {
                "type": "integer",
                "description": "ID de la campaña asociada al cliente"
              },
              "error_message": {
                "type": "string",
                "description": "Mensaje de error si hubo un problema con el último mensaje enviado"
              },
              "campaign_url": {
                "type": "string",
                "description": "URL de la campaña asociada (vacío si no hay campaña)"
              },
              "creation_date": {
                "type": "string",
                "format": "date-time",
                "description": "Fecha de creación del cliente"
              },
              "sent_at": {
                "type": "string",
                "format": "date-time",
                "description": "Fecha en que se envió el último mensaje outbound"
              },
              "delivered_at": {
                "type": "string",
                "format": "date-time",
                "description": "Fecha en que se entregó el último mensaje outbound"
              },
              "read_at": {
                "type": "string",
                "format": "date-time",
                "description": "Fecha en que se leyó el último mensaje outbound"
              },
              "last_chat_interaction": {
                "type": "string",
                "format": "date-time",
                "description": "Fecha de la última interacción en el chat"
              }
            }
          }
        }
      },
      "customer_event": {
        "type": "object",
        "title": "CreateCustomerEventRequest",
        "required": [
          "customer_event"
        ],
        "properties": {
          "customer_event": {
            "type": "object",
            "title": "CustomerEvent",
            "required": [
              "category",
              "subcategory",
              "action"
            ],
            "properties": {
              "category": {
                "type": "string",
                "description": "Categoría del evento",
                "example": "purchase"
              },
              "subcategory": {
                "type": "string",
                "description": "Subcategoría del evento",
                "example": "order_placed"
              },
              "action": {
                "type": "string",
                "description": "Acción del evento",
                "example": "created"
              },
              "type_event": {
                "type": "string",
                "description": "Tipo de evento (opcional)",
                "example": "order"
              },
              "source": {
                "type": "string",
                "description": "Fuente del evento (opcional)",
                "example": "api"
              },
              "url_spec": {
                "type": "string",
                "description": "URL específica relacionada con el evento (opcional)",
                "example": "https://example.com/order/123"
              },
              "created_at": {
                "type": "string",
                "format": "date-time",
                "description": "Fecha y hora de creación del evento (opcional). Si no se proporciona, se usa la fecha actual",
                "example": "2024-01-15T10:30:00Z"
              }
            }
          }
        }
      },
      "create_customer_event": {
        "type": "object",
        "properties": {
          "messages": {
            "type": "string",
            "example": "Customer event created successfully"
          }
        }
      },
      "whatsapp_api_message": {
        "type": "object",
        "title": "SendWhatsAppNotificationByIdResponse",
        "properties": {
          "message": {
            "type": "string",
            "description": "Mensaje de confirmación",
            "example": "Ok"
          },
          "info": {
            "type": "object",
            "title": "MessageInfo",
            "properties": {
              "channel": {
                "type": "string",
                "description": "Canal del mensaje",
                "example": "whatsapp"
              },
              "content": {
                "type": "object",
                "title": "MessageContent",
                "properties": {
                  "text": {
                    "type": "string",
                    "description": "Texto del mensaje enviado",
                    "example": "Your OTP for test 1 is test 2. This is valid for test 3."
                  },
                  "media_url": {
                    "type": "string",
                    "description": "URL del archivo multimedia (solo si se envió media)",
                    "example": "https://mercately.com/example.png"
                  }
                }
              },
              "direction": {
                "type": "string",
                "description": "Dirección del mensaje",
                "example": "outbound"
              },
              "status": {
                "type": "string",
                "description": "Estado del mensaje",
                "example": "submitted"
              },
              "destination": {
                "type": "string",
                "description": "Número de teléfono de destino",
                "example": "+593999999999"
              },
              "country": {
                "type": "string",
                "description": "Código de país del destinatario",
                "example": "EC"
              },
              "created_time": {
                "type": "string",
                "format": "date-time",
                "description": "Fecha y hora de creación del mensaje",
                "example": "2022-09-23T16:34:16.768-04:00"
              },
              "error": {
                "type": [
                  "null",
                  "string"
                ],
                "description": "Mensaje de error (null si no hay error)",
                "example": null
              }
            }
          }
        }
      },
      "messenger_message": {
        "type": "object",
        "title": "MessengerConversationsResponse",
        "properties": {
          "facebook_messages": {
            "type": "array",
            "description": "Array de mensajes de Messenger del cliente",
            "items": {
              "type": "object",
              "title": "FacebookMessage",
              "properties": {
                "id": {
                  "type": "string",
                  "description": "ID del mensaje"
                },
                "customer_id": {
                  "type": "integer",
                  "description": "ID del cliente"
                },
                "text": {
                  "type": "string",
                  "description": "Texto del mensaje"
                },
                "created_at": {
                  "type": "string",
                  "format": "date-time",
                  "description": "Fecha y hora de creación del mensaje"
                },
                "sent_by_retailer": {
                  "type": "boolean",
                  "description": "Si el mensaje fue enviado por el retailer"
                },
                "file_type": {
                  "type": "string",
                  "description": "Tipo de archivo (si aplica)"
                },
                "mid": {
                  "type": "string",
                  "description": "ID del mensaje en Facebook"
                },
                "message_identifier": {
                  "type": "string",
                  "description": "Identificador del mensaje"
                },
                "note": {
                  "type": "string",
                  "description": "Nota asociada al mensaje"
                },
                "order_note": {
                  "type": "string",
                  "description": "Nota de orden asociada"
                },
                "order_summary": {
                  "type": "string",
                  "description": "Resumen de orden asociado"
                },
                "replied_message": {
                  "type": "object",
                  "description": "Mensaje al que se está respondiendo (objeto completo del mensaje respondido, solo si existe)"
                },
                "error_message": {
                  "type": "string",
                  "description": "Mensaje de error (si aplica)"
                },
                "internal_url": {
                  "type": "string",
                  "description": "URL interna del archivo"
                },
                "payload": {
                  "type": "object",
                  "description": "Payload del mensaje"
                },
                "mia_flag": {
                  "type": "boolean",
                  "description": "Flag de MIA"
                },
                "sent_by_mia": {
                  "type": "boolean",
                  "description": "Si el mensaje fue enviado por MIA"
                },
                "mia_client_data": {
                  "type": "boolean",
                  "description": "Datos de cliente MIA"
                },
                "customer_related_data": {
                  "type": "array",
                  "description": "Datos relacionados del cliente"
                },
                "customer_tags": {
                  "type": "array",
                  "description": "Etiquetas del cliente"
                },
                "mia_assignment": {
                  "type": "boolean",
                  "description": "Asignación MIA"
                },
                "assignment_data": {
                  "type": "object",
                  "description": "Datos de asignación"
                },
                "event_data": {
                  "type": "object",
                  "description": "Datos del evento"
                },
                "mia_event": {
                  "type": "boolean",
                  "description": "Evento MIA"
                },
                "sender_full_name": {
                  "type": "string",
                  "description": "Nombre completo del remitente (solo si fue enviado desde Mercately)"
                },
                "filename": {
                  "type": "string",
                  "description": "Nombre del archivo (solo si hay file_type)"
                },
                "url": {
                  "type": "string",
                  "description": "URL del archivo (solo si hay file_type)"
                },
                "date_read": {
                  "type": "string",
                  "format": "date-time",
                  "description": "Fecha en que se leyó el mensaje (solo si sent_by_retailer es true)"
                }
              }
            }
          },
          "total_pages": {
            "type": "integer",
            "description": "Número total de páginas",
            "example": 1
          }
        }
      },
      "get_customer_event": {
        "type": "object",
        "properties": {
          "results": {
            "type": "integer",
            "description": "Número total de eventos",
            "example": 10
          },
          "total_pages": {
            "type": "integer",
            "description": "Número total de páginas",
            "example": 2
          },
          "customer_events": {
            "type": "array",
            "description": "Array de eventos del cliente",
            "items": {
              "type": "object",
              "title": "CustomerEvent",
              "properties": {
                "category": {
                  "type": "string",
                  "description": "Categoría del evento",
                  "example": "purchase"
                },
                "subcategory": {
                  "type": "string",
                  "description": "Subcategoría del evento",
                  "example": "order_placed"
                },
                "event": {
                  "type": "string",
                  "description": "Acción del evento",
                  "example": "created"
                },
                "creation_date": {
                  "type": "string",
                  "description": "Fecha y hora de creación del evento (formato: DD-MM-YYYY HH:MM)",
                  "example": "15-01-2024 10:30"
                },
                "agent": {
                  "type": "string",
                  "description": "Nombre del agente asociado al evento",
                  "example": "John Doe"
                }
              }
            }
          }
        }
      },
      "agent": {
        "type": "object",
        "title": "Agent",
        "properties": {
          "id": {
            "type": "integer",
            "example": 9
          },
          "first_name": {
            "type": "string",
            "example": "Nicolas"
          },
          "last_name": {
            "type": "string",
            "example": "Mena Garzon"
          },
          "email": {
            "type": "string",
            "example": "nicolas@mercately.com"
          },
          "active": {
            "type": "boolean",
            "example": true
          },
          "agent": {
            "type": "boolean",
            "example": false
          },
          "admin": {
            "type": "boolean",
            "example": true
          },
          "supervisor": {
            "type": "boolean",
            "example": true
          }
        }
      },
      "customer_lite": {
        "type": "object",
        "title": "CustomerLite",
        "properties": {
          "id": {
            "type": "string",
            "example": "91989a87"
          },
          "first_name": {
            "type": "string",
            "example": "javier"
          },
          "last_name": {
            "type": "string",
            "example": "Salinas"
          },
          "email": {
            "type": "string",
            "format": "email",
            "example": "javier@example.com"
          },
          "phone": {
            "type": "string",
            "example": 5933505692996
          }
        }
      },
      "deal": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "example": "9fb882221"
          },
          "name": {
            "type": "string",
            "example": "Neptu"
          },
          "amount": {
            "type": "string",
            "example": "150000.0"
          },
          "currency": {
            "type": "string",
            "example": "$"
          },
          "funnel_name": {
            "type": "string",
            "example": "Negociaciones"
          },
          "stage": {
            "type": "string",
            "example": "Calificado!"
          },
          "agent": {
            "$ref": "#/components/schemas/agent"
          },
          "customer": {
            "$ref": "#/components/schemas/customer_lite"
          },
          "channel": {
            "type": [
              "string",
              "null"
            ]
          }
        }
      },
      "index": {
        "type": "object",
        "properties": {
          "total": {
            "type": "integer",
            "example": 2
          },
          "total_page": {
            "type": "integer",
            "example": 1
          },
          "deals": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/deal"
            }
          }
        }
      },
      "create": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "example": "deal was created successfully"
          },
          "deal": {
            "$ref": "#/components/schemas/deal"
          }
        }
      },
      "get": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "example": "deal found successfully"
          },
          "deal": {
            "$ref": "#/components/schemas/deal"
          }
        }
      },
      "update": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "example": "deal was updated successfully"
          },
          "deal": {
            "$ref": "#/components/schemas/deal"
          }
        }
      },
      "send_api_message": {
        "type": "object",
        "title": "SendWhatsAppNotificationByIdRequest",
        "required": [
          "internal_id",
          "template_params"
        ],
        "properties": {
          "phone_number": {
            "type": "string",
            "description": "Número de teléfono del destinatario (formato internacional con +). Se usa cuando no se envía customer_id o cuando ese customer_id no existe.",
            "example": "+593999999999"
          },
          "customer_id": {
            "type": "string",
            "description": "web_id del cliente (obtenido del endpoint de clientes). Tiene prioridad sobre phone_number. Si no existe, se usa phone_number. Sin phone_number no se crea un cliente nuevo.",
            "example": "1713huaxq1352"
          },
          "platform_retailer_id": {
            "type": "string",
            "description": "Identificador de la integración (el `id` de GET /retailers/api/v1/integrations). Obligatorio cuando el retailer tiene varias integraciones de la plataforma.",
            "example": "6aa831f6f3c34b7e791c9b96"
          },
          "internal_id": {
            "type": "string",
            "description": "ID interno del template de WhatsApp (gupshup_template_id)",
            "example": "997dd550-c8d8-4bf7-ad98-a5ac4844a1ed"
          },
          "template_params": {
            "type": "array",
            "description": "Array de parámetros para rellenar el template",
            "items": {
              "type": "string"
            },
            "example": [
              "test 1",
              "test 2",
              "test 3"
            ]
          },
          "media_url": {
            "type": "string",
            "description": "URL del archivo multimedia (solo si el template incluye media)",
            "example": "https://mercately.com/example.png"
          },
          "agent_id": {
            "type": "integer",
            "description": "ID del agente al que se asignará el cliente",
            "example": 980
          },
          "tags": {
            "type": "array",
            "description": "Array de etiquetas para asignar al cliente",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string",
                  "description": "Nombre de la etiqueta"
                },
                "value": {
                  "type": "boolean",
                  "description": "true para asignar la etiqueta, false para removerla"
                }
              },
              "example": [
                {
                  "name": "at",
                  "value": true
                }
              ]
            }
          }
        }
      },
      "send_qr_message": {
        "type": "object",
        "title": "SendWhatsAppQrMessageRequest",
        "properties": {
          "phone_number": {
            "type": "string",
            "description": "Número de teléfono del destinatario (formato internacional con +). Se usa cuando no se envía customer_id o cuando ese customer_id no existe.",
            "example": "+593999999999"
          },
          "customer_id": {
            "type": "string",
            "description": "web_id del cliente (obtenido del endpoint de clientes). Tiene prioridad sobre phone_number. Si no existe, se usa phone_number. Sin phone_number no se crea un cliente nuevo.",
            "example": "1713huaxq1352"
          },
          "platform_retailer_id": {
            "type": "string",
            "description": "Identificador de la integración (el `id` de GET /retailers/api/v1/integrations). Obligatorio cuando el retailer tiene varias integraciones de la plataforma.",
            "example": "6aa831f6f3c34b7e791c9b96"
          },
          "message": {
            "type": "string",
            "description": "Mensaje de texto a enviar (requerido si no se envía media_url)",
            "example": "Hello, this is a test message"
          },
          "media_url": {
            "type": "string",
            "description": "URL del archivo multimedia (requerido si no se envía message). Solo se permiten imágenes JPG/JPEG/PNG y archivos PDF",
            "example": "https://mercately.com/example.png"
          },
          "first_name": {
            "type": "string",
            "description": "Nombre del cliente (opcional)",
            "example": "John"
          },
          "last_name": {
            "type": "string",
            "description": "Apellido del cliente (opcional)",
            "example": "Doe"
          },
          "email": {
            "type": "string",
            "description": "Email del cliente (opcional)",
            "example": "john@example.com"
          },
          "address": {
            "type": "string",
            "description": "Dirección del cliente (opcional)",
            "example": "123 Main St"
          },
          "city": {
            "type": "string",
            "description": "Ciudad del cliente (opcional)",
            "example": "Quito"
          },
          "state": {
            "type": "string",
            "description": "Estado/Provincia del cliente (opcional)",
            "example": "Pichincha"
          },
          "zip_code": {
            "type": "string",
            "description": "Código postal del cliente (opcional)",
            "example": "170101"
          },
          "notes": {
            "type": "string",
            "description": "Notas sobre el cliente (opcional)",
            "example": "Customer notes"
          },
          "agent_id": {
            "type": "integer",
            "description": "ID del agente al que se asignará el cliente (opcional)",
            "example": 980
          },
          "tags": {
            "type": "array",
            "description": "Array de etiquetas para asignar al cliente (opcional)",
            "items": {
              "type": "object",
              "properties": {
                "name": {
                  "type": "string",
                  "description": "Nombre de la etiqueta"
                },
                "value": {
                  "type": "boolean",
                  "description": "true para asignar la etiqueta, false para removerla"
                }
              }
            },
            "example": [
              {
                "name": "at",
                "value": true
              }
            ]
          },
          "custom_fields": {
            "type": "array",
            "description": "Array de campos personalizados del cliente (opcional)",
            "items": {
              "type": "object",
              "properties": {
                "identifier": {
                  "type": "string",
                  "description": "Identificador del campo personalizado"
                },
                "value": {
                  "type": "string",
                  "description": "Valor del campo personalizado"
                }
              }
            },
            "example": [
              {
                "identifier": "custom_field_1",
                "value": "Some value"
              }
            ]
          },
          "funnel_name": {
            "type": "string",
            "description": "Nombre del embudo para crear un deal (opcional, requiere stage)",
            "example": "Sales Funnel"
          },
          "stage": {
            "type": "string",
            "description": "Etapa del embudo para crear un deal (opcional, requiere funnel_name)",
            "example": "Lead"
          }
        }
      },
      "send_open_message": {
        "type": "object",
        "title": "SendWhatsAppOpenMessageRequest",
        "description": "Envía un mensaje libre de WhatsApp (texto o media) por la línea oficial (BSP/Gupshup) o QR del retailer.\nSe requiere `phone_number` o `customer_id` (al menos uno) y `message` o `media_url`.\nSi se envían ambos, se usa `customer_id`; si ese `customer_id` no existe, se usa `phone_number`.\nEl cliente debe tener teléfono o `user_id`; si no, responde 422.\n",
        "properties": {
          "phone_number": {
            "type": "string",
            "description": "Número de teléfono del destinatario (formato internacional con +). Se usa cuando no se envía customer_id o cuando ese customer_id no existe. Si no existe, se crea el cliente.",
            "example": "+593999999999"
          },
          "customer_id": {
            "type": "string",
            "description": "web_id del cliente (obtenido del endpoint de clientes). Tiene prioridad sobre phone_number. Si no existe, se usa phone_number.",
            "example": "1713huaxq1352"
          },
          "integration_id": {
            "type": "string",
            "description": "Id de la línea de WhatsApp, tal como lo devuelve GET /retailers/api/v1/whatsapp_templates/integrations. Obligatorio si el retailer tiene varias líneas; con una sola línea no hace falta.",
            "example": "int-1"
          },
          "message": {
            "type": "string",
            "description": "Texto del mensaje. Si se envía media_url, se usa como caption.",
            "example": "Hola, ¿cómo estás?"
          },
          "media_url": {
            "type": "string",
            "description": "URL pública del archivo. Permitidos: imágenes JPG/JPEG/PNG, documentos PDF/DOC/DOCX/XLS/XLSX, audio MP3/OGG/OGA/OPUS/M4A/AAC/WAV y video MP4/3GP/MOV/M4V.",
            "example": "https://mercately.com/example.png"
          },
          "first_name": {
            "type": "string",
            "description": "Nombre del cliente (opcional)",
            "example": "John"
          },
          "last_name": {
            "type": "string",
            "description": "Apellido del cliente (opcional)",
            "example": "Doe"
          },
          "email": {
            "type": "string",
            "description": "Email del cliente (opcional)",
            "example": "john@example.com"
          },
          "address": {
            "type": "string",
            "description": "Dirección del cliente (opcional)",
            "example": "123 Main St"
          },
          "city": {
            "type": "string",
            "description": "Ciudad del cliente (opcional)",
            "example": "Quito"
          },
          "state": {
            "type": "string",
            "description": "Estado/Provincia del cliente (opcional)",
            "example": "Pichincha"
          },
          "zip_code": {
            "type": "string",
            "description": "Código postal del cliente (opcional)",
            "example": "170101"
          },
          "notes": {
            "type": "string",
            "description": "Notas sobre el cliente (opcional)",
            "example": "Customer notes"
          }
        }
      },
      "template": {
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "description": "Identificador numérico, estable desde la creación.",
            "example": 1234
          },
          "internal_id": {
            "type": [
              "string",
              "null"
            ],
            "description": "Identificador del proveedor (el que se usa en `send_notification_by_id`). Puede ser `null` mientras la plantilla está `pending`.",
            "example": "7f3f0c1e-1f6b-4a43-9a25-0d1a5f0f0a11"
          },
          "name": {
            "type": "string",
            "example": "order_update"
          },
          "status": {
            "type": "string",
            "enum": [
              "pending",
              "submitted",
              "accepted",
              "rejected",
              "disabled",
              "deleted"
            ],
            "example": "submitted"
          },
          "category": {
            "type": "string",
            "enum": [
              "MARKETING",
              "UTILITY",
              "AUTHENTICATION"
            ],
            "example": "UTILITY"
          },
          "language": {
            "type": "string",
            "example": "spanish"
          },
          "template_type": {
            "type": "string",
            "enum": [
              "text",
              "image",
              "video",
              "document",
              "carousel"
            ],
            "example": "text"
          },
          "text": {
            "type": "string",
            "description": "Texto guardado. En plantillas `accepted` cada variable se ve como `*`; usa `body` para leer el contenido.",
            "example": "Hola {{1}}, tu pedido {{2}} va en camino"
          },
          "body": {
            "type": "string",
            "description": "Texto con las variables como `{{1}}`, `{{2}}`… Úsalo para leer el contenido de la plantilla.",
            "example": "Hola {{1}}, tu pedido {{2}} va en camino"
          },
          "header_text": {
            "type": [
              "string",
              "null"
            ],
            "example": "Tu pedido"
          },
          "interactive_action": {
            "type": [
              "string",
              "null"
            ],
            "description": "Se deduce de `buttons` (`quick_reply` o `call_to_action`)."
          },
          "buttons": {
            "type": [
              "array",
              "null"
            ],
            "items": {
              "type": "object"
            }
          },
          "cards": {
            "type": [
              "array",
              "null"
            ],
            "description": "Tarjetas del carrusel (`headerType`, `body`, `example`, `buttons`).",
            "items": {
              "type": "object"
            }
          },
          "offer": {
            "type": [
              "object",
              "null"
            ],
            "properties": {
              "title": {
                "type": "string",
                "example": "Solo hoy"
              },
              "expires_in_minutes": {
                "type": [
                  "integer",
                  "null"
                ],
                "example": 120
              }
            }
          },
          "reason": {
            "type": [
              "string",
              "null"
            ],
            "description": "Motivo del rechazo cuando `status` es `rejected`."
          },
          "created_at": {
            "type": "string",
            "format": "date-time",
            "example": "2026-10-07T12:40:37.636Z"
          }
        }
      },
      "template_error": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "example": "Template could not be created"
          },
          "errors": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "field": {
                  "type": "string",
                  "example": "text"
                },
                "code": {
                  "type": "string",
                  "example": "variables_not_sequential"
                },
                "detail": {
                  "type": "string",
                  "example": "variables must be sequential starting at {{1}}"
                }
              }
            }
          },
          "template": {
            "description": "Solo con `provider_rejected`. La plantilla guardada, con `status` `rejected`.",
            "$ref": "#/components/schemas/template"
          }
        }
      },
      "flow": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "version": {
            "type": "integer",
            "example": 2
          },
          "enabled": {
            "type": "boolean"
          },
          "whatsapp": {
            "type": "boolean"
          },
          "messenger": {
            "type": "boolean"
          },
          "instagram": {
            "type": "boolean"
          }
        }
      },
      "get_flows": {
        "type": "object",
        "properties": {
          "results": {
            "type": "integer",
            "example": 1
          },
          "total_pages": {
            "type": "integer",
            "example": 1
          },
          "flows": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/flow"
            }
          }
        }
      },
      "deactivate_flows": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "example": "Flows by platform successfully deactivated"
          },
          "info": {
            "type": "object",
            "properties": {
              "data": {
                "type": "object"
              }
            },
            "example": {
              "data": {}
            }
          }
        }
      },
      "pre_activate_flow": {
        "type": "object",
        "properties": {
          "message": {
            "type": "string",
            "example": "Flow successfully preactivated"
          },
          "info": {
            "type": "array"
          }
        }
      }
    },
    "responses": {
      "funnels_unauthorized": {
        "description": "Falta el header Api-Key",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/funnel_auth_error"
            },
            "example": {
              "message": "Unauthorized",
              "info": {
                "data": {}
              }
            }
          }
        }
      },
      "funnels_invalid_api_key": {
        "description": "La Api-Key no es válida",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/funnel_auth_error"
            },
            "example": {
              "message": "Resource not found",
              "info": {
                "data": {}
              }
            }
          }
        }
      },
      "funnel_not_found": {
        "description": "El embudo no existe o pertenece a otro retailer, o la Api-Key no es válida",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/funnel_message"
            },
            "examples": {
              "funnel_not_found": {
                "summary": "Embudo no existe o es de otro retailer",
                "value": {
                  "message": "funnel not found"
                }
              },
              "invalid_api_key": {
                "summary": "Api-Key inválida",
                "value": {
                  "message": "Resource not found",
                  "info": {
                    "data": {}
                  }
                }
              }
            }
          }
        }
      },
      "funnel_stage_not_found": {
        "description": "El embudo o la etapa no existen, pertenecen a otro retailer o la etapa no es de ese embudo",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/funnel_message"
            },
            "examples": {
              "funnel_not_found": {
                "summary": "Embudo no existe o es de otro retailer",
                "value": {
                  "message": "funnel not found"
                }
              },
              "stage_not_found": {
                "summary": "Etapa no existe en ese embudo",
                "value": {
                  "message": "stage not found"
                }
              }
            }
          }
        }
      },
      "funnel_validation_error": {
        "description": "El embudo no se guardó",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/funnel_message"
            },
            "examples": {
              "blank_name": {
                "summary": "Nombre vacío",
                "value": {
                  "message": "can't be blank"
                }
              },
              "too_long": {
                "summary": "Más de 40 caracteres",
                "value": {
                  "message": "is too long (maximum is 40 characters)"
                }
              },
              "duplicated_name": {
                "summary": "Nombre repetido en el retailer",
                "value": {
                  "message": "Este nombre de embudo ya existe"
                }
              }
            }
          }
        }
      },
      "funnel_stage_validation_error": {
        "description": "La etapa no se guardó",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/funnel_message"
            },
            "examples": {
              "blank_name": {
                "summary": "Nombre vacío",
                "value": {
                  "message": "can't be blank"
                }
              },
              "duplicated_name": {
                "summary": "Nombre repetido en el embudo",
                "value": {
                  "message": "Nombre de etapa ya existe"
                }
              },
              "probability_out_of_range": {
                "summary": "Probabilidad mayor a 100",
                "value": {
                  "message": "must be less than or equal to 100"
                }
              },
              "stagnation_time": {
                "summary": "Tiempo de estancamiento menor o igual a cero",
                "value": {
                  "message": "Debe ser mayor a cero"
                }
              },
              "invalid_type": {
                "summary": "Tipo inválido",
                "value": {
                  "message": "type is invalid"
                }
              }
            }
          }
        }
      }
    },
    "securitySchemes": {
      "api-key": {
        "type": "apiKey",
        "name": "api-key",
        "in": "header",
        "description": "API Key authentication"
      }
    }
  }
}