Compare commits

...
Author SHA1 Message Date
Lars StommerandClaude Opus 5.5 7355466231 Deploy: keep only the active release on Strato (file quota), release history as Git tags in Gitea
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:16:32 +02:00
Lars StommerandClaude Opus 5.5 669fb45731 Deploy: prune vendor translations/tests/docs to stay within Strato's file quota
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:06:04 +02:00
Lars StommerandClaude Opus 5.5 33dde2027b Docs: webspace quota note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:01:29 +02:00
Lars StommerandClaude Opus 5.5 13760f2c02 Admin two-factor authentication (mandatory for admins), users:create command, operations handbook
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:52:44 +02:00
Lars StommerandClaude Opus 5.5 dea1029225 Docs: wording
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:43:49 +02:00
Lars StommerandClaude Opus 5.5 b544adac62 Docs: staging on stommer.info, OPcache-safe release switching
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:43:37 +02:00
Lars StommerandClaude Opus 5.5 83427aec13 Deploy: fix escaped dot in .htaccess block rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:41:10 +02:00
Lars StommerandClaude Opus 5.5 fbfc9eeb95 Deploy: serve the web from the concrete release folder to avoid stale OPcache via the current symlink
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:38:13 +02:00
Lars StommerandClaude Opus 5.5 f031b3c854 Pin URL root to APP_URL outside local/testing (base-folder hosting on Strato)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:32:40 +02:00
Lars StommerandClaude Opus 5.5 92c796de2e Deployment: .htaccess-Weiterleitung für Strato (kein Symlink-Ziel), Web-PHP pro Ordner, erstes Deployment ohne Gesundheitscheck
Erfolgreich getestet auf Strato (test.fewo-stommer.de).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:22:27 +02:00
Lars StommerandClaude Opus 5.5 cb1e4cbc63 Theme: noindex außerhalb der Produktion (Testbetrieb nicht in Suchmaschinen)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:05:22 +02:00
Lars StommerandClaude Opus 5.5 769e6b7e6e Deployment: paketspezifischer Strato-SSH-Server, Tilde im Schlüsselpfad
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:57:25 +02:00
Lars StommerandClaude Opus 5.5 c7186e768e MariaDB 11.8 als Zieldatenbank (Vorlage, Doku) und zusätzlicher CI-Testlauf gegen MariaDB
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:40:48 +02:00
Lars StommerandClaude Opus 5.5 a6adab64bb Deployment-Doku (Strato-Einrichtung, SSH vs. SFTP, Gitea Actions)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:32:40 +02:00
Lars StommerandClaude Opus 5.5 8d904660b9 Automatisches Deployment nach Strato (atomare Releases, Rollback, Gitea Actions)
- scripts/deploy.sh: Build aus Git-Stand (Composer ohne Dev, Vite), Upload per SSH, Migration, Caches, atomarer Umschalter current -> releases/<zeit>, Gesundheitscheck mit automatischem Rollback; Befehle setup/deploy/rollback/releases/artisan; lokaler Testmodus
- .gitea/workflows/deploy.yml: Tests bei jedem Push, Deployment bei Tags v* oder per Knopfdruck
- Vorlagen scripts/deploy.example.env und .env.production.example (Strato MySQL, SMTP, IMAP)
- Scheduler-Endpunkt /automation/scheduler als Ausweich für fehlende Cronjobs
- ProductionSeeder für die Ersteinrichtung ohne Testdaten

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:28:00 +02:00
Lars StommerandClaude Opus 5.5 66e82d61f5 Theme-System mit Basis-Theme Ostsee-Licht, Bausteinen und saisonalen Erscheinungsbildern
- Sites (Domain, Theme, Farben; mehrfähig für weitere Vermieter), Seiten aus Bausteinen mit Menüs, Erscheinungsbilder mit jährlichem Zeitplan, Priorität und signierter Vorschau
- Theme-Kern (app/Themes): Manifest, Registry, Vererbung (Child-Themes), Token-Farben als CSS-Variablen, Bausteinkatalog als Registry (config/themes.php)
- 15 Bausteine: Titelbereich mit Suche, Eckdaten, Text mit Bildern, Galerie, Ausstattung, Lage, Preise, Angebote, Kalender & Anfrage, Bewertungen, Gastgeber, FAQ, Abschluss, Kontakt, Fließtext
- Theme Ostsee-Licht: Layout, Kopf/Fuß, Banner, mobile Buchungsleiste, Lightbox, selbst gehostete Schriften, Reduced Motion
- Seiten Start, Wohnung, Kühlungsborn, Preise & Buchung, Kontakt, Impressum, Datenschutz; Sitemap, robots.txt, JSON-LD
- Admin: Seiten-Baukasten, Erscheinungsbilder, Websites
- Dokumentation docs/THEMES.md inkl. Übergabe für die Design-Sitzung

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:04:21 +02:00
Lars StommerandClaude Opus 5.5 f2c48013ad Konzept: Entscheidungen zum Theme- und Vorlagensystem
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:25:41 +02:00
Lars StommerandClaude Opus 5.5 99e0ba4040 Dashboard: Kennzahlen und nächste Aufenthalte
- Offene Anfragen, Anreisen 14 Tage, offene/überfällige Zahlungen, Auslastung, Portal-Status
- Tabelle der Aufenthalte der nächsten 30 Tage mit offenen Beträgen und Anreiseinfo-Status
- Nur für Rollen Administrator und Vermietung

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:31:05 +02:00
Lars StommerandClaude Opus 5.5 0bf302fcf9 Phase 3: Zahlungen, Mietvertrag, Erinnerungen, Anreiseinformationen
- Zahlungen erfassen (inkl. Erstattungen), Status automatisch: Bestätigt → Anzahlung erhalten → Bezahlt → Abgeschlossen
- Anzahlungsfrist bei Bestätigung; kurzfristige Buchungen: Gesamtbetrag sofort
- Mietvertrag als PDF (dompdf, Font-Subsetting), bei Bestätigung gespeichert und angehängt; Texte im Admin (Muster)
- Täglich: Zahlungserinnerungen (Anzahlung/Rest überfällig, Kopie an Vermieter), Zahlungsaufforderung Rest 7 Tage vorher, Anreiseinfos 7 Tage vorher, Abschluss nach Abreise
- Admin: Zahlungen je Buchung, offene Beträge, Vertrag herunterladen/neu erzeugen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:29:41 +02:00
Lars StommerandClaude Opus 5.5 e5f9e0762f Schnellerkennung von Portalbuchungen per E-Mail
- IMAP-Abruf jede Minute (webklex/php-imap, ohne PHP-imap-Erweiterung) oder signierter Push von n8n
- Parser für Buchungs-, Storno- und Anfrage-Mails (de/en), Buchungsnummer, An-/Abreise
- Erkannte Buchungen werden sofort gesperrt und an handgepflegte Portale weitergegeben; Kalender-Abgleich übernimmt bzw. ersetzt Mail-Sperren
- Unklare Mails: Prüf-Mail + Admin-Liste Portal-E-Mails mit Aktion Sperre anlegen
- Überwachung des Postfachs in Monitor und /health/sync

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:29:26 +02:00
Lars StommerandClaude Opus 5.5 0b7205e050 Portal-Synchronisation: unser System führt
- Connector-System (app/Channels, config/channels.php) mit iCal-Connector, robustem Parser und Export-Feed je Portal (ohne eigene Belegungen, ohne Gästedaten)
- Abgleich alle 5 Min. mit Protokoll, Echo-Erkennung, Konflikt-Mail bei möglicher Doppelbuchung
- Überwachung: Störungs-Mail, Status-Endpunkt /health/sync für n8n
- Portal-Aufgaben für Sofortbuchungsportale (FeWo-direkt): automatisch aus Buchungen/Sperren/anderen Portalen, Mail + Erinnerung, Abhaken im Admin
- Optionaler signierter Automatisierungs-Webhook mit Rückmeldung
- Herkunftsmessung: Abfrage im Formular + UTM-Parameter
- Portal-Analyse: AGB-Prüfung Automatisierung, Umsetzungsbeschreibung

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:13:55 +02:00
Lars StommerandClaude Opus 5.5 a8e72715ab Portal-Analyse: Channel-Manager-Bewertung, Eigenbau, Sofortbuchungsrisiko
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:01:33 +02:00
Lars StommerandClaude Opus 5.5 02acda8602 Portal-Analyse: Kalender-Abgleich, Buchungshoheit, Empfehlung
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 10:52:27 +02:00
234 changed files with 10331 additions and 505 deletions

No files matched your search

