Compare commits

...
Author SHA1 Message Date
Lars Stommer 2f2aceb3bd Merge branch 'feature/mandanten-dienste' (Dienste-Steuerung und Host-Verwaltung)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-24 09:25:23 +02:00
Lars StommerandClaude Opus 5 2e3f2ca938 Mehrere Adressen je Website, damit ein zweiter Mandant niemanden abschaltet
Bisher schrieb das Feld „Domain" genau einen Host nach `site_domains` und
löschte den vorherigen. Solange es einen Mandanten gibt, fällt das nicht
auf: jede Adresse liefert die Standard-Website. Ab dem zweiten Mandanten
bekommt jede nicht eingetragene Adresse 404 – und „www.beispiel.de" ist
eine eigene Adresse. stommer.info hätte einen zweiten Mandanten nicht
überlebt.

Das Formular hat jetzt „Hauptadresse" (steht in Gästelinks) und „Weitere
Adressen". Eingaben werden normalisiert, „https://WWW.Beispiel.de/" wird
zu „www.beispiel.de".

Eine Adresse, die schon zu einer anderen Website gehört, wird abgelehnt.
Ohne diese Sperre könnte ein Mandant die Besucher eines anderen auf seine
eigene Seite ziehen, indem er dessen Adresse einträgt.

242 Feature-Tests grün.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 09:25:22 +02:00
Lars StommerandClaude Opus 5 fd2a7f7ded Dienste wirklich anschließen: zentrale Steuerung statt folgenloser Schalter
Die Schalter aus Phase 3 schrieben nur in eine Tabelle, die niemand las.
Ein gesperrter Portal-Abgleich lief trotzdem weiter. Das ist behoben.

`App\Tenancy\TenantFeatures` ist die eine Stelle, die beantwortet, ob ein
Mandant einen Dienst hat. Sie wird an allen Wegen abgefragt, die zum Dienst
führen:

- `RolePolicy::allows()` – damit greift die Mandanten-Ebene in *jeder*
  Richtlinie des Admins. Die Rolle sagt, was ein Benutzer darf; der Dienst
  sagt, was der Mandant überhaupt hat. Keine Rolle wiegt einen gesperrten
  Dienst auf.
- `Channel::importsOccupations()` – Import und Scheduler.
- Der öffentliche iCal-Feed antwortet mit 404.
- `ProcessPortalMail` und `channels:fetch-mail` für den Postfach-Schnellweg.

`TenantServiceKey::isWired()` trennt Gebautes von Geplantem. Nur verdrahtete
Dienste erscheinen als Schalter; die drei KI-Dienste stehen als Hinweis da,
bis die Anwendung sie abfragt. Eigene API-Schlüssel sind aus dem Betreiber-
Formular verschwunden – sie gehören in den Admin des Mandanten, wenn es
soweit ist (A16).

Neu im Betreiber-Bereich: Seite „System" mit den Grenzen, die für alle
Mandanten gelten (aus der .env, bewusst nicht änderbar), der Mandantenliste
und dem Zugriffsprotokoll. Bisher war dort nur die Mandantenliste.

Die Migration schaltet jedem vorhandenen Mandanten die Portal-Dienste frei,
damit der Umbau laufenden Betrieb nicht stillschweigend stoppt.

240 Feature-Tests grün, davon fünf neue in `TenantServiceGateTest`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 09:14:10 +02:00
Lars StommerandClaude Opus 5 220ec6bfdb Doku: Sicherung, Migrationsstand und Prüfung des Phase-3-Deploys
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-23 22:02:29 +02:00
Lars StommerandClaude Opus 5 afffa79289 Doku: Phase 3 ist auf stommer.info; Release-Nummern korrigiert
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Im Stand stand noch `20261023100346`, obwohl danach vier weitere Deploys
liefen (Grundriss, Fotos-Fix). Jetzt steht überall die wirklich aktive
Version `20261023195835` mit Phase 3.

Neu vermerkt: die Bankverbindung ist am Mandanten leer, weil die .env von
stommer.info keine `FEWO_BANK_*`-Werte hat – sie gehört jetzt in
System › Betrieb.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-23 22:01:53 +02:00
Lars Stommer f143a4f5f4 Merge branch 'feature/mandanten-phase3' (Mandanten Phase 3)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-23 20:49:47 +02:00
Lars StommerandClaude Opus 5 e6d4d89141 Mandanten Phase 3: Einstellungen, Texte und Dienste gehören dem Mandanten
Vermieterdaten, Bank, Steuerangabe, Adressen, Betriebsart und Fristen sind
Spalten von `tenants`. `App\Tenancy\TenantConfig` legt sie über
`config('fewo.*')` und `mail.from`, sobald der Mandantenkontext wechselt –
so lesen Vorlagen, Mails und der Mietvertrag weiter dieselben Schlüssel und
`resources/themes/**` bleibt unangetastet.

Die `.env` ist die Grundlinie: Rückfall, solange kein Mandant feststeht, und
Grenze für Löschfristen und Bot-Schutz (nur verschärfen, nicht lockern). Die
Flutgrenze bleibt global. Bank, Steuerangabe und eigene Dienst-Schlüssel
liegen verschlüsselt.

Die Seite System › Betrieb schreibt jetzt den Mandanten und enthält
zusätzlich Vermieterdaten, Bank und die Fristen. Tabelle `settings` und
Modell `Setting` entfallen; die Migration übernimmt die bisherigen Werte
aus `settings` und der Konfiguration in den Mandanten Stommer.

Neu: `tenant_services` (Freischaltung je Dienst mit optionalem eigenem
API-Schlüssel, nur im Betreiber-Bereich schaltbar) und `service_usages`.
Es zählt noch nichts, weil kein Dienst aufruft.

235 Feature-Tests grün. Der Umbauweg wurde zusätzlich auf einer Kopie der
lokalen Datenbank durchgespielt.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-23 20:49:22 +02:00
LarsandClaude Opus 5.5 12e4079126 Docs: photo storage fix (admin uploads were private) in BETRIEB §8 and STATUS
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 20:17:18 +02:00
LarsandClaude Opus 5.5 1871c04507 Fix: photos uploaded in the admin were stored privately and did not show on the website
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
The admin upload field used Filament's default disk (FILESYSTEM_DISK=local, private), while imports
and the website use the public disk – a photo uploaded in the admin appeared in the photo list but
its web sizes returned 403 (e.g. as floor plan picture). The photo collection and the upload field
now always use the public disk; a data migration moves photos already stored privately (original and
web sizes, folder = media id) to the public disk. Tests for the upload and the migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:12:32 +02:00
LarsandClaude Opus 5.5 dfd3f77a5d Floor plan editor: move corners by drag or arrow keys, insert on edges, delete by double click
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Corners stay editable after drawing: drag a corner (mouse or touch), focus it and nudge with the arrow
keys (Shift for larger steps), '+' on an edge inserts a corner in its middle, double click or Delete
removes one. Tested in a browser harness with the real field markup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:47:55 +02:00
LarsandClaude Opus 5.5 f7cbc66451 Section "Grundriss (interaktiv)": floor plan with rooms, admin editor, Seebad view
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
- Table floor_plans (tenant_id, one per apartment, picture = website photo, rooms as JSON with
  corners in percent of the picture), model FloorPlan with BelongsToTenant, Property::floorPlan()
- Admin › Webseite › Grundriss: room list with name, description, photos, equipment (from the
  equipment list), accessibility hint, visibility, and an area editor (click the corners on the picture)
- Section floor_plan: base view without JavaScript (areas jump to the room list), Seebad view with
  room buttons, highlighted area and a cartouche per room (theme.js initFloorPlans)
- Tests: tenant inheritance, point parsing, website output, admin create incl. validation; the
  render test for all themes now includes the floor plan
