Merge branch 'feature/event_scoped_admin' into homo
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticketing\Ticket\Enums;
|
||||
|
||||
enum EntryReservationPaymentType: string
|
||||
{
|
||||
case Free = 'sin_cargo';
|
||||
case Other = 'otro_metodo';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Free => 'Sin cargo',
|
||||
self::Other => 'Otro método',
|
||||
};
|
||||
}
|
||||
|
||||
/** @return list<array{value: string, label: string}> */
|
||||
public static function options(): array
|
||||
{
|
||||
return array_map(
|
||||
fn (self $type): array => [
|
||||
'value' => $type->value,
|
||||
'label' => $type->label(),
|
||||
],
|
||||
self::cases(),
|
||||
);
|
||||
}
|
||||
}
|
||||
87
app/Domains/Ticketing/Ticket/Models/EntryReservation.php
Normal file
87
app/Domains/Ticketing/Ticket/Models/EntryReservation.php
Normal 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);
|
||||
}
|
||||
}
|
||||
37
app/Domains/Ticketing/Ticket/Models/ReservationBatch.php
Normal file
37
app/Domains/Ticketing/Ticket/Models/ReservationBatch.php
Normal 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');
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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]];
|
||||
}
|
||||
}
|
||||
@@ -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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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)],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
}
|
||||
@@ -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],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
|
||||
Reference in New Issue
Block a user