+11
View File
@@ -73,3 +73,14 @@ FEWO_BANK_BIC=
FEWO_BANK_NAME=
FEWO_REVIEW_REQUEST_AFTER_DAYS=2
FEWO_GUEST_RETENTION_YEARS=10
FEWO_CHANNEL_STALE_AFTER_MINUTES=60
FEWO_CHANNEL_TASK_REMINDER_AFTER_MINUTES=120
FEWO_HEALTH_TOKEN=
FEWO_AUTOMATION_WEBHOOK_URL=
FEWO_AUTOMATION_SECRET=
FEWO_MAILBOX_HOST=
FEWO_MAILBOX_PORT=993
FEWO_MAILBOX_ENCRYPTION=ssl
FEWO_MAILBOX_USERNAME=
FEWO_MAILBOX_PASSWORD=
FEWO_MAILBOX_FOLDER=INBOX
+63
View File
@@ -0,0 +1,63 @@
# Production settings – copy to <DEPLOY_PATH>/shared/.env on the server and fill in.
# Generate APP_KEY locally once: php artisan key:generate --show
APP_NAME="Ferienwohnung Stommer"
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://www.fewo-stommer.de
APP_TIMEZONE=Europe/Berlin
APP_LOCALE=de
APP_FALLBACK_LOCALE=de
APP_FAKER_LOCALE=de_DE
APP_MAINTENANCE_DRIVER=file
LOG_CHANNEL=daily
LOG_LEVEL=warning
# Strato MariaDB 11.8 (Kundenlogin › Datenbanken und Webspace › Datenbanken verwalten)
DB_CONNECTION=mariadb
DB_HOST=
DB_PORT=3306
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_SECURE_COOKIE=true
CACHE_STORE=database
QUEUE_CONNECTION=sync
FILESYSTEM_DISK=local
# Strato mailbox fewo@stommer.de
MAIL_MAILER=smtp
MAIL_HOST=smtp.strato.de
MAIL_PORT=465
MAIL_SCHEME=smtps
MAIL_USERNAME=fewo@stommer.de
MAIL_PASSWORD=
MAIL_FROM_ADDRESS="fewo@stommer.de"
MAIL_FROM_NAME="${APP_NAME}"
FEWO_OWNER_NAME="Brigitte Stommer"
FEWO_OWNER_EMAIL=fewo@stommer.de
FEWO_NOTIFICATION_EMAIL=fewo@stommer.de
FEWO_BANK_ACCOUNT_HOLDER=
FEWO_BANK_IBAN=
FEWO_BANK_BIC=
FEWO_BANK_NAME=
# Portal booking e-mails (fast path)
FEWO_MAILBOX_HOST=imap.strato.de
FEWO_MAILBOX_PORT=993
FEWO_MAILBOX_ENCRYPTION=ssl
FEWO_MAILBOX_USERNAME=fewo@stommer.de
FEWO_MAILBOX_PASSWORD=
FEWO_MAILBOX_FOLDER=INBOX
# Monitoring / automation (long random values, e.g. php -r "echo bin2hex(random_bytes(24));")
FEWO_HEALTH_TOKEN=
FEWO_SCHEDULER_TOKEN=
FEWO_AUTOMATION_SECRET=
FEWO_AUTOMATION_WEBHOOK_URL=
+105
View File
@@ -0,0 +1,105 @@
# Tests on every push; deployment to Strato for tags "v*" or by hand (Gitea › Actions › Deploy › Run workflow).
# Needs a Gitea act_runner (e.g. on the private server) and these repository secrets:
# DEPLOY_SSH_KEY private key whose public key is stored at Strato (SFTP & SSH)
# DEPLOY_HOST package-specific SSH server, e.g. 51539426.ssh.w1.strato.hosting (not ssh.strato.de)
# DEPLOY_USER SSH user from the Strato customer login
# DEPLOY_PATH e.g. fewo-production
# DEPLOY_PHP e.g. /opt/RZphp84/bin/php-cli
# DEPLOY_URL e.g. https://www.fewo-stommer.de
name: Deploy
on:
push:
branches: [main]
tags: ['v*']
workflow_dispatch:
inputs:
environment:
description: Ziel
type: choice
options: [production, staging]
default: production
jobs:
test:
runs-on: ubuntu-latest
services:
mariadb:
image: mariadb:11.8
env:
MARIADB_DATABASE: fewo_test
MARIADB_ROOT_PASSWORD: test
ports: ['3306:3306']
options: >-
--health-cmd="healthcheck.sh --connect --innodb_initialized"
--health-interval=5s --health-timeout=5s --health-retries=20
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
extensions: mbstring, intl, gd, exif, zip, pdo_sqlite, sqlite3, pdo_mysql, fileinfo, openssl
tools: composer:v2
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
- name: Install
run: |
composer install --no-interaction --no-progress --prefer-dist
npm ci --no-audit --no-fund
npm run build
cp .env.example .env
php artisan key:generate
- name: Tests (SQLite)
run: php artisan test --compact
- name: Tests (MariaDB 11.8, wie auf Strato)
env:
DB_CONNECTION: mariadb
DB_HOST: 127.0.0.1
DB_PORT: '3306'
DB_DATABASE: fewo_test
DB_USERNAME: root
DB_PASSWORD: test
run: php artisan test --compact
deploy:
needs: test
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
extensions: mbstring, intl, gd, exif, zip, fileinfo, openssl
tools: composer:v2
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
- name: SSH key
run: |
mkdir -p ~/.ssh
printf '%s\n' "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy_key
chmod 600 ~/.ssh/deploy_key
ssh-keyscan -H "${{ secrets.DEPLOY_HOST }}" >> ~/.ssh/known_hosts
- name: Deploy
env:
DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }}
DEPLOY_PHP: ${{ secrets.DEPLOY_PHP }}
DEPLOY_URL: ${{ secrets.DEPLOY_URL }}
run: |
export DEPLOY_SSH_KEY="$HOME/.ssh/deploy_key"
bash scripts/deploy.sh "${{ inputs.environment || 'production' }}" deploy
+4
View File
@@ -28,3 +28,7 @@ _ide_helper.php
Homestead.json
Homestead.yaml
Thumbs.db
# Deployment settings with access data
/scripts/deploy.*.env
!/scripts/deploy.example.env
+4
View File
@@ -11,6 +11,10 @@ # Ferienwohnung Stommer
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`.
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
+4
View File
@@ -11,6 +11,10 @@ # Ferienwohnung Stommer
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`.
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
+11 -2
View File
@@ -3,6 +3,7 @@
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Mail\BookingConfirmed;
@@ -11,11 +12,16 @@
use Illuminate\Support\Facades\Mail;
/**
* The landlord accepts a reservation. Expired reservations can still be confirmed while the dates are free.
* The landlord accepts a reservation: the booking becomes binding, payment due dates are fixed,
* the rental contract is generated and sent with the confirmation.
* Expired reservations can still be confirmed while the dates are free.
*/
class ConfirmBooking
{
public function __construct(private AvailabilityChecker $availability) {}
public function __construct(
private AvailabilityChecker $availability,
private RentalContract $contract,
) {}
/**
* @throws ReservationException
@@ -35,9 +41,12 @@ public function handle(Booking $booking, bool $notifyGuest = true): void
'status' => BookingStatus::Confirmed,
'hold_expires_at' => null,
'confirmed_at' => now(),
'deposit_due_on' => today()->addDays(config('fewo.deposit_due_days'))->toDateString(),
]);
});
$this->contract->generate($booking);
if ($notifyGuest) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking));
}
+92
View File
@@ -0,0 +1,92 @@
<?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 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(config('fewo.notification_email'))->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()]);
}
}
}
+5 -2
View File
@@ -13,6 +13,7 @@
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Throwable;
@@ -30,13 +31,14 @@ public function __construct(
/**
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution where the guest came from
*
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true): Booking
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
{
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source): Booking {
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
Property::whereKey($property->getKey())->lockForUpdate()->first();
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
@@ -52,6 +54,7 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
'guest_id' => $guest->id,
'status' => BookingStatus::Reserved,
'source' => $source,
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
'arrival' => $stay->arrival->toDateString(),
'departure' => $stay->departure->toDateString(),
'guests' => $stay->guests,
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Actions;
use App\Channels\Mail\MailboxReader;
use App\Mail\ChannelSyncAlert;
use App\Mail\MailboxAlert;
use App\Models\Channel;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
/**
* Alerts the landlord once per incident when a portal import or the mailbox fast path fails
* or has not succeeded for too long. The alert is reset by the next success.
*/
class MonitorChannels
{
private const MAILBOX_ALERTED_KEY = 'mailbox:alerted';
public function handle(): int
{
$channels = Channel::query()->active()->whereNull('alerted_at')->get()
->filter(fn (Channel $channel): bool => $channel->isStale());
foreach ($channels as $channel) {
Mail::to(config('fewo.notification_email'))->send(new ChannelSyncAlert($channel));
$channel->forceFill(['alerted_at' => now()])->save();
}
return $channels->count() + $this->monitorMailbox();
}
public static function mailboxIsStale(): bool
{
if (! MailboxReader::isConfigured()) {
return false;
}
$lastSuccess = Cache::get(MailboxReader::LAST_SUCCESS_KEY);
return $lastSuccess === null
|| CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes')));
}
private function monitorMailbox(): int
{
if (! self::mailboxIsStale()) {
Cache::forget(self::MAILBOX_ALERTED_KEY);
return 0;
}
if (Cache::has(self::MAILBOX_ALERTED_KEY)) {
return 0;
}
Mail::to(config('fewo.notification_email'))->send(new MailboxAlert(Cache::get(MailboxReader::LAST_ERROR_KEY)));
Cache::forever(self::MAILBOX_ALERTED_KEY, true);
return 1;
}
}
+165
View File
@@ -0,0 +1,165 @@
<?php
namespace App\Actions;
use App\Channels\ConflictDetector;
use App\Channels\Mail\ParsedPortalMail;
use App\Channels\Mail\PortalMail;
use App\Channels\Mail\PortalMailParser;
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use App\Mail\ChannelConflict;
use App\Mail\PortalMailNotification;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\PortalEmail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/**
* Fast path for portal bookings: the notification e-mail usually arrives within a minute, long before
* the portal's calendar export is read. A recognised booking is blocked immediately; the later calendar
* sync confirms the block. Anything not recognised with confidence is flagged for review – never guessed.
*/
class ProcessPortalMail
{
public function __construct(
private PortalMailParser $parser,
private ConflictDetector $conflictDetector,
) {}
public function handle(PortalMail $mail): ?PortalEmail
{
if (PortalEmail::where('message_id', $mail->messageId)->exists()) {
return null;
}
$channel = $this->channelFor($mail->from);
if ($channel === null) {
return null;
}
$parsed = $this->parser->parse($mail->subject, $mail->text);
$conflicts = [];
$record = DB::transaction(function () use ($mail, $channel, $parsed, &$conflicts): PortalEmail {
[$status, $block, $note] = match ($parsed->type) {
PortalEmailType::Booking => $this->block($channel, $parsed, $conflicts),
PortalEmailType::Cancellation => $this->release($channel, $parsed),
PortalEmailType::Inquiry => [PortalEmailStatus::Ignored, null, 'Anfrage – keine Sperre nötig.'],
PortalEmailType::Unknown => [PortalEmailStatus::NeedsReview, null, 'Inhalt nicht erkannt.'],
};
return PortalEmail::create([
'channel_id' => $channel->id,
'message_id' => $mail->messageId,
'from' => mb_substr($mail->from, 0, 255),
'subject' => mb_substr($mail->subject, 0, 255),
'received_at' => $mail->receivedAt,
'type' => $parsed->type,
'status' => $status,
'starts_on' => $parsed->startsOn?->toDateString(),
'ends_on' => $parsed->endsOn?->toDateString(),
'reference' => $parsed->reference,
'blocked_period_id' => $block?->id,
'excerpt' => mb_substr(trim(preg_replace('/\s+/u', ' ', strip_tags($mail->text))), 0, 500),
'note' => $note,
]);
});
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new PortalMailNotification($record)));
}
if ($conflicts !== []) {
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelConflict($channel, $conflicts)));
}
return $record;
}
/**
* Channels list the sender addresses or domains of their notification e-mails in settings.email_senders.
*/
public function channelFor(string $from): ?Channel
{
$from = mb_strtolower($from);
return Channel::query()->active()->get()->first(function (Channel $channel) use ($from): bool {
foreach ($this->senders($channel) as $sender) {
if (str_contains($from, $sender)) {
return true;
}
}
return false;
});
}
/**
* @return list<string>
*/
public function senders(Channel $channel): array
{
return array_values(array_filter(array_map(
fn (string $sender): string => mb_strtolower(trim($sender)),
explode(',', (string) $channel->setting('email_senders')),
)));
}
/**
* @param list<string> $conflicts
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
*/
private function block(Channel $channel, ParsedPortalMail $parsed, array &$conflicts): array
{
if (! $parsed->hasPeriod()) {
return [PortalEmailStatus::NeedsReview, null, 'Buchung erkannt, aber An-/Abreise nicht sicher lesbar.'];
}
$known = $channel->blockedPeriods()
->whereDate('starts_on', $parsed->startsOn)
->whereDate('ends_on', $parsed->endsOn)
->first();
if ($known) {
return [PortalEmailStatus::AlreadyKnown, $known, null];
}
$block = $channel->blockedPeriods()->create([
'property_id' => $channel->property_id,
'starts_on' => $parsed->startsOn->toDateString(),
'ends_on' => $parsed->endsOn->toDateString(),
'reason' => "{$channel->name} (E-Mail)".($parsed->reference ? ": {$parsed->reference}" : ''),
'source' => 'email',
'external_uid' => 'email:'.($parsed->reference ?? $parsed->startsOn->format('Ymd').'-'.$parsed->endsOn->format('Ymd')),
]);
$conflicts = $this->conflictDetector->conflictsFor($block);
return [PortalEmailStatus::Blocked, $block, null];
}
/**
* Only blocks created from e-mails are released here; calendar blocks disappear with the next sync.
*
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
*/
private function release(Channel $channel, ParsedPortalMail $parsed): array
{
$emailBlocks = $channel->blockedPeriods()->where('source', 'email');
$block = match (true) {
$parsed->reference !== null => (clone $emailBlocks)->where('external_uid', 'email:'.$parsed->reference)->first(),
$parsed->hasPeriod() => (clone $emailBlocks)->whereDate('starts_on', $parsed->startsOn)->whereDate('ends_on', $parsed->endsOn)->first(),
default => null,
};
if ($block) {
$block->delete();
return [PortalEmailStatus::Released, null, 'Sperre aus E-Mail aufgehoben.'];
}
return [PortalEmailStatus::NeedsReview, null, 'Stornierung erkannt – bitte prüfen; Kalender-Sperren verschwinden mit dem nächsten Abgleich.'];
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\PaymentMethod;
use App\Models\Booking;
use App\Models\Payment;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;
/**
* Records a received payment (or a refund with a negative amount) and moves the booking along:
* Bestätigt → Anzahlung erhalten → Bezahlt.
*/
class RecordPayment
{
public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null): Payment
{
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy): Payment {
$payment = $booking->payments()->create([
'amount' => $amount,
'paid_on' => $paidOn->toDateString(),
'method' => $method,
'note' => $note,
'recorded_by' => $recordedBy,
]);
$booking->unsetRelation('payments');
$this->updateStatus($booking);
return $payment;
});
}
public function updateStatus(Booking $booking): void
{
$paymentStatuses = [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid];
if (! in_array($booking->status, $paymentStatuses, true)) {
return;
}
$paid = $booking->paidAmount();
$status = match (true) {
$paid >= $booking->total => BookingStatus::Paid,
$paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid,
default => BookingStatus::Confirmed,
};
if ($status !== $booking->status) {
$booking->update(['status' => $status]);
}
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Actions;
use App\Mail\ChannelTasksNotification;
use App\Models\ChannelTask;
use Illuminate\Support\Facades\Mail;
/**
* Reminds the landlord once about blocking tasks that are still open after the reminder time.
*/
class RemindChannelTasks
{
public function handle(): int
{
$tasks = ChannelTask::query()
->open()
->whereNull('reminded_at')
->where('created_at', '<=', now()->subMinutes(config('fewo.channels.task_reminder_after_minutes')))
->with('channel')
->get();
if ($tasks->isEmpty()) {
return 0;
}
Mail::to(config('fewo.notification_email'))->send(new ChannelTasksNotification($tasks->all(), reminder: true));
ChannelTask::whereKey($tasks->modelKeys())->update(['reminded_at' => now()]);
return $tasks->count();
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Mail\ArrivalInformation;
use App\Mail\PaymentReminder;
use App\Models\Booking;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Mail;
/**
* Daily booking workflow: payment requests and reminders, arrival information, completion after departure.
* Every message is sent at most once per booking.
*/
class SendBookingReminders
{
private const BALANCE_REQUEST_DAYS_BEFORE = 7;
private const ARRIVAL_INFO_DAYS_BEFORE = 7;
/**
* @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int}
*/
public function handle(): array
{
$today = today();
$unpaid = [BookingStatus::Confirmed, BookingStatus::DepositPaid];
$depositOverdue = $this->bookings(fn (Builder $query) => $query
->where('status', BookingStatus::Confirmed)
->whereNull('deposit_reminded_at')
->whereDate('deposit_due_on', '<', $today))
->filter(fn (Booking $booking): bool => $booking->openDeposit() > 0);
$this->remind($depositOverdue, PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at');
$balanceRequest = $this->bookings(fn (Builder $query) => $query
->whereIn('status', $unpaid)
->whereNull('balance_requested_at')
->whereDate('balance_due_on', '>=', $today)
->whereDate('balance_due_on', '<=', $today->copy()->addDays(self::BALANCE_REQUEST_DAYS_BEFORE)))
->filter(fn (Booking $booking): bool => ! $booking->requiresFullPayment() && $booking->openAmount() > 0 && $booking->status === BookingStatus::DepositPaid);
$this->remind($balanceRequest, PaymentReminder::BALANCE_REQUEST, 'balance_requested_at');
$balanceOverdue = $this->bookings(fn (Builder $query) => $query
->whereIn('status', $unpaid)
->whereNull('balance_reminded_at')
->whereDate('balance_due_on', '<', $today))
->filter(fn (Booking $booking): bool => $booking->openAmount() > 0 && ($booking->status === BookingStatus::DepositPaid || $booking->requiresFullPayment()));
$this->remind($balanceOverdue, PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at');
$arrivals = $this->bookings(fn (Builder $query) => $query
->whereIn('status', BookingStatus::occupying())
->whereNull('arrival_info_sent_at')
->whereDate('arrival', '>=', $today)
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_DAYS_BEFORE)));
foreach ($arrivals as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
$booking->update(['arrival_info_sent_at' => now()]);
}
$completed = Booking::query()
->where('status', BookingStatus::Paid)
->whereDate('departure', '<', $today)
->get();
$completed->each->update(['status' => BookingStatus::Completed]);
return [
'deposit_overdue' => $depositOverdue->count(),
'balance_request' => $balanceRequest->count(),
'balance_overdue' => $balanceOverdue->count(),
'arrival_info' => $arrivals->count(),
'completed' => $completed->count(),
];
}
/**
* @param callable(Builder<Booking>): Builder<Booking> $constraints
* @return Collection<int, Booking>
*/
private function bookings(callable $constraints): Collection
{
return $constraints(Booking::query()->with(['guest', 'property', 'payments']))
->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at'))
->get()
->toBase();
}
/**
* @param Collection<int, Booking> $bookings
*/
private function remind(Collection $bookings, string $kind, string $sentAtColumn): void
{
foreach ($bookings as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind));
$booking->update([$sentAtColumn => now()]);
}
}
}
+127
View File
@@ -0,0 +1,127 @@
<?php
namespace App\Actions;
use App\Channels\ChannelSyncException;
use App\Channels\ConflictDetector;
use App\Channels\ExternalPeriod;
use App\Mail\ChannelConflict;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\ChannelSyncLog;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/**
* Imports the occupations of one portal as blocked periods and reports overlaps with
* occupations from anywhere else immediately (possible double booking).
*/
class SyncChannel
{
public function __construct(private ConflictDetector $conflictDetector = new ConflictDetector) {}
public function handle(Channel $channel): ChannelSyncLog
{
$startedAt = microtime(true);
try {
$periods = $channel->connector()->fetchOccupations($channel);
} catch (ChannelSyncException $exception) {
$channel->forceFill(['last_synced_at' => now(), 'last_error' => $exception->getMessage()])->save();
return $channel->syncLogs()->create([
'successful' => false,
'message' => $exception->getMessage(),
'duration_ms' => $this->elapsed($startedAt),
]);
}
$today = CarbonImmutable::today();
$suffix = config('channels.uid_suffix');
$periods = array_values(array_filter(
$periods,
fn (ExternalPeriod $period): bool => $period->endsOn->greaterThan($today) && ! str_ends_with($period->uid, $suffix),
));
$counts = ['added' => 0, 'changed' => 0, 'removed' => 0];
$conflicts = [];
DB::transaction(function () use ($channel, $periods, $today, &$counts, &$conflicts): void {
$existing = $channel->blockedPeriods()->where('source', 'channel')->get()->keyBy('external_uid');
$fromEmails = $channel->blockedPeriods()->where('source', 'email')->get();
$seen = [];
foreach ($periods as $period) {
$seen[$period->uid] = true;
$block = $existing->get($period->uid);
if ($block && $block->starts_on->equalTo($period->startsOn) && $block->ends_on->equalTo($period->endsOn)) {
continue;
}
$attributes = [
'property_id' => $channel->property_id,
'starts_on' => $period->startsOn->toDateString(),
'ends_on' => $period->endsOn->toDateString(),
'reason' => "{$channel->name}".($period->summary ? ": {$period->summary}" : ''),
'source' => 'channel',
];
$confirmedEmailBlock = $block ? null : $fromEmails->first(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->equalTo($period->startsOn) && $emailBlock->ends_on->equalTo($period->endsOn));
if ($confirmedEmailBlock) {
// Already blocked from the portal's e-mail; the calendar only confirms it.
$confirmedEmailBlock->update([...$attributes, 'external_uid' => $period->uid]);
$fromEmails = $fromEmails->reject(fn (BlockedPeriod $emailBlock): bool => $emailBlock->is($confirmedEmailBlock));
$counts['changed']++;
continue;
}
if ($block) {
$block->update($attributes);
$counts['changed']++;
} else {
$block = $channel->blockedPeriods()->create([...$attributes, 'external_uid' => $period->uid]);
$counts['added']++;
}
// E-mail blocks of this portal overlapping the calendar entry describe the same booking with deviating dates.
$superseded = $fromEmails->filter(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->lessThan($block->ends_on) && $emailBlock->ends_on->greaterThan($block->starts_on));
$superseded->each->delete();
$fromEmails = $fromEmails->diff($superseded);
array_push($conflicts, ...$this->conflictDetector->conflictsFor($block));
}
$stale = $existing->reject(fn (BlockedPeriod $block, string $uid): bool => isset($seen[$uid]) || $block->ends_on->lessThanOrEqualTo($today));
$stale->each->delete();
$counts['removed'] = $stale->count();
});
$channel->forceFill([
'last_synced_at' => now(),
'last_success_at' => now(),
'last_error' => null,
'alerted_at' => null,
])->save();
if ($conflicts !== []) {
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelConflict($channel, $conflicts)));
}
return $channel->syncLogs()->create([
'successful' => true,
'events' => count($periods),
...$counts,
'conflicts' => count($conflicts),
'duration_ms' => $this->elapsed($startedAt),
]);
}
private function elapsed(float $startedAt): int
{
return (int) round((microtime(true) - $startedAt) * 1000);
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Channels;
use App\Channels\Contracts\ChannelConnector;
use InvalidArgumentException;
/**
* Resolves the connectors registered in config/channels.php.
*/
class ChannelRegistry
{
/**
* @return array<string, class-string<ChannelConnector>>
*/
public function connectors(): array
{
return collect(config('channels.connectors'))
->mapWithKeys(fn (string $class): array => [$class::key() => $class])
->all();
}
public function resolve(string $key): ChannelConnector
{
$class = $this->connectors()[$key] ?? throw new InvalidArgumentException("Unknown channel connector [{$key}].");
return app($class);
}
/**
* @return array<string, string>
*/
public function options(): array
{
return array_map(fn (string $class): string => $class::label(), $this->connectors());
}
}
+7
View File
@@ -0,0 +1,7 @@
<?php
namespace App\Channels;
use RuntimeException;
class ChannelSyncException extends RuntimeException {}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Channels;
use App\Models\BlockedPeriod;
use App\Models\Booking;
/**
* Finds occupations from other sources that overlap a block reported by a portal
* (a possible double booking). Blocks of the same portal never conflict with each other.
*/
class ConflictDetector
{
/**
* @return list<string> human readable descriptions
*/
public function conflictsFor(BlockedPeriod $block): array
{
$property = $block->property;
$channelName = $block->channel->name ?? 'Sperre';
$period = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y');
$bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get()
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guest->full_name}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
$blocks = $property->blockedPeriods()
->overlapping($block->starts_on, $block->ends_on)
->whereKeyNot($block->getKey())
->when($block->channel_id, fn ($query) => $query->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $block->channel_id)))
->with('channel')
->get()
->map(fn (BlockedPeriod $other): string => "{$channelName} meldet {$period}, überschneidet sich mit Sperre „".($other->channel->name ?? $other->reason ?? 'manuell')."“ ({$other->starts_on->format('d.m.Y')} – {$other->ends_on->format('d.m.Y')})");
return [...$bookings->all(), ...$blocks->all()];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Channels\Contracts;
use App\Channels\ChannelSyncException;
use App\Channels\ExternalPeriod;
use App\Models\Channel;
use Filament\Schemas\Components\Component;
/**
* Connects one kind of portal or channel manager. Register implementations in config/channels.php.
*/
interface ChannelConnector
{
/**
* Stable identifier stored on the channel, e.g. "ical".
*/
public static function key(): string;
public static function label(): string;
/**
* Admin form fields for the connector's settings; use state paths below "settings.".
*
* @return list<Component>
*/
public static function settingsSchema(): array;
/**
* Whether occupations can currently be imported (e.g. an import URL is configured).
*/
public function canImport(Channel $channel): bool;
/**
* All occupations the portal currently reports.
*
* @return list<ExternalPeriod>
*
* @throws ChannelSyncException
*/
public function fetchOccupations(Channel $channel): array;
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Channels;
use Carbon\CarbonImmutable;
/**
* An occupation reported by a portal: nights from startsOn up to (excluding) endsOn.
*/
final readonly class ExternalPeriod
{
public function __construct(
public string $uid,
public CarbonImmutable $startsOn,
public CarbonImmutable $endsOn,
public ?string $summary = null,
) {}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Channels\ICal;
use App\Channels\ChannelSyncException;
use App\Channels\Contracts\ChannelConnector;
use App\Models\Channel;
use Filament\Forms\Components\TextInput;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
/**
* Generic calendar connection that works with almost every portal: we read the portal's iCal export
* and the portal reads our feed for this channel.
*/
class ICalConnector implements ChannelConnector
{
public function __construct(private ICalParser $parser) {}
public static function key(): string
{
return 'ical';
}
public static function label(): string
{
return 'Kalender-Abgleich (iCal)';
}
public static function settingsSchema(): array
{
return [
TextInput::make('settings.import_url')
->label('iCal-Export-Adresse des Portals')
->helperText('Im Vermieterbereich des Portals unter „Kalender exportieren“. Leer lassen, wenn das Portal keinen Kalender anbietet.')
->url()
->maxLength(2048),
];
}
public function canImport(Channel $channel): bool
{
return filled($channel->setting('import_url'));
}
public function fetchOccupations(Channel $channel): array
{
$url = preg_replace('#^webcals?://#i', 'https://', (string) $channel->setting('import_url'));
try {
$response = Http::timeout(20)
->retry(2, 1000)
->withHeaders(['Accept' => 'text/calendar'])
->get($url)
->throw();
} catch (ConnectionException|RequestException $exception) {
throw new ChannelSyncException('Kalender konnte nicht abgerufen werden: '.$exception->getMessage(), previous: $exception);
}
return $this->parser->parse($response->body());
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace App\Channels\ICal;
use App\Models\Booking;
use App\Models\Channel;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
/**
* The calendar a portal imports from us: every occupation of the property except the ones that
* came from this very portal (otherwise the portal would block its own bookings twice).
* Events carry no guest data.
*/
class ICalFeed
{
public function build(Channel $channel): string
{
$property = $channel->property;
$from = CarbonImmutable::today()->subDays(30);
$until = CarbonImmutable::today()->addYears(2);
$suffix = config('channels.uid_suffix');
$events = [];
foreach ($property->bookings()->occupying()->overlapping($from, $until)->get() as $booking) {
/** @var Booking $booking */
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at);
}
$blocks = $property->blockedPeriods()
->overlapping($from, $until)
->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $channel->id))
->get();
foreach ($blocks as $block) {
$events[] = $this->event("block-{$block->id}{$suffix}", $block->starts_on, $block->ends_on, $block->updated_at);
}
return implode("\r\n", [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//Ferienwohnung Stommer//Belegung//DE',
'CALSCALE:GREGORIAN',
'METHOD:PUBLISH',
'X-WR-CALNAME:'.$this->escape($property->name),
...$events,
'END:VCALENDAR',
])."\r\n";
}
private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified): string
{
return implode("\r\n", [
'BEGIN:VEVENT',
"UID:{$uid}",
'DTSTAMP:'.($modified ?? now())->utc()->format('Ymd\THis\Z'),
'DTSTART;VALUE=DATE:'.$start->format('Ymd'),
'DTEND;VALUE=DATE:'.$end->format('Ymd'),
'SUMMARY:Belegt',
'TRANSP:OPAQUE',
'END:VEVENT',
]);
}
private function escape(string $text): string
{
return str_replace(['\\', ';', ',', "\n"], ['\\\\', '\\;', '\\,', '\\n'], $text);
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
namespace App\Channels\ICal;
use App\Channels\ChannelSyncException;
use App\Channels\ExternalPeriod;
use Carbon\CarbonImmutable;
/**
* Minimal RFC 5545 reader for availability feeds: VEVENTs with DTSTART/DTEND (date or date-time),
* UID and SUMMARY. Cancelled events and events without a positive length are skipped.
*/
class ICalParser
{
/**
* @return list<ExternalPeriod>
*
* @throws ChannelSyncException
*/
public function parse(string $ics): array
{
if (! str_contains($ics, 'BEGIN:VCALENDAR')) {
throw new ChannelSyncException('Die Antwort ist kein iCal-Kalender.');
}
$lines = explode("\n", preg_replace("/\r?\n[ \t]/", '', str_replace("\r\n", "\n", $ics)));
$periods = [];
$event = null;
foreach ($lines as $line) {
$line = rtrim($line, "\r");
if ($line === 'BEGIN:VEVENT') {
$event = [];
continue;
}
if ($line === 'END:VEVENT') {
if ($event !== null && ($period = $this->toPeriod($event))) {
$periods[] = $period;
}
$event = null;
continue;
}
if ($event !== null && str_contains($line, ':')) {
[$nameWithParams, $value] = explode(':', $line, 2);
$parts = explode(';', $nameWithParams);
$event[strtoupper($parts[0])] = ['value' => $value, 'params' => array_slice($parts, 1)];
}
}
return $periods;
}
/**
* @param array<string, array{value: string, params: list<string>}> $event
*/
private function toPeriod(array $event): ?ExternalPeriod
{
if (! isset($event['DTSTART']) || strtoupper($event['STATUS']['value'] ?? '') === 'CANCELLED') {
return null;
}
$start = $this->toDate($event['DTSTART']);
$end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start?->addDay();
if ($start === null || $end === null || $end->lessThanOrEqualTo($start)) {
return null;
}
$uid = $event['UID']['value'] ?? sha1($start->toDateString().'|'.$end->toDateString());
return new ExternalPeriod($uid, $start, $end, $this->unescape($event['SUMMARY']['value'] ?? null));
}
/**
* @param array{value: string, params: list<string>} $property
*/
private function toDate(array $property): ?CarbonImmutable
{
$value = trim($property['value']);
if (preg_match('/^\d{8}$/', $value)) {
return CarbonImmutable::createFromFormat('!Ymd', $value);
}
if (preg_match('/^(\d{8})T(\d{6})(Z?)$/', $value, $match)) {
$timezone = $match[3] === 'Z' ? 'UTC' : $this->timezone($property['params']);
return CarbonImmutable::createFromFormat('YmdHis', $match[1].$match[2], $timezone)
->setTimezone(config('app.timezone'))
->startOfDay();
}
return null;
}
/**
* @param list<string> $params
*/
private function timezone(array $params): string
{
foreach ($params as $param) {
if (str_starts_with(strtoupper($param), 'TZID=')) {
$tz = trim(substr($param, 5), '"');
return in_array($tz, timezone_identifiers_list(), true) ? $tz : config('app.timezone');
}
}
return config('app.timezone');
}
private function unescape(?string $text): ?string
{
return $text === null ? null : str_replace(['\\n', '\\N', '\\,', '\\;', '\\\\'], ["\n", "\n", ',', ';', '\\'], $text);
}
}
+94
View File
@@ -0,0 +1,94 @@
<?php
namespace App\Channels\Mail;
use App\Channels\ChannelSyncException;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Throwable;
use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Message;
/**
* Reads recent e-mails of the given senders from the configured IMAP mailbox without marking them as read.
* Works without the PHP imap extension.
*/
class MailboxReader
{
public const LAST_SUCCESS_KEY = 'mailbox:last_success_at';
public const LAST_ERROR_KEY = 'mailbox:last_error';
public static function isConfigured(): bool
{
return filled(config('fewo.mailbox.host')) && filled(config('fewo.mailbox.username'));
}
/**
* @param list<string> $senders addresses or domains
* @return list<PortalMail>
*
* @throws ChannelSyncException
*/
public function fetch(array $senders): array
{
$config = config('fewo.mailbox');
try {
$client = (new ClientManager)->make([
'host' => $config['host'],
'port' => $config['port'],
'encryption' => $config['encryption'],
'validate_cert' => true,
'username' => $config['username'],
'password' => $config['password'],
'protocol' => 'imap',
]);
$client->connect();
$folder = $client->getFolderByPath($config['folder']);
$mails = [];
foreach ($senders as $sender) {
$messages = $folder->query()
->whereSince(CarbonImmutable::today()->subDays($config['lookback_days']))
->whereFrom($sender)
->leaveUnread()
->get();
foreach ($messages as $message) {
$mails[] = $this->toPortalMail($message);
}
}
$client->disconnect();
} catch (Throwable $exception) {
Cache::forever(self::LAST_ERROR_KEY, $exception->getMessage());
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
}
Cache::forever(self::LAST_SUCCESS_KEY, now()->toIso8601String());
Cache::forget(self::LAST_ERROR_KEY);
return $mails;
}
private function toPortalMail(Message $message): PortalMail
{
$text = $message->getTextBody();
if (trim($text) === '') {
$text = strip_tags(preg_replace('#<(br|p|div|tr|li)[^>]*>#i', "\n", $message->getHTMLBody()));
}
$from = $message->getFrom()->first();
$date = $message->getDate()->first();
return new PortalMail(
messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)),
from: (string) ($from->mail ?? ''),
subject: (string) $message->getSubject()->first(),
text: $text,
receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(),
);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Channels\Mail;
use App\Enums\PortalEmailType;
use Carbon\CarbonImmutable;
final readonly class ParsedPortalMail
{
public function __construct(
public PortalEmailType $type,
public ?CarbonImmutable $startsOn = null,
public ?CarbonImmutable $endsOn = null,
public ?string $reference = null,
) {}
public function hasPeriod(): bool
{
return $this->startsOn !== null && $this->endsOn !== null;
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Channels\Mail;
use Carbon\CarbonImmutable;
/**
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook.
*/
final readonly class PortalMail
{
public function __construct(
public string $messageId,
public string $from,
public string $subject,
public string $text,
public CarbonImmutable $receivedAt,
) {}
}
+194
View File
@@ -0,0 +1,194 @@
<?php
namespace App\Channels\Mail;
use App\Enums\PortalEmailType;
use Carbon\CarbonImmutable;
/**
* Reads booking notifications of portals (German and English). It only extracts what it can find
* with confidence; everything else is left empty so that the e-mail is flagged for review.
*/
class PortalMailParser
{
private const CANCELLATION = ['storniert', 'stornierung', 'cancelled', 'canceled', 'cancellation', 'abgesagt'];
private const BOOKING = ['neue buchung', 'buchung bestätigt', 'buchungsbestätigung', 'reservierung bestätigt', 'sofortbuchung', 'hat gebucht', 'ist gebucht', 'new booking', 'booking confirmed', 'reservation confirmed', 'instant booking', 'you have a new reservation', 'neue reservierung'];
/** Checked before bookings: "Neue Buchungsanfrage" is not a confirmed booking. */
private const INQUIRY = ['buchungsanfrage', 'booking request', 'reservation request', 'anfrage', 'inquiry', 'enquiry'];
private const MONTHS = [
'jan' => 1, 'januar' => 1, 'january' => 1,
'feb' => 2, 'februar' => 2, 'february' => 2,
'mär' => 3, 'märz' => 3, 'mrz' => 3, 'mar' => 3, 'march' => 3,
'apr' => 4, 'april' => 4,
'mai' => 5, 'may' => 5,
'jun' => 6, 'juni' => 6, 'june' => 6,
'jul' => 7, 'juli' => 7, 'july' => 7,
'aug' => 8, 'august' => 8,
'sep' => 9, 'sept' => 9, 'september' => 9,
'okt' => 10, 'oktober' => 10, 'oct' => 10, 'october' => 10,
'nov' => 11, 'november' => 11,
'dez' => 12, 'dezember' => 12, 'dec' => 12, 'december' => 12,
];
public function parse(string $subject, string $text): ParsedPortalMail
{
$content = $this->normalize($subject."\n".$text);
$type = $this->type(mb_strtolower($subject))
?? $this->type(mb_strtolower($this->normalize($text)))
?? PortalEmailType::Unknown;
[$startsOn, $endsOn] = $this->period($content);
return new ParsedPortalMail($type, $startsOn, $endsOn, $this->reference($content));
}
/**
* The subject decides first; the body only when the subject is not conclusive.
*/
private function type(string $text): ?PortalEmailType
{
return match (true) {
$this->containsAny($text, self::CANCELLATION) => PortalEmailType::Cancellation,
$this->containsAny($text, self::INQUIRY) => PortalEmailType::Inquiry,
$this->containsAny($text, self::BOOKING) => PortalEmailType::Booking,
default => null,
};
}
/**
* @return array{?CarbonImmutable, ?CarbonImmutable}
*/
private function period(string $content): array
{
$dates = $this->dates($content);
$arrival = $this->dateAfterLabel($content, $dates, '/\b(anreise|ankunft|check-?in|arrival)\b/iu');
$departure = $this->dateAfterLabel($content, $dates, '/\b(abreise|check-?out|departure)\b/iu');
if ($arrival === null || $departure === null) {
[$arrival, $departure] = $this->firstPlausiblePair($dates);
}
if ($arrival === null || $departure === null || ! $this->isPlausible($arrival, $departure)) {
return [null, null];
}
return [$arrival, $departure];
}
/**
* All dates in the text with their offsets, in order of appearance.
*
* @return list<array{offset: int, date: CarbonImmutable}>
*/
private function dates(string $content): array
{
$monthNames = implode('|', array_map(fn (string $name): string => preg_quote($name, '/'), array_keys(self::MONTHS)));
$patterns = [
'/\b(?<d>\d{1,2})\.(?<m>\d{1,2})\.(?<y>\d{4}|\d{2})\b/u',
'/\b(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})\b/u',
'/\b(?<d>\d{1,2})\.?\s+(?<mn>'.$monthNames.')\.?\s+(?<y>\d{4})\b/iu',
'/\b(?<mn>'.$monthNames.')\.?\s+(?<d>\d{1,2}),?\s+(?<y>\d{4})\b/iu',
];
$dates = [];
foreach ($patterns as $pattern) {
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
foreach ($matches as $match) {
$month = isset($match['mn']) && $match['mn'][0] !== '' ? self::MONTHS[mb_strtolower($match['mn'][0])] ?? null : (int) $match['m'][0];
$year = (int) $match['y'][0];
$year = $year < 100 ? 2000 + $year : $year;
if ($month !== null && checkdate($month, (int) $match['d'][0], $year)) {
$dates[] = ['offset' => $match[0][1], 'date' => CarbonImmutable::create($year, $month, (int) $match['d'][0])];
}
}
}
usort($dates, fn (array $a, array $b): int => $a['offset'] <=> $b['offset']);
return $dates;
}
/**
* @param list<array{offset: int, date: CarbonImmutable}> $dates
*/
private function dateAfterLabel(string $content, array $dates, string $labelPattern): ?CarbonImmutable
{
if (! preg_match($labelPattern, $content, $label, PREG_OFFSET_CAPTURE)) {
return null;
}
$labelEnd = $label[0][1] + strlen($label[0][0]);
foreach ($dates as $date) {
if ($date['offset'] >= $labelEnd && $date['offset'] - $labelEnd <= 80) {
return $date['date'];
}
}
return null;
}
/**
* @param list<array{offset: int, date: CarbonImmutable}> $dates
* @return array{?CarbonImmutable, ?CarbonImmutable}
*/
private function firstPlausiblePair(array $dates): array
{
foreach ($dates as $index => $first) {
foreach (array_slice($dates, $index + 1) as $second) {
if ($this->isPlausible($first['date'], $second['date'])) {
return [$first['date'], $second['date']];
}
}
}
return [null, null];
}
private function isPlausible(CarbonImmutable $arrival, CarbonImmutable $departure): bool
{
return $departure->greaterThan($arrival)
&& $arrival->diffInDays($departure) <= 90
&& $arrival->greaterThanOrEqualTo(CarbonImmutable::today()->subDays(2))
&& $arrival->lessThanOrEqualTo(CarbonImmutable::today()->addYears(3));
}
private function reference(string $content): ?string
{
if (preg_match('/\b(HA-[A-Z0-9]{5,})\b/', $content, $match)) {
return $match[1];
}
if (preg_match('/(?:buchungsnummer|buchungs-nr\.?|reservierungsnummer|reservation id|reservation number|booking id|booking number)\s*[:#]?\s*([A-Z0-9][A-Z0-9-]{4,})/iu', $content, $match)) {
return $match[1];
}
return null;
}
private function normalize(string $text): string
{
$text = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return preg_replace('/[ \t\x{00A0}\x{202F}]+/u', ' ', $text);
}
/**
* @param list<string> $needles
*/
private function containsAny(string $haystack, array $needles): bool
{
foreach ($needles as $needle) {
if (str_contains($haystack, $needle)) {
return true;
}
}
return false;
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Console\Commands;
use App\Enums\UserRole;
use App\Models\User;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Validation\Rules\Password;
use function Laravel\Prompts\password;
use function Laravel\Prompts\select;
use function Laravel\Prompts\text;
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content}')]
#[Description('Create an admin panel account (the password is entered interactively and never passed as an argument)')]
class CreateUser extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$email = $this->argument('email') ?? text('E-Mail-Adresse', required: true, validate: ['email' => 'email']);
$email = mb_strtolower(trim($email));
if (User::where('email', $email)->exists()) {
$this->error("Es gibt bereits einen Benutzer mit {$email}.");
return self::FAILURE;
}
$name = $this->option('name') ?? text('Name', required: true);
$role = $this->option('role') !== null
? UserRole::tryFrom($this->option('role'))
: UserRole::from(select('Rolle', collect(UserRole::cases())->mapWithKeys(fn (UserRole $role): array => [$role->value => "{$role->getLabel()} – {$role->getDescription()}"])->all(), default: UserRole::Admin->value));
if ($role === null) {
$this->error('Unbekannte Rolle. Erlaubt: '.implode(', ', array_column(UserRole::cases(), 'value')));
return self::FAILURE;
}
$password = password('Passwort (mind. 12 Zeichen)', required: true, validate: ['password' => Password::min(12)]);
if (password('Passwort wiederholen', required: true) !== $password) {
$this->error('Die Passwörter stimmen nicht überein.');
return self::FAILURE;
}
User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
$this->info("Benutzer {$email} ({$role->getLabel()}) angelegt.");
if ($role === UserRole::Admin) {
$this->line('Bei der ersten Anmeldung wird die Zwei-Faktor-Anmeldung mit einer Authenticator-App eingerichtet.');
}
return self::SUCCESS;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Console\Commands;
use App\Actions\ProcessPortalMail;
use App\Channels\ChannelSyncException;
use App\Channels\Mail\MailboxReader;
use App\Models\Channel;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('channels:fetch-mail')]
#[Description('Read booking notifications of the portals from the mailbox and block recognised bookings immediately')]
class FetchPortalMail extends Command
{
/**
* Execute the console command.
*/
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail): int
{
if (! MailboxReader::isConfigured()) {
$this->line('Kein Postfach konfiguriert (FEWO_MAILBOX_HOST).');
return self::SUCCESS;
}
$senders = Channel::query()->active()->get()
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
->unique()
->values()
->all();
if ($senders === []) {
$this->line('Für kein Portal sind Absender hinterlegt.');
return self::SUCCESS;
}
try {
$mails = $reader->fetch($senders);
} catch (ChannelSyncException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
foreach ($mails as $mail) {
if ($record = $processPortalMail->handle($mail)) {
$this->info("{$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
}
}
return self::SUCCESS;
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Console\Commands;
use App\Actions\SyncChannel;
use App\Models\Channel;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('channels:sync {channel? : ID of a single channel}')]
#[Description('Import the occupations of all active portals (or one) and report conflicts')]
class SyncChannels extends Command
{
/**
* Execute the console command.
*/
public function handle(SyncChannel $syncChannel): int
{
$channels = Channel::query()->active()
->when($this->argument('channel'), fn ($query, $id) => $query->whereKey($id))
->get()
->filter(fn (Channel $channel): bool => $channel->importsOccupations());
foreach ($channels as $channel) {
$log = $syncChannel->handle($channel);
$log->successful
? $this->info("✓ {$channel->name}: {$log->events} Belegungen, +{$log->added} ~{$log->changed} -{$log->removed}, Konflikte: {$log->conflicts}")
: $this->error("✗ {$channel->name}: {$log->message}");
}
return self::SUCCESS;
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Documents;
use App\Models\Booking;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;
/**
* The rental contract as PDF. It is generated once at confirmation and stored, so later changes
* of texts or prices do not alter a contract the guest already received.
*/
class RentalContract
{
private const DISK = 'local';
public function generate(Booking $booking): string
{
$booking->loadMissing(['guest', 'property']);
$path = "contracts/Mietvertrag-{$booking->reference}.pdf";
Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', ['booking' => $booking])->setPaper('a4')->output());
$booking->update(['contract_path' => $path]);
return $path;
}
public function absolutePath(Booking $booking): ?string
{
return $booking->contract_path && Storage::disk(self::DISK)->exists($booking->contract_path)
? Storage::disk(self::DISK)->path($booking->contract_path)
: null;
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum ChannelTaskAction: string implements HasColor, HasLabel
{
case Block = 'block';
case Unblock = 'unblock';
public function getLabel(): string
{
return match ($this) {
self::Block => 'Sperren',
self::Unblock => 'Freigeben',
};
}
public function getColor(): string
{
return match ($this) {
self::Block => 'danger',
self::Unblock => 'success',
};
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum ChannelTaskStatus: string implements HasColor, HasLabel
{
case Open = 'open';
case Done = 'done';
case Dismissed = 'dismissed';
public function getLabel(): string
{
return match ($this) {
self::Open => 'Offen',
self::Done => 'Erledigt',
self::Dismissed => 'Verworfen',
};
}
public function getColor(): string
{
return match ($this) {
self::Open => 'warning',
self::Done => 'success',
self::Dismissed => 'gray',
};
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum PaymentMethod: string implements HasLabel
{
case Transfer = 'transfer';
case Cash = 'cash';
case Other = 'other';
public function getLabel(): string
{
return match ($this) {
self::Transfer => 'Überweisung',
self::Cash => 'Bar',
self::Other => 'Sonstiges',
};
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum PortalEmailStatus: string implements HasColor, HasLabel
{
/** A new block was created from the e-mail. */
case Blocked = 'blocked';
/** The period was already blocked (e.g. by the calendar sync). */
case AlreadyKnown = 'already_known';
/** A cancellation released a block created from an e-mail. */
case Released = 'released';
case NeedsReview = 'needs_review';
case Reviewed = 'reviewed';
case Ignored = 'ignored';
public function getLabel(): string
{
return match ($this) {
self::Blocked => 'Gesperrt',
self::AlreadyKnown => 'Bereits gesperrt',
self::Released => 'Freigegeben',
self::NeedsReview => 'Bitte prüfen',
self::Reviewed => 'Geprüft',
self::Ignored => 'Ignoriert',
};
}
public function getColor(): string
{
return match ($this) {
self::Blocked, self::Released => 'success',
self::AlreadyKnown, self::Reviewed, self::Ignored => 'gray',
self::NeedsReview => 'danger',
};
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum PortalEmailType: string implements HasLabel
{
case Booking = 'booking';
case Cancellation = 'cancellation';
case Inquiry = 'inquiry';
case Unknown = 'unknown';
public function getLabel(): string
{
return match ($this) {
self::Booking => 'Buchung',
self::Cancellation => 'Stornierung',
self::Inquiry => 'Anfrage',
self::Unknown => 'Unbekannt',
};
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* "How did you find us?" – answered by the guest in the request form.
*/
enum ReferralSource: string implements HasLabel
{
case SearchEngine = 'search_engine';
case FewoDirekt = 'fewo_direkt';
case Ostseeklar = 'ostseeklar';
case FerienUndWohnen = 'ferienundwohnen';
case TouristInformation = 'tourist_information';
case SocialMedia = 'social_media';
case Recommendation = 'recommendation';
case ReturningGuest = 'returning_guest';
case Other = 'other';
public function getLabel(): string
{
return match ($this) {
self::SearchEngine => 'Suchmaschine (z. B. Google)',
self::FewoDirekt => 'FeWo-direkt',
self::Ostseeklar => 'Ostseeklar',
self::FerienUndWohnen => 'ferienundwohnen.de',
self::TouristInformation => 'Tourist-Information Kühlungsborn',
self::SocialMedia => 'Social Media',
self::Recommendation => 'Empfehlung',
self::ReturningGuest => 'Ich war schon Gast',
self::Other => 'Sonstiges',
};
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ class EditContent extends Page
protected static ?string $slug = 'texte';
protected static ?int $navigationSort = 2;
protected static ?int $navigationSort = 3;
/** @var array<string, ?string> */
public array $data = [];
@@ -27,7 +27,7 @@ class AmenityResource extends Resource
protected static ?string $pluralModelLabel = 'Ausstattung';
protected static ?int $navigationSort = 3;
protected static ?int $navigationSort = 4;
public static function form(Schema $schema): Schema
{
@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\Appearances;
use App\Filament\Resources\Appearances\Pages\CreateAppearance;
use App\Filament\Resources\Appearances\Pages\EditAppearance;
use App\Filament\Resources\Appearances\Pages\ListAppearances;
use App\Filament\Resources\Appearances\Schemas\AppearanceForm;
use App\Filament\Resources\Appearances\Tables\AppearancesTable;
use App\Models\Appearance;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
class AppearanceResource extends Resource
{
protected static ?string $model = Appearance::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSwatch;
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
protected static ?string $modelLabel = 'Erscheinungsbild';
protected static ?string $pluralModelLabel = 'Erscheinungsbilder';
protected static ?int $navigationSort = 1;
public static function form(Schema $schema): Schema
{
return AppearanceForm::configure($schema);
}
public static function table(Table $table): Table
{
return AppearancesTable::configure($table);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => ListAppearances::route('/'),
'create' => CreateAppearance::route('/create'),
'edit' => EditAppearance::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Appearances\Pages;
use App\Filament\Resources\Appearances\AppearanceResource;
use Filament\Resources\Pages\CreateRecord;
class CreateAppearance extends CreateRecord
{
protected static string $resource = AppearanceResource::class;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Appearances\Pages;
use App\Filament\Resources\Appearances\AppearanceResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditAppearance extends EditRecord
{
protected static string $resource = AppearanceResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Appearances\Pages;
use App\Filament\Resources\Appearances\AppearanceResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListAppearances extends ListRecords
{
protected static string $resource = AppearanceResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
@@ -0,0 +1,110 @@
<?php
namespace App\Filament\Resources\Appearances\Schemas;
use App\Models\Appearance;
use App\Models\Photo;
use App\Models\Site;
use App\Models\SpecialOffer;
use App\Themes\ThemeRegistry;
use Closure;
use Filament\Forms\Components\ColorPicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
class AppearanceForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->columns(2)
->components([
Section::make('Zeitraum')
->description('Wiederholt sich jedes Jahr. Überschneiden sich Zeiträume, gilt die höhere Priorität (z. B. Silvester vor Winter). Ohne Zeitraum greift das Standard-Erscheinungsbild.')
->columns(2)
->schema([
TextInput::make('name')->label('Name')->placeholder('z. B. Weihnachten')->required()->maxLength(60),
Select::make('site_id')
->label('Website')
->options(fn (): array => Site::query()->pluck('name', 'id')->all())
->default(fn (): ?int => Site::query()->where('is_default', true)->value('id'))
->required(),
self::dayField('starts_md', 'Von (TT.MM.)'),
self::dayField('ends_md', 'Bis einschließlich (TT.MM.)'),
TextInput::make('priority')->label('Priorität')->integer()->minValue(0)->default(10),
Toggle::make('is_default')->label('Standard (wenn kein Zeitraum passt)')->inline(false),
Toggle::make('is_active')->label('Aktiv')->default(true)->inline(false),
]),
Section::make('Bild & Angebot')
->columns(2)
->schema([
Select::make('hero_photo_id')
->label('Titelbild')
->options(fn (): array => Photo::query()->orderBy('category')->orderBy('sort_order')->pluck('alt_text', 'id')->all())
->searchable()
->placeholder('Bild der Seite verwenden'),
Select::make('featured_offer_id')
->label('Hervorgehobenes Sonderangebot')
->options(fn (): array => SpecialOffer::query()->where('is_active', true)->pluck('name', 'id')->all())
->placeholder('keins'),
]),
Section::make('Texte')
->description('Leer lassen = Text der Seite bzw. kein Banner.')
->columns(2)
->collapsible()
->schema(collect(Appearance::OVERRIDABLE)
->map(fn (string $label, string $key) => TextInput::make('overrides.'.$key)->label($label)->maxLength(255))
->values()
->all()),
Section::make('Farben')
->description('Nur ändern, was anders aussehen soll; leere Felder übernehmen die Farben des Themes.')
->columns(3)
->collapsible()
->collapsed()
->schema(fn (Get $get): array => self::tokenFields($get('site_id'))),
]);
}
/**
* @return list<ColorPicker>
*/
public static function tokenFields(int|string|null $siteId, string $statePath = 'tokens'): array
{
$theme = Site::find($siteId)?->theme ?? config('themes.base');
return collect(app(ThemeRegistry::class)->get($theme)->tokens)
->map(fn (array $token, string $key): ColorPicker => ColorPicker::make("{$statePath}.{$key}")->label($token['label'])->placeholder($token['default']))
->values()
->all();
}
/**
* Day of the year entered as "TT.MM." and stored as "MM-DD".
*/
private static function dayField(string $name, string $label): TextInput
{
return TextInput::make($name)
->label($label)
->placeholder('24.12.')
->formatStateUsing(fn (?string $state): ?string => $state ? substr($state, 3, 2).'.'.substr($state, 0, 2).'.' : null)
->dehydrateStateUsing(fn (?string $state): ?string => self::toMonthDay($state))
->rule(fn (): Closure => function (string $attribute, mixed $value, Closure $fail): void {
if (filled($value) && self::toMonthDay((string) $value) === null) {
$fail('Bitte als TT.MM. eingeben, z. B. 24.12.');
}
});
}
private static function toMonthDay(?string $value): ?string
{
if (blank($value) || ! preg_match('/^\s*(\d{1,2})\.(\d{1,2})\.?\s*$/', $value, $match)) {
return null;
}
return checkdate((int) $match[2], (int) $match[1], 2024) ? sprintf('%02d-%02d', $match[2], $match[1]) : null;
}
}
@@ -0,0 +1,50 @@
<?php
namespace App\Filament\Resources\Appearances\Tables;
use App\Models\Appearance;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Table;
use Illuminate\Support\Facades\URL;
class AppearancesTable
{
public static function configure(Table $table): Table
{
return $table
->defaultSort('priority', 'desc')
->description('Die Webseite wechselt automatisch nach Datum. Mit „Vorschau“ sehen Sie ein Erscheinungsbild schon vorher.')
->columns([
TextColumn::make('name')->label('Erscheinungsbild')->weight('medium'),
TextColumn::make('period')
->label('Zeitraum')
->state(fn (Appearance $record): string => $record->is_default && ! $record->starts_md ? 'Standard' : self::day($record->starts_md).' – '.self::day($record->ends_md)),
TextColumn::make('priority')->label('Priorität')->sortable(),
IconColumn::make('current')
->label('Jetzt aktiv')
->boolean()
->state(fn (Appearance $record): bool => $record->site?->appearanceOn(today())?->is($record) ?? false),
ToggleColumn::make('is_active')->label('Aktiv'),
])
->recordActions([
Action::make('preview')
->label('Vorschau')
->icon(Heroicon::OutlinedEye)
->color('gray')
->url(fn (Appearance $record): string => URL::temporarySignedRoute('home', now()->addDay(), ['vorschau' => $record->id]), shouldOpenInNewTab: true),
EditAction::make(),
DeleteAction::make()->visible(fn (Appearance $record): bool => ! $record->is_default),
]);
}
private static function day(?string $monthDay): string
{
return $monthDay ? substr($monthDay, 3, 2).'.'.substr($monthDay, 0, 2).'.' : '?';
}
}
@@ -6,6 +6,7 @@
use App\Filament\Resources\Bookings\Pages\CreateBooking;
use App\Filament\Resources\Bookings\Pages\ListBookings;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Filament\Resources\Bookings\Schemas\BookingInfolist;
use App\Filament\Resources\Bookings\Tables\BookingsTable;
@@ -63,6 +64,13 @@ public static function getNavigationBadgeColor(): string
return 'warning';
}
public static function getRelations(): array
{
return [
PaymentsRelationManager::class,
];
}
public static function getPages(): array
{
return [
@@ -4,6 +4,7 @@
use App\Actions\ConfirmBooking;
use App\Actions\DeclineBooking;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
@@ -75,7 +76,23 @@ protected function getHeaderActions(): array
Notification::make()->title('Vorgemerkt bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send();
}),
Action::make('contract')
->label('Mietvertrag')
->icon(Heroicon::OutlinedDocumentText)
->color('gray')
->visible(fn (): bool => $this->record->contract_path !== null)
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record) ?? abort(404), "Mietvertrag-{$this->record->reference}.pdf")),
ActionGroup::make([
Action::make('regenerateContract')
->label('Mietvertrag neu erzeugen')
->icon(Heroicon::OutlinedArrowPath)
->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying()], true))
->requiresConfirmation()
->modalDescription('Der Vertrag wird mit den aktuellen Texten neu erstellt. Der Gast erhält ihn nicht automatisch.')
->action(function (RentalContract $contract): void {
$contract->generate($this->record);
Notification::make()->title('Mietvertrag neu erzeugt')->success()->send();
}),
Action::make('notes')
->label('Interne Notiz bearbeiten')
->icon(Heroicon::OutlinedPencilSquare)
@@ -0,0 +1,81 @@
<?php
namespace App\Filament\Resources\Bookings\RelationManagers;
use App\Actions\RecordPayment;
use App\Enums\PaymentMethod;
use App\Filament\Forms\Components\EuroInput;
use App\Models\Booking;
use App\Models\Payment;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* @property Booking $ownerRecord
*/
class PaymentsRelationManager extends RelationManager
{
protected static string $relationship = 'payments';
protected static ?string $title = 'Zahlungen';
public function isReadOnly(): bool
{
return false;
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('amount')
->description(fn (): string => 'Bezahlt: '.Money::format($this->ownerRecord->paidAmount()).' · offen: '.Money::format($this->ownerRecord->openAmount()))
->columns([
TextColumn::make('paid_on')->label('Eingang')->date('d.m.Y'),
TextColumn::make('amount')->label('Betrag')->money('EUR', divideBy: 100, locale: 'de'),
TextColumn::make('method')->label('Art'),
TextColumn::make('note')->label('Notiz')->placeholder('–'),
TextColumn::make('recorded_by')->label('Erfasst von')->placeholder('–'),
])
->headerActions([
Action::make('record')
->label('Zahlung erfassen')
->icon(Heroicon::OutlinedBanknotes)
->fillForm(fn (): array => [
'amount' => number_format(($this->ownerRecord->openDeposit() ?: $this->ownerRecord->openAmount()) / 100, 2, '.', ''),
'paid_on' => today(),
'method' => PaymentMethod::Transfer,
])
->schema([
EuroInput::make('amount')->label('Betrag')->helperText('Erstattungen mit Minus erfassen.')->minValue(null)->required(),
DatePicker::make('paid_on')->label('Zahlungseingang')->required(),
Select::make('method')->label('Art')->options(PaymentMethod::class)->required(),
TextInput::make('note')->label('Notiz')->maxLength(255),
])
->action(function (array $data, RecordPayment $recordPayment): void {
$recordPayment->handle(
$this->ownerRecord,
(int) $data['amount'],
CarbonImmutable::parse($data['paid_on']),
$data['method'] instanceof PaymentMethod ? $data['method'] : PaymentMethod::from($data['method']),
$data['note'] ?: null,
auth()->user()?->name,
);
Notification::make()->title('Zahlung erfasst – Status: '.$this->ownerRecord->fresh()->status->getLabel())->success()->send();
}),
])
->recordActions([
DeleteAction::make()->after(fn (Payment $record) => app(RecordPayment::class)->updateStatus($this->ownerRecord->fresh())),
]);
}
}
@@ -48,6 +48,9 @@ public static function configure(Schema $schema): Schema
TextEntry::make('deposit')->label('Anzahlung')->money('EUR', divideBy: 100, locale: 'de'),
TextEntry::make('balance')->label('Restzahlung')->state(fn (Booking $record): string => Money::format($record->total - $record->deposit)),
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y'),
TextEntry::make('paid')->label('Bezahlt')->state(fn (Booking $record): string => Money::format($record->paidAmount())),
TextEntry::make('open')->label('Offen')->state(fn (Booking $record): string => Money::format($record->openAmount()))->color(fn (Booking $record): string => $record->openAmount() > 0 ? 'danger' : 'success'),
TextEntry::make('deposit_due_on')->label('Anzahlung fällig am')->date('d.m.Y')->placeholder('–'),
]),
]),
Section::make('Nachricht des Gastes')
@@ -66,6 +69,11 @@ public static function configure(Schema $schema): Schema
TextEntry::make('confirmed_at')->label('Bestätigt am')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->confirmed_at !== null),
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'),
TextEntry::make('source')->label('Quelle'),
TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'),
TextEntry::make('utm')
->label('Kampagne (UTM)')
->state(fn (Booking $record): ?string => collect([$record->utm_source, $record->utm_medium, $record->utm_campaign])->filter()->implode(' / ') ?: null)
->visible(fn (Booking $record): bool => filled($record->utm_source)),
]),
Section::make('Gast')
->schema([
@@ -4,6 +4,7 @@
use App\Enums\BookingStatus;
use App\Models\Booking;
use App\Support\Money;
use Filament\Actions\ViewAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
@@ -16,7 +17,7 @@ class BookingsTable
public static function configure(Table $table): Table
{
return $table
->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property']))
->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property', 'payments']))
->defaultSort('created_at', 'desc')
->columns([
TextColumn::make('reference')
@@ -46,7 +47,8 @@ public static function configure(Table $table): Table
->label('Pers.'),
TextColumn::make('total')
->label('Gesamt')
->money('EUR', divideBy: 100, locale: 'de'),
->money('EUR', divideBy: 100, locale: 'de')
->description(fn (Booking $record): ?string => in_array($record->status, BookingStatus::occupying(), true) && $record->openAmount() > 0 ? 'offen '.Money::format($record->openAmount()) : null),
TextColumn::make('source')
->label('Quelle')
->toggleable(isToggledHiddenByDefault: true),
@@ -0,0 +1,56 @@
<?php
namespace App\Filament\Resources\ChannelTasks;
use App\Filament\Resources\ChannelTasks\Pages\ListChannelTasks;
use App\Filament\Resources\ChannelTasks\Tables\ChannelTasksTable;
use App\Models\ChannelTask;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
class ChannelTaskResource extends Resource
{
protected static ?string $model = ChannelTask::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentCheck;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static ?string $modelLabel = 'Portal-Aufgabe';
protected static ?string $pluralModelLabel = 'Portal-Aufgaben';
protected static ?int $navigationSort = 4;
public static function table(Table $table): Table
{
return ChannelTasksTable::configure($table);
}
public static function canCreate(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
$open = ChannelTask::query()->open()->count();
return $open > 0 ? (string) $open : null;
}
public static function getNavigationBadgeColor(): string
{
return 'danger';
}
public static function getPages(): array
{
return [
'index' => ListChannelTasks::route('/'),
];
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\ChannelTasks\Pages;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use Filament\Resources\Pages\ListRecords;
class ListChannelTasks extends ListRecords
{
protected static string $resource = ChannelTaskResource::class;
}
@@ -0,0 +1,58 @@
<?php
namespace App\Filament\Resources\ChannelTasks\Tables;
use App\Enums\ChannelTaskStatus;
use App\Models\ChannelTask;
use Filament\Actions\Action;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
class ChannelTasksTable
{
public static function configure(Table $table): Table
{
return $table
->defaultSort('created_at', 'desc')
->description('Diese Portale werden zusätzlich von Hand gepflegt. Bitte die Änderung im Portal vornehmen und hier abhaken.')
->columns([
TextColumn::make('channel.name')->label('Portal')->weight('medium'),
TextColumn::make('action')->label('Aktion')->badge(),
TextColumn::make('period')->label('Zeitraum')->state(fn (ChannelTask $record): string => $record->period()),
TextColumn::make('reason')->label('Anlass')->wrap(),
TextColumn::make('status')->label('Status')->badge()
->description(fn (ChannelTask $record): ?string => $record->completed_by ? "{$record->completed_by}, {$record->completed_at?->format('d.m. H:i')}" : null),
TextColumn::make('created_at')->label('Seit')->since(),
TextColumn::make('automation_error')->label('Automatisierung')->placeholder('–')->limit(40)->toggleable(isToggledHiddenByDefault: true),
])
->filters([
SelectFilter::make('status')
->label('Status')
->options(ChannelTaskStatus::class)
->default(ChannelTaskStatus::Open->value),
])
->recordActions([
Action::make('openPortal')
->label('Portal öffnen')
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
->color('gray')
->url(fn (ChannelTask $record): ?string => $record->channel->manage_url, shouldOpenInNewTab: true)
->visible(fn (ChannelTask $record): bool => filled($record->channel->manage_url)),
Action::make('done')
->label('Erledigt')
->icon(Heroicon::OutlinedCheck)
->color('success')
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open)
->action(fn (ChannelTask $record) => $record->complete(auth()->user()->name)),
Action::make('dismiss')
->label('Verwerfen')
->icon(Heroicon::OutlinedXMark)
->color('gray')
->requiresConfirmation()
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open)
->action(fn (ChannelTask $record) => $record->update(['status' => ChannelTaskStatus::Dismissed])),
]);
}
}
+1 -1
View File
@@ -27,7 +27,7 @@ class FaqResource extends Resource
protected static ?string $pluralModelLabel = 'Häufige Fragen';
protected static ?int $navigationSort = 4;
protected static ?int $navigationSort = 5;
public static function form(Schema $schema): Schema
{
@@ -27,7 +27,7 @@ class NoticeResource extends Resource
protected static ?string $pluralModelLabel = 'Hinweis-Banner';
protected static ?int $navigationSort = 5;
protected static ?int $navigationSort = 6;
public static function form(Schema $schema): Schema
{
@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\Pages;
use App\Filament\Resources\Pages\Pages\CreatePage;
use App\Filament\Resources\Pages\Pages\EditPage;
use App\Filament\Resources\Pages\Pages\ListPages;
use App\Filament\Resources\Pages\Schemas\PageForm;
use App\Filament\Resources\Pages\Tables\PagesTable;
use App\Models\Page;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
class PageResource extends Resource
{
protected static ?string $model = Page::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedDocumentDuplicate;
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
protected static ?string $modelLabel = 'Seite';
protected static ?string $pluralModelLabel = 'Seiten';
protected static ?int $navigationSort = 0;
public static function form(Schema $schema): Schema
{
return PageForm::configure($schema);
}
public static function table(Table $table): Table
{
return PagesTable::configure($table);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => ListPages::route('/'),
'create' => CreatePage::route('/create'),
'edit' => EditPage::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Pages\Pages;
use App\Filament\Resources\Pages\PageResource;
use Filament\Resources\Pages\CreateRecord;
class CreatePage extends CreateRecord
{
protected static string $resource = PageResource::class;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Pages\Pages;
use App\Filament\Resources\Pages\PageResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditPage extends EditRecord
{
protected static string $resource = PageResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Pages\Pages;
use App\Filament\Resources\Pages\PageResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListPages extends ListRecords
{
protected static string $resource = PageResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
@@ -0,0 +1,67 @@
<?php
namespace App\Filament\Resources\Pages\Schemas;
use App\Models\Page;
use App\Models\Site;
use App\Themes\SectionRegistry;
use Filament\Forms\Components\Builder;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Validation\Rules\Unique;
class PageForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->columns(3)
->components([
Section::make('Bausteine')
->description('Die Seite besteht aus Bausteinen. Reihenfolge per Ziehen, Inhalte je Baustein. Wie sie aussehen, bestimmt das Theme.')
->columnSpan(2)
->schema([
Builder::make('sections')
->hiddenLabel()
->blocks(fn (): array => app(SectionRegistry::class)->blocks())
->addActionLabel('Baustein hinzufügen')
->collapsible()
->collapsed()
->cloneable()
->blockNumbers(false)
->blockPickerColumns(2),
]),
Section::make('Seite')
->columnSpan(1)
->schema([
Hidden::make('site_id')->default(fn (): ?int => Site::query()->where('is_default', true)->value('id') ?? Site::query()->value('id')),
TextInput::make('title')->label('Titel')->required()->maxLength(120),
TextInput::make('slug')
->label('Adresse')
->prefix('/')
->helperText('Die Startseite heißt „start“.')
->required()
->alphaDash()
->maxLength(80)
->disabled(fn (?Page $record): bool => $record?->isHome() ?? false)
->dehydrated()
->unique(ignoreRecord: true, modifyRuleUsing: fn (Unique $rule, callable $get) => $rule->where('site_id', $get('site_id'))),
TextInput::make('menu_label')->label('Name im Menü (optional)')->maxLength(60),
Select::make('menu_location')->label('Menü')->options(Page::MENU_LOCATIONS)->default('main')->required(),
Toggle::make('is_published')->label('Veröffentlicht')->default(true),
]),
Section::make('Suchmaschinen')
->columnSpan(1)
->collapsed()
->schema([
TextInput::make('seo_title')->label('Seitentitel (Google)')->maxLength(70),
Textarea::make('seo_description')->label('Beschreibung (Google)')->rows(3)->maxLength(170),
]),
]);
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Filament\Resources\Pages\Tables;
use App\Models\Page;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Table;
class PagesTable
{
public static function configure(Table $table): Table
{
return $table
->reorderable('sort_order')
->defaultSort('sort_order')
->paginated(false)
->description('Reihenfolge per Ziehen = Reihenfolge im Menü.')
->columns([
TextColumn::make('title')->label('Seite')->weight('medium')->description(fn (Page $record): string => $record->isHome() ? '/' : '/'.$record->slug),
TextColumn::make('menu_location')->label('Menü')->formatStateUsing(fn (string $state): string => Page::MENU_LOCATIONS[$state] ?? $state)->badge(),
TextColumn::make('sections')->label('Bausteine')->state(fn (Page $record): int => count($record->sections ?? [])),
ToggleColumn::make('is_published')->label('Veröffentlicht'),
])
->recordActions([
Action::make('open')
->label('Ansehen')
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
->color('gray')
->url(fn (Page $record): string => $record->url(), shouldOpenInNewTab: true),
EditAction::make(),
DeleteAction::make()->visible(fn (Page $record): bool => ! $record->isHome()),
]);
}
}
@@ -27,7 +27,7 @@ class PhotoResource extends Resource
protected static ?string $pluralModelLabel = 'Bilder';
protected static ?int $navigationSort = 1;
protected static ?int $navigationSort = 2;
public static function form(Schema $schema): Schema
{
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\PortalEmails\Pages;
use App\Filament\Resources\PortalEmails\PortalEmailResource;
use Filament\Resources\Pages\ListRecords;
class ListPortalEmails extends ListRecords
{
protected static string $resource = PortalEmailResource::class;
}
@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\PortalEmails;
use App\Enums\PortalEmailStatus;
use App\Filament\Resources\PortalEmails\Pages\ListPortalEmails;
use App\Filament\Resources\PortalEmails\Tables\PortalEmailsTable;
use App\Models\PortalEmail;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
class PortalEmailResource extends Resource
{
protected static ?string $model = PortalEmail::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedEnvelopeOpen;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static ?string $modelLabel = 'Portal-E-Mail';
protected static ?string $pluralModelLabel = 'Portal-E-Mails';
protected static ?int $navigationSort = 5;
public static function table(Table $table): Table
{
return PortalEmailsTable::configure($table);
}
public static function canCreate(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
$review = PortalEmail::query()->where('status', PortalEmailStatus::NeedsReview)->count();
return $review > 0 ? (string) $review : null;
}
public static function getNavigationBadgeColor(): string
{
return 'danger';
}
public static function getPages(): array
{
return [
'index' => ListPortalEmails::route('/'),
];
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Filament\Resources\PortalEmails\Tables;
use App\Enums\PortalEmailStatus;
use App\Models\PortalEmail;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Notifications\Notification;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
class PortalEmailsTable
{
public static function configure(Table $table): Table
{
return $table
->defaultSort('received_at', 'desc')
->description('Buchungs-E-Mails der Portale werden jede Minute gelesen. Erkannte Buchungen werden sofort gesperrt; unklare E-Mails bitte prüfen.')
->columns([
TextColumn::make('received_at')->label('Eingang')->dateTime('d.m. H:i')->sortable(),
TextColumn::make('channel.name')->label('Portal'),
TextColumn::make('type')->label('Art')->badge(),
TextColumn::make('status')->label('Ergebnis')->badge()->description(fn (PortalEmail $record): ?string => $record->note),
TextColumn::make('period')->label('Zeitraum')->state(fn (PortalEmail $record): ?string => $record->period())->placeholder('–'),
TextColumn::make('reference')->label('Buchungsnr.')->placeholder('–'),
TextColumn::make('subject')->label('Betreff')->limit(50)->tooltip(fn (PortalEmail $record): ?string => $record->excerpt),
])
->filters([
SelectFilter::make('status')->label('Ergebnis')->options(PortalEmailStatus::class),
])
->recordActions([
Action::make('block')
->label('Sperre anlegen')
->icon(Heroicon::OutlinedLockClosed)
->color('danger')
->visible(fn (PortalEmail $record): bool => $record->status === PortalEmailStatus::NeedsReview)
->fillForm(fn (PortalEmail $record): array => ['starts_on' => $record->starts_on, 'ends_on' => $record->ends_on])
->schema([
DatePicker::make('starts_on')->label('Anreise')->required(),
DatePicker::make('ends_on')->label('Abreise')->after('starts_on')->required(),
])
->action(function (PortalEmail $record, array $data): void {
$block = $record->channel->blockedPeriods()->create([
'property_id' => $record->channel->property_id,
'starts_on' => $data['starts_on'],
'ends_on' => $data['ends_on'],
'reason' => "{$record->channel->name} (E-Mail, geprüft)".($record->reference ? ": {$record->reference}" : ''),
'source' => 'email',
'external_uid' => 'email:'.($record->reference ?? $record->message_id),
]);
$record->update(['status' => PortalEmailStatus::Blocked, 'blocked_period_id' => $block->id, 'starts_on' => $data['starts_on'], 'ends_on' => $data['ends_on']]);
Notification::make()->title('Zeitraum gesperrt')->success()->send();
}),
Action::make('reviewed')
->label('Als geprüft markieren')
->icon(Heroicon::OutlinedCheck)
->color('gray')
->visible(fn (PortalEmail $record): bool => $record->status === PortalEmailStatus::NeedsReview)
->action(fn (PortalEmail $record) => $record->update(['status' => PortalEmailStatus::Reviewed])),
]);
}
}
@@ -6,6 +6,7 @@
use App\Filament\Resources\Properties\Pages\EditProperty;
use App\Filament\Resources\Properties\Pages\ListProperties;
use App\Filament\Resources\Properties\RelationManagers\BlockedPeriodsRelationManager;
use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager;
use App\Filament\Resources\Properties\RelationManagers\ExtrasRelationManager;
use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager;
use App\Filament\Resources\Properties\RelationManagers\SpecialOffersRelationManager;
@@ -50,6 +51,7 @@ public static function getRelations(): array
SpecialOffersRelationManager::class,
ExtrasRelationManager::class,
BlockedPeriodsRelationManager::class,
ChannelsRelationManager::class,
];
}
@@ -0,0 +1,160 @@
<?php
namespace App\Filament\Resources\Properties\RelationManagers;
use App\Actions\SyncChannel;
use App\Channels\ChannelRegistry;
use App\Models\Channel;
use App\Models\ChannelSyncLog;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Schemas\Components\Group;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class ChannelsRelationManager extends RelationManager
{
protected static string $relationship = 'channels';
protected static ?string $title = 'Portale & Kanäle';
protected static ?string $modelLabel = 'Portal';
protected static ?string $pluralModelLabel = 'Portale';
public function form(Schema $schema): Schema
{
$registry = app(ChannelRegistry::class);
return $schema
->columns(2)
->components([
TextInput::make('name')
->label('Name')
->placeholder('z. B. FeWo-direkt')
->required()
->maxLength(100),
Select::make('connector')
->label('Anbindung')
->options($registry->options())
->default('ical')
->live()
->required(),
Group::make()
->columnSpanFull()
->schema(fn (Get $get): array => filled($get('connector')) ? $registry->connectors()[$get('connector')]::settingsSchema() : []),
TextEntry::make('export_url')
->label('Unsere Kalender-Adresse für dieses Portal')
->helperText('Diese Adresse im Portal unter „Kalender importieren“ eintragen. Sie enthält alle Belegungen außer denen dieses Portals.')
->state(fn (?Channel $record): ?string => $record?->exportUrl())
->copyable()
->visible(fn (?Channel $record): bool => $record !== null)
->columnSpanFull(),
TextInput::make('settings.email_senders')
->label('Absender der Buchungs-E-Mails (Schnellerkennung)')
->helperText('Komma-getrennt, z. B. „fewo-direkt.de, vrbo.com“. Buchungsbestätigungen dieser Absender werden sofort gesperrt.')
->maxLength(500)
->columnSpanFull(),
Toggle::make('requires_manual_blocking')
->label('Zusätzlich von Hand sperren (Sofortbuchung)')
->helperText('Bei jeder Belegung über andere Wege entsteht eine Aufgabe „Im Portal sperren“ – für Portale, die unseren Kalender zu selten abholen.')
->live()
->columnSpanFull(),
TextInput::make('manage_url')
->label('Link zum Kalender im Vermieterbereich')
->url()
->maxLength(2048)
->visible(fn (Get $get): bool => (bool) $get('requires_manual_blocking'))
->columnSpanFull(),
Toggle::make('is_active')
->label('Aktiv')
->default(true),
]);
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('name')
->description('Unser System ist führend: Belegungen der Portale werden alle 5 Minuten eingelesen, jedes Portal erhält einen eigenen Kalender mit allen übrigen Belegungen.')
->columns([
TextColumn::make('name')->label('Portal')->weight('medium'),
TextColumn::make('status')
->label('Status')
->badge()
->state(fn (Channel $record): string => match (true) {
! $record->is_active => 'Inaktiv',
! $record->importsOccupations() => 'Nur Export',
$record->last_error !== null => 'Fehler',
$record->isStale() => 'Veraltet',
default => 'OK',
})
->color(fn (string $state): string => match ($state) {
'OK' => 'success',
'Fehler', 'Veraltet' => 'danger',
default => 'gray',
})
->tooltip(fn (Channel $record): ?string => $record->last_error),
TextColumn::make('last_success_at')->label('Letzter Abgleich')->since()->placeholder('–'),
TextColumn::make('requires_manual_blocking')
->label('Handpflege')
->formatStateUsing(fn (bool $state): string => $state ? 'ja' : '–'),
])
->headerActions([
CreateAction::make(),
])
->recordActions([
Action::make('sync')
->label('Jetzt abgleichen')
->icon(Heroicon::OutlinedArrowPath)
->visible(fn (Channel $record): bool => $record->importsOccupations())
->action(function (Channel $record, SyncChannel $syncChannel): void {
$log = $syncChannel->handle($record);
$log->successful
? Notification::make()->title("{$log->events} Belegungen eingelesen")->body("Neu: {$log->added}, geändert: {$log->changed}, entfernt: {$log->removed}, Konflikte: {$log->conflicts}")->success()->send()
: Notification::make()->title('Abgleich fehlgeschlagen')->body($log->message)->danger()->send();
}),
Action::make('logs')
->label('Protokoll')
->icon(Heroicon::OutlinedListBullet)
->color('gray')
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen')
->schema([
RepeatableEntry::make('recentLogs')
->hiddenLabel()
->state(fn (Channel $record): array => $record->syncLogs()->limit(30)->get()->map(fn (ChannelSyncLog $log): array => [
'time' => $log->created_at->format('d.m. H:i'),
'result' => $log->successful ? "✓ {$log->events} Belegungen (+{$log->added} ~{$log->changed} -{$log->removed})" : '✗ '.$log->message,
'conflicts' => $log->conflicts ?: '',
])->all())
->table([
TableColumn::make('Zeit'),
TableColumn::make('Ergebnis'),
TableColumn::make('Konflikte'),
])
->schema([
TextEntry::make('time'),
TextEntry::make('result'),
TextEntry::make('conflicts'),
]),
]),
EditAction::make(),
DeleteAction::make(),
]);
}
}
@@ -3,6 +3,8 @@
namespace App\Filament\Resources\Properties\Schemas;
use App\Filament\Forms\Components\EuroInput;
use App\Models\Site;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\TimePicker;
use Filament\Forms\Components\Toggle;
@@ -46,6 +48,10 @@ public static function configure(Schema $schema): Schema
TimePicker::make('check_out_time')
->label('Abreise bis')
->seconds(false),
Select::make('site_id')
->label('Website')
->options(fn (): array => Site::query()->pluck('name', 'id')->all())
->placeholder('keine'),
Toggle::make('is_active')
->label('Aktiv (auf der Webseite buchbar)')
->default(true),
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\Sites\Pages;
use App\Filament\Resources\Sites\SiteResource;
use Filament\Resources\Pages\CreateRecord;
class CreateSite extends CreateRecord
{
protected static string $resource = SiteResource::class;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Sites\Pages;
use App\Filament\Resources\Sites\SiteResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditSite extends EditRecord
{
protected static string $resource = SiteResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\Sites\Pages;
use App\Filament\Resources\Sites\SiteResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListSites extends ListRecords
{
protected static string $resource = SiteResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Filament\Resources\Sites\Schemas;
use App\Filament\Resources\Appearances\Schemas\AppearanceForm;
use App\Models\Site;
use App\Themes\ThemeRegistry;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
class SiteForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->columns(2)
->components([
Section::make('Website')
->columns(2)
->schema([
TextInput::make('name')->label('Name')->required()->maxLength(120),
TextInput::make('domain')
->label('Domain')
->placeholder('www.fewo-stommer.de')
->helperText('Leer = Standard-Website für alle Adressen ohne eigene Zuordnung.')
->unique(ignoreRecord: true)
->maxLength(190),
Select::make('theme')->label('Theme')->options(fn (): array => app(ThemeRegistry::class)->options())->default(config('themes.base'))->required()->live(),
Toggle::make('is_default')->label('Standard-Website')->inline(false),
]),
Section::make('Farben des Themes')
->description('Grundfarben dieser Website; saisonale Erscheinungsbilder können einzelne Farben zusätzlich ändern.')
->columns(3)
->collapsible()
->schema(fn (Get $get, ?Site $record): array => AppearanceForm::tokenFields($record?->id, 'theme_settings.tokens')),
]);
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Filament\Resources\Sites;
use App\Filament\Resources\Sites\Pages\CreateSite;
use App\Filament\Resources\Sites\Pages\EditSite;
use App\Filament\Resources\Sites\Pages\ListSites;
use App\Filament\Resources\Sites\Schemas\SiteForm;
use App\Filament\Resources\Sites\Tables\SitesTable;
use App\Models\Site;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
class SiteResource extends Resource
{
protected static ?string $model = Site::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedGlobeAlt;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?string $modelLabel = 'Website';
protected static ?string $pluralModelLabel = 'Websites';
protected static ?int $navigationSort = 2;
public static function form(Schema $schema): Schema
{
return SiteForm::configure($schema);
}
public static function table(Table $table): Table
{
return SitesTable::configure($table);
}
public static function getRelations(): array
{
return [
//
];
}
public static function getPages(): array
{
return [
'index' => ListSites::route('/'),
'create' => CreateSite::route('/create'),
'edit' => EditSite::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Filament\Resources\Sites\Tables;
use App\Themes\ThemeRegistry;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class SitesTable
{
public static function configure(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')->label('Website')->weight('medium'),
TextColumn::make('domain')->label('Domain')->placeholder('alle übrigen Adressen'),
TextColumn::make('theme')->label('Theme')->formatStateUsing(fn (string $state): string => app(ThemeRegistry::class)->get($state)->name),
TextColumn::make('properties_count')->label('Wohnungen')->counts('properties'),
IconColumn::make('is_default')->label('Standard')->boolean(),
])
->recordActions([
EditAction::make(),
]);
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
namespace App\Filament\Widgets;
use App\Enums\BookingStatus;
use App\Enums\PortalEmailStatus;
use App\Enums\UserRole;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\PortalEmail;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
class BookingStats extends StatsOverviewWidget
{
protected static ?int $sort = 1;
public static function canView(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin, UserRole::Rentals);
}
protected function getStats(): array
{
$today = CarbonImmutable::today();
$openRequests = Booking::query()->where('status', BookingStatus::Reserved)->count();
$arrivals = Booking::query()->whereIn('status', BookingStatus::occupying())->whereBetween('arrival', [$today, $today->addDays(14)])->count();
$unpaid = Booking::query()->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid])->with('payments')->get();
$overdue = $unpaid->filter(fn (Booking $booking): bool => ($booking->deposit_due_on?->isPast() && $booking->openDeposit() > 0)
|| ($booking->balance_due_on->isPast() && $booking->openAmount() > 0));
$portalProblems = Channel::query()->active()->get()->filter(fn (Channel $channel): bool => $channel->isStale())->count()
+ ChannelTask::query()->open()->count()
+ PortalEmail::query()->where('status', PortalEmailStatus::NeedsReview)->count();
return [
Stat::make('Offene Anfragen', $openRequests)
->description($openRequests > 0 ? 'warten auf Ihre Bestätigung' : 'alles bearbeitet')
->color($openRequests > 0 ? 'warning' : 'success')
->url(BookingResource::getUrl('index', ['filters' => ['status' => ['values' => [BookingStatus::Reserved->value]]]])),
Stat::make('Anreisen (14 Tage)', $arrivals),
Stat::make('Offene Zahlungen', Money::format($unpaid->sum(fn (Booking $booking): int => $booking->openAmount())))
->description($overdue->isEmpty() ? 'nichts überfällig' : "{$overdue->count()} überfällig")
->color($overdue->isEmpty() ? 'success' : 'danger'),
Stat::make('Auslastung '.$today->year, $this->occupancy($today->startOfYear(), $today->endOfYear()->startOfDay()->addDay()).' %')
->description('eigene Buchungen und Portale'),
Stat::make('Portale', $portalProblems === 0 ? 'OK' : "{$portalProblems} offen")
->description('Abgleich, Aufgaben, E-Mails')
->color($portalProblems === 0 ? 'success' : 'danger')
->url(ChannelTaskResource::getUrl('index')),
];
}
/**
* Share of nights in [$from, $until) occupied by bookings or portal occupations (own blocks do not count).
*/
private function occupancy(CarbonImmutable $from, CarbonImmutable $until): int
{
$nights = [];
$periods = Booking::query()->whereIn('status', BookingStatus::occupying())->overlapping($from, $until)->get(['arrival', 'departure'])
->map(fn (Booking $booking): array => [$booking->arrival, $booking->departure])
->concat(BlockedPeriod::query()->whereNotNull('channel_id')->overlapping($from, $until)->get(['starts_on', 'ends_on'])
->map(fn (BlockedPeriod $block): array => [$block->starts_on, $block->ends_on]));
foreach ($periods as [$start, $end]) {
for ($night = $start->max($from); $night->lessThan($end) && $night->lessThan($until); $night = $night->addDay()) {
$nights[$night->toDateString()] = true;
}
}
return (int) round(count($nights) / max(1, $from->diffInDays($until)) * 100);
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Filament\Widgets;
use App\Enums\BookingStatus;
use App\Enums\UserRole;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\Booking;
use App\Support\Money;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;
class UpcomingStays extends TableWidget
{
protected static ?int $sort = 2;
protected int|string|array $columnSpan = 'full';
protected static ?string $heading = 'Nächste Aufenthalte (30 Tage)';
public static function canView(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin, UserRole::Rentals);
}
public function table(Table $table): Table
{
return $table
->query(fn () => Booking::query()
->with(['guest', 'payments'])
->whereIn('status', BookingStatus::occupying())
->whereDate('departure', '>=', today())
->whereDate('arrival', '<=', today()->addDays(30)))
->defaultSort('arrival')
->paginated(false)
->emptyStateHeading('Keine Aufenthalte in den nächsten 30 Tagen')
->recordUrl(fn (Booking $record): string => BookingResource::getUrl('view', ['record' => $record]))
->columns([
TextColumn::make('arrival')->label('Anreise')->date('D, d.m.')
->description(fn (Booking $record): ?string => $record->arrival->isToday() ? 'heute' : ($record->arrival->isPast() ? 'läuft' : null)),
TextColumn::make('departure')->label('Abreise')->date('D, d.m.'),
TextColumn::make('guest.last_name')->label('Gast')->formatStateUsing(fn (Booking $record): string => $record->guest->full_name),
TextColumn::make('guests')->label('Pers.'),
TextColumn::make('status')->label('Status')->badge(),
TextColumn::make('open')->label('Offen')
->state(fn (Booking $record): string => $record->openAmount() > 0 ? Money::format($record->openAmount()) : '–')
->color(fn (Booking $record): ?string => $record->openAmount() > 0 ? 'danger' : null),
TextColumn::make('arrival_info_sent_at')->label('Anreiseinfo')->since()->placeholder('noch nicht'),
]);
}
}
+132
View File
@@ -0,0 +1,132 @@
<?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();
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
{
$token = config('fewo.channels.health_token');
abort_if(blank($token) || ! hash_equals($token, (string) $request->query('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
{
$token = config('fewo.scheduler_token');
abort_if(blank($token) || ! hash_equals($token, (string) $request->query('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);
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace App\Http\Controllers;
use App\Models\Page;
use App\Support\Content;
use App\Themes\SectionRegistry;
use App\Themes\Theme;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Response;
/**
* Renders the website pages of the current site with the active theme.
*/
class PageController extends Controller
{
public function __construct(private SectionRegistry $sections) {}
/**
* Resolved per call: the controller is built before the middleware has determined site and appearance.
*/
private function theme(): Theme
{
return app(Theme::class);
}
public function home(): View
{
return $this->show(Page::HOME);
}
public function show(string $slug): View
{
abort_unless($this->theme()->site->exists, 404);
$page = $this->theme()->site->pages()
->where('slug', $slug)
->where('is_published', true)
->firstOrFail();
return view('theme::page', [
'page' => $page,
'sections' => $this->sections->render($this->theme(), $page->sections),
'title' => $page->isHome() ? null : ($page->seo_title ?: $page->title),
'description' => $page->seo_description ?: ($page->isHome() ? Content::get('seo.home.description') : null),
'ogImage' => $this->theme()->heroPhoto()?->url('lg') ?: null,
'structuredData' => $page->isHome() ? $this->structuredData() : null,
]);
}
public function sitemap(): Response
{
$pages = $this->theme()->site->exists
? $this->theme()->site->pages()->where('is_published', true)->get()
: collect();
return response()->view('sitemap', ['pages' => $pages], 200, ['Content-Type' => 'application/xml']);
}
public function robots(): Response
{
return response(implode("\n", [
'User-agent: *',
'Disallow: /admin',
'Disallow: /livewire',
'Disallow: /automation',
'Disallow: /bewertung',
'Disallow: /angebote',
'Sitemap: '.route('sitemap'),
'',
]), 200, ['Content-Type' => 'text/plain; charset=UTF-8']);
}
/**
* schema.org data of the property for search engines.
*
* @return array<string, mixed>|null
*/
private function structuredData(): ?array
{
$property = $this->theme()->property();
if ($property === null) {
return null;
}
return array_filter([
'@context' => 'https://schema.org',
'@type' => 'VacationRental',
'name' => $property->name,
'url' => route('home'),
'image' => $this->theme()->heroPhoto()?->url('lg') ?: null,
'address' => ['@type' => 'PostalAddress', 'streetAddress' => str($property->address)->before(',')->trim()->toString(), 'addressLocality' => 'Kühlungsborn', 'postalCode' => '18225', 'addressCountry' => 'DE'],
'containsPlace' => ['@type' => 'Accommodation', 'floorSize' => ['@type' => 'QuantitativeValue', 'value' => $property->size_sqm, 'unitCode' => 'MTK'], 'occupancy' => ['@type' => 'QuantitativeValue', 'maxValue' => $property->max_guests]],
'telephone' => config('fewo.owner.phone'),
]);
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use App\Enums\UserRole;
use App\Models\User;
use Closure;
use Filament\Auth\MultiFactor\Http\Middleware\EnsureMultiFactorAuthenticationIsEnabled;
use Filament\Facades\Filament;
use Illuminate\Http\Request;
/**
* Filament evaluates "two-factor required" once per panel; this narrows it to administrators.
* Other roles may set it up voluntarily in their profile.
*/
class RequireTwoFactorForAdmins extends EnsureMultiFactorAuthenticationIsEnabled
{
public function handle(Request $request, Closure $next): mixed
{
$user = Filament::auth()->user();
if (! $user instanceof User || ! $user->hasRole(UserRole::Admin)) {
return $next($request);
}
return parent::handle($request, $next);
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Middleware;
use App\Themes\Theme;
use App\Themes\ThemeFactory;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Determines site, theme and appearance for the website and activates the "theme::" views.
*/
class ResolveTheme
{
public function __construct(private ThemeFactory $factory) {}
public function handle(Request $request, Closure $next): Response
{
app()->instance(Theme::class, $this->factory->forRequest($request)->activate());
return $next($request);
}
}
+35
View File
@@ -5,6 +5,7 @@
use App\Actions\CreateReservation;
use App\Actions\RequestMarketingConsent;
use App\Availability\AvailabilityChecker;
use App\Enums\ReferralSource;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Extra;
@@ -17,6 +18,7 @@
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
@@ -66,6 +68,12 @@ class BookingRequest extends Component
/** Optional opt-in for offer e-mails (confirmed by double opt-in). */
public bool $marketingOptIn = false;
public string $referralSource = '';
/** @var array{utm_source?: string, utm_medium?: string, utm_campaign?: string} UTM parameters of the landing URL */
#[Locked]
public array $utm = [];
/** Honeypot, must stay empty. */
public string $website = '';
@@ -76,6 +84,11 @@ public function mount(?Property $property = null): void
{
$this->propertyId = ($property ?? Property::query()->where('is_active', true)->firstOrFail())->id;
$this->month = CarbonImmutable::today()->format('Y-m');
$this->prefillFromSearch();
$this->utm = collect(request()->only(['utm_source', 'utm_medium', 'utm_campaign']))
->filter(fn ($value): bool => is_string($value) && $value !== '')
->map(fn (string $value): string => mb_substr($value, 0, 100))
->all();
}
#[Computed]
@@ -228,6 +241,7 @@ public function submit(CreateReservation $createReservation): void
'city' => $this->city ?: null,
],
$this->message ?: null,
attribution: [...$this->utm, 'referral_source' => $this->referralSource ?: null],
);
} catch (QuoteException|ReservationException $exception) {
$this->addError('arrival', $exception->getMessage());
@@ -262,6 +276,7 @@ protected function rules(): array
'postalCode' => ['nullable', 'string', 'max:20'],
'city' => ['nullable', 'string', 'max:255'],
'message' => ['nullable', 'string', 'max:5000'],
'referralSource' => ['nullable', Rule::enum(ReferralSource::class)],
'privacyAccepted' => ['accepted'],
];
}
@@ -300,6 +315,26 @@ private function stayRequest(): StayRequest
);
}
/**
* Dates and guests from the availability search of the hero section (?anreise=…&abreise=…&personen=…).
*/
private function prefillFromSearch(): void
{
$arrival = rescue(fn () => CarbonImmutable::createFromFormat('!Y-m-d', (string) request()->query('anreise')) ?: null, null, false);
$departure = rescue(fn () => CarbonImmutable::createFromFormat('!Y-m-d', (string) request()->query('abreise')) ?: null, null, false);
if ($arrival && $departure && $departure->greaterThan($arrival) && $arrival->greaterThanOrEqualTo(CarbonImmutable::today())) {
$this->arrival = $arrival->toDateString();
$this->departure = $departure->toDateString();
$this->month = $arrival->format('Y-m');
}
$guests = (int) request()->query('personen');
if ($guests >= 1 && $guests <= $this->property->max_guests) {
$this->guests = $guests;
}
}
private function firstMonth(): CarbonImmutable
{
return CarbonImmutable::createFromFormat('!Y-m', $this->month);
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Sent about a week before arrival: times, how to get in, house rules (texts from the admin).
*/
class ArrivalInformation extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Bald geht es los: Ihre Anreise am '.$this->booking->arrival->format('d.m.Y'),
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.arrival-information',
);
}
}
+12
View File
@@ -2,10 +2,12 @@
namespace App\Mail;
use App\Documents\RentalContract;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
@@ -33,4 +35,14 @@ public function content(): Content
markdown: 'mail.booking-confirmed',
);
}
/**
* @return list<Attachment>
*/
public function attachments(): array
{
$path = app(RentalContract::class)->absolutePath($this->booking);
return $path ? [Attachment::fromPath($path)->as("Mietvertrag-{$this->booking->reference}.pdf")->withMime('application/pdf')] : [];
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Mail;
use App\Models\Channel;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Reports overlaps between a newly imported portal occupation and occupations from elsewhere.
*/
class ChannelConflict extends Mailable
{
use Queueable, SerializesModels;
/** @param list<string> $conflicts */
public function __construct(public Channel $channel, public array $conflicts) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Achtung: mögliche Doppelbuchung über '.$this->channel->name,
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.channel-conflict',
);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Mail;
use App\Models\Channel;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Alerts the landlord that a portal import fails or is outdated.
*/
class ChannelSyncAlert extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Channel $channel) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Kalender-Abgleich gestört: '.$this->channel->name,
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.channel-sync-alert',
);
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Mail;
use App\Models\ChannelTask;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Lists portal calendars that have to be blocked or released by hand.
*/
class ChannelTasksNotification extends Mailable
{
use Queueable, SerializesModels;
/** @param list<ChannelTask> $tasks */
public function __construct(public array $tasks, public bool $reminder = false) {}
public function envelope(): Envelope
{
return new Envelope(
subject: ($this->reminder ? 'Erinnerung: ' : '').count($this->tasks).' Kalender-Aufgabe(n) auf Portalen',
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.channel-tasks',
);
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Alerts the landlord that portal notification e-mails cannot be read any more.
*/
class MailboxAlert extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public ?string $lastError) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Postfach-Abruf gestört: Portal-Buchungen werden nur noch über den Kalender erkannt',
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.mailbox-alert',
);
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Mail;
use App\Models\Booking;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Payment request or reminder to the guest. Overdue reminders are copied to the landlord.
*/
class PaymentReminder extends Mailable
{
use Queueable, SerializesModels;
public const DEPOSIT_OVERDUE = 'deposit_overdue';
public const BALANCE_REQUEST = 'balance_request';
public const BALANCE_OVERDUE = 'balance_overdue';
public function __construct(public Booking $booking, public string $kind) {}
public function envelope(): Envelope
{
return new Envelope(
subject: match ($this->kind) {
self::BALANCE_REQUEST => "Restzahlung für Ihre Buchung {$this->booking->reference}",
default => "Zahlungserinnerung zu Ihrer Buchung {$this->booking->reference}",
},
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
bcc: $this->kind === self::BALANCE_REQUEST ? [] : [new Address(config('fewo.notification_email'))],
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.payment-reminder',
with: [
'amount' => $this->kind === self::DEPOSIT_OVERDUE && ! $this->booking->requiresFullPayment() ? $this->booking->openDeposit() : $this->booking->openAmount(),
'dueOn' => $this->kind === self::DEPOSIT_OVERDUE ? $this->booking->deposit_due_on : $this->booking->balance_due_on,
],
);
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Mail;
use App\Enums\PortalEmailStatus;
use App\Models\PortalEmail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* Tells the landlord what was done with a portal notification e-mail.
*/
class PortalMailNotification extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public PortalEmail $portalEmail) {}
public function envelope(): Envelope
{
$channel = $this->portalEmail->channel->name;
return new Envelope(
subject: match ($this->portalEmail->status) {
PortalEmailStatus::Blocked => "{$channel}-Buchung erkannt und gesperrt: {$this->portalEmail->period()}",
PortalEmailStatus::Released => "{$channel}-Stornierung: {$this->portalEmail->period()} wieder frei",
default => "Bitte prüfen: E-Mail von {$channel}",
},
);
}
public function content(): Content
{
return new Content(
markdown: 'mail.portal-mail',
);
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace App\Models;
use Carbon\CarbonInterface;
use Database\Factories\AppearanceFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A seasonal look of a site (e.g. summer, winter, Christmas, New Year's Eve): colour tokens, hero photo,
* texts and banner change – the page structure does not. The period recurs every year ("MM-DD" to "MM-DD",
* inclusive; a period may run over the turn of the year). The default appearance applies when none matches.
*/
#[Fillable(['site_id', 'name', 'starts_md', 'ends_md', 'priority', 'is_default', 'is_active', 'tokens', 'overrides', 'hero_photo_id', 'featured_offer_id'])]
class Appearance extends Model
{
/** @use HasFactory<AppearanceFactory> */
use HasFactory;
/**
* Texts an appearance can replace, with their admin labels. Sections read them through Theme::text().
*/
public const OVERRIDABLE = [
'banner.text' => 'Banner: Text',
'banner.link_label' => 'Banner: Link-Text',
'banner.link_url' => 'Banner: Link-Ziel',
'hero.eyebrow' => 'Titelbereich: kleine Überschrift',
'hero.title' => 'Titelbereich: Überschrift',
'hero.text' => 'Titelbereich: Text',
'cta.title' => 'Abschluss: Überschrift',
'cta.text' => 'Abschluss: Text',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_default' => 'boolean',
'is_active' => 'boolean',
'tokens' => 'array',
'overrides' => 'array',
];
}
/**
* @return BelongsTo<Site, $this>
*/
public function site(): BelongsTo
{
return $this->belongsTo(Site::class);
}
/**
* @return BelongsTo<Photo, $this>
*/
public function heroPhoto(): BelongsTo
{
return $this->belongsTo(Photo::class, 'hero_photo_id');
}
/**
* @return BelongsTo<SpecialOffer, $this>
*/
public function featuredOffer(): BelongsTo
{
return $this->belongsTo(SpecialOffer::class, 'featured_offer_id');
}
public function covers(CarbonInterface $date): bool
{
if ($this->starts_md === null || $this->ends_md === null) {
return false;
}
$day = $date->format('m-d');
return $this->starts_md <= $this->ends_md
? $day >= $this->starts_md && $day <= $this->ends_md
: $day >= $this->starts_md || $day <= $this->ends_md;
}
public function override(string $key): ?string
{
$value = data_get($this->overrides, $key);
return filled($value) ? (string) $value : null;
}
}
+12 -1
View File
@@ -2,9 +2,11 @@
namespace App\Models;
use App\Observers\BlockedPeriodObserver;
use Carbon\CarbonInterface;
use Database\Factories\BlockedPeriodFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -15,7 +17,8 @@
* Dates that are not bookable (own use, maintenance, bookings from portals).
* Like bookings, ends_on is the first free day again.
*/
#[Fillable(['property_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid'])]
#[ObservedBy(BlockedPeriodObserver::class)]
#[Fillable(['property_id', 'channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid'])]
class BlockedPeriod extends Model
{
/** @use HasFactory<BlockedPeriodFactory> */
@@ -42,6 +45,14 @@ public function property(): BelongsTo
return $this->belongsTo(Property::class);
}
/**
* @return BelongsTo<Channel, $this>
*/
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
/**
* @param Builder<BlockedPeriod> $query
* @return Builder<BlockedPeriod>
+55
View File
@@ -3,25 +3,34 @@
namespace App\Models;
use App\Enums\BookingStatus;
use App\Enums\ReferralSource;
use App\Observers\BookingObserver;
use Carbon\CarbonInterface;
use Database\Factories\BookingFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
/**
* A reservation or booking. arrival is the first night, departure the day the guest leaves,
* so a departure and the next arrival on the same day do not collide.
*/
#[ObservedBy(BookingObserver::class)]
#[Fillable([
'property_id',
'guest_id',
'status',
'source',
'referral_source',
'utm_source',
'utm_medium',
'utm_campaign',
'arrival',
'departure',
'guests',
@@ -30,13 +39,19 @@
'quote',
'total',
'deposit',
'deposit_due_on',
'balance_due_on',
'contract_path',
'hold_expires_at',
'message',
'internal_notes',
'confirmed_at',
'cancelled_at',
'review_requested_at',
'deposit_reminded_at',
'balance_requested_at',
'balance_reminded_at',
'arrival_info_sent_at',
])]
class Booking extends Model
{
@@ -59,15 +74,21 @@ protected function casts(): array
{
return [
'status' => BookingStatus::class,
'referral_source' => ReferralSource::class,
'arrival' => 'immutable_date',
'departure' => 'immutable_date',
'extras' => 'array',
'quote' => 'array',
'deposit_due_on' => 'immutable_date',
'balance_due_on' => 'immutable_date',
'hold_expires_at' => 'immutable_datetime',
'confirmed_at' => 'immutable_datetime',
'cancelled_at' => 'immutable_datetime',
'review_requested_at' => 'immutable_datetime',
'deposit_reminded_at' => 'immutable_datetime',
'balance_requested_at' => 'immutable_datetime',
'balance_reminded_at' => 'immutable_datetime',
'arrival_info_sent_at' => 'immutable_datetime',
];
}
@@ -123,6 +144,40 @@ public function review(): HasOne
return $this->hasOne(Review::class);
}
/**
* @return HasMany<Payment, $this>
*/
public function payments(): HasMany
{
return $this->hasMany(Payment::class)->orderBy('paid_on');
}
/**
* Sum of all payments in cents (refunds are negative).
*/
public function paidAmount(): int
{
return (int) ($this->relationLoaded('payments') ? $this->payments->sum('amount') : $this->payments()->sum('amount'));
}
public function openAmount(): int
{
return max(0, $this->total - $this->paidAmount());
}
public function openDeposit(): int
{
return max(0, $this->deposit - $this->paidAmount());
}
/**
* When the balance is already due at confirmation (short-term booking), the guest pays everything at once.
*/
public function requiresFullPayment(): bool
{
return $this->deposit_due_on !== null && $this->balance_due_on->lessThanOrEqualTo($this->deposit_due_on);
}
public function nights(): int
{
return (int) $this->arrival->diffInDays($this->departure);
+123
View File
@@ -0,0 +1,123 @@
<?php
namespace App\Models;
use App\Channels\ChannelRegistry;
use App\Channels\Contracts\ChannelConnector;
use Database\Factories\ChannelFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
/**
* A sales channel (portal) of a property. Our system leads: occupations are imported from the
* channel and every channel gets its own export feed without its own occupations.
*/
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url'])]
#[Hidden(['export_token'])]
class Channel extends Model
{
/** @use HasFactory<ChannelFactory> */
use HasFactory;
protected static function booted(): void
{
static::creating(function (Channel $channel): void {
$channel->export_token ??= Str::random(48);
});
}
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'settings' => 'array',
'is_active' => 'boolean',
'requires_manual_blocking' => 'boolean',
'last_synced_at' => 'immutable_datetime',
'last_success_at' => 'immutable_datetime',
'alerted_at' => 'immutable_datetime',
];
}
/**
* @return BelongsTo<Property, $this>
*/
public function property(): BelongsTo
{
return $this->belongsTo(Property::class);
}
/**
* @return HasMany<BlockedPeriod, $this>
*/
public function blockedPeriods(): HasMany
{
return $this->hasMany(BlockedPeriod::class);
}
/**
* @return HasMany<ChannelSyncLog, $this>
*/
public function syncLogs(): HasMany
{
return $this->hasMany(ChannelSyncLog::class)->latest('id');
}
/**
* @return HasMany<ChannelTask, $this>
*/
public function tasks(): HasMany
{
return $this->hasMany(ChannelTask::class);
}
/**
* @param Builder<Channel> $query
* @return Builder<Channel>
*/
#[Scope]
protected function active(Builder $query): Builder
{
return $query->where('is_active', true);
}
public function connector(): ChannelConnector
{
return app(ChannelRegistry::class)->resolve($this->connector);
}
public function importsOccupations(): bool
{
return $this->is_active && $this->connector()->canImport($this);
}
public function exportUrl(): string
{
return route('channels.feed', ['token' => $this->export_token]);
}
public function setting(string $key): mixed
{
return $this->settings[$key] ?? null;
}
/**
* The import is considered stale when no successful sync happened within the threshold.
*/
public function isStale(): bool
{
return $this->importsOccupations()
&& ($this->last_success_at === null || $this->last_success_at->lessThan(now()->subMinutes(config('fewo.channels.stale_after_minutes'))));
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['channel_id', 'successful', 'events', 'added', 'changed', 'removed', 'conflicts', 'message', 'duration_ms'])]
class ChannelSyncLog extends Model
{
public const UPDATED_AT = null;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'successful' => 'boolean',
'created_at' => 'immutable_datetime',
];
}
/**
* @return BelongsTo<Channel, $this>
*/
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace App\Models;
use App\Enums\ChannelTaskAction;
use App\Enums\ChannelTaskStatus;
use Database\Factories\ChannelTaskFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A change that has to be made by hand (or by an external automation) on a portal that
* cannot be kept in sync fast enough by calendar feeds, e.g. because of instant booking.
*/
#[Fillable(['channel_id', 'action', 'starts_on', 'ends_on', 'reason', 'status', 'completed_by', 'completed_at', 'reminded_at', 'automation_sent_at', 'automation_error'])]
class ChannelTask extends Model
{
/** @use HasFactory<ChannelTaskFactory> */
use HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'action' => ChannelTaskAction::class,
'status' => ChannelTaskStatus::class,
'starts_on' => 'immutable_date',
'ends_on' => 'immutable_date',
'completed_at' => 'immutable_datetime',
'reminded_at' => 'immutable_datetime',
'automation_sent_at' => 'immutable_datetime',
];
}
/**
* @return BelongsTo<Channel, $this>
*/
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
/**
* @param Builder<ChannelTask> $query
* @return Builder<ChannelTask>
*/
#[Scope]
protected function open(Builder $query): Builder
{
return $query->where('status', ChannelTaskStatus::Open);
}
public function complete(string $completedBy): void
{
$this->update([
'status' => ChannelTaskStatus::Done,
'completed_by' => $completedBy,
'completed_at' => now(),
]);
}
/**
* Human readable period, e.g. "14.06.2027 – 21.06.2027".
*/
public function period(): string
{
return $this->starts_on->format('d.m.Y').' – '.$this->ends_on->format('d.m.Y');
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Models;
use Database\Factories\PageFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A page of a site, composed of sections from the catalogue (App\Themes\Sections).
* sections = list of {type: string, data: array} as stored by the Filament builder.
* The home page has the slug "start" and is served at "/".
*/
#[Fillable(['site_id', 'slug', 'title', 'menu_label', 'menu_location', 'sort_order', 'is_published', 'sections', 'seo_title', 'seo_description'])]
class Page extends Model
{
/** @use HasFactory<PageFactory> */
use HasFactory;
public const HOME = 'start';
/** Menu locations a page can appear in. */
public const MENU_LOCATIONS = ['main' => 'Hauptmenü', 'footer' => 'Fußzeile', 'none' => 'Nicht im Menü'];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_published' => 'boolean',
'sections' => 'array',
];
}
/**
* @return BelongsTo<Site, $this>
*/
public function site(): BelongsTo
{
return $this->belongsTo(Site::class);
}
public function isHome(): bool
{
return $this->slug === self::HOME;
}
public function url(): string
{
return $this->isHome() ? route('home') : route('page', ['slug' => $this->slug]);
}
public function label(): string
{
return $this->menu_label ?: $this->title;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Models;
use App\Enums\PaymentMethod;
use Database\Factories\PaymentFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A received payment (negative amount = refund), in euro cents.
*/
#[Fillable(['booking_id', 'amount', 'paid_on', 'method', 'note', 'recorded_by'])]
class Payment extends Model
{
/** @use HasFactory<PaymentFactory> */
use HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'paid_on' => 'immutable_date',
'method' => PaymentMethod::class,
];
}
/**
* @return BelongsTo<Booking, $this>
*/
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Models;
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A notification e-mail of a portal (e.g. "new booking" from FeWo-direkt) and what the system did with it.
* Only a short excerpt is stored, not the whole e-mail.
*/
#[Fillable(['channel_id', 'message_id', 'from', 'subject', 'received_at', 'type', 'status', 'starts_on', 'ends_on', 'reference', 'blocked_period_id', 'excerpt', 'note'])]
class PortalEmail extends Model
{
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'type' => PortalEmailType::class,
'status' => PortalEmailStatus::class,
'received_at' => 'immutable_datetime',
'starts_on' => 'immutable_date',
'ends_on' => 'immutable_date',
];
}
/**
* @return BelongsTo<Channel, $this>
*/
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
/**
* @return BelongsTo<BlockedPeriod, $this>
*/
public function blockedPeriod(): BelongsTo
{
return $this->belongsTo(BlockedPeriod::class);
}
public function period(): ?string
{
return $this->starts_on && $this->ends_on ? $this->starts_on->format('d.m.Y').' – '.$this->ends_on->format('d.m.Y') : null;
}
}
+9
View File
@@ -13,6 +13,7 @@
* A rentable holiday apartment. All money amounts are stored in euro cents.
*/
#[Fillable([
'site_id',
'name',
'slug',
'address',
@@ -69,6 +70,14 @@ public function blockedPeriods(): HasMany
return $this->hasMany(BlockedPeriod::class)->orderBy('starts_on');
}
/**
* @return HasMany<Channel, $this>
*/
public function channels(): HasMany
{
return $this->hasMany(Channel::class);
}
/**
* @return HasMany<Amenity, $this>
*/
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Models;
use Carbon\CarbonInterface;
use Database\Factories\SiteFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* A website: domain, theme with its settings, pages and appearances, and the properties it shows.
* Today there is one site; more sites allow other landlords to use the system under their own domain.
*/
#[Fillable(['name', 'domain', 'is_default', 'theme', 'theme_settings', 'locale'])]
class Site extends Model
{
/** @use HasFactory<SiteFactory> */
use HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_default' => 'boolean',
'theme_settings' => 'array',
];
}
/**
* @return HasMany<Page, $this>
*/
public function pages(): HasMany
{
return $this->hasMany(Page::class)->orderBy('sort_order');
}
/**
* @return HasMany<Appearance, $this>
*/
public function appearances(): HasMany
{
return $this->hasMany(Appearance::class);
}
/**
* @return HasMany<Property, $this>
*/
public function properties(): HasMany
{
return $this->hasMany(Property::class);
}
/**
* The property sections show when they do not name one (the first active property).
*/
public function primaryProperty(): ?Property
{
return $this->properties()->where('is_active', true)->orderBy('id')->first()
?? Property::query()->where('is_active', true)->whereNull('site_id')->orderBy('id')->first();
}
/**
* The appearance in effect on $date: the active seasonal one with the highest priority, else the default.
*/
public function appearanceOn(CarbonInterface $date): ?Appearance
{
$appearances = $this->appearances()->where('is_active', true)->get();
return $appearances
->filter(fn (Appearance $appearance): bool => $appearance->covers($date))
->sortByDesc('priority')
->first()
?? $appearances->firstWhere('is_default', true);
}
}
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more