feat(mail): introduce MailService for tenant-specific SMTP handling and update related tests
This commit is contained in:
147
app/Domains/Integration/Services/MailService.php
Normal file
147
app/Domains/Integration/Services/MailService.php
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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.',
|
||||
|
||||
Reference in New Issue
Block a user