vacation-planner/app/Services/PeriodService.php
2026-11-28 12:59:18 +08:00

106 lines
3.5 KiB
PHP
Executable File

<?php
namespace App\Services;
use App\Models\Marker;
use App\Models\User;
use App\Models\VacationPeriod;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
class PeriodService
{
/**
* Add a date range for a marker, merging any overlapping or adjacent
* periods of the same marker into a single period.
*/
public function addRange(User $user, Marker $marker, CarbonImmutable $start, CarbonImmutable $end): VacationPeriod
{
return DB::transaction(function () use ($user, $marker, $start, $end) {
$neighbours = $marker->periods()
->where('start_date', '<=', $end->addDay()->toDateString())
->where('end_date', '>=', $start->subDay()->toDateString())
->get();
foreach ($neighbours as $neighbour) {
$start = $start->min(CarbonImmutable::parse($neighbour->start_date));
$end = $end->max(CarbonImmutable::parse($neighbour->end_date));
}
$neighbours->each->delete();
return VacationPeriod::create([
'user_id' => $user->id,
'marker_id' => $marker->id,
'start_date' => $start->toDateString(),
'end_date' => $end->toDateString(),
]);
});
}
/**
* Toggle a single day for a marker: remove it if already marked
* (splitting the period when the day is in the middle), otherwise
* mark it (merging with neighbouring periods).
*/
public function toggleDay(User $user, Marker $marker, CarbonImmutable $date): void
{
DB::transaction(function () use ($user, $marker, $date) {
$period = $marker->periods()
->where('start_date', '<=', $date->toDateString())
->where('end_date', '>=', $date->toDateString())
->first();
if ($period === null) {
$this->addRange($user, $marker, $date, $date);
return;
}
$start = CarbonImmutable::parse($period->start_date);
$end = CarbonImmutable::parse($period->end_date);
if ($start->equalTo($date) && $end->equalTo($date)) {
$period->delete();
return;
}
if ($start->equalTo($date)) {
$period->update(['start_date' => $date->addDay()->toDateString()]);
return;
}
if ($end->equalTo($date)) {
$period->update(['end_date' => $date->subDay()->toDateString()]);
return;
}
// Day is in the middle: split into two periods.
$period->update(['end_date' => $date->subDay()->toDateString()]);
VacationPeriod::create([
'user_id' => $user->id,
'marker_id' => $marker->id,
'start_date' => $date->addDay()->toDateString(),
'end_date' => $end->toDateString(),
]);
});
}
/**
* Replace a period's range (and optionally its marker) with a new one,
* merging with the target marker's neighbouring periods.
*/
public function reschedule(User $user, VacationPeriod $period, Marker $marker, CarbonImmutable $start, CarbonImmutable $end): VacationPeriod
{
return DB::transaction(function () use ($user, $period, $marker, $start, $end) {
$period->delete();
return $this->addRange($user, $marker, $start, $end);
});
}
}