9 Commits

Author SHA1 Message Date
873855c85a feat(auth): implement Google OAuth integration with user authentication and token exchange 2026-07-22 13:43:14 -03:00
855ac13990 feat(auth): configure Google OAuth credentials in .env.example and update socialite version in composer.json 2026-07-22 12:00:38 -03:00
87153b7839 feat(dependencies): add laravel/socialite and firebase/php-jwt to composer dependencies 2026-07-22 11:54:10 -03:00
528772fc96 feat(notification): implement email notifications for user registration and purchase events 2026-07-22 09:54:19 -03:00
7e1ffbf417 feat(integration): add requires_tenant_configuration field and update related logic and tests 2026-07-22 09:23:58 -03:00
03d8361e5f feat(mail): introduce MailService for tenant-specific SMTP handling and update related tests 2026-07-21 17:00:07 -03:00
3fe48fbfa5 feat(mail): implement MailService for tenant-specific SMTP configuration and update MailTestService to utilize it 2026-07-21 16:43:09 -03:00
22da4966e9 feat(mail-test): enhance email functionality with tenant branding and routing 2026-07-21 16:26:46 -03:00
1a05c380a0 feat(mail-test): implement email testing functionality
- Created MailTestController to handle email sending requests.
- Added SendTestMailRequest for validating email input.
- Developed MailTestService to manage email sending logic.
- Introduced TestMail Mailable for formatting test emails.
- Defined API route for sending test emails.
- Created EmailIntegrationSeeder to seed email integration settings.
- Updated DatabaseSeeder to include EmailIntegrationSeeder.
- Added MailTestControllerTest to ensure email sending functionality works as expected.
2026-07-21 16:01:18 -03:00
51 changed files with 2277 additions and 1005 deletions

View File

@@ -51,10 +51,15 @@ REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
GOOGLE_REDIRECT_URI=https://grub-renewed-nicely.ngrok-free.app/auth/google/callback
MAIL_MAILER=smtp
MAIL_SCHEME=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Domains\Auth\Controllers;
use App\Domains\Auth\Services\GoogleAuthService;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class GoogleAuthController extends Controller
{
public function __construct(private readonly GoogleAuthService $googleAuthService) {}
public function redirect(Request $request): RedirectResponse
{
return $this->googleAuthService->redirect($request);
}
public function callback(Request $request): RedirectResponse
{
return $this->googleAuthService->callback($request);
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Auth\Controllers;
use App\Domains\Auth\Requests\GoogleTokenExchangeRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\GoogleAuthService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
class GoogleTokenExchangeController extends Controller
{
public function __construct(private readonly GoogleAuthService $googleAuthService) {}
public function __invoke(GoogleTokenExchangeRequest $request): JsonResponse
{
$authentication = $this->googleAuthService->exchange($request->validated('oauth_code'));
return response()->json([
'message' => 'Sesion iniciada correctamente.',
'token' => $authentication['token'],
'token_type' => 'Bearer',
'user' => UserResource::make($authentication['user']),
]);
}
}

View File

@@ -10,7 +10,7 @@ use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono'])]
#[Fillable(['nombre_apellido', 'email', 'password', 'dni', 'telefono', 'google_id'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
class GoogleTokenExchangeRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/** @return array<string, array<int, string>> */
public function rules(): array
{
return [
'oauth_code' => ['required', 'uuid'],
];
}
}

View File

@@ -4,6 +4,7 @@ namespace App\Domains\Auth\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
class RegisterUserRequest extends FormRequest
{
@@ -18,9 +19,10 @@ class RegisterUserRequest extends FormRequest
public function rules(): array
{
return [
'tenant_codigo' => ['nullable', 'string', Rule::exists('tenants', 'codigo')],
'nombre_apellido' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')],
'password' => ['required', 'string', 'confirmed', \Illuminate\Validation\Rules\Password::min(8)->mixedCase()->symbols()],
'password' => ['required', 'string', 'confirmed', Password::min(8)->mixedCase()->symbols()],
'dni' => ['nullable', 'string', 'max:255'],
'telefono' => ['nullable', 'string', 'max:255'],
];

View File

@@ -0,0 +1,165 @@
<?php
namespace App\Domains\Auth\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Notification\Events\UserRegistered;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Support\TenantDomainNormalizer;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Laravel\Socialite\Contracts\User as SocialiteUser;
use Laravel\Socialite\Facades\Socialite;
class GoogleAuthService
{
public function redirect(Request $request): RedirectResponse
{
$tenantCode = $request->string('tenant')->toString();
$returnUrl = $request->string('return_url')->toString();
$tenant = Tenant::query()->where('codigo', $tenantCode)->first();
if (! $tenant || ! $this->isTenantReturnUrl($returnUrl, $tenant)) {
throw ValidationException::withMessages([
'tenant' => 'El tenant o la URL de retorno no son validos.',
]);
}
$state = (string) Str::uuid();
Cache::put("google-oauth-context:{$state}", [
'tenant_codigo' => $tenant->codigo,
'return_url' => rtrim($returnUrl, '/'),
], now()->addMinutes(10));
return Socialite::driver('google')
->scopes(['openid', 'profile', 'email'])
->stateless()
->with(['state' => $state])
->redirect();
}
public function callback(Request $request): RedirectResponse
{
$state = $request->string('state')->toString();
/** @var array{tenant_codigo?: string, return_url?: string}|null $context */
$context = Str::isUuid($state) ? Cache::pull("google-oauth-context:{$state}") : null;
if (! is_array($context) || ! isset($context['tenant_codigo'], $context['return_url'])) {
abort(400, 'La solicitud de autenticacion expiro. Intenta nuevamente.');
}
$tenant = Tenant::query()->where('codigo', $context['tenant_codigo'])->first();
if (! $tenant || ! $this->isTenantReturnUrl($context['return_url'], $tenant)) {
abort(400, 'La URL de retorno no es valida.');
}
/** @var SocialiteUser $googleUser */
$googleUser = Socialite::driver('google')->stateless()->user();
$user = $this->resolveUser($googleUser, $tenant);
$token = $user->createToken(
'google-oauth',
['*'],
now()->addMinutes((int) config('sanctum.expiration')),
)->plainTextToken;
$exchangeCode = (string) Str::uuid();
Cache::put("google-oauth-exchange:{$exchangeCode}", [
'user_id' => $user->id,
'token' => $token,
], now()->addMinutes(5));
return redirect()->to($context['return_url'].'/login?'.http_build_query([
'oauth_code' => $exchangeCode,
]));
}
/** @return array{user: User, token: string} */
public function exchange(string $exchangeCode): array
{
/** @var array{user_id: int, token: string}|null $authentication */
$authentication = Cache::pull("google-oauth-exchange:{$exchangeCode}");
if (! $authentication) {
throw ValidationException::withMessages([
'oauth_code' => 'El codigo de autenticacion expiro o ya fue utilizado.',
]);
}
return [
'user' => User::query()->findOrFail($authentication['user_id']),
'token' => $authentication['token'],
];
}
private function resolveUser(SocialiteUser $googleUser, Tenant $tenant): User
{
$googleId = $googleUser->getId();
$email = $googleUser->getEmail();
if (! is_string($googleId) || $googleId === '' || ! is_string($email) || ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw ValidationException::withMessages([
'google' => 'Google no devolvio una identidad valida.',
]);
}
$rawUser = $googleUser instanceof \Laravel\Socialite\Two\User ? $googleUser->getRaw() : [];
$emailVerified = $rawUser['email_verified'] ?? $rawUser['verified_email'] ?? false;
if (! in_array($emailVerified, [true, 'true', 1, '1'], true)) {
throw ValidationException::withMessages([
'google' => 'La cuenta de Google debe tener el email verificado.',
]);
}
$user = User::query()->where('google_id', $googleId)->first();
if ($user) {
return $user;
}
$user = User::query()->where('email', $email)->first();
if ($user) {
$user->forceFill(['google_id' => $googleId])->save();
return $user;
}
$name = $googleUser->getName();
$user = User::query()->create([
'nombre_apellido' => is_string($name) && $name !== '' ? $name : $email,
'email' => $email,
'email_verified_at' => now(),
'google_id' => $googleId,
'password' => Str::password(64),
]);
UserRegistered::dispatch($user, $tenant->codigo);
return $user;
}
private function isTenantReturnUrl(string $returnUrl, Tenant $tenant): bool
{
$parts = parse_url($returnUrl);
if (! is_array($parts)
|| ! isset($parts['scheme'], $parts['host'])
|| isset($parts['user'], $parts['pass'], $parts['query'], $parts['fragment'])
|| ($parts['path'] ?? '') !== '') {
return false;
}
$scheme = strtolower($parts['scheme']);
$host = TenantDomainNormalizer::normalize($parts['host']);
$tenantDomain = TenantDomainNormalizer::normalize($tenant->dominio);
if ($host === null || $tenantDomain === null || $host !== $tenantDomain) {
return false;
}
return $scheme === 'https' || ($scheme === 'http' && in_array($host, ['localhost', '127.0.0.1'], true));
}
}

View File

@@ -3,20 +3,27 @@
namespace App\Domains\Auth\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Notification\Events\UserRegistered;
class RegisterUserService
{
/**
* @param array{nombre_apellido: string, email: string, password: string, dni?: string|null, telefono?: string|null} $data
* @param array{tenant_codigo?: string|null, nombre_apellido: string, email: string, password: string, dni?: string|null, telefono?: string|null} $data
*/
public function register(array $data): User
{
return User::query()->create([
$user = User::query()->create([
'nombre_apellido' => $data['nombre_apellido'],
'email' => $data['email'],
'password' => $data['password'],
'dni' => $data['dni'] ?? null,
'telefono' => $data['telefono'] ?? null,
]);
if (! empty($data['tenant_codigo'])) {
UserRegistered::dispatch($user, $data['tenant_codigo']);
}
return $user;
}
}

View File

@@ -1,5 +1,6 @@
<?php
use App\Domains\Auth\Controllers\GoogleTokenExchangeController;
use App\Domains\Auth\Controllers\LoginController;
use App\Domains\Auth\Controllers\LogoutController;
use App\Domains\Auth\Controllers\MeController;
@@ -9,6 +10,7 @@ use Illuminate\Support\Facades\Route;
Route::post('/register', RegisterController::class);
Route::post('/login', LoginController::class);
Route::post('/auth/google/exchange', GoogleTokenExchangeController::class);
Route::middleware('auth:sanctum')->post('/logout', LogoutController::class);
Route::middleware('auth:sanctum')->get('/me', MeController::class);
Route::middleware('auth:sanctum')->put('/me', UpdateProfileController::class);

View File

@@ -13,10 +13,12 @@ class Integration extends Model
'name',
'url',
'integration_data_schema',
'requires_tenant_configuration',
];
protected $casts = [
'integration_data_schema' => 'array',
'requires_tenant_configuration' => 'boolean',
];
public function tenantIntegrations()

View File

@@ -18,6 +18,7 @@ class StoreIntegrationRequest extends FormRequest
'name' => ['required', 'string', 'max:255'],
'url' => ['nullable', 'url', 'max:255'],
'integration_data_schema' => ['nullable', 'array'],
'requires_tenant_configuration' => ['sometimes', 'boolean'],
];
}
}

View File

@@ -19,6 +19,7 @@ class UpdateIntegrationRequest extends FormRequest
'name' => ['sometimes', 'required', 'string', 'max:255'],
'url' => ['nullable', 'url', 'max:255'],
'integration_data_schema' => ['nullable', 'array'],
'requires_tenant_configuration' => ['sometimes', 'boolean'],
// the code shouldn't ideally be updatable, but if it is:
'integration_code' => ['sometimes', 'required', 'string', 'unique:integrations,integration_code,' . ($integration->id ?? '')],
];

