sintonia_webapp/app/Traits/Show/ShowInstancesTrait.php
2025-04-02 23:44:01 +02:00

107 lines
No EOL
3.7 KiB
PHP

<?php
namespace App\Traits\Show;
use App\Helpers\CarbonShowRepetition;
use App\Helpers\LengthFormatter;
use App\Http\Resources\ShowResource;
use App\Models\Preference;
use App\Models\Show\Show;
use App\Models\ShowInstances\ShowInstances;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Exception;
trait ShowInstancesTrait
{
/**
* @throws Exception
*/
public function checkOverlappingInstances(array $instancesDates, $duration, int $showId): void
{
$existingRanges = ShowInstances::where('show_id', '!=', $showId)
->get(['starts', 'ends'])
->map(fn($i) => [$i->starts, $i->ends]);
foreach ($instancesDates as $date) {
$newStart = $date;
$newEnd = (clone $date)->addHours($duration);
$hasOverlap = $existingRanges->contains(
fn($range) => $newStart < $range[1] && $newEnd > $range[0]
);
if ($hasOverlap) {
throw new Exception("Overlap detected between $newStart and $newEnd");
}
}
}
public function createShowInstances($instancesDates, $showDayDuration, $showId)
{
$showInstances = [];
foreach ($instancesDates as $instanceDate) {
$showStartDate = $instanceDate->copy();
$duration = CarbonInterval::createFromFormat('H:i', $showDayDuration);
$showEndDate = $showStartDate->copy()->add($duration);
$timeFilled = LengthFormatter::generateStringTimeFilled($showStartDate, $showEndDate);
$now = Carbon::now()->format('Y-m-d H:i:s.u');
$showInstances[] = [
'starts' => $showStartDate,
'ends' => $showEndDate,
'show_id' => $showId,
'record' => 0,
'rebroadcast' => 0,
'time_filled' => $timeFilled,
'created' => $now,
'modified_instance' => false,
'autoplaylist_built' => false,
];
}
return $showInstances;
}
/**
*
* Based on the show days rules, set up the needed show instances
*
* @param ShowResource $ShowResource
*
* @return void
* @throws Exception
*/
public function manageShowInstances(Show $show)
{
try {
$generationLimitDate = Preference::where('keystr', 'shows_populated_until')->value('valstr');
$generationLimitDate = Carbon::createFromFormat('Y-m-d H:i:s', $generationLimitDate);
$showInstances = [];
foreach ($show->showDays as $showDay) {
try {
$lastShowDate = $showDay->last_show ?? $generationLimitDate;
$instancesDates = CarbonShowRepetition::generateDates(
$showDay->repeat_type,
$showDay->first_show,
$showDay->start_time,
$lastShowDate
);
$this->checkOverlappingInstances($instancesDates, $showDay->duration, $show->id);
$showInstances[] = $this->createShowInstances($instancesDates, $showDay->duration, $show->id);
} catch (Exception $e) {
throw new Exception($e->getMessage(), 500);
}
}
foreach ($showInstances as $showInstance) {
$show->showInstances()->createMany($showInstance);
}
} catch (Exception $e) {
throw new Exception($e->getMessage(), 500);
}
}
}