Compare commits

...

9 Commits

Author SHA1 Message Date
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
e1a67fd9f3 feat(ticket): add TicketController, TicketResource, and related routes with tests 2026-07-21 14:56:17 -03:00
38f74739da feat(ticket): add source IDs to tickets and update related services and tests 2026-07-21 12:27:26 -03:00
c0978033c1 feat(ticket): implement ticket generation on purchase payment and add related tests 2026-07-21 11:23:17 -03:00
a928a2e848 feat(ticket): implement ticket generation service, model, and exception handling with tests 2026-07-21 11:20:52 -03:00
37 changed files with 2044 additions and 995 deletions

View File

@@ -51,10 +51,10 @@ 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
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

@@ -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,14 @@
<?php
namespace App\Domains\Purchase\Events;
use App\Domains\Purchase\Models\Purchase;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PurchasePaid
{
use Dispatchable, SerializesModels;
public function __construct(public readonly Purchase $purchase) {}
}

View File

@@ -4,6 +4,7 @@ namespace App\Domains\Purchase\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -11,6 +12,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\DB;
#[Fillable([
'cart_id',
@@ -137,8 +139,23 @@ class Purchase extends Model
public function markAsPaid(): void
{
$this->update([
'status' => self::STATUS_PAID,
]);
DB::transaction(function (): void {
$currentStatus = self::query()
->whereKey($this->getKey())
->lockForUpdate()
->value('status');
if ($currentStatus === self::STATUS_PAID) {
$this->status = self::STATUS_PAID;
return;
}
$this->update([
'status' => self::STATUS_PAID,
]);
PurchasePaid::dispatch($this);
});
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Domains\Ticket\Controllers;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use App\Domains\Ticket\Resources\TicketResource;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class TicketController extends Controller
{
public function index(Request $request, Tenant $tenant): JsonResponse
{
$tickets = Ticket::query()
->where('tenant_code', $tenant->codigo)
->where('user_id', $request->user()->getKey())
->orderByDesc('id')
->get();
return TicketResource::collection($tickets)->response();
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Domains\Ticket\Exceptions;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use RuntimeException;
class TicketGenerationException extends RuntimeException
{
public static function invalidQuantity(): self
{
return new self('La cantidad de tickets a generar debe ser mayor a cero.');
}
public static function emptyBundle(CatalogItem $bundle): self
{
return new self("El bundle {$bundle->id} no tiene componentes.");
}
public static function ticketsDisabled(CatalogItem $catalogItem): self
{
return new self("El producto {$catalogItem->id} no tiene tickets habilitados.");
}
public static function maximumUseDateReached(CatalogItem $catalogItem): self
{
return new self("El producto {$catalogItem->id} alcanzó su fecha máxima de uso.");
}
public static function purchaseWithoutUser(Purchase $purchase): self
{
return new self("La compra {$purchase->id} no tiene un usuario asociado.");
}
public static function catalogItemNotFound(PurchaseItem $purchaseItem): self
{
return new self("No se encontró el producto de la línea de compra {$purchaseItem->id}.");
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace App\Domains\Ticket\Listeners;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Ticket\Exceptions\TicketGenerationException;
use App\Domains\Ticket\Services\TicketGeneratorService;
class GenerateTicketsForPaidPurchase
{
public function __construct(
private readonly TicketGeneratorService $ticketGenerator,
) {}
public function handle(PurchasePaid $event): void
{
$purchase = $event->purchase
->newQuery()
->with(['user', 'items'])
->findOrFail($event->purchase->getKey());
$user = $purchase->user;
foreach ($purchase->items as $purchaseItem) {
$catalogItem = CatalogItem::query()
->where('tenant_code', $purchase->tenant_codigo)
->find($purchaseItem->source_catalog_item_id);
if ($catalogItem === null) {
throw TicketGenerationException::catalogItemNotFound($purchaseItem);
}
if (! $this->requiresTickets($catalogItem)) {
continue;
}
if ($user === null) {
throw TicketGenerationException::purchaseWithoutUser($purchase);
}
$this->ticketGenerator->generate(
$catalogItem,
$user,
$purchaseItem->cantidad,
$purchaseItem->source_variant_id,
);
}
}
private function requiresTickets(CatalogItem $catalogItem): bool
{
if (! $catalogItem->isBundle()) {
return $catalogItem->has_tickets;
}
return $catalogItem->bundleComponents()
->whereHas(
'catalogItem',
fn ($query) => $query->where('has_tickets', true),
)
->exists();
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace App\Domains\Ticket\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'tenant_code',
'ticket',
'name',
'description',
'source_catalog_item_id',
'source_variant_id',
'starts_at',
'expires_at',
'used_at',
'user_id',
])]
class Ticket extends Model
{
use HasFactory;
public $timestamps = false;
protected $appends = [
'is_valid',
'is_expired',
'is_used',
];
protected function casts(): array
{
return [
'source_catalog_item_id' => 'integer',
'source_variant_id' => 'integer',
'starts_at' => 'datetime',
'expires_at' => 'datetime',
'used_at' => 'datetime',
'user_id' => 'integer',
];
}
/** @return BelongsTo<Tenant, $this> */
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
}
/** @return BelongsTo<User, $this> */
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function isValid(): bool
{
$now = now();
return $this->used_at === null
&& ($this->starts_at === null || $this->starts_at->lessThanOrEqualTo($now))
&& ($this->expires_at === null || $this->expires_at->greaterThan($now));
}
public function getIsValidAttribute(): bool
{
return $this->isValid();
}
public function getIsExpiredAttribute(): bool
{
return $this->used_at === null
&& $this->expires_at !== null
&& $this->expires_at->lessThanOrEqualTo(now());
}
public function getIsUsedAttribute(): bool
{
return $this->used_at !== null;
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Domains\Ticket\Resources;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin Ticket */
class TicketResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'tenant_code' => $this->tenant_code,
'ticket' => $this->ticket,
'name' => $this->name,
'description' => $this->description,
'source_catalog_item_id' => $this->source_catalog_item_id,
'source_variant_id' => $this->source_variant_id,
'starts_at' => $this->starts_at,
'expires_at' => $this->expires_at,
'used_at' => $this->used_at,
'is_valid' => $this->is_valid,
'is_expired' => $this->is_expired,
'is_used' => $this->is_used,
];
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Ticket\Exceptions\TicketGenerationException;
use App\Domains\Ticket\Models\Ticket;
use Carbon\CarbonInterface;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class TicketGeneratorService
{
/**
* @return Collection<int, Ticket>
*/
public function generate(
CatalogItem $catalogItem,
User $user,
int $quantity = 1,
?int $sourceVariantId = null,
): Collection {
if ($quantity < 1) {
throw TicketGenerationException::invalidQuantity();
}
$now = now();
return DB::transaction(function () use ($catalogItem, $user, $quantity, $sourceVariantId, $now): Collection {
$catalogItems = $this->resolveCatalogItems($catalogItem, $quantity, $now);
return $catalogItems->map(fn (CatalogItem $item): Ticket => Ticket::query()->create([
'tenant_code' => $item->tenant_code,
'ticket' => (string) Str::uuid(),
'name' => $item->nombre,
'description' => (string) ($item->descripcion ?? ''),
'source_catalog_item_id' => $catalogItem->getKey(),
'source_variant_id' => $sourceVariantId,
'starts_at' => $item->minimum_use_date,
'expires_at' => $item->maximum_use_date,
'used_at' => null,
'user_id' => $user->getKey(),
]));
});
}
/**
* @return Collection<int, CatalogItem>
*/
private function resolveCatalogItems(
CatalogItem $catalogItem,
int $quantity,
CarbonInterface $now,
): Collection {
if (! $catalogItem->isBundle()) {
$this->validateCatalogItem($catalogItem, $now);
return Collection::times($quantity, fn (): CatalogItem => $catalogItem);
}
$catalogItem->loadMissing('bundleComponents.catalogItem');
if ($catalogItem->bundleComponents->isEmpty()) {
throw TicketGenerationException::emptyBundle($catalogItem);
}
return $catalogItem->bundleComponents
->flatMap(function ($component) use ($quantity, $now): Collection {
$componentItem = $component->catalogItem;
$this->validateCatalogItem($componentItem, $now);
return Collection::times(
$quantity * $component->quantity,
fn (): CatalogItem => $componentItem,
);
})
->values();
}
private function validateCatalogItem(CatalogItem $catalogItem, CarbonInterface $now): void
{
if (! $catalogItem->has_tickets) {
throw TicketGenerationException::ticketsDisabled($catalogItem);
}
if ($catalogItem->maximum_use_date?->lessThanOrEqualTo($now)) {
throw TicketGenerationException::maximumUseDateReached($catalogItem);
}
}
}

View File

@@ -0,0 +1,10 @@
<?php
use App\Domains\Ticket\Controllers\TicketController;
use Illuminate\Support\Facades\Route;
Route::prefix('tenants/{tenant:codigo}')
->middleware('auth:sanctum')
->group(function (): void {
Route::get('tickets', [TicketController::class, 'index']);
});

View File

@@ -2,7 +2,10 @@
namespace App\Providers;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Ticket\Listeners\GenerateTicketsForPaidPurchase;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
@@ -20,6 +23,8 @@ class AppServiceProvider extends ServiceProvider
*/
public function boot(): void
{
Event::listen(PurchasePaid::class, GenerateTicketsForPaidPurchase::class);
Builder::macro('paginateFromRequest', function (int $defaultPerPage = 15, int $maxPerPage = 100, ?int $page = null) {
/** @var Builder $this */
$perPage = (int) request()->query('per_page', $defaultPerPage);

View File

@@ -0,0 +1,34 @@
<?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::create('tickets', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->uuid('ticket');
$table->string('name');
$table->text('description');
$table->dateTime('starts_at')->nullable();
$table->dateTime('expires_at')->nullable();
$table->dateTime('used_at')->nullable();
$table->foreignId('user_id')->constrained()->cascadeOnUpdate()->restrictOnDelete();
$table->foreign('tenant_code')
->references('codigo')
->on('tenants')
->cascadeOnUpdate()
->restrictOnDelete();
});
}
public function down(): void
{
Schema::dropIfExists('tickets');
}
};

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('tickets', function (Blueprint $table): void {
$table->unsignedBigInteger('source_catalog_item_id')->nullable()->after('description');
$table->unsignedBigInteger('source_variant_id')->nullable()->after('source_catalog_item_id');
});
}
public function down(): void
{
Schema::table('tickets', function (Blueprint $table): void {
$table->dropColumn(['source_catalog_item_id', 'source_variant_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,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,7 +4,9 @@ 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';
require __DIR__.'/../app/Domains/Menu/routes/api.php';
require __DIR__.'/../app/Domains/Ticket/routes/api.php';

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

@@ -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,104 @@
<?php
namespace Tests\Feature\Ticket;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;
class TicketControllerTest extends TestCase
{
use RefreshDatabase;
public function test_an_authenticated_user_can_list_their_tickets_for_the_tenant(): void
{
$tenant = $this->createTenant('current');
$user = User::factory()->create();
$olderTicket = $this->createTicket($tenant, $user, 'Older ticket');
$newerTicket = $this->createTicket($tenant, $user, 'Newer ticket');
$this->actingAs($user, 'sanctum')
->getJson("/api/tenants/{$tenant->codigo}/tickets")
->assertOk()
->assertJsonCount(2, 'data')
->assertJsonPath('data.0.id', $newerTicket->id)
->assertJsonPath('data.0.name', 'Newer ticket')
->assertJsonPath('data.0.is_valid', true)
->assertJsonPath('data.0.is_expired', false)
->assertJsonPath('data.0.is_used', false)
->assertJsonPath('data.1.id', $olderTicket->id)
->assertJsonMissingPath('meta')
->assertJsonMissingPath('links');
}
public function test_it_does_not_include_tickets_from_other_users_or_tenants(): void
{
$tenant = $this->createTenant('current');
$otherTenant = $this->createTenant('other');
$user = User::factory()->create();
$otherUser = User::factory()->create();
$visibleTicket = $this->createTicket($tenant, $user, 'Visible');
$this->createTicket($tenant, $otherUser, 'Other user');
$this->createTicket($otherTenant, $user, 'Other tenant');
$this->actingAs($user, 'sanctum')
->getJson("/api/tenants/{$tenant->codigo}/tickets")
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $visibleTicket->id);
}
public function test_authentication_is_required_to_list_tickets(): void
{
$tenant = $this->createTenant('current');
$this->getJson("/api/tenants/{$tenant->codigo}/tickets")
->assertUnauthorized();
}
private function createTicket(Tenant $tenant, User $user, string $name): Ticket
{
return Ticket::query()->create([
'tenant_code' => $tenant->codigo,
'ticket' => (string) Str::uuid(),
'name' => $name,
'description' => "Description for {$name}",
'user_id' => $user->id,
]);
}
private function createTenant(string $code): Tenant
{
$headerLogo = $this->createAttachment("{$code}-header");
$footerLogo = $this->createAttachment("{$code}-footer");
return Tenant::query()->create([
'codigo' => $code,
'nombre' => ucfirst($code),
'dominio' => "{$code}.local",
'primary_color' => '#000000',
'secondary_color' => '#000000',
'danger_color' => '#000000',
'success_color' => '#000000',
'header_bg_color' => '#000000',
'footer_bg_color' => '#000000',
'header_logo_id' => $headerLogo->id,
'footer_logo_id' => $footerLogo->id,
]);
}
private function createAttachment(string $name): Attachment
{
return Attachment::query()->create([
'path' => "test/{$name}.png",
'filename' => "{$name}.png",
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
}
}

View File

@@ -0,0 +1,275 @@
<?php
namespace Tests\Feature\Ticket;
use App\Domains\Attachable\Enums\AttachmentType;
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\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Exceptions\TicketGenerationException;
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\Str;
use Tests\TestCase;
class TicketGeneratorServiceTest extends TestCase
{
use RefreshDatabase;
private TicketGeneratorService $service;
private Tenant $tenant;
private User $user;
protected function setUp(): void
{
parent::setUp();
Carbon::setTestNow('2026-07-21 10:00:00');
$this->service = app(TicketGeneratorService::class);
$this->tenant = $this->createTenant();
$this->user = User::factory()->create();
}
protected function tearDown(): void
{
Carbon::setTestNow();
parent::tearDown();
}
public function test_it_generates_tickets_from_a_standard_catalog_item(): void
{
$item = $this->createTicketableItem(
'single-day',
now()->subHour(),
now()->addDay(),
);
$tickets = $this->service->generate($item, $this->user, 2);
$this->assertCount(2, $tickets);
foreach ($tickets as $ticket) {
$this->assertTrue(Str::isUuid($ticket->ticket));
$this->assertSame($this->tenant->codigo, $ticket->tenant_code);
$this->assertSame($this->user->id, $ticket->user_id);
$this->assertSame($item->nombre, $ticket->name);
$this->assertSame($item->descripcion, $ticket->description);
$this->assertSame($item->id, $ticket->source_catalog_item_id);
$this->assertNull($ticket->source_variant_id);
$this->assertTrue($ticket->starts_at->equalTo($item->minimum_use_date));
$this->assertTrue($ticket->expires_at->equalTo($item->maximum_use_date));
}
}
public function test_it_rejects_an_item_without_tickets_enabled(): void
{
$item = $this->createTicketableItem('disabled');
$item->update(['has_tickets' => false]);
$this->expectException(TicketGenerationException::class);
$this->expectExceptionMessage('no tiene tickets habilitados');
$this->service->generate($item->fresh(), $this->user);
}
public function test_it_rejects_an_item_when_its_maximum_use_date_was_reached(): void
{
$item = $this->createTicketableItem('expired', maximumUseDate: now());
$this->expectException(TicketGenerationException::class);
$this->expectExceptionMessage('alcanzó su fecha máxima de uso');
$this->service->generate($item, $this->user);
}
public function test_it_generates_tickets_for_every_bundle_component_and_quantity(): void
{
$first = $this->createTicketableItem('first', maximumUseDate: now()->addDay());
$second = $this->createTicketableItem('second', maximumUseDate: now()->addDays(2));
$bundle = $this->createBundle('bundle');
$bundle->bundleComponents()->createMany([
['component_catalog_item_id' => $first->id, 'quantity' => 2],
['component_catalog_item_id' => $second->id, 'quantity' => 1],
]);
$tickets = $this->service->generate($bundle, $this->user, 2);
$this->assertCount(6, $tickets);
$this->assertCount(6, $tickets->where('source_catalog_item_id', $bundle->id));
$this->assertCount(4, $tickets->where('name', $first->nombre));
$this->assertCount(2, $tickets->where('name', $second->nombre));
}
public function test_bundle_generation_is_rolled_back_when_a_component_is_invalid(): void
{
$valid = $this->createTicketableItem('valid');
$invalid = $this->createTicketableItem('invalid');
$invalid->update(['has_tickets' => false]);
$bundle = $this->createBundle('invalid-bundle');
$bundle->bundleComponents()->createMany([
['component_catalog_item_id' => $valid->id, 'quantity' => 1],
['component_catalog_item_id' => $invalid->id, 'quantity' => 1],
]);
try {
$this->service->generate($bundle, $this->user);
$this->fail('La generación debería haber fallado.');
} catch (TicketGenerationException) {
$this->assertDatabaseCount('tickets', 0);
}
}
public function test_marking_a_purchase_as_paid_generates_its_tickets_once(): void
{
$item = $this->createTicketableItem('paid-ticket');
$purchase = $this->createPurchase($item, 2);
$purchase->setRelation('items', new EloquentCollection);
$purchase->markAsPaid();
$this->assertSame(Purchase::STATUS_PAID, $purchase->status);
$this->assertDatabaseCount('tickets', 2);
$purchase->markAsPaid();
$this->assertDatabaseCount('tickets', 2);
}
public function test_a_ticket_generated_from_a_purchase_keeps_its_source_ids(): void
{
$item = $this->createTicketableItem('sourced-ticket');
$purchase = $this->createPurchase($item, 1, 1234);
$purchase->markAsPaid();
$this->assertDatabaseHas('tickets', [
'source_catalog_item_id' => $item->id,
'source_variant_id' => 1234,
]);
}
public function test_marking_a_purchase_as_paid_ignores_items_without_tickets(): void
{
$item = $this->createTicketableItem('regular-product');
$item->update(['has_tickets' => false]);
$purchase = $this->createPurchase($item->fresh(), 1);
$purchase->markAsPaid();
$this->assertSame(Purchase::STATUS_PAID, $purchase->status);
$this->assertDatabaseCount('tickets', 0);
}
public function test_paid_status_is_rolled_back_when_ticket_generation_fails(): void
{
$item = $this->createTicketableItem('expired-paid-ticket', maximumUseDate: now());
$purchase = $this->createPurchase($item, 1);
try {
$purchase->markAsPaid();
$this->fail('La generación debería haber fallado.');
} catch (TicketGenerationException) {
$this->assertSame(Purchase::STATUS_PENDING_PAYMENT, $purchase->fresh()->status);
$this->assertDatabaseCount('tickets', 0);
}
}
private function createTicketableItem(
string $slug,
mixed $minimumUseDate = null,
mixed $maximumUseDate = null,
): CatalogItem {
return CatalogItem::query()->create([
'tenant_code' => $this->tenant->codigo,
'slug' => $slug,
'nombre' => ucfirst($slug),
'descripcion' => "Descripción de {$slug}",
'precio' => 10,
'has_tickets' => true,
'minimum_use_date' => $minimumUseDate,
'maximum_use_date' => $maximumUseDate,
]);
}
private function createBundle(string $slug): CatalogItem
{
return CatalogItem::query()->create([
'tenant_code' => $this->tenant->codigo,
'type' => CatalogItemType::Bundle,
'inventory_policy' => null,
'slug' => $slug,
'nombre' => ucfirst($slug),
'descripcion' => "Descripción de {$slug}",
'precio' => 20,
]);
}
private function createPurchase(
CatalogItem $catalogItem,
int $quantity,
?int $sourceVariantId = null,
): Purchase {
$purchase = Purchase::query()->create([
'tenant_codigo' => $this->tenant->codigo,
'user_id' => $this->user->id,
'status' => Purchase::STATUS_PENDING_PAYMENT,
'payment_method' => 'transfer',
'total' => 10 * $quantity,
]);
$purchase->items()->create([
'source_catalog_item_id' => $catalogItem->id,
'source_variant_id' => $sourceVariantId,
'image_attachment_id' => null,
'nombre' => $catalogItem->nombre,
'descripcion' => $catalogItem->descripcion,
'slug' => $catalogItem->slug,
'item_nombre' => $catalogItem->nombre,
'variant_attributes' => [],
'cantidad' => $quantity,
'precio_unitario' => 10,
'discount_total' => null,
'tax_total' => null,
'total' => 10 * $quantity,
]);
return $purchase;
}
private function createTenant(): Tenant
{
$header = Attachment::query()->create([
'path' => 'test/ticket-header.png',
'filename' => 'header.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
$footer = Attachment::query()->create([
'path' => 'test/ticket-footer.png',
'filename' => 'footer.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
return Tenant::query()->create([
'codigo' => 'ticket-tenant',
'nombre' => 'Ticket Tenant',
'dominio' => 'ticket.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,
]);
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace Tests\Unit\Ticket;
use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Models\Ticket;
use Illuminate\Support\Carbon;
use Tests\TestCase;
class TicketTest extends TestCase
{
protected function tearDown(): void
{
Carbon::setTestNow();
parent::tearDown();
}
public function test_it_maps_its_dates_and_relations(): void
{
$ticket = new Ticket;
$ticket->setRawAttributes([
'source_catalog_item_id' => '20',
'source_variant_id' => '30',
'starts_at' => '2026-07-21 10:00:00',
'expires_at' => '2026-07-22 10:00:00',
'used_at' => null,
'user_id' => '10',
]);
$this->assertSame('tickets', $ticket->getTable());
$this->assertFalse($ticket->usesTimestamps());
$this->assertSame(20, $ticket->source_catalog_item_id);
$this->assertSame(30, $ticket->source_variant_id);
$this->assertInstanceOf(Carbon::class, $ticket->starts_at);
$this->assertInstanceOf(Carbon::class, $ticket->expires_at);
$this->assertNull($ticket->used_at);
$this->assertSame(10, $ticket->user_id);
$this->assertInstanceOf(Tenant::class, $ticket->tenant()->getRelated());
$this->assertInstanceOf(User::class, $ticket->user()->getRelated());
}
public function test_unused_ticket_without_date_restrictions_is_valid(): void
{
$this->assertTrue((new Ticket)->isValid());
}
public function test_ticket_is_invalid_before_its_start_date(): void
{
Carbon::setTestNow('2026-07-21 10:00:00');
$ticket = new Ticket(['starts_at' => now()->addSecond()]);
$this->assertFalse($ticket->isValid());
}
public function test_ticket_is_valid_when_its_start_date_is_reached(): void
{
Carbon::setTestNow('2026-07-21 10:00:00');
$ticket = new Ticket(['starts_at' => now()]);
$this->assertTrue($ticket->isValid());
}
public function test_ticket_is_invalid_when_it_expires(): void
{
Carbon::setTestNow('2026-07-21 10:00:00');
$ticket = new Ticket(['expires_at' => now()]);
$this->assertFalse($ticket->isValid());
}
public function test_used_ticket_is_invalid(): void
{
$ticket = new Ticket(['used_at' => now()->subSecond()]);
$this->assertFalse($ticket->isValid());
}
public function test_it_appends_computed_status_fields(): void
{
Carbon::setTestNow('2026-07-21 10:00:00');
$ticket = new Ticket([
'starts_at' => now()->subHour(),
'expires_at' => now()->addHour(),
]);
$attributes = $ticket->toArray();
$this->assertTrue($attributes['is_valid']);
$this->assertFalse($attributes['is_expired']);
$this->assertFalse($attributes['is_used']);
}
public function test_unused_ticket_is_expired_when_its_expiration_date_is_reached(): void
{
Carbon::setTestNow('2026-07-21 10:00:00');
$ticket = new Ticket(['expires_at' => now()]);
$this->assertFalse($ticket->is_valid);
$this->assertTrue($ticket->is_expired);
$this->assertFalse($ticket->is_used);
}
public function test_used_ticket_is_not_reported_as_expired(): void
{
Carbon::setTestNow('2026-07-21 10:00:00');
$ticket = new Ticket([
'expires_at' => now()->subHour(),
'used_at' => now()->subDay(),
]);
$this->assertFalse($ticket->is_valid);
$this->assertFalse($ticket->is_expired);
$this->assertTrue($ticket->is_used);
}
}