Passo 01: Sistema de Rastreamento de Fluxo - Telegram Webhook

⚠️ INSTRUÇÕES IMPORTANTES ANTES DE COMEÇAR

Para evitar erros durante a implementação, siga EXATAMENTE estas etapas:

1. Ler o template COMPLETO da página

  • Leia toda a documentação antes de começar
  • Entenda o fluxo completo de implementação
  • Identifique dependências entre os passos

2. Identificar TODOS os arquivos mencionados

  • Liste todos os arquivos que serão criados/modificados
  • Verifique se já existem no projeto
  • Anote o caminho exato de cada arquivo

3. Verificar a estrutura EXATA de cada arquivo

  • Confirme namespaces e imports corretos
  • Verifique se dependências estão instaladas
  • Valide sintaxe PHP antes de implementar

4. Implementar linha por linha conforme template

  • Copie o código EXATAMENTE como mostrado
  • Não modifique namespaces ou imports
  • Execute comandos na ordem especificada

🚨 ATENÇÃO:

  • NÃO pule etapas - cada passo tem dependências
  • NÃO modifique o código fornecido sem entender as consequências
  • SEMPRE teste após cada implementação
  • MANTENHA backup antes de grandes alterações

📋 Visão Geral

Sistema de rastreamento de fluxo de mensagens que monitora a execução de métodos e gera relatórios detalhados. Depende do sistema de logging e pode ser reutilizado em outros projetos.

🚀 Comando de Implementação

implementar sistema rastreamento fluxo telegram

⚙️ Pré-requisitos

  1. Sistema de Logging implementado
  2. Laravel instalado
  3. PHP 8.0+ configurado

📁 Arquivos do Módulo

🏗️ Contracts

  • `app/Contracts/MessageFlowTrackerInterface.php`
    1. Interface para rastreamento de fluxo de mensagens
    2. Define métodos para tracking de execução
    3. Geração de relatórios
  • `app/Contracts/MessageTrackingInterface.php`
    1. Interface para classes que precisam de tracking
    2. Define métodos de inicialização e finalização

🔧 Services

  • `app/Services/MessageFlowTrackerService.php`
    1. Implementação principal do rastreamento
    2. Cache de execuções
    3. Geração de relatórios
    4. Integração com logging

🏭 Providers

  • `app/Providers/MessageFlowServiceProvider.php`
    1. Service Provider para injeção de dependência
    2. Configuração de tracking

⚙️ Configurações

  • `config/message-flow.php`
    1. Configuração de rastreamento
    2. Timeouts e limites
    3. Configurações de cache

🔧 Implementação Passo a Passo

Passo 1: Criar Interfaces

<?php
 
namespace App\Contracts;
 
interface MessageFlowTrackerInterface
{
    // Core tracking methods
    public function trackMethod(string $className, string $methodName, array $inputData = [], array $outputData = []): void;
    public function endMethod(string $className, string $methodName, array $outputData = []): void;
 
    // Report generation
    public function generateFlowReport(array $payload): string;
    public function generateUserReport(array $payload): string;
 
    // Pipeline control
    public function startTracking(string $messageId): void;
    public function endTracking(): void;
    public function clearTrace(): void;
 
    // Data retrieval
    public function getExecutedMethods(): array;
    public function getExpectedMethods(): array;
    public function getMethodData(): array;
 
    // Utility methods
    public function identifyMessageType(array $payload): string;
    public function saveTrace(): void;
    public function isEnabled(): bool;
}
<?php
 
namespace App\Contracts;
 
/**
 * Interface para métodos de tracking de mensagens
 * Esta interface define os métodos que devem estar disponíveis
 * para qualquer classe que precise rastrear execução de métodos
 */
interface MessageTrackingInterface
{
    /**
     * Inicia o tracking de um método
     */
    public function trackMethod(string $methodName, array $inputData = [], array $outputData = []): void;
 
    /**
     * Finaliza o tracking de um método
     */
    public function endMethod(string $methodName, array $outputData = []): void;
 
    /**
     * Inicializa o sistema de tracking
     */
    public function initializeTracking(): void;
}

Passo 2: Implementar Service