- Docs: THEMES §5, ZUSAMMENARBEIT §6, STATUS §6 (incl. note for tenancy phase 5)
- styles/grundriss: revised rendering, WebP renditions, room areas of the Stommer flat in percent

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:26:02 +02:00
LarsandClaude Opus 5.5 04b5189bd8 Floor plan: rendering (source + WebP 900/1712) and room areas in image coordinates
Seven rooms incl. entrance; the areas use the image's own coordinate system (viewBox 0 0 1712 919),
so an SVG overlay scales exactly with the image. A traced vector version was tested and rejected
(2.7 MB, posterised).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:11:17 +02:00
LarsandClaude Opus 5.5 9b8a851ce9 Floor plan in a light 3D view (cutaway): SVG, generator and projected room areas
Generated from the plan coordinates of the scanned floor plan (photo 20); the JSON holds the room
polygons in the same projection for the interactive section. Draft for the planned section
'Interaktiver Grundriss' (STATUS §6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 12:52:06 +02:00
Lars b3114cdfe3 Merge remote-tracking branch 'origin/main' into theme/seebad
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-23 12:33:33 +02:00
LarsandCursor faf2133232 Record that the staging admin works after the tenancy deploy.
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:33:26 +02:00
LarsandClaude Opus 5.5 d2f53ceb84 Theme Seebad 0.4.0: menu panels; fix missing chevron icons; render test for all themes
- Menu panels: arrow next to each main menu item opens a panel with the page description (SEO text),
  jump links to the headed sections and a cartouche with booking and phone; Escape/outside click closes,
  focus returns; without JavaScript the menu stays plain links
- Header: booking button hidden between 1280 and 1535 px (too narrow with the arrows), desktop phone removed
- Fix: offers carousel and menu used outline chevron icons that do not exist (500 as soon as offers are shown);
  now mini chevrons
- New test: every installed theme renders all pages with reviews and offers in every display mode
- Wish: menu photo per page (ZUSAMMENARBEIT §5)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 12:33:11 +02:00
LarsandCursor ab1dffc72f Record the tenancy handoff so the next session can start at phase 3.
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
STATUS section 7 names the deployed release, the pieces that are built, and what must stay untouched.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:26:29 +02:00
LarsandCursor fc61369c4a Record that stommer.info now runs as the Stommer landlord.
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:05:57 +02:00
Lars cec49da1be Merge branch 'feature/mandanten' 2026-10-23 12:00:22 +02:00
LarsandCursor 8ebc1a3878 Assign the existing site to one landlord so stommer.info can run tenancy.
Seebad 0.3 stays in this release. With a single landlord every host still reaches the default website.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:00:11 +02:00
LarsandClaude Opus 5.5 d9e52c4789 Status: design theme section (open points, plan for new sections)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:08:03 +02:00
Lars 3621f7e924 Merge branch 'theme/seebad' (Seebad 0.3.0: all sections)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-23 10:02:11 +02:00
LarsandClaude Opus 5.5 6930d3ab0f Theme Seebad 0.3.0: own gallery, offers, reviews, FAQ, contact, booking and rich text
- All 15 sections now in Seebad style: offers and contact framed with terrace-brace brackets,
  reviews with large average and serif quotes, FAQ with large toggles, gallery with captions on focus
- Booking page offers the phone number ("Lieber persönlich?")

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:01:58 +02:00
Lars c215da0590 Merge branch 'theme/seebad' (Seebad 0.2.0: logo, Bäderstil details)
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
2026-10-23 09:53:16 +02:00
LarsandClaude Opus 5.5 e49f160496 Theme Seebad 0.2.0: logo from satz4 and Bäderstil details of the house
- Logo (satz4) traced to SVG masters (styles/satz4/svg: full logo, picture mark, wordmark) with a palette
  sampled from the original; WebP renditions for the website; favicon/apple touch icon = simplified corner bay
- House details as theme elements: arched dormer (crest of the cartouche), hero arch with window surround and
  keystone, terrace braces as corner brackets (search box, cartouche), balcony railing on the dark band
- Colours from the logo (navy, roof terracotta as accent, wave blues, sun)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:52:57 +02:00
185 changed files with 7520 additions and 325 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"permissions": {
"allow": [
"Bash(git merge *)"
]
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ # Ferienwohnung Stommer
- 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/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. 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 every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
- 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`.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Internal addresses are admin settings too: send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly); contact/reply-to (`fewo.owner.email`) and sender (`mail.from`) are overridden at boot by `Settings::applyAddressOverrides()`. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- 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`.
+25 -1
View File
@@ -14,6 +14,8 @@
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
@@ -38,6 +40,24 @@ public function __construct(
* @throws ReservationException
*/
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
{
$tenant = $property->tenant;
if ($tenant === null) {
throw new TenantContextMissing(Property::class);
}
return app(TenantContext::class)->run(
$tenant,
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution),
);
}
/**
* @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
*/
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution): Booking
{
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
Property::whereKey($property->getKey())->lockForUpdate()->first();
@@ -91,7 +111,11 @@ private function guestFor(array $guestData): array
$guest = Guest::query()->where('email', $email)->first();
if ($guest === null) {
return [Guest::create([...$guestData, 'email' => $email]), []];
return [Guest::create([
...$guestData,
'email' => $email,
'tenant_id' => app(TenantContext::class)->id(),
]), []];
}
$labels = ['first_name' => 'Vorname', 'last_name' => 'Nachname', 'phone' => 'Telefon', 'street' => 'Straße', 'postal_code' => 'PLZ', 'city' => 'Ort', 'country' => 'Land'];
+7
View File
@@ -8,12 +8,14 @@
use App\Channels\Mail\PortalMailParser;
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use App\Enums\TenantServiceKey;
use App\Mail\ChannelConflict;
use App\Mail\PortalMailNotification;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\PortalEmail;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
@@ -40,6 +42,11 @@ public function handle(PortalMail $mail): ?PortalEmail
return null;
}
// The fast path is a service of its own: a landlord without it keeps the mail unprocessed.
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant)) {
return null;
}
$parsed = $this->parser->parse($mail->subject, $mail->text);
$conflicts = [];
+4 -1
View File
@@ -98,7 +98,10 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
*/
public function offerUrl(Booking $booking): string
{
return URL::temporarySignedRoute('offers.show', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]);
$parameters = ['booking' => $booking, 'v' => $booking->offer_version];
return $booking->website()?->temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters)
?? URL::temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters);
}
/**
+46 -2
View File
@@ -3,7 +3,9 @@
namespace App\Console\Commands;
use App\Enums\UserRole;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
@@ -13,7 +15,7 @@
use function Laravel\Prompts\select;
use function Laravel\Prompts\text;
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content}')]
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content} {--tenant= : Kurzname des Mandanten}')]
#[Description('Create an admin panel account (the password is entered interactively and never passed as an argument)')]
class CreateUser extends Command
{
@@ -22,6 +24,12 @@ class CreateUser extends Command
*/
public function handle(): int
{
$tenant = $this->resolveTenant();
if ($tenant === false) {
return self::FAILURE;
}
$email = $this->argument('email') ?? text('E-Mail-Adresse', required: true, validate: ['email' => 'email']);
$email = mb_strtolower(trim($email));
@@ -51,7 +59,12 @@ public function handle(): int
return self::FAILURE;
}
User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
$user = User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
if ($tenant instanceof Tenant) {
app(TenantContext::class)->set($tenant);
$user->attachCurrentRole($tenant);
}
$this->info("Benutzer {$email} ({$role->getLabel()}) angelegt.");
@@ -59,4 +72,35 @@ public function handle(): int
return self::SUCCESS;
}
/**
* One landlord is used automatically. Several landlords need --tenant. None is allowed:
* the account exists and is attached later.
*/
private function resolveTenant(): Tenant|false|null
{
$slug = $this->option('tenant');
if (is_string($slug) && $slug !== '') {
$tenant = Tenant::query()->where('slug', $slug)->first();
if ($tenant === null) {
$this->error("Kein Mandant mit dem Kurznamen {$slug}.");
return false;
}
return $tenant;
}
$count = Tenant::query()->count();
if ($count > 1) {
$this->error('Es gibt mehrere Mandanten. Bitte --tenant=kurzname angeben.');
return false;
}
return $count === 1 ? Tenant::query()->first() : null;
}
}
+3
View File
@@ -5,7 +5,9 @@
use App\Actions\ProcessPortalMail;
use App\Channels\ChannelSyncException;
use App\Channels\Mail\MailboxReader;
use App\Enums\TenantServiceKey;
use App\Models\Channel;
use App\Tenancy\TenantFeatures;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
@@ -26,6 +28,7 @@ public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMa
}
$senders = Channel::query()->active()->get()
->filter(fn (Channel $channel): bool => app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant))
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
->unique()
->values()
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('users:promote-operator {email : E-Mail-Adresse}')]
#[Description('Grant the operator flag. The account keeps its password, two-factor setup and any landlord role.')]
class PromoteOperator extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$email = mb_strtolower(trim((string) $this->argument('email')));
$user = User::query()->where('email', $email)->first();
if ($user === null) {
$this->error('Kein Benutzer mit dieser E-Mail.');
return self::FAILURE;
}
$user->forceFill(['is_operator' => true])->save();
$this->info("{$email} ist jetzt Betreiber. Eine bestehende Mandanten-Rolle bleibt.");
return self::SUCCESS;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Enums;
/**
* What a role may do inside the current landlord. A new role is a new case on UserRole plus a list here.
*/
enum Permission: string
{
case Bookings = 'bookings';
case Properties = 'properties';
case Guests = 'guests';
case Reviews = 'reviews';
case Channels = 'channels';
case Content = 'content';
case Users = 'users';
case Settings = 'settings';
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Enums;
/**
* Services the operator unlocks per landlord. `isWired()` says whether the application really asks before
* it acts – a service that nothing asks for must not be offered as a switch, because switching it would
* promise something that does not happen.
*/
enum TenantServiceKey: string
{
case PortalSync = 'portal_sync';
case PortalMail = 'portal_mail';
case AiOffers = 'ai_offers';
case AiMarketing = 'ai_marketing';
case AiGuestMail = 'ai_guest_mail';
public function label(): string
{
return match ($this) {
self::PortalSync => 'Portal-Abgleich (iCal)',
self::PortalMail => 'Portal-Postfach (Schnellweg)',
self::AiOffers => 'KI: Angebotsentwürfe',
self::AiMarketing => 'KI: Vermarktungsassistent',
self::AiGuestMail => 'KI: Gästekommunikation',
};
}
public function description(): string
{
return match ($this) {
self::PortalSync => 'Belegungen der Portale über iCal einlesen und den eigenen Kalender als Feed anbieten.',
self::PortalMail => 'Buchungsmails der Portale aus dem Postfach lesen und Termine sofort sperren.',
self::AiOffers, self::AiMarketing, self::AiGuestMail => 'Noch nicht gebaut.',
};
}
/**
* Whether the application asks this switch before it acts. Only wired services are offered for switching.
*/
public function isWired(): bool
{
return match ($this) {
self::PortalSync, self::PortalMail => true,
self::AiOffers, self::AiMarketing, self::AiGuestMail => false,
};
}
/**
* What applies to a landlord the operator has not decided about yet. The portal services were part of
* the product before there were landlords, so switching tenancy on must not silently stop them.
*/
public function enabledByDefault(): bool
{
return $this->isWired();
}
/**
* Whether the landlord's own API key is of any use. Nothing calls out yet, so no service has one.
*/
public function usesApiKey(): bool
{
return match ($this) {
self::AiOffers, self::AiMarketing, self::AiGuestMail => true,
self::PortalSync, self::PortalMail => false,
};
}
/**
* @return list<self>
*/
public static function wired(): array
{
return array_values(array_filter(self::cases(), fn (self $service): bool => $service->isWired()));
}
}
+30 -2
View File
@@ -14,7 +14,7 @@ enum UserRole: string implements HasDescription, HasLabel
public function getLabel(): string
{
return match ($this) {
self::Admin => 'Administrator',
self::Admin => 'Mandanten-Administrator',
self::Rentals => 'Vermietung',
self::Content => 'Inhalte',
};
@@ -23,9 +23,37 @@ public function getLabel(): string
public function getDescription(): string
{
return match ($this) {
self::Admin => 'Alles, inklusive Benutzerverwaltung',
self::Admin => 'Alles im eigenen Mandanten, inklusive Benutzerverwaltung',
self::Rentals => 'Buchungen, Gäste, Preise, Angebote und Bewertungen',
self::Content => 'Bilder, Texte, FAQ, Hinweise und Bewertungen',
};
}
public function grants(Permission $permission): bool
{
return in_array($permission, $this->permissions(), true);
}
/**
* Abilities inside the current landlord. The operator is not a role here.
*
* @return list<Permission>
*/
public function permissions(): array
{
return match ($this) {
self::Admin => Permission::cases(),
self::Rentals => [
Permission::Bookings,
Permission::Properties,
Permission::Guests,
Permission::Reviews,
Permission::Channels,
],
self::Content => [
Permission::Content,
Permission::Reviews,
],
};
}
}
@@ -0,0 +1,100 @@
<?php
namespace App\Filament\Operator\Concerns;
use App\Enums\TenantServiceKey;
use App\Models\Tenant;
use App\Tenancy\TenantFeatures;
/**
* The service switches of the tenant form. They live in their own table, so the form state is read and
* written separately from the landlord's own columns. Only wired services are written – a switch for a
* service nothing asks about would promise something that does not happen.
*/
trait EditsTenantServices
{
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeFill(array $data): array
{
$tenant = $this->record;
if (! $tenant instanceof Tenant) {
return $data; // creating: there is nothing to read yet
}
$stored = $tenant->services->keyBy('service');
$data['services'] = collect(TenantServiceKey::wired())
->mapWithKeys(fn (TenantServiceKey $service): array => [$service->value => [
'is_enabled' => $stored->get($service->value)?->is_enabled ?? $service->enabledByDefault(),
]])
->all();
return $data;
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
return $this->withoutServices($data);
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
return $this->withoutServices($data);
}
protected function afterCreate(): void
{
$this->saveServices();
}
protected function afterSave(): void
{
$this->saveServices();
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function withoutServices(array $data): array
{
$this->services = is_array($data['services'] ?? null) ? $data['services'] : [];
unset($data['services']);
return $data;
}
private function saveServices(): void
{
$tenant = $this->record;
if (! $tenant instanceof Tenant) {
return;
}
foreach (TenantServiceKey::wired() as $service) {
$state = $this->services[$service->value] ?? [];
$tenant->services()->updateOrCreate(
['service' => $service->value],
['is_enabled' => (bool) ($state['is_enabled'] ?? false)],
);
}
$tenant->unsetRelation('services');
app(TenantFeatures::class)->forget($tenant);
}
}
@@ -0,0 +1,116 @@
<?php
namespace App\Filament\Operator\Pages;
use App\Enums\TenantServiceKey;
use App\Models\Tenant;
use App\Models\TenantAccessLog;
use App\Tenancy\TenantConfig;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Collection;
/**
* What applies to the whole installation: the limits every landlord is bound by, the delivery path, and
* who opened whose admin. These values come from the server's .env and are deliberately not editable here –
* they protect the system against the landlords, so a landlord's admin must not be able to reach them.
*/
class SystemOverview extends Page
{
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedServerStack;
protected static ?string $navigationLabel = 'System';
protected static ?string $title = 'System';
protected static ?string $slug = 'system';
protected static ?int $navigationSort = 2;
protected string $view = 'filament.operator.system-overview';
/**
* The ceilings a landlord may tighten but never exceed.
*
* @return list<array{label: string, value: string, note: string}>
*/
public function limits(): array
{
$config = app(TenantConfig::class);
$rows = [
['Gästedaten löschen nach', 'fewo.guest_retention_years', 'Jahre', 'Ein Mandant kann kürzer löschen, nicht länger aufbewahren.'],
['Nicht gebuchte Anfragen löschen nach', 'fewo.retention.inquiry_months', 'Monate', ''],
['Portal-Mail-Auszug löschen nach', 'fewo.retention.portal_email_excerpt_days', 'Tage', ''],
['Herkunftsangaben löschen nach', 'fewo.retention.attribution_months', 'Monate', ''],
['Bot-Schutz: Mindestzeit im Formular', 'fewo.spam.min_seconds', 'Sekunden', 'Ein Mandant kann länger warten lassen, nicht kürzer.'],
['Bot-Schutz: Anfragen je IP und Stunde', 'fewo.spam.per_ip_per_hour', '', ''],
['Bot-Schutz: Anfragen je E-Mail und Tag', 'fewo.spam.per_email_per_day', '', ''],
['Bot-Schutz: offene Anfragen je E-Mail', 'fewo.spam.open_requests_per_email', '', ''],
['Bot-Schutz: Links im Text', 'fewo.spam.max_links', '', ''],
];
return array_map(fn (array $row): array => [
'label' => $row[0],
'value' => trim($config->baselineValue($row[1]).' '.$row[2]),
'note' => $row[3],
], $rows);
}
/**
* Values that belong to the whole installation and to no landlord.
*
* @return list<array{label: string, value: string, note: string}>
*/
public function global(): array
{
$redirect = config('fewo.mail_redirect_to');
return [
[
'label' => 'Anfragen aller Websites zusammen',
'value' => config('fewo.spam.total_per_hour').' je Stunde',
'note' => 'Flutgrenze über alle Mandanten. Kein Mandant kann sie anheben.',
],
[
'label' => 'Harte Mail-Umleitung',
'value' => filled($redirect) ? (string) $redirect : 'nicht gesetzt',
'note' => filled($redirect)
? 'FEWO_MAIL_REDIRECT_TO: jede E-Mail dieses Servers geht hierhin, auch bei scharf geschalteten Mandanten.'
: 'Ohne Umleitung entscheidet die Betriebsart des jeweiligen Mandanten.',
],
[
'label' => 'Versandweg',
'value' => (string) config('mail.default'),
'note' => 'SMTP-Zugang und Datenbank sind Infrastruktur und liegen in der .env des Servers.',
],
[
'label' => 'Datenbank-Sicherungen',
'value' => config('fewo.backup.keep').' Stück',
'note' => 'Eine Sicherung der ganzen Datenbank, über alle Mandanten.',
],
];
}
/**
* @return Collection<int, Tenant>
*/
public function tenants(): Collection
{
return Tenant::query()->withCount(['services' => fn ($query) => $query->where('is_enabled', true)])->orderBy('name')->get();
}
public function wiredServiceCount(): int
{
return count(TenantServiceKey::wired());
}
/**
* @return Collection<int, TenantAccessLog>
*/
public function accessLog(): Collection
{
return TenantAccessLog::query()->with(['tenant', 'user'])->latest('created_at')->limit(20)->get();
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
namespace App\Filament\Operator;
use App\Enums\TenantServiceKey;
use App\Filament\Operator\Tenants\Pages\CreateTenant;
use App\Filament\Operator\Tenants\Pages\EditTenant;
use App\Filament\Operator\Tenants\Pages\ListTenants;
use App\Models\Tenant;
use App\Models\TenantAccessLog;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
class TenantResource extends Resource
{
protected static ?string $model = Tenant::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBuildingOffice;
protected static ?string $modelLabel = 'Mandant';
protected static ?string $pluralModelLabel = 'Mandanten';
protected static ?string $navigationLabel = 'Mandanten';
protected static ?int $navigationSort = 1;
public static function form(Schema $schema): Schema
{
return $schema
->components([
TextInput::make('name')
->label('Name')
->required()
->maxLength(255),
TextInput::make('slug')
->label('Kurzname')
->required()
->alphaDash()
->unique(ignoreRecord: true)
->maxLength(255),
Toggle::make('is_active')
->label('Aktiv')
->helperText('Ein gesperrter Mandant ist von außen nicht mehr erreichbar. Der Betreiber kommt weiter hinein.')
->default(true),
Section::make('Dienste')
->description('Was dieser Mandant nutzen darf. Ein gesperrter Dienst verschwindet auch aus seinem Admin – die Rolle eines Benutzers kann das nicht aufwiegen.')
->columnSpanFull()
->schema([
...array_map(fn (TenantServiceKey $service): Toggle => Toggle::make('services.'.$service->value.'.is_enabled')
->label($service->label())
->helperText($service->description()), TenantServiceKey::wired()),
Text::make('Noch nicht gebaut und deshalb nicht schaltbar: '.implode(', ', array_map(
fn (TenantServiceKey $service): string => $service->label(),
array_values(array_filter(TenantServiceKey::cases(), fn (TenantServiceKey $service): bool => ! $service->isWired())),
)).'. Diese Dienste erscheinen hier, sobald die Anwendung sie wirklich abfragt; eigene API-Schlüssel gehören dann in den Admin des Mandanten.'),
]),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')->label('Name')->searchable(),
TextColumn::make('slug')->label('Kurzname'),
TextColumn::make('services_count')
->label('Dienste frei')
->counts(['services' => fn (Builder $query): Builder => $query->where('is_enabled', true)])
->suffix(' von '.count(TenantServiceKey::wired())),
ToggleColumn::make('is_active')->label('Aktiv'),
])
->recordActions([
EditAction::make(),
Action::make('openAdmin')
->label('Im Admin öffnen')
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
->action(function (Tenant $record) {
TenantAccessLog::query()->create([
'tenant_id' => $record->id,
'user_id' => auth()->id(),
]);
$domain = $record->sites()->withoutGlobalScope('tenant')->whereNotNull('domain')->value('domain');
return redirect(is_string($domain) && $domain !== '' ? 'https://'.$domain.'/admin' : url('/admin'));
}),
]);
}
public static function getPages(): array
{
return [
'index' => ListTenants::route('/'),
'create' => CreateTenant::route('/create'),
'edit' => EditTenant::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Operator\Tenants\Pages;
use App\Filament\Operator\Concerns\EditsTenantServices;
use App\Filament\Operator\TenantResource;
use Filament\Resources\Pages\CreateRecord;
class CreateTenant extends CreateRecord
{
use EditsTenantServices;
protected static string $resource = TenantResource::class;
/** @var array<string, array<string, mixed>> */
public array $services = [];
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Operator\Tenants\Pages;
use App\Filament\Operator\Concerns\EditsTenantServices;
use App\Filament\Operator\TenantResource;
use Filament\Resources\Pages\EditRecord;
class EditTenant extends EditRecord
{
use EditsTenantServices;
protected static string $resource = TenantResource::class;
/** @var array<string, array<string, mixed>> */
public array $services = [];
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Operator\Tenants\Pages;
use App\Filament\Operator\TenantResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListTenants extends ListRecords
{
protected static string $resource = TenantResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
+147 -18
View File
@@ -4,7 +4,9 @@
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
use App\Models\Tenant;
use App\Support\Settings;
use App\Tenancy\TenantConfig;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Radio;
@@ -23,13 +25,31 @@
use UnitEnum;
/**
* Operating mode (test mode sends every e-mail to one test recipient only; live delivers to the real recipients)
* and the addresses of the internal communication (notifications, contact/reply-to, sender). Administrators only.
* Operating data of the landlord: operating mode (test mode sends every e-mail to one test recipient only;
* live delivers to the real recipients), the addresses of the internal communication, the landlord's own
* address and bank details, and the periods. Administrators only.
*/
class Operations extends Page
{
use FollowsAdminMode;
/** Periods and counters the landlord may set (column => label). Empty means the system default. */
private const PERIODS = [
'deposit_due_days' => 'Anzahlung fällig nach (Tage)',
'review_request_after_days' => 'Bewertungsbitte nach Abreise (Tage)',
'guest_retention_years' => 'Gästedaten löschen nach (Jahre)',
'retention_inquiry_months' => 'Nicht gebuchte Anfragen löschen nach (Monate)',
'retention_portal_email_excerpt_days' => 'Portal-Mail-Auszug löschen nach (Tage)',
'retention_attribution_months' => 'Herkunftsangaben löschen nach (Monate)',
'spam_min_seconds' => 'Bot-Schutz: Mindestzeit im Formular (Sekunden)',
'spam_per_ip_per_hour' => 'Bot-Schutz: Anfragen je IP und Stunde',
'spam_per_email_per_day' => 'Bot-Schutz: Anfragen je E-Mail und Tag',
'spam_open_requests_per_email' => 'Bot-Schutz: gleichzeitig offene Anfragen je E-Mail',
'spam_max_links' => 'Bot-Schutz: erlaubte Links im Text',
'channel_stale_after_minutes' => 'Portal-Abgleich gilt als veraltet nach (Minuten)',
'channel_task_reminder_after_minutes' => 'Erinnerung an Portal-Aufgaben nach (Minuten)',
];
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPower;
protected static string|UnitEnum|null $navigationGroup = 'System';
@@ -42,7 +62,7 @@ class Operations extends Page
protected static ?int $navigationSort = 1;
/** @var array<string, ?string> */
/** @var array<string, mixed> */
public array $data = [];
public static function canAccess(): bool
@@ -52,13 +72,25 @@ public static function canAccess(): bool
public function mount(): void
{
$tenant = $this->tenant();
$this->form->fill([
'mode' => Settings::get(Settings::MODE, Settings::MODE_TEST),
'test_recipient' => Settings::get(Settings::TEST_RECIPIENT) ?? auth()->user()?->email,
'notification_recipients' => Settings::notificationRecipients(),
'contact_email' => config('fewo.owner.email'),
'sender_name' => config('mail.from.name'),
'sender_email' => config('mail.from.address'),
'mode' => $tenant->operating_mode ?: Settings::MODE_TEST,
'test_recipient' => $tenant->test_recipient ?: auth()->user()?->email,
'notification_recipients' => $tenant->notificationRecipients(),
'contact_email' => $tenant->contact_email,
'sender_name' => $tenant->sender_name,
'sender_email' => $tenant->sender_email,
'owner_name' => $tenant->owner_name,
'owner_street' => $tenant->owner_street,
'owner_city' => $tenant->owner_city,
'owner_phone' => $tenant->owner_phone,
'bank_account_holder' => $tenant->bank_account_holder,
'bank_name' => $tenant->bank_name,
'bank_iban' => $tenant->bank_iban,
'bank_bic' => $tenant->bank_bic,
'tax_note' => $tenant->tax_note,
...$this->periodValues($tenant),
]);
}
@@ -117,6 +149,34 @@ public function form(Schema $schema): Schema
: '')
->columnSpanFull(),
]),
Section::make('Vermieterin')
->description('Steht in E-Mails, im Angebot, im Mietvertrag und auf der Webseite.')
->columns(2)
->schema([
TextInput::make('owner_name')->label('Name')->required()->maxLength(255),
TextInput::make('owner_phone')->label('Telefon')->maxLength(50),
TextInput::make('owner_street')->label('Straße und Hausnummer')->maxLength(255),
TextInput::make('owner_city')->label('PLZ und Ort')->maxLength(255),
]),
Section::make('Bankverbindung und Steuer')
->description('Steht im Mietvertrag und in den Zahlungsaufforderungen. Die Angaben liegen verschlüsselt in der Datenbank.')
->columns(2)
->schema([
TextInput::make('bank_account_holder')->label('Kontoinhaber')->maxLength(255),
TextInput::make('bank_name')->label('Bank')->maxLength(255),
TextInput::make('bank_iban')->label('IBAN')->maxLength(40),
TextInput::make('bank_bic')->label('BIC')->maxLength(20),
TextInput::make('tax_note')
->label('Steuerangabe')
->helperText('Zum Beispiel die Steuernummer oder der Hinweis auf die Kleinunternehmerregelung.')
->maxLength(255)
->columnSpanFull(),
]),
Section::make('Fristen und Grenzen')
->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.')
->columns(3)
->collapsed()
->schema($this->periodFields()),
]);
}
@@ -133,20 +193,89 @@ public function content(Schema $schema): Schema
public function save(): void
{
$data = $this->form->getState();
$tenant = $this->tenant();
$wasLive = $tenant->isLive();
if ($data['mode'] === Settings::MODE_LIVE && Settings::get(Settings::MODE) !== Settings::MODE_LIVE) {
$tenant->update([
'operating_mode' => $data['mode'],
'test_recipient' => $data['test_recipient'] ?? $tenant->test_recipient,
'notification_emails' => implode(', ', Settings::addressList(implode(',', $data['notification_recipients'] ?? []))),
'contact_email' => $data['contact_email'],
'sender_name' => $data['sender_name'],
'sender_email' => $data['sender_email'],
'owner_name' => $data['owner_name'],
'owner_street' => $data['owner_street'] ?? null,
'owner_city' => $data['owner_city'] ?? null,
'owner_phone' => $data['owner_phone'] ?? null,
'bank_account_holder' => $data['bank_account_holder'] ?? null,
'bank_name' => $data['bank_name'] ?? null,
'bank_iban' => $data['bank_iban'] ?? null,
'bank_bic' => $data['bank_bic'] ?? null,
'tax_note' => $data['tax_note'] ?? null,
...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)),
]);
app(TenantConfig::class)->refresh();
if ($data['mode'] === Settings::MODE_LIVE && ! $wasLive) {
Notification::make()->title('Scharf geschaltet')->body('Ab jetzt erhalten Gäste und Vermieterin die E-Mails direkt.')->warning()->send();
} else {
Notification::make()->title('Gespeichert')->success()->send();
}
}
Settings::save([
Settings::MODE => $data['mode'],
Settings::TEST_RECIPIENT => $data['test_recipient'] ?? Settings::get(Settings::TEST_RECIPIENT),
Settings::NOTIFICATION_RECIPIENTS => implode(', ', Settings::addressList(implode(',', $data['notification_recipients'] ?? []))),
Settings::CONTACT_EMAIL => $data['contact_email'],
Settings::SENDER_NAME => $data['sender_name'],
Settings::SENDER_EMAIL => $data['sender_email'],
]);
/**
* The landlord this page edits: the one of the request, else the only one there is.
*/
private function tenant(): Tenant
{
$tenant = Settings::tenant();
abort_if($tenant === null, 404);
return $tenant;
}
/**
* @return array<string, ?int>
*/
private function periodValues(Tenant $tenant): array
{
return array_combine(array_keys(self::PERIODS), array_map(fn (string $column): ?int => $tenant->{$column}, array_keys(self::PERIODS)));
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function periodInput(array $data): array
{
return array_combine(array_keys(self::PERIODS), array_map(fn (string $column): mixed => $data[$column] ?? null, array_keys(self::PERIODS)));
}
/**
* @return list<TextInput>
*/
private function periodFields(): array
{
return array_map(function (string $column) {
$field = TextInput::make($column)
->label(self::PERIODS[$column])
->numeric()
->integer()
->minValue(0);
$config = app(TenantConfig::class);
if (($ceiling = $config->ceilingFor($column)) !== null) {
return $field->maxValue($ceiling)->helperText('Vorgabe des Systems: höchstens '.$ceiling);
}
if (($floor = $config->floorFor($column)) !== null) {
return $field->minValue($floor)->helperText('Vorgabe des Systems: mindestens '.$floor);
}
return $field;
}, array_keys(self::PERIODS));
}
}
@@ -0,0 +1,56 @@
<?php
namespace App\Filament\Resources\FloorPlans;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Resources\FloorPlans\Pages\CreateFloorPlan;
use App\Filament\Resources\FloorPlans\Pages\EditFloorPlan;
use App\Filament\Resources\FloorPlans\Pages\ListFloorPlans;
use App\Filament\Resources\FloorPlans\Schemas\FloorPlanForm;
use App\Filament\Resources\FloorPlans\Tables\FloorPlansTable;
use App\Models\FloorPlan;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
/**
* Floor plan per apartment: picture from the website photos plus rooms drawn on it (section "Grundriss").
*/
class FloorPlanResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = FloorPlan::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedMap;
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
protected static ?string $modelLabel = 'Grundriss';
protected static ?string $pluralModelLabel = 'Grundriss';
protected static ?int $navigationSort = 5;
public static function form(Schema $schema): Schema
{
return FloorPlanForm::configure($schema);
}
public static function table(Table $table): Table
{
return FloorPlansTable::configure($table);
}
public static function getPages(): array
{
return [
'index' => ListFloorPlans::route('/'),
'create' => CreateFloorPlan::route('/create'),
'edit' => EditFloorPlan::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Resources\FloorPlans\Pages;
use App\Filament\Resources\FloorPlans\FloorPlanResource;
use Filament\Resources\Pages\CreateRecord;
class CreateFloorPlan extends CreateRecord
{
protected static string $resource = FloorPlanResource::class;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\FloorPlans\Pages;
use App\Filament\Resources\FloorPlans\FloorPlanResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditFloorPlan extends EditRecord
{
protected static string $resource = FloorPlanResource::class;
protected function getHeaderActions(): array
{
return [
DeleteAction::make(),
];
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Resources\FloorPlans\Pages;
use App\Filament\Resources\FloorPlans\FloorPlanResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListFloorPlans extends ListRecords
{
protected static string $resource = FloorPlanResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
@@ -0,0 +1,81 @@
<?php
namespace App\Filament\Resources\FloorPlans\Schemas;
use App\Filament\Forms\Components\PhotoSelect;
use App\Models\Amenity;
use App\Models\FloorPlan;
use App\Models\Property;
use Closure;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Components\ViewField;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Illuminate\Support\Str;
class FloorPlanForm
{
public static function configure(Schema $schema): Schema
{
return $schema
->columns(2)
->components([
Select::make('property_id')
->label('Wohnung')
->options(fn (): array => Property::query()->pluck('name', 'id')->all())
->default(fn (): ?int => Property::query()->value('id'))
->unique(ignoreRecord: true)
->validationMessages(['unique' => 'Für diese Wohnung gibt es schon einen Grundriss.'])
->required()
->live(),
PhotoSelect::make('photo_id')
->label('Grundriss-Bild')
->helperText('Rendering oder Plan aus Webseite › Fotos. Ein neues Bild im gleichen Ausschnitt behält die Räume.')
->required()
->live(),
Repeater::make('rooms')
->label('Räume')
->columnSpanFull()
->defaultItems(0)
->addActionLabel('Raum hinzufügen')
->reorderable()
->collapsible()
->itemLabel(fn (array $state): string => filled($state['name'] ?? null) ? $state['name'] : 'Neuer Raum')
->columns(2)
->schema([
Hidden::make('id')->default(fn (): string => (string) Str::uuid()),
TextInput::make('name')->label('Name')->placeholder('z. B. Schlafzimmer')->required()->maxLength(60)->live(onBlur: true),
Toggle::make('is_visible')->label('Auf der Website zeigen')->default(true)->inline(false),
ViewField::make('points')
->label('Fläche auf dem Grundriss')
->view('filament.forms.floor-plan-area')
->columnSpanFull()
->rules([
fn (): Closure => function (string $attribute, mixed $value, Closure $fail): void {
if (count(FloorPlan::points(is_string($value) ? $value : null)) < 3) {
$fail('Bitte mindestens drei Ecken des Raums auf dem Bild anklicken.');
}
},
]),
Textarea::make('description')->label('Beschreibung')->rows(3)->maxLength(400)->columnSpanFull(),
PhotoSelect::make('photo_ids')->label('Fotos')->multiple()->helperText('Das erste Foto steht oben, die weiteren als kleine Bilder darunter.'),
Select::make('amenity_ids')
->label('Ausstattung')
->multiple()
->searchable()
->options(fn (Get $get): array => Amenity::query()->where('property_id', $get('../../property_id'))->orderBy('sort_order')->pluck('name', 'id')->all())
->helperText('Aus Webseite › Ausstattung – nichts doppelt pflegen.'),
TextInput::make('hint')
->label('Hinweis zur Barrierefreiheit (optional)')
->placeholder('z. B. Flache Dusche mit kleiner Kante')
->maxLength(160)
->columnSpanFull(),
]),
]);
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Filament\Resources\FloorPlans\Tables;
use App\Models\FloorPlan;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
class FloorPlansTable
{
public static function configure(Table $table): Table
{
return $table
->paginated(false)
->columns([
TextColumn::make('property.name')->label('Wohnung'),
TextColumn::make('rooms')->label('Räume')
->state(fn (FloorPlan $record): string => $record->visibleRooms()->pluck('name')->implode(', ') ?: 'noch keine'),
TextColumn::make('updated_at')->label('Geändert')->since(),
])
->recordActions([
EditAction::make(),
]);
}
}
@@ -21,6 +21,7 @@ public static function configure(Schema $schema): Schema
SpatieMediaLibraryFileUpload::make('image')
->label('Bild')
->collection(Photo::COLLECTION)
->disk('public')
->image()
->imageEditor()
->maxSize(25 * 1024)
@@ -0,0 +1,136 @@
<?php
namespace App\Filament\Resources\Sites\Concerns;
use App\Models\Site;
use App\Models\SiteDomain;
use Illuminate\Validation\ValidationException;
/**
* The further hostnames of a website. The field "Domain" stays the main address used for guest links;
* everything entered here answers as well. Needed as soon as there is a second landlord, because from
* then on an unknown host is a 404 and "www" is a host of its own.
*/
trait EditsSiteHosts
{
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeFill(array $data): array
{
$site = $this->record;
if (! $site instanceof Site) {
return $data;
}
$primary = SiteDomain::normalise($site->domain);
$data['extra_hosts'] = $site->domains()
->pluck('host')
->reject(fn (string $host): bool => $host === $primary)
->values()
->all();
return $data;
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
return $this->withoutHosts($data);
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
return $this->withoutHosts($data);
}
protected function afterCreate(): void
{
$this->saveHosts();
}
protected function afterSave(): void
{
$this->saveHosts();
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function withoutHosts(array $data): array
{
$hosts = is_array($data['extra_hosts'] ?? null) ? $data['extra_hosts'] : [];
$this->extraHosts = array_values(array_filter(array_map(
fn (mixed $host): string => SiteDomain::normalise(is_string($host) ? $host : null),
$hosts,
)));
$this->refuseForeignHosts();
unset($data['extra_hosts']);
return $data;
}
/**
* A hostname that already answers for another website must not be taken over – otherwise one landlord
* could pull another landlord's visitors onto their own site just by typing that address here.
*/
private function refuseForeignHosts(): void
{
$site = $this->record;
$taken = SiteDomain::query()
->whereIn('host', $this->extraHosts)
->when($site instanceof Site, fn ($query) => $query->where('site_id', '!=', $site->id))
->pluck('host');
if ($taken->isNotEmpty()) {
throw ValidationException::withMessages([
'data.extra_hosts' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '),
]);
}
}
private function saveHosts(): void
{
$site = $this->record;
if (! $site instanceof Site) {
return;
}
$primary = SiteDomain::normalise($site->domain);
$wanted = collect($this->extraHosts)
->filter()
->when(filled($primary), fn ($hosts) => $hosts->push($primary))
->unique()
->values();
$site->domains()->whereNotIn('host', $wanted->all())->delete();
foreach ($wanted as $host) {
// Never take a host away from another website: that would hand one landlord's visitors to another.
$owner = SiteDomain::query()->where('host', $host)->value('site_id');
if ($owner !== null && $owner !== $site->id) {
continue;
}
SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]);
}
}
}
@@ -2,10 +2,16 @@
namespace App\Filament\Resources\Sites\Pages;
use App\Filament\Resources\Sites\Concerns\EditsSiteHosts;
use App\Filament\Resources\Sites\SiteResource;
use Filament\Resources\Pages\CreateRecord;
class CreateSite extends CreateRecord
{
use EditsSiteHosts;
protected static string $resource = SiteResource::class;
/** @var list<string> */
public array $extraHosts = [];
}
@@ -2,14 +2,20 @@
namespace App\Filament\Resources\Sites\Pages;
use App\Filament\Resources\Sites\Concerns\EditsSiteHosts;
use App\Filament\Resources\Sites\SiteResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditSite extends EditRecord
{
use EditsSiteHosts;
protected static string $resource = SiteResource::class;
/** @var list<string> */
public array $extraHosts = [];
protected function getHeaderActions(): array
{
return [
@@ -7,6 +7,7 @@
use App\Themes\ThemeRegistry;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
@@ -26,11 +27,17 @@ public static function configure(Schema $schema): Schema
->schema([
TextInput::make('name')->label('Name')->required()->maxLength(120),
TextInput::make('domain')
->label('Domain')
->label('Hauptadresse')
->placeholder('www.fewo-stommer.de')
->helperText('Leer = Standard-Website für alle Adressen ohne eigene Zuordnung.')
->helperText('Steht in Links an Gäste. Leer = Standard-Website, solange es nur diesen Mandanten gibt. Ab dem zweiten Mandanten antwortet nur eine eingetragene Adresse, alles andere bekommt 404.')
->unique(ignoreRecord: true)
->maxLength(190),
TagsInput::make('extra_hosts')
->label('Weitere Adressen')
->placeholder('stommer.info')
->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Alle hier eingetragenen liefern dieselbe Website. Enter nach jeder Adresse.')
->nestedRecursiveRules(['string', 'max:190'])
->columnSpanFull(),
Select::make('theme')
->label('Theme')
->options(fn (): array => app(ThemeRegistry::class)->options())
@@ -15,7 +15,8 @@ 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('domain')->label('Hauptadresse')->placeholder('alle übrigen Adressen'),
TextColumn::make('domains.host')->label('Antwortet auf')->badge()->placeholder('jede Adresse'),
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(),
@@ -3,9 +3,40 @@
namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\Users\UserResource;
use App\Models\User;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
class CreateUser extends CreateRecord
{
protected static string $resource = UserResource::class;
/**
* An address that already belongs to another landlord is attached. The account, its password
* and its two-factor setup stay as they are.
*
* @param array<string, mixed> $data
*/
protected function handleRecordCreation(array $data): Model
{
$email = is_string($data['email'] ?? null) ? $data['email'] : '';
$existing = User::query()->where('email', $email)->first();
if ($existing === null) {
return parent::handleRecordCreation($data);
}
$attributes = [
'name' => $data['name'] ?? $existing->name,
'role' => $data['role'] ?? $existing->role,
];
if (array_key_exists('admin_mode', $data)) {
$attributes['admin_mode'] = $data['admin_mode'];
}
$existing->forceFill($attributes)->save();
return $existing;
}
}
@@ -3,6 +3,7 @@
namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\Users\UserResource;
use App\Models\User;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
@@ -16,4 +17,22 @@ protected function getHeaderActions(): array
DeleteAction::make(),
];
}
/**
* A hidden password field must not be writable by a crafted request either.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
$actor = auth()->user();
$record = $this->getRecord();
if (! $actor instanceof User || ! $record instanceof User || ! $actor->mayResetCredentials($record)) {
unset($data['password']);
}
return $data;
}
}
@@ -4,6 +4,9 @@
use App\Enums\AdminMode;
use App\Enums\UserRole;
use App\Models\User;
use App\Tenancy\TenantContext;
use Closure;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;
@@ -21,15 +24,54 @@ public static function configure(Schema $schema): Schema
->maxLength(255),
TextInput::make('email')
->label('E-Mail (Anmeldename)')
->helperText('Besteht die E-Mail schon, kommt das Konto zu diesem Mandanten dazu. Passwort und Zwei-Faktor-Anmeldung bleiben.')
->email()
->required()
->unique(ignoreRecord: true)
->maxLength(255),
->maxLength(255)
->rules([
fn (?User $record): Closure => function (string $attribute, mixed $value, Closure $fail) use ($record): void {
if (! is_string($value)) {
return;
}
$existing = User::query()->where('email', $value)->first();
if ($existing === null) {
return;
}
if ($record !== null) {
if ($existing->isNot($record)) {
$fail('Diese E-Mail wird schon verwendet.');
}
return;
}
$tenantId = app(TenantContext::class)->id();
if ($tenantId !== null && $existing->tenants()->where('tenants.id', $tenantId)->exists()) {
$fail('Diese Person gehört schon zu diesem Mandanten.');
}
},
]),
Radio::make('role')
->label('Rolle')
->helperText('Bestimmt, was die Person darf.')
->helperText('Gilt für diesen Mandanten.')
->options(UserRole::class)
->required()
->afterStateHydrated(function (Radio $component, ?User $record): void {
if ($record === null) {
return;
}
$tenantId = app(TenantContext::class)->id();
$role = $tenantId !== null ? ($record->roleOn($tenantId) ?? $record->role) : $record->role;
if ($role !== null) {
$component->state($role->value);
}
})
->columnSpanFull(),
Radio::make('admin_mode')
->label('Ansicht')
@@ -42,6 +84,15 @@ public static function configure(Schema $schema): Schema
->revealable()
->minLength(10)
->required(fn (string $operation): bool => $operation === 'create')
->visible(function (string $operation, ?User $record): bool {
if ($operation === 'create') {
return true;
}
$actor = auth()->user();
return $actor instanceof User && $actor->mayResetCredentials($record);
})
->dehydrated(fn (?string $state): bool => filled($state)),
]);
}
@@ -2,7 +2,9 @@
namespace App\Filament\Resources\Users\Tables;
use App\Enums\UserRole;
use App\Models\User;
use App\Tenancy\TenantContext;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
@@ -20,7 +22,18 @@ public static function configure(Table $table): Table
->columns([
TextColumn::make('name')->label('Name')->searchable(),
TextColumn::make('email')->label('E-Mail')->searchable(),
TextColumn::make('role')->label('Rolle')->badge(),
TextColumn::make('role')
->label('Rolle')
->badge()
->state(function (User $record): ?UserRole {
$tenantId = app(TenantContext::class)->id();
if ($tenantId === null) {
return $record->role;
}
return $record->roleOn($tenantId) ?? $record->role;
}),
TextColumn::make('mode')->label('Ansicht')->state(fn (User $record): string => $record->adminMode()->getLabel()),
IconColumn::make('two_factor')->label('2FA')->state(fn (User $record): bool => filled($record->getAppAuthenticationSecret()))->boolean(),
])
@@ -32,12 +45,35 @@ public static function configure(Table $table): Table
->color('warning')
->requiresConfirmation()
->modalDescription('Zum Beispiel bei verlorenem Handy: Die Person richtet die Zwei-Faktor-Anmeldung bei der nächsten Anmeldung neu ein.')
->visible(fn (User $record): bool => filled($record->getAppAuthenticationSecret()))
->visible(function (User $record): bool {
$actor = auth()->user();
return filled($record->getAppAuthenticationSecret())
&& $actor instanceof User
&& $actor->mayResetCredentials($record);
})
->action(function (User $record): void {
$actor = auth()->user();
if (! $actor instanceof User || ! $actor->mayResetCredentials($record)) {
return;
}
$record->saveAppAuthenticationSecret(null);
$record->saveAppAuthenticationRecoveryCodes(null);
Notification::make()->title('2FA zurückgesetzt')->success()->send();
}),
Action::make('revokeAccess')
->label('Zugang entziehen')
->icon(Heroicon::OutlinedNoSymbol)
->color('danger')
->requiresConfirmation()
->modalDescription('Das Konto bleibt bestehen und verliert nur den Zugang zu diesem Mandanten. Passwort und Zwei-Faktor-Anmeldung bleiben.')
->visible(fn (User $record): bool => $record->tenants()->count() >= 2)
->action(function (User $record): void {
$record->revokeCurrentTenant();
Notification::make()->title('Zugang entzogen')->success()->send();
}),
DeleteAction::make(),
]);
}
@@ -9,11 +9,13 @@
use App\Filament\Resources\Users\Schemas\UserForm;
use App\Filament\Resources\Users\Tables\UsersTable;
use App\Models\User;
use App\Tenancy\TenantContext;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;
class UserResource extends Resource
@@ -30,6 +32,23 @@ class UserResource extends Resource
protected static ?string $pluralModelLabel = 'Benutzer';
/**
* Accounts are global. This list shows only people who belong to the landlord that is open.
*
* @return Builder<User>
*/
public static function getEloquentQuery(): Builder
{
$query = parent::getEloquentQuery();
$tenantId = app(TenantContext::class)->id();
if ($tenantId === null) {
return $query;
}
return $query->whereHas('tenants', fn (Builder $membership) => $membership->where('tenants.id', $tenantId));
}
public static function form(Schema $schema): Schema
{
return UserForm::configure($schema);
@@ -27,6 +27,8 @@ public function feed(string $token, ICalFeed $feed): Response
{
$channel = Channel::query()->where('export_token', $token)->where('is_active', true)->firstOrFail();
abort_unless($channel->servesItsLandlord(), 404);
return response($feed->build($channel), 200, [
'Content-Type' => 'text/calendar; charset=utf-8',
'Content-Disposition' => 'inline; filename="belegung.ics"',
@@ -20,7 +20,8 @@ public function confirm(Guest $guest): View
return view('marketing-consent', [
'title' => 'Anmeldung bestätigt',
'message' => 'Vielen Dank! Wir informieren Sie künftig über freie Termine und Angebote. Sie können sich jederzeit wieder abmelden.',
'unsubscribeUrl' => URL::signedRoute('marketing.unsubscribe', $guest),
'unsubscribeUrl' => $guest->website()?->signedRoute('marketing.unsubscribe', $guest)
?? URL::signedRoute('marketing.unsubscribe', $guest),
]);
}
+12 -3
View File
@@ -7,6 +7,7 @@
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use DateTimeInterface;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -38,8 +39,8 @@ public function show(Request $request, Booking $booking, AcceptOffer $accept): V
'booking' => $booking,
'problem' => $problem,
'canAnswer' => $booking->status === BookingStatus::OfferSent && $problem === null,
'acceptUrl' => URL::temporarySignedRoute('offers.accept', $expires, ['booking' => $booking, 'v' => $version]),
'rejectUrl' => URL::temporarySignedRoute('offers.reject', $expires, ['booking' => $booking, 'v' => $version]),
'acceptUrl' => $this->signed($booking, 'offers.accept', $expires, $version),
'rejectUrl' => $this->signed($booking, 'offers.reject', $expires, $version),
'title' => 'Ihr Angebot',
]);
}
@@ -62,7 +63,7 @@ public function reject(Request $request, Booking $booking, RejectOffer $reject):
private function answer(Request $request, Booking $booking, callable $action, string $success): RedirectResponse
{
$version = (int) $request->query('v');
$back = URL::temporarySignedRoute('offers.show', now()->addDays(30), ['booking' => $booking, 'v' => $version]);
$back = $this->signed($booking, 'offers.show', now()->addDays(30), $version);
try {
$action($version);
@@ -72,4 +73,12 @@ private function answer(Request $request, Booking $booking, callable $action, st
return redirect()->to($back)->with('offer.success', $success);
}
private function signed(Booking $booking, string $name, DateTimeInterface $expiration, int $version): string
{
$parameters = ['booking' => $booking, 'v' => $version];
return $booking->website()?->temporarySignedRoute($name, $expiration, $parameters)
?? URL::temporarySignedRoute($name, $expiration, $parameters);
}
}
+38 -1
View File
@@ -2,6 +2,9 @@
namespace App\Http\Middleware;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use App\Themes\Theme;
use App\Themes\ThemeFactory;
use Closure;
@@ -17,8 +20,42 @@ public function __construct(private ThemeFactory $factory) {}
public function handle(Request $request, Closure $next): Response
{
app()->instance(Theme::class, $this->factory->forRequest($request)->activate());
$context = app(TenantContext::class);
$context->forget();
$theme = $this->factory->forRequest($request)->activate();
app()->instance(Theme::class, $theme);
$tenant = null;
if ($theme->site->exists && $theme->site->tenant_id !== null) {
$tenant = $theme->site->tenant;
} elseif (Tenant::query()->count() === 1) {
$tenant = Tenant::query()->first();
}
if ($tenant !== null) {
if (! $tenant->is_active && ! $this->operatorMayPass($request)) {
abort(404);
}
$context->set($tenant);
}
return $next($request);
}
/**
* A suspended landlord stays reachable for the operator, and the operator panel itself stays open.
*/
private function operatorMayPass(Request $request): bool
{
if ($request->is('betreiber', 'betreiber/*')) {
return true;
}
$user = $request->user();
return $user instanceof User && $user->is_operator;
}
}
+4 -2
View File
@@ -15,6 +15,7 @@
use App\Pricing\PriceQuote;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
@@ -276,9 +277,10 @@ public function submit(CreateReservation $createReservation): void
*/
private function tooManyRequests(): bool
{
$tenantKey = (string) (app(TenantContext::class)->id() ?? 'global');
$limits = [
'booking-request:'.request()->ip() => [config('fewo.spam.per_ip_per_hour'), 3600],
'booking-request-email:'.sha1(mb_strtolower($this->email)) => [config('fewo.spam.per_email_per_day'), 86400],
'booking-request:'.$tenantKey.':'.request()->ip() => [config('fewo.spam.per_ip_per_hour'), 3600],
'booking-request-email:'.$tenantKey.':'.sha1(mb_strtolower($this->email)) => [config('fewo.spam.per_email_per_day'), 86400],
'booking-request-all' => [config('fewo.spam.total_per_hour'), 3600],
];
+2 -1
View File
@@ -31,7 +31,8 @@ public function envelope(): Envelope
public function content(): Content
{
return new Content(
with: ['url' => URL::temporarySignedRoute('marketing.confirm', now()->addDays(14), $this->guest)],
with: ['url' => $this->guest->website()?->temporarySignedRoute('marketing.confirm', now()->addDays(14), ['guest' => $this->guest])
?? URL::temporarySignedRoute('marketing.confirm', now()->addDays(14), $this->guest)],
markdown: 'mail.marketing-consent-request',
);
}
+2 -1
View File
@@ -31,7 +31,8 @@ public function envelope(): Envelope
public function content(): Content
{
return new Content(
with: ['url' => URL::temporarySignedRoute('reviews.create', now()->addDays(90), $this->booking)],
with: ['url' => $this->booking->website()?->temporarySignedRoute('reviews.create', now()->addDays(90), ['booking' => $this->booking])
?? URL::temporarySignedRoute('reviews.create', now()->addDays(90), $this->booking)],
markdown: 'mail.review-request',
);
}
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\AmenityArea;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\AmenityFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,7 +17,7 @@
class Amenity extends Model
{
/** @use HasFactory<AmenityFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Carbon\CarbonInterface;
use Database\Factories\AppearanceFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -19,7 +20,7 @@
class Appearance extends Model
{
/** @use HasFactory<AppearanceFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Texts an appearance can replace, with their admin labels. Sections read them through Theme::text().
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use App\Observers\BlockedPeriodObserver;
use Carbon\CarbonInterface;
use Database\Factories\BlockedPeriodFactory;
@@ -22,7 +23,7 @@
class BlockedPeriod extends Model
{
/** @use HasFactory<BlockedPeriodFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+38 -2
View File
@@ -4,6 +4,7 @@
use App\Enums\BookingStatus;
use App\Enums\ReferralSource;
use App\Models\Concerns\BelongsToTenant;
use App\Observers\BookingObserver;
use Carbon\CarbonInterface;
use Database\Factories\BookingFactory;
@@ -65,15 +66,41 @@
class Booking extends Model
{
/** @use HasFactory<BookingFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
protected static function booted(): void
{
static::created(function (Booking $booking): void {
$booking->forceFill(['reference' => $booking->created_at->format('Y').'-'.str_pad((string) $booking->id, 4, '0', STR_PAD_LEFT)])->saveQuietly();
$booking->forceFill(['reference' => $booking->nextReference()])->saveQuietly();
});
}
/**
* Next booking number of this landlord in the year of creation, continuing after the highest
* number already issued. Existing numbers are never rewritten.
*/
public function nextReference(): string
{
$year = $this->created_at->format('Y');
$references = static::withoutGlobalScope('tenant')
->where('tenant_id', $this->tenant_id)
->where('reference', 'like', $year.'-%')
->whereKeyNot($this->id)
->lockForUpdate()
->pluck('reference');
$number = 1;
foreach ($references as $reference) {
if (is_string($reference) && preg_match('/-(\d+)$/', $reference, $match) === 1) {
$number = max($number, ((int) $match[1]) + 1);
}
}
return $year.'-'.str_pad((string) $number, 4, '0', STR_PAD_LEFT);
}
/**
* Get the attributes that should be cast.
*
@@ -199,4 +226,13 @@ public function isHoldActive(): bool
{
return in_array($this->status, BookingStatus::holding(), true) && $this->hold_expires_at?->isFuture();
}
/**
* The website this stay belongs to, regardless of which landlord is current.
*/
public function website(): ?Site
{
return $this->property()->withoutGlobalScope('tenant')->first()
?->site()->withoutGlobalScope('tenant')->first();
}
}
+14 -2
View File
@@ -4,6 +4,9 @@
use App\Channels\ChannelRegistry;
use App\Channels\Contracts\ChannelConnector;
use App\Enums\TenantServiceKey;
use App\Models\Concerns\BelongsToTenant;
use App\Tenancy\TenantFeatures;
use Database\Factories\ChannelFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
@@ -24,7 +27,7 @@
class Channel extends Model
{
/** @use HasFactory<ChannelFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
protected static function booted(): void
{
@@ -99,7 +102,16 @@ public function connector(): ChannelConnector
public function importsOccupations(): bool
{
return $this->is_active && $this->connector()->canImport($this);
return $this->is_active && $this->servesItsLandlord() && $this->connector()->canImport($this);
}
/**
* Whether the landlord this channel belongs to has the portal synchronisation unlocked at all.
* Asked here, so that neither an import nor the export feed can run around the switch.
*/
public function servesItsLandlord(): bool
{
return app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $this->tenant);
}
public function exportUrl(): string
+3
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -9,6 +10,8 @@
#[Fillable(['channel_id', 'successful', 'events', 'added', 'changed', 'removed', 'conflicts', 'message', 'duration_ms'])]
class ChannelSyncLog extends Model
{
use BelongsToTenant;
public const UPDATED_AT = null;
/**
+2 -1
View File
@@ -4,6 +4,7 @@
use App\Enums\ChannelTaskAction;
use App\Enums\ChannelTaskStatus;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\ChannelTaskFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -20,7 +21,7 @@
class ChannelTask extends Model
{
/** @use HasFactory<ChannelTaskFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+118
View File
@@ -0,0 +1,118 @@
<?php
namespace App\Models\Concerns;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Models\Site;
use App\Models\Tenant;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;
/**
* Every row belongs to exactly one landlord. When a landlord is current, queries only see that
* landlord. Inserts copy the landlord from the parent row, then from the current context.
*
* @mixin Model
*/
trait BelongsToTenant
{
public function initializeBelongsToTenant(): void
{
$this->mergeFillable(['tenant_id']);
}
public static function bootBelongsToTenant(): void
{
static::addGlobalScope('tenant', function (Builder $builder): void {
$context = app(TenantContext::class);
if ($context->id() !== null) {
$builder->where($builder->getModel()->qualifyColumn('tenant_id'), $context->id());
return;
}
if ($context->isRequired()) {
throw new TenantContextMissing($builder->getModel()::class);
}
});
static::creating(function (Model $model): void {
$inherited = self::tenantIdFromParent($model);
if ($inherited !== null) {
$model->setAttribute('tenant_id', $inherited);
return;
}
if (filled($model->getAttribute('tenant_id'))) {
return;
}
$current = app(TenantContext::class)->id();
if ($current !== null) {
$model->setAttribute('tenant_id', $current);
return;
}
if (app()->runningUnitTests() && ! app(TenantContext::class)->isRequired()) {
$model->setAttribute('tenant_id', Tenant::factory()->create([
'name' => 'Testmandant',
'slug' => 'test-'.Str::lower(Str::random(10)),
])->id);
return;
}
throw new TenantContextMissing($model::class);
});
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
/**
* The parent row wins, so a booking cannot land on a different landlord than its apartment.
*/
private static function tenantIdFromParent(Model $model): ?int
{
$parents = [
'property_id' => Property::class,
'booking_id' => Booking::class,
'channel_id' => Channel::class,
'site_id' => Site::class,
'guest_id' => Guest::class,
];
foreach ($parents as $column => $class) {
$id = $model->getAttribute($column);
if (! $id) {
continue;
}
$tenantId = $class::withoutGlobalScope('tenant')->whereKey($id)->value('tenant_id');
if ($tenantId !== null) {
return (int) $tenantId;
}
}
return null;
}
}
+5 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
@@ -9,4 +10,7 @@
* Value of an editable website text; the available keys are defined in config/content.php.
*/
#[Fillable(['key', 'value'])]
class ContentBlock extends Model {}
class ContentBlock extends Model
{
use BelongsToTenant;
}
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\ExtraPricing;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\ExtraFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -18,7 +19,7 @@
class Extra extends Model
{
/** @use HasFactory<ExtraFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\FaqFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -13,7 +14,7 @@
class Faq extends Model
{
/** @use HasFactory<FaqFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\FloorPlanFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Collection;
/**
* Floor plan of an apartment: a picture (rendering or scan) from the website photos and the rooms drawn
* on it. Room corners are stored in percent of the picture, so the areas fit every picture size.
*
* @property list<array{id?: string, name?: string, description?: string, hint?: string, points?: string, photo_ids?: list<int|string>, amenity_ids?: list<int|string>, is_visible?: bool}>|null $rooms
*/
#[Fillable(['property_id', 'photo_id', 'rooms'])]
class FloorPlan extends Model
{
/** @use HasFactory<FloorPlanFactory> */
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'rooms' => 'array',
];
}
/**
* @return BelongsTo<Property, $this>
*/
public function property(): BelongsTo
{
return $this->belongsTo(Property::class);
}
/**
* @return BelongsTo<Photo, $this>
*/
public function photo(): BelongsTo
{
return $this->belongsTo(Photo::class);
}
/**
* Rooms shown on the website: visible and with an area of at least three corners.
*
* @return Collection<int, array<string, mixed>>
*/
public function visibleRooms(): Collection
{
return collect($this->rooms ?? [])
->filter(fn (array $room): bool => ($room['is_visible'] ?? true) && filled($room['name'] ?? null) && count(self::points($room['points'] ?? null)) >= 3)
->values();
}
/**
* Parses "x,y x,y …" (percent) into points, ignoring anything outside 0–100.
*
* @return list<array{float, float}>
*/
public static function points(?string $points): array
{
$parsed = [];
foreach (preg_split('/\s+/', trim((string) $points)) ?: [] as $pair) {
if (preg_match('/^(\d{1,3}(?:\.\d+)?),(\d{1,3}(?:\.\d+)?)$/', $pair, $match) && (float) $match[1] <= 100 && (float) $match[2] <= 100) {
$parsed[] = [(float) $match[1], (float) $match[2]];
}
}
return $parsed;
}
}
+10 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\GuestFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -17,7 +18,7 @@
class Guest extends Model
{
/** @use HasFactory<GuestFactory> */
use HasFactory, Notifiable;
use BelongsToTenant, HasFactory, Notifiable;
/**
* Get the attributes that should be cast.
@@ -96,4 +97,12 @@ public function anonymize(): void
])->save();
});
}
/**
* The website of this guest's landlord, regardless of which landlord is current.
*/
public function website(): ?Site
{
return $this->tenant?->sites()->withoutGlobalScope('tenant')->orderByDesc('is_default')->orderBy('id')->first();
}
}
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\NoticeTone;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\NoticeFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -17,7 +18,7 @@
class Notice extends Model
{
/** @use HasFactory<NoticeFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\PageFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -18,7 +19,7 @@
class Page extends Model
{
/** @use HasFactory<PageFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
public const HOME = 'start';
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\PaymentMethod;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\PaymentFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,7 +17,7 @@
class Payment extends Model
{
/** @use HasFactory<PaymentFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+4 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\PhotoCategory;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\PhotoFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -22,7 +23,7 @@
class Photo extends Model implements HasMedia
{
/** @use HasFactory<PhotoFactory> */
use HasFactory, InteractsWithMedia;
use BelongsToTenant, HasFactory, InteractsWithMedia;
public const COLLECTION = 'image';
@@ -44,7 +45,9 @@ protected function casts(): array
public function registerMediaCollections(): void
{
// Website photos are public files; the app's default disk (FILESYSTEM_DISK=local) is private.
$this->addMediaCollection(self::COLLECTION)
->useDisk('public')
->singleFile()
->acceptsMimeTypes(['image/jpeg', 'image/png', 'image/webp']);
}
+3
View File
@@ -4,6 +4,7 @@
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -15,6 +16,8 @@
#[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
{
use BelongsToTenant;
/**
* Get the attributes that should be cast.
*
+20 -1
View File
@@ -2,12 +2,15 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Carbon\CarbonImmutable;
use Database\Factories\PropertyFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
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 rentable holiday apartment. All money amounts are stored in euro cents.
@@ -36,7 +39,7 @@
class Property extends Model
{
/** @use HasFactory<PropertyFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
@@ -68,6 +71,14 @@ protected function casts(): array
/**
* @return HasMany<Season, $this>
*/
/**
* @return BelongsTo<Site, $this>
*/
public function site(): BelongsTo
{
return $this->belongsTo(Site::class);
}
public function seasons(): HasMany
{
return $this->hasMany(Season::class)->orderBy('starts_on');
@@ -105,6 +116,14 @@ public function amenities(): HasMany
return $this->hasMany(Amenity::class)->orderBy('sort_order');
}
/**
* @return HasOne<FloorPlan, $this>
*/
public function floorPlan(): HasOne
{
return $this->hasOne(FloorPlan::class);
}
/**
* @return HasMany<SpecialOffer, $this>
*/
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\ReviewStatus;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\ReviewFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -38,7 +39,7 @@
class Review extends Model
{
/** @use HasFactory<ReviewFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/** Rating categories besides the overall rating, with their German labels. */
public const CATEGORIES = [
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Carbon\CarbonInterface;
use Database\Factories\SeasonFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -19,7 +20,7 @@
class Season extends Model
{
/** @use HasFactory<SeasonFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+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;
/**
* One use of a service by a landlord. Nothing writes usages yet because no service calls out.
*/
#[Fillable(['tenant_id', 'service', 'quantity', 'used_at'])]
class ServiceUsage extends Model
{
public $timestamps = false;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'used_at' => 'datetime',
];
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
}
-12
View File
@@ -1,12 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
/**
* One operational setting (key → value), read through App\Support\Settings.
*/
#[Fillable(['key', 'value'])]
class Setting extends Model {}
+99 -1
View File
@@ -2,12 +2,16 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Carbon\CarbonInterface;
use Database\Factories\SiteFactory;
use DateInterval;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\URL;
/**
* A website: domain, theme with its settings, pages and appearances, and the properties it shows.
@@ -17,7 +21,14 @@
class Site extends Model
{
/** @use HasFactory<SiteFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
protected static function booted(): void
{
static::saved(function (Site $site): void {
$site->syncDomainHost();
});
}
/**
* Get the attributes that should be cast.
@@ -32,6 +43,93 @@ protected function casts(): array
];
}
/**
* @return HasMany<SiteDomain, $this>
*/
public function domains(): HasMany
{
return $this->hasMany(SiteDomain::class);
}
/**
* Scheme and host for guest links. Empty while the website has no hostname yet.
*/
public function origin(): ?string
{
$host = $this->domains()->value('host') ?: $this->domain;
if (! is_string($host) || $host === '') {
return null;
}
$scheme = in_array($host, ['localhost', '127.0.0.1'], true) ? 'http' : 'https';
return $scheme.'://'.$host;
}
/**
* @param array<string, mixed> $parameters
*/
public function temporarySignedRoute(string $name, DateTimeInterface|DateInterval|int $expiration, array $parameters = []): string
{
return $this->withOrigin(fn (): string => URL::temporarySignedRoute($name, $expiration, $parameters));
}
public function signedRoute(string $name, mixed $parameters = []): string
{
return $this->withOrigin(fn (): string => URL::signedRoute($name, $parameters));
}
/**
* Keep the single domain field and the host table on the same hostname.
*/
public function syncDomainHost(): void
{
if (! $this->wasRecentlyCreated && ! $this->wasChanged('domain')) {
return;
}
$previous = $this->getOriginal('domain');
if (is_string($previous) && $previous !== '' && $previous !== $this->domain) {
$this->domains()->where('host', mb_strtolower($previous))->delete();
}
if (! is_string($this->domain) || $this->domain === '') {
return;
}
SiteDomain::query()->updateOrCreate(
['host' => mb_strtolower($this->domain)],
['site_id' => $this->id],
);
}
/**
* @param callable(): string $callback
*/
private function withOrigin(callable $callback): string
{
$origin = $this->origin();
if ($origin === null) {
return $callback();
}
$generator = app('url');
$previousRoot = (fn () => $this->forcedRoot)->call($generator);
$previousScheme = (fn () => $this->forceScheme)->call($generator);
URL::forceRootUrl($origin);
URL::forceScheme(parse_url($origin, PHP_URL_SCHEME) ?: 'https');
try {
return $callback();
} finally {
URL::forceRootUrl($previousRoot);
URL::forceScheme(is_string($previousScheme) ? strstr($previousScheme, ':', true) : null);
}
}
/**
* @return HasMany<Page, $this>
*/
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One hostname of a website. A host belongs to exactly one website.
*/
#[Fillable(['site_id', 'host'])]
class SiteDomain extends Model
{
/**
* Turns what someone typed into a bare hostname: "https://WWW.Example.de/" becomes "www.example.de".
* Returns an empty string when nothing usable is left, so callers can skip it.
*/
public static function normalise(?string $value): string
{
$host = mb_strtolower(trim((string) $value));
$host = (string) preg_replace('~^[a-z]+://~', '', $host);
$host = (string) preg_replace('~[/?#].*$~', '', $host);
return trim($host, '.');
}
/**
* @return BelongsTo<Site, $this>
*/
public function site(): BelongsTo
{
return $this->belongsTo(Site::class);
}
}
+2 -1
View File
@@ -4,6 +4,7 @@
use App\Enums\DiscountType;
use App\Enums\OfferKind;
use App\Models\Concerns\BelongsToTenant;
use App\Pricing\StayRequest;
use App\Support\Money;
use Carbon\CarbonImmutable;
@@ -48,7 +49,7 @@
class SpecialOffer extends Model
{
/** @use HasFactory<SpecialOfferFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace App\Models;
use App\Support\Settings;
use App\Tenancy\TenantDefaults;
use Database\Factories\TenantFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* A landlord. Owns websites, apartments, guests, bookings and settings. One account can belong
* to several landlords; the operator is not a landlord.
*/
#[Fillable([
'name', 'slug', 'is_active',
'owner_name', 'owner_street', 'owner_city', 'owner_phone', 'contact_email', 'notification_emails',
'sender_name', 'sender_email',
'bank_account_holder', 'bank_iban', 'bank_bic', 'bank_name', 'tax_note',
'operating_mode', 'test_recipient',
'deposit_due_days', 'review_request_after_days', 'guest_retention_years', 'retention_inquiry_months',
'retention_portal_email_excerpt_days', 'retention_attribution_months',
'spam_min_seconds', 'spam_per_ip_per_hour', 'spam_per_email_per_day', 'spam_open_requests_per_email', 'spam_max_links',
'channel_stale_after_minutes', 'channel_task_reminder_after_minutes',
])]
class Tenant extends Model
{
/** @use HasFactory<TenantFactory> */
use HasFactory;
/**
* The landlord the existing single-website data belongs to.
*/
public static function stommer(): self
{
return static::query()->firstOrCreate(
['slug' => 'stommer'],
['name' => 'Stommer'] + TenantDefaults::forLegacyLandlord(encryptBank: false),
);
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_active' => 'boolean',
'bank_account_holder' => 'encrypted',
'bank_iban' => 'encrypted',
'bank_bic' => 'encrypted',
'bank_name' => 'encrypted',
'tax_note' => 'encrypted',
];
}
/**
* @return HasMany<Site, $this>
*/
public function sites(): HasMany
{
return $this->hasMany(Site::class);
}
/**
* @return HasMany<Property, $this>
*/
public function properties(): HasMany
{
return $this->hasMany(Property::class);
}
/**
* @return HasMany<TenantService, $this>
*/
public function services(): HasMany
{
return $this->hasMany(TenantService::class);
}
/**
* @return HasMany<ServiceUsage, $this>
*/
public function serviceUsages(): HasMany
{
return $this->hasMany(ServiceUsage::class);
}
public function isLive(): bool
{
return $this->operating_mode === 'live';
}
/**
* Notification addresses of this landlord.
*
* @return list<string>
*/
public function notificationRecipients(): array
{
return Settings::addressList($this->notification_emails);
}
/**
* @return BelongsToMany<User, $this>
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class)->withPivot('role')->withTimestamps();
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Written when an operator opens a landlord's admin. Support access stays visible.
*/
#[Fillable(['tenant_id', 'user_id', 'created_at'])]
class TenantAccessLog extends Model
{
public $timestamps = false;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'created_at' => 'datetime',
];
}
protected static function booted(): void
{
static::creating(function (TenantAccessLog $log): void {
$log->created_at ??= now();
});
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A service the operator switched on for a landlord. The own API key is optional and stored encrypted;
* an empty key means that the operator's key applies (no service calls it yet).
*/
#[Fillable(['tenant_id', 'service', 'is_enabled', 'api_key'])]
class TenantService extends Model
{
/** @var list<string> */
protected $hidden = ['api_key'];
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_enabled' => 'boolean',
'api_key' => 'encrypted',
];
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
}
+169 -3
View File
@@ -5,6 +5,7 @@
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Enums\AdminMode;
use App\Enums\UserRole;
use App\Tenancy\TenantContext;
use Database\Factories\UserFactory;
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthentication;
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthenticationRecovery;
@@ -15,6 +16,7 @@
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
@@ -25,12 +27,24 @@ class User extends Authenticatable implements FilamentUser, HasAppAuthentication
/** @use HasFactory<UserFactory> */
use HasFactory, InteractsWithAppAuthentication, InteractsWithAppAuthenticationRecovery, Notifiable;
protected static function booted(): void
{
static::saved(function (User $user): void {
$user->attachCurrentRole();
});
}
/**
* Accounts are created by administrators only; an account without a role has no access.
* The operator panel is only for operators. The landlord admin needs a role there, or the operator flag.
* Password and two-factor belong to the account and are not a per-landlord setting.
*/
public function canAccessPanel(Panel $panel): bool
{
return $this->role !== null;
if ($panel->getId() === 'operator') {
return (bool) $this->is_operator;
}
return $this->currentRole() !== null || (bool) $this->is_operator;
}
/**
@@ -43,7 +57,158 @@ public function adminMode(): AdminMode
public function hasRole(UserRole ...$roles): bool
{
return in_array($this->role, $roles, true);
return in_array($this->currentRole(), $roles, true);
}
/**
* Role inside the landlord that is current. The operator acts as administrator of whichever landlord is open.
* With exactly one landlord, the old account role still applies until a membership exists.
*/
public function currentRole(): ?UserRole
{
$tenantId = app(TenantContext::class)->id();
if ($tenantId !== null) {
if ($this->is_operator) {
return UserRole::Admin;
}
$role = $this->roleOn($tenantId);
if ($role !== null) {
return $role;
}
if ($this->role !== null && Tenant::query()->count() === 1) {
return $this->role;
}
return null;
}
if ($this->role !== null) {
return $this->role;
}
if ($this->is_operator) {
return UserRole::Admin;
}
$memberships = $this->tenants()->get();
if ($memberships->count() === 1) {
return $this->roleFromPivot($memberships->first()?->pivot?->role);
}
return null;
}
public function roleOn(int $tenantId): ?UserRole
{
$membership = $this->tenants()->where('tenants.id', $tenantId)->first();
return $this->roleFromPivot($membership?->pivot?->role);
}
/**
* Copy the account role onto the current landlord. Does nothing without a role or a landlord.
*/
public function attachCurrentRole(?Tenant $tenant = null): void
{
if ($this->role === null) {
return;
}
$tenant ??= app(TenantContext::class)->get();
if ($tenant === null) {
return;
}
$alreadyMember = $this->tenants()->where('tenants.id', $tenant->id)->exists();
if ($alreadyMember) {
if ($this->wasChanged('role')) {
$this->tenants()->updateExistingPivot($tenant->id, ['role' => $this->role->value]);
}
return;
}
$this->tenants()->attach($tenant->id, ['role' => $this->role->value]);
}
/**
* Password and two-factor stay on the account. A landlord admin may reset them only when the
* account belongs to no other landlord. Otherwise only the operator may.
*/
public function mayResetCredentials(?User $other): bool
{
if ($this->is_operator) {
return true;
}
if (! $this->hasRole(UserRole::Admin)) {
return false;
}
if ($other === null) {
return true;
}
return $other->tenants()->count() < 2;
}
/**
* Another landlord this account belongs to, when that landlord has its own domain.
*/
public function otherTenantAdminUrl(): ?string
{
$current = app(TenantContext::class)->id();
$other = $this->tenants()->where('tenants.id', '!=', $current)->first();
if ($other === null) {
return null;
}
$domain = $other->sites()->withoutGlobalScope('tenant')->whereNotNull('domain')->value('domain');
if (! is_string($domain) || $domain === '') {
return null;
}
return 'https://'.$domain.'/admin';
}
public function showsTenantSwitch(): bool
{
return $this->otherTenantAdminUrl() !== null;
}
public function revokeCurrentTenant(): void
{
$tenantId = app(TenantContext::class)->id();
if ($tenantId !== null) {
$this->tenants()->detach($tenantId);
}
}
/**
* @return BelongsToMany<Tenant, $this>
*/
public function tenants(): BelongsToMany
{
return $this->belongsToMany(Tenant::class)->withPivot('role')->withTimestamps();
}
private function roleFromPivot(mixed $role): ?UserRole
{
if ($role instanceof UserRole) {
return $role;
}
return is_string($role) ? UserRole::tryFrom($role) : null;
}
/**
@@ -58,6 +223,7 @@ protected function casts(): array
'password' => 'hashed',
'role' => UserRole::class,
'admin_mode' => AdminMode::class,
'is_operator' => 'boolean',
];
}
}
+7 -1
View File
@@ -47,6 +47,12 @@ private function occupies(BookingStatus|string|null $status): bool
private function tasks(Booking $booking, ChannelTaskAction $action): void
{
$this->createChannelTasks->handle($booking->property, $booking->arrival, $booking->departure, $action, "Buchung {$booking->reference}");
$property = $booking->property()->withoutGlobalScope('tenant')->first();
if ($property === null) {
return;
}
$this->createChannelTasks->handle($property, $booking->arrival, $booking->departure, $action, "Buchung {$booking->reference}");
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class AmenityPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class AppearancePolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class BlockedPeriodPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Bookings;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class BookingPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Bookings;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class ChannelTaskPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Channels;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class FaqPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Policies;
use App\Enums\Permission;
class FloorPlanPolicy extends RolePolicy
{
protected function permission(): Permission
{
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class GuestPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Guests;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class NoticePolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class PagePolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class PhotoPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class PortalEmailPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Channels;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class PropertyPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Properties;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class ReviewPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals, UserRole::Content];
return Permission::Reviews;
}
}
+15 -7
View File
@@ -2,18 +2,17 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
use App\Models\User;
use App\Tenancy\TenantFeatures;
/**
* Grants every ability to the roles listed in roles(). Administrators always have access.
* Grants every ability that the current membership includes. The operator counts as administrator
* of the landlord that is open. A new role is added on UserRole, not in each policy.
*/
abstract class RolePolicy
{
/**
* @return list<UserRole>
*/
abstract protected function roles(): array;
abstract protected function permission(): Permission;
public function viewAny(User $user): bool
{
@@ -50,8 +49,17 @@ public function reorder(User $user): bool
return $this->allows($user);
}
/**
* Both questions, in one place: the role says what this user may do, TenantFeatures says what the
* landlord has unlocked at all. An administrator of a landlord without the portal services does not
* reach the portal screens either – no role grants what the landlord does not have.
*/
protected function allows(User $user): bool
{
return $user->hasRole(UserRole::Admin, ...$this->roles());
if (! $user->currentRole()?->grants($this->permission())) {
return false;
}
return app(TenantFeatures::class)->permits($this->permission());
}
}
+4 -2
View File
@@ -2,10 +2,12 @@
namespace App\Policies;
use App\Enums\Permission;
class SitePolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [];
return Permission::Settings;
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Policies;
use App\Models\Tenant;
use App\Models\User;
/**
* Landlords are created and suspended by the operator. Deleting one is a later, separate step.
*/
class TenantPolicy
{
public function viewAny(User $user): bool
{
return $user->is_operator;
}
public function view(User $user, Tenant $tenant): bool
{
return $user->is_operator;
}
public function create(User $user): bool
{
return $user->is_operator;
}
public function update(User $user, Tenant $tenant): bool
{
return $user->is_operator;
}
public function delete(User $user, Tenant $tenant): bool
{
return false;
}
public function deleteAny(User $user): bool
{
return false;
}
}
+10 -4
View File
@@ -2,20 +2,26 @@
namespace App\Policies;
use App\Enums\Permission;
use App\Models\User;
/**
* Only administrators manage accounts; nobody can delete their own account.
* Only administrators of the current landlord manage accounts. A shared account is detached, not deleted,
* and nobody can delete their own account.
*/
class UserPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [];
return Permission::Users;
}
public function delete(User $user, ?User $model = null): bool
{
return $this->allows($user) && ! $user->is($model);
if (! $this->allows($user) || $user->is($model)) {
return false;
}
return $model === null || $model->tenants()->count() < 2;
}
}
+12 -5
View File
@@ -2,12 +2,14 @@
namespace App\Providers;
use App\Support\Settings;
use App\Support\StripImageMetadata;
use App\Tenancy\TenantConfig;
use App\Tenancy\TenantContext;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
use Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAddedEvent;
use Throwable;
class AppServiceProvider extends ServiceProvider
{
@@ -16,7 +18,8 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
//
$this->app->singleton(TenantContext::class);
$this->app->singleton(TenantConfig::class);
}
/**
@@ -24,9 +27,13 @@ public function register(): void
*/
public function boot(): void
{
// Test mode (System › Betrieb, default until switched live): every e-mail goes to the test recipient only.
Settings::applyAddressOverrides();
Settings::applyMailRouting();
// Operating data of the landlord (addresses, periods) and test mode (every e-mail goes to the test
// recipient only, until switched live). Console and boot know the landlord only if there is exactly one.
try {
$this->app->make(TenantConfig::class)->refresh();
} catch (Throwable) {
// no database yet (package discovery, first install)
}
// Photos: remove metadata (GPS position, camera data) from uploaded originals, which stay downloadable.
Event::listen(MediaHasBeenAddedEvent::class, fn (MediaHasBeenAddedEvent $event) => StripImageMetadata::strip($event->media));
@@ -3,6 +3,7 @@
namespace App\Providers\Filament;
use App\Enums\AdminMode;
use App\Http\Middleware\ResolveTheme;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Auth\MultiFactor\App\AppAuthentication;
@@ -49,6 +50,11 @@ public function panel(Panel $panel): Panel
isRequired: true,
)
->userMenuItems([
'tenant-switch' => Action::make('switchTenant')
->label('Anderer Mandant')
->icon(Heroicon::OutlinedArrowsRightLeft)
->visible(fn (): bool => self::currentUser()?->showsTenantSwitch() ?? false)
->url(fn (): ?string => self::currentUser()?->otherTenantAdminUrl()),
'admin-mode' => Action::make('switchAdminMode')
->label(fn (): string => (self::currentUser()?->adminMode() ?? AdminMode::Expert)->other()->switchLabel())
->icon(fn (): Heroicon => self::currentUser()?->adminMode() === AdminMode::Simple ? Heroicon::OutlinedAdjustmentsHorizontal : Heroicon::OutlinedSparkles)
@@ -79,6 +85,7 @@ public function panel(Panel $panel): Panel
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
ResolveTheme::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
PreventRequestForgery::class,
@@ -0,0 +1,65 @@
<?php
namespace App\Providers\Filament;
use App\Filament\Operator\Pages\SystemOverview;
use App\Http\Middleware\ResolveTheme;
use Filament\Auth\MultiFactor\App\AppAuthentication;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Pages\Dashboard;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\Widgets\AccountWidget;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
class OperatorPanelProvider extends PanelProvider
{
public function panel(Panel $panel): Panel
{
return $panel
->id('operator')
->path('betreiber')
->login()
->profile(isSimple: false)
->multiFactorAuthentication(
[AppAuthentication::make()->brandName('FeWo Stommer')->recoverable()],
isRequired: true,
)
->brandName('Betreiber')
->colors([
'primary' => Color::Slate,
])
->discoverResources(in: app_path('Filament/Operator'), for: 'App\Filament\Operator')
->pages([
Dashboard::class,
SystemOverview::class,
])
->widgets([
AccountWidget::class,
])
->middleware([
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
ResolveTheme::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
PreventRequestForgery::class,
SubstituteBindings::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
])
->authMiddleware([
Authenticate::class,
]);
}
}
+14 -2
View File
@@ -4,6 +4,7 @@
use App\Models\ContentBlock;
use App\Models\Photo;
use App\Tenancy\TenantContext;
use Filament\Forms\Components\RichEditor\RichContentRenderer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\HtmlString;
@@ -54,7 +55,7 @@ public static function save(array $values): void
ContentBlock::updateOrCreate(['key' => $key], ['value' => $value]);
}
Cache::forget(self::CACHE_KEY);
Cache::forget(self::cacheKey());
}
/**
@@ -84,6 +85,17 @@ private static function definition(string $key): array
*/
private static function stored(): array
{
return Cache::rememberForever(self::CACHE_KEY, fn (): array => ContentBlock::pluck('value', 'key')->all());
return Cache::rememberForever(self::cacheKey(), fn (): array => ContentBlock::pluck('value', 'key')->all());
}
/**
* Stored texts are cached per landlord. Without a current landlord the key stays the historical one,
* which only happens before a request has chosen a website.
*/
private static function cacheKey(): string
{
$tenantId = app(TenantContext::class)->id();
return $tenantId === null ? self::CACHE_KEY : self::CACHE_KEY.'.'.$tenantId;
}
}
+24 -76
View File
@@ -2,72 +2,37 @@
namespace App\Support;
use App\Models\Setting;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
use Throwable;
use App\Models\Tenant;
use App\Tenancy\TenantConfig;
/**
* Operational settings from the admin (System › Betrieb), cached. The most important one: the operating mode.
* Operating mode and addresses of the current landlord (admin page System › Betrieb, stored on the landlord).
* In **test mode** (the default until the site is switched live) every e-mail goes to the test recipient only,
* whatever address was entered on the website.
* whatever address was entered on the website. Without any landlord the .env values apply.
*/
class Settings
{
public const MODE = 'operations.mode';
public const TEST_RECIPIENT = 'operations.test_recipient';
/** Comma-separated: who is informed about new requests, answered offers, portal events … */
public const NOTIFICATION_RECIPIENTS = 'addresses.notifications';
/** Contact address shown on the website and in the contract; reply-to of guest mails. */
public const CONTACT_EMAIL = 'addresses.contact';
public const SENDER_EMAIL = 'addresses.sender_email';
public const SENDER_NAME = 'addresses.sender_name';
public const MODE_TEST = 'test';
public const MODE_LIVE = 'live';
private const CACHE_KEY = 'settings.all';
public static function get(string $key, ?string $default = null): ?string
{
try {
$values = Cache::rememberForever(self::CACHE_KEY, fn (): array => Setting::query()->pluck('value', 'key')->all());
} catch (Throwable) {
return $default; // e.g. before the migrations ran
}
return $values[$key] ?? $default;
}
/**
* @param array<string, ?string> $values
* The landlord of the context, else the only landlord.
*/
public static function save(array $values): void
public static function tenant(): ?Tenant
{
foreach ($values as $key => $value) {
Setting::query()->updateOrCreate(['key' => $key], ['value' => $value]);
}
Cache::forget(self::CACHE_KEY);
self::applyAddressOverrides();
self::applyMailRouting();
return app(TenantConfig::class)->effectiveTenant();
}
/**
* The recipients of internal notifications (admin setting, else FEWO_NOTIFICATION_EMAIL).
* The recipients of internal notifications (the landlord's setting, else FEWO_NOTIFICATION_EMAIL while no landlord is known).
*
* @return list<string>
*/
public static function notificationRecipients(): array
{
return self::addressList(self::get(self::NOTIFICATION_RECIPIENTS) ?: (string) config('fewo.notification_email'));
return self::tenant()?->notificationRecipients()
?: self::addressList((string) config('fewo.notification_email'));
}
/**
@@ -83,25 +48,9 @@ public static function addressList(?string $value): array
));
}
/**
* Admin settings for the contact address and the sender override the .env values for this request.
*/
public static function applyAddressOverrides(): void
{
$overrides = array_filter([
'fewo.owner.email' => self::get(self::CONTACT_EMAIL),
'mail.from.address' => self::get(self::SENDER_EMAIL),
'mail.from.name' => self::get(self::SENDER_NAME),
]);
if ($overrides !== []) {
config($overrides);
}
}
public static function isLive(): bool
{
return self::get(self::MODE, self::MODE_TEST) === self::MODE_LIVE;
return (self::tenant()?->operating_mode ?? self::MODE_TEST) === self::MODE_LIVE;
}
/**
@@ -109,34 +58,33 @@ public static function isLive(): bool
* FEWO_MAIL_REDIRECT_TO in .env always wins (hard override for test servers).
*/
public static function mailRedirect(): ?string
{
return self::mailRedirectFor(self::tenant());
}
public static function mailRedirectFor(?Tenant $tenant): ?string
{
$override = config('fewo.mail_redirect_to');
if (filled($override)) {
return (string) $override;
}
if (self::isLive()) {
if ($tenant?->isLive()) {
return null;
}
return self::get(self::TEST_RECIPIENT) ?: (self::notificationRecipients()[0] ?? null);
// A landlord without any address of their own must not fall through to normal delivery: the operator's
// address catches the mails until the landlord has entered their own.
$recipients = $tenant?->notificationRecipients() ?: self::addressList((string) config('fewo.notification_email'));
return $tenant?->test_recipient ?: ($recipients[0] ?? null);
}
/**
* Applies the redirect to the mailer; called at boot and after saving.
* Applies the redirect of the current landlord to the mailer; called after saving.
*/
public static function applyMailRouting(): void
{
$manager = Mail::getFacadeRoot();
if (! $manager instanceof MailManager) {
return; // Mail::fake() in tests
}
$redirect = self::mailRedirect();
$manager->purge();
if (filled($redirect)) {
$manager->alwaysTo($redirect);
}
app(TenantConfig::class)->refresh();
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Tenancy;
use Illuminate\Support\Facades\DB;
/**
* Points every existing row at the landlord "Stommer". Used once, when tenancy is introduced
* on a database that already has the single-landlord data. Fresh databases have nothing to assign.
*/
class AssignLegacyData
{
/**
* Tables that gain a tenant_id. Order is irrelevant; nothing is deleted.
*
* @var list<string>
*/
public const TABLES = [
'sites',
'properties',
'guests',
'bookings',
'channels',
'portal_emails',
'photos',
'pages',
'appearances',
'notices',
'faqs',
'blocked_periods',
'amenities',
'reviews',
'channel_tasks',
'payments',
'seasons',
'extras',
'special_offers',
'channel_sync_logs',
'content_blocks',
];
public static function run(): void
{
$pending = false;
foreach (self::TABLES as $table) {
if (DB::table($table)->whereNull('tenant_id')->exists()) {
$pending = true;
break;
}
}
if (! $pending) {
return;
}
$tenantId = DB::table('tenants')->where('slug', 'stommer')->value('id');
if ($tenantId === null) {
$tenantId = DB::table('tenants')->insertGetId([
'name' => 'Stommer',
'slug' => 'stommer',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
]);
}
foreach (self::TABLES as $table) {
DB::table($table)->whereNull('tenant_id')->update(['tenant_id' => $tenantId]);
}
}
}
+215
View File
@@ -0,0 +1,215 @@
<?php
namespace App\Tenancy;
use App\Models\Tenant;
use App\Support\Settings;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* Lays the operating data of the current landlord over config('fewo.*') and the mail sender, so e-mails,
* contracts and theme views keep reading the same keys. The values from config/.env stay the baseline:
* infrastructure, the fallback while no landlord is known, and the limits a landlord may tighten but not exceed.
*/
class TenantConfig
{
/**
* Retention periods and bot protection: the landlord may be stricter, never more lax than the baseline.
* Fewer days/attempts is stricter.
*
* @var array<string, string>
*/
private const AT_MOST = [
'fewo.guest_retention_years' => 'guest_retention_years',
'fewo.retention.inquiry_months' => 'retention_inquiry_months',
'fewo.retention.portal_email_excerpt_days' => 'retention_portal_email_excerpt_days',
'fewo.retention.attribution_months' => 'retention_attribution_months',
'fewo.spam.per_ip_per_hour' => 'spam_per_ip_per_hour',
'fewo.spam.per_email_per_day' => 'spam_per_email_per_day',
'fewo.spam.open_requests_per_email' => 'spam_open_requests_per_email',
'fewo.spam.max_links' => 'spam_max_links',
];
/**
* The time trap works the other way round: a longer minimum time is stricter.
*
* @var array<string, string>
*/
private const AT_LEAST = [
'fewo.spam.min_seconds' => 'spam_min_seconds',
];
/**
* Values the landlord chooses freely; empty means the baseline.
*
* @var array<string, string>
*/
private const FREE = [
'fewo.deposit_due_days' => 'deposit_due_days',
'fewo.review_request_after_days' => 'review_request_after_days',
'fewo.channels.stale_after_minutes' => 'channel_stale_after_minutes',
'fewo.channels.task_reminder_after_minutes' => 'channel_task_reminder_after_minutes',
];
/**
* Data of the landlord: an empty value stays empty instead of falling back to another landlord's.
*
* @var array<string, string>
*/
private const OWNED = [
'fewo.owner.name' => 'owner_name',
'fewo.owner.street' => 'owner_street',
'fewo.owner.city' => 'owner_city',
'fewo.owner.phone' => 'owner_phone',
'fewo.owner.email' => 'contact_email',
'fewo.bank.account_holder' => 'bank_account_holder',
'fewo.bank.iban' => 'bank_iban',
'fewo.bank.bic' => 'bank_bic',
'fewo.bank.bank_name' => 'bank_name',
];
/** @var array<string, mixed>|null */
private ?array $baseline = null;
/**
* What this class wrote into the config last time. A key that now holds something else was changed from
* outside (a test, a command) – that value becomes the new baseline instead of being overwritten again.
*
* @var array<string, mixed>
*/
private array $written = [];
/**
* The landlord of the current context, else the only landlord there is (console, boot), else none.
*/
public function effectiveTenant(): ?Tenant
{
$current = app(TenantContext::class)->get();
if ($current !== null) {
return $current;
}
try {
$tenants = Tenant::query()->limit(2)->get();
} catch (Throwable) {
return null; // before the migrations ran
}
return $tenants->count() === 1 ? $tenants->first() : null;
}
/**
* Applies the effective landlord, or the baseline when there is none.
*/
public function refresh(): void
{
$this->apply($this->effectiveTenant());
}
public function apply(?Tenant $tenant): void
{
$baseline = $this->baseline();
$values = $baseline;
if ($tenant !== null && ! array_key_exists('owner_name', $tenant->getAttributes())) {
$tenant = null; // the migration that adds the columns has not run yet; the baseline stands
}
if ($tenant !== null) {
foreach (self::OWNED as $key => $column) {
$values[$key] = $tenant->{$column};
}
foreach (self::FREE as $key => $column) {
$values[$key] = $tenant->{$column} ?? $baseline[$key];
}
foreach (self::AT_MOST as $key => $column) {
$values[$key] = min($tenant->{$column} ?? $baseline[$key], $baseline[$key]);
}
foreach (self::AT_LEAST as $key => $column) {
$values[$key] = max($tenant->{$column} ?? $baseline[$key], $baseline[$key]);
}
$values['mail.from.address'] = $tenant->sender_email ?: $baseline['mail.from.address'];
$values['mail.from.name'] = $tenant->sender_name ?: $baseline['mail.from.name'];
}
config($values);
$this->written = $values;
$this->applyMailRouting($tenant);
}
/**
* The mailer sends everything to one address while the landlord is in test mode.
*/
public function applyMailRouting(?Tenant $tenant): void
{
$manager = Mail::getFacadeRoot();
if (! $manager instanceof MailManager) {
return; // Mail::fake() in tests
}
$manager->purge();
$redirect = Settings::mailRedirectFor($tenant);
if (filled($redirect)) {
$manager->alwaysTo($redirect);
}
}
/**
* The value of a config key as the installation configured it, before any landlord was laid over it.
*/
public function baselineValue(string $key): mixed
{
return $this->baseline()[$key] ?? config($key);
}
/**
* The highest value the landlord may enter for a column, or null when it is free.
*/
public function ceilingFor(string $column): ?int
{
$key = array_search($column, self::AT_MOST, true);
return $key === false ? null : (int) $this->baseline()[$key];
}
/**
* The lowest value the landlord may enter for a column, or null when it is free.
*/
public function floorFor(string $column): ?int
{
$key = array_search($column, self::AT_LEAST, true);
return $key === false ? null : (int) $this->baseline()[$key];
}
/**
* @return array<string, mixed>
*/
private function baseline(): array
{
$keys = [...array_keys(self::OWNED), ...array_keys(self::FREE), ...array_keys(self::AT_MOST), ...array_keys(self::AT_LEAST), 'mail.from.address', 'mail.from.name'];
if ($this->baseline === null) {
$this->baseline = array_combine($keys, array_map(fn (string $key): mixed => config($key), $keys));
return $this->baseline;
}
foreach ($keys as $key) {
if (array_key_exists($key, $this->written) && config($key) !== $this->written[$key]) {
$this->baseline[$key] = config($key);
}
}
return $this->baseline;
}
}
+79
View File
@@ -0,0 +1,79 @@
<?php
namespace App\Tenancy;
use App\Models\Tenant;
/**
* The landlord of the current request, job or command. Empty means "not chosen yet".
* While presence is required, a query on a tenant-owned model without a landlord fails closed.
*/
class TenantContext
{
private ?Tenant $tenant = null;
private bool $required = false;
public function set(Tenant $tenant): void
{
$this->tenant = $tenant;
$this->applyConfig();
}
public function forget(): void
{
$this->tenant = null;
$this->required = false;
$this->applyConfig();
}
public function get(): ?Tenant
{
return $this->tenant;
}
public function id(): ?int
{
return $this->tenant?->id;
}
public function requirePresence(bool $required = true): void
{
$this->required = $required;
}
public function isRequired(): bool
{
return $this->required;
}
/**
* Run a callback as $tenant, then restore whoever was current before.
*
* @template T
*
* @param callable(): T $callback
* @return T
*/
public function run(Tenant $tenant, callable $callback): mixed
{
$previous = $this->tenant;
$this->tenant = $tenant;
$this->applyConfig();
try {
return $callback();
} finally {
$this->tenant = $previous;
$this->applyConfig();
}
}
/**
* Operating data of the landlord (addresses, periods, bank) is overlaid on config('fewo.*').
*/
private function applyConfig(): void
{
app(TenantConfig::class)->refresh();
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Tenancy;
use RuntimeException;
/**
* A tenant-owned query or insert ran without a current landlord while one was required.
*/
class TenantContextMissing extends RuntimeException
{
public function __construct(string $model)
{
parent::__construct("No current tenant for [{$model}].");
}
}
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff. Show more