feat(ticketing): add entry reservations management for admin app

- Introduced new routes for entry reservations in admin app, including form, index, store, and download functionalities.
- Created a migration to add the "Reserva de Tickets" menu item to the admin app.
- Updated MenuSeeder to include the new menu item for ticket reservations.
- Developed a PDF view for entry reservations.
- Implemented tests for the EntryReservationController and EntryReservationService to ensure proper functionality and access control.
- Refactored test setup to use a dedicated schema creation trait for better isolation and maintainability.
This commit is contained in:
2026-10-02 12:20:25 -03:00
parent f10237eb1f
commit 45e92602ed
19 changed files with 1081 additions and 148 deletions

View File

@@ -0,0 +1,94 @@
<?php
namespace App\Domains\Ticketing\Ticket\Controllers\AdminApp;
use App\Domains\Ticketing\Ticket\Requests\ExportEntryReservationsRequest;
use App\Domains\Ticketing\Ticket\Requests\IndexEntryReservationsRequest;
use App\Domains\Ticketing\Ticket\Requests\StoreEntryReservationsRequest;
use App\Domains\Ticketing\Ticket\Resources\EntryReservationFormResource;
use App\Domains\Ticketing\Ticket\Resources\EntryReservationResource;
use App\Domains\Ticketing\Ticket\Services\EntryReservationExcelService;
use App\Domains\Ticketing\Ticket\Services\EntryReservationFormService;
use App\Domains\Ticketing\Ticket\Services\EntryReservationPdfService;
use App\Domains\Ticketing\Ticket\Services\EntryReservationService;
use App\Domains\Ticketing\Ticket\Services\TicketPdfService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class EntryReservationController extends Controller
{
public function form(IndexEntryReservationsRequest $request, EntryReservationFormService $service): EntryReservationFormResource
{
return new EntryReservationFormResource($service->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();
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace App\Domains\Ticketing\Ticket\Requests;
use App\Shared\Rules\ValidTimezone;
class ExportEntryReservationsRequest extends IndexEntryReservationsRequest
{
public function rules(): array
{
return [...parent::rules(), 'timezone' => ['required', 'string', new ValidTimezone]];
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace App\Domains\Ticketing\Ticket\Requests;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class IndexEntryReservationsRequest extends FormRequest
{
public function authorize(): bool
{
return $this->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'],
];
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Domains\Ticketing\Ticket\Requests;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
use Illuminate\Validation\Rule;
class StoreEntryReservationsRequest extends IndexEntryReservationsRequest
{
public function rules(): array
{
return [
'idempotency_key' => ['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)],
];
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace App\Domains\Ticketing\Ticket\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class EntryReservationFormResource extends JsonResource
{
public function toArray(Request $request): array
{
return $this->resource;
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Domains\Ticketing\Ticket\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class EntryReservationResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $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,
];
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace App\Domains\Ticketing\Ticket\Services;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use Illuminate\Support\Collection;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\HttpFoundation\StreamedResponse;
class EntryReservationExcelService
{
public function __construct(private readonly EntryReservationReportService $report) {}
/** @param Collection<int, EntryReservation> $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',
]);
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace App\Domains\Ticketing\Ticket\Services;
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
use App\Domains\Commerce\Catalog\Models\CatalogItem;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
use Illuminate\Database\Eloquent\Builder;
class EntryReservationFormService
{
public function get(Tenant $tenant, ?int $eventId = null): array
{
$items = CatalogItem::query()->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];
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Domains\Ticketing\Ticket\Services;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use Barryvdh\DomPDF\Facade\Pdf;
use Barryvdh\DomPDF\PDF as DomPdf;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
class EntryReservationPdfService
{
public function __construct(private readonly EntryReservationReportService $report) {}
/** @param Collection<int, EntryReservation> $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],
);
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Domains\Ticketing\Ticket\Services;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use Illuminate\Support\Collection;
class EntryReservationReportService
{
public function rows(Collection $reservations): Collection
{
return $reservations->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(),
]);
}
}

View File

@@ -23,6 +23,14 @@ use Illuminate\Validation\ValidationException;
/** Application workflow for one ticket per selected catalog item / variant. */ /** Application workflow for one ticket per selected catalog item / variant. */
class EntryReservationService 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) {} 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), 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.'); 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'); ->whereKey(array_column($rows, 'catalog_item_id'))->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$variants = Variant::query()->whereIn('catalog_item_id', $items->keys()) $variants = Variant::query()->whereIn('catalog_item_id', $items->keys())
->whereKey(array_filter(array_column($rows, 'variant_id'))) ->whereKey(array_filter(array_column($rows, 'variant_id')))
@@ -229,7 +248,7 @@ class EntryReservationService
->setRelation('catalogItem', $item)->setRelation('variant', $variant)); ->setRelation('catalogItem', $item)->setRelation('variant', $variant));
} }
return $reservations; return $reservations->loadMissing(self::SELECTION_RELATIONS);
}, 3); }, 3);
} }
@@ -239,11 +258,12 @@ class EntryReservationService
abort_unless($user->tenant_codigo !== null && $user->tenant_codigo !== '', 403); abort_unless($user->tenant_codigo !== null && $user->tenant_codigo !== '', 403);
return EntryReservation::query() 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['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['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)) ->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'); ->orderByDesc('fecha_reserva')->orderByDesc('id');
} }

View File