<?php
 
namespace App\Services;
 
use App\Contracts\MessageFlowTrackerInterface;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
 
class MessageFlowTrackerService implements MessageFlowTrackerInterface
{
    private array $executedMethods = [];
    private array $expectedMethods = [];
    private array $methodData = [];
    private array $timestamps = [];
    private string $messageId;
    private bool $isEnabled;
 
    public function __construct()
    {
        $this->isEnabled = config('message-flow.enabled', false);
        $this->messageId = uniqid('msg_', true);
 
        // Define o fluxo esperado para cada tipo de mensagem
        $this->expectedMethods = [
            'text' => [
                'TelegramMessageProcessorService.processWebhookPayload',
                'TelegramMessageProcessorService.processTextMessage',
                'TelegramBotService.processMessage',
                // UnifiedCommandSystem is the current command processor; optional to track
                // 'UnifiedCommandSystem.processCommand',
                // Response can be sent via keyboard or plain text; we track keyboard variant
                'TelegramChannel.sendMessageWithKeyboard'
            ],
            'voice' => [
                'TelegramMessageProcessorService.processWebhookPayload',
                'TelegramMessageProcessorService.processVoiceMessage',
                'SpeechToTextService.convertVoiceToText',
                'TelegramBotService.processMessage',
                // Response can be via sendTextMessage or sendMessageWithKeyboard
                'TelegramChannel.sendMessageWithKeyboard'
            ],
            'callback_query' => [
                'TelegramMessageProcessorService.processWebhookPayload',
                'TelegramMessageProcessorService.processCallbackQuery',
                'TelegramBotService.processCallbackQuery',
                'TelegramChannel.sendTextMessage'
            ]
        ];
    }
 
    /**
     * Método interno para tracking (usado pelo trait)
     */
    public function trackMethodInternal(string $className, string $methodName, array $inputData = [], array $outputData = []): void
    {
        $this->trackMethod($className, $methodName, $inputData, $outputData);
    }
 
    /**
     * Registra que um método foi executado
     */
    public function trackMethod(string $className, string $methodName, array $inputData = [], array $outputData = []): void
    {
        if (!$this->isEnabled) return;
 
        $methodKey = "{$className}.{$methodName}";
        $startTime = microtime(true);
 
        $this->executedMethods[] = $methodKey;
        $this->methodData[$methodKey] = [
            'input' => $inputData,
            'output' => $outputData,
            'start_time' => $startTime,
            'execution_time' => 0
        ];
 
        $this->timestamps[$methodKey] = $startTime;
 
        Log::info("Message flow: Method executed", [
            'message_id' => $this->messageId,
            'method' => $methodKey,
            'input_data' => $inputData
        ]);
    }
 
    /**
     * Método interno para finalizar tracking (usado pelo trait)
     */
    public function endMethodInternal(string $className, string $methodName, array $outputData = []): void
    {
        $this->endMethod($className, $methodName, $outputData);
    }
 
    /**
     * Finaliza o tracking de um método
     */
    public function endMethod(string $className, string $methodName, array $outputData = []): void
    {
        if (!$this->isEnabled) return;
 
        $methodKey = "{$className}.{$methodName}";
 
        if (isset($this->methodData[$methodKey])) {
            $endTime = microtime(true);
            $startTime = $this->methodData[$methodKey]['start_time'];
            $executionTime = ($endTime - $startTime) * 1000; // em milissegundos
 
            $this->methodData[$methodKey]['output'] = $outputData;
            $this->methodData[$methodKey]['execution_time'] = $executionTime;
            $this->methodData[$methodKey]['end_time'] = $endTime;
        }
    }
 
    /**
     * Identifica o tipo de mensagem baseado no payload
     */
    public function identifyMessageType(array $payload): string
    {
        if (isset($payload['callback_query'])) return 'callback_query';
        if (isset($payload['message']['voice'])) return 'voice';
        if (isset($payload['message']['text'])) return 'text';
        return 'unknown';
    }
 
