diff --git a/app/Domains/Ticketing/Ticket/Controllers/AdminApp/EntryReservationController.php b/app/Domains/Ticketing/Ticket/Controllers/AdminApp/EntryReservationController.php new file mode 100644 index 00000000..33883b42 --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Controllers/AdminApp/EntryReservationController.php @@ -0,0 +1,94 @@ +get( + $request->user()->tenant()->firstOrFail(), $request->user()->event_id, + )); + } + + public function index(IndexEntryReservationsRequest $request, EntryReservationService $service): AnonymousResourceCollection + { + return EntryReservationResource::collection( + $service->reservations($request->user(), $request->validated()), + ); + } + + public function downloadPdf( + ExportEntryReservationsRequest $request, + EntryReservationService $service, + EntryReservationPdfService $pdf, + ): Response { + $user = $request->user(); + + return $pdf->download( + $user->tenant()->firstOrFail(), + $service->reservationsForExport($user, $request->validated()), + $request->validated('timezone'), + ); + } + + public function downloadExcel( + ExportEntryReservationsRequest $request, + EntryReservationService $service, + EntryReservationExcelService $excel, + ): StreamedResponse { + $user = $request->user(); + + return $excel->download( + $user->tenant()->firstOrFail(), + $service->reservationsForExport($user, $request->validated()), + $request->validated('timezone'), + ); + } + + public function downloadTicketPdf( + IndexEntryReservationsRequest $request, + int $reservation, + EntryReservationService $service, + TicketPdfService $pdf, + ): Response { + $user = $request->user(); + + return $pdf->download( + $user->tenant()->firstOrFail(), + collect([$service->reservationTicket($user, $reservation)]), + ); + } + + public function store(StoreEntryReservationsRequest $request, EntryReservationService $service): AnonymousResourceCollection + { + return EntryReservationResource::collection($service->reserve( + $request->user(), $request->validated('idempotency_key'), $request->validated('rows'), + )); + } + + public function destroy( + IndexEntryReservationsRequest $request, + int $reservation, + EntryReservationService $service, + ): Response { + $service->cancel($request->user(), $reservation); + + return response()->noContent(); + } +} diff --git a/app/Domains/Ticketing/Ticket/Requests/ExportEntryReservationsRequest.php b/app/Domains/Ticketing/Ticket/Requests/ExportEntryReservationsRequest.php new file mode 100644 index 00000000..f9bbdff2 --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Requests/ExportEntryReservationsRequest.php @@ -0,0 +1,13 @@ + ['required', 'string', new ValidTimezone]]; + } +} diff --git a/app/Domains/Ticketing/Ticket/Requests/IndexEntryReservationsRequest.php b/app/Domains/Ticketing/Ticket/Requests/IndexEntryReservationsRequest.php new file mode 100644 index 00000000..0e848970 --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Requests/IndexEntryReservationsRequest.php @@ -0,0 +1,26 @@ +user()?->tenant_codigo === 'onticket'; + } + + public function rules(): array + { + return [ + 'catalog_item_id' => ['sometimes', 'nullable', 'integer', 'min:1'], + 'variant_id' => ['sometimes', 'nullable', 'integer', 'min:1'], + 'tipo_pago' => ['sometimes', 'nullable', Rule::enum(EntryReservationPaymentType::class)], + 'page' => ['sometimes', 'integer', 'min:1'], + 'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'], + ]; + } +} diff --git a/app/Domains/Ticketing/Ticket/Requests/StoreEntryReservationsRequest.php b/app/Domains/Ticketing/Ticket/Requests/StoreEntryReservationsRequest.php new file mode 100644 index 00000000..e5b2282f --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Requests/StoreEntryReservationsRequest.php @@ -0,0 +1,21 @@ + ['required', 'uuid'], + 'rows' => ['required', 'array', 'list', 'min:1', 'max:100'], + 'rows.*' => ['required', 'array:catalog_item_id,variant_id,tipo_pago'], + 'rows.*.catalog_item_id' => ['required', 'integer', 'min:1'], + 'rows.*.variant_id' => ['sometimes', 'nullable', 'integer', 'min:1'], + 'rows.*.tipo_pago' => ['required', Rule::enum(EntryReservationPaymentType::class)], + ]; + } +} diff --git a/app/Domains/Ticketing/Ticket/Resources/EntryReservationFormResource.php b/app/Domains/Ticketing/Ticket/Resources/EntryReservationFormResource.php new file mode 100644 index 00000000..6697a907 --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Resources/EntryReservationFormResource.php @@ -0,0 +1,14 @@ +resource; + } +} diff --git a/app/Domains/Ticketing/Ticket/Resources/EntryReservationResource.php b/app/Domains/Ticketing/Ticket/Resources/EntryReservationResource.php new file mode 100644 index 00000000..58c11168 --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Resources/EntryReservationResource.php @@ -0,0 +1,28 @@ + $this->id, + 'catalog_item_id' => $this->catalog_item_id, + 'variant_id' => $this->variant_id, + 'catalog_item' => ['id' => $this->catalog_item_id, 'name' => $this->catalogItem?->nombre], + 'variant' => $this->variant === null ? null : [ + 'id' => $this->variant_id, + 'label' => $this->variant->getSelectionLabel(), + ], + 'ticket_id' => $this->ticket_id, + 'fecha_reserva' => $this->fecha_reserva->toIso8601String(), + 'tipo_pago' => $this->tipo_pago->value, + 'tipo_pago_label' => $this->tipo_pago->label(), + 'importe' => $this->importe, + ]; + } +} diff --git a/app/Domains/Ticketing/Ticket/Services/EntryReservationExcelService.php b/app/Domains/Ticketing/Ticket/Services/EntryReservationExcelService.php new file mode 100644 index 00000000..8cf3164a --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Services/EntryReservationExcelService.php @@ -0,0 +1,89 @@ + $reservations */ + public function download(Tenant $tenant, Collection $reservations, string $timeZone): StreamedResponse + { + $generatedAt = now(); + $rows = $this->report->rows($reservations); + $spreadsheet = new Spreadsheet; + $spreadsheet->getProperties() + ->setCreator('Shopit') + ->setTitle('Reservas de tickets') + ->setSubject($tenant->nombre); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('Reservas'); + $sheet->fromArray([ + 'Ítem', + 'Variante', + 'ID', + 'Fecha', + 'Importe', + 'Pago', + ], null, 'A1'); + + foreach ($rows as $index => $reservation) { + $row = $index + 2; + foreach (['A' => 'item', 'B' => 'variant'] as $column => $key) { + $sheet->setCellValueExplicit("{$column}{$row}", $reservation[$key], DataType::TYPE_STRING); + } + $sheet->setCellValueExplicit( + "C{$row}", + $reservation['ticket_id'] === null ? '-' : (string) $reservation['ticket_id'], + DataType::TYPE_STRING, + ); + $sheet->setCellValue( + "D{$row}", + Date::dateTimeToExcel($reservation['fecha_reserva']->copy()->timezone($timeZone)), + ); + if ($reservation['importe'] !== null) { + $sheet->setCellValue("E{$row}", (float) $reservation['importe']); + } + $sheet->setCellValueExplicit("F{$row}", $reservation['pago'], DataType::TYPE_STRING); + } + + $lastRow = max(2, $rows->count() + 1); + $sheet->getStyle("D2:D{$lastRow}")->getNumberFormat()->setFormatCode('dd/mm/yyyy hh:mm'); + $sheet->getStyle("E2:E{$lastRow}")->getNumberFormat()->setFormatCode('$ #,##0.00'); + $sheet->getStyle('A1:F1')->applyFromArray([ + 'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']], + 'fill' => [ + 'fillType' => Fill::FILL_SOLID, + 'startColor' => ['rgb' => '26382E'], + ], + 'alignment' => ['vertical' => Alignment::VERTICAL_CENTER], + ]); + $sheet->getRowDimension(1)->setRowHeight(24); + $sheet->freezePane('A2'); + $sheet->setAutoFilter("A1:F{$lastRow}"); + foreach (['A' => 30, 'B' => 60, 'C' => 16, 'D' => 20, 'E' => 16, 'F' => 18] as $column => $width) { + $sheet->getColumnDimension($column)->setWidth($width); + } + + $filename = 'reservas_tickets_'.$tenant->codigo.'_' + .$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.xlsx'; + + return response()->streamDownload(function () use ($spreadsheet): void { + (new Xlsx($spreadsheet))->save('php://output'); + $spreadsheet->disconnectWorksheets(); + }, $filename, [ + 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ]); + } +} diff --git a/app/Domains/Ticketing/Ticket/Services/EntryReservationFormService.php b/app/Domains/Ticketing/Ticket/Services/EntryReservationFormService.php new file mode 100644 index 00000000..93492cdb --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Services/EntryReservationFormService.php @@ -0,0 +1,65 @@ +where('tenant_code', $tenant->codigo)->where('has_tickets', true) + ->when($eventId !== null, fn (Builder $query) => $query->where('event_id', $eventId)) + ->with([ + 'inventory', 'itemAttributes.attribute.options', + 'variants' => fn ($query) => $query->orderBy('id'), + 'variants.inventory', 'variants.definitions.itemAttribute.attribute.options', + 'variants.eventDates', 'variants.eventDate', + ])->orderBy('nombre')->orderBy('id')->get(); + + $filterItems = $items->map(fn (CatalogItem $item): array => [ + 'id' => $item->id, 'name' => $item->nombre, + 'variants' => $item->variants->map(function (Variant $variant) use ($item): array { + $variant->setRelation('catalogItem', $item); + + return ['id' => $variant->id, 'label' => $variant->getSelectionLabel()]; + })->values()->all(), + ])->values()->all(); + + $reservationEventId = $eventId ?? $tenant->active_event_id; + $available = $items->filter(fn (CatalogItem $item): bool => ! $item->isBundle() + && $item->isSaleOpen() + && ($reservationEventId === null || $item->event_id === $reservationEventId)) + ->map(function (CatalogItem $item): ?array { + $tracked = $item->inventory_policy !== InventoryPolicy::Unlimited; + $requiresVariant = $item->variants->isNotEmpty(); + $variants = $item->variants->filter(function (Variant $variant) use ($item, $tracked): bool { + $variant->setRelation('catalogItem', $item); + + return $variant->isSellable() + && (! $tracked || ($variant->inventory?->availableStock() ?? 0) > 0); + })->map(fn (Variant $variant): array => [ + 'id' => $variant->id, 'label' => $variant->getSelectionLabel(), + 'price' => $variant->getPrice(), + 'available_stock' => $tracked ? $variant->inventory->availableStock() : null, + ])->values()->all(); + if (($requiresVariant && $variants === []) + || (! $requiresVariant && $tracked && ($item->inventory?->availableStock() ?? 0) <= 0)) { + return null; + } + + return [ + 'id' => $item->id, 'name' => $item->nombre, 'price' => $item->getPrice(), + 'requires_variant' => $requiresVariant, 'variants' => $variants, + 'available_stock' => $tracked ? $item->inventory?->availableStock() : null, + ]; + })->filter()->values()->all(); + + return ['payment_types' => EntryReservationPaymentType::options(), 'items' => $available, 'filter_items' => $filterItems]; + } +} diff --git a/app/Domains/Ticketing/Ticket/Services/EntryReservationPdfService.php b/app/Domains/Ticketing/Ticket/Services/EntryReservationPdfService.php new file mode 100644 index 00000000..bf9c6d97 --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Services/EntryReservationPdfService.php @@ -0,0 +1,51 @@ + $reservations */ + public function download(Tenant $tenant, Collection $reservations, string $timeZone): Response + { + $generatedAt = now(); + $rows = $this->report->rows($reservations); + $pdf = Pdf::loadView('pdf.adminapp.entry-reservations', [ + 'tenant' => $tenant, + 'reservations' => $rows, + 'generatedAt' => $generatedAt, + 'timeZone' => $timeZone, + ])->setPaper('a4', 'landscape'); + + $this->addPageNumbers($pdf); + + return $pdf->download( + 'reservas_tickets_'.$tenant->codigo.'_' + .$generatedAt->copy()->timezone($timeZone)->format('Ymd_His').'.pdf' + ); + } + + private function addPageNumbers(DomPdf $pdf): void + { + $pdf->render(); + $domPdf = $pdf->getDomPDF(); + $font = $domPdf->getFontMetrics()->getFont('DejaVu Sans'); + + $domPdf->getCanvas()->page_text( + 385, + 575, + 'Página {PAGE_NUM} de {PAGE_COUNT}', + $font, + 7, + [0.48, 0.52, 0.49], + ); + } +} diff --git a/app/Domains/Ticketing/Ticket/Services/EntryReservationReportService.php b/app/Domains/Ticketing/Ticket/Services/EntryReservationReportService.php new file mode 100644 index 00000000..61dc8ca6 --- /dev/null +++ b/app/Domains/Ticketing/Ticket/Services/EntryReservationReportService.php @@ -0,0 +1,21 @@ +values()->map(fn (EntryReservation $reservation): array => [ + 'item' => $reservation->catalogItem?->nombre ?? '-', + 'variant' => $reservation->variant?->getSelectionLabel() ?? 'Sin variante', + 'ticket_id' => $reservation->ticket_id, + 'fecha_reserva' => $reservation->fecha_reserva, + 'importe' => $reservation->importe, + 'pago' => $reservation->tipo_pago->label(), + ]); + } +} diff --git a/app/Domains/Ticketing/Ticket/Services/EntryReservationService.php b/app/Domains/Ticketing/Ticket/Services/EntryReservationService.php index 3b64572f..ae6f1675 100644 --- a/app/Domains/Ticketing/Ticket/Services/EntryReservationService.php +++ b/app/Domains/Ticketing/Ticket/Services/EntryReservationService.php @@ -23,6 +23,14 @@ use Illuminate\Validation\ValidationException; /** Application workflow for one ticket per selected catalog item / variant. */ class EntryReservationService { + private const SELECTION_RELATIONS = [ + 'catalogItem', + 'variant.catalogItem.itemAttributes.attribute.options', + 'variant.definitions.itemAttribute.attribute.options', + 'variant.eventDates', + 'variant.eventDate', + ]; + public function __construct(private readonly TicketGeneratorService $tickets) {} /** @@ -114,10 +122,21 @@ class EntryReservationService abort_unless($batch->tenant_code === $tenant->codigo && $this->matchesBatch($batch, $rows, $hash), 409, 'La clave de envío ya fue utilizada con otra selección.'); - return $batch->reservations()->with(['catalogItem', 'variant', 'ticket'])->orderBy('id')->get(); + // A scope change must not expose any part of a previously submitted batch. + if ($user->event_id !== null) { + abort_if($batch->reservations()->withTrashed() + ->whereDoesntHave('catalogItem', fn (Builder $query) => $query + ->where('tenant_code', $user->tenant_codigo) + ->where('event_id', $user->event_id)) + ->exists(), 403); + } + + return $batch->reservations()->with([...self::SELECTION_RELATIONS, 'ticket'])->orderBy('id')->get(); } - $items = CatalogItem::query()->forTenantCatalog($tenant) + $eventId = $user->event_id ?? $tenant->active_event_id; + $items = CatalogItem::query()->where('tenant_code', $tenant->codigo) + ->when($eventId !== null, fn (Builder $query) => $query->where('event_id', $eventId)) ->whereKey(array_column($rows, 'catalog_item_id'))->orderBy('id')->lockForUpdate()->get()->keyBy('id'); $variants = Variant::query()->whereIn('catalog_item_id', $items->keys()) ->whereKey(array_filter(array_column($rows, 'variant_id'))) @@ -229,7 +248,7 @@ class EntryReservationService ->setRelation('catalogItem', $item)->setRelation('variant', $variant)); } - return $reservations; + return $reservations->loadMissing(self::SELECTION_RELATIONS); }, 3); } @@ -239,11 +258,12 @@ class EntryReservationService abort_unless($user->tenant_codigo !== null && $user->tenant_codigo !== '', 403); return EntryReservation::query() - ->whereHas('catalogItem', fn (Builder $query) => $query->where('tenant_code', $user->tenant_codigo)) + ->whereHas('catalogItem', fn (Builder $query) => $query->where('tenant_code', $user->tenant_codigo) + ->when($user->event_id !== null, fn (Builder $query) => $query->where('event_id', $user->event_id))) ->when($filters['catalog_item_id'] ?? null, fn (Builder $query, int $id) => $query->where('catalog_item_id', $id)) ->when($filters['variant_id'] ?? null, fn (Builder $query, int $id) => $query->where('variant_id', $id)) ->when($filters['tipo_pago'] ?? null, fn (Builder $query, string $type) => $query->where('tipo_pago', $type)) - ->with(['catalogItem', 'variant']) + ->with(self::SELECTION_RELATIONS) ->orderByDesc('fecha_reserva')->orderByDesc('id'); } diff --git a/app/Domains/Ticketing/Ticket/routes/adminapp.php b/app/Domains/Ticketing/Ticket/routes/adminapp.php index b785612a..4b29034c 100644 --- a/app/Domains/Ticketing/Ticket/routes/adminapp.php +++ b/app/Domains/Ticketing/Ticket/routes/adminapp.php @@ -1,11 +1,24 @@ middleware(['auth:sanctum', 'adminapp.tenant']) ->group(function (): void { + Route::prefix('entry-reservations')->middleware('tenant.menu:adminapp.ticket-reservations') + ->group(function (): void { + Route::get('form', [EntryReservationController::class, 'form'])->name('adminapp.entry-reservations.form'); + Route::get('/', [EntryReservationController::class, 'index'])->name('adminapp.entry-reservations.index'); + Route::post('/', [EntryReservationController::class, 'store'])->name('adminapp.entry-reservations.store'); + Route::get('pdf', [EntryReservationController::class, 'downloadPdf'])->name('adminapp.entry-reservations.pdf'); + Route::get('excel', [EntryReservationController::class, 'downloadExcel'])->name('adminapp.entry-reservations.excel'); + Route::get('{reservation}/ticket/pdf', [EntryReservationController::class, 'downloadTicketPdf']) + ->whereNumber('reservation')->name('adminapp.entry-reservations.ticket.pdf'); + Route::delete('{reservation}', [EntryReservationController::class, 'destroy']) + ->whereNumber('reservation')->name('adminapp.entry-reservations.destroy'); + }); Route::get('tickets', [TicketController::class, 'index']) ->middleware('tenant.menu:adminapp.tickets') ->name('adminapp.tickets.index'); diff --git a/database/migrations/2026_10_02_010000_add_ticket_reservations_adminapp_menu.php b/database/migrations/2026_10_02_010000_add_ticket_reservations_adminapp_menu.php new file mode 100644 index 00000000..0edcecbd --- /dev/null +++ b/database/migrations/2026_10_02_010000_add_ticket_reservations_adminapp_menu.php @@ -0,0 +1,82 @@ +where('code', 'main.adminapp')->exists()) { + // Reference data is added by seeders on fresh installations. + return; + } + + $now = now(); + + DB::transaction(function () use ($now): void { + DB::table('menues')->updateOrInsert( + ['code' => self::MENU_CODE], + [ + 'label' => 'Reserva de Tickets', + 'parent_menu_code' => 'main.adminapp', + 'content_type' => 'dynamic', + 'static_content_schema' => null, + 'route' => '/admin/ticket-reservations', + 'created_at' => $now, + 'updated_at' => $now, + ], + ); + + DB::table('tenants_menues') + ->where('menu_code', self::MENU_CODE) + ->where('tenant_code', '!=', self::TENANT_CODE) + ->delete(); + + if (DB::table('tenants')->where('codigo', self::TENANT_CODE)->exists()) { + DB::table('tenants_menues')->updateOrInsert( + [ + 'tenant_code' => self::TENANT_CODE, + 'menu_code' => self::MENU_CODE, + ], + [ + 'static_content' => null, + 'created_at' => $now, + 'updated_at' => $now, + ], + ); + } + + DB::table('roles') + ->whereIn('codigo', ['admin', 'adminapp']) + ->pluck('codigo') + ->each(function (string $roleCode): void { + DB::table('roles_menues')->updateOrInsert([ + 'rol_codigo' => $roleCode, + 'menu_codigo' => self::MENU_CODE, + ]); + }); + }); + } + + public function down(): void + { + DB::transaction(function (): void { + DB::table('tenants_menues') + ->where('menu_code', self::MENU_CODE) + ->delete(); + + DB::table('roles_menues') + ->where('menu_codigo', self::MENU_CODE) + ->delete(); + + DB::table('menues') + ->where('code', self::MENU_CODE) + ->delete(); + }); + } +}; diff --git a/database/seeders/MenuSeeder.php b/database/seeders/MenuSeeder.php index 25a61dcb..e5bf7197 100644 --- a/database/seeders/MenuSeeder.php +++ b/database/seeders/MenuSeeder.php @@ -100,6 +100,12 @@ class MenuSeeder extends Seeder 'parent_menu_code' => 'main.adminapp', 'route' => '/admin/tickets', ], + [ + 'code' => 'adminapp.ticket-reservations', + 'label' => 'Reserva de Tickets', + 'parent_menu_code' => 'main.adminapp', + 'route' => '/admin/ticket-reservations', + ], [ 'code' => 'adminapp.fiesta-futbol-infantil.entradas', 'label' => 'Entradas', @@ -318,6 +324,7 @@ class MenuSeeder extends Seeder 'adminapp.desfile.reservas', ]; $onTicketMenuCodes = [ + 'adminapp.ticket-reservations', 'event.index', 'event.category', 'event.detail', diff --git a/resources/views/pdf/adminapp/entry-reservations.blade.php b/resources/views/pdf/adminapp/entry-reservations.blade.php new file mode 100644 index 00000000..eb6e41b6 --- /dev/null +++ b/resources/views/pdf/adminapp/entry-reservations.blade.php @@ -0,0 +1,57 @@ + + + + + + + +

