Refactor ticket validity handling and improve tests
- Updated tests for Accommodation, Entry, Food, Merchandise, and Sale controllers to use soft deletes for variants and ensure proper inventory counts. - Enhanced ticket generation logic to resolve validity from soft-deleted catalog sources. - Introduced a new TicketValidityResolver service to manage ticket validity based on event dates and variant definitions. - Removed unnecessary database assertions and improved the clarity of validity checks in tests. - Added comprehensive tests for the new TicketValidityResolver service, ensuring correct handling of event dates and multi-select options. - Cleaned up unused code and assertions in existing tests for better maintainability.
This commit is contained in:
77
app/Domains/Ticket/Services/ResolvedTicketValidity.php
Normal file
77
app/Domains/Ticket/Services/ResolvedTicketValidity.php
Normal file
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Resultado completo de resolver la vigencia de un ticket.
|
||||
*
|
||||
* Cada ResolvedValidityGroup contiene condiciones AND. Entre los grupos se
|
||||
* aplica OR, por lo que alcanza con que uno de ellos esté activo.
|
||||
*/
|
||||
final readonly class ResolvedTicketValidity
|
||||
{
|
||||
/** @param Collection<int, ResolvedValidityGroup> $groups */
|
||||
public function __construct(
|
||||
public Collection $groups,
|
||||
public bool $isResolvable = true,
|
||||
public bool $isUnrestricted = false,
|
||||
) {}
|
||||
|
||||
/** No existe ninguna restricción temporal configurada. */
|
||||
public static function unrestricted(): self
|
||||
{
|
||||
return new self(collect(), isUnrestricted: true);
|
||||
}
|
||||
|
||||
/** La configuración fuente está incompleta o es inconsistente. */
|
||||
public static function unresolvable(): self
|
||||
{
|
||||
return new self(collect(), isResolvable: false);
|
||||
}
|
||||
|
||||
/** Es válido cuando no tiene restricciones o algún grupo OR está activo. */
|
||||
public function isValid(?CarbonInterface $at = null): bool
|
||||
{
|
||||
if (! $this->isResolvable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->isUnrestricted || $this->groups->contains(
|
||||
fn (ResolvedValidityGroup $group): bool => $group->isValid($at)
|
||||
);
|
||||
}
|
||||
|
||||
/** Sólo está vencido cuando todos los grupos OR ya vencieron. */
|
||||
public function isExpired(?CarbonInterface $at = null): bool
|
||||
{
|
||||
return $this->isResolvable
|
||||
&& ! $this->isUnrestricted
|
||||
&& $this->groups->isNotEmpty()
|
||||
&& $this->groups->every(
|
||||
fn (ResolvedValidityGroup $group): bool => $group->isExpired($at)
|
||||
);
|
||||
}
|
||||
|
||||
/** Inicio más temprano de todas las alternativas, usado como resumen. */
|
||||
public function effectiveStartsAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
return $this->groups
|
||||
->map(fn (ResolvedValidityGroup $group): ?CarbonInterface => $group->effectiveStartsAt($at))
|
||||
->filter()
|
||||
->sortBy(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/** Vencimiento más tardío de todas las alternativas, usado como resumen. */
|
||||
public function effectiveExpiresAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
return $this->groups
|
||||
->map(fn (ResolvedValidityGroup $group): ?CarbonInterface => $group->effectiveExpiresAt($at))
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $expiresAt): int => $expiresAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
}
|
||||
97
app/Domains/Ticket/Services/ResolvedValidityGroup.php
Normal file
97
app/Domains/Ticket/Services/ResolvedValidityGroup.php
Normal file
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Ticket\Enums\ValidityTimeType;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Representa una intersección de vigencias: todos los ValidityTime del grupo
|
||||
* deben cumplirse simultáneamente (AND).
|
||||
*
|
||||
* Ejemplo: [fecha del evento, horario de almuerzo] significa que el ticket
|
||||
* solamente es válido durante la intersección de ambas ventanas.
|
||||
*/
|
||||
final readonly class ResolvedValidityGroup
|
||||
{
|
||||
/** @param Collection<int, ValidityTime> $validityTimes */
|
||||
public function __construct(public Collection $validityTimes) {}
|
||||
|
||||
/** Comprueba si el instante pertenece a la intersección efectiva del grupo. */
|
||||
public function isValid(?CarbonInterface $at = null): bool
|
||||
{
|
||||
$at ??= now();
|
||||
$startsAt = $this->effectiveStartsAt($at);
|
||||
$expiresAt = $this->effectiveExpiresAt($at);
|
||||
|
||||
return $this->validityTimes->isNotEmpty()
|
||||
&& ($startsAt === null || $startsAt->lessThanOrEqualTo($at))
|
||||
&& ($expiresAt === null || $expiresAt->greaterThan($at));
|
||||
}
|
||||
|
||||
/** Un grupo vence cuando termina su intersección efectiva. */
|
||||
public function isExpired(?CarbonInterface $at = null): bool
|
||||
{
|
||||
$at ??= now();
|
||||
$expiresAt = $this->effectiveExpiresAt($at);
|
||||
|
||||
return $expiresAt !== null && $expiresAt->lessThanOrEqualTo($at);
|
||||
}
|
||||
|
||||
/**
|
||||
* En un AND, la intersección comienza en el inicio más tardío.
|
||||
* Por ejemplo, fecha 00:00 + horario 12:00 comienza a las 12:00.
|
||||
*/
|
||||
public function effectiveStartsAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
$at ??= now();
|
||||
$anchor = $this->dateAnchor() ?? $at;
|
||||
|
||||
return $this->validityTimes
|
||||
->map(fn (ValidityTime $validityTime): ?CarbonInterface => $validityTime->startsAt($anchor))
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* En un AND, la intersección termina en el vencimiento más temprano.
|
||||
* Los horarios cuyo fin no supera al inicio se interpretan como nocturnos.
|
||||
*/
|
||||
public function effectiveExpiresAt(?CarbonInterface $at = null): ?CarbonInterface
|
||||
{
|
||||
$at ??= now();
|
||||
$anchor = $this->dateAnchor() ?? $at;
|
||||
|
||||
return $this->validityTimes
|
||||
->map(function (ValidityTime $validityTime) use ($anchor): ?CarbonInterface {
|
||||
$startsAt = $validityTime->startsAt($anchor);
|
||||
$expiresAt = $validityTime->expiresAt($anchor);
|
||||
|
||||
if ($startsAt !== null && $expiresAt !== null && $expiresAt->lessThanOrEqualTo($startsAt)) {
|
||||
return $expiresAt->addDay();
|
||||
}
|
||||
|
||||
return $expiresAt;
|
||||
})
|
||||
->filter()
|
||||
->sortBy(fn (CarbonInterface $expiresAt): int => $expiresAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Usa la fecha de un fixed_window como ancla para convertir ventanas que
|
||||
* sólo contienen horas (time_window) en instantes concretos.
|
||||
*/
|
||||
private function dateAnchor(): ?CarbonInterface
|
||||
{
|
||||
return $this->validityTimes
|
||||
->filter(fn (ValidityTime $validityTime): bool => $validityTime->type === ValidityTimeType::FixedWindow)
|
||||
->map(fn (ValidityTime $validityTime): ?CarbonInterface => $validityTime->fixed_starts_at)
|
||||
->filter()
|
||||
->sortByDesc(fn (CarbonInterface $startsAt): int => $startsAt->getTimestamp())
|
||||
->first();
|
||||
}
|
||||
}
|
||||
@@ -138,7 +138,8 @@ class ScannerTicketService
|
||||
private function relations(): array
|
||||
{
|
||||
return [
|
||||
'validityGroups.validityTimes',
|
||||
...TicketValidityResolver::RELATIONS,
|
||||
...TicketPresentationResolver::RELATIONS,
|
||||
'sourceCatalogItem.category',
|
||||
'sourceVariant.eventDate',
|
||||
'sourceVariant.catalogItem',
|
||||
|
||||
@@ -5,19 +5,16 @@ namespace App\Domains\Ticket\Services;
|
||||
use App\Domains\Auth\Models\User;
|
||||
use App\Domains\Catalog\Models\CatalogItem;
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Event\Models\EventDate;
|
||||
use App\Domains\Ticket\Enums\TicketGenerationPolicy;
|
||||
use App\Domains\Ticket\Exceptions\TicketGenerationException;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\TicketValidityGroup;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class TicketGeneratorService
|
||||
{
|
||||
public function __construct(private readonly TicketValidityResolver $validityResolver) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Ticket>
|
||||
*/
|
||||
@@ -45,19 +42,9 @@ class TicketGeneratorService
|
||||
): Ticket {
|
||||
$item = $target['catalog_item'];
|
||||
$variant = $target['variant'];
|
||||
$eventDate = $target['event_date'];
|
||||
$validityGroups = $this->buildTicketValidityGroups(
|
||||
$item,
|
||||
$variant,
|
||||
$eventDate,
|
||||
$this->resolveValidityTime($item, $variant),
|
||||
);
|
||||
|
||||
$ticket = Ticket::query()->create([
|
||||
'tenant_code' => $item->tenant_code,
|
||||
'ticket' => (string) Str::uuid(),
|
||||
'name' => $this->ticketName($item, $variant, $eventDate),
|
||||
'description' => (string) ($item->descripcion ?? ''),
|
||||
'source_purchase_id' => $sourcePurchaseId,
|
||||
'source_catalog_item_id' => $item->getKey(),
|
||||
'source_variant_id' => $variant?->getKey(),
|
||||
@@ -65,31 +52,12 @@ class TicketGeneratorService
|
||||
'user_id' => $user->getKey(),
|
||||
]);
|
||||
|
||||
$groups = $validityGroups->map(function (Collection $validityTimes) use ($ticket): TicketValidityGroup {
|
||||
$group = $ticket->validityGroups()->create();
|
||||
$group->validityTimes()->attach(
|
||||
$validityTimes
|
||||
->map(fn (ValidityTime $validityTime): int => $validityTime->getKey())
|
||||
->all()
|
||||
);
|
||||
$group->setRelation(
|
||||
'validityTimes',
|
||||
new EloquentCollection($validityTimes->all()),
|
||||
);
|
||||
|
||||
return $group;
|
||||
});
|
||||
|
||||
$ticket->setRelation('validityGroups', new EloquentCollection($groups->all()));
|
||||
|
||||
return $ticket;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null, event_date: EventDate|null}>
|
||||
*/
|
||||
/** @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null}> */
|
||||
private function resolveTargets(
|
||||
CatalogItem $catalogItem,
|
||||
int $quantity,
|
||||
@@ -126,9 +94,7 @@ class TicketGeneratorService
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null, event_date: EventDate|null}>
|
||||
*/
|
||||
/** @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null}> */
|
||||
private function targetsForVariant(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
@@ -138,36 +104,18 @@ class TicketGeneratorService
|
||||
return Collection::times($quantity, fn (): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => null,
|
||||
'event_date' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
$variant->loadMissing(['eventDates.validityTime', 'eventDate.validityTime']);
|
||||
$selectedEventDates = $variant->selectedEventDates();
|
||||
|
||||
if ($catalogItem->ticket_generation_policy === TicketGenerationPolicy::OnePerUnit) {
|
||||
$eventDate = $selectedEventDates->count() === 1
|
||||
? $selectedEventDates->first()
|
||||
: null;
|
||||
|
||||
return Collection::times($quantity, fn (): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => $variant,
|
||||
'event_date' => $eventDate,
|
||||
]);
|
||||
if (! $this->validityResolver->resolveVariant($variant)->isResolvable) {
|
||||
throw TicketGenerationException::invalidValidityConfiguration($catalogItem, $variant);
|
||||
}
|
||||
|
||||
$eventDates = $selectedEventDates->isEmpty()
|
||||
? collect([null])
|
||||
: $selectedEventDates;
|
||||
|
||||
return Collection::times($quantity)
|
||||
->flatMap(fn () => $eventDates->map(fn (?EventDate $eventDate): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => $variant,
|
||||
'event_date' => $eventDate,
|
||||
]))
|
||||
->values();
|
||||
return Collection::times($quantity, fn (): array => [
|
||||
'catalog_item' => $catalogItem,
|
||||
'variant' => $variant,
|
||||
]);
|
||||
}
|
||||
|
||||
private function resolveVariant(
|
||||
@@ -201,112 +149,5 @@ class TicketGeneratorService
|
||||
if (! $catalogItem->has_tickets) {
|
||||
throw TicketGenerationException::ticketsDisabled($catalogItem);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private function resolveValidityTime(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
): ?ValidityTime {
|
||||
if ($catalogItem->validity_time_id !== null) {
|
||||
return $catalogItem->validityTime;
|
||||
}
|
||||
|
||||
if ($variant === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$variant->loadMissing('definitions.itemAttribute.attribute.options.validityTime');
|
||||
|
||||
$validityTimes = $variant->definitions
|
||||
->map(function ($definition): ?ValidityTime {
|
||||
$option = $definition->itemAttribute?->attribute?->options
|
||||
->firstWhere('value', $definition->value);
|
||||
|
||||
return $option?->validityTime;
|
||||
})
|
||||
->filter()
|
||||
->unique(fn (ValidityTime $validityTime): int => $validityTime->getKey())
|
||||
->values();
|
||||
|
||||
if ($validityTimes->count() > 1) {
|
||||
throw TicketGenerationException::ambiguousValidityTime($catalogItem);
|
||||
}
|
||||
|
||||
return $validityTimes->first();
|
||||
}
|
||||
|
||||
private function ticketName(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
?EventDate $eventDate,
|
||||
): string {
|
||||
if ($variant === null) {
|
||||
return $catalogItem->nombre;
|
||||
}
|
||||
|
||||
$options = $variant->selectionOptions();
|
||||
|
||||
if ($eventDate !== null) {
|
||||
$options->put('event_date', [
|
||||
'value' => (string) $eventDate->getKey(),
|
||||
'label' => $eventDate->date->format('d/m/Y'),
|
||||
]);
|
||||
}
|
||||
|
||||
$properties = $options
|
||||
->flatMap(function (array $option): array {
|
||||
if (array_is_list($option)) {
|
||||
return collect($option)
|
||||
->pluck('label')
|
||||
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
||||
->all();
|
||||
}
|
||||
|
||||
$label = $option['label'] ?? null;
|
||||
|
||||
return is_string($label) && $label !== '' ? [$label] : [];
|
||||
})
|
||||
->values();
|
||||
|
||||
if ($properties->isEmpty()) {
|
||||
return $catalogItem->nombre;
|
||||
}
|
||||
|
||||
return $catalogItem->nombre.' ('.$properties->implode(', ').')';
|
||||
}
|
||||
|
||||
/** @return Collection<int, Collection<int, ValidityTime>> */
|
||||
private function buildTicketValidityGroups(
|
||||
CatalogItem $catalogItem,
|
||||
?Variant $variant,
|
||||
?EventDate $eventDate,
|
||||
?ValidityTime $validityTime,
|
||||
): Collection {
|
||||
$eventDates = collect([$eventDate]);
|
||||
|
||||
if (
|
||||
$catalogItem->ticket_generation_policy === TicketGenerationPolicy::OnePerUnit
|
||||
&& $variant !== null
|
||||
) {
|
||||
$variant->loadMissing(['eventDates.validityTime', 'eventDate.validityTime']);
|
||||
$selectedEventDates = $variant->selectedEventDates();
|
||||
|
||||
if ($selectedEventDates->isNotEmpty()) {
|
||||
$eventDates = $selectedEventDates;
|
||||
}
|
||||
}
|
||||
|
||||
return $eventDates
|
||||
->map(function (?EventDate $date) use ($validityTime): Collection {
|
||||
$date?->loadMissing('validityTime');
|
||||
|
||||
return collect([$date?->validityTime, $validityTime])
|
||||
->filter()
|
||||
->unique(fn (ValidityTime $time): int => $time->getKey())
|
||||
->values();
|
||||
})
|
||||
->filter(fn (Collection $group): bool => $group->isNotEmpty())
|
||||
->values();
|
||||
}
|
||||
}
|
||||
|
||||
60
app/Domains/Ticket/Services/TicketPresentationResolver.php
Normal file
60
app/Domains/Ticket/Services/TicketPresentationResolver.php
Normal file
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
|
||||
class TicketPresentationResolver
|
||||
{
|
||||
/** 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;
|
||||
}
|
||||
|
||||
$properties = $variant->selectionOptions()
|
||||
->flatMap(function (array $option): array {
|
||||
if (array_is_list($option)) {
|
||||
return collect($option)
|
||||
->pluck('label')
|
||||
->filter(fn ($label): bool => is_string($label) && $label !== '')
|
||||
->all();
|
||||
}
|
||||
|
||||
$label = $option['label'] ?? null;
|
||||
|
||||
return is_string($label) && $label !== '' ? [$label] : [];
|
||||
})
|
||||
->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
|
||||
?? '');
|
||||
}
|
||||
}
|
||||
134
app/Domains/Ticket/Services/TicketValidityResolver.php
Normal file
134
app/Domains/Ticket/Services/TicketValidityResolver.php
Normal file
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Ticket\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\Variant;
|
||||
use App\Domains\Catalog\Models\VariantDefinition;
|
||||
use App\Domains\Ticket\Models\Ticket;
|
||||
use App\Domains\Ticket\Models\ValidityTime;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Deriva la expresión temporal de un ticket desde su variante.
|
||||
*
|
||||
* Las selecciones alternativas de una misma dimensión (varias fechas u opciones
|
||||
* multiselección) se interpretan como OR. Las dimensiones diferentes se combinan
|
||||
* mediante AND usando un producto cartesiano.
|
||||
*/
|
||||
class TicketValidityResolver
|
||||
{
|
||||
/** Relaciones necesarias para resolver tickets sin consultas N+1. */
|
||||
public const RELATIONS = [
|
||||
'sourceVariant.eventDates.validityTime',
|
||||
'sourceVariant.eventDate.validityTime',
|
||||
'sourceVariant.definitions.itemAttribute.attribute.options.validityTime',
|
||||
];
|
||||
|
||||
/**
|
||||
* Resuelve la variante fuente del ticket. Un ticket creado legítimamente sin
|
||||
* variante es irrestricto; una referencia esperada pero rota es irresoluble.
|
||||
*/
|
||||
public function resolveTicket(Ticket $ticket): ResolvedTicketValidity
|
||||
{
|
||||
if ($ticket->source_variant_id === null) {
|
||||
return ResolvedTicketValidity::unrestricted();
|
||||
}
|
||||
|
||||
$ticket->loadMissing(self::RELATIONS);
|
||||
|
||||
if ($ticket->sourceVariant === null) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
return $this->resolveVariant($ticket->sourceVariant);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convierte las fechas y definiciones temporales de la variante en grupos
|
||||
* normalizados: AND dentro de cada grupo y OR entre grupos.
|
||||
*/
|
||||
public function resolveVariant(Variant $variant): ResolvedTicketValidity
|
||||
{
|
||||
$variant->loadMissing([
|
||||
'eventDates.validityTime',
|
||||
'eventDate.validityTime',
|
||||
'definitions.itemAttribute.attribute.options.validityTime',
|
||||
]);
|
||||
|
||||
$dimensions = collect();
|
||||
$eventDates = $variant->selectedEventDates();
|
||||
|
||||
if ($eventDates->contains(fn ($eventDate): bool => $eventDate->validityTime === null)) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
if ($eventDates->isNotEmpty()) {
|
||||
// Todas las fechas pertenecen a una misma dimensión alternativa:
|
||||
// fecha 1 OR fecha 2 OR fecha 3.
|
||||
$dimensions->push(
|
||||
$eventDates->map(fn ($eventDate): Collection => collect([$eventDate->validityTime]))
|
||||
);
|
||||
}
|
||||
|
||||
foreach ($variant->definitions->groupBy('item_attribute_id') as $definitions) {
|
||||
$itemAttribute = $definitions->first()?->itemAttribute;
|
||||
$attribute = $itemAttribute?->attribute;
|
||||
|
||||
if ($itemAttribute === null || $attribute === null) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
if (! $attribute->type->supportsOptions() || $attribute->type->usesDynamicOptions()) {
|
||||
// Texto, números y demás atributos no temporales no restringen
|
||||
// la vigencia. EventDate se procesó arriba mediante su relación.
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $itemAttribute->allow_multi_select && $definitions->count() > 1) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
$alternatives = $definitions->map(function (VariantDefinition $definition) use ($attribute): ?Collection {
|
||||
$option = $attribute->options->firstWhere('value', $definition->value);
|
||||
|
||||
if ($option === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return collect([$option->validityTime])->filter()->values();
|
||||
});
|
||||
|
||||
if ($alternatives->contains(null)) {
|
||||
return ResolvedTicketValidity::unresolvable();
|
||||
}
|
||||
|
||||
if ($alternatives->contains(fn (Collection $alternative): bool => $alternative->isNotEmpty())) {
|
||||
// Las opciones elegidas del mismo atributo son alternativas OR.
|
||||
$dimensions->push($alternatives->values());
|
||||
}
|
||||
}
|
||||
|
||||
if ($dimensions->isEmpty()) {
|
||||
return ResolvedTicketValidity::unrestricted();
|
||||
}
|
||||
|
||||
$groups = collect([collect()]);
|
||||
|
||||
foreach ($dimensions as $alternatives) {
|
||||
// El producto cartesiano agrega cada dimensión como una condición
|
||||
// AND y conserva sus opciones internas como alternativas OR.
|
||||
$groups = $groups->flatMap(
|
||||
fn (Collection $group): Collection => $alternatives->map(
|
||||
fn (Collection $alternative): Collection => $group
|
||||
->merge($alternative)
|
||||
->unique(fn (ValidityTime $time): int => $time->getKey() ?? spl_object_id($time))
|
||||
->values()
|
||||
)
|
||||
)->values();
|
||||
}
|
||||
|
||||
return new ResolvedTicketValidity(
|
||||
$groups->map(fn (Collection $times): ResolvedValidityGroup => new ResolvedValidityGroup($times))
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user