    /**
     * Gera relatório completo do fluxo
     */
    public function generateFlowReport(array $payload): string
    {
        if (!$this->isEnabled) return '';
 
        $messageType = $this->identifyMessageType($payload);
        $expectedMethods = $this->expectedMethods[$messageType] ?? [];
 
        $report = "🔄 **Rastreamento da Mensagem**\n\n";
        $report .= "📋 **Informações Gerais**\n";
        $report .= "• ID da Mensagem: `{$this->messageId}`\n";
        $report .= "• Tipo: " . $this->getMessageTypeEmoji($messageType) . " " . strtoupper($messageType) . "\n";
        $report .= "• Conteúdo: " . $this->extractMessageContent($payload) . "\n";
        $report .= "• Timestamp: " . now()->format('H:i:s.u') . "\n\n";
 
        $report .= "✅ **Métodos Executados**\n";
        if (empty($this->executedMethods)) {
            $report .= "❌ Nenhum método foi executado!\n\n";
        } else {
            foreach ($this->executedMethods as $index => $method) {
                $methodData = $this->methodData[$method] ?? [];
                $executionTime = $methodData['execution_time'] ?? 0;
 
                $report .= ($index + 1) . ". **{$method}**\n";
                $report .= "   ⏱️ Tempo: " . round($executionTime, 2) . "ms\n";
 
                if (!empty($methodData['input'])) {
                    $report .= "   📥 Entrada: " . $this->summarizeData($methodData['input']) . "\n";
                }
 
                if (!empty($methodData['output'])) {
                    $report .= "   📤 Saída: " . $this->summarizeData($methodData['output']) . "\n";
                }
 
                $report .= "\n";
            }
        }
 
        $report .= "❌ **Métodos NÃO Executados (Esperados)**\n";
        $missingMethods = array_diff($expectedMethods, $this->executedMethods);
 
        // OR logic for response methods on text and voice messages
        if ($messageType === 'text' || $messageType === 'voice') {
            $responseOr = [
                'TelegramChannel.sendMessageWithKeyboard',
                'TelegramChannel.sendTextMessage'
            ];
            $executedResponse = array_intersect($this->executedMethods, $responseOr);
            if (!empty($executedResponse)) {
                $missingMethods = array_values(array_diff($missingMethods, $responseOr));
            }
        }
 
        if (empty($missingMethods)) {
            $report .= "✅ Todos os métodos esperados foram executados!\n\n";
        } else {
            foreach ($missingMethods as $method) {
                $report .= "• **{$method}** - ❌ NÃO EXECUTADO\n";
            }
            $report .= "\n";
        }
 
        $report .= "⚠️ **Análise do Problema**\n";
        if (!empty($missingMethods)) {
            $report .= "A mensagem não foi processada completamente porque:\n";
            foreach ($missingMethods as $method) {
                $report .= "• " . $this->explainMissingMethod($method) . "\n";
            }
        } else {
            $report .= "Todos os métodos foram executados com sucesso.\n";
        }
 
        $report .= "\n🔧 **Dicas para Debug**\n";
        $report .= "• Verifique logs do Laravel para erros\n";
        $report .= "• Confirme se todos os serviços estão ativos\n";
        $report .= "• Verifique permissões e configurações\n";
 
        return $report;
    }
 
    /**
     * Gera relatório resumido para o usuário
     */
    public function generateUserReport(array $payload): string
    {
        if (!$this->isEnabled) return '';
 
        $messageType = $this->identifyMessageType($payload);
        $expectedMethods = $this->expectedMethods[$messageType] ?? [];
        $missingMethods = array_diff($expectedMethods, $this->executedMethods);
 
        // OR logic for response methods on text and voice messages
        if ($messageType === 'text' || $messageType === 'voice') {
            $responseOr = [
                'TelegramChannel.sendMessageWithKeyboard',
                'TelegramChannel.sendTextMessage'
            ];
            $executedResponse = array_intersect($this->executedMethods, $responseOr);
            if (!empty($executedResponse)) {
                $missingMethods = array_values(array_diff($missingMethods, $responseOr));
            }
        }
 
        if (empty($missingMethods)) {
            return "✅ Sua mensagem foi processada com sucesso em todas as etapas!";
        }
 
        $report = "❌ Sua mensagem não foi processada completamente.\n\n";
        $report .= "**Etapas executadas:** " . count($this->executedMethods) . "/" . count($expectedMethods) . "\n\n";
 
        if (count($missingMethods) <= 3) {
            $report .= "**Etapas que falharam:**\n";
            foreach ($missingMethods as $method) {
                $report .= "• " . $this->getUserFriendlyMethodName($method) . "\n";
            }
        } else {
            $report .= "**Muitas etapas falharam** - Entre em contato com o suporte.\n";
        }
 
        $report .= "\n💡 **Sugestões:**\n";
        $report .= "• Tente novamente em alguns instantes\n";
        $report .= "• Use comandos simples como /start ou /help\n";
        $report .= "• Se o problema persistir, contate o suporte\n";
 
        return $report;
    }
 
