Merge branch 'feature/event_scoped_admin' into dev

This commit is contained in:
2026-10-02 12:21:29 -03:00
51 changed files with 2488 additions and 355 deletions

View File

@@ -8,6 +8,7 @@ use App\Domains\Commerce\Catalog\Enums\InventorySubject;
use App\Domains\Commerce\Catalog\Services\CatalogInventoryService;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Event\Models\Event;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Shared\Attachable\Models\Attachment;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -147,6 +148,12 @@ class CatalogItem extends Model
return $this->hasMany(Ticket::class, 'source_catalog_item_id');
}
/** @return HasMany<EntryReservation, $this> */
public function entryReservations(): HasMany
{
return $this->hasMany(EntryReservation::class);
}
/** @return BelongsToMany<Attribute, $this> */
public function attributes(): BelongsToMany
{
@@ -266,13 +273,13 @@ class CatalogItem extends Model
{
$this->variants
->filter(fn (Variant $variant): bool => $variant->exists)
->loadMissing('desfileEntryReservations');
->loadMissing('entryReservations');
return $this->variants
->each(fn (Variant $variant) => $variant->setRelation('catalogItem', $this))
->filter(fn (Variant $variant): bool => $variant->hasOnlyActiveEventDates()
&& (! $variant->relationLoaded('desfileEntryReservations')
|| $variant->desfileEntryReservations->isEmpty())
&& (! $variant->relationLoaded('entryReservations')
|| $variant->entryReservations->isEmpty())
&& (($includedVariantId !== null && $variant->id === $includedVariantId)
|| ($variant->isSellable() && (
$this->inventory_policy === InventoryPolicy::Unlimited

View File

@@ -2,8 +2,8 @@
namespace App\Domains\Commerce\Catalog\Models;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use App\Shared\Attachable\Models\Attachment;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -76,7 +76,7 @@ class Variant extends Model
}
/** @return HasMany<EntryReservation, $this> */
public function desfileEntryReservations(): HasMany
public function entryReservations(): HasMany
{
return $this->hasMany(EntryReservation::class);
}

View File

@@ -7,8 +7,8 @@ use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Catalog\Models\StockReservation;
use App\Domains\Commerce\Catalog\Models\StockReservationLine;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Event\Models\EventDate;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use Illuminate\Support\Collection;
class VariantReplacementService

View File

@@ -25,9 +25,8 @@ class TenantTransactionResetService
'carts' => $scope['cart_ids']->count(),
'cart_items' => $scope['cart_item_ids']->count(),
'tickets' => DB::table('tickets')->where('tenant_code', $tenantCode)->count(),
'entry_reservations' => DB::table('desfile_entry_reservations')
->whereIn('variant_id', DB::table('variantes')->whereIn('catalog_item_id',
DB::table('catalog_items')->where('tenant_code', $tenantCode)->select('id'))->select('id'))->count(),
'entry_reservations' => DB::table('entry_reservations')
->whereIn('catalog_item_id', DB::table('catalog_items')->where('tenant_code', $tenantCode)->select('id'))->count(),
'stock_reservations' => $this->reservationQuery($scope)->count(),
'purchase_changes' => DB::table('value_changes')
->where('tenant_code', $tenantCode)
@@ -50,10 +49,9 @@ class TenantTransactionResetService
$telepagosQr = DB::table('telepagos_qr')->whereIn('compra_id', $scope['purchase_ids'])->count();
$summary = [
'stock_reservations_deleted' => $this->reservationQuery($scope)->delete(),
'entry_reservations_deleted' => DB::table('desfile_entry_reservations')
->whereIn('variant_id', DB::table('variantes')->whereIn('catalog_item_id',
DB::table('catalog_items')->where('tenant_code', $tenantCode)->select('id'))->select('id'))->delete(),
'entry_reservation_batches_deleted' => DB::table('desfile_reservation_batches')->where('tenant_code', $tenantCode)->delete(),
'entry_reservations_deleted' => DB::table('entry_reservations')
->whereIn('catalog_item_id', DB::table('catalog_items')->where('tenant_code', $tenantCode)->select('id'))->delete(),
'entry_reservation_batches_deleted' => DB::table('reservation_batches')->where('tenant_code', $tenantCode)->delete(),
'tickets_deleted' => DB::table('tickets')->where('tenant_code', $tenantCode)->delete(),
'purchase_changes_deleted' => DB::table('value_changes')
->where('tenant_code', $tenantCode)

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

@@ -1,54 +0,0 @@
<?php
namespace App\Domains\Ticketing\Desfile\Models;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Ticketing\Desfile\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Ticket\Models\Ticket;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
#[Fillable([
'variant_id',
'ticket_id',
'inventory_id',
'batch_id',
'fecha_reserva',
'importe',
'tipo_pago',
])]
class EntryReservation extends Model
{
use SoftDeletes;
protected $table = 'desfile_entry_reservations';
protected function casts(): array
{
return [
'variant_id' => 'integer',
'fecha_reserva' => 'datetime',
'importe' => 'decimal:2',
'tipo_pago' => EntryReservationPaymentType::class,
];
}
/** @return BelongsTo<Variant, $this> */
public function variant(): BelongsTo
{
return $this->belongsTo(Variant::class)->withTrashed();
}
public function ticket(): BelongsTo
{
return $this->belongsTo(Ticket::class);
}
public function inventory(): BelongsTo
{
return $this->belongsTo(Inventory::class);
}
}

View File

@@ -2,7 +2,7 @@
namespace App\Domains\Ticketing\Desfile\Requests;
use App\Domains\Ticketing\Desfile\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

View File

@@ -2,7 +2,7 @@
namespace App\Domains\Ticketing\Desfile\Requests;
use App\Domains\Ticketing\Desfile\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

View File

@@ -15,6 +15,7 @@ class EntryReservationResource extends JsonResource
return [
'id' => $this->id,
'catalog_item_id' => $this->catalog_item_id,
'variant_id' => $this->variant_id,
'ticket_id' => $this->ticket_id,
'fecha_reserva' => $this->fecha_reserva->toIso8601String(),

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

@@ -3,7 +3,7 @@
namespace App\Domains\Ticketing\Desfile\Services;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use Illuminate\Support\Collection;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Shared\Date;

View File

@@ -3,7 +3,7 @@
namespace App\Domains\Ticketing\Desfile\Services;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use Barryvdh\DomPDF\Facade\Pdf;
use Barryvdh\DomPDF\PDF as DomPdf;
use Illuminate\Http\Response;

View File

@@ -2,7 +2,7 @@
namespace App\Domains\Ticketing\Desfile\Services;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Models\EntryReservation;
use Illuminate\Support\Collection;
class EntryReservationReportService

View File

@@ -1,240 +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\Desfile\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Ticket\Exceptions\TicketGenerationException;
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 = DB::table('desfile_reservation_batches')
->where('user_id', $user->id)->where('idempotency_key', $key)->lockForUpdate()->first();
if ($batch !== null) {
abort_unless($batch->tenant_code === $user->tenant_codigo && hash_equals($batch->request_hash, $hash), 409,
'La clave de envío ya fue utilizada con otras entradas.');
return EntryReservation::query()->where('batch_id', $batch->id)->with('ticket')->orderBy('id')->get();
}
$tenant = $user->tenant()->firstOrFail();
$entry = CatalogItem::query()->forTenantCatalog($tenant)->where('slug', 'entrada')
->lockForUpdate()->firstOrFail();
$ids = array_column($rows, 'variant_id');
$variants = $entry->variants()->whereKey($ids)->orderBy('id')->lockForUpdate()->get();
$inventories = Inventory::query()->whereKey($variants->pluck('inventory_id')->filter()->unique())
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$variants->load([
'eventDates', 'eventDate',
'desfileEntryReservations' => fn ($query) => $query->lockForUpdate(),
]);
foreach ($variants as $variant) {
$variant->setRelation('inventory', $inventories->get($variant->inventory_id));
}
$entry->setRelation('variants', $variants);
$available = $entry->visibleVariants()->keyBy('id');
$requirements = [];
$errors = [];
foreach ($rows as $index => $row) {
$variant = $available->get($row['variant_id']);
if ($variant === null || $variant->inventory === null) {
$errors["rows.{$index}.variant_id"] = $this->entryLabel($variants->firstWhere('id', $row['variant_id']), $index).': la entrada ya no está disponible.';
continue;
}
$requirements[$variant->inventory_id] = ($requirements[$variant->inventory_id] ?? 0) + 1;
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
$tracked = $entry->inventory_policy !== InventoryPolicy::Unlimited;
foreach ($requirements as $inventoryId => $quantity) {
if ($tracked && $inventories[$inventoryId]->availableStock() < $quantity) {
foreach ($rows as $index => $row) {
$variant = $available[$row['variant_id']];
if ($variant->inventory_id === $inventoryId) {
$errors["rows.{$index}.variant_id"] = $this->entryLabel($variant, $index).': no hay stock suficiente para reservar las entradas seleccionadas.';
}
}
}
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
$batchId = DB::table('desfile_reservation_batches')->insertGetId([
'user_id' => $user->id, 'tenant_code' => $tenant->codigo,
'idempotency_key' => $key, 'request_hash' => $hash,
'created_at' => now(), 'updated_at' => now(),
]);
foreach ($requirements as $inventoryId => $quantity) {
$inventories[$inventoryId]->reserveEntry($quantity, $tracked);
}
$reservations = collect();
foreach ($rows as $index => $row) {
$variant = $available[$row['variant_id']];
$payment = EntryReservationPaymentType::from($row['tipo_pago']);
try {
$ticket = $this->tickets->generate($entry, $user, 1, $variant->id)->sole();
} catch (TicketGenerationException $exception) {
throw ValidationException::withMessages([
"rows.{$index}.variant_id" => $this->entryLabel($variant, $index).': no se pudo emitir el ticket. '.$exception->getMessage(),
]);
}
$reservation = EntryReservation::query()->create([
'batch_id' => $batchId, 'ticket_id' => $ticket->id,
'variant_id' => $variant->id, 'inventory_id' => $variant->inventory_id,
'fecha_reserva' => now(), 'tipo_pago' => $payment,
'importe' => $payment === EntryReservationPaymentType::Free ? 0 : $variant->getPrice(),
]);
$reservations->push($reservation->setRelation('ticket', $ticket));
}
return $reservations;
}, 3);
}
private function entryLabel(?Variant $variant, int $index): string
{
if ($variant === null) {
return 'Entrada '.($index + 1);
}
$values = $variant->selectionValues();
return collect(['tipo' => 'Tipo', 'sector' => 'Sector', 'fila' => 'Fila', 'asiento' => 'Asiento'])
->map(fn (string $label, string $key): string => $label.': '.($values->get($key) ?? 'sin especificar'))
->implode(', ');
}
}

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');

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

@@ -1,6 +1,6 @@
<?php
namespace App\Domains\Ticketing\Desfile\Enums;
namespace App\Domains\Ticketing\Ticket\Enums;
enum EntryReservationPaymentType: string
{

View File

@@ -0,0 +1,87 @@
<?php
namespace App\Domains\Ticketing\Ticket\Models;
use App\Domains\Commerce\Catalog\Models\CatalogItem;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Validation\ValidationException;
#[Fillable([
'catalog_item_id',
'variant_id',
'ticket_id',
'inventory_id',
'batch_id',
'fecha_reserva',
'importe',
'tipo_pago',
])]
class EntryReservation extends Model
{
use SoftDeletes;
protected $table = 'entry_reservations';
protected function casts(): array
{
return [
'catalog_item_id' => 'integer',
'variant_id' => 'integer',
'fecha_reserva' => 'datetime',
'importe' => 'decimal:2',
'tipo_pago' => EntryReservationPaymentType::class,
];
}
protected static function booted(): void
{
static::saving(function (self $reservation): void {
if ($reservation->variant_id === null) {
return;
}
$variant = Variant::withTrashed()->findOrFail($reservation->variant_id);
// Existing variant-based callers can keep creating reservations as before.
$reservation->catalog_item_id ??= $variant->catalog_item_id;
if ($reservation->catalog_item_id !== $variant->catalog_item_id) {
throw ValidationException::withMessages([
'variant_id' => 'La variante no pertenece al ítem del catálogo seleccionado.',
]);
}
});
}
/** @return BelongsTo<CatalogItem, $this> */
public function catalogItem(): BelongsTo
{
return $this->belongsTo(CatalogItem::class)->withTrashed();
}
/** @return BelongsTo<ReservationBatch, $this> */
public function batch(): BelongsTo
{
return $this->belongsTo(ReservationBatch::class, 'batch_id');
}
/** @return BelongsTo<Variant, $this> */
public function variant(): BelongsTo
{
return $this->belongsTo(Variant::class)->withTrashed();
}
public function ticket(): BelongsTo
{
return $this->belongsTo(Ticket::class);
}
public function inventory(): BelongsTo
{
return $this->belongsTo(Inventory::class);
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Domains\Ticketing\Ticket\Models;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['user_id', 'tenant_code', 'idempotency_key', 'request_hash'])]
class ReservationBatch extends Model
{
protected function casts(): array
{
return ['user_id' => 'integer'];
}
/** @return BelongsTo<User, $this> */
public function user(): BelongsTo
{
return $this->belongsTo(User::class)->withTrashed();
}
/** @return BelongsTo<Tenant, $this> */
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
}
/** @return HasMany<EntryReservation, $this> */
public function reservations(): HasMany
{
return $this->hasMany(EntryReservation::class, 'batch_id');
}
}