Reservas de tickets

+

{{ $tenant->nombre }} · Generado el {{ $generatedAt->copy()->timezone($timeZone)->format('d/m/Y H:i') }}

+ +
+ Reservas incluidas: {{ $reservations->count() }} +
+ + + + + + + + + + + + + + @forelse ($reservations as $reservation) + + + + + + + + + @empty + + @endforelse + +
ÍtemVarianteIDFechaImportePago
{{ $reservation['item'] }}{{ $reservation['variant'] }}{{ $reservation['ticket_id'] ?? '-' }}{{ $reservation['fecha_reserva']->copy()->timezone($timeZone)->format('d/m/Y H:i') }}{{ $reservation['importe'] === null ? '-' : '$'.number_format((float) $reservation['importe'], 2, ',', '.') }}{{ $reservation['pago'] }}
No hay reservas para los criterios seleccionados.
+ + diff --git a/tests/Feature/Seeders/MenuSeederTest.php b/tests/Feature/Seeders/MenuSeederTest.php index 10d323c6..11c0b5f0 100644 --- a/tests/Feature/Seeders/MenuSeederTest.php +++ b/tests/Feature/Seeders/MenuSeederTest.php @@ -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() ); diff --git a/tests/Feature/Ticket/EntryReservationControllerTest.php b/tests/Feature/Ticket/EntryReservationControllerTest.php new file mode 100644 index 00000000..59501b33 --- /dev/null +++ b/tests/Feature/Ticket/EntryReservationControllerTest.php @@ -0,0 +1,313 @@ +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); + } +} diff --git a/tests/Feature/Ticket/EntryReservationServiceTest.php b/tests/Feature/Ticket/EntryReservationServiceTest.php index 7f73c3d2..1173d507 100644 --- a/tests/Feature/Ticket/EntryReservationServiceTest.php +++ b/tests/Feature/Ticket/EntryReservationServiceTest.php @@ -11,162 +11,23 @@ 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\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Schema; 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(); - // 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('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' => 'ticket_shop']); - DB::table('users')->insert(['id' => 1, 'tenant_codigo' => 'ticket_shop']); - DB::table('catalog_items')->insert([ - 'id' => 1, 'tenant_code' => 'ticket_shop', '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' => 'ticket_shop', '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' => 'ticket_shop', '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, - ]); - } - } + $this->createTicketReservationSchema(); } private function service(bool $failSecond = false): EntryReservationService diff --git a/tests/Support/CreatesTicketReservationSchema.php b/tests/Support/CreatesTicketReservationSchema.php new file mode 100644 index 00000000..3d7f2724 --- /dev/null +++ b/tests/Support/CreatesTicketReservationSchema.php @@ -0,0 +1,156 @@ +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, + ]); + } + } + } +}