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

# Manage Closing Date

> Gerencia datas de fechamento de cartões de crédito. Permite listar contas, criar, atualizar, deletar e consultar datas de fechamento. Requer API key para autenticação e assinatura ativa.

<Note>
  Gerencia datas de fechamento de faturas de cartões de crédito: listar contas elegíveis, criar, atualizar, deletar e obter datas de fechamento. Este endpoint replica a lógica da ferramenta `manageClosingDate` via REST usando API key.

  É importante para que o Pierre possa buscar as datas de fechamento das contas de cartão de crédito e calcular os valores das faturas.
</Note>

## Descrição

O endpoint `POST /tools/api/manage-closing-date` permite:

* `LIST_ACCOUNTS`: lista contas de cartão de crédito e indica quais já possuem data de fechamento configurada
* `INSERT`: cria uma data de fechamento para uma conta
* `UPDATE`: atualiza uma data de fechamento existente (dia, status ativo e notas)
* `DELETE`: remove uma data de fechamento
* `GET`: obtém datas de fechamento (todas ou de uma conta específica)

## Autenticação

Este endpoint requer autenticação via Bearer token e assinatura ativa.

<ParamField header="Authorization" type="string" required>
  Bearer token com a API key do usuário. Formato: `Bearer sk-your-api-key-here`
</ParamField>

## Parâmetros (Body JSON)

<ParamField name="operation" type="string" required>
  Operação a executar. Valores: `LIST_ACCOUNTS`, `INSERT`, `UPDATE`, `DELETE`, `GET`
</ParamField>

<ParamField name="accountId" type="string">
  ID da conta (obrigatório para `INSERT` e `UPDATE`)
</ParamField>

<ParamField name="closingDay" type="number">
  Dia do mês de fechamento (1-31). Necessário para `INSERT`; opcional em `UPDATE`
</ParamField>

<ParamField name="isActive" type="boolean">
  Se a data de fechamento está ativa (opcional em `INSERT`/`UPDATE`)
</ParamField>

<ParamField name="notes" type="string">
  Notas opcionais sobre a data de fechamento
</ParamField>

<ParamField name="closingDateId" type="string">
  ID da data de fechamento (obrigatório para `DELETE`; opcional em `UPDATE`)
</ParamField>

## Respostas por Operação

### LIST\_ACCOUNTS

<ResponseExample>
  ```json 200 OK theme={null}
  {
    "success": true,
    "message": "Credit card accounts retrieved successfully",
    "data": {
      "accounts": [
        {
          "id": "acc_abc",
          "name": "Cartão XP",
          "marketingName": "Visa Gold",
          "number": "**** 1234",
          "hasClosingDate": true,
          "closingDay": 10,
          "isActive": true,
          "notes": "Fecho no dia 10"
        }
      ],
      "totalAccounts": 1,
      "accountsWithClosingDate": 1,
      "accountsWithoutClosingDate": 0
    },
    "timestamp": "2024-05-15T10:30:00Z"
  }
  ```
</ResponseExample>

### INSERT

<ResponseExample>
  ```json 200 OK theme={null}
  {
    "success": true,
    "message": "Closing date created successfully",
    "data": {
      "accountId": "acc_abc",
      "closingDay": 10,
      "isActive": true,
      "notes": "Fecho no dia 10"
    },
    "timestamp": "2024-05-15T10:30:00Z"
  }
  ```
</ResponseExample>

### UPDATE

<ResponseExample>
  ```json 200 OK theme={null}
  {
    "success": true,
    "message": "Closing date updated successfully",
    "data": {
      "id": "cld_123",
      "accountId": "acc_abc",
      "closingDay": 12,
      "isActive": true,
      "notes": "Atualizado para dia 12"
    },
    "timestamp": "2024-05-15T10:30:00Z"
  }
  ```
</ResponseExample>

### DELETE

<ResponseExample>
  ```json 200 OK theme={null}
  {
    "success": true,
    "message": "Closing date deleted successfully",
    "data": {
      "deletedId": "cld_123",
      "accountId": "acc_abc"
    },
    "timestamp": "2024-05-15T10:30:00Z"
  }
  ```
</ResponseExample>

### GET