@@ -1,11 +1,24 @@
<?php <?php
use App\Domains\Ticketing\Ticket\Controllers\AdminApp\EntryReservationController;
use App\Domains\Ticketing\Ticket\Controllers\AdminApp\TicketController; use App\Domains\Ticketing\Ticket\Controllers\AdminApp\TicketController;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant') Route::prefix('v1/adminapp/tenant')
->middleware(['auth:sanctum', 'adminapp.tenant']) ->middleware(['auth:sanctum', 'adminapp.tenant'])
->group(function (): void { ->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']) Route::get('tickets', [TicketController::class, 'index'])
->middleware('tenant.menu:adminapp.tickets') ->middleware('tenant.menu:adminapp.tickets')
->name('adminapp.tickets.index'); ->name('adminapp.tickets.index');

View File

@@ -0,0 +1,82 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
private const MENU_CODE = 'adminapp.ticket-reservations';
private const TENANT_CODE = 'onticket';
public function up(): void
{
if (! DB::table('menues')->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();
});
}
};

View File

@@ -100,6 +100,12 @@ class MenuSeeder extends Seeder
'parent_menu_code' => 'main.adminapp', 'parent_menu_code' => 'main.adminapp',
'route' => '/admin/tickets', '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', 'code' => 'adminapp.fiesta-futbol-infantil.entradas',
'label' => 'Entradas', 'label' => 'Entradas',
@@ -318,6 +324,7 @@ class MenuSeeder extends Seeder
'adminapp.desfile.reservas', 'adminapp.desfile.reservas',
]; ];
$onTicketMenuCodes = [ $onTicketMenuCodes = [
'adminapp.ticket-reservations',
'event.index', 'event.index',
'event.category', 'event.category',
'event.detail', 'event.detail',

View File

@@ -0,0 +1,57 @@
<!doctype html>
<html lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
@page { margin: 28px 34px 58px; }
body { color: #17211b; font-family: DejaVu Sans, sans-serif; font-size: 9px; margin: 0; }
h1 { font-size: 21px; margin: 0 0 3px; }
.subtitle { color: #66736b; margin: 0 0 18px; }
.summary { background: #eef5f1; border-left: 4px solid #198754; margin-bottom: 16px; padding: 9px 12px; }
.summary strong { font-size: 13px; }
table { border-collapse: collapse; width: 100%; }
thead { display: table-header-group; }
tr { page-break-inside: avoid; }
th { background: #26382e; color: #fff; font-size: 8px; letter-spacing: .4px; padding: 7px 6px; text-align: left; text-transform: uppercase; }
td { border-bottom: 1px solid #dfe7e2; padding: 7px 6px; vertical-align: top; }
tbody tr:nth-child(even) { background: #f7f9f8; }
.number { text-align: right; }
.empty { color: #66736b; padding: 24px; text-align: center; }
</style>
</head>
<body>
<h1>Reservas de tickets</h1>
<p class="subtitle">{{ $tenant->nombre }} · Generado el {{ $generatedAt->copy()->timezone($timeZone)->format('d/m/Y H:i') }}</p>
<div class="summary">
Reservas incluidas: <strong>{{ $reservations->count() }}</strong>
</div>
<table>
<thead>
<tr>
<th>Ítem</th>
<th>Variante</th>
<th>ID</th>
<th>Fecha</th>
<th class="number">Importe</th>
<th>Pago</th>
</tr>
</thead>
<tbody>
@forelse ($reservations as $reservation)
<tr>
<td>{{ $reservation['item'] }}</td>
<td>{{ $reservation['variant'] }}</td>
<td>{{ $reservation['ticket_id'] ?? '-' }}</td>
<td>{{ $reservation['fecha_reserva']->copy()->timezone($timeZone)->format('d/m/Y H:i') }}</td>
<td class="number">{{ $reservation['importe'] === null ? '-' : '$'.number_format((float) $reservation['importe'], 2, ',', '.') }}</td>
<td>{{ $reservation['pago'] }}</td>
</tr>
@empty
<tr><td class="empty" colspan="6">No hay reservas para los criterios seleccionados.</td></tr>
@endforelse
</tbody>
</table>
</body>
</html>

View File

@@ -54,6 +54,8 @@ class MenuSeederTest extends TestCase
...$expectedMenus, ...$expectedMenus,
...$fiestaCategoryMenus, ...$fiestaCategoryMenus,
'adminapp.desfile.entradas' => ['Entradas', '/admin/desfile/entradas'], '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(), ]))->sort()->values()->all(),
$adminApp->children->pluck('code')->sort()->values()->all() $adminApp->children->pluck('code')->sort()->values()->all()
); );

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

@@ -11,162 +11,23 @@ use App\Domains\Ticketing\Ticket\Services\ResolvedTicketValidity;
use App\Domains\Ticketing\Ticket\Services\TicketGeneratorService; use App\Domains\Ticketing\Ticket\Services\TicketGeneratorService;
use App\Domains\Ticketing\Ticket\Services\TicketValidityResolver; use App\Domains\Ticketing\Ticket\Services\TicketValidityResolver;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException; use Illuminate\Validation\ValidationException;
use Mockery; use Mockery;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\Support\CreatesTicketReservationSchema;
use Tests\TestCase; use Tests\TestCase;
/** Uses real transactions on the guarded SQLite :memory: connection. */ /** Uses real transactions on the guarded SQLite :memory: connection. */
class EntryReservationServiceTest extends TestCase class EntryReservationServiceTest extends TestCase
{ {
use CreatesTicketReservationSchema;
protected function setUp(): void protected function setUp(): void
{ {
parent::setUp(); parent::setUp();
// Minimal domain schema isolates this workflow from unrelated legacy migrations. $this->createTicketReservationSchema();
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,
]);
}
}
} }
private function service(bool $failSecond = false): EntryReservationService private function service(bool $failSecond = false): EntryReservationService

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,
]);
}
}
}
}