> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hustapp.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Leads e tarefas

> Crie, atualize, mova e exclua os cards do funil

Card é o item de uma etapa: um lead, em pipelines do tipo `lead`, ou uma tarefa, nas demais.

## Objeto Card

| Campo | Tipo | Descrição |
| - | - | - |
| `id` | `integer` | Identificador. |
| `title` | `string` | Título: nome do lead ou da tarefa. |
| `description` | `string \| null` | Descrição, em HTML. |
| `type` | `string` | `lead`, `task` ou `item` (item de checklist). |
| `status` | `string` | [Status](/crm/visao-geral.md#status) atual. |
| `priority` | `string` | [Prioridade](/crm/visao-geral.md#prioridade). Padrão `medium`. |
| `dateStart` | `string` | Data de criação. |
| `dateDue` | `string \| null` | Vencimento. |
| `valueUnique` | `number \| null` | Valor único, de venda avulsa. |
| `valueRecurring` | `number \| null` | Valor recorrente mensal. |
| `sequence` | `integer \| null` | Ordem dentro da etapa. |
| `source` | `string \| null` | Origem. Somente leitura. |
| `lostDescription` | `string \| null` | Motivo de perda. Somente leitura. |
| `products` | `array \| null` | Produtos: `{ name, price }`. Somente leitura. |
| `importation` | `object \| null` | Metadados de importação: `{ id, source, date }`. |
| `user` | `object \| null` | Responsável. |
| `department` | `object \| null` | Departamento. |
| `calleds` | `array` | [Atendimentos vinculados](/crm/atendimentos.md), com o contato. |
| `contacts` | `array` | Contatos vinculados. |
| `subTasks` | `array` | [Itens de checklist](#itens-de-checklist). |
| `comments` | `array` | [Comentários](/crm/comentarios.md). Só em [Obter card](#obter-card). |

## Listar cards

```http theme={null}
GET /task
```

| Parâmetro | Descrição |
| - | - |
| `type` | `task` (padrão), `lead`, `item` ou `all`. `all` traz tudo, exceto itens de checklist. |
| `q` | Busca no título. |
| `limit` | Máximo de registros. |

Ordenado do mais recente para o mais antigo.

```bash theme={null}
curl -G https://api.hustapp.com/task \
  -H "Authorization: Bearer SEU_TOKEN" \
  --data-urlencode "type=lead" \
  --data-urlencode "q=empresa" \
  --data-urlencode "limit=50"
```

## Obter card

```http theme={null}
GET /task/{id}
```

Traz o card completo, com comentários, anexos, itens de checklist, atendimentos e contatos.

```bash theme={null}
curl https://api.hustapp.com/task/501 \
  -H "Authorization: Bearer SEU_TOKEN"
```

## Criar card

```http theme={null}
POST /task
```

| Campo | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `title` | `string` | Sim | Título. |
| `pipeline` | `object` | Sim | `{ id }` da pipeline. |
| `description` | `string` | Não | Descrição. |
| `called` | `object` | Não | `{ id }` de um atendimento para vincular ao card. |

Comportamento:

* O card entra na **primeira etapa** da pipeline.
* Se a pipeline não tiver etapas, as [etapas padrão](/crm/etapas.md#etapas-padrão) são criadas.
* O tipo do card segue o tipo da pipeline: `lead` em pipelines `lead`, `task` nas demais.
* Se a pipeline tiver `template`, a descrição e os itens de checklist do modelo são aplicados.

```bash cURL theme={null}
curl -X POST https://api.hustapp.com/task \
  -H "Authorization: Bearer SEU_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Empresa X",
    "description": "Lead vindo do site",
    "pipeline": { "id": 1 },
    "called": { "id": 9876 }
  }'
```

```javascript Node.js theme={null}
const res = await fetch("https://api.hustapp.com/task", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "Empresa X",
    description: "Lead vindo do site",
    pipeline: { id: 1 },
    called: { id: 9876 },
  }),
});

const card = await res.json();
```

```python Python theme={null}
import requests

card = requests.post(
    "https://api.hustapp.com/task",
    headers={"Authorization": f"Bearer {token}"},
    json={
        "title": "Empresa X",
        "description": "Lead vindo do site",
        "pipeline": {"id": 1},
        "called": {"id": 9876},
    },
).json()
```

```php PHP theme={null}
<?php
$ch = curl_init('https://api.hustapp.com/task');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'title' => 'Empresa X',
        'description' => 'Lead vindo do site',
        'pipeline' => ['id' => 1],
        'called' => ['id' => 9876],
    ]),
]);

$card = json_decode(curl_exec($ch), true);
curl_close($ch);
```

```pascal Delphi theme={null}
uses
  System.Net.HttpClient, System.Classes, System.JSON, System.SysUtils;

const
  Body =
    '{' +
    '  "title": "Empresa X",' +
    '  "description": "Lead vindo do site",' +
    '  "pipeline": { "id": 1 },' +
    '  "called": { "id": 9876 }' +
    '}';

var
  HttpClient: THTTPClient;
  Response: IHTTPResponse;
  Card: TJSONObject;
  CardId: Integer;
begin
  HttpClient := THTTPClient.Create;
  try
    HttpClient.CustomHeaders['Authorization'] := 'Bearer ' + Token;
    HttpClient.ContentType := 'application/json';
    Response := HttpClient.Post('https://api.hustapp.com/task',
      TStringStream.Create(Body, TEncoding.UTF8));

    Card := TJSONObject.ParseJSONValue(Response.ContentAsString) as TJSONObject;
    try
      CardId := Card.GetValue<Integer>('id');
    finally
      Card.Free;
    end;
  finally
    HttpClient.Free;
  end;
end;
```

Retorna `200` com o card criado.

## Atualizar card

```http theme={null}
PUT /task/{id}
```

Todos os campos são opcionais: envie só o que mudar.

| Campo | Tipo | Descrição |
| - | - | - |
| `title` | `string` | Título. |
| `description` | `string` | Descrição, em HTML. |
| `status` | `string` | [Status](/crm/visao-geral.md#status). |
| `priority` | `string` | [Prioridade](/crm/visao-geral.md#prioridade). |
| `dateStart` | `string` | Data de início. |
| `dateDue` | `string` | Vencimento. O responsável é avisado no WhatsApp quando o dia muda. |
| `valueUnique` | `number` | Valor único. |
| `valueRecurring` | `number` | Valor recorrente. |
| `user` | `object` | `{ id }` do responsável. O novo responsável é avisado no WhatsApp. |
| `pipeline` | `object` | `{ id }` de outra pipeline. **Transfere** o card para a primeira etapa dela, com o status dessa etapa. |

**Permissão:** gestor, responsável pelo card, ou qualquer usuário quando o card não tem responsável.

```bash cURL theme={null}
curl -X PUT https://api.hustapp.com/task/501 \
  -H "Authorization: Bearer SEU_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "status": "finished_win",
    "valueUnique": 2500,
    "valueRecurring": 300,
    "user": { "id": 12 }
  }'
```

```javascript Node.js theme={null}
const res = await fetch("https://api.hustapp.com/task/501", {
  method: "PUT",
  headers: {
    Authorization: `Bearer ${token}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    status: "finished_win",
    valueUnique: 2500,
    valueRecurring: 300,
    user: { id: 12 },
  }),
});

const card = await res.json();
```

```python Python theme={null}
import requests

card = requests.put(
    "https://api.hustapp.com/task/501",
    headers={"Authorization": f"Bearer {token}"},
    json={
        "status": "finished_win",
        "valueUnique": 2500,
        "valueRecurring": 300,
        "user": {"id": 12},
    },
).json()
```

```php PHP theme={null}
<?php
$ch = curl_init('https://api.hustapp.com/task/501');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'PUT',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'status' => 'finished_win',
        'valueUnique' => 2500,
        'valueRecurring' => 300,
        'user' => ['id' => 12],
    ]),
]);

