Merge branch 'feature/event_scoped_admin' into homo

This commit is contained in:
2026-10-02 12:22:15 -03:00
51 changed files with 2488 additions and 355 deletions

View File

@@ -9,15 +9,18 @@ use App\Domains\Ticketing\Desfile\Requests\ExportEntryReservationsRequest;
use App\Domains\Ticketing\Desfile\Requests\IndexEntryReservationsRequest;
use App\Domains\Ticketing\Desfile\Requests\StoreEntryReservationsRequest;
use App\Domains\Ticketing\Desfile\Resources\EntryReservationResource;
use App\Domains\Ticketing\Desfile\Services\DesfileEntryReservationPolicy;
use App\Domains\Ticketing\Desfile\Services\DesfileEntryReservationService;
use App\Domains\Ticketing\Desfile\Services\EntryReservationExcelService;
use App\Domains\Ticketing\Desfile\Services\EntryReservationPdfService;
use App\Domains\Ticketing\Desfile\Services\EntryReservationReportService;
use App\Domains\Ticketing\Desfile\Services\EntryReservationService;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Services\EntryReservationService as TicketEntryReservationService;
use App\Domains\Ticketing\Ticket\Services\ResolvedTicketValidity;
use App\Domains\Ticketing\Ticket\Services\TicketGeneratorService;
use App\Domains\Ticketing\Ticket\Services\TicketValidityResolver;
use Barryvdh\DomPDF\ServiceProvider as DomPdfServiceProvider;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -136,6 +139,7 @@ class EntryReservationServiceTest extends TestCase
(require database_path('migrations/2026_09_23_010000_create_desfile_entry_reservations_table.php'))->up();
(require database_path('migrations/2026_09_24_000000_add_administrative_entry_reservation_stock.php'))->up();
(require database_path('migrations/2026_09_24_010000_add_soft_deletes_to_desfile_entry_reservations_table.php'))->up();
(require database_path('migrations/2026_10_02_000000_generalize_ticket_reservations.php'))->up();
DB::table('tenants')->insert(['codigo' => 'desfile_pura_tendencia']);
DB::table('users')->insert(['id' => 1, 'tenant_codigo' => 'desfile_pura_tendencia']);
DB::table('catalog_items')->insert([
@@ -165,7 +169,12 @@ class EntryReservationServiceTest extends TestCase
}
}
private function service(bool $failSecond = false): EntryReservationService
private function service(bool $failSecond = false): DesfileEntryReservationService
{
return new DesfileEntryReservationService($this->ticketService($failSecond), new DesfileEntryReservationPolicy);
}
private function ticketService(bool $failSecond = false): TicketEntryReservationService
{
$generator = Mockery::mock(TicketGeneratorService::class);
$generator->shouldReceive('generate')->andReturnUsing(function ($entry, $user, $quantity, $variantId) use ($failSecond) {
@@ -182,7 +191,7 @@ class EntryReservationServiceTest extends TestCase
return collect([Ticket::query()->findOrFail($id)]);
});
return new EntryReservationService($generator);
return new TicketEntryReservationService($generator);
}
private function rows(): array
@@ -200,8 +209,8 @@ class EntryReservationServiceTest extends TestCase
$replayed = $service->reserve($user, $key, $this->rows());
$this->assertSame($result->pluck('id')->all(), $replayed->pluck('id')->all());
$this->assertDatabaseCount('tickets', 2);
$this->assertDatabaseCount('desfile_entry_reservations', 2);
$this->assertDatabaseCount('desfile_reservation_batches', 1);
$this->assertDatabaseCount('entry_reservations', 2);
$this->assertDatabaseCount('reservation_batches', 1);
foreach (Inventory::all() as $inventory) {
$this->assertSame(1, $inventory->entry_reserved_stock);
$this->assertSame(1, $inventory->real_stock);
@@ -223,7 +232,7 @@ class EntryReservationServiceTest extends TestCase
$this->assertStringContainsString('Tipo: NORMAL, Sector: A, Fila: 3, Asiento: 17', $error->errors()['rows.1.variant_id'][0]);
}
$this->assertDatabaseCount('tickets', 0);
$this->assertDatabaseCount('desfile_entry_reservations', 0);
$this->assertDatabaseCount('entry_reservations', 0);
$this->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
}
@@ -236,8 +245,8 @@ class EntryReservationServiceTest extends TestCase
$this->assertSame('Ticket generation failed', $error->getMessage());
}
$this->assertDatabaseCount('tickets', 0);
$this->assertDatabaseCount('desfile_entry_reservations', 0);
$this->assertDatabaseCount('desfile_reservation_batches', 0);
$this->assertDatabaseCount('entry_reservations', 0);
$this->assertDatabaseCount('reservation_batches', 0);
$this->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
}
@@ -250,6 +259,120 @@ class EntryReservationServiceTest extends TestCase
$service->reserve($user, (string) Str::uuid(), $this->rows());
}
public function test_a_seat_cannot_be_reserved_twice_even_when_inventory_has_more_stock(): void
{
DB::table('inventories')->where('id', 1)->update(['real_stock' => 3]);
$service = $this->service();
$user = User::findOrFail(1);
$row = $this->rows()[0];
$reservation = $service->reserve($user, (string) Str::uuid(), [$row])->sole();
try {
$service->reserve($user, (string) Str::uuid(), [$row]);
$this->fail('Expected a unique seat despite remaining stock');
} catch (ValidationException $error) {
$this->assertArrayHasKey('rows.0.variant_id', $error->errors());
$this->assertStringContainsString('Asiento: 17', $error->errors()['rows.0.variant_id'][0]);
}
$this->assertDatabaseCount('tickets', 1);
$this->assertDatabaseCount('reservation_batches', 1);
$this->assertSame(1, Inventory::findOrFail(1)->entry_reserved_stock);
$service->cancel($user, $reservation->id);
$replacement = $service->reserve($user, (string) Str::uuid(), [$row])->sole();
$this->assertNotSame($reservation->id, $replacement->id);
$this->assertSame(1, Inventory::findOrFail(1)->entry_reserved_stock);
}
public function test_duplicate_seats_in_one_batch_are_rejected_without_changing_stock(): void
{
DB::table('inventories')->where('id', 1)->update(['real_stock' => 3]);
$row = $this->rows()[0];
try {
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), [$row, $row]);
$this->fail('Expected duplicate seat validation');
} catch (ValidationException $error) {
$this->assertArrayHasKey('rows.1.variant_id', $error->errors());
}
$this->assertDatabaseCount('tickets', 0);
$this->assertDatabaseCount('reservation_batches', 0);
$this->assertSame(0, Inventory::findOrFail(1)->entry_reserved_stock);
}
public function test_legacy_batches_replay_after_cancellation_and_an_active_event_change(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$key = (string) Str::uuid();
$result = $service->reserve($user, $key, $this->rows());
DB::table('reservation_batches')->update([
'request_hash' => hash('sha256', json_encode($this->rows(), JSON_THROW_ON_ERROR)),
]);
$service->cancel($user, $result->first()->id);
DB::table('tenants')->update(['active_event_id' => 20]);
$replay = $service->reserve($user, $key, array_reverse($this->rows()));
$this->assertSame($result->last()->id, $replay->sole()->id);
$this->assertSame($result->last()->id, $service->reservations($user)->sole()->id);
$this->assertSame($result->last()->ticket_id, $service->reservationTicket($user, $result->last()->id)->id);
$this->assertSame('NORMAL', $replay->sole()->variant->selectionValues()->get('tipo'));
$this->assertDatabaseCount('tickets', 2);
$this->assertDatabaseCount('reservation_batches', 1);
}
public function test_desfile_cannot_list_export_download_or_cancel_other_catalog_item_reservations(): void
{
DB::table('catalog_items')->insert([
'id' => 2, 'tenant_code' => 'desfile_pura_tendencia', 'slug' => 'other-ticket',
'inventory_policy' => 'tracked', 'precio' => 100,
]);
DB::table('inventories')->insert(['id' => 3, 'real_stock' => 1]);
DB::table('variantes')->insert(['id' => 3, 'catalog_item_id' => 2, 'inventory_id' => 3, 'precio' => 100]);
$user = User::findOrFail(1);
$other = $this->ticketService()->reserve($user, (string) Str::uuid(), [
['catalog_item_id' => 2, 'variant_id' => 3, 'tipo_pago' => 'sin_cargo'],
])->sole();
$service = $this->service();
$own = $service->reserve($user, (string) Str::uuid(), [$this->rows()[0]])->sole();
$this->assertSame([$own->id], $service->reservations($user)->pluck('id')->all());
$this->assertSame([$own->id], $service->reservationsForExport($user)->pluck('id')->all());
foreach (['reservationTicket', 'cancel'] as $method) {
try {
$service->$method($user, $other->id);
$this->fail('Expected the Desfile catalog scope');
} catch (ModelNotFoundException) {
$this->assertNull(Ticket::findOrFail($other->ticket_id)->cancelled_at);
}
}
DB::table('catalog_items')->where('id', 1)->update(['deleted_at' => now()]);
$this->assertSame(0, $service->reservations($user)->total());
$this->assertCount(0, $service->reservationsForExport($user));
}
public function test_desfile_service_rejects_other_tenants_for_every_operation(): void
{
$user = new User(['tenant_codigo' => 'other']);
$service = $this->service();
$operations = [
fn () => $service->reservations($user),
fn () => $service->reservationsForExport($user),
fn () => $service->reservationTicket($user, 1),
fn () => $service->cancel($user, 1),
fn () => $service->reserve($user, (string) Str::uuid(), $this->rows()),
];
foreach ($operations as $operation) {
try {
$operation();
$this->fail('Expected the Desfile tenant restriction');
} catch (HttpException $error) {
$this->assertSame(403, $error->getStatusCode());
}
}
}
public function test_it_cancels_the_ticket_releases_stock_and_soft_deletes_the_reservation(): void
{
$service = $this->service();
@@ -258,7 +381,7 @@ class EntryReservationServiceTest extends TestCase
$service->cancel($user, $reservation->id);
$this->assertSoftDeleted('desfile_entry_reservations', ['id' => $reservation->id]);
$this->assertSoftDeleted('entry_reservations', ['id' => $reservation->id]);
$this->assertNotNull(Ticket::findOrFail($reservation->ticket_id)->cancelled_at);
$this->assertSame(0, Inventory::findOrFail(1)->entry_reserved_stock);
$this->assertSame(1, Inventory::findOrFail(1)->availableStock());
@@ -280,7 +403,7 @@ class EntryReservationServiceTest extends TestCase
$this->assertArrayHasKey('status', $error->errors());
}
$this->assertDatabaseHas('desfile_entry_reservations', [
$this->assertDatabaseHas('entry_reservations', [
'id' => $reservation->id,
'deleted_at' => null,
]);
@@ -440,9 +563,13 @@ class EntryReservationServiceTest extends TestCase
$validity->shouldReceive('resolveVariant')->andReturn(
ResolvedTicketValidity::unrestricted(),
);
$service = new EntryReservationService(new TicketGeneratorService($validity));
$service = new DesfileEntryReservationService(
new TicketEntryReservationService(new TicketGeneratorService($validity)),
new DesfileEntryReservationPolicy,
);
$result = $service->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
foreach ($result as $reservation) {
$this->assertSame(1, $reservation->catalog_item_id);
$this->assertDatabaseHas('tickets', [
'id' => $reservation->ticket_id, 'user_id' => 1,
'source_variant_id' => $reservation->variant_id,

View File

@@ -99,7 +99,7 @@ class AdminAppDesfileEntryReservationFormControllerTest extends TestCase
]);
}
if ($state === 'administrative') {
$variant->desfileEntryReservations()->create([
$variant->entryReservations()->create([
'fecha_reserva' => now(), 'importe' => 0, 'tipo_pago' => 'sin_cargo',
]);
}
@@ -111,7 +111,7 @@ class AdminAppDesfileEntryReservationFormControllerTest extends TestCase
->assertOk()->assertJsonCount(1, 'data.variants')
->assertJsonPath('data.variants.0.id', $availableId)
->assertJsonPath('data.fields.3.options', [['value' => '1', 'label' => '1']]);
$this->assertDatabaseCount('desfile_entry_reservations', 1);
$this->assertDatabaseCount('entry_reservations', 1);
$this->assertSame(1, (int) Inventory::query()->sum('reserved_stock'));
}

View File

@@ -0,0 +1,206 @@
<?php
namespace Tests\Feature\Migrations;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\ReservationBatch;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\QueryException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Tests\TestCase;
/** Tests the upgrade on the guarded SQLite :memory: connection. */
class GeneralizeTicketReservationsTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
Schema::create('tenants', function (Blueprint $table): void {
$table->id();
$table->string('codigo');
});
Schema::create('users', function (Blueprint $table): void {
$table->id();
$table->softDeletes();
});
Schema::create('catalog_items', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->softDeletes();
});
Schema::create('variantes', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('catalog_item_id');
$table->softDeletes();
});
Schema::create('tickets', fn (Blueprint $table) => $table->id());
Schema::create('inventories', fn (Blueprint $table) => $table->id());
(require database_path('migrations/2026_09_23_010000_create_desfile_entry_reservations_table.php'))->up();
(require database_path('migrations/2026_09_24_000000_add_administrative_entry_reservation_stock.php'))->up();
(require database_path('migrations/2026_09_24_010000_add_soft_deletes_to_desfile_entry_reservations_table.php'))->up();
DB::table('users')->insert(['id' => 1]);
DB::table('tenants')->insert([
['codigo' => 'desfile_pura_tendencia'], ['codigo' => 'other'],
]);
DB::table('catalog_items')->insert([
['id' => 1, 'tenant_code' => 'desfile_pura_tendencia'],
['id' => 2, 'tenant_code' => 'other'],
]);
DB::table('variantes')->insert([
['id' => 1, 'catalog_item_id' => 1, 'deleted_at' => null],
['id' => 2, 'catalog_item_id' => 2, 'deleted_at' => now()],
]);
DB::table('tickets')->insert(['id' => 10]);
DB::table('inventories')->insert(['id' => 20, 'entry_reserved_stock' => 1]);
DB::table('desfile_reservation_batches')->insert([
'id' => 30, 'user_id' => 1, 'tenant_code' => 'desfile_pura_tendencia',
'idempotency_key' => 'aab7c678-7f4d-486a-87ec-7f613ad6f58d',
'request_hash' => str_repeat('a', 64),
'created_at' => now(), 'updated_at' => now(),
]);
DB::table('desfile_entry_reservations')->insert([
['id' => 40, 'variant_id' => 1, 'ticket_id' => 10, 'inventory_id' => 20,
'batch_id' => 30, 'fecha_reserva' => now(), 'importe' => 250,
'tipo_pago' => 'otro_metodo', 'deleted_at' => null],
['id' => 41, 'variant_id' => 2, 'ticket_id' => null, 'inventory_id' => null,
'batch_id' => null, 'fecha_reserva' => now(), 'importe' => 0,
'tipo_pago' => 'sin_cargo', 'deleted_at' => now()],
]);
}
private function migration(): Migration
{
return require database_path('migrations/2026_10_02_000000_generalize_ticket_reservations.php');
}
public function test_upgrade_preserves_reservations_batches_stock_and_deleted_history(): void
{
$this->migration()->up();
$this->assertFalse(Schema::hasTable('desfile_entry_reservations'));
$this->assertFalse(Schema::hasTable('desfile_reservation_batches'));
$this->assertDatabaseCount('entry_reservations', 2);
$this->assertDatabaseCount('reservation_batches', 1);
$reservation = EntryReservation::findOrFail(40);
$this->assertSame(1, $reservation->catalog_item_id);
$this->assertSame(1, $reservation->catalogItem->id);
$this->assertSame(30, $reservation->batch->id);
$this->assertSame(40, $reservation->batch->reservations->sole()->id);
$this->assertSame(10, $reservation->ticket->id);
$this->assertSame('250.00', $reservation->importe);
$this->assertSame(str_repeat('a', 64), $reservation->batch->request_hash);
$this->assertSame(1, $reservation->inventory->entry_reserved_stock);
$historical = EntryReservation::withTrashed()->findOrFail(41);
$this->assertTrue($historical->trashed());
$this->assertTrue($historical->variant->trashed());
$this->assertSame(2, $historical->catalog_item_id);
}
public function test_reservations_can_belong_to_other_tenants_and_have_no_variant(): void
{
$this->migration()->up();
$batch = ReservationBatch::create([
'user_id' => 1, 'tenant_code' => 'other',
'idempotency_key' => '9495eb8e-a424-4f1b-8911-e05c51e1caf7',
'request_hash' => str_repeat('b', 64),
]);
$reservation = $batch->reservations()->create([
'catalog_item_id' => 2, 'fecha_reserva' => now(),
'tipo_pago' => 'sin_cargo', 'importe' => 0,
]);
$this->assertNull($reservation->variant_id);
$this->assertSame('other', $reservation->catalogItem->tenant_code);
$this->assertSame('other', $reservation->batch->tenant->codigo);
$this->assertSame(1, $reservation->batch->user->id);
}
public function test_variant_based_callers_infer_the_catalog_item(): void
{
$this->migration()->up();
$reservation = EntryReservation::create([
'variant_id' => 1, 'fecha_reserva' => now(), 'tipo_pago' => 'sin_cargo',
]);
$this->assertSame(1, $reservation->fresh()->catalog_item_id);
}
public function test_a_variant_from_another_catalog_item_is_rejected(): void
{
$this->migration()->up();
$this->expectException(ValidationException::class);
EntryReservation::create([
'catalog_item_id' => 2, 'variant_id' => 1,
'fecha_reserva' => now(), 'tipo_pago' => 'sin_cargo',
]);
}
public function test_the_catalog_item_is_required_at_the_database_level(): void
{
$this->migration()->up();
$this->expectException(QueryException::class);
DB::table('entry_reservations')->insert([
'fecha_reserva' => now(), 'tipo_pago' => 'sin_cargo',
]);
}
public function test_upgrade_preserves_foreign_keys_and_batch_idempotency(): void
{
$this->migration()->up();
$this->assertSame([], DB::select('PRAGMA foreign_key_check'));
foreach (['catalog_items' => 1, 'variantes' => 1, 'tickets' => 10, 'inventories' => 20, 'reservation_batches' => 30] as $table => $id) {
try {
DB::table($table)->where('id', $id)->delete();
$this->fail("Expected {$table} to remain referenced");
} catch (QueryException) {
$this->assertDatabaseHas($table, ['id' => $id]);
}
}
$batch = ReservationBatch::findOrFail(30);
$this->expectException(QueryException::class);
ReservationBatch::create($batch->only(['user_id', 'tenant_code', 'idempotency_key', 'request_hash']));
}
public function test_rollback_restores_the_original_schema_and_keeps_data(): void
{
$migration = $this->migration();
$migration->up();
$migration->down();
$this->assertFalse(Schema::hasTable('entry_reservations'));
$this->assertFalse(Schema::hasTable('reservation_batches'));
$this->assertDatabaseCount('desfile_entry_reservations', 2);
$this->assertDatabaseCount('desfile_reservation_batches', 1);
$this->assertFalse(Schema::hasColumn('desfile_entry_reservations', 'catalog_item_id'));
$this->assertSame([], DB::select('PRAGMA foreign_key_check'));
$migration->up();
$this->assertSame(1, EntryReservation::findOrFail(40)->catalog_item_id);
}
public function test_rollback_does_not_discard_reservations_without_variants(): void
{
$migration = $this->migration();
$migration->up();
EntryReservation::create([
'catalog_item_id' => 2, 'fecha_reserva' => now(), 'tipo_pago' => 'sin_cargo',
]);
try {
$migration->down();
$this->fail('Expected incompatible rollback to be rejected');
} catch (\LogicException) {
$this->assertDatabaseCount('entry_reservations', 3);
$this->assertTrue(Schema::hasTable('reservation_batches'));
}
}
public function test_an_orphaned_catalog_is_rejected_before_renaming_tables(): void
{
DB::table('variantes')->where('id', 2)->update(['catalog_item_id' => 999]);
try {
$this->migration()->up();
$this->fail('Expected orphaned catalog to be rejected');
} catch (\LogicException) {
$this->assertDatabaseCount('desfile_entry_reservations', 2);
$this->assertFalse(Schema::hasTable('entry_reservations'));
}
}
}

