diff --git a/app/Domains/Ticketing/Desfile/Controllers/EntryReservationController.php b/app/Domains/Ticketing/Desfile/Controllers/EntryReservationController.php new file mode 100644 index 0000000..7376e2a --- /dev/null +++ b/app/Domains/Ticketing/Desfile/Controllers/EntryReservationController.php @@ -0,0 +1,19 @@ +reserve( + $request->user(), $request->validated('idempotency_key'), $request->validated('rows'), + )); + } +} diff --git a/app/Domains/Ticketing/Desfile/Models/EntryReservation.php b/app/Domains/Ticketing/Desfile/Models/EntryReservation.php index 6af818b..40c7dea 100644 --- a/app/Domains/Ticketing/Desfile/Models/EntryReservation.php +++ b/app/Domains/Ticketing/Desfile/Models/EntryReservation.php @@ -2,14 +2,19 @@ namespace App\Domains\Ticketing\Desfile\Models; +use App\Domains\Commerce\Catalog\Models\Inventory; use App\Domains\Commerce\Catalog\Models\Variant; use App\Domains\Ticketing\Desfile\Enums\EntryReservationPaymentType; +use App\Domains\Ticketing\Ticket\Models\Ticket; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; #[Fillable([ 'variant_id', + 'ticket_id', + 'inventory_id', + 'batch_id', 'fecha_reserva', 'importe', 'tipo_pago', @@ -33,4 +38,14 @@ class EntryReservation extends Model { return $this->belongsTo(Variant::class)->withTrashed(); } + + public function ticket(): BelongsTo + { + return $this->belongsTo(Ticket::class); + } + + public function inventory(): BelongsTo + { + return $this->belongsTo(Inventory::class); + } } diff --git a/app/Domains/Ticketing/Desfile/Requests/StoreEntryReservationsRequest.php b/app/Domains/Ticketing/Desfile/Requests/StoreEntryReservationsRequest.php new file mode 100644 index 0000000..d479992 --- /dev/null +++ b/app/Domains/Ticketing/Desfile/Requests/StoreEntryReservationsRequest.php @@ -0,0 +1,26 @@ +user()?->tenant_codigo === 'desfile_pura_tendencia'; + } + + public function rules(): array + { + return [ + 'idempotency_key' => ['required', 'uuid'], + 'rows' => ['required', 'array', 'min:1', 'max:100'], + 'rows.*' => ['required', 'array:variant_id,tipo_pago'], + 'rows.*.variant_id' => ['required', 'integer', 'min:1', 'distinct'], + 'rows.*.tipo_pago' => ['required', Rule::enum(EntryReservationPaymentType::class)], + ]; + } +} diff --git a/app/Domains/Ticketing/Desfile/Resources/EntryReservationResource.php b/app/Domains/Ticketing/Desfile/Resources/EntryReservationResource.php new file mode 100644 index 0000000..29d9e73 --- /dev/null +++ b/app/Domains/Ticketing/Desfile/Resources/EntryReservationResource.php @@ -0,0 +1,21 @@ + $this->id, + 'variant_id' => $this->variant_id, + 'ticket_id' => $this->ticket_id, + 'fecha_reserva' => $this->fecha_reserva->toIso8601String(), + 'tipo_pago' => $this->tipo_pago->value, + 'importe' => $this->importe, + ]; + } +} diff --git a/app/Domains/Ticketing/Desfile/Services/EntryReservationService.php b/app/Domains/Ticketing/Desfile/Services/EntryReservationService.php new file mode 100644 index 0000000..dc92183 --- /dev/null +++ b/app/Domains/Ticketing/Desfile/Services/EntryReservationService.php @@ -0,0 +1,132 @@ + $rows */ + public function reserve(User $user, string $key, array $rows): Collection + { + abort_unless($user->tenant_codigo === 'desfile_pura_tendencia', 403); + $normalized = collect($rows)->map(fn (array $row): array => [ + 'variant_id' => (int) $row['variant_id'], 'tipo_pago' => $row['tipo_pago'], + ])->sortBy('variant_id')->values()->all(); + $hash = hash('sha256', json_encode($normalized, JSON_THROW_ON_ERROR)); + + return DB::transaction(function () use ($user, $key, $rows, $hash): Collection { + // Serialize retries by the same administrator, including the first insert. + User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail(); + $batch = DB::table('desfile_reservation_batches') + ->where('user_id', $user->id)->where('idempotency_key', $key)->lockForUpdate()->first(); + if ($batch !== null) { + abort_unless($batch->tenant_code === $user->tenant_codigo && hash_equals($batch->request_hash, $hash), 409, + 'La clave de envío ya fue utilizada con otras entradas.'); + + return EntryReservation::query()->where('batch_id', $batch->id)->with('ticket')->orderBy('id')->get(); + } + + $tenant = $user->tenant()->firstOrFail(); + $entry = CatalogItem::query()->forTenantCatalog($tenant)->where('slug', 'entrada') + ->lockForUpdate()->firstOrFail(); + $ids = array_column($rows, 'variant_id'); + $variants = $entry->variants()->whereKey($ids)->orderBy('id')->lockForUpdate()->get(); + $inventories = Inventory::query()->whereKey($variants->pluck('inventory_id')->filter()->unique()) + ->orderBy('id')->lockForUpdate()->get()->keyBy('id'); + $variants->load([ + 'eventDates', 'eventDate', + 'desfileEntryReservations' => fn ($query) => $query->lockForUpdate(), + ]); + foreach ($variants as $variant) { + $variant->setRelation('inventory', $inventories->get($variant->inventory_id)); + } + $entry->setRelation('variants', $variants); + $available = $entry->visibleVariants()->keyBy('id'); + $requirements = []; + $errors = []; + foreach ($rows as $index => $row) { + $variant = $available->get($row['variant_id']); + if ($variant === null || $variant->inventory === null) { + $errors["rows.{$index}.variant_id"] = $this->entryLabel($variants->firstWhere('id', $row['variant_id']), $index).': la entrada ya no está disponible.'; + + continue; + } + $requirements[$variant->inventory_id] = ($requirements[$variant->inventory_id] ?? 0) + 1; + } + if ($errors !== []) { + throw ValidationException::withMessages($errors); + } + $tracked = $entry->inventory_policy !== InventoryPolicy::Unlimited; + foreach ($requirements as $inventoryId => $quantity) { + if ($tracked && $inventories[$inventoryId]->availableStock() < $quantity) { + foreach ($rows as $index => $row) { + $variant = $available[$row['variant_id']]; + if ($variant->inventory_id === $inventoryId) { + $errors["rows.{$index}.variant_id"] = $this->entryLabel($variant, $index).': no hay stock suficiente para reservar las entradas seleccionadas.'; + } + } + } + } + if ($errors !== []) { + throw ValidationException::withMessages($errors); + } + + $batchId = DB::table('desfile_reservation_batches')->insertGetId([ + 'user_id' => $user->id, 'tenant_code' => $tenant->codigo, + 'idempotency_key' => $key, 'request_hash' => $hash, + 'created_at' => now(), 'updated_at' => now(), + ]); + foreach ($requirements as $inventoryId => $quantity) { + $inventories[$inventoryId]->reserveEntry($quantity, $tracked); + } + $reservations = collect(); + foreach ($rows as $index => $row) { + $variant = $available[$row['variant_id']]; + $payment = EntryReservationPaymentType::from($row['tipo_pago']); + try { + $ticket = $this->tickets->generate($entry, $user, 1, $variant->id)->sole(); + } catch (TicketGenerationException $exception) { + throw ValidationException::withMessages([ + "rows.{$index}.variant_id" => $this->entryLabel($variant, $index).': no se pudo emitir el ticket. '.$exception->getMessage(), + ]); + } + $reservation = EntryReservation::query()->create([ + 'batch_id' => $batchId, 'ticket_id' => $ticket->id, + 'variant_id' => $variant->id, 'inventory_id' => $variant->inventory_id, + 'fecha_reserva' => now(), 'tipo_pago' => $payment, + 'importe' => $payment === EntryReservationPaymentType::Free ? 0 : $variant->getPrice(), + ]); + $reservations->push($reservation->setRelation('ticket', $ticket)); + } + + return $reservations; + }, 3); + } + + private function entryLabel(?Variant $variant, int $index): string + { + if ($variant === null) { + return 'Entrada '.($index + 1); + } + + $values = $variant->selectionValues(); + + return collect(['tipo' => 'Tipo', 'sector' => 'Sector', 'fila' => 'Fila', 'asiento' => 'Asiento']) + ->map(fn (string $label, string $key): string => $label.': '.($values->get($key) ?? 'sin especificar')) + ->implode(', '); + } +} diff --git a/app/Domains/Ticketing/Desfile/routes/api.php b/app/Domains/Ticketing/Desfile/routes/api.php index 9d2429b..df2e545 100644 --- a/app/Domains/Ticketing/Desfile/routes/api.php +++ b/app/Domains/Ticketing/Desfile/routes/api.php @@ -1,8 +1,13 @@ middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.reservas']) + ->name('adminapp.desfile.entry-reservations.store'); + Route::prefix('v1/adminapp/tenant/desfile') ->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.entradas']) ->group(function (): void { diff --git a/tests/Feature/Desfile/EntryReservationServiceTest.php b/tests/Feature/Desfile/EntryReservationServiceTest.php new file mode 100644 index 0000000..58c4131 --- /dev/null +++ b/tests/Feature/Desfile/EntryReservationServiceTest.php @@ -0,0 +1,291 @@ +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'); + }); + Schema::create('item_attributes', function (Blueprint $table): void { + $table->id(); + $table->foreignId('attribute_id'); + $table->boolean('allow_multi_select')->default(false); + }); + 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(); + }); + (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(); + 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(['attribute_id' => $attributeId]); + 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]); + + 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_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_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_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()); + } +}