$card = json_decode(curl_exec($ch), true);
curl_close($ch);
```

```pascal Delphi theme={null}
uses
  System.Net.HttpClient, System.Classes, System.SysUtils;

const
  Body =
    '{' +
    '  "status": "finished_win",' +
    '  "valueUnique": 2500,' +
    '  "valueRecurring": 300,' +
    '  "user": { "id": 12 }' +
    '}';

var
  HttpClient: THTTPClient;
  Response: IHTTPResponse;
begin
  HttpClient := THTTPClient.Create;
  try
    HttpClient.CustomHeaders['Authorization'] := 'Bearer ' + Token;
    HttpClient.ContentType := 'application/json';
    Response := HttpClient.Put('https://api.hustapp.com/task/501',
      TStringStream.Create(Body, TEncoding.UTF8));
  finally
    HttpClient.Free;
  end;
end;
```

| Status | Corpo |
| - | - |
| `200` | O card atualizado. |
| `403` | `{ "message": "Você não tem permissão para editar esta tarefa." }` |
| `500` | `INVALID_STATUS`, `INVALID_PRIORITY`, `TASK_NOT_FOUND` ou `PIPELINEDEST_NOT_FOUND`. |

> [!NOTE]
>
> Os avisos de WhatsApp saem pela conexão principal, não WABA, da empresa, para o telefone cadastrado do responsável.

## Mover card de etapa

```http theme={null}
PUT /task/{id}/stage/{idStage}
```

Move o card para a etapa e aplica o status dela. Retorna `200` com o card atualizado; use o `status` do retorno.

```bash cURL theme={null}
curl -X PUT https://api.hustapp.com/task/501/stage/11 \
  -H "Authorization: Bearer SEU_TOKEN"
