Die Schalter aus Phase 3 schrieben nur in eine Tabelle, die niemand las. Ein gesperrter Portal-Abgleich lief trotzdem weiter. Das ist behoben. `App\Tenancy\TenantFeatures` ist die eine Stelle, die beantwortet, ob ein Mandant einen Dienst hat. Sie wird an allen Wegen abgefragt, die zum Dienst führen: - `RolePolicy::allows()` – damit greift die Mandanten-Ebene in *jeder* Richtlinie des Admins. Die Rolle sagt, was ein Benutzer darf; der Dienst sagt, was der Mandant überhaupt hat. Keine Rolle wiegt einen gesperrten Dienst auf. - `Channel::importsOccupations()` – Import und Scheduler. - Der öffentliche iCal-Feed antwortet mit 404. - `ProcessPortalMail` und `channels:fetch-mail` für den Postfach-Schnellweg. `TenantServiceKey::isWired()` trennt Gebautes von Geplantem. Nur verdrahtete Dienste erscheinen als Schalter; die drei KI-Dienste stehen als Hinweis da, bis die Anwendung sie abfragt. Eigene API-Schlüssel sind aus dem Betreiber- Formular verschwunden – sie gehören in den Admin des Mandanten, wenn es soweit ist (A16). Neu im Betreiber-Bereich: Seite „System" mit den Grenzen, die für alle Mandanten gelten (aus der .env, bewusst nicht änderbar), der Mandantenliste und dem Zugriffsprotokoll. Bisher war dort nur die Mandantenliste. Die Migration schaltet jedem vorhandenen Mandanten die Portal-Dienste frei, damit der Umbau laufenden Betrieb nicht stillschweigend stoppt. 240 Feature-Tests grün, davon fünf neue in `TenantServiceGateTest`. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
144 lines
5.2 KiB
PHP
144 lines
5.2 KiB
PHP
<?php
|
||
|
||
namespace App\Http\Controllers;
|
||
|
||
use App\Actions\MonitorChannels;
|
||
use App\Actions\ProcessPortalMail;
|
||
use App\Channels\ICal\ICalFeed;
|
||
use App\Channels\Mail\MailboxReader;
|
||
use App\Channels\Mail\PortalMail;
|
||
use App\Enums\ChannelTaskStatus;
|
||
use App\Models\Channel;
|
||
use App\Models\ChannelTask;
|
||
use Carbon\CarbonImmutable;
|
||
use Illuminate\Http\JsonResponse;
|
||
use Illuminate\Http\Request;
|
||
use Illuminate\Http\Response;
|
||
use Illuminate\Support\Facades\Artisan;
|
||
use Illuminate\Support\Facades\Cache;
|
||
|
||
/**
|
||
* Public endpoints of the channel synchronisation: export feeds for portals, the health check for
|
||
* external monitoring and the callback of the optional blocking automation.
|
||
*/
|
||
class ChannelController extends Controller
|
||
{
|
||
public function feed(string $token, ICalFeed $feed): Response
|
||
{
|
||
$channel = Channel::query()->where('export_token', $token)->where('is_active', true)->firstOrFail();
|
||
|
||
abort_unless($channel->servesItsLandlord(), 404);
|
||
|
||
return response($feed->build($channel), 200, [
|
||
'Content-Type' => 'text/calendar; charset=utf-8',
|
||
'Content-Disposition' => 'inline; filename="belegung.ics"',
|
||
'Cache-Control' => 'no-cache, max-age=0',
|
||
]);
|
||
}
|
||
|
||
public function health(Request $request): JsonResponse
|
||
{
|
||
abort_unless($this->hasValidToken($request, config('fewo.channels.health_token')), 404);
|
||
|
||
$channels = Channel::query()->active()->get()->map(fn (Channel $channel): array => [
|
||
'name' => $channel->name,
|
||
'imports' => $channel->importsOccupations(),
|
||
'ok' => ! $channel->isStale(),
|
||
'last_success_at' => $channel->last_success_at?->toIso8601String(),
|
||
'last_error' => $channel->last_error,
|
||
]);
|
||
$openTasks = ChannelTask::query()->open()->count();
|
||
$mailbox = [
|
||
'configured' => MailboxReader::isConfigured(),
|
||
'ok' => ! MonitorChannels::mailboxIsStale(),
|
||
'last_success_at' => Cache::get(MailboxReader::LAST_SUCCESS_KEY),
|
||
'last_error' => Cache::get(MailboxReader::LAST_ERROR_KEY),
|
||
];
|
||
|
||
$ok = $channels->every(fn (array $channel): bool => $channel['ok']) && $mailbox['ok'];
|
||
|
||
return response()->json([
|
||
'status' => $ok ? 'ok' : 'degraded',
|
||
'open_tasks' => $openTasks,
|
||
'mailbox' => $mailbox,
|
||
'channels' => $channels->values(),
|
||
], $ok ? 200 : 503);
|
||
}
|
||
|
||
/**
|
||
* Runs the task scheduler once (fallback for hosting without suitable cron jobs).
|
||
*/
|
||
public function scheduler(Request $request): JsonResponse
|
||
{
|
||
abort_unless($this->hasValidToken($request, config('fewo.scheduler_token')), 404);
|
||
|
||
Artisan::call('schedule:run');
|
||
|
||
return response()->json(['ran_at' => now()->toIso8601String(), 'output' => trim(Artisan::output())]);
|
||
}
|
||
|
||
/**
|
||
* Push variant of the e-mail fast path, e.g. from an n8n IMAP trigger:
|
||
* JSON {message_id, from, subject, text, received_at}, signed like the automation webhook.
|
||
*/
|
||
public function portalMail(Request $request, ProcessPortalMail $processPortalMail): JsonResponse
|
||
{
|
||
$this->verifySignature($request);
|
||
|
||
$data = $request->validate([
|
||
'message_id' => ['required', 'string', 'max:255'],
|
||
'from' => ['required', 'string', 'max:255'],
|
||
'subject' => ['required', 'string', 'max:500'],
|
||
'text' => ['required', 'string', 'max:200000'],
|
||
'received_at' => ['nullable', 'date'],
|
||
]);
|
||
|
||
$record = $processPortalMail->handle(new PortalMail(
|
||
messageId: $data['message_id'],
|
||
from: $data['from'],
|
||
subject: $data['subject'],
|
||
text: $data['text'],
|
||
receivedAt: isset($data['received_at']) ? CarbonImmutable::parse($data['received_at']) : CarbonImmutable::now(),
|
||
));
|
||
|
||
return response()->json([
|
||
'processed' => $record !== null,
|
||
'type' => $record?->type->value,
|
||
'status' => $record?->status->value,
|
||
]);
|
||
}
|
||
|
||
/**
|
||
* The automation reports a task as done. The raw body must be signed like the outgoing webhook.
|
||
*/
|
||
public function completeTask(Request $request, ChannelTask $task): JsonResponse
|
||
{
|
||
$this->verifySignature($request);
|
||
|
||
if ($task->status === ChannelTaskStatus::Open) {
|
||
$task->complete('Automatisierung');
|
||
}
|
||
|
||
return response()->json(['status' => $task->status->value]);
|
||
}
|
||
|
||
private function verifySignature(Request $request): void
|
||
{
|
||
$secret = config('fewo.automation.secret');
|
||
$signature = (string) $request->header('X-Signature');
|
||
|
||
abort_if(blank($secret) || ! hash_equals(hash_hmac('sha256', $request->getContent(), $secret), $signature), 403);
|
||
}
|
||
|
||
/**
|
||
* The token is sent as header "Authorization: Bearer <token>" (preferred – does not end up in web server logs)
|
||
* or, for older automations, as ?token=<token>.
|
||
*/
|
||
private function hasValidToken(Request $request, ?string $expected): bool
|
||
{
|
||
$given = (string) ($request->bearerToken() ?? $request->header('X-Fewo-Token') ?? $request->query('token', ''));
|
||
|
||
return filled($expected) && hash_equals((string) $expected, $given);
|
||
}
|
||
}
|