View File

@@ -94,7 +94,7 @@ abstract class BaseIntegrationService
->where('integration_code', $this->integrationCode)
->first();
if (!$this->tenantIntegration) {
if (!$this->tenantIntegration && $this->integration->requires_tenant_configuration) {
throw new Exception("Tenant '{$this->tenantCode}' does not have integration '{$this->integrationCode}' configured.");
}
}

View File

@@ -0,0 +1,158 @@
<?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;
private bool $usesTenantMailer = false;
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();
if ($this->tenantIntegration) {
$this->mailer = $this->resolveMailer();
$this->usesTenantMailer = true;
} else {
$this->mailer = $this->mailFactory->mailer();
$this->usesTenantMailer = false;
}
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 $this->usesTenantMailer
? 'tenant-smtp'
: (string) config('mail.default');
}
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

@@ -0,0 +1,32 @@
<?php
namespace App\Domains\MailTest\Controllers;
use App\Domains\MailTest\Requests\SendTestMailRequest;
use App\Domains\MailTest\Services\MailTestService;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
class MailTestController extends Controller
{
public function __construct(
protected MailTestService $mailTestService,
) {}
public function __invoke(SendTestMailRequest $request, string $tenantCode): JsonResponse
{
$tenant = Tenant::query()
->where('codigo', $tenantCode)
->firstOrFail();
return response()->json(
$this->mailTestService->send(
$tenant,
$request->validated('to'),
$request->validated('subject'),
$request->validated('message'),
)
);
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Domains\MailTest\Mailables;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class TestMail extends Mailable
{
use Queueable, SerializesModels;
public function __construct(
public readonly string $mailSubject,
public readonly string $mailMessage,
public readonly Tenant $tenant,
) {}
public function envelope(): Envelope
{
return new Envelope(subject: $this->mailSubject);
}
public function content(): Content
{
$this->tenant->loadMissing(['headerLogo', 'footerLogo']);
return new Content(
view: 'mail.test',
with: [
'tenant' => $this->tenant,
'headerLogoUrl' => $this->tenant->headerLogo?->getTemporaryUrl(1440),
'footerLogoUrl' => $this->tenant->footerLogo?->getTemporaryUrl(1440),
],
);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Domains\MailTest\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SendTestMailRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, array<int, string>>
*/
public function rules(): array
{
return [
'to' => ['required', 'string', 'email', 'max:255'],
'subject' => ['nullable', 'string', 'max:255'],
'message' => ['nullable', 'string', 'max:5000'],
];
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Domains\MailTest\Services;
use App\Domains\Integration\Services\MailService;
use App\Domains\Tenant\Models\Tenant;
class MailTestService
{
/**
* @return array<string, string>
*/
public function send(Tenant $tenant, string $recipient, ?string $subject = null, ?string $message = null): array
{
$subject ??= 'Prueba de correo de Shopit';
$message ??= 'Este es un correo de prueba enviado desde Shopit.';
$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.',
'recipient' => $recipient,
'tenant_code' => $tenant->codigo,
'mailer' => $mailService->mailerName(),
'sent_at' => now()->toIso8601String(),
];
}
}

View File

@@ -0,0 +1,6 @@
<?php
use App\Domains\MailTest\Controllers\MailTestController;
use Illuminate\Support\Facades\Route;
Route::post('{tenant_code}/mail-test/send', MailTestController::class);

View File

@@ -0,0 +1,20 @@
<?php
namespace App\Domains\Notification\Events;
use App\Domains\Purchase\Models\Purchase;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class TicketsAvailable
{
use Dispatchable, SerializesModels;
/**
* @param array<int, int> $ticketIds
*/
public function __construct(
public readonly Purchase $purchase,
public readonly array $ticketIds,
) {}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Domains\Notification\Events;
use App\Domains\Auth\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class UserRegistered
{
use Dispatchable, SerializesModels;
public function __construct(
public readonly User $user,
public readonly string $tenantCode,
) {}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Domains\Notification\Listeners;
use App\Domains\Notification\Services\NotificationMailService;
use App\Domains\Purchase\Events\PurchasePaid;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Queue\InteractsWithQueue;
class SendPurchasePaidEmail implements ShouldQueueAfterCommit
{
use InteractsWithQueue;
public string $queue = 'emails';
public int $tries = 3;
/** @var array<int, int> */
public array $backoff = [30, 120, 300];
public function handle(PurchasePaid $event): void
{
app(NotificationMailService::class)->sendPurchasePaid($event->purchase->getKey());
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Domains\Notification\Listeners;
use App\Domains\Notification\Events\TicketsAvailable;
use App\Domains\Notification\Services\NotificationMailService;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Queue\InteractsWithQueue;
class SendTicketsAvailableEmail implements ShouldQueueAfterCommit
{
use InteractsWithQueue;
public string $queue = 'emails';
public int $tries = 3;
/** @var array<int, int> */
public array $backoff = [30, 120, 300];
public function handle(TicketsAvailable $event): void
{
app(NotificationMailService::class)->sendTicketsAvailable($event->purchase->getKey(), $event->ticketIds);
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Domains\Notification\Listeners;
use App\Domains\Notification\Events\UserRegistered;
use App\Domains\Notification\Services\NotificationMailService;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Queue\InteractsWithQueue;
class SendWelcomeEmail implements ShouldQueueAfterCommit
{
use InteractsWithQueue;
public string $queue = 'emails';
public int $tries = 3;
/** @var array<int, int> */
public array $backoff = [30, 120, 300];
public function handle(UserRegistered $event): void
{
app(NotificationMailService::class)->sendWelcome($event->user->getKey(), $event->tenantCode);
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace App\Domains\Notification\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Integration\Services\MailService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Support\Collection;
class NotificationMailService
{
public function __construct(
private readonly MailService $mailService,
) {}
public function sendWelcome(int $userId, string $tenantCode): void
{
$tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail();
$user = User::query()->findOrFail($userId);
$this->mailService
->forTenant($tenantCode)
->send(
$user->email,
"Bienvenido a {$tenant->nombre}",
view('mail.notifications.welcome', compact('tenant', 'user'))->render(),
);
}
public function sendPurchasePaid(int $purchaseId): void
{
$purchase = Purchase::query()
->with(['tenant', 'user', 'items'])
->findOrFail($purchaseId);
$this->mailService
->forTenant($purchase->tenant_codigo)
->send(
$this->recipientFor($purchase),
"Pago confirmado - Compra #{$purchase->getKey()}",
view('mail.notifications.purchase-paid', compact('purchase'))->render(),
);
}
/** @param array<int, int> $ticketIds */
public function sendTicketsAvailable(int $purchaseId, array $ticketIds): void
{
$purchase = Purchase::query()->with(['tenant', 'user'])->findOrFail($purchaseId);
/** @var Collection<int, Ticket> $tickets */
$tickets = Ticket::query()
->where('tenant_code', $purchase->tenant_codigo)
->where('user_id', $purchase->user_id)
->whereKey($ticketIds)
->get();
if ($tickets->isEmpty()) {
return;
}
$this->mailService
->forTenant($purchase->tenant_codigo)
->send(
$this->recipientFor($purchase),
'Tus tickets ya están disponibles',
view('mail.notifications.tickets-available', compact('purchase', 'tickets'))->render(),
);
}
private function recipientFor(Purchase $purchase): string
{
return (string) ($purchase->email ?: $purchase->user?->email);
}
}

View File

@@ -3,6 +3,7 @@
namespace App\Domains\Ticket\Listeners;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Notification\Events\TicketsAvailable;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Ticket\Exceptions\TicketGenerationException;
use App\Domains\Ticket\Services\TicketGeneratorService;
@@ -20,6 +21,7 @@ class GenerateTicketsForPaidPurchase
->with(['user', 'items'])
->findOrFail($event->purchase->getKey());
$user = $purchase->user;
$ticketIds = [];
foreach ($purchase->items as $purchaseItem) {
$catalogItem = CatalogItem::query()
@@ -38,12 +40,18 @@ class GenerateTicketsForPaidPurchase
throw TicketGenerationException::purchaseWithoutUser($purchase);
}
$this->ticketGenerator->generate(
$generatedTickets = $this->ticketGenerator->generate(
$catalogItem,
$user,
$purchaseItem->cantidad,
$purchaseItem->source_variant_id,
);
array_push($ticketIds, ...$generatedTickets->pluck('id')->all());
}
if ($ticketIds !== []) {
TicketsAvailable::dispatch($purchase, $ticketIds);
}
}

View File

@@ -2,6 +2,11 @@
namespace App\Providers;
use App\Domains\Notification\Events\TicketsAvailable;
use App\Domains\Notification\Events\UserRegistered;
use App\Domains\Notification\Listeners\SendPurchasePaidEmail;
use App\Domains\Notification\Listeners\SendTicketsAvailableEmail;
use App\Domains\Notification\Listeners\SendWelcomeEmail;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Ticket\Listeners\GenerateTicketsForPaidPurchase;
use Illuminate\Database\Eloquent\Builder;
@@ -23,7 +28,10 @@ class AppServiceProvider extends ServiceProvider
*/
public function boot(): void
{
Event::listen(PurchasePaid::class, SendPurchasePaidEmail::class);
Event::listen(PurchasePaid::class, GenerateTicketsForPaidPurchase::class);
Event::listen(TicketsAvailable::class, SendTicketsAvailableEmail::class);
Event::listen(UserRegistered::class, SendWelcomeEmail::class);
Builder::macro('paginateFromRequest', function (int $defaultPerPage = 15, int $maxPerPage = 100, ?int $page = null) {
/** @var Builder $this */

View File

@@ -9,8 +9,9 @@
"php": "^8.3",
"laravel/framework": "^13.8",
"laravel/sanctum": "^4.3",
"laravel/socialite": "^5.29",
"laravel/tinker": "^3.0",
"league/flysystem-aws-s3-v3": "^3.0"
"league/flysystem-aws-s3-v3": "^3.0"
},
"require-dev": {
"fakerphp/faker": "^1.23",
@@ -44,7 +45,7 @@
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --queue=emails,default --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi @no_additional_args",

445
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "15f02d79a83b338e4181fb79dcd0a600",
"content-hash": "484f8cfa9bdc596ad33f42417d839354",
"packages": [
{
"name": "aws/aws-crt-php",
@@ -658,6 +658,72 @@
],
"time": "2025-03-06T22:45:56+00:00"
},
{
"name": "firebase/php-jwt",
"version": "v7.1.0",
"source": {
"type": "git",
"url": "https://github.com/googleapis/php-jwt.git",
"reference": "b374a5d1a4f1f67fadc2165cdb284645945e2fc0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/googleapis/php-jwt/zipball/b374a5d1a4f1f67fadc2165cdb284645945e2fc0",
"reference": "b374a5d1a4f1f67fadc2165cdb284645945e2fc0",
"shasum": ""
},
"require": {
"php": "^8.0"
},
"require-dev": {
"guzzlehttp/guzzle": "^7.4",
"phpfastcache/phpfastcache": "^9.2",
"phpseclib/phpseclib": "~3.0",
"phpspec/prophecy-phpunit": "^2.0",
"phpunit/phpunit": "^9.5",
"psr/cache": "^2.0||^3.0",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0"
},
"suggest": {
"ext-sodium": "Support EdDSA (Ed25519) signatures",
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present",
"phpseclib/phpseclib": "Support PS256 (RSASSA-PSS) signatures"
},
"type": "library",
"autoload": {
"psr-4": {
"Firebase\\JWT\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Neuman Vong",
"email": "neuman+pear@twilio.com",
"role": "Developer"
},
{
"name": "Anant Narayanan",
"email": "anant@php.net",
"role": "Developer"
}
],
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
"homepage": "https://github.com/googleapis/php-jwt",
"keywords": [
"jwt",
"php"
],
"support": {
"issues": "https://github.com/googleapis/php-jwt/issues",
"source": "https://github.com/googleapis/php-jwt/tree/v7.1.0"
},
"time": "2026-06-11T17:54:14+00:00"
},
{
"name": "fruitcake/php-cors",
"version": "v1.4.0",
@@ -1615,6 +1681,78 @@
},
"time": "2026-04-16T14:03:50+00:00"
},
{
"name": "laravel/socialite",
"version": "v5.29.0",
"source": {
"type": "git",
"url": "https://github.com/laravel/socialite.git",
"reference": "cd343a5841f02292af119ee607edc71300c9ae4f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/socialite/zipball/cd343a5841f02292af119ee607edc71300c9ae4f",
"reference": "cd343a5841f02292af119ee607edc71300c9ae4f",
"shasum": ""
},
"require": {
"ext-json": "*",
"firebase/php-jwt": "^6.4|^7.0",
"guzzlehttp/guzzle": "^6.0|^7.0",
"illuminate/contracts": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"illuminate/http": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"illuminate/support": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0|^12.0|^13.0",
"league/oauth1-client": "^1.11",
"php": "^7.2|^8.0",
"phpseclib/phpseclib": "^3.0"
},
"require-dev": {
"mockery/mockery": "^1.0",
"orchestra/testbench": "^4.18|^5.20|^6.47|^7.55|^8.36|^9.15|^10.8|^11.0",
"phpstan/phpstan": "^1.12.23",
"phpunit/phpunit": "^8.0|^9.3|^10.4|^11.5|^12.0"
},
"type": "library",
"extra": {
"laravel": {
"aliases": {
"Socialite": "Laravel\\Socialite\\Facades\\Socialite"
},
"providers": [
"Laravel\\Socialite\\SocialiteServiceProvider"
]
},
"branch-alias": {
"dev-master": "5.x-dev"
}
},
"autoload": {
"psr-4": {
"Laravel\\Socialite\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "Laravel wrapper around OAuth 1 & OAuth 2 libraries.",
"homepage": "https://laravel.com",
"keywords": [
"laravel",
"oauth"
],
"support": {
"issues": "https://github.com/laravel/socialite/issues",
"source": "https://github.com/laravel/socialite"
},
"time": "2026-07-01T13:50:23+00:00"
},
{
"name": "laravel/tinker",
"version": "v3.0.2",
@@ -2116,6 +2254,82 @@
],
"time": "2024-09-21T08:32:55+00:00"
},
{
"name": "league/oauth1-client",
"version": "v1.11.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/oauth1-client.git",
"reference": "f9c94b088837eb1aae1ad7c4f23eb65cc6993055"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/oauth1-client/zipball/f9c94b088837eb1aae1ad7c4f23eb65cc6993055",
"reference": "f9c94b088837eb1aae1ad7c4f23eb65cc6993055",
"shasum": ""
},
"require": {
"ext-json": "*",
"ext-openssl": "*",
"guzzlehttp/guzzle": "^6.0|^7.0",
"guzzlehttp/psr7": "^1.7|^2.0",
"php": ">=7.1||>=8.0"
},
"require-dev": {
"ext-simplexml": "*",
"friendsofphp/php-cs-fixer": "^2.17",
"mockery/mockery": "^1.3.3",
"phpstan/phpstan": "^0.12.42",
"phpunit/phpunit": "^7.5||9.5"
},
"suggest": {
"ext-simplexml": "For decoding XML-based responses."
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0-dev",
"dev-develop": "2.0-dev"
}
},
"autoload": {
"psr-4": {
"League\\OAuth1\\Client\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ben Corlett",
"email": "bencorlett@me.com",
"homepage": "http://www.webcomm.com.au",
"role": "Developer"
}
],
"description": "OAuth 1.0 Client Library",
"keywords": [
"Authentication",
"SSO",
"authorization",
"bitbucket",
"identity",
"idp",
"oauth",
"oauth1",
"single sign on",
"trello",
"tumblr",
"twitter"
],
"support": {
"issues": "https://github.com/thephpleague/oauth1-client/issues",
"source": "https://github.com/thephpleague/oauth1-client/tree/v1.11.0"
},
"time": "2024-12-10T19:59:05+00:00"
},
{
"name": "league/uri",
"version": "7.8.1",
@@ -2875,6 +3089,125 @@
],
"time": "2026-02-16T23:10:27+00:00"
},
{
"name": "paragonie/constant_time_encoding",
"version": "v3.1.3",
"source": {
"type": "git",
"url": "https://github.com/paragonie/constant_time_encoding.git",
"reference": "d5b01a39b3415c2cd581d3bd3a3575c1ebbd8e77"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/constant_time_encoding/zipball/d5b01a39b3415c2cd581d3bd3a3575c1ebbd8e77",
"reference": "d5b01a39b3415c2cd581d3bd3a3575c1ebbd8e77",
"shasum": ""
},
"require": {
"php": "^8"
},
"require-dev": {
"infection/infection": "^0",
"nikic/php-fuzzer": "^0",
"phpunit/phpunit": "^9|^10|^11",
"vimeo/psalm": "^4|^5|^6"
},
"type": "library",
"autoload": {
"psr-4": {
"ParagonIE\\ConstantTime\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com",
"role": "Maintainer"
},
{
"name": "Steve 'Sc00bz' Thomas",
"email": "steve@tobtu.com",
"homepage": "https://www.tobtu.com",
"role": "Original Developer"
}
],
"description": "Constant-time Implementations of RFC 4648 Encoding (Base-64, Base-32, Base-16)",
"keywords": [
"base16",
"base32",
"base32_decode",
"base32_encode",
"base64",
"base64_decode",
"base64_encode",
"bin2hex",
"encoding",
"hex",
"hex2bin",
"rfc4648"
],
"support": {
"email": "info@paragonie.com",
"issues": "https://github.com/paragonie/constant_time_encoding/issues",
"source": "https://github.com/paragonie/constant_time_encoding"
},
"time": "2025-09-24T15:06:41+00:00"
},
{
"name": "paragonie/random_compat",
"version": "v9.99.100",
"source": {
"type": "git",
"url": "https://github.com/paragonie/random_compat.git",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a",
"shasum": ""
},
"require": {
"php": ">= 7"
},
"require-dev": {
"phpunit/phpunit": "4.*|5.*",
"vimeo/psalm": "^1"
},
"suggest": {
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
},
"type": "library",
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com"
}
],
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
"keywords": [
"csprng",
"polyfill",
"pseudorandom",
"random"
],
"support": {
"email": "info@paragonie.com",
"issues": "https://github.com/paragonie/random_compat/issues",
"source": "https://github.com/paragonie/random_compat"
},
"time": "2020-10-15T08:29:30+00:00"
},
{
"name": "phpoption/phpoption",
"version": "1.9.5",
@@ -2950,6 +3283,116 @@
],
"time": "2025-12-27T19:41:33+00:00"
},
{
"name": "phpseclib/phpseclib",
"version": "3.0.55",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
"reference": "db9744e6d47e742b1f974e965ad49bdd041105af"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/db9744e6d47e742b1f974e965ad49bdd041105af",
"reference": "db9744e6d47e742b1f974e965ad49bdd041105af",
"shasum": ""
},
"require": {
"paragonie/constant_time_encoding": "^1|^2|^3",
"paragonie/random_compat": "^1.4|^2.0|^9.99.99",
"php": ">=5.6.1"
},
"require-dev": {
"phpunit/phpunit": "*"
},
"suggest": {
"ext-dom": "Install the DOM extension to load XML formatted public keys.",
"ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.",
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",
"ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.",
"ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations."
},
"type": "library",
"autoload": {
"files": [
"phpseclib/bootstrap.php"
],
"psr-4": {
"phpseclib3\\": "phpseclib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jim Wigginton",
"email": "terrafrost@php.net",
"role": "Lead Developer"
},
{
"name": "Patrick Monnerat",
"email": "pm@datasphere.ch",
"role": "Developer"
},
{
"name": "Andreas Fischer",
"email": "bantu@phpbb.com",
"role": "Developer"
},
{
"name": "Hans-Jürgen Petrich",
"email": "petrich@tronic-media.com",
"role": "Developer"
},
{
"name": "Graham Campbell",
"email": "graham@alt-three.com",
"role": "Developer"
}
],
"description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.",
"homepage": "http://phpseclib.sourceforge.net",
"keywords": [
"BigInteger",
"aes",
"asn.1",
"asn1",
"blowfish",
"crypto",
"cryptography",
"encryption",
"rsa",
"security",
"sftp",
"signature",
"signing",
"ssh",
"twofish",
"x.509",
"x509"
],
"support": {
"issues": "https://github.com/phpseclib/phpseclib/issues",
"source": "https://github.com/phpseclib/phpseclib/tree/3.0.55"
},
"funding": [
{
"url": "https://github.com/terrafrost",
"type": "github"
},
{
"url": "https://www.patreon.com/phpseclib",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib",
"type": "tidelift"
}
],
"time": "2026-06-14T23:24:10+00:00"
},
{
"name": "psr/clock",
"version": "1.0.0",

View File

@@ -39,4 +39,10 @@ return [
'secret' => env('INTEGRATION_SECRET'),
],
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URI'),
],
];

View File

@@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->string('google_id')->nullable()->unique()->after('email');
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table): void {
$table->dropUnique(['google_id']);
$table->dropColumn('google_id');
});
}
};

View File

@@ -0,0 +1,27 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('integrations', function (Blueprint $table) {
$table->boolean('requires_tenant_configuration')->default(true);
});
DB::table('integrations')
->where('integration_code', 'email')
->update(['requires_tenant_configuration' => false]);
}
public function down(): void
{
Schema::table('integrations', function (Blueprint $table) {
$table->dropColumn('requires_tenant_configuration');
});
}
};