View File

@@ -7,7 +7,6 @@ use App\Domains\Commerce\Catalog\Models\Variant;
use App\Domains\Commerce\Purchase\Models\PurchaseItem;
use App\Domains\Core\Auth\Models\User;
use App\Domains\Core\Tenant\Models\Tenant;
use App\Domains\Ticketing\Desfile\Models\EntryReservation;
use App\Domains\Ticketing\Event\Models\Event;
use App\Domains\Ticketing\Ticket\Services\ResolvedTicketValidity;
use App\Domains\Ticketing\Ticket\Services\ResolvedValidityGroup;

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\Commerce\Catalog\Models\CatalogItem;
use App\Domains\Commerce\Catalog\Models\Inventory;
use App\Domains\Commerce\Catalog\Models\Variant;
use Illuminate\Validation\ValidationException;
interface EntryReservationPolicy
{
/**
* Validate additional rules after selections are resolved and locked, before
* stock or tickets change. Idempotent replays do not run this validation.
*
* @param array<int, array{item: CatalogItem, variant: Variant|null, inventory: Inventory|null}> $selections
*
* @throws ValidationException
*/
public function validate(array $selections): void;
}

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

@@ -0,0 +1,313 @@
<?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\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 Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
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) {}
/**
* @param array{catalog_item_id?: int, variant_id?: int, tipo_pago?: string|null, page?: int, per_page?: int} $filters
* @return LengthAwarePaginator<EntryReservation>
*/
public function reservations(User $user, array $filters = []): LengthAwarePaginator
{
return $this->reservationsQuery($user, $filters)
->paginate(perPage: $filters['per_page'] ?? 15, page: $filters['page'] ?? 1)
->withQueryString();
}
/**
* @param array{catalog_item_id?: int, variant_id?: int, tipo_pago?: string|null} $filters
* @return Collection<int, EntryReservation>
*/
public function reservationsForExport(User $user, array $filters = []): Collection
{
return $this->reservationsQuery($user, $filters)->get();
}
public function reservationTicket(User $user, int $reservationId, ?int $catalogItemId = null): Ticket
{
$reservation = $this->reservationsQuery($user, ['catalog_item_id' => $catalogItemId])
->whereKey($reservationId)->whereNotNull('ticket_id')
->with(['ticket' => fn ($query) => $query->with([
...TicketValidityResolver::RELATIONS,
...TicketPresentationResolver::RELATIONS,
])])->firstOrFail();
return $reservation->ticket;
}
public function cancel(User $user, int $reservationId, ?int $catalogItemId = null): void
{
DB::transaction(function () use ($user, $reservationId, $catalogItemId): void {
$reservation = $this->reservationsQuery($user, ['catalog_item_id' => $catalogItemId])
->whereKey($reservationId)->lockForUpdate()->firstOrFail();
if ($reservation->ticket_id !== null) {
$ticket = Ticket::query()->whereKey($reservation->ticket_id)->lockForUpdate()->firstOrFail();
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()->whereKey($reservation->inventory_id)->lockForUpdate()->firstOrFail();
$inventory->releaseEntry(1);
}
$reservation->delete();
}, 3);
}
/**
* Each row reserves one unit. Prices and inventory are resolved on the server.
*
* @param list<array{catalog_item_id: int, variant_id?: int|null, tipo_pago: string}> $rows
* @return Collection<int, EntryReservation>
*/
public function reserve(User $user, string $key, array $rows, ?EntryReservationPolicy $policy = null): Collection
{
$validated = Validator::make(['idempotency_key' => $key, 'rows' => $rows], [
'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)],
])->validate();
$rows = array_map(fn (array $row): array => [
'catalog_item_id' => (int) $row['catalog_item_id'],
'variant_id' => isset($row['variant_id']) ? (int) $row['variant_id'] : null,
'tipo_pago' => $row['tipo_pago'],
], $validated['rows']);
$hash = $this->requestHash($rows);
return DB::transaction(function () use ($user, $key, $rows, $hash, $policy): Collection {
User::query()->whereKey($user->id)->lockForUpdate()->firstOrFail();
$tenant = $user->tenant()->firstOrFail();
$batch = ReservationBatch::query()->where('user_id', $user->id)
->where('idempotency_key', $key)->lockForUpdate()->first();
if ($batch !== null) {
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.');
// 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();
}
$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')))
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$variants->load(['eventDates', 'eventDate']);
$inventoryIds = $items->pluck('inventory_id')->merge($variants->pluck('inventory_id'))->filter()->unique();
$inventories = Inventory::query()->whereKey($inventoryIds)->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$selections = [];
$requirements = [];
$errors = [];
foreach ($rows as $index => $row) {
$item = $items->get($row['catalog_item_id']);
$variant = $row['variant_id'] !== null ? $variants->get($row['variant_id']) : null;
$field = $this->selectionField($row, $index);
if ($item === null || ! $item->has_tickets || ! $item->isSaleOpen()) {
$errors[$field] = 'El ítem no está disponible para reservar tickets en este catálogo.';
continue;
}
if ($item->isBundle()) {
$errors[$field] = 'Seleccioná el ítem que emite el ticket; los paquetes requieren reservar sus componentes.';
continue;
}
if ($row['variant_id'] !== null) {
if ($variant === null || $variant->catalog_item_id !== $item->id) {
$errors[$field] = 'La variante no pertenece al ítem del catálogo seleccionado.';
continue;
}
$variant->setRelation('catalogItem', $item);
if (! $variant->isSellable()) {
$errors[$field] = 'La variante ya no está disponible.';
continue;
}
} elseif ($item->variants()->exists()) {
$errors["rows.{$index}.variant_id"] = 'Seleccioná una variante del ítem del catálogo.';
continue;
}
$selection = $variant ?? $item;
$inventory = $inventories->get($selection->inventory_id);
$tracked = $item->inventory_policy !== InventoryPolicy::Unlimited;
if ($inventory === null && ($selection->inventory_id !== null || $tracked)) {
$errors[$field] = 'La selección no tiene un inventario disponible.';
continue;
}
$selection->setRelation('inventory', $inventory);
$selections[$index] = ['item' => $item, 'variant' => $variant, 'inventory' => $inventory];
if ($inventory !== null) {
$requirement = $requirements[$inventory->id] ?? ['quantity' => 0, 'tracked' => false];
$requirements[$inventory->id] = [
'quantity' => $requirement['quantity'] + 1,
'tracked' => $requirement['tracked'] || $tracked,
];
}
}
if ($errors !== []) {
throw ValidationException::withMessages($errors);
}
$policy?->validate($selections);
foreach ($requirements as $inventoryId => $requirement) {
if ($requirement['tracked'] && $inventories[$inventoryId]->availableStock() < $requirement['quantity']) {
foreach ($selections as $index => $selection) {
if ($selection['inventory']?->id === $inventoryId) {
$errors[$this->selectionField($rows[$index], $index)] = 'No hay stock suficiente para reservar la selección.';
}
}
}
}
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 => $requirement) {
$inventories[$inventoryId]->reserveEntry($requirement['quantity'], $requirement['tracked']);
}
$reservations = new Collection;
foreach ($selections as $index => $selection) {
$item = $selection['item'];
$variant = $selection['variant'];
try {
$ticket = $this->tickets->generate($item, $user, 1, $variant?->id)->sole();
} catch (TicketGenerationException $exception) {
throw ValidationException::withMessages([
$this->selectionField($rows[$index], $index) => 'No se pudo emitir el ticket. '.$exception->getMessage(),
]);
}
$payment = EntryReservationPaymentType::from($rows[$index]['tipo_pago']);
$reservation = EntryReservation::query()->create([
'batch_id' => $batch->id, 'ticket_id' => $ticket->id,
'catalog_item_id' => $variant?->catalog_item_id ?? $item->id,
'variant_id' => $variant?->id, 'inventory_id' => $selection['inventory']?->id,
'fecha_reserva' => now(), 'tipo_pago' => $payment,
'importe' => $payment === EntryReservationPaymentType::Free ? 0 : ($variant ?? $item)->getPrice(),
]);
$reservations->push($reservation->setRelation('ticket', $ticket)
->setRelation('catalogItem', $item)->setRelation('variant', $variant));
}
return $reservations->loadMissing(self::SELECTION_RELATIONS);
}, 3);
}
/** @param array<string, mixed> $filters */
private function reservationsQuery(User $user, array $filters = []): Builder
{
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)
->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(self::SELECTION_RELATIONS)
->orderByDesc('fecha_reserva')->orderByDesc('id');
}
/** @param array{variant_id: int|null} $row */
private function selectionField(array $row, int $index): string
{
return "rows.{$index}.".($row['variant_id'] !== null ? 'variant_id' : 'catalog_item_id');
}
/** @param list<array{catalog_item_id: int, variant_id: int|null, tipo_pago: string}> $rows */
private function requestHash(array $rows): string
{
$normalized = collect($rows)->sortBy([
['catalog_item_id', 'asc'], ['variant_id', 'asc'], ['tipo_pago', 'asc'],
])->values()->all();
return hash('sha256', json_encode($normalized, JSON_THROW_ON_ERROR));
}
/** @param list<array{catalog_item_id: int, variant_id: int|null, tipo_pago: string}> $rows */
private function matchesBatch(ReservationBatch $batch, array $rows, string $hash): bool
{
if (hash_equals($batch->request_hash, $hash)) {
return true;
}
if (collect($rows)->contains(fn (array $row) => $row['variant_id'] === null)) {
return false;
}
// Older batches fingerprinted variant and payment only. Check the persisted
// catalog IDs too, so compatibility cannot replay a different catalog item.
$legacyRows = collect($rows)->map(fn (array $row) => [
'variant_id' => $row['variant_id'], 'tipo_pago' => $row['tipo_pago'],
])->sortBy('variant_id')->values()->all();
$legacyHash = hash('sha256', json_encode($legacyRows, JSON_THROW_ON_ERROR));
if (! hash_equals($batch->request_hash, $legacyHash)) {
return false;
}
$storedRows = $batch->reservations()->withTrashed()->get()->map(fn (EntryReservation $reservation) => [
'catalog_item_id' => $reservation->catalog_item_id,
'variant_id' => $reservation->variant_id,
'tipo_pago' => $reservation->tipo_pago->value,
])->all();
return hash_equals($this->requestHash($storedRows), $hash);
}
}

View File

@@ -1,11 +1,24 @@
<?php
use App\Domains\Ticketing\Ticket\Controllers\AdminApp\EntryReservationController;
use App\Domains\Ticketing\Ticket\Controllers\AdminApp\TicketController;
use Illuminate\Support\Facades\Route;
Route::prefix('v1/adminapp/tenant')
->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');

View File

@@ -5,7 +5,7 @@ namespace App\Shared\Forms\Services;
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\Desfile\Enums\EntryReservationPaymentType;
use App\Domains\Ticketing\Ticket\Enums\EntryReservationPaymentType;
class DesfileEntryReservationFormService
{