<ResponseExample>
  ```json 200 OK (com accountId) theme={null}
  {
    "success": true,
    "message": "Closing date retrieved successfully",
    "data": {
      "id": "cld_123",
      "userId": "usr_123",
      "accountId": "acc_abc",
      "closingDay": 10,
      "isActive": true,
      "notes": "Fecho no dia 10",
      "createdAt": "2024-05-01T00:00:00.000Z",
      "updatedAt": "2024-05-10T00:00:00.000Z"
    },
    "timestamp": "2024-05-15T10:30:00Z"
  }
  ```
</ResponseExample>

<ResponseExample>
  ```json 200 OK (sem accountId) theme={null}
  {
    "success": true,
    "message": "All closing dates retrieved successfully",
    "data": [
      {
        "id": "cld_123",
        "accountId": "acc_abc",
        "closingDay": 10,
        "isActive": true,
        "notes": "Fecho no dia 10"
      }
    ],
    "timestamp": "2024-05-15T10:30:00Z"
  }
  ```
</ResponseExample>

## Erros Comuns

<ResponseExample>
  ```json 400 Bad Request theme={null}
  { "error": "Account ID and closing day are required for INSERT operation" }
  ```
</ResponseExample>

<ResponseExample>
  ```json 403 Forbidden theme={null}
  { "error": "Closing date does not belong to user" }
  ```
</ResponseExample>

<ResponseExample>
  ```json 401 Unauthorized theme={null}
  {
    "error": "Invalid or inactive API key",
    "type": "invalid_api_key"
  }
  ```
</ResponseExample>

## Exemplos de Uso

Este endpoint suporta **5 operações diferentes** através do parâmetro `operation`. Cada exemplo abaixo demonstra como executar uma operação específica:

### cURL - Todas as Operações

```bash theme={null}
# 1. LIST_ACCOUNTS - Listar contas de cartão elegíveis
curl -X POST 'https://www.pierre.finance/tools/api/manage-closing-date' \
  -H 'Authorization: Bearer sk-your-api-key-here' \
  -H 'Content-Type: application/json' \
  -d '{"operation":"LIST_ACCOUNTS"}'

# 2. INSERT - Criar nova data de fechamento
curl -X POST 'https://www.pierre.finance/tools/api/manage-closing-date' \
  -H 'Authorization: Bearer sk-your-api-key-here' \
  -H 'Content-Type: application/json' \
  -d '{"operation":"INSERT","accountId":"acc_abc","closingDay":10,"isActive":true,"notes":"Fecho no dia 10"}'

# 3. UPDATE - Atualizar data de fechamento existente
curl -X POST 'https://www.pierre.finance/tools/api/manage-closing-date' \
  -H 'Authorization: Bearer sk-your-api-key-here' \
  -H 'Content-Type: application/json' \
  -d '{"operation":"UPDATE","accountId":"acc_abc","closingDay":12,"notes":"Atualizado para dia 12"}'

# 4. DELETE - Remover data de fechamento
curl -X POST 'https://www.pierre.finance/tools/api/manage-closing-date' \
  -H 'Authorization: Bearer sk-your-api-key-here' \
  -H 'Content-Type: application/json' \
  -d '{"operation":"DELETE","closingDateId":"cld_123"}'

# 5. GET - Consultar data de fechamento específica
curl -X POST 'https://www.pierre.finance/tools/api/manage-closing-date' \
  -H 'Authorization: Bearer sk-your-api-key-here' \
  -H 'Content-Type: application/json' \
  -d '{"operation":"GET","accountId":"acc_abc"}'

# 6. GET - Consultar todas as datas de fechamento do usuário
curl -X POST 'https://www.pierre.finance/tools/api/manage-closing-date' \
  -H 'Authorization: Bearer sk-your-api-key-here' \
  -H 'Content-Type: application/json' \
  -d '{"operation":"GET"}'
```

### JavaScript - Exemplos por Operação

```javascript theme={null}
const API_KEY = 'sk-your-api-key-here';
const BASE_URL = 'https://www.pierre.finance/tools/api/manage-closing-date';

async function manageClosingDate(body) {
  const res = await fetch(BASE_URL, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });
  return await res.json();
}

// 1. Listar contas de cartão elegíveis
const accounts = await manageClosingDate({ operation: 'LIST_ACCOUNTS' });

// 2. Criar nova data de fechamento
const created = await manageClosingDate({ 
  operation: 'INSERT', 
  accountId: 'acc_abc', 
  closingDay: 10,
  isActive: true,
  notes: 'Fecho no dia 10'
});

// 3. Atualizar data existente
const updated = await manageClosingDate({ 
  operation: 'UPDATE', 
  accountId: 'acc_abc', 
  closingDay: 12,
  notes: 'Atualizado para dia 12'
});

// 4. Remover data de fechamento
const deleted = await manageClosingDate({ 
  operation: 'DELETE', 
  closingDateId: 'cld_123' 
});

// 5. Consultar data específica
const specific = await manageClosingDate({ 
  operation: 'GET', 
  accountId: 'acc_abc' 
});

// 6. Consultar todas as datas do usuário
const all = await manageClosingDate({ operation: 'GET' });
```

