From 03d8361e5f8e693ccc6289becdd7245241ae379a Mon Sep 17 00:00:00 2001 From: ncoronel Date: Tue, 21 Jul 2026 17:00:07 -0300 Subject: [PATCH] feat(mail): introduce MailService for tenant-specific SMTP handling and update related tests --- .../Integration/Services/MailService.php | 147 ++++++++++++++++++ .../Services/TenantIntegrationService.php | 2 + app/Domains/Mail/Services/MailService.php | 96 ------------ .../MailTest/Services/MailTestService.php | 12 +- database/seeders/EmailIntegrationSeeder.php | 2 +- tests/Feature/Integration/MailServiceTest.php | 147 ++++++++++++++++++ tests/Feature/Mail/MailServiceTest.php | 86 ---------- .../MailTest/MailTestControllerTest.php | 68 ++++---- 8 files changed, 334 insertions(+), 226 deletions(-) create mode 100644 app/Domains/Integration/Services/MailService.php delete mode 100644 app/Domains/Mail/Services/MailService.php create mode 100644 tests/Feature/Integration/MailServiceTest.php delete mode 100644 tests/Feature/Mail/MailServiceTest.php diff --git a/app/Domains/Integration/Services/MailService.php b/app/Domains/Integration/Services/MailService.php new file mode 100644 index 0000000..5a8e36a --- /dev/null +++ b/app/Domains/Integration/Services/MailService.php @@ -0,0 +1,147 @@ +mailFactory = $mailFactory ?? app(MailFactory::class); + } + + public function forTenant(string $tenantCode): self + { + parent::forTenant($tenantCode); + + $this->tenant = Tenant::query() + ->where('codigo', $tenantCode) + ->firstOrFail(); + $this->mailer = $this->resolveMailer(); + + return $this; + } + + public function getHeaders(): array + { + return []; + } + + public function send(string|array $recipient, string $subject, string $content): void + { + if (! $this->mailer || ! $this->tenant) { + throw new Exception('MailService no está configurado. Llamá a forTenant() primero.'); + } + + $this->tenant->loadMissing(['headerLogo', 'footerLogo']); + + $html = Blade::render( + <<<'BLADE' + + {!! $content !!} + + BLADE, + [ + 'tenant' => $this->tenant, + 'headerLogoUrl' => $this->tenant->headerLogo?->getTemporaryUrl(1440), + 'footerLogoUrl' => $this->tenant->footerLogo?->getTemporaryUrl(1440), + 'content' => $content, + ], + ); + + $mail = (new Mailable) + ->subject($subject) + ->html($html); + + $this->mailer->to($recipient)->send($mail); + } + + public function mailerName(): string + { + return 'tenant-smtp'; + } + + public function onSetup(): void + { + if (! $this->tenant) { + throw new Exception('MailService no está configurado. Llamá a forTenant() primero.'); + } + + $recipient = $this->getIntegrationSetting('MAIL_FROM_ADDRESS'); + + if (! is_string($recipient) || $recipient === '') { + throw new InvalidArgumentException('Falta MAIL_FROM_ADDRESS en la configuración SMTP del tenant.'); + } + + $this->send( + $recipient, + 'Configuración de correo validada', + '

Configuración de correo validada

' + .'

La integración SMTP de '.e($this->tenant->nombre).' fue configurada correctamente.

' + .'

Este mensaje fue enviado automáticamente para validar las credenciales de correo.

', + ); + } + + private function resolveMailer(): Mailer + { + $data = $this->tenantIntegration?->integration_data; + + if (! is_array($data)) { + throw new InvalidArgumentException('La configuración SMTP del tenant no es válida.'); + } + + foreach (self::REQUIRED_SMTP_FIELDS as $field) { + if (! array_key_exists($field, $data) || $data[$field] === null || $data[$field] === '') { + throw new InvalidArgumentException("Falta {$field} en la configuración SMTP del tenant."); + } + } + + // MailFake implements MailFactory but cannot build transports. + if (! $this->mailFactory instanceof MailManager) { + return $this->mailFactory->mailer(); + } + + $mailer = $this->mailFactory->build([ + 'name' => "tenant-smtp-{$this->tenantCode}", + 'transport' => 'smtp', + 'scheme' => $data['MAIL_SCHEME'] ?? null, + 'host' => $data['MAIL_HOST'], + 'port' => (int) $data['MAIL_PORT'], + 'username' => $data['MAIL_USERNAME'], + 'password' => $data['MAIL_PASSWORD'], + 'timeout' => isset($data['MAIL_TIMEOUT']) ? (int) $data['MAIL_TIMEOUT'] : null, + 'local_domain' => $data['MAIL_EHLO_DOMAIN'] ?? null, + ]); + + $mailer->alwaysFrom( + $data['MAIL_FROM_ADDRESS'], + $data['MAIL_FROM_NAME'] ?? $this->tenant?->nombre, + ); + + return $mailer; + } +} diff --git a/app/Domains/Integration/Services/TenantIntegrationService.php b/app/Domains/Integration/Services/TenantIntegrationService.php index 2baa478..de3cf1a 100644 --- a/app/Domains/Integration/Services/TenantIntegrationService.php +++ b/app/Domains/Integration/Services/TenantIntegrationService.php @@ -47,6 +47,8 @@ class TenantIntegrationService protected function resolveService(string $integrationCode): ?BaseIntegrationService { switch ($integrationCode) { + case 'email': + return new MailService; case 'telepagos': case 'telepagos_homo': return new TelepagosIntegrationService($integrationCode); diff --git a/app/Domains/Mail/Services/MailService.php b/app/Domains/Mail/Services/MailService.php deleted file mode 100644 index 81dde7e..0000000 --- a/app/Domains/Mail/Services/MailService.php +++ /dev/null @@ -1,96 +0,0 @@ -mailFactory = $mailFactory ?? app(MailFactory::class); - $this->emailIntegration = TenantIntegration::query() - ->where('tenant_code', $this->tenant->codigo) - ->where('integration_code', self::INTEGRATION_CODE) - ->first(); - $this->mailer = $this->resolveMailer(); - } - - public function send(string|array $recipient, Mailable $mail): void - { - $this->mailer->to($recipient)->send($mail); - } - - public function mailerName(): string - { - return $this->emailIntegration ? 'tenant-smtp' : (string) config('mail.default'); - } - - private function resolveMailer(): Mailer - { - if (! $this->emailIntegration) { - return $this->mailFactory->mailer(); - } - - // MailFake implements the mail factory contract, but deliberately cannot - // build transports. Returning it keeps normal Mail::fake() assertions useful. - if (! $this->mailFactory instanceof MailManager) { - return $this->mailFactory->mailer(); - } - - $data = $this->emailIntegration->integration_data; - - if (! is_array($data)) { - throw new InvalidArgumentException('La configuración SMTP del tenant no es válida.'); - } - - foreach (self::REQUIRED_SMTP_FIELDS as $field) { - if (! array_key_exists($field, $data) || $data[$field] === null || $data[$field] === '') { - throw new InvalidArgumentException("Falta {$field} en la configuración SMTP del tenant."); - } - } - - $mailer = $this->mailFactory->build([ - 'name' => "tenant-smtp-{$this->tenant->codigo}", - 'transport' => 'smtp', - 'scheme' => $data['MAIL_SCHEME'] ?? null, - 'host' => $data['MAIL_HOST'], - 'port' => (int) $data['MAIL_PORT'], - 'username' => $data['MAIL_USERNAME'], - 'password' => $data['MAIL_PASSWORD'], - 'timeout' => isset($data['MAIL_TIMEOUT']) ? (int) $data['MAIL_TIMEOUT'] : null, - 'local_domain' => $data['MAIL_EHLO_DOMAIN'] ?? null, - ]); - - $mailer->alwaysFrom( - $data['MAIL_FROM_ADDRESS'], - $data['MAIL_FROM_NAME'] ?? $this->tenant->nombre, - ); - - return $mailer; - } -} diff --git a/app/Domains/MailTest/Services/MailTestService.php b/app/Domains/MailTest/Services/MailTestService.php index 220f12d..958e2ce 100644 --- a/app/Domains/MailTest/Services/MailTestService.php +++ b/app/Domains/MailTest/Services/MailTestService.php @@ -2,8 +2,7 @@ namespace App\Domains\MailTest\Services; -use App\Domains\Mail\Services\MailService; -use App\Domains\MailTest\Mailables\TestMail; +use App\Domains\Integration\Services\MailService; use App\Domains\Tenant\Models\Tenant; class MailTestService @@ -16,8 +15,13 @@ class MailTestService $subject ??= 'Prueba de correo de Shopit'; $message ??= 'Este es un correo de prueba enviado desde Shopit.'; - $mailService = new MailService($tenant); - $mailService->send($recipient, new TestMail($subject, $message, $tenant)); + $mailService = (new MailService)->forTenant($tenant->codigo); + $mailService->send( + $recipient, + $subject, + '

'.e($subject).'

' + .'

'.nl2br(e($message)).'

', + ); return [ 'message' => 'Correo de prueba enviado correctamente.', diff --git a/database/seeders/EmailIntegrationSeeder.php b/database/seeders/EmailIntegrationSeeder.php index 71baaa6..edb3798 100644 --- a/database/seeders/EmailIntegrationSeeder.php +++ b/database/seeders/EmailIntegrationSeeder.php @@ -20,7 +20,7 @@ class EmailIntegrationSeeder extends Seeder 'integration_data_schema' => [ 'MAIL_MAILER' => 'required|string|in:smtp', 'MAIL_SCHEME' => 'required|string|in:smtp', - 'MAIL_HOST' => 'required|string|in:smtp.gmail.com', + 'MAIL_HOST' => 'required|string', 'MAIL_PORT' => 'required|integer|in:587', 'MAIL_USERNAME' => 'required|email', 'MAIL_PASSWORD' => 'required|string', diff --git a/tests/Feature/Integration/MailServiceTest.php b/tests/Feature/Integration/MailServiceTest.php new file mode 100644 index 0000000..e71683e --- /dev/null +++ b/tests/Feature/Integration/MailServiceTest.php @@ -0,0 +1,147 @@ +createTenant(); + $this->createEmailIntegration(); + TenantIntegration::create([ + 'tenant_code' => $tenant->codigo, + 'integration_code' => 'email', + 'integration_data' => $this->emailData(), + ]); + + $mailer = Mockery::mock(Mailer::class); + $mailer->shouldReceive('alwaysFrom') + ->once() + ->with('store@example.com', 'Acme Mail'); + + $manager = Mockery::mock(MailManager::class); + $manager->shouldReceive('build') + ->once() + ->with(Mockery::on(fn (array $config): bool => $config === [ + 'name' => 'tenant-smtp-acme', + 'transport' => 'smtp', + 'scheme' => 'smtp', + 'host' => 'smtp.example.com', + 'port' => 587, + 'username' => 'mailer@example.com', + 'password' => 'secret', + 'timeout' => null, + 'local_domain' => null, + ])) + ->andReturn($mailer); + + $service = (new MailService($manager))->forTenant($tenant->codigo); + + $this->assertSame('tenant-smtp', $service->mailerName()); + } + + public function test_on_setup_sends_a_branded_test_email_to_the_configured_sender(): void + { + Mail::fake(); + $tenant = $this->createTenant(); + $this->createEmailIntegration(); + TenantIntegration::create([ + 'tenant_code' => $tenant->codigo, + 'integration_code' => 'email', + 'integration_data' => $this->emailData(), + ]); + + (new MailService)->forTenant($tenant->codigo)->onSetup(); + + Mail::assertSent(Mailable::class, function (Mailable $mail) use ($tenant): bool { + $html = $mail->render(); + + return $mail->hasTo('store@example.com') + && $mail->subject === 'Configuración de correo validada' + && str_contains($html, $tenant->nombre) + && str_contains($html, 'background-color: #112233') + && str_contains($html, 'background-color: #445566'); + }); + } + + public function test_configuring_the_email_integration_runs_its_setup_hook(): void + { + Mail::fake(); + $tenant = $this->createTenant(); + $integration = $this->createEmailIntegration(); + + app(TenantIntegrationService::class)->updateOrCreateIntegration( + $tenant->codigo, + $integration, + $this->emailData(), + ); + + Mail::assertSent(Mailable::class, 1); + } + + private function createTenant(): Tenant + { + $logo = Attachment::create([ + 'path' => 'tenants/logo.png', + 'filename' => 'logo.png', + 'type' => AttachmentType::Image, + 'mime_type' => 'image/png', + 'extension' => 'png', + ]); + + return Tenant::create([ + 'codigo' => 'acme', + 'nombre' => 'Acme Store', + 'dominio' => 'acme.example.com', + 'primary_color' => '#778899', + 'secondary_color' => '#64748b', + 'danger_color' => '#dc2626', + 'success_color' => '#16a34a', + 'header_bg_color' => '#112233', + 'footer_bg_color' => '#445566', + 'header_logo_id' => $logo->id, + 'footer_logo_id' => $logo->id, + ]); + } + + private function createEmailIntegration(): Integration + { + return Integration::create([ + 'integration_code' => 'email', + 'name' => 'Email', + ]); + } + + /** + * @return array + */ + private function emailData(): array + { + return [ + 'MAIL_SCHEME' => 'smtp', + 'MAIL_HOST' => 'smtp.example.com', + 'MAIL_PORT' => 587, + 'MAIL_USERNAME' => 'mailer@example.com', + 'MAIL_PASSWORD' => 'secret', + 'MAIL_FROM_ADDRESS' => 'store@example.com', + 'MAIL_FROM_NAME' => 'Acme Mail', + ]; + } +} diff --git a/tests/Feature/Mail/MailServiceTest.php b/tests/Feature/Mail/MailServiceTest.php deleted file mode 100644 index 8bc55eb..0000000 --- a/tests/Feature/Mail/MailServiceTest.php +++ /dev/null @@ -1,86 +0,0 @@ - 'tenants/logo.png', - 'filename' => 'logo.png', - 'type' => AttachmentType::Image, - 'mime_type' => 'image/png', - 'extension' => 'png', - ]); - $tenant = Tenant::create([ - 'codigo' => 'acme', - 'nombre' => 'Acme Store', - 'dominio' => 'acme.example.com', - 'primary_color' => '#778899', - 'secondary_color' => '#64748b', - 'danger_color' => '#dc2626', - 'success_color' => '#16a34a', - 'header_bg_color' => '#112233', - 'footer_bg_color' => '#445566', - 'header_logo_id' => $logo->id, - 'footer_logo_id' => $logo->id, - ]); - Integration::create([ - 'integration_code' => 'email', - 'name' => 'Email', - ]); - TenantIntegration::create([ - 'tenant_code' => $tenant->codigo, - 'integration_code' => 'email', - 'integration_data' => [ - 'MAIL_SCHEME' => 'smtp', - 'MAIL_HOST' => 'smtp.example.com', - 'MAIL_PORT' => 587, - 'MAIL_USERNAME' => 'mailer@example.com', - 'MAIL_PASSWORD' => 'secret', - 'MAIL_FROM_ADDRESS' => 'store@example.com', - 'MAIL_FROM_NAME' => 'Acme Mail', - ], - ]); - - $mailer = Mockery::mock(Mailer::class); - $mailer->shouldReceive('alwaysFrom') - ->once() - ->with('store@example.com', 'Acme Mail'); - - $manager = Mockery::mock(MailManager::class); - $manager->shouldReceive('build') - ->once() - ->with(Mockery::on(fn (array $config): bool => $config === [ - 'name' => 'tenant-smtp-acme', - 'transport' => 'smtp', - 'scheme' => 'smtp', - 'host' => 'smtp.example.com', - 'port' => 587, - 'username' => 'mailer@example.com', - 'password' => 'secret', - 'timeout' => null, - 'local_domain' => null, - ])) - ->andReturn($mailer); - - $service = new MailService($tenant, $manager); - - $this->assertSame('tenant-smtp', $service->mailerName()); - } -} diff --git a/tests/Feature/MailTest/MailTestControllerTest.php b/tests/Feature/MailTest/MailTestControllerTest.php index 7805bb0..3f9b8d2 100644 --- a/tests/Feature/MailTest/MailTestControllerTest.php +++ b/tests/Feature/MailTest/MailTestControllerTest.php @@ -9,6 +9,7 @@ use App\Domains\Integration\Models\TenantIntegration; use App\Domains\MailTest\Mailables\TestMail; use App\Domains\Tenant\Models\Tenant; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Mail\Mailable; use Illuminate\Support\Facades\Mail; use Tests\TestCase; @@ -31,14 +32,14 @@ class MailTestControllerTest extends TestCase ->assertJsonPath('message', 'Correo de prueba enviado correctamente.') ->assertJsonPath('recipient', 'recipient@example.com') ->assertJsonPath('tenant_code', 'acme') - ->assertJsonPath('mailer', 'array') + ->assertJsonPath('mailer', 'tenant-smtp') ->assertJsonStructure(['sent_at']); - Mail::assertSent(TestMail::class, function (TestMail $mail) use ($tenant): bool { + Mail::assertSent(Mailable::class, function (Mailable $mail) use ($tenant): bool { return $mail->hasTo('recipient@example.com') - && $mail->mailSubject === 'SMTP test' - && $mail->mailMessage === 'Test message' - && $mail->tenant->is($tenant); + && $mail->subject === 'SMTP test' + && str_contains($mail->render(), 'Test message') + && str_contains($mail->render(), $tenant->nombre); }); } @@ -51,42 +52,12 @@ class MailTestControllerTest extends TestCase 'to' => 'recipient@example.com', ])->assertOk(); - Mail::assertSent(TestMail::class, function (TestMail $mail): bool { - return $mail->mailSubject === 'Prueba de correo de Shopit' - && $mail->mailMessage === 'Este es un correo de prueba enviado desde Shopit.'; + Mail::assertSent(Mailable::class, function (Mailable $mail): bool { + return $mail->subject === 'Prueba de correo de Shopit' + && str_contains($mail->render(), 'Este es un correo de prueba enviado desde Shopit.'); }); } - public function test_it_uses_the_tenant_email_integration_when_configured(): void - { - Mail::fake(); - $tenant = $this->createTenant(); - - Integration::create([ - 'integration_code' => 'email', - 'name' => 'Email', - ]); - TenantIntegration::create([ - 'tenant_code' => $tenant->codigo, - 'integration_code' => 'email', - 'integration_data' => [ - 'MAIL_SCHEME' => 'smtp', - 'MAIL_HOST' => 'smtp.example.com', - 'MAIL_PORT' => 587, - 'MAIL_USERNAME' => 'mailer@example.com', - 'MAIL_PASSWORD' => 'secret', - 'MAIL_FROM_ADDRESS' => 'store@example.com', - ], - ]); - - $this->postJson('/api/acme/mail-test/send', [ - 'to' => 'recipient@example.com', - ])->assertOk() - ->assertJsonPath('mailer', 'tenant-smtp'); - - Mail::assertSent(TestMail::class); - } - public function test_it_validates_the_recipient(): void { Mail::fake(); @@ -182,7 +153,7 @@ class MailTestControllerTest extends TestCase 'extension' => 'png', ]); - return Tenant::create([ + $tenant = Tenant::create([ 'codigo' => 'acme', 'nombre' => 'Acme Store', 'dominio' => 'acme.example.com', @@ -195,5 +166,24 @@ class MailTestControllerTest extends TestCase 'header_logo_id' => $headerLogo->id, 'footer_logo_id' => $footerLogo->id, ]); + + Integration::create([ + 'integration_code' => 'email', + 'name' => 'Email', + ]); + TenantIntegration::create([ + 'tenant_code' => $tenant->codigo, + 'integration_code' => 'email', + 'integration_data' => [ + 'MAIL_SCHEME' => 'smtp', + 'MAIL_HOST' => 'smtp.example.com', + 'MAIL_PORT' => 587, + 'MAIL_USERNAME' => 'mailer@example.com', + 'MAIL_PASSWORD' => 'secret', + 'MAIL_FROM_ADDRESS' => 'store@example.com', + ], + ]); + + return $tenant; } }