463 lines
21 KiB
PHP
463 lines
21 KiB
PHP
<?php
|
|
|
|
namespace Tests\Feature\Desfile;
|
|
|
|
use App\Domains\Commerce\Catalog\Models\Inventory;
|
|
use App\Domains\Core\Auth\Models\User;
|
|
use App\Domains\Core\Tenant\Models\Tenant;
|
|
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\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\ResolvedTicketValidity;
|
|
use App\Domains\Ticketing\Ticket\Services\TicketGeneratorService;
|
|
use App\Domains\Ticketing\Ticket\Services\TicketValidityResolver;
|
|
use Barryvdh\DomPDF\ServiceProvider as DomPdfServiceProvider;
|
|
use Illuminate\Database\Schema\Blueprint;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Mockery;
|
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
use Tests\TestCase;
|
|
|
|
/** Exercises real transactions on the guarded SQLite :memory: connection. */
|
|
class EntryReservationServiceTest extends TestCase
|
|
{
|
|
protected function setUp(): void
|
|
{
|
|
parent::setUp();
|
|
$this->app->register(DomPdfServiceProvider::class);
|
|
// Minimal domain schema isolates this workflow from unrelated legacy migrations.
|
|
Schema::create('users', function (Blueprint $table): void {
|
|
$table->id();
|
|
$table->string('tenant_codigo');
|
|
$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('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();
|
|
});
|
|
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');
|
|
$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();
|
|
DB::table('tenants')->insert(['codigo' => 'desfile_pura_tendencia']);
|
|
DB::table('users')->insert(['id' => 1, 'tenant_codigo' => 'desfile_pura_tendencia']);
|
|
DB::table('catalog_items')->insert([
|
|
'id' => 1, 'tenant_code' => 'desfile_pura_tendencia', 'slug' => 'entrada',
|
|
'inventory_policy' => 'tracked', 'precio' => 100,
|
|
]);
|
|
foreach ([1, 2] as $id) {
|
|
DB::table('inventories')->insert(['id' => $id, 'real_stock' => 1]);
|
|
DB::table('variantes')->insert(['id' => $id, 'catalog_item_id' => 1, 'inventory_id' => $id, 'precio' => 250]);
|
|
}
|
|
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,
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
private function service(bool $failSecond = false): EntryReservationService
|
|
{
|
|
$generator = Mockery::mock(TicketGeneratorService::class);
|
|
$generator->shouldReceive('generate')->andReturnUsing(function ($entry, $user, $quantity, $variantId) use ($failSecond) {
|
|
if ($failSecond && $variantId === 2) {
|
|
throw new \RuntimeException('Ticket generation failed');
|
|
}
|
|
$this->assertSame(1, $quantity);
|
|
$id = DB::table('tickets')->insertGetId([
|
|
'user_id' => $user->id,
|
|
'source_variant_id' => $variantId,
|
|
'tenant_code' => $user->tenant_codigo,
|
|
]);
|
|
|
|
return collect([Ticket::query()->findOrFail($id)]);
|
|
});
|
|
|
|
return new EntryReservationService($generator);
|
|
}
|
|
|
|
private function rows(): array
|
|
{
|
|
return [['variant_id' => 1, 'tipo_pago' => 'sin_cargo'], ['variant_id' => 2, 'tipo_pago' => 'otro_metodo']];
|
|
}
|
|
|
|
public function test_reserves_stock_calculates_prices_and_replays_without_duplicates(): void
|
|
{
|
|
$service = $this->service();
|
|
$key = (string) Str::uuid();
|
|
$user = User::query()->findOrFail(1);
|
|
$result = $service->reserve($user, $key, $this->rows());
|
|
$this->assertSame(['0.00', '250.00'], $result->pluck('importe')->all());
|
|
$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);
|
|
foreach (Inventory::all() as $inventory) {
|
|
$this->assertSame(1, $inventory->entry_reserved_stock);
|
|
$this->assertSame(1, $inventory->real_stock);
|
|
$this->assertSame(0, $inventory->reserved_stock);
|
|
$this->assertSame(0, $inventory->sold_units);
|
|
$this->assertSame(0, $inventory->availableStock());
|
|
}
|
|
$this->assertDatabaseHas('tickets', ['user_id' => 1, 'source_variant_id' => 1]);
|
|
}
|
|
|
|
public function test_conflicting_cart_stock_rejects_the_entire_batch(): void
|
|
{
|
|
DB::table('inventories')->where('id', 2)->update(['reserved_stock' => 1]);
|
|
try {
|
|
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
|
$this->fail('Expected unavailable variant');
|
|
} catch (ValidationException $error) {
|
|
$this->assertArrayHasKey('rows.1.variant_id', $error->errors());
|
|
$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->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
|
|
}
|
|
|
|
public function test_ticket_failure_rolls_back_stock_tickets_and_idempotency_record(): void
|
|
{
|
|
try {
|
|
$this->service(true)->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
|
$this->fail('Expected generation failure');
|
|
} catch (\RuntimeException $error) {
|
|
$this->assertSame('Ticket generation failed', $error->getMessage());
|
|
}
|
|
$this->assertDatabaseCount('tickets', 0);
|
|
$this->assertDatabaseCount('desfile_entry_reservations', 0);
|
|
$this->assertDatabaseCount('desfile_reservation_batches', 0);
|
|
$this->assertSame(0, (int) Inventory::sum('entry_reserved_stock'));
|
|
}
|
|
|
|
public function test_new_attempt_cannot_reserve_an_already_reserved_variant(): void
|
|
{
|
|
$service = $this->service();
|
|
$user = User::findOrFail(1);
|
|
$service->reserve($user, (string) Str::uuid(), $this->rows());
|
|
$this->expectException(ValidationException::class);
|
|
$service->reserve($user, (string) Str::uuid(), $this->rows());
|
|
}
|
|
|
|
public function test_it_cancels_the_ticket_releases_stock_and_soft_deletes_the_reservation(): void
|
|
{
|
|
$service = $this->service();
|
|
$user = User::findOrFail(1);
|
|
$reservation = $service->reserve($user, (string) Str::uuid(), [$this->rows()[0]])->sole();
|
|
|
|
$service->cancel($user, $reservation->id);
|
|
|
|
$this->assertSoftDeleted('desfile_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());
|
|
$this->assertSame(0, $service->reservations($user)->total());
|
|
$this->assertCount(0, $service->reservationsForExport($user));
|
|
}
|
|
|
|
public function test_it_does_not_release_stock_when_the_ticket_is_not_active(): void
|
|
{
|
|
$service = $this->service();
|
|
$user = User::findOrFail(1);
|
|
$reservation = $service->reserve($user, (string) Str::uuid(), [$this->rows()[0]])->sole();
|
|
Ticket::query()->whereKey($reservation->ticket_id)->update(['used_at' => now()]);
|
|
|
|
try {
|
|
$service->cancel($user, $reservation->id);
|
|
$this->fail('Expected cancellation validation error');
|
|
} catch (ValidationException $error) {
|
|
$this->assertArrayHasKey('status', $error->errors());
|
|
}
|
|
|
|
$this->assertDatabaseHas('desfile_entry_reservations', [
|
|
'id' => $reservation->id,
|
|
'deleted_at' => null,
|
|
]);
|
|
$this->assertSame(1, Inventory::findOrFail(1)->entry_reserved_stock);
|
|
}
|
|
|
|
public function test_a_reused_key_with_different_rows_is_rejected(): void
|
|
{
|
|
$service = $this->service();
|
|
$key = (string) Str::uuid();
|
|
$user = User::findOrFail(1);
|
|
$service->reserve($user, $key, $this->rows());
|
|
try {
|
|
$service->reserve($user, $key, [['variant_id' => 1, 'tipo_pago' => 'otro_metodo']]);
|
|
$this->fail('Expected conflict');
|
|
} catch (HttpException $error) {
|
|
$this->assertSame(409, $error->getStatusCode());
|
|
}
|
|
$this->assertDatabaseCount('tickets', 2);
|
|
}
|
|
|
|
public function test_variants_outside_the_tenant_catalog_are_rejected(): void
|
|
{
|
|
DB::table('variantes')->where('id', 2)->update(['catalog_item_id' => 999]);
|
|
$this->expectException(ValidationException::class);
|
|
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
|
}
|
|
|
|
public function test_shared_inventory_is_checked_for_the_whole_batch(): void
|
|
{
|
|
DB::table('variantes')->where('id', 2)->update(['inventory_id' => 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.variant_id'], array_keys($error->errors()));
|
|
foreach ($error->errors() as $messages) {
|
|
$this->assertStringContainsString('Tipo: NORMAL, Sector: A, Fila: 3, Asiento: 17', $messages[0]);
|
|
}
|
|
}
|
|
$this->assertDatabaseCount('tickets', 0);
|
|
}
|
|
|
|
public function test_cart_cannot_reserve_administratively_reserved_stock(): void
|
|
{
|
|
$this->service()->reserve(User::findOrFail(1), (string) Str::uuid(), $this->rows());
|
|
$this->expectException(\InvalidArgumentException::class);
|
|
Inventory::findOrFail(1)->reserve(1, true);
|
|
}
|
|
|
|
public function test_lists_paginated_reservations_filtered_by_payment_type(): void
|
|
{
|
|
$service = $this->service();
|
|
$user = User::findOrFail(1);
|
|
$service->reserve($user, (string) Str::uuid(), $this->rows());
|
|
|
|
$reservations = $service->reservations($user, [
|
|
'tipo_pago' => 'otro_metodo',
|
|
'page' => 1,
|
|
'per_page' => 1,
|
|
]);
|
|
|
|
$this->assertSame(1, $reservations->total());
|
|
$this->assertSame(1, $reservations->perPage());
|
|
$reservation = $reservations->sole();
|
|
$this->assertSame('otro_metodo', $reservation->tipo_pago->value);
|
|
$this->assertNotNull($reservation->ticket_id);
|
|
$this->assertSame('NORMAL', $reservation->variant->selectionValues()->get('tipo'));
|
|
|
|
$payload = (new EntryReservationResource($reservation))->toArray(Request::create('/'));
|
|
$this->assertSame($reservation->id, $payload['id']);
|
|
$this->assertSame($reservation->ticket_id, $payload['ticket_id']);
|
|
$this->assertSame('NORMAL', $payload['entrada']['tipo']);
|
|
$this->assertSame('Otro método', $payload['tipo_pago_label']);
|
|
}
|
|
|
|
public function test_request_rejects_duplicate_variants_and_client_amounts(): void
|
|
{
|
|
$rules = (new StoreEntryReservationsRequest)->rules();
|
|
$validator = Validator::make([
|
|
'idempotency_key' => (string) Str::uuid(),
|
|
'rows' => [
|
|
['variant_id' => 1, 'tipo_pago' => 'sin_cargo', 'importe' => 0],
|
|
['variant_id' => 1, 'tipo_pago' => 'invalid'],
|
|
],
|
|
], $rules);
|
|
$this->assertTrue($validator->fails());
|
|
$this->assertArrayHasKey('rows.0', $validator->errors()->toArray());
|
|
$this->assertArrayHasKey('rows.1.variant_id', $validator->errors()->toArray());
|
|
$this->assertArrayHasKey('rows.1.tipo_pago', $validator->errors()->toArray());
|
|
}
|
|
|
|
public function test_index_request_validates_payment_type_and_pagination(): void
|
|
{
|
|
$validator = Validator::make([
|
|
'tipo_pago' => 'invalid',
|
|
'page' => 0,
|
|
'per_page' => 101,
|
|
], (new IndexEntryReservationsRequest)->rules());
|
|
|
|
$this->assertTrue($validator->fails());
|
|
$this->assertSame(
|
|
['tipo_pago', 'page', 'per_page'],
|
|
array_keys($validator->errors()->toArray()),
|
|
);
|
|
}
|
|
|
|
public function test_export_request_requires_a_valid_timezone(): void
|
|
{
|
|
$validator = Validator::make([
|
|
'tipo_pago' => 'sin_cargo',
|
|
'timezone' => 'Invalid/Timezone',
|
|
], (new ExportEntryReservationsRequest)->rules());
|
|
|
|
$this->assertTrue($validator->fails());
|
|
$this->assertArrayHasKey('timezone', $validator->errors()->toArray());
|
|
}
|
|
|
|
public function test_exports_filtered_reservations_to_pdf_and_excel(): void
|
|
{
|
|
$service = $this->service();
|
|
$user = User::findOrFail(1);
|
|
$service->reserve($user, (string) Str::uuid(), $this->rows());
|
|
$reservations = $service->reservationsForExport($user, ['tipo_pago' => 'otro_metodo']);
|
|
$tenant = Tenant::query()->firstOrFail();
|
|
$tenant->setAttribute('nombre', 'Desfile Pura Tendencia');
|
|
$report = new EntryReservationReportService;
|
|
|
|
$this->assertCount(1, $reservations);
|
|
$this->assertSame(
|
|
$reservations->sole()->ticket_id,
|
|
$service->reservationTicket($user, $reservations->sole()->id)->id,
|
|
);
|
|
$this->assertSame('Otro método', $report->rows($reservations)->sole()['pago']);
|
|
|
|
$pdf = (new EntryReservationPdfService($report))->download(
|
|
$tenant,
|
|
$reservations,
|
|
'America/Argentina/Buenos_Aires',
|
|
);
|
|
$this->assertSame('application/pdf', $pdf->headers->get('content-type'));
|
|
|
|
$excel = (new EntryReservationExcelService($report))->download(
|
|
$tenant,
|
|
$reservations,
|
|
'America/Argentina/Buenos_Aires',
|
|
);
|
|
$this->assertSame(
|
|
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
$excel->headers->get('content-type'),
|
|
);
|
|
}
|
|
|
|
public function test_real_ticket_generator_links_admin_variant_and_reservation(): 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, 'user_id' => 1,
|
|
'source_variant_id' => $reservation->variant_id,
|
|
'source_catalog_item_id' => 1, 'tenant_code' => 'desfile_pura_tendencia',
|
|
'source_purchase_item_id' => null,
|
|
]);
|
|
$this->assertTrue(Str::isUuid($reservation->ticket->ticket));
|
|
}
|
|
}
|
|
|
|
public function test_request_rejects_a_user_from_another_tenant(): void
|
|
{
|
|
$request = new StoreEntryReservationsRequest;
|
|
$request->setUserResolver(fn () => new User(['tenant_codigo' => 'other']));
|
|
$this->assertFalse($request->authorize());
|
|
}
|
|
}
|