Files
shopit-back/app/Domains/Ticket/Services/TicketPresentationResolver.php

79 lines
2.8 KiB
PHP

<?php
namespace App\Domains\Ticket\Services;
use App\Domains\Event\Models\EventDate;
use App\Domains\Event\Services\EffectiveEventDateResolver;
use App\Domains\Ticket\Models\Ticket;
class TicketPresentationResolver
{
public function __construct(private readonly EffectiveEventDateResolver $effectiveEventDateResolver) {}
/** Relaciones necesarias para calcular nombre y descripción sin consultas N+1. */
public const RELATIONS = [
'sourceCatalogItem',
'sourceVariant.catalogItem.itemAttributes.attribute.options',
'sourceVariant.definitions.itemAttribute.attribute.options',
'sourceVariant.eventDates',
'sourceVariant.eventDate',
];
public function name(Ticket $ticket): string
{
$ticket->loadMissing(self::RELATIONS);
$catalogItem = $ticket->sourceCatalogItem;
if ($catalogItem === null) {
return '';
}
$variant = $ticket->sourceVariant;
if ($variant === null) {
return $catalogItem->nombre;
}
$itemAttributes = $variant->catalogItem->itemAttributes;
$eventDateLabels = $variant->selectedEventDates()
->map(fn (EventDate $date): EventDate => $this->effectiveEventDateResolver->resolveLatest($date) ?? $date)
->unique(fn (EventDate $date): int => $date->getKey())
->map(fn (EventDate $date): string => $date->date->format('d/m/Y'))
->implode(', ');
$properties = $variant->selectionOptions($itemAttributes)
->map(function (array $option, string $attributeCode) use ($itemAttributes, $eventDateLabels): ?string {
$labels = $attributeCode === 'event_date' ? $eventDateLabels : collect(array_is_list($option) ? $option : [$option])
->pluck('label')
->filter(fn ($label): bool => is_string($label) && $label !== '')
->implode(', ');
if ($labels === '') {
return null;
}
$ticketLabel = $itemAttributes->first(
fn ($itemAttribute): bool => $itemAttribute->attribute?->codigo === $attributeCode,
)?->ticket_label;
return is_string($ticketLabel) && trim($ticketLabel) !== ''
? trim($ticketLabel).' '.$labels
: $labels;
})
->filter()
->values();
return $properties->isEmpty()
? $catalogItem->nombre
: $catalogItem->nombre.' ('.$properties->implode(', ').')';
}
public function description(Ticket $ticket): string
{
$ticket->loadMissing(self::RELATIONS);
return (string) ($ticket->sourceVariant?->getDescription()
?? $ticket->sourceCatalogItem?->descripcion
?? '');
}
}