Skip to content

Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️

7.5 KB
Raw Blame
<?php

namespace HiEvents\Services\Domain\EventOccurrence;

use HiEvents\DomainObjects\Enums\ProductQuantityAppliesTo;
use HiEvents\DomainObjects\Enums\ProductType;
use HiEvents\DomainObjects\EventOccurrenceDomainObject;
use HiEvents\DomainObjects\EventSeatMapBandProductDomainObject;
use HiEvents\DomainObjects\EventSeatMapDomainObject;
use HiEvents\DomainObjects\Generated\ProductDomainObjectAbstract;
use HiEvents\DomainObjects\ProductDomainObject;
use HiEvents\DomainObjects\ProductPriceDomainObject;
use HiEvents\DomainObjects\ProductPriceOccurrenceOverrideDomainObject;
use HiEvents\Enterprise\Seating\Services\Domain\EventSeatMapLookupService;
use HiEvents\Repository\Eloquent\Value\OrderAndDirection;
use HiEvents\Repository\Interfaces\ProductPriceOccurrenceOverrideRepositoryInterface;
use HiEvents\Repository\Interfaces\ProductRepositoryInterface;
use HiEvents\Services\Domain\EventOccurrence\DTO\OccurrenceAllocationDTO;
use HiEvents\Services\Domain\EventOccurrence\DTO\OccurrenceBookingLimitsDTO;
use Illuminate\Support\Collection;

class OccurrenceBookingLimitsService
{
    public function __construct(
        private readonly ProductPriceOccurrenceOverrideRepositoryInterface $overrideRepository,
        private readonly ProductRepositoryInterface $productRepository,
        private readonly EventSeatMapLookupService $eventSeatMapLookup,
    ) {}

    /**
     * @param  Collection<EventOccurrenceDomainObject>  $occurrences
     */
    public function attachTo(Collection $occurrences, int $eventId): void
    {
        if ($occurrences->isEmpty()) {
            return;
        }

        $products = $this->productRepository
            ->loadRelation(ProductPriceDomainObject::class)
            ->findWhere(
                where: [ProductDomainObjectAbstract::EVENT_ID => $eventId],
                orderAndDirections: [
                    new OrderAndDirection(ProductDomainObjectAbstract::ORDER),
                    new OrderAndDirection(ProductDomainObjectAbstract::ID),
                ],
            );

        $limits = $this->forOccurrences($occurrences, $products, $this->eventSeatMapLookup->findForEvent($eventId));

        $occurrences->each(
            fn (EventOccurrenceDomainObject $occurrence) => $occurrence->setBookingLimits($limits[$occurrence->getId()] ?? null)
        );
    }

    /**
     * @param  Collection<EventOccurrenceDomainObject>  $occurrences
     * @param  Collection<ProductDomainObject>  $products  products with prices loaded
     * @return array<int, OccurrenceBookingLimitsDTO> keyed by occurrence id
     */
    private function forOccurrences(Collection $occurrences, Collection $products, ?EventSeatMapDomainObject $eventSeatMap): array
    {
        $bandLinks = $eventSeatMap?->getEventSeatMapBandProducts() ?? collect();
        $seatedProductIds = $bandLinks->map(fn (EventSeatMapBandProductDomainObject $link) => $link->getProductId())->unique()->all();
        $unseatedProducts = $seatedProductIds === []
            ? $products
            : $products->reject(fn (ProductDomainObject $product) => in_array($product->getId(), $seatedProductIds, true));
        $seatAllocations = $eventSeatMap === null ? [] : $this->seatAllocations($eventSeatMap, $bandLinks);

        $occurrenceIds = $occurrences->map(fn (EventOccurrenceDomainObject $occurrence) => $occurrence->getId())->all();

        $overrides = $occurrenceIds === []
            ? collect()
            : $this->overrideRepository->findWhereIn('event_occurrence_id', $occurrenceIds);

        $overridesByOccurrence = $overrides->groupBy(
            fn (ProductPriceOccurrenceOverrideDomainObject $override) => $override->getEventOccurrenceId()
        );

        $limits = [];
        foreach ($occurrences as $occurrence) {
            $limits[$occurrence->getId()] = $this->forOccurrence(
                $occurrence,
                $unseatedProducts,
                $seatAllocations,
                $overridesByOccurrence->get($occurrence->getId(), collect())
                    ->keyBy(fn (ProductPriceOccurrenceOverrideDomainObject $override) => $override->getProductPriceId()),
            );
        }

        return $limits;
    }

