Files
fewo-stommer/app/Actions/CreateChannelTasks.php
2026-10-23 07:14:25 +02:00

94 lines
3.1 KiB
PHP

<?php
namespace App\Actions;
use App\Enums\ChannelTaskAction;
use App\Mail\ChannelTasksNotification;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\Property;
use App\Support\Settings;
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): array
{
if ($endsOn->lessThanOrEqualTo(today())) {
return [];
}
$channels = $property->channels()->active()
->where('requires_manual_blocking', true)
->when($exceptChannelId, fn ($query) => $query->whereKeyNot($exceptChannelId))
->get();
$tasks = $channels->map(fn (Channel $channel): ChannelTask => $channel->tasks()->create([
'action' => $action,
'starts_on' => $startsOn->toDateString(),
'ends_on' => $endsOn->toDateString(),
'reason' => $reason,
]))->all();
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
{
$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()]);
}
}
}