### Python - Exemplos por Operação

```python theme={null}
import requests

API_KEY = 'sk-your-api-key-here'
BASE_URL = 'https://www.pierre.finance/tools/api/manage-closing-date'

headers = {
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json'
}

def manage_closing_date(body):
    response = requests.post(BASE_URL, headers=headers, json=body)
    return response.json()

# 1. Listar contas de cartão elegíveis
accounts = manage_closing_date({'operation': 'LIST_ACCOUNTS'})

# 2. Criar nova data de fechamento
created = manage_closing_date({
    'operation': 'INSERT', 
    'accountId': 'acc_abc', 
    'closingDay': 10,
    'isActive': True,
    'notes': 'Fecho no dia 10'
})

# 3. Atualizar data existente
updated = manage_closing_date({
    'operation': 'UPDATE', 
    'accountId': 'acc_abc', 
    'closingDay': 12,
    'notes': 'Atualizado para dia 12'
})

# 4. Remover data de fechamento
deleted = manage_closing_date({
    'operation': 'DELETE', 
    'closingDateId': 'cld_123'
})

# 5. Consultar data específica
specific = manage_closing_date({
    'operation': 'GET', 
    'accountId': 'acc_abc'
})

# 6. Consultar todas as datas do usuário
all_dates = manage_closing_date({'operation': 'GET'})
```


## OpenAPI

````yaml POST /tools/api/manage-closing-date
openapi: 3.1.0
info:
  title: Pierre Finance API
  description: >-
    API para acessar dados financeiros do Pierre Finance, incluindo contas,
    transações, parcelas e sincronização.
  version: v1.0.0
servers:
  - url: https://www.pierre.finance
security: []
tags:
  - name: Authentication
    description: API key management and authentication
  - name: Accounts
    description: Financial accounts management
  - name: Transactions
    description: Financial transactions
  - name: Installments
    description: Credit card installments and purchases
  - name: Bills
    description: Credit card bills and current bill summaries
  - name: Balance
    description: Account balance information
  - name: Closing Dates
    description: Credit card closing date management
  - name: Sync
    description: Account synchronization
  - name: Spending Limits
    description: Personal spending limits and alerts management
  - name: Payment Reminders
    description: Payment reminders management with WhatsApp and Email notifications
  - name: Analytics
    description: Financial analytics and insights
  - name: Memories
    description: User memory management for personalized AI interactions
  - name: Open Finance
    description: Open Finance connection and integration
paths:
  /tools/api/manage-closing-date:
    post:
      tags:
        - Closing Dates
      description: >-
        Gerencia datas de fechamento de cartões de crédito. Permite listar
        contas, criar, atualizar, deletar e consultar datas de fechamento.
        Requer API key para autenticação e assinatura ativa.
      operationId: manageClosingDate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ManageClosingDateRequest'
      responses:
        '200':
          description: Operação realizada com sucesso
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ListAccountsResponse'
                  - $ref: '#/components/schemas/ClosingDateOperationResponse'
        '400':
          description: Parâmetros inválidos
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                  details:
                    type: array
                    items:
                      type: object
        '401':
          $ref: '#/components/responses/AuthError'
        '403':
          description: Acesso negado
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Closing date does not belong to user
        '404':
          description: Recurso não encontrado
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    example: Closing date not found or does not belong to user
        '500':
          $ref: '#/components/responses/ServerError'
      security:
        - BearerAuth: []
components:
  schemas:
    ManageClosingDateRequest: {}
    ListAccountsResponse: {}
    ClosingDateOperationResponse: {}
    AuthError: {}
    ServerError: {}
  responses:
    AuthError:
      description: Authentication or subscription error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/AuthError'
    ServerError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ServerError'
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: string
      description: 'API key in Bearer token format. Example: Bearer sk-your-api-key-here'

````