Files
fewo-stommer/app/Actions/ConfigureChannel.php
2026-10-27 19:00:25 +01:00

50 lines
2.5 KiB
PHP

<?php
namespace App\Actions;
use App\Channels\ICal\ICalFeed;
use App\Channels\ICal\ICalParser;
use App\Enums\ChannelStatus;
use App\Models\Channel;
use App\Models\Property;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class ConfigureChannel
{
/** @param array<string, mixed> $data */
public function handle(Property $property, array $data, ?Channel $channel = null): Channel
{
return DB::transaction(function () use ($property, $data, $channel): Channel {
$stored = $channel ? $property->channels()->whereKey($channel->id)->lockForUpdate()->firstOrFail() : null;
$candidate = $stored ? clone $stored : new Channel;
$candidate->fill($data);
$candidate->property_id = $property->id;
$candidate->tenant_id = $property->tenant_id;
if ($stored && $stored->setting('import_url') !== $candidate->setting('import_url')) {
$candidate->forceFill(['ical_analysis' => null, 'ical_analyzed_at' => null]);
}
if ($stored) {
$candidate->is_active = $candidate->status === ChannelStatus::Active;
}
if ($candidate->import_enabled && blank($candidate->setting('import_url'))) {
throw ValidationException::withMessages(['settings.import_url' => 'Für einen aktivierten Import ist eine Kalenderadresse erforderlich.']);
}
if ($stored && $stored->setting('import_url') !== $candidate->setting('import_url') && $stored->blockedPeriods()->withTrashed()->exists()) {
throw ValidationException::withMessages(['settings.import_url' => 'Bei bestehendem Importbestand die Quelladresse nicht ungeprüft ersetzen. Einen neuen Kanal anlegen oder die Bestandsumstellung gesondert freigeben.']);
}
if ($stored && $stored->exportsOccupations() && ! $candidate->exportsOccupations() && $stored->export_snapshot === null) {
$body = app(ICalFeed::class)->build($stored);
app(ICalParser::class)->parse($body);
$candidate->forceFill(['export_snapshot' => $body, 'export_snapshot_at' => now()]);
}
if ($stored && $stored->importsOccupations() !== $candidate->importsOccupations()) {
$stored->blockedPeriods()->where('source', 'channel')->update(['missing_imports' => 0]);
}
$candidate->save();
return $candidate->refresh();
});
}
}