    /**
     * Salva o rastreamento no cache para análise posterior
     */
    public function saveTrace(): void
    {
        if (!$this->isEnabled) return;
 
        $trace = [
            'message_id' => $this->messageId,
            'executed_methods' => $this->executedMethods,
            'expected_methods' => $this->expectedMethods[$this->identifyMessageType([])] ?? [],
            'method_data' => $this->methodData,
            'timestamps' => $this->timestamps,
            'created_at' => now()->toISOString()
        ];
 
        Cache::put("message_trace:{$this->messageId}", $trace, now()->addHours(24));
    }
 
    /**
     * Inicia o tracking de uma nova mensagem
     */
    public function startTracking(string $messageId): void
    {
        $this->messageId = $messageId;
        $this->clearTrace();
        $this->isEnabled = config('message-flow.enabled', false);
    }
 
    /**
     * Finaliza o tracking e salva o trace
     */
    public function endTracking(): void
    {
        $this->saveTrace();
        $this->clearTrace();
    }
 
    /**
     * Limpa o rastreamento atual
     */
    public function clearTrace(): void
    {
        $this->executedMethods = [];
        $this->methodData = [];
        $this->timestamps = [];
        $this->messageId = uniqid('msg_', true);
    }
 
    /**
     * Verifica se o tracking está habilitado
     */
    public function isEnabled(): bool
    {
        return $this->isEnabled;
    }
 
    /**
     * Retorna os métodos executados
     */
    public function getExecutedMethods(): array
    {
        return $this->executedMethods;
    }
 
    /**
     * Retorna os métodos esperados para o tipo de mensagem
     */
    public function getExpectedMethods(): array
    {
        $messageType = $this->identifyMessageType([]);
        return $this->expectedMethods[$messageType] ?? [];
    }
 
    /**
     * Retorna os dados dos métodos
     */
    public function getMethodData(): array
    {
        return $this->methodData;
    }
 
    // Métodos auxiliares privados
    private function getMessageTypeEmoji(string $type): string
    {
        return match($type) {
            'text' => '📝',
            'voice' => '🎤',
            'callback_query' => '🔘',
            default => '❓'
        };
    }
 
    private function extractMessageContent(array $payload): string
    {
        if (isset($payload['message']['text'])) {
            return '"' . $payload['message']['text'] . '"';
        }
 
        if (isset($payload['message']['voice'])) {
            return 'Mensagem de voz';
        }
 
        if (isset($payload['callback_query']['data'])) {
            return 'Callback: ' . $payload['callback_query']['data'];
        }
 
        return 'Conteúdo desconhecido';
    }
 
    private function summarizeData(array $data): string
    {
        if (empty($data)) return 'Sem dados';
 
        $summary = [];
        foreach ($data as $key => $value) {
            if (is_string($value) && strlen($value) < 30) {
                $summary[] = "$key: $value";
            } elseif (is_numeric($value)) {
                $summary[] = "$key: $value";
            } elseif (is_bool($value)) {
                $summary[] = "$key: " . ($value ? 'Sim' : 'Não');
            }
        }
 
        return implode(', ', array_slice($summary, 0, 3));
    }
 
