Files
shopit-back/app/Domains/Notification/Services/NotificationMailService.php

494 lines
18 KiB
PHP

<?php
namespace App\Domains\Notification\Services;
use App\Domains\Auth\Models\ResetPasswordAttempt;
use App\Domains\Auth\Models\User;
use App\Domains\Integration\Services\MailService;
use App\Domains\Notification\Events\PasswordResetRequested;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Services\TicketPdfService;
use App\Domains\Ticket\Services\TicketPresentationResolver;
use App\Domains\Ticket\Services\TicketValidityResolver;
use Closure;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Throwable;
class NotificationMailService
{
public function __construct(
private readonly MailService $mailService,
private readonly TicketPdfService $ticketPdfService,
private readonly IdempotentEmailDeliveryService $emailDeliveryService,
) {}
public function sendWelcome(int $userId, string $tenantCode): void
{
$context = [
'user_id' => $userId,
'tenant_code' => $tenantCode,
];
$tenant = Tenant::query()->with('websiteType')->where('codigo', $tenantCode)->firstOrFail();
$user = User::query()->findOrFail($userId);
$this->sendIdempotently(
"welcome:{$tenantCode}:{$userId}",
'welcome',
$tenantCode,
$context,
$user->email,
function () use ($user, $tenant, $tenantCode): array {
$brand = $tenant->websiteType ?? $tenant;
$tenantUrl = 'https://'.$tenant->dominio.$tenant->base_path;
$this->mailService
->forTenant($tenantCode)
->send(
$user->email,
"Bienvenido a {$brand->nombre}",
view('mail.notifications.welcome', compact('brand', 'user', 'tenantUrl'))->render(),
$brand,
);
return [
'brand_type' => $tenant->websiteType === null ? 'tenant' : 'website_type',
];
},
);
}
public function sendPasswordResetCode(
int $attemptId,
string $tenantCode,
string $channel = PasswordResetRequested::CHANNEL_STOREFRONT,
): void {
$context = [
'attempt_id' => $attemptId,
'tenant_code' => $tenantCode,
'channel' => $channel,
];
$tenant = Tenant::query()
->with('websiteType')
->where('codigo', $tenantCode)
->firstOrFail();
$attempt = ResetPasswordAttempt::query()
->with('user')
->findOrFail($attemptId);
if ($attempt->status !== ResetPasswordAttempt::STATUS_PENDING) {
$this->logSkipped('password_reset', array_merge($context, [
'reason' => 'attempt_not_pending',
'attempt_status' => $attempt->status,
'user_id' => $attempt->user_id,
]));
return;
}
$this->sendIdempotently(
"password-reset:{$attemptId}",
'password_reset',
$tenantCode,
$context,
$attempt->user->email,
function () use ($attempt, $tenant, $tenantCode, $channel): array {
$recoveryDomain = match ($channel) {
PasswordResetRequested::CHANNEL_ADMINAPP => $tenant->websiteType?->dominio,
PasswordResetRequested::CHANNEL_SCANNER => $tenant->websiteType?->scanner_domain,
default => $tenant->dominio,
};
$recoveryBasePath = $channel === PasswordResetRequested::CHANNEL_STOREFRONT
&& $tenant->base_path !== '/'
? $tenant->base_path
: '';
$recoveryQuery = ['email' => $attempt->user->email];
if (
$channel === PasswordResetRequested::CHANNEL_SCANNER
&& $attempt->reason === ResetPasswordAttempt::REASON_STAFF_CREATED
) {
$recoveryQuery['code'] = $attempt->codigo;
}
$recoveryUrl = $recoveryDomain === null
? null
: 'https://'.$recoveryDomain.$recoveryBasePath.'/recuperar-contrasena/codigo?'.http_build_query($recoveryQuery);
$brand = $tenant->websiteType ?? $tenant;
[$subject, $template] = match ($attempt->reason) {
ResetPasswordAttempt::REASON_STAFF_CREATED => [
'Tu cuenta de escáner está lista', 'scanner-created',
],
ResetPasswordAttempt::REASON_ADMINISTRATOR_CREATED => [
'Tu cuenta de administrador está lista', 'administrator-created',
],
ResetPasswordAttempt::REASON_ACCOUNT_LOCKED => [
'Desbloqueá tu cuenta', 'account-locked',
],
default => ['Código para recuperar tu contraseña', 'password-reset'],
};
$this->mailService
->forTenant($tenantCode)
->send(
$attempt->user->email,
"{$subject} - {$brand->nombre}",
view("mail.notifications.{$template}", [
'attempt' => $attempt,
'recoveryUrl' => $recoveryUrl,
'brand' => $brand,
])->render(),
$brand,
);
return [
'user_id' => $attempt->user_id,
'recovery_domain_available' => $recoveryDomain !== null,
];
},
);
}
public function sendPurchaseConfirmed(int $purchaseId): void
{
$context = ['purchase_id' => $purchaseId];
$purchase = Purchase::query()
->with(['tenant', 'user', 'items'])
->find($purchaseId);
if ($purchase === null) {
$this->logSkipped('purchase_confirmed', array_merge($context, [
'reason' => 'purchase_not_found',
'missing_model' => Purchase::class,
]));
return;
}
$recipient = $this->recipientFor($purchase);
if ($recipient === '') {
$this->logSkipped('purchase_confirmed', array_merge($context, ['reason' => 'missing_recipient']));
return;
}
$this->sendIdempotently(
"purchase-confirmed:{$purchaseId}",
'purchase_confirmed',
$purchase->tenant_codigo,
$context,
$recipient,
function () use ($purchase, $recipient): array {
/** @var Collection<int, Ticket> $tickets */
$tickets = $purchase->tickets()
->where('tenant_code', $purchase->tenant_codigo)
->with(TicketPresentationResolver::RELATIONS)
->get();
$attachments = $tickets->isEmpty()
? []
: [[
'data' => $this->ticketPdfService->contents($purchase->tenant, $tickets),
'name' => $this->ticketPdfService->filename($tickets),
'mime' => 'application/pdf',
]];
$this->mailService
->forTenant($purchase->tenant_codigo)
->send(
$recipient,
"Compra confirmada - Compra #{$purchase->getKey()}",
view('mail.notifications.purchase-confirmed', compact('purchase', 'tickets'))->render(),
attachments: $attachments,
);
return [
'tenant_code' => $purchase->tenant_codigo,
'user_id' => $purchase->user_id,
'purchase_status' => $purchase->status,
'purchase_item_count' => $purchase->items->count(),
'ticket_count' => $tickets->count(),
'ticket_ids' => $tickets->modelKeys(),
];
},
);
}
/**
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
*/
public function sendEventDateRescheduled(
string $tenantCode,
int $sourceEventDateId,
int $destinationEventDateId,
string $previousDate,
string $newDate,
array $purchaseTickets,
): void {
foreach ($purchaseTickets as $purchaseTicketGroup) {
$purchaseId = $purchaseTicketGroup['purchase_id'];
$ticketIds = $purchaseTicketGroup['ticket_ids'];
$context = [
'tenant_code' => $tenantCode,
'event_date_id' => $sourceEventDateId,
'destination_event_date_id' => $destinationEventDateId,
'purchase_id' => $purchaseId,
'ticket_ids' => $ticketIds,
];
$purchase = $this->eventDateNotificationPurchase($tenantCode, $purchaseId);
if ($purchase === null || $purchase->status !== Purchase::STATUS_PAID) {
$this->logSkipped('event_date_rescheduled', array_merge($context, [
'reason' => 'purchase_not_paid_or_not_found',
]));
continue;
}
/** @var Collection<int, Ticket> $tickets */
$tickets = $purchase->tickets()
->where('tenant_code', $tenantCode)
->whereKey($ticketIds)
->with([
...TicketPresentationResolver::RELATIONS,
...TicketValidityResolver::RELATIONS,
])
->get()
->filter(fn (Ticket $ticket): bool => $ticket->is_active())
->values();
if ($tickets->isEmpty()) {
$this->logSkipped('event_date_rescheduled', array_merge($context, [
'reason' => 'no_longer_active_tickets',
]));
continue;
}
$recipient = $this->recipientFor($purchase);
if ($recipient === '') {
$this->logSkipped('event_date_rescheduled', array_merge($context, [
'reason' => 'missing_recipient',
]));
continue;
}
$deliveryKey = "event-date-rescheduled:{$sourceEventDateId}:{$destinationEventDateId}:{$purchaseId}";
$this->sendIdempotently(
$deliveryKey,
'event_date_rescheduled',
$tenantCode,
$context,
$recipient,
function () use (
$tenantCode,
$purchase,
$recipient,
$previousDate,
$newDate,
$tickets,
): array {
$brand = $purchase->tenant->websiteType ?? $purchase->tenant;
$this->mailService
->forTenant($tenantCode)
->send(
$recipient,
"Tu evento fue reprogramado - Compra #{$purchase->getKey()}",
view('mail.notifications.event-date-rescheduled', compact(
'purchase', 'previousDate', 'newDate', 'tickets'
))->render(),
$brand,
);
return ['ticket_count' => $tickets->count()];
},
);
}
}
/**
* @param list<array{purchase_id: int, ticket_ids: list<int>}> $purchaseTickets
*/
public function sendEventDateSuspended(
string $tenantCode,
int $eventDateId,
string $date,
array $purchaseTickets,
): void {
foreach ($purchaseTickets as $purchaseTicketGroup) {
$purchaseId = $purchaseTicketGroup['purchase_id'];
$ticketIds = $purchaseTicketGroup['ticket_ids'];
$context = [
'tenant_code' => $tenantCode,
'event_date_id' => $eventDateId,
'purchase_id' => $purchaseId,
'ticket_ids' => $ticketIds,
];
$purchase = $this->eventDateNotificationPurchase($tenantCode, $purchaseId);
if ($purchase === null || $purchase->status !== Purchase::STATUS_PAID) {
$this->logSkipped('event_date_suspended', array_merge($context, [
'reason' => 'purchase_not_paid_or_not_found',
]));
continue;
}
/** @var Collection<int, Ticket> $tickets */
$tickets = $purchase->tickets()
->where('tenant_code', $tenantCode)
->whereKey($ticketIds)
->with([
...TicketPresentationResolver::RELATIONS,
...TicketValidityResolver::RELATIONS,
])
->get()
->filter(fn (Ticket $ticket): bool => in_array($ticket->status, [
Ticket::STATUS_ACTIVE,
Ticket::STATUS_DISABLED,
], true))
->values();
if ($tickets->isEmpty()) {
$this->logSkipped('event_date_suspended', array_merge($context, [
'reason' => 'no_longer_relevant_tickets',
]));
continue;
}
$recipient = $this->recipientFor($purchase);
if ($recipient === '') {
$this->logSkipped('event_date_suspended', array_merge($context, [
'reason' => 'missing_recipient',
]));
continue;
}
$deliveryKey = "event-date-suspended:{$eventDateId}:{$purchaseId}";
$disabledTickets = $tickets
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_DISABLED)
->values();
$activeTickets = $tickets
->filter(fn (Ticket $ticket): bool => $ticket->status === Ticket::STATUS_ACTIVE)
->values();
$this->sendIdempotently(
$deliveryKey,
'event_date_suspended',
$tenantCode,
$context,
$recipient,
function () use (
$tenantCode,
$purchase,
$recipient,
$date,
$disabledTickets,
$activeTickets,
): array {
$brand = $purchase->tenant->websiteType ?? $purchase->tenant;
$this->mailService
->forTenant($tenantCode)
->send(
$recipient,
"Una fecha de tu evento fue suspendida - Compra #{$purchase->getKey()}",
view('mail.notifications.event-date-suspended', compact(
'purchase', 'date', 'disabledTickets', 'activeTickets'
))->render(),
$brand,
);
return [
'ticket_count' => $disabledTickets->count() + $activeTickets->count(),
'disabled_ticket_ids' => $disabledTickets->modelKeys(),
'active_ticket_ids' => $activeTickets->modelKeys(),
];
},
);
}
}
private function eventDateNotificationPurchase(string $tenantCode, int $purchaseId): ?Purchase
{
return Purchase::query()
->where('tenant_codigo', $tenantCode)
->with(['tenant.websiteType', 'user'])
->find($purchaseId);
}
private function recipientFor(Purchase $purchase): string
{
return (string) ($purchase->email ?: $purchase->user?->email);
}
/**
* @param array<string, mixed> $context
* @param Closure(): array<string, mixed> $send
*/
private function sendIdempotently(
string $key,
string $emailType,
?string $tenantCode,
array $context,
string $recipient,
Closure $send,
): void {
$sent = $this->emailDeliveryService->sendOnce(
$key,
$emailType,
$tenantCode,
$context,
$recipient,
function () use ($emailType, $context, $send): void {
$this->sendLogged($emailType, $context, $send);
},
);
if (! $sent) {
$this->logSkipped($emailType, array_merge($context, ['reason' => 'already_claimed']));
}
}
/**
* @param array<string, mixed> $context
* @param Closure(): (array<string, mixed>|null) $send
*/
private function sendLogged(string $emailType, array $context, Closure $send): void
{
try {
$resultContext = $send();
if ($resultContext === null) {
return;
}
Log::channel('emails')->info('Notification email sent.', array_merge($context, $resultContext, [
'email_type' => $emailType,
'mailer' => $this->mailService->mailerName(),
]));
} catch (Throwable $exception) {
Log::channel('emails')->error('Notification email delivery failed.', array_merge($context, [
'email_type' => $emailType,
'exception' => $exception,
]));
throw $exception;
}
}
/** @param array<string, mixed> $context */
private function logSkipped(string $emailType, array $context): void
{
Log::channel('emails')->warning('Notification email skipped.', array_merge($context, [
'email_type' => $emailType,
]));
}
}