Filtros e Busca de Notas

Este exemplo mostra como usar os filtros disponíveis na API para buscar notas específicas.

Filtros Básicos

Buscar por Status

# Buscar apenas notas processadas
curl -X GET "https://api-sandbox.connectvets.com.br/notes/v1/notes?transcription_status=completed" \
  -H "X-API-KEY: sua_api_key_aqui"

# Buscar notas com erro
curl -X GET "https://api-sandbox.connectvets.com.br/notes/v1/notes?transcription_status=failed" \
  -H "X-API-KEY: sua_api_key_aqui"

Filtrar por Data

# Notas de um período específico
curl -X GET "https://api-sandbox.connectvets.com.br/notes/v1/notes?from=2024-01-01&to=2024-01-31" \
  -H "X-API-KEY: sua_api_key_aqui"

# Notas dos últimos 7 dias
curl -X GET "https://api-sandbox.connectvets.com.br/notes/v1/notes?days=7" \
  -H "X-API-KEY: sua_api_key_aqui"

Buscar por Nome do Paciente

# Buscar paciente específico
curl -X GET "https://api-sandbox.connectvets.com.br/notes/v1/notes?name=Rex" \
  -H "X-API-KEY: sua_api_key_aqui"

Implementações por Linguagem

JavaScript/Node.js

class NotesFilter {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api-sandbox.connectvets.com.br/notes/v1';
  }

  async searchNotes(filters = {}) {
    const params = new URLSearchParams();
    
    // Adicionar filtros à query
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== null && value !== undefined && value !== '') {
        params.append(key, value);
      }
    });

    const response = await fetch(`${this.baseUrl}/notes?${params}`, {
      headers: {
        'X-API-KEY': this.apiKey,
        'Content-Type': 'application/json'
      }
    });

    return await response.json();
  }

  // Filtros específicos
  async getCompletedNotes(page = 1, limit = 10) {
    return this.searchNotes({
      transcription_status: 'completed',
      page,
      limit
    });
  }

  async getNotesByDateRange(from, to) {
    return this.searchNotes({
      from: from, // YYYY-MM-DD
      to: to,     // YYYY-MM-DD
      transcription_status: 'completed'
    });
  }

  async getPatientNotes(patientName) {
    return this.searchNotes({
      name: patientName,
      transcription_status: 'completed'
    });
  }

  async getRecentNotes(days = 7) {
    const to = new Date().toISOString().split('T')[0];
    const from = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
      .toISOString().split('T')[0];

    return this.getNotesByDateRange(from, to);
  }
}

// Exemplos de uso
async function examples() {
  const filter = new NotesFilter(process.env.CONNECTVETS_API_KEY);

  try {
    // Buscar notas processadas hoje
    const today = new Date().toISOString().split('T')[0];
    const todayNotes = await filter.getNotesByDateRange(today, today);
    console.log('Notas de hoje:', todayNotes.data.length);

    // Buscar notas de um paciente específico
    const rexNotes = await filter.getPatientNotes('Rex');
    console.log('Notas do Rex:', rexNotes.data.length);

    // Buscar notas dos últimos 30 dias
    const recentNotes = await filter.getRecentNotes(30);
    console.log('Notas recentes:', recentNotes.data.length);

    // Busca personalizada
    const customSearch = await filter.searchNotes({
      transcription_status: 'completed',
      from: '2024-01-01',
      limit: 50
    });
    console.log('Busca personalizada:', customSearch.data.length);

  } catch (error) {
    console.error('Erro na busca:', error);
  }
}

examples();

Python

import requests
from datetime import datetime, timedelta
from typing import Dict, List, Optional

