Files
LarsandClaude Opus 5.5 154b8a434c Postfach: Posteingang wird unter jedem Namen gefunden; kein doppeltes „SSL“
- MailboxReader::folder(): „Posteingang“, „Inbox“ oder leer → INBOX (so
  heißt der Posteingang auf dem IMAP-Server); andere Namen ohne Beachtung
  der Groß-/Kleinschreibung; unbekannter Ordner → Meldung mit den
  vorhandenen Ordnern statt „Call to a member function query() on null“.
  Gilt für Portal-Abruf, vollständigen Abruf und „Postfach prüfen“.
- Verschlüsselung: Platzhalter „Standard (SSL)“ statt eines zweiten „SSL“;
  Hinweis am Ordnerfeld.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:26:49 +01:00

472 lines
25 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Filament\Pages;
use App\Actions\SendDigests;
use App\Channels\ChannelSyncException;
use App\Channels\Mail\MailboxReader;
use App\Enums\DigestSection;
use App\Enums\TenantServiceKey;
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
use App\Models\Mailbox;
use App\Models\Tenant;
use App\Support\Settings;
use App\Tenancy\TenantConfig;
use App\Tenancy\TenantFeatures;
use BackedEnum;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Cache;
use UnitEnum;
/**
* Operating data of the landlord: operating mode (test mode sends every e-mail to one test recipient only;
* live delivers to the real recipients), the addresses of the internal communication, the landlord's own
* address and bank details, reminders and summaries, and the periods. Administrators only.
*/
class Operations extends Page
{
use FollowsAdminMode;
/** Periods and counters the landlord may set (column => label). Empty means the system default. */
private const PERIODS = [
'deposit_due_days' => 'Anzahlung fällig nach (Tage)',
'review_request_after_days' => 'Bewertungsbitte nach Abreise (Tage)',
'guest_retention_years' => 'Gästedaten löschen nach (Jahre)',
'retention_inquiry_months' => 'Nicht gebuchte Anfragen löschen nach (Monate)',
'retention_portal_email_excerpt_days' => 'Portal-Mail-Auszug löschen nach (Tage)',
'retention_attribution_months' => 'Herkunftsangaben löschen nach (Monate)',
'spam_min_seconds' => 'Bot-Schutz: Mindestzeit im Formular (Sekunden)',
'spam_per_ip_per_hour' => 'Bot-Schutz: Anfragen je IP und Stunde',
'spam_per_email_per_day' => 'Bot-Schutz: Anfragen je E-Mail und Tag',
'spam_open_requests_per_email' => 'Bot-Schutz: gleichzeitig offene Anfragen je E-Mail',
'spam_max_links' => 'Bot-Schutz: erlaubte Links im Text',
'channel_stale_after_minutes' => 'Portal-Abgleich gilt als veraltet nach (Minuten)',
'channel_task_reminder_after_minutes' => 'Erinnerung an Portal-Aufgaben nach (Minuten)',
];
/** Choices for repeating open findings (days => label). */
public const REMINDER_INTERVALS = [0 => 'Nur einmal', 1 => 'Täglich', 2 => 'Alle 2 Tage', 3 => 'Alle 3 Tage', 7 => 'Wöchentlich'];
public const WEEKDAYS = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag'];
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPower;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?string $navigationLabel = 'Betrieb';
protected static ?string $title = 'Betrieb';
protected static ?string $slug = 'betrieb';
protected static ?int $navigationSort = 1;
/** @var array<string, mixed> */
public array $data = [];
public static function canAccess(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin);
}
public function mount(): void
{
$tenant = $this->tenant();
$this->form->fill([
'mode' => $tenant->operating_mode ?: Settings::MODE_TEST,
'test_recipient' => $tenant->test_recipient ?: auth()->user()?->email,
'notification_recipients' => $tenant->notificationRecipients(),
'contact_email' => $tenant->contact_email,
'sender_name' => $tenant->sender_name,
'sender_email' => $tenant->sender_email,
'owner_name' => $tenant->owner_name,
'owner_street' => $tenant->owner_street,
'owner_city' => $tenant->owner_city,
'owner_phone' => $tenant->owner_phone,
'bank_account_holder' => $tenant->bank_account_holder,
'bank_name' => $tenant->bank_name,
'bank_iban' => $tenant->bank_iban,
'bank_bic' => $tenant->bank_bic,
'tax_note' => $tenant->tax_note,
'mailbox_host' => $tenant->activeMailbox()?->host ?? $tenant->mailbox_host,
'mailbox_port' => $tenant->activeMailbox()?->port ?? $tenant->mailbox_port,
'mailbox_username' => $tenant->activeMailbox()?->username ?? $tenant->mailbox_username,
'mailbox_password' => $tenant->activeMailbox()?->password ?? $tenant->mailbox_password,
'mailbox_encryption' => $tenant->activeMailbox()?->encryption ?? $tenant->mailbox_encryption,
'mailbox_folder' => $tenant->activeMailbox()?->folder ?? $tenant->mailbox_folder,
'mailbox_address' => $tenant->activeMailbox()?->address,
'mailbox_mode' => $tenant->activeMailbox()?->mode ?? Mailbox::PORTAL_ONLY,
'reminder_interval_days' => $tenant->reminder_interval_days,
'digest_daily' => $tenant->digest_daily,
'digest_weekly' => $tenant->digest_weekly,
'digest_weekday' => $tenant->digest_weekday,
'digest_hour' => $tenant->digest_hour,
'digest_sections' => array_map(fn (DigestSection $section): string => $section->value, DigestSection::chosen($tenant->digest_sections)),
'digest_when_empty' => $tenant->digest_when_empty,
...$this->periodValues($tenant),
]);
}
public function form(Schema $schema): Schema
{
return $schema
->statePath('data')
->components([
Section::make('E-Mail-Versand')
->description('Im Testbetrieb gehen alle E-Mails – Eingangsbestätigungen, Angebote, Bestätigungen, Erinnerungen, Benachrichtigungen – ausschließlich an die Testadresse, egal welche Adresse auf der Webseite eingetragen wurde.')
->schema([
Radio::make('mode')
->label('Betriebsart')
->options([
Settings::MODE_TEST => 'Testbetrieb – alle E-Mails an die Testadresse',
Settings::MODE_LIVE => 'Scharf geschaltet – E-Mails an Gäste und Vermieterin',
])
->required()
->live(),
TextInput::make('test_recipient')
->label('Testadresse')
->email()
->required(fn (Get $get): bool => $get('mode') === Settings::MODE_TEST)
->visible(fn (Get $get): bool => $get('mode') === Settings::MODE_TEST),
Text::make(fn (): string => filled(config('fewo.mail_redirect_to'))
? 'Hinweis: Auf diesem Server ist zusätzlich FEWO_MAIL_REDIRECT_TO='.config('fewo.mail_redirect_to').' gesetzt – diese Umleitung gilt immer, auch wenn hier scharf geschaltet ist.'
: ''),
]),
Section::make('Adressen der internen Kommunikation')
->description('Gelten sofort für alle E-Mails, die Webseite und den Mietvertrag. Im Testbetrieb gehen trotzdem alle E-Mails nur an die Testadresse.')
->columns(2)
->schema([
TagsInput::make('notification_recipients')
->label('Benachrichtigungen an')
->helperText('Neue Anfragen, angenommene/abgelehnte Angebote, abgelaufene Fristen, Bewertungen, Portal-Mails und -Aufgaben, Kopie der Zahlungserinnerungen. Mehrere Adressen möglich (Enter nach jeder Adresse).')
->placeholder('adresse@beispiel.de')
->nestedRecursiveRules(['email'])
->required()
->columnSpanFull(),
TextInput::make('contact_email')
->label('Kontakt- und Antwortadresse')
->helperText('Steht auf der Webseite und im Mietvertrag; Antworten der Gäste auf unsere E-Mails gehen hierhin.')
->email()
->required(),
TextInput::make('sender_name')
->label('Absendername')
->required()
->maxLength(100),
TextInput::make('sender_email')
->label('Absenderadresse')
->helperText(fn (): string => 'Muss das Postfach sein, mit dem der Server versendet (SMTP-Anmeldung: '.(config('mail.mailers.smtp.username') ?: 'nicht gesetzt').') – sonst lehnt Strato den Versand ab.')
->email()
->required(),
Text::make(fn (Get $get): string => filled(config('mail.mailers.smtp.username')) && filled($get('sender_email')) && strcasecmp((string) $get('sender_email'), (string) config('mail.mailers.smtp.username')) !== 0
? '⚠ Die Absenderadresse weicht vom SMTP-Postfach ('.config('mail.mailers.smtp.username').') ab. Strato stellt solche E-Mails in der Regel nicht zu.'
: '')
->columnSpanFull(),
]),
Section::make('Vermieterin')
->description('Steht in E-Mails, im Angebot, im Mietvertrag und auf der Webseite.')
->columns(2)
->schema([
TextInput::make('owner_name')->label('Name')->required()->maxLength(255),
TextInput::make('owner_phone')->label('Telefon')->maxLength(50),
TextInput::make('owner_street')->label('Straße und Hausnummer')->maxLength(255),
TextInput::make('owner_city')->label('PLZ und Ort')->maxLength(255),
]),
Section::make('Bankverbindung und Steuer')
->description('Steht im Mietvertrag und in den Zahlungsaufforderungen. Die Angaben liegen verschlüsselt in der Datenbank.')
->columns(2)
->schema([
TextInput::make('bank_account_holder')->label('Kontoinhaber')->maxLength(255),
TextInput::make('bank_name')->label('Bank')->maxLength(255),
TextInput::make('bank_iban')->label('IBAN')->maxLength(40),
TextInput::make('bank_bic')->label('BIC')->maxLength(20),
TextInput::make('tax_note')
->label('Steuerangabe')
->helperText('Zum Beispiel die Steuernummer oder der Hinweis auf die Kleinunternehmerregelung.')
->maxLength(255)
->columnSpanFull(),
]),
Section::make('Benachrichtigungen')
->description('Wie oft offene Meldungen wiederholt werden und welche Zusammenfassungen Sie per E-Mail erhalten. Empfänger sind die Adressen unter „Benachrichtigungen an“.')
->columns(2)
->schema([
Select::make('reminder_interval_days')
->label('Offene Meldungen erneut senden')
->helperText('Gilt für mögliche Doppelbuchungen (solange sie im Postfach ungelesen sind und weiter bestehen) und offene Portal-Aufgaben.')
->options(self::REMINDER_INTERVALS)
->selectablePlaceholder(false)
->required()
->columnSpanFull(),
Toggle::make('digest_daily')->label('Tägliche Zusammenfassung'),
Toggle::make('digest_weekly')->label('Wöchentliche Zusammenfassung')->live(),
Select::make('digest_hour')
->label('Versand ab')
->options(collect(range(5, 21))->mapWithKeys(fn (int $hour): array => [$hour => sprintf('%02d:00 Uhr', $hour)])->all())
->selectablePlaceholder(false)
->required(),
Select::make('digest_weekday')
->label('Wochentag der Wochenübersicht')
->helperText('An diesem Tag kommt nur die Wochenübersicht, nicht zusätzlich die tägliche.')
->options(self::WEEKDAYS)
->selectablePlaceholder(false)
->visible(fn (Get $get): bool => (bool) $get('digest_weekly'))
->required(),
CheckboxList::make('digest_sections')
->label('Inhalt der Zusammenfassung')
->options(DigestSection::class)
->descriptions(collect(DigestSection::cases())->mapWithKeys(fn (DigestSection $section): array => [$section->value => $section->getDescription()])->all())
->columns(2)
->required()
->columnSpanFull(),
Toggle::make('digest_when_empty')
->label('Auch senden, wenn nichts ansteht')
->helperText('Sonst entfällt die Zusammenfassung an Tagen ohne offene Punkte.')
->columnSpanFull(),
]),
Section::make('Portal-Postfach')
->description('Aus diesem Postfach werden die Buchungsmails der Portale gelesen, damit ein Termin sofort gesperrt wird. Leerer Server = ausgeschaltet. Das Passwort liegt verschlüsselt in der Datenbank.')
->columns(2)
->collapsed()
->visible(fn (): bool => app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail))
->schema([
TextInput::make('mailbox_host')->label('IMAP-Server')->maxLength(190),
TextInput::make('mailbox_port')->label('Port')->numeric()->integer()->placeholder('993'),
TextInput::make('mailbox_username')->label('Benutzer')->maxLength(190),
TextInput::make('mailbox_password')->label('Passwort')->password()->revealable()->autocomplete(false)->maxLength(190),
Select::make('mailbox_encryption')
->label('Verschlüsselung')
->options(['ssl' => 'SSL', 'tls' => 'TLS', 'starttls' => 'STARTTLS'])
->placeholder('Standard (SSL)'),
TextInput::make('mailbox_folder')->label('Ordner')->placeholder('INBOX')->maxLength(190)
->helperText('Leer lassen für den Posteingang (auf dem Server „INBOX“, auch „Posteingang“ wird erkannt).'),
Select::make('mailbox_mode')->label('Was wird gelesen?')
->options([Mailbox::PORTAL_ONLY => 'Nur Buchungsmails der Portale (wie bisher)', Mailbox::FULL => 'Alle Nachrichten (eigenes Postfach für die Gästekommunikation)'])
->required()
->helperText('„Alle Nachrichten“ nur für ein Postfach, das ausschließlich für Anfragen und Gästeantworten dient: Antworten und Gast-Mails werden dann den Vorgängen zugeordnet oder im Posteingang zur Klärung gezeigt.'),
TextInput::make('mailbox_address')->label('Adresse dieses Postfachs (für Antworten der Gäste)')->email()->maxLength(190)
->helperText('Rückfragen nennen diese Adresse als Antwortadresse, damit die Antwort hier ankommt.'),
Text::make(fn (): string => $this->mailboxState())->columnSpanFull(),
Actions::make([
Action::make('checkMailbox')->label('Postfach prüfen')->icon(Heroicon::OutlinedSignal)->color('gray')
->action(fn () => $this->checkMailbox()),
])->columnSpanFull(),
]),
Section::make('Fristen und Grenzen')
->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.')
->columns(3)
->collapsed()
->schema($this->periodFields()),
]);
}
public function content(Schema $schema): Schema
{
return $schema->components([
Form::make([EmbeddedSchema::make('form')])
->id('form')
->livewireSubmitHandler('save')
->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]),
]);
}
protected function getHeaderActions(): array
{
return [
Action::make('sendDigest')
->label('Zusammenfassung jetzt senden')
->icon(Heroicon::OutlinedPaperAirplane)
->color('gray')
->modalDescription('Schickt die Zusammenfassung mit den gespeicherten Einstellungen sofort an die Benachrichtigungsadressen – auch wenn nichts ansteht. Der reguläre Versand bleibt unverändert.')
->schema([
Radio::make('weekly')
->label('Welche?')
->options([0 => 'Tagesübersicht', 1 => 'Wochenübersicht'])
->default(0)
->required(),
])
->action(function (array $data): void {
app(SendDigests::class)->send($this->tenant(), (bool) $data['weekly'], force: true);
Notification::make()->title('Zusammenfassung gesendet')->body(Settings::isLive() ? null : 'Testbetrieb: Sie geht an die Testadresse.')->success()->send();
}),
];
}
/**
* Connects to the saved mailbox and counts the messages of the last days; nothing is read or marked.
*/
public function checkMailbox(): void
{
$connection = $this->tenant()->mailbox();
if ($connection === null) {
Notification::make()->title('Kein Postfach gespeichert')->body('Bitte Server und Benutzer eintragen und speichern.')->warning()->send();
return;
}
try {
$count = app(MailboxReader::class)->probe($connection);
} catch (ChannelSyncException $exception) {
Notification::make()->title('Postfach nicht erreichbar')->body($exception->getMessage())->danger()->persistent()->send();
return;
}
Notification::make()->title('Verbindung in Ordnung')->body($count.' Nachricht(en) der letzten '.config('fewo.mailbox.lookback_days', 3).' Tage im Ordner „'.$connection['folder'].'“.')->success()->send();
}
/**
* When the mailbox was last read and whether the last attempt failed.
*/
private function mailboxState(): string
{
$mailbox = $this->tenant()->activeMailbox();
if ($mailbox === null || blank($mailbox->host)) {
return 'Kein Postfach eingerichtet.';
}
$error = Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY));
$success = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY));
return 'Abruf jede Minute. Zuletzt erfolgreich gelesen: '.($success ? CarbonImmutable::parse($success)->format('d.m.Y, H:i').' Uhr' : 'noch nie')
.($error ? ' · Letzter Fehler: '.mb_substr((string) $error, 0, 200) : '')
.($mailbox->readsEverything() ? ' · Eingegangene Nachrichten stehen unter Verwaltung › Posteingang.' : ' · Gelesen werden nur Buchungsmails der Portale.');
}
public function save(): void
{
$data = $this->form->getState();
$tenant = $this->tenant();
$wasLive = $tenant->isLive();
$tenant->update([
'operating_mode' => $data['mode'],
'test_recipient' => $data['test_recipient'] ?? $tenant->test_recipient,
'notification_emails' => implode(', ', Settings::addressList(implode(',', $data['notification_recipients'] ?? []))),
'contact_email' => $data['contact_email'],
'sender_name' => $data['sender_name'],
'sender_email' => $data['sender_email'],
'owner_name' => $data['owner_name'],
'owner_street' => $data['owner_street'] ?? null,
'owner_city' => $data['owner_city'] ?? null,
'owner_phone' => $data['owner_phone'] ?? null,
'bank_account_holder' => $data['bank_account_holder'] ?? null,
'bank_name' => $data['bank_name'] ?? null,
'bank_iban' => $data['bank_iban'] ?? null,
'bank_bic' => $data['bank_bic'] ?? null,
'tax_note' => $data['tax_note'] ?? null,
'mailbox_host' => $data['mailbox_host'] ?? null,
'mailbox_port' => filled($data['mailbox_port'] ?? null) ? (int) $data['mailbox_port'] : null,
'mailbox_username' => $data['mailbox_username'] ?? null,
'mailbox_password' => $data['mailbox_password'] ?? null,
'mailbox_encryption' => $data['mailbox_encryption'] ?? null,
'mailbox_folder' => $data['mailbox_folder'] ?? null,
'reminder_interval_days' => (int) $data['reminder_interval_days'],
'digest_daily' => (bool) $data['digest_daily'],
'digest_weekly' => (bool) $data['digest_weekly'],
'digest_weekday' => (int) ($data['digest_weekday'] ?? $tenant->digest_weekday),
'digest_hour' => (int) $data['digest_hour'],
'digest_sections' => count($data['digest_sections']) === count(DigestSection::cases()) ? null : array_values($data['digest_sections']),
'digest_when_empty' => (bool) $data['digest_when_empty'],
...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)),
]);
// v0.11 (CH-05): the active mailbox record leads; it is kept in step with the fields above.
$mailbox = $tenant->activeMailbox() ?? new Mailbox(['is_active' => true]);
$mailbox->forceFill(['tenant_id' => $tenant->id])->fill([
'host' => $data['mailbox_host'] ?? null,
'port' => filled($data['mailbox_port'] ?? null) ? (int) $data['mailbox_port'] : null,
'username' => $data['mailbox_username'] ?? null,
'password' => $data['mailbox_password'] ?? null,
'encryption' => $data['mailbox_encryption'] ?? null,
'folder' => $data['mailbox_folder'] ?? null,
'address' => $data['mailbox_address'] ?? null,
'mode' => $data['mailbox_mode'] ?? Mailbox::PORTAL_ONLY,
]);
if ($mailbox->exists || filled($mailbox->host)) {
$mailbox->save();
}
app(TenantConfig::class)->refresh();
if ($data['mode'] === Settings::MODE_LIVE && ! $wasLive) {
Notification::make()->title('Scharf geschaltet')->body('Ab jetzt erhalten Gäste und Vermieterin die E-Mails direkt.')->warning()->send();
} else {
Notification::make()->title('Gespeichert')->success()->send();
}
}
/**
* The landlord this page edits: the one of the request, else the only one there is.
*/
private function tenant(): Tenant
{
$tenant = Settings::tenant();
abort_if($tenant === null, 404);
return $tenant;
}
/**
* @return array<string, ?int>
*/
private function periodValues(Tenant $tenant): array
{
return array_combine(array_keys(self::PERIODS), array_map(fn (string $column): ?int => $tenant->{$column}, array_keys(self::PERIODS)));
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function periodInput(array $data): array
{
return array_combine(array_keys(self::PERIODS), array_map(fn (string $column): mixed => $data[$column] ?? null, array_keys(self::PERIODS)));
}
/**
* @return list<TextInput>
*/
private function periodFields(): array
{
return array_map(function (string $column) {
$field = TextInput::make($column)
->label(self::PERIODS[$column])
->numeric()
->integer()
->minValue(0);
$config = app(TenantConfig::class);
if (($ceiling = $config->ceilingFor($column)) !== null) {
return $field->maxValue($ceiling)->helperText('Vorgabe des Systems: höchstens '.$ceiling);
}
if (($floor = $config->floorFor($column)) !== null) {
return $field->minValue($floor)->helperText('Vorgabe des Systems: mindestens '.$floor);
}
return $field;
}, array_keys(self::PERIODS));
}
}