feat: add support for multiple event dates in variants

- Updated the FeaturedGroupService to include 'variants.eventDates' in the items query.
- Introduced a BelongsToMany relationship in EventDate for selected variants.
- Modified PurchaseItemResource and PurchaseItemSnapshotFactory to handle multiple event dates for variants.
- Enhanced StartCheckoutService to load event dates for variants.
- Updated TicketGeneratorService to accommodate event dates in ticket generation.
- Created migrations to support multi-value event dates and allow multiple variant values per attribute.
- Adjusted seeders to reflect new event date handling and added new attributes.
- Added tests to ensure correct functionality for multi-date variants and their integration with ticket generation.
This commit is contained in:
2026-08-07 11:57:38 -03:00
parent 91af233941
commit 21b70777f2
22 changed files with 516 additions and 413 deletions

View File

@@ -104,6 +104,8 @@ class CartService
'items.variant.attachments', 'items.variant.attachments',
'items.variant.inventory', 'items.variant.inventory',
'items.variant.definitions.itemAttribute.attribute', 'items.variant.definitions.itemAttribute.attribute',
'items.variant.eventDates',
'items.variant.eventDate',
]); ]);
} }

View File

@@ -11,6 +11,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable([ #[Fillable([
'catalog_item_id', 'catalog_item_id',
'attribute_id', 'attribute_id',
'allow_multi_select',
])] ])]
class ItemAttribute extends Model class ItemAttribute extends Model
{ {
@@ -18,6 +19,15 @@ class ItemAttribute extends Model
protected $table = 'item_attributes'; protected $table = 'item_attributes';
protected function casts(): array
{
return [
'catalog_item_id' => 'integer',
'attribute_id' => 'integer',
'allow_multi_select' => 'boolean',
];
}
/** @return BelongsTo<CatalogItem, $this> */ /** @return BelongsTo<CatalogItem, $this> */
public function catalogItem(): BelongsTo public function catalogItem(): BelongsTo
{ {

View File

@@ -11,6 +11,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
#[Fillable([ #[Fillable([
'catalog_item_id', 'catalog_item_id',
@@ -46,6 +47,17 @@ class Variant extends Model
return $this->belongsTo(EventDate::class); return $this->belongsTo(EventDate::class);
} }
/** @return BelongsToMany<EventDate, $this> */
public function eventDates(): BelongsToMany
{
return $this->belongsToMany(
EventDate::class,
'variant_event_dates',
'variant_id',
'event_date_id',
)->orderBy('date')->orderBy('time_start');
}
/** @return HasMany<Ticket, $this> */ /** @return HasMany<Ticket, $this> */
public function sourceTickets(): HasMany public function sourceTickets(): HasMany
{ {
@@ -92,4 +104,39 @@ class Variant extends Model
{ {
return $this->catalogItem->nombre; return $this->catalogItem->nombre;
} }
/** @return Collection<string, string|array<int, string>> */
public function selectionValues(): Collection
{
$values = $this->definitions
->mapWithKeys(fn ($definition) => [
$definition->itemAttribute?->attribute?->codigo => $definition->value,
])
->filter(fn ($value, $key): bool => $key !== null);
$eventDateIds = $this->selectedEventDates()
->pluck('id')
->map(fn ($id): string => (string) $id)
->values();
if ($eventDateIds->count() === 1) {
$values->put('event_date', $eventDateIds->first());
} elseif ($eventDateIds->isNotEmpty()) {
$values->put('event_date', $eventDateIds->all());
}
return $values;
}
/** @return Collection<int, EventDate> */
public function selectedEventDates(): Collection
{
$eventDates = $this->eventDates;
if ($eventDates->isEmpty() && $this->event_date_id !== null && $this->eventDate !== null) {
return collect([$this->eventDate]);
}
return $eventDates;
}
} }

View File

@@ -75,6 +75,15 @@ class StoreCatalogItemRequest extends FormRequest
fn ($query) => $query->where('tenant_codigo', $tenantCode) fn ($query) => $query->where('tenant_codigo', $tenantCode)
), ),
], ],
'multi_select_attribute_codes' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
'multi_select_attribute_codes.*' => [
'required',
'string',
'distinct',
Rule::exists('attribute', 'codigo')->where(
fn ($query) => $query->where('tenant_codigo', $tenantCode)
),
],
'images' => ['sometimes', 'array'], 'images' => ['sometimes', 'array'],
'images.*' => ['required', new ImageOrBase64Rule], 'images.*' => ['required', new ImageOrBase64Rule],
'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'], 'variants' => [Rule::prohibitedIf($isBundle), 'sometimes', 'array'],
@@ -87,6 +96,15 @@ class StoreCatalogItemRequest extends FormRequest
fn ($query) => $query->where('tenant_code', $tenantCode) fn ($query) => $query->where('tenant_code', $tenantCode)
), ),
], ],
'variants.*.event_date_ids' => ['sometimes', 'array', 'min:1'],
'variants.*.event_date_ids.*' => [
'required',
'integer',
'distinct',
Rule::exists('event_dates', 'id')->where(
fn ($query) => $query->where('tenant_code', $tenantCode)
),
],
'variants.*.inventory_id' => ['prohibited'], 'variants.*.inventory_id' => ['prohibited'],
'variants.*.reserved_stock' => ['prohibited'], 'variants.*.reserved_stock' => ['prohibited'],
'variants.*.sold_units' => ['prohibited'], 'variants.*.sold_units' => ['prohibited'],

View File

@@ -39,14 +39,12 @@ class CatalogFeaturedItemResource extends JsonResource
'id' => $variant->id, 'id' => $variant->id,
'event_date_id' => $variant->event_date_id, 'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'), 'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited 'stock_tecnico' => $catalogItem->inventory_policy === InventoryPolicy::Unlimited
? null ? null
: $variant->inventory->availableStock(), : $variant->inventory->availableStock(),
'values' => $variant->definitions 'values' => $variant->selectionValues(),
->mapWithKeys(fn ($definition) => [
$definition->itemAttribute?->attribute?->codigo => $definition->value,
])
->filter(fn ($value, $key): bool => $key !== null),
]) ])
->values(), ->values(),
]; ];

View File

