diff --git a/app/Console/Commands/ConsumePublishedRecourseEmails.php b/app/Console/Commands/ConsumePublishedRecourseEmails.php index f22ed4c..01548d6 100644 --- a/app/Console/Commands/ConsumePublishedRecourseEmails.php +++ b/app/Console/Commands/ConsumePublishedRecourseEmails.php @@ -2,6 +2,7 @@ namespace App\Console\Commands; +use App\Events\EmailSentEvent; use App\Mail\PublishedRecourse; use Exception; use Illuminate\Console\Command; @@ -9,6 +10,7 @@ use Illuminate\Support\Facades\Mail; use PhpAmqpLib\Connection\AMQPStreamConnection; use PhpAmqpLib\Message\AMQPMessage; +use Throwable; class ConsumePublishedRecourseEmails extends Command { @@ -82,10 +84,10 @@ public function handle(): void $connection->close(); } - private function sendEmail($data): bool + private function sendEmail(array $data, PublishedRecourse $mailable): bool { try { - Mail::to($data['email'])->send(new PublishedRecourse($data)); + Mail::to($data['email'])->send($mailable); return true; } catch (Exception $e) { \Sentry\captureMessage($e, \Sentry\Severity::info()); @@ -96,16 +98,50 @@ private function sendEmail($data): bool protected function processMessage(AMQPMessage $msg): void { - $data = json_decode($msg->body, true); + $data = json_decode($msg->getBody(), true); + $mailable = new PublishedRecourse($data); - if ($this->sendEmail($data)) { + if ($this->sendEmail($data, $mailable)) { $msg->ack(); // Confirma o processamento $this->info("📧 E-mail enviado para: {$data['email']}"); Log::info("📧 E-mail enviado para: {$data['email']}"); + $this->recordDispatch($data, $mailable); return; } $this->error("❌ Falha ao enviar e-mail para: {$data['email']}"); Log::error("❌ Falha ao enviar e-mail para: {$data['email']}"); } + + /** + * Dispara o evento de auditoria do envio. + * + * Chamado após o ack: uma falha aqui não pode devolver a mensagem + * à fila, senão o proponente receberia o e-mail de novo. + */ + private function recordDispatch(array $data, PublishedRecourse $mailable): void + { + try { + EmailSentEvent::dispatch( + $data['email'], + $mailable->envelope()->subject, + PublishedRecourse::class, + now(), + [ + 'type' => 'published_recourse', + // Ausente em mensagens publicadas antes de o plugin Recourse enviar o campo + 'recourse_id' => $data['recourseId'] ?? null, + 'agent_id' => $data['agentId'] ?? null, + 'opportunity_name' => $data['opportunityName'] ?? null, + ], + $mailable->render(), + ); + } catch (Throwable $e) { + \Sentry\captureException($e); + Log::error('Falha ao registrar a auditoria do e-mail de recurso publicado', [ + 'email' => $data['email'], + 'exception' => $e->getMessage(), + ]); + } + } } diff --git a/app/Events/EmailSentEvent.php b/app/Events/EmailSentEvent.php new file mode 100644 index 0000000..7860034 --- /dev/null +++ b/app/Events/EmailSentEvent.php @@ -0,0 +1,24 @@ + $event->to, + 'subject' => $event->subject, + 'content' => $event->content, + 'mailable_type' => $event->mailableType, + 'meta' => $event->meta, + 'status' => 'sent', + 'attempted_at' => $event->sentAt, + 'dispatched_at' => $event->sentAt, + ]); + } +} diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php index e6ee748..6346bf9 100644 --- a/app/Providers/EventServiceProvider.php +++ b/app/Providers/EventServiceProvider.php @@ -2,8 +2,10 @@ namespace App\Providers; +use App\Events\EmailSentEvent; use App\Events\OpinionManagementEvent; use App\Listeners\OpinionManagementListener; +use App\Listeners\RecordEmailDispatch; use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider; class EventServiceProvider extends ServiceProvider @@ -12,6 +14,9 @@ class EventServiceProvider extends ServiceProvider OpinionManagementEvent::class => [ OpinionManagementListener::class, ], + EmailSentEvent::class => [ + RecordEmailDispatch::class, + ], ]; /** * Register services. diff --git a/tests/Feature/RecordEmailDispatchTest.php b/tests/Feature/RecordEmailDispatchTest.php new file mode 100644 index 0000000..431666e --- /dev/null +++ b/tests/Feature/RecordEmailDispatchTest.php @@ -0,0 +1,51 @@ + true, 'audit.console' => true]); + + $sentAt = Carbon::parse('2026-12-02 10:30:00'); + + EmailSentEvent::dispatch( + 'agente@example.com', + 'Resposta do recurso publicada', + PublishedRecourse::class, + $sentAt, + ['type' => 'published_recourse', 'recourse_id' => 789, 'agent_id' => 123456, 'opportunity_name' => 'Edital Teste'], + '

conteúdo

', + ); + + $dispatch = EmailDispatch::query()->sole(); + + $this->assertSame('agente@example.com', $dispatch->to); + $this->assertSame('Resposta do recurso publicada', $dispatch->subject); + $this->assertSame('

conteúdo

', $dispatch->content); + $this->assertSame(PublishedRecourse::class, $dispatch->mailable_type); + $this->assertSame('sent', $dispatch->status); + $this->assertSame( + ['type' => 'published_recourse', 'recourse_id' => 789, 'agent_id' => 123456, 'opportunity_name' => 'Edital Teste'], + $dispatch->meta, + ); + $this->assertTrue($dispatch->dispatched_at->equalTo($sentAt)); + $this->assertTrue($dispatch->attempted_at->equalTo($sentAt)); + + $this->assertDatabaseHas('audits', [ + 'auditable_type' => EmailDispatch::class, + 'auditable_id' => $dispatch->id, + 'event' => 'created', + ]); + } +} diff --git a/tests/Unit/Console/Commands/ConsumePublishedRecourseEmailsTest.php b/tests/Unit/Console/Commands/ConsumePublishedRecourseEmailsTest.php index 2e03e81..20833ec 100644 --- a/tests/Unit/Console/Commands/ConsumePublishedRecourseEmailsTest.php +++ b/tests/Unit/Console/Commands/ConsumePublishedRecourseEmailsTest.php @@ -3,13 +3,18 @@ namespace Tests\Unit\Console\Commands; use App\Console\Commands\ConsumePublishedRecourseEmails; +use App\Events\EmailSentEvent; use App\Mail\PublishedRecourse; use Illuminate\Console\OutputStyle; +use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Mail; use Mockery; use Mockery\MockInterface; use PhpAmqpLib\Channel\AMQPChannel; use PhpAmqpLib\Message\AMQPMessage; +use RuntimeException; +use Sentry\SentrySdk; +use Sentry\State\Hub; use Symfony\Component\Process\Process; use Tests\TestCase; @@ -50,10 +55,12 @@ public function test_send_email_true(): void $reflection = new \ReflectionClass($command); $method = $reflection->getMethod('sendEmail'); $method->setAccessible(true); - $method->invoke($command, json_decode($msgMock->body, true)); + $data = json_decode($msgMock->getBody(), true); + $mailable = new PublishedRecourse($data); + $send = $method->invoke($command, $data, $mailable); - // Asserts that the email was not sent - Mail::assertSent(PublishedRecourse::class); + $this->assertTrue($send); + Mail::assertSent(PublishedRecourse::class, fn ($mail) => $mail === $mailable); } public function test_send_email_false(): void @@ -73,7 +80,8 @@ public function test_send_email_false(): void $reflection = new \ReflectionClass($command); $method = $reflection->getMethod('sendEmail'); $method->setAccessible(true); - $send = $method->invoke($command, json_decode($msgMock->body, true)); + $data = json_decode($msgMock->getBody(), true); + $send = $method->invoke($command, $data, new PublishedRecourse($data)); // Asserts that the email was not sent $this->assertFalse($send); @@ -83,6 +91,7 @@ public function test_send_email_false(): void public function test_process_message_with_success(): void { Mail::fake(); + Event::fake([EmailSentEvent::class]); $msgMock = $this->createMockAMQPMessage( json_encode([ @@ -107,17 +116,92 @@ public function test_process_message_with_success(): void Mail::assertSent(PublishedRecourse::class); } -// public function test_process_message_with_failure(): void -// { - // @TODO: Needs discovery -// } + public function test_process_message_dispara_evento_de_auditoria_apos_envio(): void + { + Mail::fake(); + Event::fake([EmailSentEvent::class]); + $this->freezeTime(); + + $msgMock = $this->createMockAMQPMessage(json_encode([ + 'email' => 'test@example.com', + 'recourseId' => 789, + 'agentId' => 123456, + 'opportunityName' => 'Test Opportunity', + ])); + $msgMock->shouldReceive('ack')->once()->andReturnNull(); + + $this->invokeProcessMessage($msgMock); + + Event::assertDispatchedTimes(EmailSentEvent::class, 1); + Event::assertDispatched(EmailSentEvent::class, function (EmailSentEvent $event) { + return $event->to === 'test@example.com' + && $event->subject === 'Resposta do recurso publicada' + && $event->mailableType === PublishedRecourse::class + && $event->sentAt->equalTo(now()) + && $event->meta === [ + 'type' => 'published_recourse', + 'recourse_id' => 789, + 'agent_id' => 123456, + 'opportunity_name' => 'Test Opportunity', + ] + && str_contains((string) $event->content, 'Test Opportunity'); + }); + } + + public function test_process_message_sem_envio_nao_dispara_evento_nem_ack(): void + { + Mail::fake(); + Event::fake([EmailSentEvent::class]); + SentrySdk::setCurrentHub(new Hub()); + + // Sem a chave email o envio falha + $msgMock = $this->createMockAMQPMessage(json_encode(['agentId' => 123456])); + $msgMock->shouldNotReceive('ack'); + + // A mensagem de erro do command também acessa $data['email'] + try { + $this->invokeProcessMessage($msgMock); + } catch (\ErrorException) { + } + + Mail::assertNotSent(PublishedRecourse::class); + Event::assertNotDispatched(EmailSentEvent::class); + } + + public function test_falha_na_auditoria_nao_interrompe_o_consumer(): void + { + Mail::fake(); + SentrySdk::setCurrentHub(new Hub()); + Event::forget(EmailSentEvent::class); + Event::listen(EmailSentEvent::class, fn () => throw new RuntimeException('banco indisponível')); + + $msgMock = $this->createMockAMQPMessage(json_encode([ + 'email' => 'test@example.com', + 'agentId' => 123456, + 'opportunityName' => 'Test Opportunity', + ])); + $msgMock->shouldReceive('ack')->once()->andReturnNull(); + + $this->invokeProcessMessage($msgMock); + + Mail::assertSent(PublishedRecourse::class); + } + + private function invokeProcessMessage(MockInterface $msgMock): void + { + $command = new ConsumePublishedRecourseEmails; + $command->setOutput($this->createMock(OutputStyle::class)); + + $method = (new \ReflectionClass($command))->getMethod('processMessage'); + $method->invoke($command, $msgMock); + } private function createMockAMQPMessage(string $body): MockInterface { $channelMock = Mockery::mock(AMQPChannel::class); $msgMock = Mockery::mock(AMQPMessage::class); - $msgMock->body = $body; + $msgMock->shouldReceive('getBody')->andReturn($body); $msgMock->delivery_info = [ 'channel' => $channelMock, 'delivery_tag' => 1,