class NotesFilter:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api-sandbox.connectvets.com.br/notes/v1"
        self.session = requests.Session()
        self.session.headers.update({"X-API-KEY": api_key})
    
    def search_notes(self, filters: Dict = None) -> Dict:
        """Buscar notas com filtros"""
        params = {}
        
        if filters:
            # Remover valores vazios
            params = {k: v for k, v in filters.items() 
                     if v is not None and v != ''}
        
        response = self.session.get(f"{self.base_url}/notes", params=params)
        response.raise_for_status()
        return response.json()
    
    def get_completed_notes(self, page: int = 1, limit: int = 10) -> Dict:
        """Buscar apenas notas processadas"""
        return self.search_notes({
            'transcription_status': 'completed',
            'page': page,
            'limit': limit
        })
    
    def get_notes_by_date_range(self, from_date: str, to_date: str) -> Dict:
        """Buscar notas por período (YYYY-MM-DD)"""
        return self.search_notes({
            'from': from_date,
            'to': to_date,
            'transcription_status': 'completed'
        })
    
    def get_patient_notes(self, patient_name: str) -> Dict:
        """Buscar notas de um paciente específico"""
        return self.search_notes({
            'name': patient_name,
            'transcription_status': 'completed'
        })
    
    def get_recent_notes(self, days: int = 7) -> Dict:
        """Buscar notas dos últimos X dias"""
        to_date = datetime.now().strftime('%Y-%m-%d')
        from_date = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')
        
        return self.get_notes_by_date_range(from_date, to_date)

# Exemplos de uso
def main():
    filter_client = NotesFilter(os.getenv('CONNECTVETS_API_KEY'))
    
    try:
        # Buscar notas de hoje
        today = datetime.now().strftime('%Y-%m-%d')
        today_notes = filter_client.get_notes_by_date_range(today, today)
        print(f"Notas de hoje: {len(today_notes['data'])}")
        
        # Buscar notas de um paciente
        rex_notes = filter_client.get_patient_notes('Rex')
        print(f"Notas do Rex: {len(rex_notes['data'])}")
        
        # Buscar notas dos últimos 30 dias
        recent_notes = filter_client.get_recent_notes(30)
        print(f"Notas recentes: {len(recent_notes['data'])}")
        
        # Busca personalizada
        custom_search = filter_client.search_notes({
            'transcription_status': 'completed',
            'from': '2024-01-01',
            'limit': 50
        })
        print(f"Busca personalizada: {len(custom_search['data'])}")
        
    except Exception as e:
        print(f"Erro: {e}")

if __name__ == "__main__":
    main()

PHP

<?php

class NotesFilter {
    private $apiKey;
    private $baseUrl = 'https://api-sandbox.connectvets.com.br/notes/v1';
    
    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
    }
    
    public function searchNotes($filters = []) {
        // Remover valores vazios
        $params = array_filter($filters, function($value) {
            return $value !== null && $value !== '';
        });
        
        $url = $this->baseUrl . '/notes';
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'X-API-KEY: ' . $this->apiKey,
                'Content-Type: application/json'
            ]
        ]);
        
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        
        if ($httpCode !== 200) {
            throw new Exception('Erro na busca: ' . $response);
        }
        
        return json_decode($response, true);
    }
    
    public function getCompletedNotes($page = 1, $limit = 10) {
        return $this->searchNotes([
            'transcription_status' => 'completed',
            'page' => $page,
            'limit' => $limit
        ]);
    }
    
    public function getNotesByDateRange($fromDate, $toDate) {
        return $this->searchNotes([
            'from' => $fromDate,
            'to' => $toDate,
            'transcription_status' => 'completed'
        ]);
    }
    
    public function getPatientNotes($patientName) {
        return $this->searchNotes([
            'name' => $patientName,
            'transcription_status' => 'completed'
        ]);
    }
    
    public function getRecentNotes($days = 7) {
        $toDate = date('Y-m-d');
        $fromDate = date('Y-m-d', strtotime("-{$days} days"));
        
        return $this->getNotesByDateRange($fromDate, $toDate);
    }
}

// Exemplos de uso
try {
    $filter = new NotesFilter($_ENV['CONNECTVETS_API_KEY']);
    
    // Buscar notas de hoje
    $today = date('Y-m-d');
    $todayNotes = $filter->getNotesByDateRange($today, $today);
    echo "Notas de hoje: " . count($todayNotes['data']) . "\n";
    
    // Buscar notas de um paciente
    $rexNotes = $filter->getPatientNotes('Rex');
    echo "Notas do Rex: " . count($rexNotes['data']) . "\n";
    
    // Buscar notas dos últimos 30 dias
    $recentNotes = $filter->getRecentNotes(30);
    echo "Notas recentes: " . count($recentNotes['data']) . "\n";
    
} catch (Exception $e) {
    echo "Erro: " . $e->getMessage() . "\n";
}
?>