@@ -88,6 +88,7 @@ class CatalogItemDetailResource extends JsonResource
'codigo' => $attribute->codigo, 'codigo' => $attribute->codigo,
'nombre' => $attribute->nombre, 'nombre' => $attribute->nombre,
'is_required' => $attribute->is_required, 'is_required' => $attribute->is_required,
'allow_multi_select' => $itemAttribute->allow_multi_select,
'metadata_schema' => $attribute->metadata_schema, 'metadata_schema' => $attribute->metadata_schema,
'type' => $attribute->type->value, 'type' => $attribute->type->value,
'options' => $attribute->type === FieldType::EventDate 'options' => $attribute->type === FieldType::EventDate
@@ -155,20 +156,15 @@ class CatalogItemDetailResource extends JsonResource
/** @return array<string, mixed> */ /** @return array<string, mixed> */
private function variantData(Variant $variant): array private function variantData(Variant $variant): array
{ {
$values = $variant->definitions $values = $variant->selectionValues();
->mapWithKeys(fn ($definition) => [ $eventDates = $variant->selectedEventDates();
$definition->itemAttribute?->attribute?->codigo => $definition->value,
])
->filter(fn ($value, $key): bool => $key !== null);
if ($variant->event_date_id !== null) {
$values->put('event_date', (string) $variant->event_date_id);
}
return [ return [
'id' => $variant->id, 'id' => $variant->id,
'event_date_id' => $variant->event_date_id, 'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'), 'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $eventDates->pluck('id')->values(),
'event_dates' => $eventDates->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'stock_tecnico' => $this->variantStock($variant), 'stock_tecnico' => $this->variantStock($variant),
'values' => $values, 'values' => $values,
]; ];

View File

@@ -40,12 +40,10 @@ class CatalogItemResource extends JsonResource
'id' => $variant->id, 'id' => $variant->id,
'event_date_id' => $variant->event_date_id, 'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'), 'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'real_stock' => $variant->inventory?->real_stock, 'real_stock' => $variant->inventory?->real_stock,
'values' => $variant->definitions 'values' => $variant->selectionValues(),
->mapWithKeys(fn ($definition) => [
$definition->itemAttribute?->attribute?->codigo => $definition->value,
])
->filter(fn ($value, $key) => $key !== null),
'images' => $variant->attachments 'images' => $variant->attachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440)) ->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values(), ->values(),

View File

@@ -35,14 +35,12 @@ class CatalogSearchItemResource extends JsonResource
'id' => $variant->id, 'id' => $variant->id,
'event_date_id' => $variant->event_date_id, 'event_date_id' => $variant->event_date_id,
'event_date' => $variant->eventDate?->date?->format('Y-m-d'), 'event_date' => $variant->eventDate?->date?->format('Y-m-d'),
'event_date_ids' => $variant->selectedEventDates()->pluck('id')->values(),
'event_dates' => $variant->selectedEventDates()->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))->values(),
'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited 'stock_tecnico' => $this->inventory_policy === InventoryPolicy::Unlimited
? null ? null
: $variant->inventory?->availableStock(), : $variant->inventory?->availableStock(),
'values' => $variant->definitions 'values' => $variant->selectionValues(),
->mapWithKeys(fn ($definition) => [
$definition->itemAttribute?->attribute?->codigo => $definition->value,
])
->filter(fn ($value, $key): bool => $key !== null),
]) ])
->values(), ->values(),
]; ];

View File