View File

@@ -54,6 +54,8 @@ class MenuSeederTest extends TestCase
...$expectedMenus,
...$fiestaCategoryMenus,
'adminapp.desfile.entradas' => ['Entradas', '/admin/desfile/entradas'],
'adminapp.desfile.reservas' => ['Reserva de Tickets', '/admin/desfile/reservas'],
'adminapp.ticket-reservations' => ['Reserva de Tickets', '/admin/ticket-reservations'],
]))->sort()->values()->all(),
$adminApp->children->pluck('code')->sort()->values()->all()
);

View File

@@ -13,8 +13,8 @@ use App\Domains\Core\Authorization\Enums\RoleCode;
use App\Domains\Core\Menu\Models\Menu;
use App\Domains\Core\Tenant\Models\AdminWebsiteType;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Desfile\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Models\TicketRefund;
use App\Shared\Attachable\Enums\AttachmentType;

View File

@@ -72,7 +72,7 @@ class AdminAppTicketEventScopeTest extends TestCase
$table->unsignedBigInteger('purchase_item_id');
$table->decimal('amount', 12, 2);
});
Schema::create('desfile_entry_reservations', function (Blueprint $table): void {
Schema::create('entry_reservations', function (Blueprint $table): void {
$table->id();
$table->unsignedBigInteger('ticket_id');
$table->softDeletes();

View File

@@ -0,0 +1,313 @@
<?php
namespace Tests\Feature\Ticket;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Services\EntryReservationExcelService;
use App\Domains\Ticketing\Ticket\Services\EntryReservationPdfService;
use App\Domains\Ticketing\Ticket\Services\EntryReservationService;
use App\Domains\Ticketing\Ticket\Services\ResolvedTicketValidity;
use App\Domains\Ticketing\Ticket\Services\TicketPdfService;
use App\Domains\Ticketing\Ticket\Services\TicketValidityResolver;
use Barryvdh\DomPDF\ServiceProvider as DomPdfServiceProvider;
use Database\Seeders\MenuSeeder;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum;
use Mockery;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Tests\Support\CreatesTicketReservationSchema;
use Tests\TestCase;
class EntryReservationControllerTest extends TestCase
{
use CreatesTicketReservationSchema;
private const URL = '/api/v1/adminapp/tenant/entry-reservations';
protected function setUp(): void
{
parent::setUp();
$this->createTicketReservationSchema('onticket');
$this->app->register(DomPdfServiceProvider::class);
Schema::table('users', fn (Blueprint $table) => $table->string('rol_codigo')->default('adminapp'));
Schema::table('tenants', fn (Blueprint $table) => $table->string('nombre')->default('OnTicket'));
Schema::create('menues', function (Blueprint $table): void {
$table->string('code')->primary();
$table->string('label')->nullable();
$table->string('parent_menu_code')->nullable();
$table->string('content_type')->default('dynamic');
$table->text('static_content_schema')->nullable();
$table->string('route')->nullable();
$table->timestamps();
});
Schema::create('tenants_menues', function (Blueprint $table): void {
$table->string('tenant_code');
$table->string('menu_code');
$table->text('static_content')->nullable();
$table->timestamps();
$table->unique(['tenant_code', 'menu_code']);
});
Schema::create('roles', function (Blueprint $table): void {
$table->id();
$table->string('codigo')->unique();
});
Schema::create('roles_menues', function (Blueprint $table): void {
$table->string('rol_codigo');
$table->string('menu_codigo');
$table->unique(['rol_codigo', 'menu_codigo']);
});
DB::table('menues')->insert(['code' => 'main.adminapp', 'label' => 'Administración']);
DB::table('roles')->insert([['codigo' => 'admin'], ['codigo' => 'adminapp'], ['codigo' => 'user']]);
$this->migration()->up();
$validity = Mockery::mock(TicketValidityResolver::class);
$validity->shouldReceive('resolveVariant')->andReturn(ResolvedTicketValidity::unrestricted());
$validity->shouldReceive('resolveTicket')->andReturn(ResolvedTicketValidity::unrestricted());
$this->app->instance(TicketValidityResolver::class, $validity);
}
private function migration()
{
return require database_path('migrations/2026_10_02_010000_add_ticket_reservations_adminapp_menu.php');
}
private function login(int $id = 1): void
{
Sanctum::actingAs(User::findOrFail($id));
}
private function payload(): array
{
return ['idempotency_key' => (string) Str::uuid(), 'rows' => [
['catalog_item_id' => 1, 'variant_id' => 1, 'tipo_pago' => 'otro_metodo'],
['catalog_item_id' => 2, 'variant_id' => null, 'tipo_pago' => 'sin_cargo'],
]];
}
public function test_menu_migration_and_seeder_only_assign_onticket_and_admin_roles(): void
{
DB::table('tenants_menues')->insert(['tenant_code' => 'other', 'menu_code' => 'adminapp.ticket-reservations']);
$this->migration()->up();
$this->assertSame(['onticket'], DB::table('tenants_menues')->where('menu_code', 'adminapp.ticket-reservations')->pluck('tenant_code')->all());
$this->assertSame(['admin', 'adminapp'], DB::table('roles_menues')->where('menu_codigo', 'adminapp.ticket-reservations')->orderBy('rol_codigo')->pluck('rol_codigo')->all());
$this->seed(MenuSeeder::class);
$this->assertDatabaseHas('menues', ['code' => 'adminapp.ticket-reservations', 'parent_menu_code' => 'main.adminapp', 'route' => '/admin/ticket-reservations']);
$this->assertSame(['onticket'], DB::table('tenants_menues')->where('menu_code', 'adminapp.ticket-reservations')->pluck('tenant_code')->all());
$this->assertDatabaseMissing('roles_menues', ['rol_codigo' => 'user', 'menu_codigo' => 'adminapp.ticket-reservations']);
$this->migration()->down();
$this->assertDatabaseMissing('menues', ['code' => 'adminapp.ticket-reservations']);
$this->assertDatabaseHas('menues', ['code' => 'main.adminapp']);
}
public function test_authentication_adminapp_role_and_menu_are_required(): void
{
$this->getJson(self::URL.'/form')->assertUnauthorized();
$this->login();
DB::table('users')->where('id', 1)->update(['rol_codigo' => 'user']);
$this->login();
$this->getJson(self::URL)->assertForbidden();
DB::table('users')->where('id', 1)->update(['rol_codigo' => 'adminapp']);
$this->login();
DB::table('tenants_menues')->delete();
$this->getJson(self::URL.'/form')->assertNotFound();
$this->postJson(self::URL, $this->payload())->assertNotFound();
}
public function test_other_tenant_is_rejected_even_if_the_menu_is_assigned(): void
{
DB::table('tenants_menues')->insert(['tenant_code' => 'other', 'menu_code' => 'adminapp.ticket-reservations']);
$this->login(2);
foreach (['', '/form', '/pdf', '/excel', '/1/ticket/pdf'] as $suffix) {
$this->getJson(self::URL.$suffix)->assertForbidden();
}
$this->postJson(self::URL, $this->payload())->assertForbidden();
$this->deleteJson(self::URL.'/1')->assertForbidden();
}
public function test_form_uses_generic_variants_and_keeps_reserved_variants_with_remaining_stock(): void
{
$this->login();
$this->postJson(self::URL, $this->payload())->assertOk();
$form = $this->getJson(self::URL.'/form')->assertOk();
$this->assertSame([1, 2, 4], array_column($form->json('data.items'), 'id'));
$this->assertSame(2, $form->json('data.items.0.variants.0.available_stock'));
$this->assertSame(250, $form->json('data.items.0.variants.0.price'));
$this->assertStringContainsString('NORMAL', $form->json('data.items.0.variants.0.label'));
$form->assertJsonPath('data.items.1.requires_variant', false)->assertJsonPath('data.items.2.available_stock', null);
DB::table('variantes')->where('id', 2)->update(['sales_disabled_at' => now()]);
DB::table('inventories')->where('id', 1)->update(['real_stock' => 1]);
DB::table('catalog_items')->where('id', 2)->update(['sales_end_at' => now()->subMinute()]);
$hidden = $this->getJson(self::URL.'/form')->assertOk();
$this->assertSame([4], array_column($hidden->json('data.items'), 'id'));
$this->assertSame([1, 2, 4], array_column($hidden->json('data.filter_items'), 'id'));
}
public function test_active_event_only_limits_new_selections_and_not_history(): void
{
$this->login();
$this->postJson(self::URL, $this->payload())->assertOk();
DB::table('tenants')->where('codigo', 'onticket')->update(['active_event_id' => 10]);
DB::table('catalog_items')->where('id', 4)->update(['event_id' => 10]);
$form = $this->getJson(self::URL.'/form')->assertOk();
$this->assertSame([4], array_column($form->json('data.items'), 'id'));
$this->getJson(self::URL)->assertOk()->assertJsonPath('meta.total', 2);
}
public function test_reserves_mixed_items_replays_filters_and_cancels_with_the_real_generator(): void
{
$this->login();
$payload = $this->payload();
$created = $this->postJson(self::URL, $payload)->assertOk();
$created->assertJsonPath('data.0.catalog_item_id', 1)->assertJsonPath('data.0.importe', '250.00')
->assertJsonPath('data.1.variant', null)->assertJsonPath('data.1.importe', '0.00');
$replay = $this->postJson(self::URL, $payload)->assertOk();
$this->assertSame($created->json('data'), $replay->json('data'));
$this->getJson(self::URL.'?catalog_item_id=1&variant_id=1&tipo_pago=otro_metodo&per_page=1')
->assertOk()->assertJsonPath('meta.total', 1)->assertJsonPath('data.0.variant.id', 1);
$this->assertDatabaseCount('tickets', 2);
$this->assertDatabaseHas('tickets', ['source_catalog_item_id' => 2, 'source_variant_id' => null]);
$id = $created->json('data.0.id');
$ticketId = $created->json('data.0.ticket_id');
$this->deleteJson(self::URL.'/'.$id)->assertNoContent();
$this->assertNotNull(Ticket::findOrFail($ticketId)->cancelled_at);
$this->assertSame(0, Inventory::findOrFail(1)->entry_reserved_stock);
$this->getJson(self::URL)->assertOk()->assertJsonPath('meta.total', 1);
}
public function test_invalid_selection_and_client_prices_are_rejected_atomically(): void
{
$this->login();
$payload = $this->payload();
$payload['rows'][0]['catalog_item_id'] = 3;
$this->postJson(self::URL, $payload)->assertUnprocessable()->assertJsonValidationErrors('rows.0.variant_id');
$payload = $this->payload();
$payload['rows'][1]['importe'] = 1;
$this->postJson(self::URL, $payload)->assertUnprocessable()->assertJsonValidationErrors('rows.1');
$this->assertDatabaseCount('tickets', 0);
$this->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
}
public function test_exports_use_generic_columns_filters_and_timezone(): void
{
$this->login();
$this->postJson(self::URL, $this->payload())->assertOk();
$query = '?catalog_item_id=2&timezone=America/Argentina/Buenos_Aires';
$this->getJson(self::URL.'/pdf?timezone=invalid')->assertUnprocessable();
$pdf = $this->get(self::URL.'/pdf'.$query)->assertOk()->assertHeader('Content-Type', 'application/pdf');
$this->assertStringStartsWith('%PDF', $pdf->getContent());
$excel = $this->get(self::URL.'/excel'.$query)->assertOk();
$content = $excel->streamedContent();
$this->assertStringStartsWith('PK', $content);
$filename = tempnam(sys_get_temp_dir(), 'ticket-reservations-test-');
try {
file_put_contents($filename, $content);
$sheet = IOFactory::load($filename)->getActiveSheet();
$this->assertSame(['Ítem', 'Variante', 'ID', 'Fecha', 'Importe', 'Pago'], $sheet->rangeToArray('A1:F1')[0]);
$this->assertSame(2, $sheet->getHighestRow());
$this->assertSame('Sin variante', $sheet->getCell('B2')->getValue());
$this->assertSame('Sin cargo', $sheet->getCell('F2')->getValue());
$this->assertSame('dd/mm/yyyy hh:mm', $sheet->getStyle('D2')->getNumberFormat()->getFormatCode());
} finally {
unlink($filename);
}
}
public function test_individual_ticket_download_and_cancellation_are_scoped_by_tenant(): void
{
$this->login();
$created = $this->postJson(self::URL, $this->payload())->assertOk();
$pdf = Mockery::mock(TicketPdfService::class);
$pdf->shouldReceive('download')->once()->andReturnUsing(function ($tenant, $tickets) use ($created) {
$this->assertSame('onticket', $tenant->codigo);
$this->assertSame($created->json('data.0.ticket_id'), $tickets->sole()->id);
return response('%PDF-test', 200, ['Content-Type' => 'application/pdf']);
});
$this->app->instance(TicketPdfService::class, $pdf);
$this->get(self::URL.'/'.$created->json('data.0.id').'/ticket/pdf')->assertOk();
$foreign = $this->app->make(EntryReservationService::class)
->reserve(User::findOrFail(2), (string) Str::uuid(), [
['catalog_item_id' => 3, 'tipo_pago' => 'sin_cargo'],
])->sole();
$this->getJson(self::URL.'/'.$foreign->id.'/ticket/pdf')->assertNotFound();
$this->deleteJson(self::URL.'/'.$foreign->id)->assertNotFound();
$this->assertNull(Ticket::findOrFail($foreign->ticket_id)->cancelled_at);
}
public function test_user_event_scope_limits_form_filters_history_exports_and_individual_actions(): void
{
DB::table('catalog_items')->where('id', 1)->update(['event_id' => 10]);
DB::table('catalog_items')->whereIn('id', [2, 4])->update(['event_id' => 20]);
$this->login();
$created = $this->postJson(self::URL, $this->payload())->assertOk();
$ownId = $created->json('data.0.id');
$outsideId = $created->json('data.1.id');
DB::table('users')->where('id', 1)->update(['event_id' => 10]);
DB::table('tenants')->where('codigo', 'onticket')->update(['active_event_id' => 20]);
$this->login();
$form = $this->getJson(self::URL.'/form')->assertOk();
$this->assertSame([1], array_column($form->json('data.items'), 'id'));
$this->assertSame([1], array_column($form->json('data.filter_items'), 'id'));
$this->getJson(self::URL)->assertOk()->assertJsonPath('meta.total', 1)->assertJsonPath('data.0.id', $ownId);
$this->getJson(self::URL.'?catalog_item_id=2&event_id=20')->assertOk()->assertJsonPath('meta.total', 0);
$this->getJson(self::URL.'/'.$outsideId.'/ticket/pdf')->assertNotFound();
$this->deleteJson(self::URL.'/'.$outsideId)->assertNotFound();
$this->assertNull(Ticket::findOrFail($created->json('data.1.ticket_id'))->cancelled_at);
$pdf = Mockery::mock(EntryReservationPdfService::class);
$pdf->shouldReceive('download')->once()->andReturnUsing(function ($tenant, $reservations) use ($ownId) {
$this->assertSame([$ownId], $reservations->pluck('id')->all());
return response('%PDF-test', 200);
});
$this->app->instance(EntryReservationPdfService::class, $pdf);
$this->get(self::URL.'/pdf?timezone=UTC')->assertOk();
$excel = Mockery::mock(EntryReservationExcelService::class);
$excel->shouldReceive('download')->once()->andReturnUsing(function ($tenant, $reservations) use ($ownId) {
$this->assertSame([$ownId], $reservations->pluck('id')->all());
return response()->streamDownload(fn () => print ('test'), 'reservations.xlsx');
});
$this->app->instance(EntryReservationExcelService::class, $excel);
$this->get(self::URL.'/excel?timezone=UTC')->assertOk();
$this->deleteJson(self::URL.'/'.$ownId)->assertNoContent();
}
public function test_user_event_scope_overrides_active_event_for_new_reservations_and_rejects_other_items(): void
{
DB::table('catalog_items')->where('id', 1)->update(['event_id' => 10]);
DB::table('catalog_items')->where('id', 2)->update(['event_id' => 20]);
DB::table('tenants')->where('codigo', 'onticket')->update(['active_event_id' => 20]);
DB::table('users')->where('id', 1)->update(['event_id' => 10]);
$this->login();
$this->postJson(self::URL, $this->payload())->assertUnprocessable()->assertJsonValidationErrors('rows.1.catalog_item_id');
$this->assertDatabaseCount('tickets', 0);
$payload = $this->payload();
$payload['rows'] = [$payload['rows'][0]];
$created = $this->postJson(self::URL, $payload)->assertOk();
$this->assertDatabaseHas('tickets', ['id' => $created->json('data.0.ticket_id'), 'event_id' => 10]);
$this->postJson(self::URL, $payload)->assertOk()->assertJsonPath('data.0.id', $created->json('data.0.id'));
$this->assertDatabaseCount('tickets', 1);
}
public function test_retries_cannot_replay_a_mixed_event_batch_after_user_scope_changes(): void
{
DB::table('catalog_items')->where('id', 1)->update(['event_id' => 10]);
DB::table('catalog_items')->where('id', 2)->update(['event_id' => 20]);
$this->login();
$payload = $this->payload();
$created = $this->postJson(self::URL, $payload)->assertOk();
// Cancelled rows still belong to the batch and cannot bypass the new scope.
$this->deleteJson(self::URL.'/'.$created->json('data.1.id'))->assertNoContent();
DB::table('users')->where('id', 1)->update(['event_id' => 10]);
$this->login();
$this->postJson(self::URL, $payload)->assertForbidden();
$this->assertDatabaseCount('tickets', 2);
$this->assertDatabaseCount('reservation_batches', 1);
}
}

View File

@@ -1,6 +1,6 @@
<?php
namespace Tests\Feature\Desfile;
namespace Tests\Feature\Ticket;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Schema;
@@ -12,8 +12,9 @@ class EntryReservationSchemaTest extends TestCase
public function test_the_entry_reservations_table_has_the_requested_columns(): void
{
$this->assertTrue(Schema::hasColumns('desfile_entry_reservations', [
$this->assertTrue(Schema::hasColumns('entry_reservations', [
'id',
'catalog_item_id',
'variant_id',
'fecha_reserva',
'importe',

View File

@@ -0,0 +1,370 @@
<?php
namespace Tests\Feature\Ticket;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Services\EntryReservationPolicy;
use App\Domains\Ticketing\Ticket\Services\EntryReservationService;
use App\Domains\Ticketing\Ticket\Services\ResolvedTicketValidity;
use App\Domains\Ticketing\Ticket\Services\TicketGeneratorService;
use App\Domains\Ticketing\Ticket\Services\TicketValidityResolver;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Mockery;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\Support\CreatesTicketReservationSchema;
use Tests\TestCase;
/** Uses real transactions on the guarded SQLite :memory: connection. */
class EntryReservationServiceTest extends TestCase
{
use CreatesTicketReservationSchema;
protected function setUp(): void
{
parent::setUp();
$this->createTicketReservationSchema();
}
private function service(bool $failSecond = false): EntryReservationService
{
$generator = Mockery::mock(TicketGeneratorService::class);
$generator->shouldReceive('generate')->andReturnUsing(function ($item, $user, $quantity, $variantId) use ($failSecond) {
if ($failSecond && $item->id === 2) {
throw new \RuntimeException('Ticket generation failed');
}
return collect([Ticket::create([
'tenant_code' => $item->tenant_code, 'user_id' => $user->id,
'source_catalog_item_id' => $item->id, 'source_variant_id' => $variantId,
'ticket' => (string) Str::uuid(),
])]);
});
return new EntryReservationService($generator);
}
private function rows(): array
{
return [
['catalog_item_id' => 1, 'variant_id' => 1, 'tipo_pago' => 'sin_cargo'],
['catalog_item_id' => 2, 'tipo_pago' => 'otro_metodo'],
];
}
public function test_reserves_multiple_items_with_and_without_variants_and_replays_the_batch(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$key = (string) Str::uuid();
$result = $service->reserve($user, $key, $this->rows());
$this->assertSame([1, 2], $result->pluck('catalog_item_id')->all());
$this->assertSame([1, null], $result->pluck('variant_id')->all());
$this->assertSame(['0.00', '700.00'], $result->pluck('importe')->all());
$replay = $service->reserve($user, $key, array_reverse($this->rows()));
$this->assertSame($result->pluck('id')->all(), $replay->pluck('id')->all());
$this->assertDatabaseCount('tickets', 2);
$this->assertDatabaseCount('entry_reservations', 2);
$this->assertDatabaseCount('reservation_batches', 1);
$this->assertSame(1, Inventory::findOrFail(1)->entry_reserved_stock);
$this->assertSame(1, Inventory::findOrFail(3)->entry_reserved_stock);
}
public function test_repeated_variants_use_stock_instead_of_assuming_a_unique_seat(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$row = $this->rows()[0];
$service->reserve($user, (string) Str::uuid(), [$row, $row]);
$service->reserve($user, (string) Str::uuid(), [$row]);
$this->assertSame(3, Inventory::findOrFail(1)->entry_reserved_stock);
$this->expectException(ValidationException::class);
$service->reserve($user, (string) Str::uuid(), [$row]);
}
public function test_custom_policy_validates_resolved_selections_inside_the_transaction_before_stock_changes(): void
{
$policy = Mockery::mock(EntryReservationPolicy::class);
$policy->shouldReceive('validate')->once()->andReturnUsing(function (array $selections): void {
$this->assertGreaterThan(0, DB::transactionLevel());
$this->assertSame(1, $selections[0]['item']->id);
$this->assertSame(1, $selections[0]['variant']->id);
$this->assertSame(2, $selections[1]['item']->id);
$this->assertNull($selections[1]['variant']);
$this->assertSame(0, $selections[0]['inventory']->entry_reserved_stock);
throw ValidationException::withMessages(['rows.0.variant_id' => 'Custom selection rule.']);
});
try {
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows(), $policy);
$this->fail('Expected custom selection validation');
} catch (ValidationException $error) {
$this->assertSame(['rows.0.variant_id' => ['Custom selection rule.']], $error->errors());
}
$this->assertDatabaseCount('tickets', 0);
$this->assertDatabaseCount('reservation_batches', 0);
$this->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
}
public function test_idempotent_replays_do_not_validate_the_custom_policy_again(): void
{
$policy = Mockery::mock(EntryReservationPolicy::class);
$policy->shouldReceive('validate')->once();
$service = $this->service();
$user = User::findOrFail(1);
$key = (string) Str::uuid();
$result = $service->reserve($user, $key, $this->rows(), $policy);
$replay = $service->reserve($user, $key, array_reverse($this->rows()), $policy);
$this->assertSame($result->pluck('id')->all(), $replay->pluck('id')->all());
$this->assertDatabaseCount('tickets', 2);
$this->assertSame(1, Inventory::findOrFail(1)->entry_reserved_stock);
}
public function test_shared_inventory_is_checked_for_the_entire_batch(): void
{
DB::table('catalog_items')->where('id', 2)->update(['inventory_id' => 1]);
DB::table('inventories')->where('id', 1)->update(['real_stock' => 1]);
try {
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
$this->fail('Expected insufficient shared stock');
} catch (ValidationException $error) {
$this->assertSame(['rows.0.variant_id', 'rows.1.catalog_item_id'], array_keys($error->errors()));
}
$this->assertDatabaseCount('tickets', 0);
$this->assertDatabaseCount('reservation_batches', 0);
$this->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
}
public function test_ticket_failure_rolls_back_the_entire_batch(): void
{
try {
$this->service(true)->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
$this->fail('Expected ticket failure');
} catch (\RuntimeException $error) {
$this->assertSame('Ticket generation failed', $error->getMessage());
}
$this->assertDatabaseCount('tickets', 0);
$this->assertDatabaseCount('entry_reservations', 0);
$this->assertDatabaseCount('reservation_batches', 0);
$this->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
}
public function test_an_item_from_another_tenant_is_rejected(): void
{
$this->expectException(ValidationException::class);
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), [
['catalog_item_id' => 3, 'tipo_pago' => 'sin_cargo'],
]);
}
public function test_a_variant_from_another_item_is_rejected(): void
{
$this->expectException(ValidationException::class);
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), [
['catalog_item_id' => 2, 'variant_id' => 1, 'tipo_pago' => 'sin_cargo'],
]);
}
public function test_a_variant_is_required_when_the_item_has_variants(): void
{
$this->expectException(ValidationException::class);
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), [
['catalog_item_id' => 1, 'tipo_pago' => 'sin_cargo'],
]);
}
public function test_disabled_variants_and_items_without_tickets_are_rejected(): void
{
DB::table('variantes')->where('id', 1)->update(['sales_disabled_at' => now()]);
DB::table('catalog_items')->where('id', 2)->update(['has_tickets' => false]);
try {
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
$this->fail('Expected unavailable selection');
} catch (ValidationException $error) {
$this->assertSame(['rows.0.variant_id', 'rows.1.catalog_item_id'], array_keys($error->errors()));
}
$this->assertDatabaseCount('entry_reservations', 0);
}
public function test_the_active_event_limits_the_catalog_for_new_reservations(): void
{
DB::table('tenants')->where('codigo', 'ticket_shop')->update(['active_event_id' => 10]);
DB::table('catalog_items')->where('id', 1)->update(['event_id' => 10]);
DB::table('catalog_items')->where('id', 2)->update(['event_id' => 20]);
$this->expectException(ValidationException::class);
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
}
public function test_unlimited_items_can_emit_tickets_without_inventory(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$reservation = $service->reserve($user, (string) Str::uuid(), [
['catalog_item_id' => 4, 'tipo_pago' => 'otro_metodo'],
])->sole();
$this->assertNull($reservation->inventory_id);
$this->assertNull($reservation->variant_id);
$this->assertSame('500.00', $reservation->importe);
$service->cancel($user, $reservation->id);
$this->assertSoftDeleted('entry_reservations', ['id' => $reservation->id]);
}
public function test_filters_and_exports_are_scoped_by_tenant_and_catalog_item(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$service->reserve($user, (string) Str::uuid(), $this->rows());
$service->reserve(User::findOrFail(2), (string) Str::uuid(), [
['catalog_item_id' => 3, 'tipo_pago' => 'sin_cargo'],
]);
$this->assertSame(2, $service->reservations($user)->total());
$this->assertSame(1, $service->reservations($user, ['catalog_item_id' => 2, 'tipo_pago' => 'otro_metodo'])->total());
$this->assertSame(1, $service->reservations($user, ['variant_id' => 1, 'per_page' => 1])->total());
$this->assertSame(2, $service->reservationsForExport($user)->count());
$this->assertSame(2, $service->reservationsForExport($user, ['catalog_item_id' => 2])->sole()->catalog_item_id);
$this->assertSame(0, $service->reservations($user, ['catalog_item_id' => 3])->total());
}
public function test_cancel_releases_stock_and_cancels_the_ticket_without_a_variant(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$reservation = $service->reserve($user, (string) Str::uuid(), [$this->rows()[1]])->sole();
$service->cancel($user, $reservation->id, 2);
$this->assertSoftDeleted('entry_reservations', ['id' => $reservation->id]);
$this->assertNotNull(Ticket::findOrFail($reservation->ticket_id)->cancelled_at);
$this->assertSame(0, Inventory::findOrFail(3)->entry_reserved_stock);
$this->assertSame(0, $service->reservations($user)->total());
}
public function test_another_tenant_cannot_cancel_a_reservation(): void
{
$service = $this->service();
$reservation = $service->reserve(User::findOrFail(1), (string) Str::uuid(), [$this->rows()[0]])->sole();
$this->expectException(ModelNotFoundException::class);
$service->cancel(User::findOrFail(2), $reservation->id);
}
public function test_cancellation_can_be_restricted_to_one_catalog_item_by_an_adapter(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$reservation = $service->reserve($user, (string) Str::uuid(), [$this->rows()[0]])->sole();
$this->expectException(ModelNotFoundException::class);
$service->cancel($user, $reservation->id, 2);
}
public function test_cancellation_does_not_release_stock_for_a_used_ticket(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$reservation = $service->reserve($user, (string) Str::uuid(), [$this->rows()[0]])->sole();
Ticket::whereKey($reservation->ticket_id)->update(['used_at' => now()]);
try {
$service->cancel($user, $reservation->id);
$this->fail('Expected active ticket requirement');
} catch (ValidationException $error) {
$this->assertArrayHasKey('status', $error->errors());
}
$this->assertSame(1, Inventory::findOrFail(1)->entry_reserved_stock);
$this->assertDatabaseHas('entry_reservations', ['id' => $reservation->id, 'deleted_at' => null]);
}
public function test_a_reused_key_with_a_different_item_is_rejected(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$key = (string) Str::uuid();
$service->reserve($user, $key, [$this->rows()[1]]);
try {
$service->reserve($user, $key, [['catalog_item_id' => 4, 'tipo_pago' => 'otro_metodo']]);
$this->fail('Expected idempotency conflict');
} catch (HttpException $error) {
$this->assertSame(409, $error->getStatusCode());
}
$this->assertDatabaseCount('tickets', 1);
}
public function test_clients_cannot_supply_the_price(): void
{
$this->expectException(ValidationException::class);
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), [
[...$this->rows()[0], 'importe' => 10],
]);
}
public function test_old_variant_only_batch_hashes_replay_including_cancelled_history(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$key = (string) Str::uuid();
$rows = [
['catalog_item_id' => 1, 'variant_id' => 1, 'tipo_pago' => 'sin_cargo'],
['catalog_item_id' => 1, 'variant_id' => 2, 'tipo_pago' => 'otro_metodo'],
];
$result = $service->reserve($user, $key, $rows);
$legacyRows = array_map(fn ($row) => ['variant_id' => $row['variant_id'], 'tipo_pago' => $row['tipo_pago']], $rows);
DB::table('reservation_batches')->update([
'request_hash' => hash('sha256', json_encode($legacyRows, JSON_THROW_ON_ERROR)),
]);
$service->cancel($user, $result->first()->id);
$replay = $service->reserve($user, $key, array_reverse($rows));
$this->assertSame($result->last()->id, $replay->sole()->id);
$this->assertDatabaseCount('tickets', 2);
$this->assertDatabaseCount('reservation_batches', 1);
$this->assertSame(0, Inventory::findOrFail(1)->entry_reserved_stock);
$this->assertSame(1, Inventory::findOrFail(2)->entry_reserved_stock);
}
public function test_old_batch_hashes_cannot_replay_with_a_different_catalog_item(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$key = (string) Str::uuid();
$service->reserve($user, $key, [$this->rows()[0]]);
DB::table('reservation_batches')->update([
'request_hash' => hash('sha256', json_encode([
['variant_id' => 1, 'tipo_pago' => 'sin_cargo'],
], JSON_THROW_ON_ERROR)),
]);
try {
$service->reserve($user, $key, [
['catalog_item_id' => 2, 'variant_id' => 1, 'tipo_pago' => 'sin_cargo'],
]);
$this->fail('Expected legacy idempotency conflict');
} catch (HttpException $error) {
$this->assertSame(409, $error->getStatusCode());
}
$this->assertDatabaseCount('tickets', 1);
}
public function test_ticket_download_selection_uses_tenant_and_catalog_item_scope(): void
{
$service = $this->service();
$user = User::findOrFail(1);
$reservation = $service->reserve($user, (string) Str::uuid(), [$this->rows()[1]])->sole();
$this->assertSame($reservation->ticket_id, $service->reservationTicket($user, $reservation->id, 2)->id);
$this->expectException(ModelNotFoundException::class);
$service->reservationTicket(User::findOrFail(2), $reservation->id);
}
public function test_real_ticket_generator_links_each_catalog_item_and_optional_variant(): void
{
$validity = Mockery::mock(TicketValidityResolver::class);
$validity->shouldReceive('resolveVariant')->andReturn(ResolvedTicketValidity::unrestricted());
$service = new EntryReservationService(new TicketGeneratorService($validity));
$result = $service->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
foreach ($result as $reservation) {
$this->assertDatabaseHas('tickets', [
'id' => $reservation->ticket_id, 'tenant_code' => 'ticket_shop',
'source_catalog_item_id' => $reservation->catalog_item_id,
'source_variant_id' => $reservation->variant_id, 'source_purchase_item_id' => null,
]);
}
}
}

View File

@@ -0,0 +1,156 @@
<?php
namespace Tests\Support;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
trait CreatesTicketReservationSchema
{
protected function createTicketReservationSchema(string $tenantCode = 'ticket_shop'): void
{
// Minimal domain schema isolates this workflow from unrelated legacy migrations.
Schema::create('users', function (Blueprint $table): void {
$table->id();
$table->string('tenant_codigo');
$table->unsignedBigInteger('event_id')->nullable();
$table->softDeletes();
});
Schema::create('tenants', function (Blueprint $table): void {
$table->id();
$table->string('codigo')->unique();
$table->unsignedBigInteger('active_event_id')->nullable();
});
Schema::create('catalog_items', function (Blueprint $table): void {
$table->id();
$table->string('tenant_code');
$table->string('slug');
$table->string('nombre')->default('Entrada');
$table->string('type')->default('standard');
$table->unsignedBigInteger('inventory_id')->nullable();
$table->string('inventory_policy');
$table->decimal('precio', 10, 2);
$table->timestamp('sales_end_at')->nullable();
$table->softDeletes();
$table->boolean('has_tickets')->default(true);
$table->unsignedBigInteger('event_id')->nullable();
});
Schema::create('inventories', function (Blueprint $table): void {
$table->id();
foreach (['real_stock', 'reserved_stock', 'sold_units', 'refunded_units'] as $column) {
$table->integer($column)->default(0);
}
});
Schema::create('variantes', function (Blueprint $table): void {
$table->id();
$table->foreignId('catalog_item_id');
$table->foreignId('inventory_id');
$table->decimal('precio', 10, 2);
$table->unsignedBigInteger('event_date_id')->nullable();
$table->unsignedBigInteger('replaced_by_variant_id')->nullable();
$table->timestamp('sales_disabled_at')->nullable();
$table->softDeletes();
});
Schema::create('event_dates', function (Blueprint $table): void {
$table->id();
$table->date('date');
$table->time('time_start')->nullable();
$table->unsignedBigInteger('rescheduled_to_event_date_id')->nullable();
$table->timestamp('suspended_at')->nullable();
});
Schema::create('attribute', function (Blueprint $table): void {
$table->id();
$table->string('codigo');
$table->string('type')->default('string');
});
Schema::create('item_attributes', function (Blueprint $table): void {
$table->id();
$table->foreignId('catalog_item_id');
$table->foreignId('attribute_id');
$table->boolean('allow_multi_select')->default(false);
$table->integer('sort_order')->default(0);
});
Schema::create('attribute_options', function (Blueprint $table): void {
$table->id();
$table->foreignId('attribute_id');
$table->string('value');
$table->string('label');
$table->integer('sort_order')->default(0);
});
Schema::create('variant_values', function (Blueprint $table): void {
$table->id();
$table->foreignId('variant_id');
$table->foreignId('item_attribute_id');
$table->string('value');
});
Schema::create('variant_event_dates', function (Blueprint $table): void {
$table->foreignId('variant_id');
$table->foreignId('event_date_id');
});
Schema::create('tickets', function (Blueprint $table): void {
$table->id();
$table->foreignId('user_id');
$table->foreignId('source_variant_id')->nullable();
$table->string('tenant_code')->nullable();
$table->uuid('ticket')->nullable()->unique();
$table->unsignedBigInteger('source_catalog_item_id')->nullable();
$table->unsignedBigInteger('source_purchase_item_id')->nullable();
$table->unsignedBigInteger('event_id')->nullable();
$table->timestamp('used_at')->nullable();
$table->timestamp('disabled_at')->nullable();
$table->timestamp('cancelled_at')->nullable();
$table->timestamp('refunded_at')->nullable();
});
Schema::create('value_changes', function (Blueprint $table): void {
$table->id();
$table->morphs('trackable');
$table->string('tenant_code');
$table->string('attribute');
$table->text('old_value')->nullable();
$table->text('new_value')->nullable();
$table->timestamp('changed_at');
$table->string('actor_type');
$table->foreignId('user_id')->nullable();
});
(require database_path('migrations/2026_09_23_010000_create_desfile_entry_reservations_table.php'))->up();
(require database_path('migrations/2026_09_24_000000_add_administrative_entry_reservation_stock.php'))->up();
(require database_path('migrations/2026_09_24_010000_add_soft_deletes_to_desfile_entry_reservations_table.php'))->up();
(require database_path('migrations/2026_10_02_000000_generalize_ticket_reservations.php'))->up();
DB::table('tenants')->insert(['codigo' => $tenantCode]);
DB::table('users')->insert(['id' => 1, 'tenant_codigo' => $tenantCode]);
DB::table('catalog_items')->insert([
'id' => 1, 'tenant_code' => $tenantCode, 'slug' => 'entrada',
'inventory_policy' => 'tracked', 'precio' => 100,
]);
foreach ([1, 2] as $id) {
DB::table('inventories')->insert(['id' => $id, 'real_stock' => 3]);
DB::table('variantes')->insert(['id' => $id, 'catalog_item_id' => 1, 'inventory_id' => $id, 'precio' => 250]);
}
DB::table('tenants')->insert(['codigo' => 'other']);
DB::table('users')->insert(['id' => 2, 'tenant_codigo' => 'other']);
DB::table('inventories')->insert(['id' => 3, 'real_stock' => 3]);
DB::table('catalog_items')->insert([
['id' => 2, 'tenant_code' => $tenantCode, 'slug' => 'general', 'inventory_policy' => 'tracked', 'inventory_id' => 3, 'precio' => 700],
['id' => 3, 'tenant_code' => 'other', 'slug' => 'other', 'inventory_policy' => 'unlimited', 'inventory_id' => null, 'precio' => 900],
['id' => 4, 'tenant_code' => $tenantCode, 'slug' => 'unlimited', 'inventory_policy' => 'unlimited', 'inventory_id' => null, 'precio' => 500],
]);
foreach (['tipo' => 'NORMAL', 'sector' => 'A', 'fila' => '3', 'asiento' => '17'] as $code => $value) {
$attributeId = DB::table('attribute')->insertGetId(['codigo' => $code]);
$itemAttributeId = DB::table('item_attributes')->insertGetId([
'catalog_item_id' => 1,
'attribute_id' => $attributeId,
]);
DB::table('attribute_options')->insert([
'attribute_id' => $attributeId,
'value' => $value,
'label' => $value,
]);
foreach ([1, 2] as $variantId) {
DB::table('variant_values')->insert([
'variant_id' => $variantId, 'item_attribute_id' => $itemAttributeId, 'value' => $value,
]);
}
}
}
}

View File

@@ -6,7 +6,7 @@ use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
use App\Domains\Commerce\Catalog\Models\CatalogItem;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use Illuminate\Database\Eloquent\Collection;
use Tests\TestCase;
@@ -16,10 +16,10 @@ class VariantAvailabilityTest extends TestCase
{
$reserved = new Variant;
$reserved->id = 1;
$reserved->setRelation('desfileEntryReservations', new Collection([new EntryReservation]));
$reserved->setRelation('entryReservations', new Collection([new EntryReservation]));
$available = new Variant;
$available->id = 2;
$available->setRelation('desfileEntryReservations', new Collection);
$available->setRelation('entryReservations', new Collection);
$item = new CatalogItem(['inventory_policy' => InventoryPolicy::Unlimited]);
$item->setRelation('variants', new Collection([$reserved, $available]));

View File

@@ -1,9 +1,9 @@
<?php
namespace Tests\Unit\Desfile;
namespace Tests\Unit\Ticket;
use App\Domains\Ticketing\Desfile\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use PHPUnit\Framework\TestCase;
class EntryReservationTest extends TestCase
@@ -21,6 +21,7 @@ class EntryReservationTest extends TestCase
$reservation = new EntryReservation;
$this->assertSame([
'catalog_item_id',
'variant_id',
'ticket_id',
'inventory_id',

View File

@@ -6,8 +6,8 @@ use App\Domains\Commerce\Catalog\Models\CatalogItem;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Enums\ValidityTimeType;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Models\ValidityTime;
use App\Domains\Ticketing\Ticket\Services\ResolvedTicketValidity;