    private function explainMissingMethod(string $method): string
    {
        $explanations = [
            'TelegramMessageProcessorService.processWebhookPayload' => 'Falha na validação inicial do payload',
            'TelegramMessageProcessorService.processTextMessage' => 'Falha no processamento da mensagem de texto',
            'TelegramBotService.processMessage' => 'Falha no serviço principal do bot',
            'TelegramCommandParser.parseCommand' => 'Falha na interpretação do comando',
            'TelegramCommandHandlerManager.handleCommand' => 'Falha no gerenciamento de comandos',
            'TelegramChannel.sendTextMessage' => 'Falha no envio da resposta',
            'TelegramChannel.sendMessageWithKeyboard' => 'Falha no envio da resposta',
            'SpeechToTextService.convertVoiceToText' => 'Falha na conversão de voz para texto'
        ];
 
        return $explanations[$method] ?? 'Método não executado por razão desconhecida';
    }
 
    private function getUserFriendlyMethodName(string $method): string
    {
        $names = [
            'TelegramMessageProcessorService.processWebhookPayload' => 'Validação da mensagem',
            'TelegramMessageProcessorService.processTextMessage' => 'Processamento do texto',
            'TelegramBotService.processMessage' => 'Análise do comando',
            'TelegramCommandParser.parseCommand' => 'Interpretação do comando',
            'TelegramCommandHandlerManager.handleCommand' => 'Execução do comando',
            'TelegramChannel.sendTextMessage' => 'Envio da resposta',
            'TelegramChannel.sendMessageWithKeyboard' => 'Envio da resposta',
            'SpeechToTextService.convertVoiceToText' => 'Conversão de voz'
        ];
 
        return $names[$method] ?? 'Processamento da mensagem';
    }
}

Passo 3: Criar Provider

<?php
 
namespace App\Providers;
 
use App\Contracts\MessageFlowTrackerInterface;
use App\Services\MessageFlowTrackerService;
use Illuminate\Support\ServiceProvider;
 
class MessageFlowServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        // Registra a interface como singleton para compartilhar a mesma instância
        $this->app->singleton(MessageFlowTrackerInterface::class, MessageFlowTrackerService::class);
    }
 
    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // Publica o arquivo de configuração
        $this->publishes([
            __DIR__.'/../../config/message-flow.php' => config_path('message-flow.php'),
        ], 'message-flow-config');
    }
}

Passo 4: Configurar Message Flow

#config/message-flow.php

<?php
 