@@ -37,12 +37,14 @@ class CatalogService
$variants = $data['variants'] ?? []; $variants = $data['variants'] ?? [];
$images = $data['images'] ?? []; $images = $data['images'] ?? [];
$attributeCodes = $data['attribute_codes'] ?? []; $attributeCodes = $data['attribute_codes'] ?? [];
$multiSelectAttributeCodes = $data['multi_select_attribute_codes'] ?? [];
$components = $data['components'] ?? []; $components = $data['components'] ?? [];
$hasDirectStock = array_key_exists('real_stock', $data); $hasDirectStock = array_key_exists('real_stock', $data);
$realStock = (int) ($data['real_stock'] ?? 0); $realStock = (int) ($data['real_stock'] ?? 0);
$hasEventDateVariants = $variants !== [] && collect($variants)->every( $hasEventDateVariants = $variants !== [] && collect($variants)->every(
fn (array $variant): bool => ! empty($variant['event_date_id']) fn (array $variant): bool => ! empty($variant['event_date_id'])
|| ! empty($variant['event_date_ids'])
); );
if ($hasEventDateVariants && ! in_array('event_date', $attributeCodes, true)) { if ($hasEventDateVariants && ! in_array('event_date', $attributeCodes, true)) {
@@ -55,6 +57,14 @@ class CatalogService
$hasVariants = $attributeCodes !== [] || $hasEventDateVariants; $hasVariants = $attributeCodes !== [] || $hasEventDateVariants;
if (array_diff($multiSelectAttributeCodes, $attributeCodes) !== []) {
throw ValidationException::withMessages([
'multi_select_attribute_codes' => [
'Multi-select attributes must also be present in attribute_codes.',
],
]);
}
$this->validateEventProductType($data); $this->validateEventProductType($data);
$this->validateUniqueVariantCombinations($variants, $attributeCodes); $this->validateUniqueVariantCombinations($variants, $attributeCodes);
@@ -79,6 +89,7 @@ class CatalogService
$data['variants'], $data['variants'],
$data['images'], $data['images'],
$data['attribute_codes'], $data['attribute_codes'],
$data['multi_select_attribute_codes'],
$data['components'], $data['components'],
$data['real_stock'], $data['real_stock'],
$data['reserved_stock'], $data['reserved_stock'],
@@ -100,7 +111,7 @@ class CatalogService
$catalogItem = CatalogItem::query()->create($data); $catalogItem = CatalogItem::query()->create($data);
$itemAttributes = $type === CatalogItemType::Standard $itemAttributes = $type === CatalogItemType::Standard
? $this->createItemAttributes($catalogItem, $attributeCodes) ? $this->createItemAttributes($catalogItem, $attributeCodes, $multiSelectAttributeCodes)
: []; : [];
if ($type === CatalogItemType::Bundle) { if ($type === CatalogItemType::Bundle) {
@@ -141,6 +152,7 @@ class CatalogService
'variants.inventory', 'variants.inventory',
'variants.attachments', 'variants.attachments',
'variants.eventDate', 'variants.eventDate',
'variants.eventDates',
'variants.definitions.itemAttribute.attribute', 'variants.definitions.itemAttribute.attribute',
'bundleComponents.catalogItem', 'bundleComponents.catalogItem',
'bundleComponents.variant.catalogItem', 'bundleComponents.variant.catalogItem',
@@ -162,6 +174,7 @@ class CatalogService
'variants.inventory', 'variants.inventory',
'variants.attachments', 'variants.attachments',
'variants.eventDate', 'variants.eventDate',
'variants.eventDates',
'variants.definitions' => fn ($query) => $query->orderBy('id'), 'variants.definitions' => fn ($query) => $query->orderBy('id'),
'variants.definitions.itemAttribute.attribute', 'variants.definitions.itemAttribute.attribute',
'bundleComponents.catalogItem.inventory', 'bundleComponents.catalogItem.inventory',
@@ -217,6 +230,7 @@ class CatalogService
'variants.inventory', 'variants.inventory',
'variants.attachments', 'variants.attachments',
'variants.eventDate', 'variants.eventDate',
'variants.eventDates',
'variants.definitions.itemAttribute.attribute', 'variants.definitions.itemAttribute.attribute',
'bundleComponents.catalogItem', 'bundleComponents.catalogItem',
'bundleComponents.variant.catalogItem', 'bundleComponents.variant.catalogItem',
@@ -250,6 +264,7 @@ class CatalogService
'variants.inventory', 'variants.inventory',
'variants.attachments', 'variants.attachments',
'variants.eventDate', 'variants.eventDate',
'variants.eventDates',
'variants.definitions.itemAttribute.attribute', 'variants.definitions.itemAttribute.attribute',
'bundleComponents.catalogItem', 'bundleComponents.catalogItem',
'bundleComponents.variant.catalogItem', 'bundleComponents.variant.catalogItem',
@@ -435,11 +450,13 @@ class CatalogService
/** /**
* @param array<int, string> $attributeCodes * @param array<int, string> $attributeCodes
* @param array<int, string> $multiSelectAttributeCodes
* @return array<string, ItemAttribute> * @return array<string, ItemAttribute>
*/ */
private function createItemAttributes( private function createItemAttributes(
CatalogItem $catalogItem, CatalogItem $catalogItem,
array $attributeCodes, array $attributeCodes,
array $multiSelectAttributeCodes = [],
): array { ): array {
$itemAttributes = []; $itemAttributes = [];
$attributeCodes = array_values(array_unique($attributeCodes)); $attributeCodes = array_values(array_unique($attributeCodes));
@@ -462,6 +479,7 @@ class CatalogService
$itemAttribute = $catalogItem->itemAttributes()->create([ $itemAttribute = $catalogItem->itemAttributes()->create([
'attribute_id' => $attribute->id, 'attribute_id' => $attribute->id,
'allow_multi_select' => in_array($attributeCode, $multiSelectAttributeCodes, true),
]); ]);
$itemAttributes[$attributeCode] = $itemAttribute; $itemAttributes[$attributeCode] = $itemAttribute;
@@ -495,28 +513,49 @@ class CatalogService
} }
$inventory = $this->createInventory((int) ($data['real_stock'] ?? 0)); $inventory = $this->createInventory((int) ($data['real_stock'] ?? 0));
$eventDateId = $data['event_date_id'] ?? null; $eventDateIds = collect($data['event_date_ids'] ?? [])
->when(
if ( isset($data['event_date_id']),
$eventDateId !== null fn ($ids) => $ids->push($data['event_date_id']),
&& (
! EventDate::query()
->whereKey($eventDateId)
->where('tenant_code', $catalogItem->tenant_code)
->exists()
) )
) { ->filter(fn ($id): bool => $id !== null)
->map(fn ($id): int => (int) $id)
->unique()
->sort()
->values();
$eventDateItemAttribute = $itemAttributes['event_date'] ?? null;
if ($eventDateItemAttribute !== null && (
$eventDateIds->isEmpty()
|| (! $eventDateItemAttribute->allow_multi_select && $eventDateIds->count() !== 1)
)) {
throw ValidationException::withMessages([ throw ValidationException::withMessages([
"variants.{$index}.event_date_id" => [ "variants.{$index}.event_date_ids" => [
'The event date must belong to the catalog item tenant.', $eventDateItemAttribute->allow_multi_select
? 'At least one event date must be selected.'
: 'Exactly one event date must be selected.',
],
]);
}
$validEventDateCount = EventDate::query()
->whereKey($eventDateIds)
->where('tenant_code', $catalogItem->tenant_code)
->count();
if ($validEventDateCount !== $eventDateIds->count()) {
throw ValidationException::withMessages([
"variants.{$index}.event_date_ids" => [
'Every event date must belong to the catalog item tenant.',
], ],
]); ]);
} }
$variant = $catalogItem->variants()->create([ $variant = $catalogItem->variants()->create([
'inventory_id' => $inventory->id, 'inventory_id' => $inventory->id,
'event_date_id' => $eventDateId, 'event_date_id' => $eventDateIds->count() === 1 ? $eventDateIds->first() : null,
]); ]);
$variant->eventDates()->sync($eventDateIds->all());
$variant->setRelation('catalogItem', $catalogItem); $variant->setRelation('catalogItem', $catalogItem);
foreach ($data['values'] ?? [] as $attributeCode => $value) { foreach ($data['values'] ?? [] as $attributeCode => $value) {
@@ -566,7 +605,17 @@ class CatalogService
sort($attributeCodes); sort($attributeCodes);
foreach (array_values($variants) as $index => $variant) { foreach (array_values($variants) as $index => $variant) {
$combination = [(string) ($variant['event_date_id'] ?? '')]; $eventDateIds = collect($variant['event_date_ids'] ?? [])
->when(
isset($variant['event_date_id']),
fn ($ids) => $ids->push($variant['event_date_id']),
)
->map(fn ($id): int => (int) $id)
->unique()
->sort()
->values()
->implode(',');
$combination = [$eventDateIds];
foreach ($attributeCodes as $attributeCode) { foreach ($attributeCodes as $attributeCode) {
$value = trim((string) ($variant['values'][$attributeCode] ?? '')); $value = trim((string) ($variant['values'][$attributeCode] ?? ''));

View File

@@ -44,6 +44,7 @@ class FeaturedGroupService
'variants.inventory', 'variants.inventory',
'variants.attachments', 'variants.attachments',
'variants.eventDate', 'variants.eventDate',
'variants.eventDates',
'variants.definitions.itemAttribute.attribute', 'variants.definitions.itemAttribute.attribute',
'bundleComponents.catalogItem', 'bundleComponents.catalogItem',
'bundleComponents.variant.catalogItem', 'bundleComponents.variant.catalogItem',

View File

@@ -9,6 +9,7 @@ use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
@@ -43,6 +44,17 @@ class EventDate extends Model
return $this->hasMany(Variant::class); return $this->hasMany(Variant::class);
} }
/** @return BelongsToMany<Variant, $this> */
public function selectedByVariants(): BelongsToMany
{
return $this->belongsToMany(
Variant::class,
'variant_event_dates',
'event_date_id',
'variant_id',
);
}
public function startsAt(): CarbonInterface public function startsAt(): CarbonInterface
{ {
return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_start); return Carbon::parse($this->date->format('Y-m-d').' '.$this->time_start);

View File

@@ -98,14 +98,28 @@ class PurchaseItemResource extends JsonResource
return []; return [];
} }
return $variant->definitions $attributes = $variant->definitions
->map(fn ($definition): array => [ ->map(fn ($definition): array => [
'name' => (string) ($definition->itemAttribute?->attribute?->nombre ?? ''), 'name' => (string) ($definition->itemAttribute?->attribute?->nombre ?? ''),
'value' => $definition->value, 'value' => $definition->value,
]) ])
->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null) ->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
->values() ->values();
->all();
$eventDates = $variant->relationLoaded('eventDates')
? $variant->selectedEventDates()
: collect();
if ($eventDates->isNotEmpty()) {
$attributes->prepend([
'name' => 'Fecha',
'value' => $eventDates
->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))
->values()
->all(),
]);
}
return $attributes->all();
} }
private function formatMoney(float|int|string|null $amount): string private function formatMoney(float|int|string|null $amount): string

View File

@@ -53,13 +53,25 @@ class PurchaseItemSnapshotFactory
/** @return array<int, array{name: string, value: mixed}> */ /** @return array<int, array{name: string, value: mixed}> */
private function snapshotAttributes(Variant $variant): array private function snapshotAttributes(Variant $variant): array
{ {
return $variant->definitions $attributes = $variant->definitions
->map(fn ($definition): array => [ ->map(fn ($definition): array => [
'name' => (string) ($definition->itemAttribute?->attribute?->nombre ?? ''), 'name' => (string) ($definition->itemAttribute?->attribute?->nombre ?? ''),
'value' => $definition->value, 'value' => $definition->value,
]) ])
->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null) ->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null)
->values() ->values();
->all();
$eventDates = $variant->selectedEventDates();
if ($eventDates->isNotEmpty()) {
$attributes->prepend([
'name' => 'Fecha',
'value' => $eventDates
->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))
->values()
->all(),
]);
}
return $attributes->all();
} }
} }

