Files
fewo-stommer/app/Actions/CreateChannelTasks.php
T
Lars 783068501c
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m33s
Generische iCal-Kanäle mit Bestandsklärung und sicheren Exporten bereitstellen
2026-10-27 17:14:45 +01:00

156 lines
6.3 KiB
PHP

<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\ChannelExportMode;
use App\Enums\ChannelTaskAction;
use App\Enums\ChannelTaskStatus;
use App\Mail\ChannelTasksNotification;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\Property;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* Creates blocking/unblocking tasks for every portal that must be maintained by hand
* (e.g. instant booking portals whose calendar import is too slow), notifies the landlord
* and hands the task to an optional external automation.
*/
class CreateChannelTasks
{
/**
* @return list<ChannelTask>
*/
public function handle(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn, ChannelTaskAction $action, string $reason, ?int $exceptChannelId = null, ?int $originChannelId = null, bool $external = false): array
{
if ($endsOn->lessThanOrEqualTo(today())) {
return [];
}
$channels = $property->channels()->active()
->where('requires_manual_blocking', true)
->when($exceptChannelId, fn ($query) => $query->whereKeyNot($exceptChannelId))
->when($originChannelId, fn ($query) => $query->whereKeyNot($originChannelId))
->get()->filter(fn (Channel $channel): bool => $channel->exportsOccupations()
&& (! ($external || $exceptChannelId !== null || $originChannelId !== null) || $channel->export_mode === ChannelExportMode::Regular));
$tasks = [];
foreach ($channels as $channel) {
$segments = $action === ChannelTaskAction::Unblock ? $this->freeSegments($property, $startsOn, $endsOn) : [[$startsOn, $endsOn]];
foreach ($segments as [$start, $end]) {
$task = $channel->tasks()->where('action', $action)->where('status', ChannelTaskStatus::Open)
->whereDate('starts_on', $start)->whereDate('ends_on', $end)->first()
?? $channel->tasks()->create([
'action' => $action, 'starts_on' => $start->toDateString(), 'ends_on' => $end->toDateString(),
'status' => ChannelTaskStatus::Open, 'reason' => $reason,
]);
if ($task->wasRecentlyCreated) {
$tasks[] = $task;
}
}
}
if ($tasks === []) {
return [];
}
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelTasksNotification($tasks)));
foreach ($tasks as $task) {
$this->sendToAutomation($task);
}
return $tasks;
}
/**
* POSTs the task to the automation webhook, signed with HMAC-SHA256 (header X-Signature).
* The automation confirms via the signed callback URL contained in the payload.
*/
public function sendToAutomation(ChannelTask $task): void
{
$task->refresh();
if ($task->status !== ChannelTaskStatus::Open) {
return;
}
if (! $task->channel->exportsOccupations()) {
$task->update(['automation_error' => 'Kanalexport ist pausiert; keine automatische Portaländerung.']);
return;
}
if ($task->action === ChannelTaskAction::Unblock && ! app(AvailabilityChecker::class)->isAvailable($task->channel->property, $task->starts_on, $task->ends_on)) {
$task->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Zeitraum ist inzwischen wieder belegt; nicht entsperren.']);
return;
}
if ($task->action === ChannelTaskAction::Block) {
$occupied = app(AvailabilityChecker::class)->occupiedNights($task->channel->property, $task->starts_on, $task->ends_on);
for ($night = $task->starts_on; $night->lessThan($task->ends_on); $night = $night->addDay()) {
if (! isset($occupied[$night->toDateString()])) {
$task->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Sperraufgabe ist durch eine Belegungsänderung überholt; aktuellen Zeitraum prüfen.']);
return;
}
}
}
$url = config('fewo.automation.webhook_url');
$secret = config('fewo.automation.secret');
if (blank($url) || blank($secret)) {
return;
}
$body = json_encode([
'task_id' => $task->id,
'channel' => $task->channel->name,
'connector' => $task->channel->connector,
'action' => $task->action->value,
'starts_on' => $task->starts_on->toDateString(),
'ends_on' => $task->ends_on->toDateString(),
'manage_url' => $task->channel->manage_url,
'callback_url' => URL::route('channel-tasks.complete', $task),
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
try {
Http::timeout(10)
->withHeaders(['X-Signature' => hash_hmac('sha256', $body, $secret)])
->withBody($body, 'application/json')
->post($url)
->throw();
$task->update(['automation_sent_at' => now(), 'automation_error' => null]);
} catch (Throwable $exception) {
$task->update(['automation_error' => $exception->getMessage()]);
}
}
/** @return list<array{CarbonImmutable, CarbonImmutable}> */
private function freeSegments(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn): array
{
$start = CarbonImmutable::instance($startsOn);
$end = CarbonImmutable::instance($endsOn);
$occupied = app(AvailabilityChecker::class)->occupiedNights($property, $start, $end);
$segments = [];
$segmentStart = null;
for ($night = $start; $night->lessThan($end); $night = $night->addDay()) {
if (! isset($occupied[$night->toDateString()])) {
$segmentStart ??= $night;
} elseif ($segmentStart !== null) {
$segments[] = [$segmentStart, $night];
$segmentStart = null;
}
}
if ($segmentStart !== null) {
$segments[] = [$segmentStart, $end];
}
return $segments;
}
}