feat(mail): introduce MailService for tenant-specific SMTP handling and update related tests

This commit is contained in:
2026-07-21 17:00:07 -03:00
parent 3fe48fbfa5
commit 03d8361e5f
8 changed files with 334 additions and 226 deletions

View File

@@ -0,0 +1,147 @@
<?php
namespace App\Domains\Integration\Services;
use App\Domains\Tenant\Models\Tenant;
use Exception;
use Illuminate\Contracts\Mail\Factory as MailFactory;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Blade;
use InvalidArgumentException;
class MailService extends BaseIntegrationService
{
private const REQUIRED_SMTP_FIELDS = [
'MAIL_HOST',
'MAIL_PORT',
'MAIL_USERNAME',
'MAIL_PASSWORD',
'MAIL_FROM_ADDRESS',
];
protected string $integrationCode = 'email';
private readonly MailFactory $mailFactory;
private ?Mailer $mailer = null;
private ?Tenant $tenant = null;
public function __construct(?MailFactory $mailFactory = null)
{
$this->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'
<x-mail.branded-layout :tenant="$tenant" :header-logo-url="$headerLogoUrl" :footer-logo-url="$footerLogoUrl">
{!! $content !!}
</x-mail.branded-layout>
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',
'<h1 style="margin: 0 0 20px;">Configuración de correo validada</h1>'
.'<p>La integración SMTP de '.e($this->tenant->nombre).' fue configurada correctamente.</p>'
.'<p style="color: #64748b; font-size: 13px;">Este mensaje fue enviado automáticamente para validar las credenciales de correo.</p>',
);
}
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;
}
}

View File

@@ -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);

View File

@@ -1,96 +0,0 @@
<?php
namespace App\Domains\Mail\Services;
use App\Domains\Integration\Models\TenantIntegration;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Contracts\Mail\Factory as MailFactory;
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\MailManager;
use InvalidArgumentException;
class MailService
{
private const INTEGRATION_CODE = 'email';
private const REQUIRED_SMTP_FIELDS = [
'MAIL_HOST',
'MAIL_PORT',
'MAIL_USERNAME',
'MAIL_PASSWORD',
'MAIL_FROM_ADDRESS',
];
private readonly MailFactory $mailFactory;
private readonly ?TenantIntegration $emailIntegration;
private readonly Mailer $mailer;
public function __construct(
private readonly Tenant $tenant,
?MailFactory $mailFactory = null,
) {
$this->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;
}
}

View File

@@ -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,
'<h1 style="margin: 0 0 20px;">'.e($subject).'</h1>'
.'<p>'.nl2br(e($message)).'</p>',
);
return [
'message' => 'Correo de prueba enviado correctamente.',

View File

@@ -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',

View File

@@ -0,0 +1,147 @@
<?php
namespace Tests\Feature\Integration;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Integration\Models\Integration;
use App\Domains\Integration\Models\TenantIntegration;
use App\Domains\Integration\Services\MailService;
use App\Domains\Integration\Services\TenantIntegrationService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailer;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Mail;
use Mockery;
use Tests\TestCase;
class MailServiceTest extends TestCase
{
use RefreshDatabase;
public function test_it_builds_an_isolated_smtp_mailer_from_the_tenant_integration(): void
{
$tenant = $this->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<string, string|int>
*/
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',
];
}
}

View File

@@ -1,86 +0,0 @@
<?php
namespace Tests\Feature\Mail;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Integration\Models\Integration;
use App\Domains\Integration\Models\TenantIntegration;
use App\Domains\Mail\Services\MailService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\Mailer;
use Illuminate\Mail\MailManager;
use Mockery;
use Tests\TestCase;
class MailServiceTest extends TestCase
{
use RefreshDatabase;
public function test_it_builds_an_isolated_smtp_mailer_from_the_tenant_integration(): void
{
$logo = Attachment::create([
'path' => '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());
}
}

View File

@@ -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;
}
}