Parâmetros de Filtro Disponíveis

ParâmetroTipoDescriçãoExemplo
transcription_statusStringStatus da transcriçãocompleted, processing, failed
nameStringNome do paciente (busca parcial)Rex, Mia
fromDateData inicial (YYYY-MM-DD)2024-01-01
toDateData final (YYYY-MM-DD)2024-01-31
daysIntegerÚltimos X dias7, 30
pageIntegerPágina (paginação)1, 2, 3
limitIntegerLimite por página10, 50, 100
external_idStringID do seu sistemaCLIENTE_123

Combinando Filtros

Busca Complexa

// Buscar notas processadas do último mês de pacientes específicos
const complexSearch = await filter.searchNotes({
  transcription_status: 'completed',
  from: '2024-01-01',
  to: '2024-01-31',
  limit: 100
});

// Filtrar ainda mais nos resultados (lado cliente)
const dogNotes = complexSearch.data.filter(note => 
  note.name.toLowerCase().includes('rex') || 
  note.name.toLowerCase().includes('bob')
);

Paginação

async function getAllNotes(filters = {}) {
  const allNotes = [];
  let page = 1;
  const limit = 50;
  
  while (true) {
    const response = await filter.searchNotes({
      ...filters,
      page,
      limit
    });
    
    if (response.data.length === 0) break;
    
    allNotes.push(...response.data);
    page++;
    
    // Limite de segurança
    if (page > 100) break;
  }
  
  return allNotes;
}

Casos de Uso Práticos

1. Relatório Diário

async function dailyReport(date) {
  const notes = await filter.getNotesByDateRange(date, date);
  
  const stats = {
    total: notes.data.length,
    completed: notes.data.filter(n => n.transcription_status === 'completed').length,
    failed: notes.data.filter(n => n.transcription_status === 'failed').length
  };
  
  console.log(`Relatório de ${date}:`);
  console.log(`Total: ${stats.total}`);
  console.log(`Processadas: ${stats.completed}`);
  console.log(`Com erro: ${stats.failed}`);
  
  return stats;
}

2. Buscar Histórico do Paciente

async function getPatientHistory(patientName) {
  const notes = await filter.getPatientNotes(patientName);
  
  // Ordenar por data (mais recente primeiro)
  const sortedNotes = notes.data.sort((a, b) => 
    new Date(b.created_at) - new Date(a.created_at)
  );
  
  return sortedNotes.map(note => ({
    id: note.id,
    date: note.created_at.split('T')[0],
    status: note.transcription_status,
    sections: note.note_sections?.length || 0
  }));
}

3. Monitorar Falhas

async function checkFailures() {
  const failedNotes = await filter.searchNotes({
    transcription_status: 'failed',
    days: 1 // Último dia
  });
  
  if (failedNotes.data.length > 0) {
    console.log(`⚠️ ${failedNotes.data.length} notas falharam nas últimas 24h`);
    
    failedNotes.data.forEach(note => {
      console.log(`- ${note.id}: ${note.name} (${note.created_at})`);
    });
  }
  
  return failedNotes.data;
}

Otimização de Performance

Cache de Resultados

class CachedNotesFilter extends NotesFilter {
  constructor(apiKey) {
    super(apiKey);
    this.cache = new Map();
    this.cacheTimeout = 5 * 60 * 1000; // 5 minutos
  }
  
  async searchNotes(filters = {}) {
    const cacheKey = JSON.stringify(filters);
    const cached = this.cache.get(cacheKey);
    
    if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
      console.log('📋 Resultado do cache');
      return cached.data;
    }
    
    const result = await super.searchNotes(filters);
    
    this.cache.set(cacheKey, {
      data: result,
      timestamp: Date.now()
    });
    
    return result;
  }
}

Dica: Use paginação para grandes volumes de dados e implemente cache para melhorar a performance.