    /**
     * @param  OccurrenceAllocationDTO[]  $seatAllocations
     */
    private function forOccurrence(
        EventOccurrenceDomainObject $occurrence,
        Collection $products,
        array $seatAllocations,
        Collection $overridesByPrice,
    ): OccurrenceBookingLimitsDTO {
        $allocations = $seatAllocations;
        $allocationTotal = array_sum(array_map(fn (OccurrenceAllocationDTO $allocation) => $allocation->quantity, $seatAllocations));
        $uncapped = false;

        /** @var ProductDomainObject $product */
        foreach ($products as $product) {
            if ($product->getProductType() !== ProductType::TICKET->name) {
                continue;
            }

            $prices = ($product->getProductPrices() ?? collect())
                ->sortBy(fn (ProductPriceDomainObject $price) => $price->getOrder());

            /** @var ProductPriceDomainObject $price */
            foreach ($prices as $price) {
                $quantity = $this->allocationForDate($price, $overridesByPrice->get($price->getId()));

                if ($quantity === null) {
                    $uncapped = true;
                } else {
                    $allocationTotal += $quantity;
                }

                $allocations[] = new OccurrenceAllocationDTO(
                    product_price_id: $price->getId(),
                    product_title: $product->getTitle(),
                    price_label: $price->getLabel(),
                    quantity: $quantity,
                    applies_to: $price->getQuantityAppliesTo(),
                );
            }
        }

        $allocationTotal = $uncapped || $allocations === [] ? null : $allocationTotal;
        $capacity = $occurrence->getCapacity();
        $limits = array_filter([$capacity, $allocationTotal], fn (?int $value) => $value !== null);

        return new OccurrenceBookingLimitsDTO(
            capacity: $capacity,
            allocation_total: $allocationTotal,
            sellable: $limits === [] ? null : min($limits),
            allocations: $allocations,
        );
    }

    /**
     * @param  Collection<EventSeatMapBandProductDomainObject>  $bandLinks
     * @return OccurrenceAllocationDTO[]
     */
    private function seatAllocations(EventSeatMapDomainObject $eventSeatMap, Collection $bandLinks): array
    {
        $linkedBands = $bandLinks->map(fn (EventSeatMapBandProductDomainObject $link) => $link->getBandKey())->unique()->all();
        $capacityByBand = $this->eventSeatMapLookup->indexFor($eventSeatMap->getEventId())->capacityByBand();
        $bandNames = collect($eventSeatMap->getLayout()['bands'] ?? [])->pluck('name', 'key');

        return collect($linkedBands)
            ->map(fn (string $bandKey) => new OccurrenceAllocationDTO(
                product_price_id: null,
                product_title: __('Seats · :band', ['band' => $bandNames->get($bandKey, $bandKey)]),
                price_label: null,
                quantity: $capacityByBand[$bandKey] ?? 0,
                applies_to: ProductQuantityAppliesTo::OCCURRENCE->name,
            ))
            ->values()
            ->all();
    }

    private function allocationForDate(ProductPriceDomainObject $price, ?ProductPriceOccurrenceOverrideDomainObject $override): ?int
    {
        if (! $price->isQuantityPerOccurrence()) {
            return null;
        }

        return $override?->getQuantityAvailable() ?? $price->getInitialQuantityAvailable();
    }
}