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'
+
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, + ''.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