Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions app/Console/Commands/ConsumePublishedRecourseEmails.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

namespace App\Console\Commands;

use App\Events\EmailSentEvent;
use App\Mail\PublishedRecourse;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use Throwable;

class ConsumePublishedRecourseEmails extends Command
{
Expand Down Expand Up @@ -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());
Expand All @@ -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(),
]);
}
}
}
24 changes: 24 additions & 0 deletions app/Events/EmailSentEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace App\Events;

use Carbon\CarbonInterface;
use Illuminate\Foundation\Events\Dispatchable;

/**
* Disparado após um e-mail ser aceito pelo servidor de envio,
* para que o envio fique registrado em email_dispatches.
*/
class EmailSentEvent
{
use Dispatchable;

public function __construct(
public readonly string $to,
public readonly string $subject,
public readonly string $mailableType,
public readonly CarbonInterface $sentAt,
public readonly array $meta = [],
public readonly ?string $content = null,
) {}
}
29 changes: 29 additions & 0 deletions app/Listeners/RecordEmailDispatch.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\Listeners;

use App\Events\EmailSentEvent;
use App\Models\EmailDispatch;

/**
* Registra o envio em email_dispatches; o Auditable do model gera a entrada em audits.
*
* Roda de forma síncrona: não há worker de queue:work no supervisord,
* então um listener enfileirado nunca seria executado.
*/
class RecordEmailDispatch
{
public function handle(EmailSentEvent $event): void
{
EmailDispatch::create([
'to' => $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,
]);
}
}
5 changes: 5 additions & 0 deletions app/Providers/EventServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -12,6 +14,9 @@ class EventServiceProvider extends ServiceProvider
OpinionManagementEvent::class => [
OpinionManagementListener::class,
],
EmailSentEvent::class => [
RecordEmailDispatch::class,
],
];
/**
* Register services.
Expand Down
51 changes: 51 additions & 0 deletions tests/Feature/RecordEmailDispatchTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace Tests\Feature;

use App\Events\EmailSentEvent;
use App\Mail\PublishedRecourse;
use App\Models\EmailDispatch;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Tests\TestCase;

class RecordEmailDispatchTest extends TestCase
{
use RefreshDatabase;

public function test_evento_de_envio_registra_auditoria_no_banco(): void
{
config(['audit.enabled' => 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'],
'<p>conteúdo</p>',
);

$dispatch = EmailDispatch::query()->sole();

$this->assertSame('agente@example.com', $dispatch->to);
$this->assertSame('Resposta do recurso publicada', $dispatch->subject);
$this->assertSame('<p>conteúdo</p>', $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',
]);
}
}
102 changes: 93 additions & 9 deletions tests/Unit/Console/Commands/ConsumePublishedRecourseEmailsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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
Expand All @@ -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);
Expand All @@ -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([
Expand All @@ -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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Evitar de mascarar erros errais. Usar $this->expectException()

}

Mail::assertNotSent(PublishedRecourse::class);
Event::assertNotDispatched(EmailSentEvent::class);
}

public function test_falha_na_auditoria_nao_interrompe_o_consumer(): void

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Colocar os testes em ingles mantendo o padrao

{
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,
Expand Down
Loading