View File

@@ -278,6 +278,8 @@ class StartCheckoutService
'variant.attachments', 'variant.attachments',
'variant.catalogItem', 'variant.catalogItem',
'variant.definitions.itemAttribute.attribute', 'variant.definitions.itemAttribute.attribute',
'variant.eventDates',
'variant.eventDate',
]); ]);
} }

View File

@@ -5,6 +5,7 @@ namespace App\Domains\Ticket\Services;
use App\Domains\Auth\Models\User; use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant; use App\Domains\Catalog\Models\Variant;
use App\Domains\Event\Models\EventDate;
use App\Domains\Ticket\Enums\ValidityTimeType; use App\Domains\Ticket\Enums\ValidityTimeType;
use App\Domains\Ticket\Exceptions\TicketGenerationException; use App\Domains\Ticket\Exceptions\TicketGenerationException;
use App\Domains\Ticket\Models\Ticket; use App\Domains\Ticket\Models\Ticket;
@@ -44,9 +45,11 @@ class TicketGeneratorService
): Ticket { ): Ticket {
$item = $target['catalog_item']; $item = $target['catalog_item'];
$variant = $target['variant']; $variant = $target['variant'];
$eventDate = $target['event_date'];
$validityTime = $this->resolveValidityTime($item, $variant); $validityTime = $this->resolveValidityTime($item, $variant);
$validityTime = $this->materializeEventDateValidityTime( $validityTime = $this->materializeEventDateValidityTime(
$variant, $variant,
$eventDate,
$validityTime, $validityTime,
$fixedValidityTimes, $fixedValidityTimes,
); );
@@ -68,7 +71,7 @@ class TicketGeneratorService
} }
/** /**
* @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null}> * @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null, event_date: EventDate|null}>
*/ */
private function resolveTargets( private function resolveTargets(
CatalogItem $catalogItem, CatalogItem $catalogItem,
@@ -79,10 +82,7 @@ class TicketGeneratorService
$variant = $this->resolveVariant($catalogItem, $sourceVariantId); $variant = $this->resolveVariant($catalogItem, $sourceVariantId);
$this->validateTarget($catalogItem, $variant); $this->validateTarget($catalogItem, $variant);
return Collection::times($quantity, fn (): array => [ return $this->targetsForVariant($catalogItem, $variant, $quantity);
'catalog_item' => $catalogItem,
'variant' => $variant,
]);
} }
$catalogItem->loadMissing([ $catalogItem->loadMissing([
@@ -100,17 +100,46 @@ class TicketGeneratorService
$variant = $component->variant; $variant = $component->variant;
$this->validateTarget($componentItem, $variant); $this->validateTarget($componentItem, $variant);
return Collection::times( return $this->targetsForVariant(
$componentItem,
$variant,
$quantity * $component->quantity, $quantity * $component->quantity,
fn (): array => [
'catalog_item' => $componentItem,
'variant' => $variant,
],
); );
}) })
->values(); ->values();
} }
/**
* @return Collection<int, array{catalog_item: CatalogItem, variant: Variant|null, event_date: EventDate|null}>
*/
private function targetsForVariant(
CatalogItem $catalogItem,
?Variant $variant,
int $quantity,
): Collection {
if ($variant === null) {
return Collection::times($quantity, fn (): array => [
'catalog_item' => $catalogItem,
'variant' => null,
'event_date' => null,
]);
}
$variant->loadMissing(['eventDates', 'eventDate']);
$selectedEventDates = $variant->selectedEventDates();
$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();
}
private function resolveVariant( private function resolveVariant(
CatalogItem $catalogItem, CatalogItem $catalogItem,
?int $sourceVariantId, ?int $sourceVariantId,
@@ -185,32 +214,29 @@ class TicketGeneratorService
*/ */
private function materializeEventDateValidityTime( private function materializeEventDateValidityTime(
?Variant $variant, ?Variant $variant,
?EventDate $eventDate,
?ValidityTime $validityTime, ?ValidityTime $validityTime,
array &$fixedValidityTimes, array &$fixedValidityTimes,
): ?ValidityTime { ): ?ValidityTime {
if ( if (
$variant === null $variant === null
|| $validityTime === null || $eventDate === null
|| $validityTime->type !== ValidityTimeType::TimeWindow
) { ) {
return $validityTime; return $validityTime;
} }
$variant->loadMissing('eventDate'); if ($validityTime !== null && $validityTime->type !== ValidityTimeType::TimeWindow) {
$eventDate = $variant->eventDate;
if ($eventDate === null) {
return $validityTime; return $validityTime;
} }
$cacheKey = $eventDate->getKey().':'.$validityTime->getKey(); $cacheKey = $eventDate->getKey().':'.($validityTime?->getKey() ?? 'event');
if (isset($fixedValidityTimes[$cacheKey])) { if (isset($fixedValidityTimes[$cacheKey])) {
return $fixedValidityTimes[$cacheKey]; return $fixedValidityTimes[$cacheKey];
} }
$startsAt = $validityTime->startsAt($eventDate->date); $startsAt = $validityTime?->startsAt($eventDate->date) ?? $eventDate->startsAt();
$expiresAt = $validityTime->expiresAt($eventDate->date); $expiresAt = $validityTime?->expiresAt($eventDate->date) ?? $eventDate->endsAt();
if ( if (
$startsAt !== null $startsAt !== null

View File

@@ -0,0 +1,42 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('item_attributes', function (Blueprint $table): void {
$table->boolean('allow_multi_select')->default(false)->after('attribute_id');
});
Schema::create('variant_event_dates', function (Blueprint $table): void {
$table->foreignId('variant_id')->constrained('variantes')->cascadeOnDelete();
$table->foreignId('event_date_id')->constrained('event_dates')->cascadeOnDelete();
$table->primary(['variant_id', 'event_date_id']);
$table->index(['event_date_id', 'variant_id']);
});
DB::table('variantes')
->whereNotNull('event_date_id')
->orderBy('id')
->each(function (object $variant): void {
DB::table('variant_event_dates')->insertOrIgnore([
'variant_id' => $variant->id,
'event_date_id' => $variant->event_date_id,
]);
});
}
public function down(): void
{
Schema::dropIfExists('variant_event_dates');
Schema::table('item_attributes', function (Blueprint $table): void {
$table->dropColumn('allow_multi_select');
});
}
};

View File

@@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('variant_values', function (Blueprint $table): void {
$table->dropUnique('variant_values_variant_id_item_attribute_id_unique');
});
}
public function down(): void
{
Schema::table('variant_values', function (Blueprint $table): void {
$table->unique(['variant_id', 'item_attribute_id']);
});
}
};

View File

@@ -104,7 +104,14 @@ class AttributeSeeder extends Seeder
{ {
Attribute::query() Attribute::query()
->where('tenant_codigo', $tenant->codigo) ->where('tenant_codigo', $tenant->codigo)
->whereIn('codigo', ['talle_numerico', 'fecha']) ->whereNotIn('codigo', [
'event_date',
'servicio',
'color',
'horario',
'talle',
'tipo_alojamiento',
])
->delete(); ->delete();
$this->seedAttribute($tenant, [ $this->seedAttribute($tenant, [
@@ -118,6 +125,17 @@ class AttributeSeeder extends Seeder
$lunchValidityTime = $this->timeWindow('12:00:00', '15:00:00'); $lunchValidityTime = $this->timeWindow('12:00:00', '15:00:00');
$dinnerValidityTime = $this->timeWindow('20:00:00', '24:00:00'); $dinnerValidityTime = $this->timeWindow('20:00:00', '24:00:00');
$this->seedAttribute($tenant, [
'codigo' => 'tipo_alojamiento',
'nombre' => 'TipoAlojamiento',
'type' => FieldType::Select->value,
'is_required' => true,
'options' => [
['value' => 'Carpa', 'label' => 'Carpa', 'sort_order' => 1],
['value' => 'Motorhome', 'label' => 'Motorhome', 'sort_order' => 2],
],
]);
$this->seedAttribute($tenant, [ $this->seedAttribute($tenant, [
'codigo' => 'servicio', 'codigo' => 'servicio',
'nombre' => 'Servicio', 'nombre' => 'Servicio',

View File

@@ -2,7 +2,6 @@
namespace Database\Seeders; namespace Database\Seeders;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\EventProductType; use App\Domains\Catalog\Enums\EventProductType;
use App\Domains\Catalog\Enums\FeaturedGroupSource; use App\Domains\Catalog\Enums\FeaturedGroupSource;
use App\Domains\Catalog\Enums\GroupLayout; use App\Domains\Catalog\Enums\GroupLayout;
@@ -13,9 +12,8 @@ use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\FeaturedGroup; use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Services\CatalogService; use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\ValidityTimeType;
use App\Domains\Ticket\Models\ValidityTime;
use Illuminate\Database\Seeder; use Illuminate\Database\Seeder;
use Illuminate\Support\Collection;
use RuntimeException; use RuntimeException;
class FiestaFutbolInfantilProductSeeder extends Seeder class FiestaFutbolInfantilProductSeeder extends Seeder
@@ -32,141 +30,82 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
$this->deleteExistingCatalog($tenant); $this->deleteExistingCatalog($tenant);
FeaturedGroup::query()->where('tenant_code', $tenant->codigo)->delete(); FeaturedGroup::query()->where('tenant_code', $tenant->codigo)->delete();
Category::query() Category::query()->where('tenant_code', $tenant->codigo)->update(['categoria_id' => null]);
->where('tenant_code', $tenant->codigo)
->update(['categoria_id' => null]);
Category::query()->where('tenant_code', $tenant->codigo)->delete(); Category::query()->where('tenant_code', $tenant->codigo)->delete();
$tenant->update([ $tenant->update([
'event_title' => 'Fiesta Nacional del Fútbol Infantil', 'event_title' => 'Fiesta Nacional del Fútbol Infantil',
'event_location' => 'Sunchales, Santa Fe', 'event_location' => 'Sunchales, Santa Fe',
]); ]);
$tenant->eventDates()->delete(); $tenant->eventDates()->delete();
$eventDates = collect(['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12']) $eventDates = collect(['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'])
->mapWithKeys(function (string $date) use ($tenant): array { ->map(fn (string $date) => $tenant->eventDates()->create([
$eventDate = $tenant->eventDates()->create([ 'date' => $date,
'date' => $date, 'time_start' => '00:00:00',
'time_start' => '00:00:00', 'time_end' => '23:59:59',
'time_end' => '23:59:59', ]));
]); $dateIds = $eventDates->pluck('id')->map(fn ($id): int => (int) $id)->values();
return [$date => $eventDate]; $this->createProduct($tenant, [
}); 'slug' => 'camiseta',
'nombre' => 'Camiseta',
$ticketCategory = Category::query()->firstOrCreate([ 'precio' => 18000,
'nombre' => 'Entradas', 'attribute_codes' => ['color', 'talle'],
'tenant_code' => $tenant->codigo, 'variants' => collect(['Verde', 'Blanco'])
]); ->crossJoin(['14', 'S', 'M', 'L', 'XL', 'XXL'])
$accommodationCategory = Category::query()->firstOrCreate([ ->map(fn (array $values): array => [
'nombre' => 'Alojamientos',
'tenant_code' => $tenant->codigo,
]);
$merchandisingCategory = Category::query()->firstOrCreate([
'nombre' => 'Merchandising',
'tenant_code' => $tenant->codigo,
]);
$foodCategory = Category::query()->firstOrCreate([
'nombre' => 'Comida',
'tenant_code' => $tenant->codigo,
]);
$dates = $eventDates->keys()->all();
$minimumUseDate = $dates[0].' 00:00:00';
$maximumUseDate = $dates[array_key_last($dates)].' 23:59:59';
$eventValidityTime = ValidityTime::query()->firstOrCreate([
'type' => ValidityTimeType::FixedWindow,
'fixed_starts_at' => $minimumUseDate,
'fixed_expires_at' => $maximumUseDate,
]);
$generalAdmission = $this->catalogService->create([
'tenant_code' => $tenant->codigo,
'event_product_type' => EventProductType::Entry->value,
'category_id' => $ticketCategory->id,
'slug' => 'entrada-general',
'nombre' => 'Entrada General',
'descripcion' => 'Acceso total al predio. No incluye acceso a estacionamiento. Niños menores de 5 años ingresan gratis.',
'precio' => 10000,
'inventory_policy' => InventoryPolicy::Unlimited->value,
'has_tickets' => true,
'validity_time_id' => $eventValidityTime->id,
'attribute_codes' => ['event_date'],
'variants' => array_map(
fn (string $date): array => [
'real_stock' => 0, 'real_stock' => 0,
'event_date_id' => $eventDates->get($date)->id, 'values' => ['color' => $values[0], 'talle' => $values[1]],
], ])->all(),
$dates,
),
]); ]);
$items = [ $this->createProduct($tenant, [
['slug' => 'alojamiento-por-noche', 'nombre' => 'Alojamiento por noche', 'precio' => 35000, 'category_id' => $accommodationCategory->id], 'slug' => 'alojamiento',
['slug' => 'alojamiento-fin-de-semana', 'nombre' => 'Alojamiento fin de semana', 'precio' => 90000, 'category_id' => $accommodationCategory->id], 'nombre' => 'Alojamiento',
['slug' => 'remera-oficial', 'nombre' => 'Remera oficial', 'precio' => 18000, 'category_id' => $merchandisingCategory->id], 'precio' => 35000,
['slug' => 'gorra-oficial', 'nombre' => 'Gorra oficial', 'precio' => 12000, 'category_id' => $merchandisingCategory->id], 'attribute_codes' => ['tipo_alojamiento'],
['slug' => 'hamburguesa-papa-frita', 'nombre' => 'Hamburguesa con papa frita', 'precio' => 8000, 'category_id' => $foodCategory->id], 'variants' => collect(['Carpa', 'Motorhome'])->map(fn (string $type): array => [
['slug' => 'pancho', 'nombre' => 'Pancho', 'precio' => 4000, 'category_id' => $foodCategory->id],
];
$createdItems = [];
foreach ($items as $item) {
$createdItems[$item['slug']] = $this->catalogService->create([
'tenant_code' => $tenant->codigo,
'event_product_type' => EventProductType::Product->value,
'descripcion' => $item['descripcion'] ?? $item['nombre'],
'inventory_policy' => InventoryPolicy::Unlimited->value,
'real_stock' => 0, 'real_stock' => 0,
'validity_time_id' => $eventValidityTime->id, 'values' => ['tipo_alojamiento' => $type],
...$item, ])->all(),
]); ]);
}
$this->catalogService->create([ $this->createProduct($tenant, [
'tenant_code' => $tenant->codigo, 'slug' => 'comida',
'event_product_type' => EventProductType::Entry->value, 'nombre' => 'Comida',
'type' => CatalogItemType::Bundle->value, 'precio' => 8000,
'slug' => 'entrada-general-todos-los-dias', 'attribute_codes' => ['event_date', 'horario', 'servicio'],
'nombre' => 'Entrada General - Todos los días', 'variants' => $dateIds
'descripcion' => 'Incluye una entrada para cada día de la Fiesta Nacional del Fútbol Infantil.', ->crossJoin(['Desayuno', 'Almuerzo', 'Cena'], ['Comedor', 'Vianda'])
->map(fn (array $values): array => [
'real_stock' => 0,
'event_date_ids' => [(int) $values[0]],
'values' => ['horario' => $values[1], 'servicio' => $values[2]],
])->all(),
]);
$this->createProduct($tenant, [
'slug' => 'abono',
'nombre' => 'Abono',
'precio' => 40000, 'precio' => 40000,
'category_id' => $ticketCategory->id, 'event_product_type' => EventProductType::Entry->value,
'components' => $generalAdmission->variants 'has_tickets' => true,
->map(fn ($variant): array => [ 'attribute_codes' => ['event_date'],
'catalog_item_id' => $generalAdmission->id, 'multi_select_attribute_codes' => ['event_date'],
'variant_id' => $variant->id, 'variants' => $this->nonEmptySubsets($dateIds)
'quantity' => 1, ->map(fn (array $ids): array => ['real_stock' => 0, 'event_date_ids' => $ids])
])
->all(), ->all(),
]); ]);
$this->catalogService->create([ FeaturedGroup::query()->create([
'tenant_code' => $tenant->codigo, 'tenant_code' => $tenant->codigo,
'event_product_type' => EventProductType::Product->value, 'source_type' => FeaturedGroupSource::All,
'type' => CatalogItemType::Bundle->value, 'category_id' => null,
'slug' => 'combo-2-panchos-2-hamburguesas', 'product_layout' => ProductLayout::ColumnWithCart,
'nombre' => 'Combo 2 Panchos + 2 Hamburguesas', 'group_layout' => GroupLayout::Simple,
'descripcion' => 'Incluye 2 panchos y 2 hamburguesas con papa frita.', 'group_name' => 'Productos',
'precio' => 24000, 'group_order' => 0,
'category_id' => $foodCategory->id,
'components' => [
[
'catalog_item_id' => $createdItems['pancho']->id,
'quantity' => 2,
],
[
'catalog_item_id' => $createdItems['hamburguesa-papa-frita']->id,
'quantity' => 2,
],
],
]);
$this->seedFeaturedGroups($tenant, [
'Entradas' => $ticketCategory,
'Alojamientos' => $accommodationCategory,
'Merchandising' => $merchandisingCategory,
'Comida' => $foodCategory,
]); ]);
} }
@@ -174,49 +113,40 @@ class FiestaFutbolInfantilProductSeeder extends Seeder
{ {
CatalogItem::query() CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->where('type', CatalogItemType::Bundle->value) ->orderByRaw("CASE WHEN type = 'bundle' THEN 0 ELSE 1 END")
->each(fn (CatalogItem $item) => $this->catalogService->delete($item));
CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('type', CatalogItemType::Standard->value)
->each(fn (CatalogItem $item) => $this->catalogService->delete($item)); ->each(fn (CatalogItem $item) => $this->catalogService->delete($item));
} }
/** @param array<string, Category> $categories */ /** @param array<string, mixed> $data */
private function seedFeaturedGroups(Tenant $tenant, array $categories): void private function createProduct(Tenant $tenant, array $data): CatalogItem
{ {
$groups = [ return $this->catalogService->create([
'Entradas' => [ 'tenant_code' => $tenant->codigo,
'product_layout' => ProductLayout::Row, 'event_product_type' => EventProductType::Product->value,
'group_layout' => GroupLayout::SimpleVertical, 'descripcion' => $data['nombre'],
], 'inventory_policy' => InventoryPolicy::Unlimited->value,
'Alojamientos' => [ ...$data,
'product_layout' => ProductLayout::ColumnWithCart, ]);
'group_layout' => GroupLayout::Simple, }
],
'Merchandising' => [
'product_layout' => ProductLayout::ColumnWithCart,
'group_layout' => GroupLayout::Simple,
],
'Comida' => [
'product_layout' => ProductLayout::ColumnWithCart,
'group_layout' => GroupLayout::Simple,
],
];
$groupOrder = 0; /** @return Collection<int, array<int, int>> */
foreach ($groups as $groupName => $config) { private function nonEmptySubsets(Collection $values): Collection
FeaturedGroup::query()->create([ {
'tenant_code' => $tenant->codigo, $items = $values->all();
'source_type' => FeaturedGroupSource::Category, $subsets = collect();
'category_id' => $categories[$groupName]->id,
'product_layout' => $config['product_layout'],
'group_layout' => $config['group_layout'],
'group_name' => $groupName,
'group_order' => $groupOrder++,
]);
for ($mask = 1; $mask < (1 << count($items)); $mask++) {
$subset = [];
foreach ($items as $index => $item) {
if (($mask & (1 << $index)) !== 0) {
$subset[] = $item;
}
}
$subsets->push($subset);
} }
return $subsets
->sortBy(fn (array $subset): string => count($subset).':'.implode(',', $subset))
->values();
} }
} }

View File

@@ -136,6 +136,42 @@ class CatalogServiceTest extends TestCase
); );
} }
public function test_it_creates_a_variant_with_multiple_event_dates(): void
{
$eventDateAttribute = $this->createAttribute('event_date', FieldType::EventDate);
$firstDate = $this->tenant->eventDates()->create([
'date' => '2026-10-09',
'time_start' => '00:00:00',
'time_end' => '23:59:59',
]);
$secondDate = $this->tenant->eventDates()->create([
'date' => '2026-10-10',
'time_start' => '00:00:00',
'time_end' => '23:59:59',
]);
$item = $this->service->create([
'tenant_code' => $this->tenant->codigo,
'slug' => 'multi-date-pass',
'nombre' => 'Multi-date pass',
'precio' => 100,
'attribute_codes' => [$eventDateAttribute->codigo],
'multi_select_attribute_codes' => ['event_date'],
'variants' => [[
'real_stock' => 5,
'event_date_ids' => [$secondDate->id, $firstDate->id],
]],
]);
$variant = $item->variants->sole();
$this->assertNull($variant->event_date_id);
$this->assertSame([$firstDate->id, $secondDate->id], $variant->eventDates->pluck('id')->all());
$this->assertSame(
[(string) $firstDate->id, (string) $secondDate->id],
$variant->selectionValues()->get('event_date'),
);
}
public function test_it_rejects_duplicate_variant_combinations(): void public function test_it_rejects_duplicate_variant_combinations(): void
{ {
$sector = $this->createAttribute('sector'); $sector = $this->createAttribute('sector');

View File

@@ -4,20 +4,12 @@ namespace Tests\Feature\Seeders;
use App\Domains\Attachable\Enums\AttachmentType; use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment; use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Enums\EventProductType;
use App\Domains\Catalog\Enums\FeaturedGroupSource; use App\Domains\Catalog\Enums\FeaturedGroupSource;
use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Catalog\Models\Attribute; use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\CatalogItem; use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category; use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\FeaturedGroup; use App\Domains\Catalog\Models\FeaturedGroup;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Event\Models\EventDate;
use App\Domains\Shared\Enums\FieldType;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\ValidityTimeType;
use Database\Seeders\AttributeSeeder; use Database\Seeders\AttributeSeeder;
use Database\Seeders\FiestaFutbolInfantilProductSeeder; use Database\Seeders\FiestaFutbolInfantilProductSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -27,21 +19,10 @@ class FiestaFutbolInfantilProductSeederTest extends TestCase
{ {
use RefreshDatabase; use RefreshDatabase;
public function test_it_seeds_event_items_for_the_new_catalog(): void public function test_it_seeds_the_category_free_configurable_catalog(): void
{ {
$headerLogo = Attachment::query()->create([ $headerLogo = $this->attachment('header');
'path' => 'tests/header.png', $footerLogo = $this->attachment('footer');
'filename' => 'header.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
$footerLogo = Attachment::query()->create([
'path' => 'tests/footer.png',
'filename' => 'footer.png',
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
$tenant = Tenant::query()->create([ $tenant = Tenant::query()->create([
'codigo' => 'fiesta_futbol_infantil', 'codigo' => 'fiesta_futbol_infantil',
'nombre' => 'Fiesta Fútbol Infantil', 'nombre' => 'Fiesta Fútbol Infantil',
@@ -56,189 +37,55 @@ class FiestaFutbolInfantilProductSeederTest extends TestCase
'footer_logo_id' => $footerLogo->id, 'footer_logo_id' => $footerLogo->id,
]); ]);
$this->seed([ $this->seed([AttributeSeeder::class, FiestaFutbolInfantilProductSeeder::class]);
AttributeSeeder::class, $this->seed([AttributeSeeder::class, FiestaFutbolInfantilProductSeeder::class]);
FiestaFutbolInfantilProductSeeder::class,
]);
$this->seed([
AttributeSeeder::class,
FiestaFutbolInfantilProductSeeder::class,
]);
$attributes = Attribute::query()
->where('tenant_codigo', $tenant->codigo)
->with('options.validityTime')
->orderBy('id')
->get();
$this->assertSame( $this->assertSame(
['event_date', 'servicio', 'color', 'horario', 'talle'], ['color', 'event_date', 'horario', 'servicio', 'talle', 'tipo_alojamiento'],
$attributes->pluck('codigo')->all(), Attribute::query()->where('tenant_codigo', $tenant->codigo)->orderBy('codigo')->pluck('codigo')->all(),
); );
$this->assertSame(FieldType::EventDate, $attributes[0]->type); $this->assertSame(0, Category::query()->where('tenant_code', $tenant->codigo)->count());
$this->assertEmpty($attributes[0]->options);
$this->assertSame(['Comedor', 'Vianda'], $attributes[1]->options->pluck('value')->all());
$this->assertSame(['Verde', 'Blanco'], $attributes[2]->options->pluck('value')->all());
$this->assertSame(['Desayuno', 'Almuerzo', 'Cena'], $attributes[3]->options->pluck('value')->all());
$this->assertSame(['14', 'S', 'M', 'L', 'XL', 'XXL'], $attributes[4]->options->pluck('value')->all());
$this->assertSame( $this->assertSame(
[ ['abono', 'alojamiento', 'camiseta', 'comida'],
['Desayuno', ValidityTimeType::TimeWindow, '07:00:00', '12:00:00'], CatalogItem::query()->where('tenant_code', $tenant->codigo)->orderBy('slug')->pluck('slug')->all(),
['Almuerzo', ValidityTimeType::TimeWindow, '12:00:00', '15:00:00'],
['Cena', ValidityTimeType::TimeWindow, '20:00:00', '24:00:00'],
],
$attributes[3]->options
->map(fn ($option): array => [
$option->value,
$option->validityTime->type,
$option->validityTime->start_time,
$option->validityTime->end_time,
])
->all(),
); );
$tenant->refresh()->load('eventDates'); $expectedVariantCounts = [
$this->assertSame('Fiesta Nacional del Fútbol Infantil', $tenant->event_title); 'camiseta' => 12,
$this->assertSame('Sunchales, Santa Fe', $tenant->event_location); 'alojamiento' => 2,
$this->assertCount(4, $tenant->eventDates); 'comida' => 24,
$this->assertSame(4, EventDate::query()->where('tenant_code', $tenant->codigo)->count()); 'abono' => 15,
];
$generalAdmission = CatalogItem::query() foreach ($expectedVariantCounts as $slug => $count) {
->where('tenant_code', $tenant->codigo) $item = CatalogItem::query()->where('tenant_code', $tenant->codigo)->where('slug', $slug)->sole();
->where('slug', 'entrada-general') $this->assertCount($count, $item->variants);
->with('variants.eventDate', 'itemAttributes') $this->assertNull($item->category_id);
->sole();
$this->assertNull($generalAdmission->inventory_id);
$this->assertSame(EventProductType::Entry, $generalAdmission->event_product_type);
$this->assertCount(1, $generalAdmission->itemAttributes);
$this->assertCount(4, $generalAdmission->variants);
$this->assertEqualsCanonicalizing(
['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'],
$generalAdmission->variants
->map(fn ($variant) => $variant->eventDate->date->format('Y-m-d'))
->all()
);
$this->assertSame('2026-10-09 00:00:00', $generalAdmission->validityTime->fixed_starts_at->format('Y-m-d H:i:s'));
$this->assertSame('2026-10-12 23:59:59', $generalAdmission->validityTime->fixed_expires_at->format('Y-m-d H:i:s'));
$standardItems = CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('type', CatalogItemType::Standard->value)
->get();
$this->assertCount(7, $standardItems);
foreach ($standardItems as $standardItem) {
$this->assertSame(
'2026-10-09 00:00:00',
$standardItem->validityTime->fixed_starts_at->format('Y-m-d H:i:s'),
);
$this->assertSame(
'2026-10-12 23:59:59',
$standardItem->validityTime->fixed_expires_at->format('Y-m-d H:i:s'),
);
} }
$allDaysItem = CatalogItem::query() $abono = CatalogItem::query()
->where('tenant_code', $tenant->codigo) ->where('tenant_code', $tenant->codigo)
->where('nombre', 'Entrada General - Todos los días') ->where('slug', 'abono')
->with('bundleComponents.variant.eventDate') ->with('itemAttributes.attribute', 'variants.eventDates')
->sole(); ->sole();
$dateAttribute = $abono->itemAttributes->firstWhere('attribute.codigo', 'event_date');
$this->assertSame(CatalogItemType::Bundle, $allDaysItem->type); $this->assertTrue($dateAttribute->allow_multi_select);
$this->assertSame('40000.00', $allDaysItem->precio);
$this->assertNull($allDaysItem->inventory_id);
$this->assertFalse($allDaysItem->has_tickets);
$this->assertSame(EventProductType::Entry, $allDaysItem->event_product_type);
$this->assertCount(4, $allDaysItem->bundleComponents);
$this->assertEqualsCanonicalizing( $this->assertEqualsCanonicalizing(
['2026-10-09', '2026-10-10', '2026-10-11', '2026-10-12'], [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4],
$allDaysItem->bundleComponents $abono->variants->map(fn ($variant): int => $variant->eventDates->count())->all(),
->map(fn ($component) => $component->variant->eventDate->date->format('Y-m-d'))
->all()
); );
$foodCombo = CatalogItem::query() $featuredGroup = FeaturedGroup::query()->where('tenant_code', $tenant->codigo)->sole();
->where('tenant_code', $tenant->codigo) $this->assertSame(FeaturedGroupSource::All, $featuredGroup->source_type);
->where('nombre', 'Combo 2 Panchos + 2 Hamburguesas') $this->assertNull($featuredGroup->category_id);
->with('bundleComponents.catalogItem') }
->sole();
$this->assertSame(CatalogItemType::Bundle, $foodCombo->type); private function attachment(string $name): Attachment
$this->assertSame('24000.00', $foodCombo->precio); {
$this->assertNull($foodCombo->inventory_id); return Attachment::query()->create([
$this->assertSame(EventProductType::Product, $foodCombo->event_product_type); 'path' => "tests/{$name}.png",
$this->assertSame( 'filename' => "{$name}.png",
[ 'type' => AttachmentType::Image,
'hamburguesa-papa-frita' => 2, 'mime_type' => 'image/png',
'pancho' => 2, ]);
],
$foodCombo->bundleComponents
->mapWithKeys(fn ($component): array => [
$component->catalogItem->slug => $component->quantity,
])
->sortKeys()
->all()
);
$this->assertSame(9, CatalogItem::query()->where('tenant_code', $tenant->codigo)->count());
$this->assertSame(10, Inventory::query()->count());
$this->assertSame(
['Alojamientos', 'Comida', 'Entradas', 'Merchandising'],
Category::query()
->where('tenant_code', $tenant->codigo)
->orderBy('nombre')
->pluck('nombre')
->all(),
);
$this->assertSame(
'Merchandising',
CatalogItem::query()
->where('tenant_code', $tenant->codigo)
->where('slug', 'remera-oficial')
->with('category')
->sole()
->category
->nombre,
);
$featuredGroups = FeaturedGroup::query()
->where('tenant_code', $tenant->codigo)
->with('category.catalogItems')
->orderBy('group_order')
->get();
$this->assertSame(
[
'Entradas' => ['entrada-general', 'entrada-general-todos-los-dias'],
'Alojamientos' => ['alojamiento-por-noche', 'alojamiento-fin-de-semana'],
'Merchandising' => ['remera-oficial', 'gorra-oficial'],
'Comida' => ['hamburguesa-papa-frita', 'pancho', 'combo-2-panchos-2-hamburguesas'],
],
$featuredGroups
->mapWithKeys(fn (FeaturedGroup $group): array => [
$group->group_name => $group->category->catalogItems->pluck('slug')->all(),
])
->all()
);
$this->assertSame(
[
['Entradas', FeaturedGroupSource::Category, 'Entradas', ProductLayout::Row, GroupLayout::SimpleVertical, 0],
['Alojamientos', FeaturedGroupSource::Category, 'Alojamientos', ProductLayout::ColumnWithCart, GroupLayout::Simple, 1],
['Merchandising', FeaturedGroupSource::Category, 'Merchandising', ProductLayout::ColumnWithCart, GroupLayout::Simple, 2],
['Comida', FeaturedGroupSource::Category, 'Comida', ProductLayout::ColumnWithCart, GroupLayout::Simple, 3],
],
$featuredGroups
->map(fn (FeaturedGroup $group): array => [
$group->group_name,
$group->source_type,
$group->category->nombre,
$group->product_layout,
$group->group_layout,
$group->group_order,
])
->all()
);
} }
} }

View File

@@ -235,6 +235,31 @@ class TicketGeneratorServiceTest extends TestCase
$this->assertSame('2026-08-21 02:00:00', $fixedWindow->fixed_expires_at->format('Y-m-d H:i:s')); $this->assertSame('2026-08-21 02:00:00', $fixedWindow->fixed_expires_at->format('Y-m-d H:i:s'));
} }
public function test_a_multi_date_variant_generates_one_ticket_for_each_selected_date(): void
{
$item = $this->createTicketableItem('multi-date-pass');
$dates = collect(['2026-08-20', '2026-08-21'])->map(fn (string $date) => EventDate::query()->create([
'tenant_code' => $this->tenant->codigo,
'date' => $date,
'time_start' => '00:00:00',
'time_end' => '23:59:59',
]));
$variant = $item->variants()->create([
'inventory_id' => Inventory::query()->create()->id,
]);
$variant->eventDates()->sync($dates->pluck('id'));
$tickets = $this->service->generate($item, $this->user, 1, $variant->id);
$tickets->each->loadMissing('validityTime');
$this->assertCount(2, $tickets);
$this->assertSame(
['2026-08-20 00:00:00', '2026-08-21 00:00:00'],
$tickets->map(fn ($ticket): string => $ticket->validityTime->fixed_starts_at->format('Y-m-d H:i:s'))->all(),
);
$this->assertSame([$variant->id], $tickets->pluck('source_variant_id')->unique()->values()->all());
}
public function test_marking_a_purchase_as_paid_ignores_items_without_tickets(): void public function test_marking_a_purchase_as_paid_ignores_items_without_tickets(): void
{ {
Event::fake([TicketsAvailable::class]); Event::fake([TicketsAvailable::class]);