```

```javascript Node.js theme={null}
const res = await fetch("https://api.hustapp.com/task/501/stage/11", {
  method: "PUT",
  headers: { Authorization: `Bearer ${token}` },
});

const { status } = await res.json();
```

```python Python theme={null}
import requests

card = requests.put(
    "https://api.hustapp.com/task/501/stage/11",
    headers={"Authorization": f"Bearer {token}"},
).json()
```

```php PHP theme={null}
<?php
$ch = curl_init('https://api.hustapp.com/task/501/stage/11');
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => 'PUT',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $token],
]);

$card = json_decode(curl_exec($ch), true);
curl_close($ch);
```

```pascal Delphi theme={null}
uses
  System.Net.HttpClient, System.Classes;

var
  HttpClient: THTTPClient;
  Response: IHTTPResponse;
begin
  HttpClient := THTTPClient.Create;
  try
    HttpClient.CustomHeaders['Authorization'] := 'Bearer ' + Token;
    Response := HttpClient.Put('https://api.hustapp.com/task/501/stage/11',
      TStringStream.Create(''));
  finally
    HttpClient.Free;
  end;
end;
```

## Reordenar cards

```http theme={null}
PUT /task/sequence
```

Atualiza a ordem e a etapa de cada card enviado, como no arrastar e soltar do Kanban. Se a etapa tiver status, ele é aplicado ao card. Envie todos os cards das etapas de origem e destino afetadas. Retorna `200` com `true`.

```json theme={null}
[
  { "id": 501, "sequence": 0, "stage": { "id": 10 } },
  { "id": 502, "sequence": 1, "stage": { "id": 10 } },
  { "id": 503, "sequence": 0, "stage": { "id": 11 } }
]
```

## Excluir card

```http theme={null}
DELETE /task/{id}
```

Remove o card com os itens de checklist, comentários e anexos, e desfaz os vínculos com atendimentos e contatos. Retorna `200` com `true`.

## Responsável

Para atribuir, use [Atualizar card](#atualizar-card) com `{ "user": { "id": 12 } }`.

Para remover, **somente gestor**:

```http theme={null}
DELETE /task/{id}/user
```

| Status | Corpo |
| - | - |
| `200` | `true` |
| `400` | `{ "message": "Você não tem permissão para remover o responsável desta tarefa." }` |

## Itens de checklist

Itens de checklist são cards do tipo `item` ligados a um card pai. Aparecem em `subTasks` do card pai.

| Ação | Requisição |
| - | - |
| Criar | `POST /task` com `{ "title": "Enviar contrato", "task": { "id": 501 } }`. Dispensa `pipeline`. |
| Concluir | `PUT /task/{idItem}` com `{ "status": "finished" }` |
| Reabrir | `PUT /task/{idItem}` com `{ "status": "pending" }` |
| Renomear | `PUT /task/{idItem}` com `{ "title": "Enviar contrato assinado" }` |
| Excluir | `DELETE /task/{idItem}` |

## Propostas vinculadas

```http theme={null}
GET /task/{id}/invoices
```

Lista as propostas e cobranças vinculadas ao card.

## Origens

```http theme={null}
GET /task/origin
```

Lista as origens de lead cadastradas na empresa.

| Campo | Tipo | Descrição |
| - | - | - |
| `id` | `integer` | Identificador. |
| `type` | `string` | `referral_client`, `referral_contact`, `referral_custom`, `campaign_meta_instagram`, `campaign_meta_facebook`, `campaign_google`, `campaign_hust`, `campaign_custom` ou `custom`. |
| `name` | `string` | Nome. |
| `details` | `object` | Dados livres. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.