feat(ticket): implement DesfileEntryReservationController and related services for ticket reservations

This commit is contained in:
2026-10-02 11:50:47 -03:00
parent ab5bc43760
commit f10237eb1f
9 changed files with 365 additions and 264 deletions

View File

@@ -6,18 +6,18 @@ use App\Domains\Ticketing\Desfile\Requests\ExportEntryReservationsRequest;
use App\Domains\Ticketing\Desfile\Requests\IndexEntryReservationsRequest;
use App\Domains\Ticketing\Desfile\Requests\StoreEntryReservationsRequest;
use App\Domains\Ticketing\Desfile\Resources\EntryReservationResource;
use App\Domains\Ticketing\Desfile\Services\DesfileEntryReservationService;
use App\Domains\Ticketing\Desfile\Services\EntryReservationExcelService;
use App\Domains\Ticketing\Desfile\Services\EntryReservationPdfService;
use App\Domains\Ticketing\Desfile\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
class DesfileEntryReservationController extends Controller
{
public function index(IndexEntryReservationsRequest $request, EntryReservationService $service): AnonymousResourceCollection
public function index(IndexEntryReservationsRequest $request, DesfileEntryReservationService $service): AnonymousResourceCollection
{
return EntryReservationResource::collection(
$service->reservations($request->user(), $request->validated()),
@@ -26,7 +26,7 @@ class EntryReservationController extends Controller
public function downloadPdf(
ExportEntryReservationsRequest $request,
EntryReservationService $service,
DesfileEntryReservationService $service,
EntryReservationPdfService $pdf,
): Response {
$user = $request->user();
@@ -40,7 +40,7 @@ class EntryReservationController extends Controller
public function downloadExcel(
ExportEntryReservationsRequest $request,
EntryReservationService $service,
DesfileEntryReservationService $service,
EntryReservationExcelService $excel,
): StreamedResponse {
$user = $request->user();
@@ -55,7 +55,7 @@ class EntryReservationController extends Controller
public function downloadTicketPdf(
IndexEntryReservationsRequest $request,
int $reservation,
EntryReservationService $service,
DesfileEntryReservationService $service,
TicketPdfService $pdf,
): Response {
$user = $request->user();
@@ -66,7 +66,7 @@ class EntryReservationController extends Controller
);
}
public function store(StoreEntryReservationsRequest $request, EntryReservationService $service): AnonymousResourceCollection
public function store(StoreEntryReservationsRequest $request, DesfileEntryReservationService $service): AnonymousResourceCollection
{
return EntryReservationResource::collection($service->reserve(
$request->user(), $request->validated('idempotency_key'), $request->validated('rows'),
@@ -76,7 +76,7 @@ class EntryReservationController extends Controller
public function destroy(
IndexEntryReservationsRequest $request,
int $reservation,
EntryReservationService $service,
DesfileEntryReservationService $service,
): Response {
$service->cancel($request->user(), $reservation);

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Domains\Ticketing\Desfile\Services;
use App\Domains\Ticketing\Ticket\Services\EntryReservationPolicy;
use Illuminate\Validation\ValidationException;
class DesfileEntryReservationPolicy implements EntryReservationPolicy
{
public function validate(array $selections): void
{
$errors = [];
$seen = [];
foreach ($selections as $index => $selection) {
$variant = $selection['variant'];
if ($variant === null || $selection['inventory'] === null
|| isset($seen[$variant->id])
|| $variant->entryReservations()->lockForUpdate()->get()->isNotEmpty()) {
$errors["rows.{$index}.variant_id"] = 'La entrada ya no está disponible.';
}
if ($variant !== null) {
$seen[$variant->id] = true;
}
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
}
}

View File

@@ -0,0 +1,123 @@
<?php
namespace App\Domains\Ticketing\Desfile\Services;
use App\Domains\Commerce\Catalog\Models\CatalogItem;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Services\EntryReservationService as TicketEntryReservationService;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Validation\ValidationException;
/** Adapts the Desfile API and seat rules to the catalog-based reservation workflow. */
class DesfileEntryReservationService
{
private const SELECTION_RELATIONS = [
'variant.catalogItem.itemAttributes.attribute.options',
'variant.definitions.itemAttribute.attribute.options',
'variant.eventDates',
'variant.eventDate',
];
public function __construct(
private readonly TicketEntryReservationService $reservations,
private readonly DesfileEntryReservationPolicy $policy,
) {}
/**
* @param array{tipo_pago?: string|null, page?: int, per_page?: int} $filters
* @return LengthAwarePaginator<EntryReservation>
*/
public function reservations(User $user, array $filters = []): LengthAwarePaginator
{
$result = $this->reservations->reservations($user, [
...$filters, 'catalog_item_id' => $this->entryId($user),
]);
$result->getCollection()->loadMissing(self::SELECTION_RELATIONS);
return $result;
}
/**
* @param array{tipo_pago?: string|null} $filters
* @return Collection<int, EntryReservation>
*/
public function reservationsForExport(User $user, array $filters = []): Collection
{
return $this->reservations->reservationsForExport($user, [
...$filters, 'catalog_item_id' => $this->entryId($user),
])->loadMissing(self::SELECTION_RELATIONS);
}
public function reservationTicket(User $user, int $reservationId): Ticket
{
return $this->reservations->reservationTicket($user, $reservationId, $this->entryId($user));
}
public function cancel(User $user, int $reservationId): void
{
$this->reservations->cancel($user, $reservationId, $this->entryId($user));
}
/** @param list<array{variant_id: int, tipo_pago: string}> $rows */
public function reserve(User $user, string $key, array $rows): Collection
{
$this->authorize($user);
$entry = CatalogItem::query()->where('tenant_code', $user->tenant_codigo)
->where('slug', 'entrada')->firstOrFail();
$catalogRows = array_map(fn (array $row): array => [
...$row, 'catalog_item_id' => $entry->id,
], $rows);
try {
return $this->reservations->reserve($user, $key, $catalogRows, $this->policy)
->loadMissing(self::SELECTION_RELATIONS);
} catch (ValidationException $exception) {
// Keep the row fields used by the form and describe the selected seat.
$variants = $entry->variants()->whereKey(array_column($rows, 'variant_id'))
->with(['definitions.itemAttribute.attribute.options'])->get()->keyBy('id');
$errors = [];
foreach ($exception->errors() as $field => $messages) {
if (preg_match('/^rows\.(\d+)\.variant_id$/', $field, $match)) {
$index = (int) $match[1];
$label = $this->entryLabel($variants->get($rows[$index]['variant_id'] ?? null), $index);
$messages = array_map(fn (string $message): string => $label.': '.$message, $messages);
}
$errors[$field] = $messages;
}
throw ValidationException::withMessages($errors);
}
}
private function authorize(User $user): void
{
abort_unless($user->tenant_codigo === 'desfile_pura_tendencia', 403);
}
private function entryId(User $user): int
{
$this->authorize($user);
// Historical reservations remain accessible when the active event changes.
// A missing entry must not remove the catalog filter from the generic query.
return CatalogItem::query()->where('tenant_code', $user->tenant_codigo)
->where('slug', 'entrada')->value('id') ?? -1;
}
private function entryLabel(?Variant $variant, int $index): string
{
if ($variant === null) {
return 'Entrada '.($index + 1);
}
$values = $variant->selectionValues();
return collect(['tipo' => 'Tipo', 'sector' => 'Sector', 'fila' => 'Fila', 'asiento' => 'Asiento'])
->map(fn (string $label, string $key): string => $label.': '.($values->get($key) ?? 'sin especificar'))
->implode(', ');
}
}

View File

@@ -1,241 +0,0 @@
<?php
namespace App\Domains\Ticketing\Desfile\Services;
use App\Domains\Commerce\Catalog\Enums\InventoryPolicy;
use App\Domains\Commerce\Catalog\Models\CatalogItem;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Ticket\Exceptions\TicketGenerationException;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\ReservationBatch;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Domains\Ticketing\Ticket\Services\TicketGeneratorService;
use App\Domains\Ticketing\Ticket\Services\TicketPresentationResolver;
use App\Domains\Ticketing\Ticket\Services\TicketValidityResolver;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class EntryReservationService
{
public function __construct(private readonly TicketGeneratorService $tickets) {}
/**
* @param array{tipo_pago?: string|null, page?: int, per_page?: int} $filters
* @return LengthAwarePaginator<EntryReservation>
*/
public function reservations(User $user, array $filters = []): LengthAwarePaginator
{
abort_unless($user->tenant_codigo === 'desfile_pura_tendencia', 403);
return $this->reservationsQuery($user, $filters)
->paginate(
perPage: $filters['per_page'] ?? 15,
pageName: 'page',
page: $filters['page'] ?? 1,
)
->withQueryString();
}
/**
* @param array{tipo_pago?: string|null} $filters
* @return Collection<int, EntryReservation>
*/
public function reservationsForExport(User $user, array $filters = []): Collection
{
abort_unless($user->tenant_codigo === 'desfile_pura_tendencia', 403);
return $this->reservationsQuery($user, $filters)->get();
}
public function reservationTicket(User $user, int $reservationId): Ticket
{
abort_unless($user->tenant_codigo === 'desfile_pura_tendencia', 403);
$reservation = EntryReservation::query()
->whereKey($reservationId)
->whereNotNull('ticket_id')
->whereHas('variant.catalogItem', fn (Builder $query): Builder => $query
->where('tenant_code', $user->tenant_codigo)
->where('slug', 'entrada'))
->with(['ticket' => fn ($query) => $query->with([
...TicketValidityResolver::RELATIONS,
...TicketPresentationResolver::RELATIONS,
])])
->firstOrFail();
return $reservation->ticket;
}
public function cancel(User $user, int $reservationId): void
{
abort_unless($user->tenant_codigo === 'desfile_pura_tendencia', 403);
DB::transaction(function () use ($user, $reservationId): void {
$reservation = EntryReservation::query()
->whereKey($reservationId)
->whereHas('variant.catalogItem', fn (Builder $query): Builder => $query
->where('tenant_code', $user->tenant_codigo)
->where('slug', 'entrada'))
->lockForUpdate()
->firstOrFail();
if ($reservation->ticket_id !== null) {
$ticket = Ticket::query()->lockForUpdate()->findOrFail($reservation->ticket_id);
if (! $ticket->can_cancel()) {
throw ValidationException::withMessages([
'status' => 'El ticket debe estar activo para poder cancelar la reserva.',
]);
}
$ticket->markAsCancelled();
$ticket->save();
}
if ($reservation->inventory_id !== null) {
$inventory = Inventory::query()->lockForUpdate()->findOrFail($reservation->inventory_id);
$inventory->releaseEntry(1);
}
$reservation->delete();
}, 3);
}
/** @param array{tipo_pago?: string|null} $filters */
private function reservationsQuery(User $user, array $filters = []): Builder
{
return EntryReservation::query()
->whereHas('variant.catalogItem', fn (Builder $query): Builder => $query
->where('tenant_code', $user->tenant_codigo)
->where('slug', 'entrada'))
->when(
$filters['tipo_pago'] ?? null,
fn (Builder $query, string $paymentType): Builder => $query->where('tipo_pago', $paymentType),
)
->with([
'variant.catalogItem.itemAttributes.attribute.options',
'variant.definitions.itemAttribute.attribute.options',
'variant.eventDates',
'variant.eventDate',
])
->orderByDesc('fecha_reserva')
->orderByDesc('id');
}
/** @param list<array{variant_id: int, tipo_pago: string}> $rows */
public function reserve(User $user, string $key, array $rows): Collection
{
abort_unless($user->tenant_codigo === 'desfile_pura_tendencia', 403);
$normalized = collect($rows)->map(fn (array $row): array => [
'variant_id' => (int) $row['variant_id'], 'tipo_pago' => $row['tipo_pago'],
])->sortBy('variant_id')->values()->all();
$hash = hash('sha256', json_encode($normalized, JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($user, $key, $rows, $hash): Collection {
// Serialize retries by the same administrator, including the first insert.
User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail();
$batch = ReservationBatch::query()
->where('user_id', $user->id)->where('idempotency_key', $key)->lockForUpdate()->first();
if ($batch !== null) {
abort_unless($batch->tenant_code === $user->tenant_codigo && hash_equals($batch->request_hash, $hash), 409,
'La clave de envío ya fue utilizada con otras entradas.');
return EntryReservation::query()->where('batch_id', $batch->id)->with('ticket')->orderBy('id')->get();
}
$tenant = $user->tenant()->firstOrFail();
$entry = CatalogItem::query()->forTenantCatalog($tenant)->where('slug', 'entrada')
->lockForUpdate()->firstOrFail();
$ids = array_column($rows, 'variant_id');
$variants = $entry->variants()->whereKey($ids)->orderBy('id')->lockForUpdate()->get();
$inventories = Inventory::query()->whereKey($variants->pluck('inventory_id')->filter()->unique())
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$variants->load([
'eventDates', 'eventDate',
'entryReservations' => fn ($query) => $query->lockForUpdate(),
]);
foreach ($variants as $variant) {
$variant->setRelation('inventory', $inventories->get($variant->inventory_id));
}
$entry->setRelation('variants', $variants);
$available = $entry->visibleVariants()->keyBy('id');
$requirements = [];
$errors = [];
foreach ($rows as $index => $row) {
$variant = $available->get($row['variant_id']);
if ($variant === null || $variant->inventory === null) {
$errors["rows.{$index}.variant_id"] = $this->entryLabel($variants->firstWhere('id', $row['variant_id']), $index).': la entrada ya no está disponible.';
continue;
}
$requirements[$variant->inventory_id] = ($requirements[$variant->inventory_id] ?? 0) + 1;
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
$tracked = $entry->inventory_policy !== InventoryPolicy::Unlimited;
foreach ($requirements as $inventoryId => $quantity) {
if ($tracked && $inventories[$inventoryId]->availableStock() < $quantity) {
foreach ($rows as $index => $row) {
$variant = $available[$row['variant_id']];
if ($variant->inventory_id === $inventoryId) {
$errors["rows.{$index}.variant_id"] = $this->entryLabel($variant, $index).': no hay stock suficiente para reservar las entradas seleccionadas.';
}
}
}
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
$batch = ReservationBatch::query()->create([
'user_id' => $user->id, 'tenant_code' => $tenant->codigo,
'idempotency_key' => $key, 'request_hash' => $hash,
]);
foreach ($requirements as $inventoryId => $quantity) {
$inventories[$inventoryId]->reserveEntry($quantity, $tracked);
}
$reservations = collect();
foreach ($rows as $index => $row) {
$variant = $available[$row['variant_id']];
$payment = EntryReservationPaymentType::from($row['tipo_pago']);
try {
$ticket = $this->tickets->generate($entry, $user, 1, $variant->id)->sole();
} catch (TicketGenerationException $exception) {
throw ValidationException::withMessages([
"rows.{$index}.variant_id" => $this->entryLabel($variant, $index).': no se pudo emitir el ticket. '.$exception->getMessage(),
]);
}
$reservation = EntryReservation::query()->create([
'batch_id' => $batch->id, 'ticket_id' => $ticket->id,
'catalog_item_id' => $entry->id,
'variant_id' => $variant->id, 'inventory_id' => $variant->inventory_id,
'fecha_reserva' => now(), 'tipo_pago' => $payment,
'importe' => $payment === EntryReservationPaymentType::Free ? 0 : $variant->getPrice(),
]);
$reservations->push($reservation->setRelation('ticket', $ticket));
}
return $reservations;
}, 3);
}
private function entryLabel(?Variant $variant, int $index): string
{
if ($variant === null) {
return 'Entrada '.($index + 1);
}
$values = $variant->selectionValues();
return collect(['tipo' => 'Tipo', 'sector' => 'Sector', 'fila' => 'Fila', 'asiento' => 'Asiento'])
->map(fn (string $label, string $key): string => $label.': '.($values->get($key) ?? 'sin especificar'))
->implode(', ');
}
}

View File

@@ -1,26 +1,26 @@
<?php
use App\Domains\Ticketing\Desfile\Controllers\DesfileEntryReservationController;
use App\Domains\Ticketing\Desfile\Controllers\EntryController;
use App\Domains\Ticketing\Desfile\Controllers\EntryReservationController;
use Illuminate\Support\Facades\Route;
Route::get('v1/adminapp/tenant/desfile/entry-reservations', [EntryReservationController::class, 'index'])
Route::get('v1/adminapp/tenant/desfile/entry-reservations', [DesfileEntryReservationController::class, 'index'])
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.reservas'])
->name('adminapp.desfile.entry-reservations.index');
Route::get('v1/adminapp/tenant/desfile/entry-reservations/pdf', [EntryReservationController::class, 'downloadPdf'])
Route::get('v1/adminapp/tenant/desfile/entry-reservations/pdf', [DesfileEntryReservationController::class, 'downloadPdf'])
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.reservas'])
->name('adminapp.desfile.entry-reservations.pdf');
Route::get('v1/adminapp/tenant/desfile/entry-reservations/excel', [EntryReservationController::class, 'downloadExcel'])
Route::get('v1/adminapp/tenant/desfile/entry-reservations/excel', [DesfileEntryReservationController::class, 'downloadExcel'])
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.reservas'])
->name('adminapp.desfile.entry-reservations.excel');
Route::get('v1/adminapp/tenant/desfile/entry-reservations/{reservation}/ticket/pdf', [EntryReservationController::class, 'downloadTicketPdf'])
Route::get('v1/adminapp/tenant/desfile/entry-reservations/{reservation}/ticket/pdf', [DesfileEntryReservationController::class, 'downloadTicketPdf'])
->whereNumber('reservation')
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.reservas'])
->name('adminapp.desfile.entry-reservations.ticket.pdf');
Route::post('v1/adminapp/tenant/desfile/entry-reservations', [EntryReservationController::class, 'store'])
Route::post('v1/adminapp/tenant/desfile/entry-reservations', [DesfileEntryReservationController::class, 'store'])
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.reservas'])
->name('adminapp.desfile.entry-reservations.store');
Route::delete('v1/adminapp/tenant/desfile/entry-reservations/{reservation}', [EntryReservationController::class, 'destroy'])
Route::delete('v1/adminapp/tenant/desfile/entry-reservations/{reservation}', [DesfileEntryReservationController::class, 'destroy'])
->whereNumber('reservation')
->middleware(['auth:sanctum', 'adminapp.tenant', 'tenant.menu:adminapp.desfile.reservas'])
->name('adminapp.desfile.entry-reservations.destroy');