View File

@@ -30,6 +30,7 @@ class DatabaseSeeder extends Seeder
ProductCatalogFromImagesSeeder::class,
FiestaFutbolInfantilProductSeeder::class,
TelepagosIntegrationSeeder::class,
EmailIntegrationSeeder::class,
MenuSeeder::class,
]);
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Database\Seeders;
use App\Domains\Integration\Models\Integration;
use Illuminate\Database\Seeder;
class EmailIntegrationSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
Integration::updateOrCreate(
['integration_code' => 'email'],
[
'name' => 'Email',
'url' => null,
'requires_tenant_configuration' => false,
'integration_data_schema' => [
'MAIL_MAILER' => 'required|string|in:smtp',
'MAIL_SCHEME' => 'required|string|in:smtp',
'MAIL_HOST' => 'required|string',
'MAIL_PORT' => 'required|integer|in:587',
'MAIL_USERNAME' => 'required|email',
'MAIL_PASSWORD' => 'required|string',
'MAIL_FROM_ADDRESS' => 'required|email',
'MAIL_FROM_NAME' => 'nullable|string|max:255',
],
]
);
}
}

View File

@@ -17,6 +17,7 @@ class TelepagosIntegrationSeeder extends Seeder
[
'name' => 'Telepagos',
'url' => 'https://api.telepagos.com.ar',
'requires_tenant_configuration' => true,
'integration_data_schema' => [
'username' => 'required|string',
'password' => 'required|string',
@@ -29,6 +30,7 @@ class TelepagosIntegrationSeeder extends Seeder
[
'name' => 'Telepagos Homologación',
'url' => 'https://api.homo.telepagos.com.ar',
'requires_tenant_configuration' => true,
'integration_data_schema' => [
'username' => 'required|string',
'password' => 'required|string',

View File

@@ -0,0 +1,49 @@
@props(['tenant', 'headerLogoUrl' => null, 'footerLogoUrl' => null])
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light">
<title>{{ $tenant->nombre }}</title>
<style>
@media only screen and (max-width: 620px) {
.mail-container { width: 100% !important; }
.mail-content { padding: 32px 24px !important; }
}
</style>
</head>
<body style="margin: 0; padding: 0; background-color: #f1f5f9; color: #334155; font-family: Arial, Helvetica, sans-serif;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background-color: #f1f5f9;">
<tr>
<td align="center" style="padding: 32px 12px;">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" border="0" class="mail-container" style="width: 600px; max-width: 600px; background-color: #ffffff; border-top: 4px solid {{ $tenant->primary_color }}; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(15, 23, 42, 0.08);">
<tr>
<td align="center" bgcolor="{{ $tenant->header_bg_color }}" style="padding: 24px 32px; background-color: {{ $tenant->header_bg_color }};">
@if ($headerLogoUrl)
<img src="{{ $headerLogoUrl }}" alt="{{ $tenant->nombre }}" width="180" style="display: block; width: auto; max-width: 180px; max-height: 64px; border: 0;">
@else
<span style="color: {{ $tenant->primary_color }}; font-size: 24px; font-weight: 700; line-height: 1.2;">{{ $tenant->nombre }}</span>
@endif
</td>
</tr>
<tr>
<td class="mail-content" style="padding: 40px 48px; font-size: 16px; line-height: 1.6;">
{{ $slot }}
</td>
</tr>
<tr>
<td align="center" bgcolor="{{ $tenant->footer_bg_color }}" style="padding: 24px 32px; background-color: {{ $tenant->footer_bg_color }}; color: #ffffff; font-size: 12px; line-height: 1.5;">
@if ($footerLogoUrl)
<img src="{{ $footerLogoUrl }}" alt="{{ $tenant->nombre }}" width="140" style="display: block; width: auto; max-width: 140px; max-height: 48px; margin: 0 auto 16px; border: 0;">
@endif
{{ $footer ?? 'Este correo fue enviado por '.$tenant->nombre.'.' }}
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,12 @@
<h1 style="margin: 0 0 20px;">¡Recibimos tu pago!</h1>
<p>La compra <strong>#{{ $purchase->id }}</strong> fue confirmada correctamente.</p>
<table role="presentation" style="width: 100%; border-collapse: collapse; margin: 20px 0;">
@foreach ($purchase->items as $item)
<tr>
<td style="padding: 8px 0; border-bottom: 1px solid #e2e8f0;">{{ $item->item_nombre }}</td>
<td style="padding: 8px 0; border-bottom: 1px solid #e2e8f0; text-align: center;">× {{ $item->cantidad }}</td>
<td style="padding: 8px 0; border-bottom: 1px solid #e2e8f0; text-align: right;">${{ number_format((float) $item->total, 2, ',', '.') }}</td>
</tr>
@endforeach
</table>
<p style="font-size: 18px;"><strong>Total pagado: ${{ number_format((float) $purchase->total, 2, ',', '.') }}</strong></p>

View File

@@ -0,0 +1,7 @@
<h1 style="margin: 0 0 20px;">Tus tickets ya están disponibles</h1>
<p>Generamos {{ $tickets->count() }} {{ $tickets->count() === 1 ? 'ticket' : 'tickets' }} para la compra <strong>#{{ $purchase->id }}</strong>.</p>
<ul style="padding-left: 20px;">
@foreach ($tickets as $ticket)
<li style="margin-bottom: 8px;">{{ $ticket->name }}</li>
@endforeach
</ul>

View File

@@ -0,0 +1,3 @@
<h1 style="margin: 0 0 20px;">¡Bienvenido a {{ $tenant->nombre }}!</h1>
<p>Hola {{ $user->nombre_apellido }}, tu cuenta fue creada correctamente.</p>
<p>Ya podés ingresar y comenzar a comprar.</p>

View File

@@ -0,0 +1,11 @@
<x-mail.branded-layout :tenant="$tenant" :header-logo-url="$headerLogoUrl" :footer-logo-url="$footerLogoUrl">
<h1 style="margin: 0 0 20px; color: {{ $tenant->primary_color }}; font-size: 26px; line-height: 1.3;">
Prueba de correo de Shopit
</h1>
<p style="margin: 0 0 16px;">{!! nl2br(e($mailMessage)) !!}</p>
<p style="margin: 24px 0 0; color: #64748b; font-size: 13px;">
Si recibiste este mensaje, la configuración de correo funciona correctamente.
</p>
</x-mail.branded-layout>

View File

@@ -4,6 +4,7 @@ require __DIR__.'/../app/Domains/Auth/routes/api.php';
require __DIR__.'/../app/Domains/Catalog/routes/api.php';
require __DIR__.'/../app/Domains/Cart/routes/api.php';
require __DIR__.'/../app/Domains/StorageTest/routes/api.php';
require __DIR__.'/../app/Domains/MailTest/routes/api.php';
require __DIR__.'/../app/Domains/Purchase/routes/api.php';
require __DIR__.'/../app/Domains/Tenant/routes/api.php';
require __DIR__.'/../app/Domains/Integration/routes/api.php';

View File

@@ -1,7 +1,11 @@
<?php
use App\Domains\Auth\Controllers\GoogleAuthController;
use Illuminate\Support\Facades\Route;
Route::get('/auth/google/redirect', [GoogleAuthController::class, 'redirect'])->name('auth.google.redirect');
Route::get('/api/auth/google/callback', [GoogleAuthController::class, 'callback'])->name('auth.google.callback');
Route::get('/', function () {
return view('welcome');
});

View File

@@ -2,8 +2,13 @@
namespace Tests\Feature\Auth;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Notification\Events\UserRegistered;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Tests\TestCase;
class RegisterControllerTest extends TestCase
@@ -15,8 +20,8 @@ class RegisterControllerTest extends TestCase
$response = $this->postJson('/api/register', [
'nombre_apellido' => 'Ada Lovelace',
'email' => 'ada@example.com',
'password' => 'secret123',
'password_confirmation' => 'secret123',
'password' => 'Secret!123',
'password_confirmation' => 'Secret!123',
'dni' => '12345678A',
'telefono' => '+541122334455',
]);
@@ -38,7 +43,7 @@ class RegisterControllerTest extends TestCase
$user = User::query()->where('email', 'ada@example.com')->firstOrFail();
$this->assertNotSame('secret123', $user->password);
$this->assertNotSame('Secret!123', $user->password);
}
public function test_it_registers_a_user_without_optional_fields(): void
@@ -46,8 +51,8 @@ class RegisterControllerTest extends TestCase
$response = $this->postJson('/api/register', [
'nombre_apellido' => 'Alan Turing',
'email' => 'alan@example.com',
'password' => 'secret123',
'password_confirmation' => 'secret123',
'password' => 'Secret!123',
'password_confirmation' => 'Secret!123',
]);
$response
@@ -66,6 +71,50 @@ class RegisterControllerTest extends TestCase
]);
}
public function test_it_dispatches_the_welcome_notification_with_tenant_context(): void
{
Event::fake([UserRegistered::class]);
$header = Attachment::query()->create([
'path' => 'test/welcome-header.png',
'filename' => 'header.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
$footer = Attachment::query()->create([
'path' => 'test/welcome-footer.png',
'filename' => 'footer.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
$tenant = Tenant::query()->create([
'codigo' => 'welcome-tenant',
'nombre' => 'Welcome Tenant',
'dominio' => 'welcome.local',
'primary_color' => '#000000',
'secondary_color' => '#000000',
'danger_color' => '#000000',
'success_color' => '#000000',
'header_bg_color' => '#000000',
'footer_bg_color' => '#000000',
'header_logo_id' => $header->id,
'footer_logo_id' => $footer->id,
]);
$this->postJson('/api/register', [
'tenant_codigo' => $tenant->codigo,
'nombre_apellido' => 'Grace Hopper',
'email' => 'grace@example.com',
'password' => 'Secret!123',
'password_confirmation' => 'Secret!123',
])->assertCreated();
Event::assertDispatched(
UserRegistered::class,
fn (UserRegistered $event): bool => $event->tenantCode === $tenant->codigo
&& $event->user->email === 'grace@example.com',
);
}
public function test_it_validates_required_fields_and_unique_email(): void
{
User::factory()->create([

View File

@@ -0,0 +1,169 @@
<?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_it_uses_the_default_mailer_when_tenant_configuration_is_not_required(): void
{
Mail::fake();
config(['mail.default' => 'array']);
$tenant = $this->createTenant();
Integration::create([
'integration_code' => 'email',
'name' => 'Email',
'requires_tenant_configuration' => false,
]);
$service = (new MailService)->forTenant($tenant->codigo);
$service->send('customer@example.com', 'Default mailer', '<p>Fallback</p>');
$this->assertSame('array', $service->mailerName());
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
return $mail->hasTo('customer@example.com')
&& $mail->subject === 'Default mailer'
&& str_contains($mail->render(), 'Fallback');
});
}
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

@@ -19,6 +19,7 @@ use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
use Tests\TestCase;
@@ -32,6 +33,7 @@ class TelepagosWebhookTest extends TestCase
config(['services.integrations.secret' => 'base64:'.base64_encode(random_bytes(32))]);
Cache::flush();
Queue::fake();
}
public function test_transfer_payment_intent_requires_a_valid_transfer_payer_dni(): void

View File

@@ -0,0 +1,189 @@
<?php
namespace Tests\Feature\MailTest;
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\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;
class MailTestControllerTest extends TestCase
{
use RefreshDatabase;
public function test_it_sends_a_test_email(): void
{
Mail::fake();
$tenant = $this->createTenant();
$response = $this->postJson('/api/acme/mail-test/send', [
'to' => 'recipient@example.com',
'subject' => 'SMTP test',
'message' => 'Test message',
]);
$response->assertOk()
->assertJsonPath('message', 'Correo de prueba enviado correctamente.')
->assertJsonPath('recipient', 'recipient@example.com')
->assertJsonPath('tenant_code', 'acme')
->assertJsonPath('mailer', 'tenant-smtp')
->assertJsonStructure(['sent_at']);
Mail::assertSent(Mailable::class, function (Mailable $mail) use ($tenant): bool {
return $mail->hasTo('recipient@example.com')
&& $mail->subject === 'SMTP test'
&& str_contains($mail->render(), 'Test message')
&& str_contains($mail->render(), $tenant->nombre);
});
}
public function test_it_uses_default_content_when_optional_fields_are_omitted(): void
{
Mail::fake();
$this->createTenant();
$this->postJson('/api/acme/mail-test/send', [
'to' => 'recipient@example.com',
])->assertOk();
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_validates_the_recipient(): void
{
Mail::fake();
$this->createTenant();
$this->postJson('/api/acme/mail-test/send', [
'to' => 'invalid-email',
])->assertUnprocessable()
->assertJsonValidationErrors(['to']);
Mail::assertNothingSent();
}
public function test_the_mail_template_uses_the_tenant_branding(): void
{
$tenant = new Tenant([
'codigo' => 'tenant-store',
'nombre' => 'Tenant Store',
'primary_color' => '#778899',
'header_bg_color' => '#112233',
'footer_bg_color' => '#445566',
]);
$tenant->setRelation('headerLogo', new class extends Attachment
{
public function getTemporaryUrl(int $expiresInMinutes = 10): string
{
return 'https://example.com/header-logo.png';
}
});
$tenant->setRelation('footerLogo', new class extends Attachment
{
public function getTemporaryUrl(int $expiresInMinutes = 10): string
{
return 'https://example.com/footer-logo.png';
}
});
$mail = new TestMail(
'Branded email',
'Tenant message',
$tenant,
);
$html = $mail->render();
$this->assertStringContainsString('https://example.com/header-logo.png', $html);
$this->assertStringContainsString('https://example.com/footer-logo.png', $html);
$this->assertStringContainsString('background-color: #112233', $html);
$this->assertStringContainsString('background-color: #445566', $html);
$this->assertStringContainsString('color: #778899', $html);
$this->assertStringContainsString('Tenant Store', $html);
$this->assertStringContainsString('Tenant message', $html);
}
public function test_it_returns_not_found_for_an_unknown_tenant(): void
{
Mail::fake();
$this->postJson('/api/unknown/mail-test/send', [
'to' => 'recipient@example.com',
])->assertNotFound();
Mail::assertNothingSent();
}
public function test_it_does_not_resolve_the_tenant_by_id(): void
{
Mail::fake();
$tenant = $this->createTenant();
$this->postJson("/api/{$tenant->id}/mail-test/send", [
'to' => 'recipient@example.com',
])->assertNotFound();
Mail::assertNothingSent();
}
private function createTenant(): Tenant
{
$headerLogo = Attachment::create([
'path' => 'tenants/header.png',
'filename' => 'header.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
'extension' => 'png',
]);
$footerLogo = Attachment::create([
'path' => 'tenants/footer.png',
'filename' => 'footer.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' => $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;
}
}

View File

@@ -0,0 +1,138 @@
<?php
namespace Tests\Feature\Notification;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Integration\Models\Integration;
use App\Domains\Notification\Services\NotificationMailService;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\Mailable;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
class NotificationMailServiceTest extends TestCase
{
use RefreshDatabase;
private Tenant $tenant;
private User $user;
protected function setUp(): void
{
parent::setUp();
Mail::fake();
Integration::query()->create([
'integration_code' => 'email',
'name' => 'Email',
'url' => null,
'requires_tenant_configuration' => false,
'integration_data_schema' => [],
]);
$header = Attachment::query()->create([
'path' => 'test/mail-header.png',
'filename' => 'header.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
$footer = Attachment::query()->create([
'path' => 'test/mail-footer.png',
'filename' => 'footer.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
$this->tenant = Tenant::query()->create([
'codigo' => 'mail-tenant',
'nombre' => 'Mail Tenant',
'dominio' => 'mail.local',
'primary_color' => '#112233',
'secondary_color' => '#000000',
'danger_color' => '#000000',
'success_color' => '#000000',
'header_bg_color' => '#000000',
'footer_bg_color' => '#000000',
'header_logo_id' => $header->id,
'footer_logo_id' => $footer->id,
]);
$this->user = User::factory()->create([
'nombre_apellido' => 'Ada Lovelace',
'email' => 'ada@example.com',
]);
}
public function test_it_sends_a_branded_welcome_email(): void
{
app(NotificationMailService::class)->sendWelcome($this->user->id, $this->tenant->codigo);
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
$mail->assertTo('ada@example.com');
$mail->assertHasSubject('Bienvenido a Mail Tenant');
return str_contains($mail->render(), 'Ada Lovelace')
&& str_contains($mail->render(), 'Mail Tenant');
});
}
public function test_it_sends_purchase_and_ticket_emails_to_the_purchase_recipient(): void
{
$purchase = Purchase::query()->create([
'tenant_codigo' => $this->tenant->codigo,
'user_id' => $this->user->id,
'status' => Purchase::STATUS_PAID,
'payment_method' => 'transfer',
'total' => 25,
'email' => 'checkout@example.com',
]);
$catalogItem = CatalogItem::query()->create([
'tenant_code' => $this->tenant->codigo,
'slug' => 'entrada',
'nombre' => 'Entrada',
'descripcion' => 'Entrada general',
'precio' => 25,
'has_tickets' => true,
]);
$purchase->items()->create([
'source_catalog_item_id' => $catalogItem->id,
'nombre' => 'Entrada',
'descripcion' => 'Entrada general',
'slug' => 'entrada',
'item_nombre' => 'Entrada general',
'variant_attributes' => [],
'cantidad' => 1,
'precio_unitario' => 25,
'total' => 25,
]);
$ticket = Ticket::query()->create([
'tenant_code' => $this->tenant->codigo,
'ticket' => fake()->uuid(),
'name' => 'Entrada general',
'description' => 'Entrada general',
'user_id' => $this->user->id,
]);
$service = app(NotificationMailService::class);
$service->sendPurchasePaid($purchase->id);
$service->sendTicketsAvailable($purchase->id, [$ticket->id]);
Mail::assertSent(Mailable::class, 2);
Mail::assertSent(Mailable::class, function (Mailable $mail) use ($purchase): bool {
$mail->assertTo('checkout@example.com');
return $mail->subject === "Pago confirmado - Compra #{$purchase->id}"
&& str_contains($mail->render(), 'Total pagado');
});
Mail::assertSent(Mailable::class, function (Mailable $mail): bool {
$mail->assertTo('checkout@example.com');
return $mail->subject === 'Tus tickets ya están disponibles'
&& str_contains($mail->render(), 'Entrada general');
});
}
}

View File

@@ -15,6 +15,7 @@ use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
use Tests\TestCase;
@@ -22,6 +23,13 @@ class StorePurchaseTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Queue::fake();
}
public function test_it_creates_a_purchase_from_cart_id_without_persisting_items_yet(): void
{
$tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');

View File

@@ -7,6 +7,7 @@ use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Notification\Events\TicketsAvailable;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Exceptions\TicketGenerationException;
@@ -14,6 +15,8 @@ use App\Domains\Ticket\Services\TicketGeneratorService;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
use Tests\TestCase;
@@ -32,6 +35,7 @@ class TicketGeneratorServiceTest extends TestCase
parent::setUp();
Carbon::setTestNow('2026-07-21 10:00:00');
Queue::fake();
$this->service = app(TicketGeneratorService::class);
$this->tenant = $this->createTenant();
$this->user = User::factory()->create();
@@ -128,6 +132,7 @@ class TicketGeneratorServiceTest extends TestCase
public function test_marking_a_purchase_as_paid_generates_its_tickets_once(): void
{
Event::fake([TicketsAvailable::class]);
$item = $this->createTicketableItem('paid-ticket');
$purchase = $this->createPurchase($item, 2);
$purchase->setRelation('items', new EloquentCollection);
@@ -136,10 +141,12 @@ class TicketGeneratorServiceTest extends TestCase
$this->assertSame(Purchase::STATUS_PAID, $purchase->status);
$this->assertDatabaseCount('tickets', 2);
Event::assertDispatchedTimes(TicketsAvailable::class, 1);
$purchase->markAsPaid();
$this->assertDatabaseCount('tickets', 2);
Event::assertDispatchedTimes(TicketsAvailable::class, 1);
}
public function test_a_ticket_generated_from_a_purchase_keeps_its_source_ids(): void
@@ -157,6 +164,7 @@ class TicketGeneratorServiceTest extends TestCase
public function test_marking_a_purchase_as_paid_ignores_items_without_tickets(): void
{
Event::fake([TicketsAvailable::class]);
$item = $this->createTicketableItem('regular-product');
$item->update(['has_tickets' => false]);
$purchase = $this->createPurchase($item->fresh(), 1);
@@ -165,6 +173,7 @@ class TicketGeneratorServiceTest extends TestCase
$this->assertSame(Purchase::STATUS_PAID, $purchase->status);
$this->assertDatabaseCount('tickets', 0);
Event::assertNotDispatched(TicketsAvailable::class);
}
public function test_paid_status_is_rolled_back_when_ticket_generation_fails(): void