return [
    /*
    |--------------------------------------------------------------------------
    | Message Flow Tracking Configuration
    |--------------------------------------------------------------------------
    |
    | This file contains configuration for the message flow tracking system
    | that monitors and logs the complete flow of messages through the system.
    |
    */
 
    'enabled' => env('MESSAGE_FLOW_TRACKING_ENABLED', false),
 
    /*
    |--------------------------------------------------------------------------
    | Tracking Configuration
    |--------------------------------------------------------------------------
    |
    | Configure what and how to track in the message flow
    |
    */
 
    'tracking' => [
        'log_to_file' => env('MESSAGE_FLOW_LOG_TO_FILE', false),
        'send_to_user' => env('MESSAGE_FLOW_SEND_TO_USER', true),
        'cache_traces' => env('MESSAGE_FLOW_CACHE_TRACES', false),
 
        'stages_to_track' => [
            'webhook_received',
            'payload_validated',
            'duplicate_check',
            'message_processed',
            'database_operations',
            'external_api_calls',
            'response_sent',
            'error_handling'
        ],
 
        'categories_to_track' => [
            'system',
            'validation',
            'database',
            'external_api',
            'processing',
            'response',
            'error'
        ]
    ],
 
    /*
    |--------------------------------------------------------------------------
    | Output Configuration
    |--------------------------------------------------------------------------
    |
    | Configure how and where to output the tracking information
    |
    */
 
    'output' => [
        'send_to_user' => env('MESSAGE_FLOW_SEND_TO_USER', true),
        'log_to_file' => env('MESSAGE_FLOW_LOG_TO_FILE', false),
        'store_in_database' => env('MESSAGE_FLOW_STORE_IN_DATABASE', false),
        'cache_for_monitoring' => env('MESSAGE_FLOW_CACHE_FOR_MONITORING', true),
 
        'formats' => [
            'telegram' => true,
            'whatsapp' => true,
            'email' => true,
            'console' => true
        ]
    ],
 
    /*
    |--------------------------------------------------------------------------
    | Performance Configuration
    |--------------------------------------------------------------------------
    |
    | Configure performance thresholds and monitoring
    |
    */
 
    'performance' => [
        'slow_stage_threshold' => env('MESSAGE_FLOW_SLOW_THRESHOLD', 100), // milliseconds
        'very_slow_stage_threshold' => env('MESSAGE_FLOW_VERY_SLOW_THRESHOLD', 500), // milliseconds
        'memory_warning_threshold' => env('MESSAGE_FLOW_MEMORY_WARNING', 50), // MB
        'memory_critical_threshold' => env('MESSAGE_FLOW_MEMORY_CRITICAL', 100), // MB
 
        'track_query_count' => env('MESSAGE_FLOW_TRACK_QUERIES', true),
        'track_memory_usage' => env('MESSAGE_FLOW_TRACK_MEMORY', true),
        'track_execution_time' => env('MESSAGE_FLOW_TRACK_TIME', true)
    ],
 
    /*
    |--------------------------------------------------------------------------
    | Storage Configuration
    |--------------------------------------------------------------------------
    |
    | Configure how to store and manage tracking data
    |
    */
 
    'storage' => [
        'cache_ttl' => env('MESSAGE_FLOW_CACHE_TTL', 1440), // minutes (24 hours)
        'database_ttl' => env('MESSAGE_FLOW_DB_TTL', 10080), // minutes (7 days)
        'file_ttl' => env('MESSAGE_FLOW_FILE_TTL', 43200), // minutes (30 days)
 
        'max_traces_per_user' => env('MESSAGE_FLOW_MAX_TRACES', 100),
        'max_stages_per_trace' => env('MESSAGE_FLOW_MAX_STAGES', 50),
        'cleanup_frequency' => env('MESSAGE_FLOW_CLEANUP_FREQ', 3600), // seconds
    ],
 
    /*
    |--------------------------------------------------------------------------
    | Report Configuration
    |--------------------------------------------------------------------------
    |
    | Configure report generation and formatting
    |
    */
 
    'reports' => [
        'user_report_enabled' => env('MESSAGE_FLOW_USER_REPORT', true),
        'developer_report_enabled' => env('MESSAGE_FLOW_DEV_REPORT', true),
        'performance_report_enabled' => env('MESSAGE_FLOW_PERF_REPORT', true),
 
        'user_report_format' => env('MESSAGE_FLOW_USER_FORMAT', 'telegram'),
        'developer_report_format' => env('MESSAGE_FLOW_DEV_FORMAT', 'json'),
 
        'include_performance_insights' => env('MESSAGE_FLOW_INCLUDE_INSIGHTS', true),
        'include_recommendations' => env('MESSAGE_FLOW_INCLUDE_RECOMMENDATIONS', true),
        'include_error_details' => env('MESSAGE_FLOW_INCLUDE_ERRORS', true)
    ]
];

Passo 5: Registrar Provider

#config/app.php

'providers' => [
    // ... outros providers
    App\Providers\MessageFlowServiceProvider::class,
],

✅ Validação do Módulo

Checklist de Implementação

  • [ ] Interface `MessageFlowTrackerInterface` criada
  • [ ] Interface `MessageTrackingInterface` criada
  • [ ] Service `MessageFlowTrackerService` implementado
  • [ ] Provider `MessageFlowServiceProvider` registrado
  • [ ] Configuração `message-flow.php` criada
  • [ ] Integração com sistema de logging

Comandos de Validação

# Verificar configuração
php artisan config:cache
php artisan config:show message-flow
 
# Testar tracking
php artisan tinker
# >>> $tracker = app(\App\Contracts\MessageFlowTrackerInterface::class);
# >>> $tracker->trackMethod('TestClass', 'testMethod');
# >>> $tracker->endMethod('TestClass', 'testMethod');
# >>> $tracker->generateReport();
Imprimir/Exportar
QR Code
QR Code templates_ai:funcionalidades:laravel:telegram_bot:01_message_flow_system (generated for current page)