Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2e78446a8 | ||
|
|
03ad4667ac | ||
|
|
d9383cf3e5 | ||
|
|
e0e8c1d856 | ||
|
|
2f2aceb3bd | ||
|
|
2e3f2ca938 | ||
|
|
fd2a7f7ded | ||
|
|
220ec6bfdb | ||
|
|
afffa79289 | ||
|
|
f143a4f5f4 | ||
|
|
e6d4d89141 |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git merge *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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`.
|
||||
|
||||
@@ -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 = [];
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?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.
|
||||
*
|
||||
* Holds no Filament hooks; EditsTenantSetup calls these.
|
||||
*/
|
||||
trait EditsTenantServices
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function fillServices(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>
|
||||
*/
|
||||
private function takeServices(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,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
/**
|
||||
* Everything the operator sets up for a landlord that does not live in the tenants table itself:
|
||||
* the websites with their entry addresses, and the services that are unlocked.
|
||||
*/
|
||||
trait EditsTenantSetup
|
||||
{
|
||||
use EditsTenantServices;
|
||||
use EditsTenantWebsites;
|
||||
|
||||
/** @var array<string, array<string, mixed>> */
|
||||
public array $services = [];
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
public array $websites = [];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
return $this->fillWebsites($this->fillServices($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
return $this->takeWebsites($this->takeServices($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
return $this->takeWebsites($this->takeServices($data));
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
$this->saveServices();
|
||||
$this->saveWebsites();
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
$this->saveServices();
|
||||
$this->saveWebsites();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Models\SiteDomain;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* The websites of a landlord and the addresses they answer on. These belong to the operator: the webspace
|
||||
* and the hosting are the operator's, and a landlord must not be able to point an address at themselves.
|
||||
*
|
||||
* Wiring a new domain to this directory stays a manual step at the hoster. What is kept here is the other
|
||||
* half: which host belongs to which website, and through it to which landlord.
|
||||
*
|
||||
* Holds no Filament hooks; EditsTenantSetup calls these.
|
||||
*/
|
||||
trait EditsTenantWebsites
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function fillWebsites(array $data): array
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$data['websites'] = $tenant->sites()->withoutGlobalScope('tenant')->with('domains')->get()
|
||||
->map(fn (Site $site): array => [
|
||||
'id' => $site->id,
|
||||
'name' => $site->name,
|
||||
'hosts' => $site->domains->pluck('host')->all(),
|
||||
])
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function takeWebsites(array $data): array
|
||||
{
|
||||
$this->websites = is_array($data['websites'] ?? null) ? array_values($data['websites']) : [];
|
||||
|
||||
$this->normaliseWebsites();
|
||||
|
||||
unset($data['websites']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans the entered addresses and refuses what already belongs elsewhere, before anything is written.
|
||||
*/
|
||||
private function normaliseWebsites(): void
|
||||
{
|
||||
$seen = [];
|
||||
|
||||
foreach ($this->websites as $index => $website) {
|
||||
$hosts = [];
|
||||
|
||||
foreach ((array) ($website['hosts'] ?? []) as $host) {
|
||||
$host = SiteDomain::normalise(is_string($host) ? $host : null);
|
||||
|
||||
if ($host === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($host, $seen, true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'data.websites' => 'Die Adresse '.$host.' ist mehrfach eingetragen.',
|
||||
]);
|
||||
}
|
||||
|
||||
$seen[] = $host;
|
||||
$hosts[] = $host;
|
||||
}
|
||||
|
||||
$this->websites[$index]['hosts'] = $hosts;
|
||||
}
|
||||
|
||||
$this->refuseForeignHosts($seen);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $hosts
|
||||
*/
|
||||
private function refuseForeignHosts(array $hosts): void
|
||||
{
|
||||
$ownIds = collect($this->websites)->pluck('id')->filter()->all();
|
||||
|
||||
$taken = SiteDomain::query()
|
||||
->whereIn('host', $hosts)
|
||||
->whereNotIn('site_id', $ownIds ?: [0])
|
||||
->pluck('host');
|
||||
|
||||
if ($taken->isNotEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'data.websites' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the websites. A website that is new gets an empty home page straight away, because a website
|
||||
* without one answers 404 and the landlord would have no way in.
|
||||
*/
|
||||
private function saveWebsites(): void
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
app(TenantContext::class)->run($tenant, function () use ($tenant): void {
|
||||
$keep = [];
|
||||
|
||||
foreach ($this->websites as $website) {
|
||||
$name = trim((string) ($website['name'] ?? ''));
|
||||
|
||||
if ($name === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hosts = (array) ($website['hosts'] ?? []);
|
||||
$site = $this->siteFor($tenant, $website['id'] ?? null, $name, $hosts);
|
||||
|
||||
$keep[] = $site->id;
|
||||
|
||||
$site->domains()->whereNotIn('host', $hosts ?: [''])->delete();
|
||||
|
||||
foreach ($hosts as $host) {
|
||||
SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]);
|
||||
}
|
||||
}
|
||||
|
||||
$tenant->sites()->whereNotIn('id', $keep ?: [0])->each(fn (Site $site) => $site->delete());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $hosts
|
||||
*/
|
||||
private function siteFor(Tenant $tenant, mixed $id, string $name, array $hosts): Site
|
||||
{
|
||||
$site = $id ? Site::query()->whereKey($id)->first() : null;
|
||||
|
||||
if ($site !== null) {
|
||||
$site->update(['name' => $name, 'domain' => $hosts[0] ?? null]);
|
||||
|
||||
return $site;
|
||||
}
|
||||
|
||||
$site = Site::query()->create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'name' => $name,
|
||||
'domain' => $hosts[0] ?? null,
|
||||
'is_default' => $tenant->sites()->count() === 0,
|
||||
'theme' => config('themes.base'),
|
||||
]);
|
||||
|
||||
Page::query()->create([
|
||||
'site_id' => $site->id,
|
||||
'slug' => Page::HOME,
|
||||
'title' => $name,
|
||||
'sections' => [],
|
||||
'is_published' => true,
|
||||
]);
|
||||
|
||||
return $site;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Pages;
|
||||
|
||||
use App\Support\SystemSettings;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Actions;
|
||||
use Filament\Schemas\Components\EmbeddedSchema;
|
||||
use Filament\Schemas\Components\Form;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
|
||||
/**
|
||||
* The settings of the whole installation. They are the baseline every landlord is bound by, and a
|
||||
* landlord's admin never reaches this page.
|
||||
*
|
||||
* Empty means: the value from the server's .env applies again. Database credentials and APP_KEY are not
|
||||
* here and cannot be – they are needed to open the database and to decrypt what is stored in it.
|
||||
*/
|
||||
class SystemSettingsPage extends Page
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsHorizontal;
|
||||
|
||||
protected static ?string $navigationLabel = 'Einstellungen';
|
||||
|
||||
protected static ?string $title = 'Systemweite Einstellungen';
|
||||
|
||||
protected static ?string $slug = 'einstellungen';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
/** @var array<string, mixed> */
|
||||
public array $data = [];
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->form->fill(collect(SystemSettings::EDITABLE)
|
||||
->mapWithKeys(fn (array $definition, string $key): array => [self::field($key) => SystemSettings::get($key)])
|
||||
->all());
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
$sections = collect(SystemSettings::EDITABLE)
|
||||
->groupBy(fn (array $definition): string => $definition[2], preserveKeys: true)
|
||||
->map(fn ($group, string $section) => Section::make($section)
|
||||
->columns(2)
|
||||
->schema($group->keys()->map(fn (string $key) => $this->field_($key))->all()));
|
||||
|
||||
return $schema
|
||||
->statePath('data')
|
||||
->components([
|
||||
Text::make('Leer lassen heißt: der Wert aus der .env des Servers gilt wieder. Datenbank-Zugang und APP_KEY stehen bewusst nicht hier – sie werden gebraucht, um die Datenbank überhaupt zu öffnen und das Gespeicherte zu entschlüsseln.'),
|
||||
...$sections->values()->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
Form::make([EmbeddedSchema::make('form')])
|
||||
->id('form')
|
||||
->livewireSubmitHandler('save')
|
||||
->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
|
||||
SystemSettings::save(collect(SystemSettings::EDITABLE)
|
||||
->mapWithKeys(fn (array $definition, string $key): array => [$key => $data[self::field($key)] ?? null])
|
||||
->all());
|
||||
|
||||
Notification::make()->title('Gespeichert')->success()->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Config keys contain dots, which Filament would read as nesting.
|
||||
*/
|
||||
private static function field(string $key): string
|
||||
{
|
||||
return str_replace('.', '__', $key);
|
||||
}
|
||||
|
||||
private function field_(string $key): TextInput|Select
|
||||
{
|
||||
[$label, $kind, , $help] = SystemSettings::EDITABLE[$key];
|
||||
$name = self::field($key);
|
||||
|
||||
if ($kind === 'mailer') {
|
||||
return Select::make($name)
|
||||
->label($label)
|
||||
->helperText($help)
|
||||
->options(['smtp' => 'SMTP (echter Versand)', 'log' => 'Nur Logdatei (kein Versand)', 'array' => 'Verwerfen (nur für Tests)']);
|
||||
}
|
||||
|
||||
$field = TextInput::make($name)->label($label)->helperText($help);
|
||||
|
||||
return match ($kind) {
|
||||
'int' => $field->numeric()->integer()->minValue(0),
|
||||
'secret' => $field->password()->revealable()->autocomplete(false),
|
||||
default => $field,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
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;
|
||||
@@ -10,14 +11,21 @@
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
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
|
||||
{
|
||||
@@ -48,9 +56,50 @@ public static function form(Schema $schema): Schema
|
||||
->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),
|
||||
->label('Zugang freigeschaltet')
|
||||
->helperText('Ausgeschaltet sehen Besucher statt der Webseite nur den Hinweis unten. Der Betreiber kommt weiter hinein.')
|
||||
->default(true)
|
||||
->live(),
|
||||
Textarea::make('suspended_message')
|
||||
->label('Hinweis bei gesperrtem Zugang')
|
||||
->placeholder('Diese Webseite ist zurzeit nicht erreichbar. Bitte versuchen Sie es später noch einmal.')
|
||||
->helperText('Leer = der Standardtext. Wird mit Status 503 ausgeliefert, damit Suchmaschinen die Seite nicht aus dem Index werfen.')
|
||||
->rows(2)
|
||||
->columnSpanFull(),
|
||||
Section::make('Einsprungsadressen')
|
||||
->description('Unter welchen Adressen dieser Mandant antwortet. Die Adresse muss zusätzlich beim Hoster einmalig auf dieses Verzeichnis gelegt werden – das passiert nicht hier. Ab dem zweiten Mandanten bekommt jede nicht eingetragene Adresse eine Fehlerseite.')
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
Repeater::make('websites')
|
||||
->label('Websites')
|
||||
->addActionLabel('Weitere Website')
|
||||
->defaultItems(1)
|
||||
->itemLabel(fn (array $state): ?string => $state['name'] ?? null)
|
||||
->schema([
|
||||
Hidden::make('id'),
|
||||
TextInput::make('name')
|
||||
->label('Name der Website')
|
||||
->required()
|
||||
->maxLength(120),
|
||||
TagsInput::make('hosts')
|
||||
->label('Adressen')
|
||||
->placeholder('beispiel.de')
|
||||
->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Die erste gilt als Hauptadresse und steht in Links an Gäste.')
|
||||
->nestedRecursiveRules(['string', 'max:190']),
|
||||
]),
|
||||
]),
|
||||
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.'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -60,6 +109,10 @@ public static function table(Table $table): 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([
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\Concerns\EditsTenantSetup;
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateTenant extends CreateRecord
|
||||
{
|
||||
use EditsTenantSetup;
|
||||
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\Concerns\EditsTenantSetup;
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditTenant extends EditRecord
|
||||
{
|
||||
use EditsTenantSetup;
|
||||
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
|
||||
class ListTenants extends ListRecords
|
||||
{
|
||||
@@ -13,7 +14,9 @@ class ListTenants extends ListRecords
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
CreateAction::make()
|
||||
->label('Neuen Mandanten anlegen')
|
||||
->icon(Heroicon::OutlinedPlus),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Sites\Concerns;
|
||||
|
||||
use App\Models\Site;
|
||||
|
||||
/**
|
||||
* Shows the hostnames of a website in the landlord's admin. Read only: addresses are given out by the
|
||||
* operator, because every address also has to be wired to this directory at the hoster, and because a
|
||||
* landlord must not be able to point somebody else's address at their own website.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
$data['extra_hosts'] = $site->domains()
|
||||
->where('host', '!=', (string) $site->domain)
|
||||
->pluck('host')
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
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;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
|
||||
@@ -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,16 @@ public static function configure(Schema $schema): Schema
|
||||
->schema([
|
||||
TextInput::make('name')->label('Name')->required()->maxLength(120),
|
||||
TextInput::make('domain')
|
||||
->label('Domain')
|
||||
->placeholder('www.fewo-stommer.de')
|
||||
->helperText('Leer = Standard-Website, solange es nur diesen Mandanten gibt. Ab dem zweiten Mandanten antwortet nur eine eingetragene Domain.')
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(190),
|
||||
->label('Hauptadresse')
|
||||
->helperText('Steht in Links an Gäste. Adressen werden vom Betreiber vergeben, weil sie beim Hoster eingerichtet werden müssen.')
|
||||
->disabled()
|
||||
->dehydrated(false),
|
||||
TagsInput::make('extra_hosts')
|
||||
->label('Antwortet außerdem auf')
|
||||
->placeholder('keine weitere Adresse')
|
||||
->disabled()
|
||||
->dehydrated(false)
|
||||
->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(),
|
||||
|
||||
@@ -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"',
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\Site;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
@@ -9,6 +10,7 @@
|
||||
use App\Themes\ThemeFactory;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
@@ -36,15 +38,45 @@ public function handle(Request $request, Closure $next): Response
|
||||
|
||||
if ($tenant !== null) {
|
||||
if (! $tenant->is_active && ! $this->operatorMayPass($request)) {
|
||||
abort(404);
|
||||
return $this->suspended($tenant);
|
||||
}
|
||||
|
||||
$context->set($tenant);
|
||||
}
|
||||
|
||||
$this->useSiteOrigin($theme->site);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Links must carry the address the visitor came in on. AppServiceProvider forces APP_URL for every
|
||||
* generated URL, because on Strato the document root is a release folder; with one landlord that was
|
||||
* harmless, but a second website on its own domain would otherwise send every visitor to the first
|
||||
* landlord's host. The forced root stays – only its value becomes the website that was resolved.
|
||||
*/
|
||||
private function useSiteOrigin(Site $site): void
|
||||
{
|
||||
$origin = $site->exists ? $site->origin() : null;
|
||||
|
||||
if ($origin === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
URL::forceRootUrl($origin);
|
||||
URL::forceScheme(parse_url($origin, PHP_URL_SCHEME) ?: 'https');
|
||||
}
|
||||
|
||||
/**
|
||||
* What a visitor of a suspended landlord sees: a plain notice instead of a dead link.
|
||||
*/
|
||||
private function suspended(Tenant $tenant): Response
|
||||
{
|
||||
return response()->view('suspended', [
|
||||
'message' => $tenant->suspended_message ?: 'Diese Webseite ist zurzeit nicht erreichbar. Bitte versuchen Sie es später noch einmal.',
|
||||
], 503);
|
||||
}
|
||||
|
||||
/**
|
||||
* A suspended landlord stays reachable for the operator, and the operator panel itself stays open.
|
||||
*/
|
||||
|
||||
+12
-1
@@ -4,7 +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;
|
||||
@@ -100,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
|
||||
|
||||
@@ -66,7 +66,7 @@ public static function bootBelongsToTenant(): void
|
||||
}
|
||||
|
||||
if (app()->runningUnitTests() && ! app(TenantContext::class)->isRequired()) {
|
||||
$model->setAttribute('tenant_id', Tenant::query()->create([
|
||||
$model->setAttribute('tenant_id', Tenant::factory()->create([
|
||||
'name' => 'Testmandant',
|
||||
'slug' => 'test-'.Str::lower(Str::random(10)),
|
||||
])->id);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
@@ -12,6 +12,19 @@
|
||||
#[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>
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* One setting of the whole installation, read through App\Support\SystemSettings. Belongs to no landlord;
|
||||
* only the operator ever writes it. Secrets are stored encrypted by the service, not by a cast, because
|
||||
* the value column also holds plain numbers.
|
||||
*/
|
||||
#[Fillable(['key', 'value', 'is_secret'])]
|
||||
class SystemSetting extends Model
|
||||
{
|
||||
/** @var list<string> */
|
||||
protected $hidden = ['value'];
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_secret' => 'boolean',
|
||||
];
|
||||
}
|
||||
}
|
||||
+50
-2
@@ -2,6 +2,8 @@
|
||||
|
||||
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;
|
||||
@@ -13,7 +15,17 @@
|
||||
* 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'])]
|
||||
#[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', 'suspended_message',
|
||||
'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> */
|
||||
@@ -26,7 +38,7 @@ public static function stommer(): self
|
||||
{
|
||||
return static::query()->firstOrCreate(
|
||||
['slug' => 'stommer'],
|
||||
['name' => 'Stommer'],
|
||||
['name' => 'Stommer'] + TenantDefaults::forLegacyLandlord(encryptBank: false),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -37,6 +49,11 @@ protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_active' => 'boolean',
|
||||
'bank_account_holder' => 'encrypted',
|
||||
'bank_iban' => 'encrypted',
|
||||
'bank_bic' => 'encrypted',
|
||||
'bank_name' => 'encrypted',
|
||||
'tax_note' => 'encrypted',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -56,6 +73,37 @@ 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>
|
||||
*/
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Enums\Permission;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
|
||||
/**
|
||||
* Grants every ability that the current membership includes. The operator counts as administrator
|
||||
@@ -48,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 (bool) $user->currentRole()?->grants($this->permission());
|
||||
if (! $user->currentRole()?->grants($this->permission())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return app(TenantFeatures::class)->permits($this->permission());
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,15 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Support\Settings;
|
||||
use App\Support\StripImageMetadata;
|
||||
use App\Support\SystemSettings;
|
||||
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
|
||||
{
|
||||
@@ -18,6 +20,7 @@ class AppServiceProvider extends ServiceProvider
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->singleton(TenantContext::class);
|
||||
$this->app->singleton(TenantConfig::class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,9 +28,16 @@ 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();
|
||||
// Settings of the installation first (they become the baseline a landlord may tighten), then the
|
||||
// operating data of the landlord: addresses, periods and test mode, which sends every e-mail to the
|
||||
// test recipient only until a landlord is switched live. Console and boot know the landlord only if
|
||||
// there is exactly one.
|
||||
try {
|
||||
SystemSettings::apply();
|
||||
$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));
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace App\Providers\Filament;
|
||||
|
||||
use App\Filament\Operator\Pages\SystemOverview;
|
||||
use App\Filament\Operator\Pages\SystemSettingsPage;
|
||||
use App\Http\Middleware\ResolveTheme;
|
||||
use Filament\Auth\MultiFactor\App\AppAuthentication;
|
||||
use Filament\Http\Middleware\Authenticate;
|
||||
@@ -40,6 +42,8 @@ public function panel(Panel $panel): Panel
|
||||
->discoverResources(in: app_path('Filament/Operator'), for: 'App\Filament\Operator')
|
||||
->pages([
|
||||
Dashboard::class,
|
||||
SystemOverview::class,
|
||||
SystemSettingsPage::class,
|
||||
])
|
||||
->widgets([
|
||||
AccountWidget::class,
|
||||
|
||||
+24
-76
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Models\SystemSetting;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Settings of the whole installation, owned by the operator. They are laid over the configuration at boot,
|
||||
* before any landlord is known, so `config('fewo.*')` keeps being the one place the rest of the code reads.
|
||||
*
|
||||
* This is not the old `settings` table in a new coat: that one held a single landlord's operating data,
|
||||
* which now lives on `tenants`. What is kept here belongs to no landlord and is never reachable from a
|
||||
* landlord's admin.
|
||||
*
|
||||
* Database credentials and APP_KEY cannot be kept here. They are needed to open the database and to decrypt
|
||||
* what is in it, so they have to be readable before any of this exists – they stay in the server's .env.
|
||||
*/
|
||||
class SystemSettings
|
||||
{
|
||||
/**
|
||||
* Editable keys: config key => [label, kind, section, help]. The kind decides the form field and
|
||||
* whether the value is stored encrypted.
|
||||
*
|
||||
* @var array<string, array{0: string, 1: string, 2: string, 3: string}>
|
||||
*/
|
||||
public const EDITABLE = [
|
||||
'fewo.guest_retention_years' => ['Gästedaten löschen nach (Jahre)', 'int', 'Löschfristen', 'Obergrenze für alle Mandanten; ein Mandant kann kürzer löschen.'],
|
||||
'fewo.retention.inquiry_months' => ['Nicht gebuchte Anfragen löschen nach (Monate)', 'int', 'Löschfristen', ''],
|
||||
'fewo.retention.portal_email_excerpt_days' => ['Portal-Mail-Auszug löschen nach (Tage)', 'int', 'Löschfristen', ''],
|
||||
'fewo.retention.attribution_months' => ['Herkunftsangaben löschen nach (Monate)', 'int', 'Löschfristen', ''],
|
||||
|
||||
'fewo.spam.min_seconds' => ['Mindestzeit im Formular (Sekunden)', 'int', 'Bot-Schutz', 'Untergrenze; ein Mandant kann länger warten lassen.'],
|
||||
'fewo.spam.per_ip_per_hour' => ['Anfragen je IP und Stunde', 'int', 'Bot-Schutz', ''],
|
||||
'fewo.spam.per_email_per_day' => ['Anfragen je E-Mail und Tag', 'int', 'Bot-Schutz', ''],
|
||||
'fewo.spam.open_requests_per_email' => ['Gleichzeitig offene Anfragen je E-Mail', 'int', 'Bot-Schutz', ''],
|
||||
'fewo.spam.max_links' => ['Erlaubte Links im Text', 'int', 'Bot-Schutz', ''],
|
||||
'fewo.spam.total_per_hour' => ['Anfragen aller Websites zusammen, je Stunde', 'int', 'Bot-Schutz', 'Flutgrenze über alle Mandanten. Kein Mandant kann sie anheben.'],
|
||||
|
||||
'fewo.channels.stale_after_minutes' => ['Portal-Abgleich gilt als veraltet nach (Minuten)', 'int', 'Portale', ''],
|
||||
'fewo.channels.task_reminder_after_minutes' => ['Erinnerung an Portal-Aufgaben nach (Minuten)', 'int', 'Portale', ''],
|
||||
|
||||
'fewo.backup.keep' => ['Aufbewahrte Datenbank-Sicherungen', 'int', 'Sicherung', 'Eine Sicherung der ganzen Datenbank, über alle Mandanten.'],
|
||||
|
||||
'mail.default' => ['Versandweg', 'mailer', 'E-Mail-Versand', '„log“ schreibt jede E-Mail nur in die Logdatei und versendet nichts.'],
|
||||
'mail.mailers.smtp.host' => ['SMTP-Server', 'text', 'E-Mail-Versand', ''],
|
||||
'mail.mailers.smtp.port' => ['SMTP-Port', 'int', 'E-Mail-Versand', ''],
|
||||
'mail.mailers.smtp.username' => ['SMTP-Benutzer', 'text', 'E-Mail-Versand', 'Die Absenderadresse eines Mandanten muss zu diesem Postfach passen, sonst lehnt Strato ab.'],
|
||||
'mail.mailers.smtp.password' => ['SMTP-Passwort', 'secret', 'E-Mail-Versand', ''],
|
||||
'fewo.mail_redirect_to' => ['Harte Umleitung aller E-Mails', 'text', 'E-Mail-Versand', 'Gefüllt: JEDE E-Mail dieses Servers geht nur hierhin, auch bei scharf geschalteten Mandanten. Leer: die Betriebsart jedes Mandanten entscheidet allein.'],
|
||||
|
||||
'fewo.scheduler_token' => ['Scheduler-Token', 'secret', 'Schnittstellen', 'Für GET /automation/scheduler. Leer = abgeschaltet.'],
|
||||
'fewo.channels.health_token' => ['Health-Token', 'secret', 'Schnittstellen', 'Für GET /health/sync. Leer = abgeschaltet.'],
|
||||
'fewo.automation.webhook_url' => ['Automation: Adresse', 'text', 'Schnittstellen', ''],
|
||||
'fewo.automation.secret' => ['Automation: Geheimnis', 'secret', 'Schnittstellen', ''],
|
||||
];
|
||||
|
||||
private const CACHE_KEY = 'system-settings';
|
||||
|
||||
/**
|
||||
* What the server configured, before anything stored was laid over it. Captured once per process.
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
private static array $baseline = [];
|
||||
|
||||
/**
|
||||
* Lays the stored values over the configuration. Called at boot before any landlord is resolved, so
|
||||
* TenantConfig takes these as its baseline.
|
||||
*/
|
||||
public static function apply(): void
|
||||
{
|
||||
$stored = self::stored();
|
||||
$values = [];
|
||||
|
||||
foreach (array_keys(self::EDITABLE) as $key) {
|
||||
if (! array_key_exists($key, self::$baseline)) {
|
||||
self::$baseline[$key] = config($key);
|
||||
}
|
||||
|
||||
// A key the operator cleared has to give the .env value back in the same request, not only
|
||||
// after the next boot – otherwise an emptied field looks saved while the old value still acts.
|
||||
$values[$key] = array_key_exists($key, $stored)
|
||||
? self::cast($key, $stored[$key])
|
||||
: self::$baseline[$key];
|
||||
}
|
||||
|
||||
config($values);
|
||||
}
|
||||
|
||||
/**
|
||||
* The value in force: what the operator stored, else what the server's .env configured.
|
||||
*/
|
||||
public static function get(string $key): mixed
|
||||
{
|
||||
$stored = self::stored();
|
||||
|
||||
return array_key_exists($key, $stored) ? self::cast($key, $stored[$key]) : config($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $values config key => value; null or "" falls back to the .env again
|
||||
*/
|
||||
public static function save(array $values): void
|
||||
{
|
||||
foreach ($values as $key => $value) {
|
||||
if (! array_key_exists($key, self::EDITABLE)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$isSecret = self::EDITABLE[$key][1] === 'secret';
|
||||
|
||||
if (blank($value)) {
|
||||
SystemSetting::query()->where('key', $key)->delete();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
SystemSetting::query()->updateOrCreate(
|
||||
['key' => $key],
|
||||
['value' => $isSecret ? encrypt((string) $value) : (string) $value, 'is_secret' => $isSecret],
|
||||
);
|
||||
}
|
||||
|
||||
Cache::forget(self::CACHE_KEY);
|
||||
self::apply();
|
||||
}
|
||||
|
||||
public static function forget(): void
|
||||
{
|
||||
Cache::forget(self::CACHE_KEY);
|
||||
self::$baseline = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, ?string>
|
||||
*/
|
||||
private static function stored(): array
|
||||
{
|
||||
try {
|
||||
return Cache::rememberForever(self::CACHE_KEY, fn (): array => SystemSetting::query()->pluck('value', 'key')->all());
|
||||
} catch (Throwable) {
|
||||
return []; // before the migrations ran
|
||||
}
|
||||
}
|
||||
|
||||
private static function cast(string $key, ?string $value): mixed
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$kind = self::EDITABLE[$key][1] ?? 'text';
|
||||
|
||||
return match ($kind) {
|
||||
'int' => (int) $value,
|
||||
'secret' => rescue(fn (): string => decrypt($value), null, report: false),
|
||||
default => $value,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -17,12 +17,14 @@ class TenantContext
|
||||
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
|
||||
@@ -57,11 +59,21 @@ 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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tenancy;
|
||||
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
|
||||
/**
|
||||
* Operating data of a landlord taken from what the single-landlord installation used: the admin settings
|
||||
* and config/.env. Used once by the migration and as the factory default in tests.
|
||||
*/
|
||||
class TenantDefaults
|
||||
{
|
||||
/**
|
||||
* @param array<string, ?string> $settings Rows of the former `settings` table (key => value)
|
||||
* @param bool $encryptBank true for raw database writes; the model's own cast encrypts otherwise
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function forLegacyLandlord(array $settings = [], bool $encryptBank = true): array
|
||||
{
|
||||
return [
|
||||
'owner_name' => self::baseline('fewo.owner.name'),
|
||||
'owner_street' => self::baseline('fewo.owner.street'),
|
||||
'owner_city' => self::baseline('fewo.owner.city'),
|
||||
'owner_phone' => self::baseline('fewo.owner.phone'),
|
||||
'contact_email' => self::setting($settings, 'addresses.contact') ?? self::baseline('fewo.owner.email'),
|
||||
'notification_emails' => self::setting($settings, 'addresses.notifications') ?? config('fewo.notification_email'),
|
||||
'sender_name' => self::setting($settings, 'addresses.sender_name') ?? self::baseline('mail.from.name'),
|
||||
'sender_email' => self::setting($settings, 'addresses.sender_email') ?? self::baseline('mail.from.address'),
|
||||
'bank_account_holder' => self::bank(self::baseline('fewo.bank.account_holder'), $encryptBank),
|
||||
'bank_iban' => self::bank(self::baseline('fewo.bank.iban'), $encryptBank),
|
||||
'bank_bic' => self::bank(self::baseline('fewo.bank.bic'), $encryptBank),
|
||||
'bank_name' => self::bank(self::baseline('fewo.bank.bank_name'), $encryptBank),
|
||||
'operating_mode' => ($settings['operations.mode'] ?? 'test') === 'live' ? 'live' : 'test',
|
||||
'test_recipient' => self::setting($settings, 'operations.test_recipient'),
|
||||
'deposit_due_days' => self::baseline('fewo.deposit_due_days'),
|
||||
'review_request_after_days' => self::baseline('fewo.review_request_after_days'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The value of the installation, not the one a landlord may already have laid over the configuration.
|
||||
*/
|
||||
private static function baseline(string $key): mixed
|
||||
{
|
||||
return app(TenantConfig::class)->baselineValue($key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, ?string> $settings
|
||||
*/
|
||||
private static function setting(array $settings, string $key): ?string
|
||||
{
|
||||
return filled($settings[$key] ?? null) ? (string) $settings[$key] : null;
|
||||
}
|
||||
|
||||
private static function bank(mixed $value, bool $encrypt): ?string
|
||||
{
|
||||
if (blank($value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $encrypt ? Crypt::encryptString((string) $value) : (string) $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tenancy;
|
||||
|
||||
use App\Enums\Permission;
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantService;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The single place that answers "is this service unlocked for this landlord". Everything that acts on a
|
||||
* service asks here: the policies of the admin, the console commands, the portal feed. Roles decide what a
|
||||
* *user* may do, this decides what the *landlord* has at all – a landlord without the service keeps nobody
|
||||
* out by role, so both questions have to be asked, and asking them in two places is how they drift apart.
|
||||
*/
|
||||
class TenantFeatures
|
||||
{
|
||||
/**
|
||||
* Services a permission depends on. The permission is granted when at least one of them is unlocked,
|
||||
* so a landlord with only the mailbox still reaches the portal screens.
|
||||
*
|
||||
* @var array<string, list<TenantServiceKey>>
|
||||
*/
|
||||
private const REQUIRES_ANY = [
|
||||
Permission::Channels->value => [TenantServiceKey::PortalSync, TenantServiceKey::PortalMail],
|
||||
];
|
||||
|
||||
/**
|
||||
* Unlocked services per landlord id, for the length of one request.
|
||||
*
|
||||
* @var array<int, array<string, bool>>
|
||||
*/
|
||||
private array $cache = [];
|
||||
|
||||
/**
|
||||
* Whether the landlord may use the service. Without a landlord (console before a context is chosen,
|
||||
* boot) the default of the service applies, which keeps a single-landlord installation unchanged.
|
||||
*/
|
||||
public function enabled(TenantServiceKey $service, ?Tenant $tenant = null): bool
|
||||
{
|
||||
$tenant ??= app(TenantContext::class)->get();
|
||||
|
||||
if ($tenant === null) {
|
||||
return $service->enabledByDefault();
|
||||
}
|
||||
|
||||
return $this->forTenant($tenant)[$service->value] ?? $service->enabledByDefault();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the landlord has what a permission needs. A permission that depends on no service is always
|
||||
* granted here – the role still decides separately.
|
||||
*/
|
||||
public function permits(Permission $permission, ?Tenant $tenant = null): bool
|
||||
{
|
||||
$required = self::REQUIRES_ANY[$permission->value] ?? [];
|
||||
|
||||
if ($required === []) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ($required as $service) {
|
||||
if ($this->enabled($service, $tenant)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forgets what was read, so a switch takes effect without a new request.
|
||||
*/
|
||||
public function forget(?Tenant $tenant = null): void
|
||||
{
|
||||
if ($tenant === null) {
|
||||
$this->cache = [];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
unset($this->cache[$tenant->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, bool>
|
||||
*/
|
||||
private function forTenant(Tenant $tenant): array
|
||||
{
|
||||
if (! array_key_exists($tenant->id, $this->cache)) {
|
||||
try {
|
||||
$this->cache[$tenant->id] = TenantService::query()
|
||||
->where('tenant_id', $tenant->id)
|
||||
->pluck('is_enabled', 'service')
|
||||
->map(fn (mixed $enabled): bool => (bool) $enabled)
|
||||
->all();
|
||||
} catch (Throwable) {
|
||||
return []; // before the migrations ran; the defaults apply
|
||||
}
|
||||
}
|
||||
|
||||
return $this->cache[$tenant->id];
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantDefaults;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
@@ -22,6 +23,7 @@ public function definition(): array
|
||||
'name' => $name,
|
||||
'slug' => Str::slug($name).'-'.Str::lower(Str::random(4)),
|
||||
'is_active' => true,
|
||||
...TenantDefaults::forLegacyLandlord(encryptBank: false),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
use App\Tenancy\TenantDefaults;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Landlord data, bank, addresses, operating mode and periods become columns of the landlord. The values
|
||||
* of the existing (single) landlord come from the `settings` table and from config/.env. The `settings`
|
||||
* table stays until the shipped code no longer reads it (own step, see docs/MANDANTEN-PLAN.md §4).
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->string('owner_name')->nullable();
|
||||
$table->string('owner_street')->nullable();
|
||||
$table->string('owner_city')->nullable();
|
||||
$table->string('owner_phone')->nullable();
|
||||
$table->string('contact_email')->nullable();
|
||||
$table->text('notification_emails')->nullable();
|
||||
$table->string('sender_name')->nullable();
|
||||
$table->string('sender_email')->nullable();
|
||||
$table->text('bank_account_holder')->nullable();
|
||||
$table->text('bank_iban')->nullable();
|
||||
$table->text('bank_bic')->nullable();
|
||||
$table->text('bank_name')->nullable();
|
||||
$table->text('tax_note')->nullable();
|
||||
$table->string('operating_mode', 10)->default('test');
|
||||
$table->string('test_recipient')->nullable();
|
||||
$table->unsignedSmallInteger('deposit_due_days')->nullable();
|
||||
$table->unsignedSmallInteger('review_request_after_days')->nullable();
|
||||
$table->unsignedSmallInteger('guest_retention_years')->nullable();
|
||||
$table->unsignedSmallInteger('retention_inquiry_months')->nullable();
|
||||
$table->unsignedSmallInteger('retention_portal_email_excerpt_days')->nullable();
|
||||
$table->unsignedSmallInteger('retention_attribution_months')->nullable();
|
||||
$table->unsignedSmallInteger('spam_min_seconds')->nullable();
|
||||
$table->unsignedSmallInteger('spam_per_ip_per_hour')->nullable();
|
||||
$table->unsignedSmallInteger('spam_per_email_per_day')->nullable();
|
||||
$table->unsignedSmallInteger('spam_open_requests_per_email')->nullable();
|
||||
$table->unsignedSmallInteger('spam_max_links')->nullable();
|
||||
$table->unsignedSmallInteger('channel_stale_after_minutes')->nullable();
|
||||
$table->unsignedSmallInteger('channel_task_reminder_after_minutes')->nullable();
|
||||
});
|
||||
|
||||
$stommer = DB::table('tenants')->where('slug', 'stommer')->first();
|
||||
|
||||
if ($stommer !== null) {
|
||||
DB::table('tenants')->where('id', $stommer->id)->update(TenantDefaults::forLegacyLandlord(
|
||||
DB::table('settings')->pluck('value', 'key')->all(),
|
||||
));
|
||||
}
|
||||
|
||||
Schema::create('tenant_services', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('service', 40);
|
||||
$table->boolean('is_enabled')->default(false);
|
||||
$table->text('api_key')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['tenant_id', 'service']);
|
||||
});
|
||||
|
||||
Schema::create('service_usages', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('service', 40);
|
||||
$table->unsignedInteger('quantity')->default(1);
|
||||
$table->timestamp('used_at')->useCurrent();
|
||||
|
||||
$table->index(['tenant_id', 'service', 'used_at']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('service_usages');
|
||||
Schema::dropIfExists('tenant_services');
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->dropColumn([
|
||||
'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',
|
||||
]);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* The operating settings are columns of the landlord now (see the previous migration); nothing reads
|
||||
* this table any more. One store for operating data, not two.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::dropIfExists('settings');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::create('settings', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('key')->unique();
|
||||
$table->text('value')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
};
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Writes the switches of the services that are wired, so the operator sees the state instead of an
|
||||
* empty form. The portal services were part of the product before there were landlords, so every
|
||||
* landlord that exists today keeps them.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
$now = now();
|
||||
|
||||
foreach (DB::table('tenants')->pluck('id') as $tenantId) {
|
||||
foreach (TenantServiceKey::wired() as $service) {
|
||||
DB::table('tenant_services')->updateOrInsert(
|
||||
['tenant_id' => $tenantId, 'service' => $service->value],
|
||||
['is_enabled' => $service->enabledByDefault(), 'updated_at' => $now, 'created_at' => $now],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::table('tenant_services')->whereIn('service', array_map(
|
||||
fn (TenantServiceKey $service): string => $service->value,
|
||||
TenantServiceKey::wired(),
|
||||
))->delete();
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Two things the operator owns. The notice a suspended landlord's visitors see instead of a dead link,
|
||||
* and the settings of the whole installation – which, unlike the former `settings` table, belong to
|
||||
* nobody's landlord: they are the operator's, and a landlord's admin never reaches them.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->text('suspended_message')->nullable();
|
||||
});
|
||||
|
||||
Schema::create('system_settings', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('key')->unique();
|
||||
$table->text('value')->nullable();
|
||||
$table->boolean('is_secret')->default(false);
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('system_settings');
|
||||
|
||||
Schema::table('tenants', function (Blueprint $table) {
|
||||
$table->dropColumn('suspended_message');
|
||||
});
|
||||
}
|
||||
};
|
||||
+11
-9
@@ -1,6 +1,6 @@
|
||||
# Mandantenfähigkeit – Umbauplan
|
||||
|
||||
Stand: 23.10.2026, nachmittag · Phase 1, 2 und der Website-Teil von Phase 4 sind auf `main` und auf stommer.info (Release `20261023100346`) · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md) · Design: [DESIGN-KONZEPT.md](DESIGN-KONZEPT.md) §7 · Übergabe: [STATUS.md](STATUS.md) Abschnitt 7
|
||||
Stand: 23.10.2026, abends · Phase 1, 2, 3 und der Website-Teil von Phase 4 sind auf `main` und auf stommer.info (Release `20261023195835`) · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md) · Design: [DESIGN-KONZEPT.md](DESIGN-KONZEPT.md) §7 · Übergabe: [STATUS.md](STATUS.md) Abschnitt 7
|
||||
|
||||
Kein Portal, kein Marktplatz. Das Produkt bleibt die eigene Website eines Vermieters mit Vermietung. Wenige Mandanten, eine gemeinsame Datenbank, Laravel und Filament bleiben die Basis. Ein Python-Dienst ist nicht Teil dieses Umbaus.
|
||||
|
||||
@@ -228,22 +228,24 @@ ### Phase 2 – Rollen, Admin, Benutzer
|
||||
|
||||
Tests: Mitglied von A öffnet eine Buchung von B per Adresse und bekommt 404. Mandanten-Administrator vergibt keine Betreiber-Markierung und sieht keine fremden Benutzer. Konto mit zwei Mitgliedschaften: Passwort-Reset durch den Mandanten-Administrator wird verweigert, durch den Betreiber nicht. Rolle Vermietung kann keine Benutzer anlegen. Einfache Ansicht enthält dieselben Menüpunkte wie vor dem Umbau. Konto mit einem Mandanten sieht keinen Wechsel.
|
||||
|
||||
### Phase 3 – Einstellungen, Texte, Dienste-Grundlage
|
||||
### Phase 3 – Einstellungen, Texte, Dienste-Grundlage · umgesetzt
|
||||
|
||||
Ziel: Vermieterdaten und Texte sind Daten des Mandanten. Die `.env` von Stommer ist nach der Übernahme nur noch Infrastruktur.
|
||||
|
||||
- Spalten am Mandanten, `content_blocks` je Mandant, FAQ und Hinweise je Mandant, Seite „Betrieb“ schreibt den aktuellen Mandanten.
|
||||
- Katalog in `config/content.php` bleibt.
|
||||
- `tenant_services` und `service_usages`, Schalter nur im Betreiber-Bereich.
|
||||
- Tabelle `settings` entfernen.
|
||||
- Spalten am Mandanten, `content_blocks` je Mandant, FAQ und Hinweise je Mandant, Seite „Betrieb“ schreibt den aktuellen Mandanten. Umgesetzt.
|
||||
- Katalog in `config/content.php` bleibt. Unverändert.
|
||||
- `tenant_services` und `service_usages`, Schalter nur im Betreiber-Bereich. Umgesetzt und am 24.10. **wirklich angeschlossen**: `App\Tenancy\TenantFeatures` wird in `RolePolicy::allows()`, beim Portal-Import, im iCal-Feed und im Postfach-Schnellweg abgefragt. Nur verdrahtete Dienste sind schaltbar (`TenantServiceKey::isWired()`); die KI-Dienste erscheinen erst, wenn die Anwendung sie abfragt. Eigene API-Schlüssel gehören dann in den Admin des Mandanten, nicht zum Betreiber (A16). `service_usages` steht bereit, es zählt noch nichts.
|
||||
- Tabelle `settings` entfernen. Umgesetzt.
|
||||
|
||||
Tests: Zwei Mandanten, unterschiedliches Impressum, unterschiedliche Bank, unterschiedliche Betriebsart. Mandant kann die Flutgrenze und die Löschfrist nicht über die globale Obergrenze heben. Leerer Dienst-Schlüssel ist erlaubt.
|
||||
Gebaut als Überlagerung: `App\Tenancy\TenantConfig` legt die Werte des aktuellen Mandanten über `config('fewo.*')` und `mail.from`, sobald sich der Kontext ändert. Vorlagen, Mails und der Vertrag lesen weiter dieselben Schlüssel; `resources/themes/**` blieb unangetastet. Die `.env` bleibt die Grundlinie: Rückfall ohne Mandanten und Obergrenze für Löschfristen und Bot-Schutz.
|
||||
|
||||
Tests (`tests/Feature/TenantSettingsTest.php`, `OperationsModeTest.php`): Zwei Mandanten, unterschiedliches Impressum, unterschiedliche Bank, unterschiedliche Betriebsart. Mandant kann die Löschfrist und den Bot-Schutz nicht über die globale Obergrenze heben. Leerer Dienst-Schlüssel ist erlaubt, eigene Schlüssel und Bankdaten liegen verschlüsselt.
|
||||
|
||||
### Phase 4 – Domain, Cron, Mail, Postfach
|
||||
|
||||
Ziel: Host, Erinnerungen und Portal-Mails gehören dem richtigen Mandanten.
|
||||
|
||||
- `site_domains`, 404 für unbekannte Hosts ab dem zweiten Mandanten. Umgesetzt. Mit genau einem Mandanten bleibt die Standard-Website auf jeder Adresse.
|
||||
- `site_domains`, 404 für unbekannte Hosts ab dem zweiten Mandanten. Umgesetzt. Mit genau einem Mandanten bleibt die Standard-Website auf jeder Adresse. Am 24.10. ergänzt: mehrere Adressen je Website im Admin, weil „www" ein eigener Host ist und das Feld „Domain" nur einen schrieb. Fremde Hosts werden abgelehnt.
|
||||
- Links mit dem Ursprung der Website. Umgesetzt für Angebot, Annahme, Bewertung und Einwilligung.
|
||||
- Scheduler-Schleife, Postfach je Mandant, Absender je Versand. Noch nicht.
|
||||
|
||||
@@ -288,6 +290,6 @@ ## 9. Betrieb und Abgrenzung
|
||||
|
||||
## 10. Freigabe
|
||||
|
||||
Phase 1 und 2 sowie der Website-Teil von Phase 4 sind auf stommer.info (Release `20261023100346`). Die bisherigen Daten gehören zum Mandanten Stommer, `lars@stommer.com` ist Betreiber. Die nächste Codesitzung ist Phase 3; Übergabe mit den gebauten Bausteinen: [STATUS.md](STATUS.md) Abschnitt 7. Phase 3 bis 5 bringen weitere Migrationen. Phase 6 und 7 warten auf eine eigene Freigabe.
|
||||
Phase 1, 2 und 3 sowie der Website-Teil von Phase 4 sind auf stommer.info (Release `20261023195835`). Die bisherigen Daten gehören zum Mandanten Stommer, `lars@stommer.com` ist Betreiber. Die nächste Codesitzung ist der Rest von Phase 4; Übergabe mit den gebauten Bausteinen: [STATUS.md](STATUS.md) Abschnitt 7. Phase 4 und 5 bringen weitere Migrationen. Phase 6 und 7 warten auf eine eigene Freigabe.
|
||||
|
||||
Die Sicherheitsregel in §1 gilt: Passwort und 2FA gehören zum Konto, die Rolle zur Mitgliedschaft. Der Betreiber darf zusätzlich Mandanten-Administrator der eigenen Wohnung sein.
|
||||
+36
-15
@@ -1,6 +1,6 @@
|
||||
# Projektstand
|
||||
|
||||
Stand: 23.10.2026 · ausgelieferter Stand: `deploy/staging/20261023100346` · 217 Feature-Tests grün
|
||||
Stand: 24.10.2026 · ausgelieferter Stand: `deploy/staging/20261024072737` · 242 Feature-Tests grün
|
||||
|
||||
> Dieses Dokument ist der Einstieg für jede neue Arbeitssitzung. Bitte bei größeren Änderungen fortschreiben (Abschnitte „Fertig“, „Offen“, „Nächste Schritte“).
|
||||
|
||||
@@ -70,7 +70,7 @@ ## 3. Offen
|
||||
**Technik**
|
||||
- Cronjob auf Strato einrichten (BETRIEB.md §6).
|
||||
- Design-Theme Seebad 0.3 ist auf `main` und auf stommer.info aktiv (Abschnitt 6).
|
||||
- Mandantenfähigkeit: Phase 1, 2 und der Website-Teil von Phase 4 sind auf stommer.info. **Nächste Codesitzung: Phase 3.** Stand, Bausteine und Fallen stehen in Abschnitt 7. Plan: `docs/MANDANTEN-PLAN.md`.
|
||||
- Mandantenfähigkeit: Phase 1, 2, 3 und der Website-Teil von Phase 4 sind auf stommer.info. **Nächste Codesitzung: Rest von Phase 4.** Stand, Bausteine und Fallen stehen in Abschnitt 7. Plan: `docs/MANDANTEN-PLAN.md`.
|
||||
- Logo in E-Mails und im Vertrags-PDF (`public/brand/logo-600.png` liegt bereit).
|
||||
- Content-Security-Policy: braucht wegen Livewire/Filament Nonces und einen sorgfältigen Test.
|
||||
- Produktion `www.fewo-stommer.de` vorbereiten:
|
||||
@@ -135,32 +135,43 @@ ## 6. Design-Theme „Seebad“ (Abschnitt der Design-Session)
|
||||
|
||||
## 7. Mandanten – Übergabe an die nächste Sitzung
|
||||
|
||||
Stand: 23.10.2026, 12:20 · Branch `main` · Plan: [MANDANTEN-PLAN.md](MANDANTEN-PLAN.md) · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md)
|
||||
Stand: 23.10.2026, abends · Branch `main` · Plan: [MANDANTEN-PLAN.md](MANDANTEN-PLAN.md) · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md)
|
||||
|
||||
**Hier weitermachen: Phase 3** (Einstellungen, Texte, Dienste-Grundlage). Danach der Rest von Phase 4 (Scheduler, Postfach, Absender, iCal-Token), dann Phase 5 (Export und Löschung eines Mandanten). Phase 6 und 7 erst nach eigener Freigabe und einem Eintrag in ZUSAMMENARBEIT.md §6. Neuen Branch von `main` abzweigen. `feature/mandanten` ist bereits zusammengeführt.
|
||||
**Hier weitermachen: der Rest von Phase 4** (Scheduler-Schleife über die Mandanten, Portal-Postfach je Mandant, Absender je Versand, iCal-Token). Danach Phase 5 (Export und Löschung eines Mandanten). Phase 6 und 7 erst nach eigener Freigabe und einem Eintrag in ZUSAMMENARBEIT.md §6. Neuen Branch von `main` abzweigen.
|
||||
|
||||
**Phase 3 ist ausgeliefert** (23.10.2026 abends). Die Migrationen sind auf der MariaDB von stommer.info durch, `settings` ist weg, die Werte stehen am Mandanten Stommer.
|
||||
|
||||
**Dienste-Steuerung und Host-Verwaltung sind ausgeliefert** (24.10.2026, Release `20261024072737`). Seitdem läuft stommer.info mit **zwei** Mandanten:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Mandant 1 | `stommer` – die bestehenden Daten, Website „Ferienwohnung Stommer" |
|
||||
| Mandant 2 | `testmandant` („Testmandant (Probe)") – ohne Website, ohne Benutzer, nur damit die Trennung unter echten Bedingungen sichtbar ist. Betriebsart Test, Mails fallen auf `FEWO_NOTIFICATION_EMAIL` zurück. |
|
||||
| Hosts | An der Website von Stommer stehen jetzt `stommer.info` (Hauptadresse) **und** `www.stommer.info`. Das war die Voraussetzung: ab dem zweiten Mandanten bekommt jede nicht eingetragene Adresse 404. |
|
||||
| Geprüft nach dem Anlegen | `/`, `/wohnung`, `/buchen` auf beiden Hosts 200 und weiterhin Inhalte von Stommer; `/admin` und `/betreiber` 302. |
|
||||
|
||||
### Ausgeliefert
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Server | nur **stommer.info** (Staging). `www.fewo-stommer.de` ist unberührt und bleibt WordPress. |
|
||||
| Release | `20261023100346`, Git-Tag `deploy/staging/20261023100346`, Commit `cec49da` |
|
||||
| Code danach | Commits auf `main` nach `cec49da` sind Dokumentation. Sie sind nicht erneut ausgeliefert. Ein Deploy nur wegen dieser Texte ist unnötig: das Skript nimmt `docs/` nicht mit. |
|
||||
| Migration | drei Migrationen vom 23.10. sind auf der MariaDB von stommer.info durch. Vorhandene Zeilen gehören zum Mandanten **Stommer** (`slug` `stommer`). Ein zweites Migrieren legt keinen zweiten Stommer an, solange keine Zeile ohne Mandant übrig ist. |
|
||||
| Sicherung davor | `C:\Dev\fewo-backups\staging\20261023-120038` (Datenbank-Dump und Dateien). Ein Rollback der Version nimmt die Migration **nicht** zurück. |
|
||||
| Release | `20261024072737`, Git-Tag `deploy/staging/20261024072737`, Commit `2f2aceb` (Phase 3, Dienste-Steuerung, Host-Verwaltung) |
|
||||
| Code danach | Commits auf `main` nach `2f2aceb` sind Dokumentation. Sie sind nicht erneut ausgeliefert. Ein Deploy nur wegen dieser Texte ist unnötig: das Skript nimmt `docs/` nicht mit. |
|
||||
| Migration | fünf Migrationen vom 23.10. sind auf der MariaDB von stommer.info durch. Vorhandene Zeilen gehören zum Mandanten **Stommer** (`slug` `stommer`); die Betriebsdaten stehen an dessen Spalten, `settings` ist weg. Ein zweites Migrieren legt keinen zweiten Stommer an, solange keine Zeile ohne Mandant übrig ist. |
|
||||
| Sicherung davor | `C:\Dev\fewo-backups\staging\20261024-092543`; davor `…\20261023-215553` (die letzte mit noch vorhandener `settings`-Tabelle). Erstellt mit `scripts/backup-pull.sh staging`. Ein Rollback der Version nimmt die Migration **nicht** zurück. |
|
||||
| Konto | `php artisan users:promote-operator lars@stommer.com` ist auf dem Server gelaufen. Passwort und 2FA sind gleich geblieben. |
|
||||
| Prüfung | `https://stommer.info/`, `/wohnung` und `/buchen` antworten 200 und zeigen weiter Seebad und Stommer. `/admin` und `/betreiber` leiten ohne Anmeldung auf die Login-Seite um (302). Lars hat den Admin danach angemeldet geprüft: funktionsfähig. |
|
||||
| Prüfung | `https://stommer.info/`, `/wohnung` und `/buchen` antworten 200 und zeigen weiter Seebad und Stommer samt Vermieterdaten aus den Mandanten-Spalten. `/admin` und `/betreiber` leiten ohne Anmeldung auf die Login-Seite um (302). Betriebsart Testbetrieb, Umleitung an `lars@stommer.com`. **Noch nicht angemeldet geprüft:** die Seite System › Betrieb mit den neuen Abschnitten. |
|
||||
|
||||
Die lokale Datei `database/database.sqlite` (`.env`: `DB_CONNECTION=sqlite`, `APP_URL=http://localhost:8000`) ist **nicht** migriert. `php artisan serve` auf diesem Rechner trifft das alte Schema und läuft mit dem neuen Code nicht. Testinstanz ist stommer.info. Die lokale Datei nur migrieren, wenn jemand bewusst lokal arbeiten will (`php artisan migrate`, danach `users:promote-operator` für das lokale Konto). Die `.env` nicht auf die Datenbank von stommer.info zeigen lassen.
|
||||
Die lokale Datei `database/database.sqlite` (`.env`: `DB_CONNECTION=sqlite`, `APP_URL=http://localhost:8000`) ist **nicht** vollständig migriert (die zwei Migrationen von Phase 3 stehen dort auf „Pending“). `php artisan serve` auf diesem Rechner trifft das alte Schema und läuft mit dem neuen Code nicht. Testinstanz ist stommer.info. Die lokale Datei nur migrieren, wenn jemand bewusst lokal arbeiten will (`php artisan migrate`, danach `users:promote-operator` für das lokale Konto). Die `.env` nicht auf die Datenbank von stommer.info zeigen lassen.
|
||||
|
||||
Nicht committet und nicht Teil des Umbaus: `styles/satz3/svg/haus.svg`, `styles/satz3/svg/haus-klein.svg`.
|
||||
|
||||
### Nicht anfassen, solange es nicht der Auftrag ist
|
||||
|
||||
- `resources/themes/**`. Seebad 0.3 ist auf stommer.info aktiv. Eine neue Theme-Datei erst nach Eintrag in ZUSAMMENARBEIT.md §6.
|
||||
- Keinen zweiten Mandanten anlegen, bevor an der Website von Stommer der Host `stommer.info` steht (Webseite › Website, Feld Domain). Die Domain ist leer. Mit genau einem Mandanten liefert jeder Host die Standard-Website. Ab dem zweiten Mandanten antwortet ein unbekannter Host mit 404, `is_default` rettet ihn nicht. `www` ist ein eigener Host.
|
||||
- Die Hosts stehen jetzt (`stommer.info`, `www.stommer.info`), und es gibt zwei Mandanten. Jede weitere Adresse muss **vor** ihrer Benutzung in Webseite › Website eingetragen werden, sonst 404. `is_default` rettet einen unbekannten Host nicht.
|
||||
- `users.role` nicht löschen. Die Mitgliedschaft in `tenant_user` gilt; die Spalte bleibt der Übergang, wenn es genau einen Mandanten gibt und noch kein Kontext gesetzt ist.
|
||||
- Tabelle `settings` nicht nebenbei leeren. Das ist Phase 3.
|
||||
- `config/fewo.php` bleibt die Grundlinie und die Obergrenze. Werte des Mandanten gehören in die Spalten von `tenants`, nicht in neue `.env`-Schlüssel.
|
||||
- Filaments `Panel::tenant()` und `tenantDomain()` nicht einschalten.
|
||||
- Produktion nicht ausliefern. Deploy nur aus aktuellem `main` mit grünen Feature-Tests (`scripts/deploy.sh staging deploy`). Dabei läuft `migrate` mit. Die Datenbank nicht allein migrieren, während noch alter Code aktiv ist.
|
||||
|
||||
@@ -178,13 +189,23 @@ ### So ist es gebaut
|
||||
| Rollen | `tenant_user.role`. `User::currentRole()`: Betreiber im gesetzten Kontext ist Mandanten-Administrator; sonst die Mitgliedschaft; sonst, bei genau einem Mandanten, `users.role`. `is_operator` ist nicht massenzuweisbar, nur `users:promote-operator`. In `canAccessPanel` als `(bool)` lesen, sonst kommt `null` zurück und der Panel-Zugriff wirft einen TypeError. Passwort und 2FA setzt ein Mandanten-Administrator nur zurück, wenn das Konto ausschließlich seinem Mandanten gehört. |
|
||||
| Betreiber | Panel `operator`, Pfad `/betreiber`, entdeckt nur `App\Filament\Operator`. Mandant anlegen und bearbeiten. Löschen ist in der Policy falsch (Phase 5). „Im Admin öffnen“ schreibt `tenant_access_logs` und geht auf `https://<domain>/admin`. Der Menüpunkt „Anderer Mandant“ erscheint nur, wenn es eine weitere Mitgliedschaft mit Domain gibt. `routes/web.php` lässt `betreiber` nicht als Seiten-Slug durch. |
|
||||
| Weitere Stellen | `Property::site()` ist `BelongsTo`. `Booking::website()` und `Guest::website()` laden die Website ohne Mandanten-Scope. `BookingObserver` lädt die Wohnung ohne Scope `tenant`, sonst fehlt sie bei einem fremden Kontext. Rate-Limits je IP und E-Mail enthalten die Mandanten-Id; `booking-request-all` bleibt global. Cache-Schlüssel der Texte: `content-blocks.{tenantId}`. |
|
||||
| Noch global | Tabelle `settings` (Vermieter, Bank, Betriebsart, Fristen, Adressen). Postfach, Absender und der Scheduler kennen keinen Mandanten. Der Cronjob auf Strato ist weiterhin nicht eingerichtet, der Versandweg ist `log`. Das ist mit einem Mandanten der bisherige Betrieb. |
|
||||
| `TenantConfig` (Phase 3) | Legt die Werte des Mandanten über `config('fewo.*')` und `mail.from`, sobald der Kontext gesetzt, gewechselt oder vergessen wird. Dadurch lesen Vorlagen, Mails und der Vertrag weiter dieselben Schlüssel, und `resources/themes/**` musste nicht angefasst werden. Die `.env` ist die Grundlinie. Ändert jemand von außen einen dieser Schlüssel (Test, Befehl), wird dieser Wert zur neuen Grundlinie statt beim nächsten Durchlauf überschrieben zu werden. |
|
||||
| Grenzen (Phase 3) | Löschfristen und Bot-Schutz sind nach oben durch die `.env` gedeckelt (`AT_MOST`), die Mindestzeit im Formular nach unten (`AT_LEAST`); das Formular zeigt die Grenze an. Anzahlungsfrist, Bewertungsfrist und Portal-Fristen sind frei. Die Flutgrenze `spam.total_per_hour` bleibt global. |
|
||||
| Betrieb (Phase 3) | Die Seite System › Betrieb schreibt jetzt den Mandanten des Kontextes (`Settings::tenant()`), nicht mehr die Tabelle `settings`. Sie enthält zusätzlich Vermieterdaten, Bank, Steuerangabe und die Fristen. Bank, Steuerangabe und Dienst-Schlüssel liegen über das `encrypted`-Cast verschlüsselt (`APP_KEY`). |
|
||||
| Dienste (Phase 3) | `tenant_services` (Mandant, Schlüssel aus `App\Enums\TenantServiceKey`, an/aus, eigener API-Schlüssel) wird nur im Betreiber-Bereich am Mandanten-Formular geschaltet. `service_usages` steht bereit; es zählt noch nichts, weil kein Dienst aufruft. |
|
||||
| `settings` | Entfernt. Modell `App\Models\Setting` gelöscht, `Settings::get/save` gibt es nicht mehr. |
|
||||
| Dienste (24.10.) | `App\Tenancy\TenantFeatures` ist die einzige Stelle, die beantwortet, ob ein Mandant einen Dienst hat. Abgefragt in `RolePolicy::allows()` (damit in **jeder** Richtlinie des Admins), in `Channel::importsOccupations()`, im öffentlichen iCal-Feed und im Postfach-Schnellweg. Keine Rolle wiegt einen gesperrten Dienst auf. `TenantServiceKey::isWired()` trennt Gebautes von Geplantem: nur verdrahtete Dienste sind schaltbar, die drei KI-Dienste stehen als Hinweis. Eigene API-Schlüssel gehören später in den Admin des Mandanten, nicht zum Betreiber. |
|
||||
| Hosts (24.10.) | Website-Formular: „Hauptadresse" (steht in Gästelinks) plus „Weitere Adressen". Eingaben werden normalisiert. Eine Adresse, die zu einer anderen Website gehört, wird abgelehnt – sonst könnte ein Mandant die Besucher eines anderen abfangen. |
|
||||
| Noch global | Postfach, Absender des Scheduler-Laufs und der Scheduler selbst kennen keinen Mandanten (Rest von Phase 4). Der Cronjob auf Strato ist weiterhin nicht eingerichtet, der Versandweg ist `log`. Das ist mit einem Mandanten der bisherige Betrieb. Ein Mandant ohne eigene Adressen fällt für die Testumleitung auf `FEWO_NOTIFICATION_EMAIL` zurück, damit nichts versehentlich an echte Gäste geht. |
|
||||
|
||||
Tests dazu: `tests/Feature/TenantIsolationTest.php`, `TenantAccessTest.php`, `WebsiteTenancyTest.php`. Zuletzt 217 Feature-Tests grün. PHP auf diesem Rechner: `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.NTS.8.4_*\php.exe`, nicht im PATH der Git-Bash. Für `scripts/deploy.sh` von hier `COMPOSER_BIN` auf `php …/composer/composer.phar` setzen, sonst findet die Bash kein `composer`.
|
||||
Tests dazu: `tests/Feature/TenantIsolationTest.php`, `TenantAccessTest.php`, `WebsiteTenancyTest.php`, `TenantSettingsTest.php`, `OperationsModeTest.php`. Zuletzt 235 Feature-Tests grün. PHP auf diesem Rechner: `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.NTS.8.4_*\php.exe`, nicht im PATH der Git-Bash. Für `scripts/deploy.sh` von hier `COMPOSER_BIN` auf `php …/composer/composer.phar` setzen, sonst findet die Bash kein `composer`.
|
||||
|
||||
### Offen, aber nicht in derselben Sitzung nötig gewesen
|
||||
|
||||
- Phase 3, Rest von Phase 4, Phase 5. Jede davon bringt eigene Migrationen. Auslieferung und Migration wieder in einem Schritt, nach Sicherung.
|
||||
- Rest von Phase 4 und Phase 5. Jede davon bringt eigene Migrationen. Auslieferung und Migration wieder in einem Schritt, nach Sicherung.
|
||||
- **Bankverbindung eintragen:** Die `.env` von stommer.info hat keine `FEWO_BANK_*`-Werte, deshalb sind Kontoinhaber, IBAN, BIC und Bank am Mandanten leer (wie vorher auch). Sie gehören jetzt in System › Betrieb › Bankverbindung und Steuer; `mail/partials/bank.blade.php` und der Vertrag zeigen den Block erst, wenn eine IBAN da ist.
|
||||
- **Testmandant wieder loswerden,** wenn er nicht mehr gebraucht wird. Löschen ist erst Phase 5; bis dahin im Betreiber-Bereich auf „nicht aktiv" stellen.
|
||||
- **Vor jeder weiteren Adresse:** Jede Schreibweise ist ein eigener Host. Kommt `fewo-stommer.de` dazu, gehören `fewo-stommer.de` **und** `www.fewo-stommer.de` in das Feld „Weitere Adressen", sonst antwortet eine davon mit 404.
|
||||
- Betreiber-Bereich https://stommer.info/betreiber einmal öffnen. Der Admin ist geprüft.
|
||||
- Host `stommer.info` an der Website eintragen, bevor ein zweiter Mandant entsteht. Später ebenso `www` und `fewo-stommer.de`, wenn die Produktion umzieht.
|
||||
- Brigitte, Cronjob, SMTP, Rechtstexte: Abschnitt 4, unverändert und unabhängig vom Mandanten-Code.
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<x-filament-panels::page>
|
||||
<x-filament::section>
|
||||
<x-slot name="heading">Mandanten</x-slot>
|
||||
<x-slot name="description">Wer auf diesem Server liegt und was freigeschaltet ist.</x-slot>
|
||||
|
||||
<div class="fi-ta-ctn overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="text-left text-gray-500 dark:text-gray-400">
|
||||
<th class="py-2 pr-4 font-medium">Name</th>
|
||||
<th class="py-2 pr-4 font-medium">Kurzname</th>
|
||||
<th class="py-2 pr-4 font-medium">Zustand</th>
|
||||
<th class="py-2 font-medium">Dienste frei</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-gray-200 dark:divide-white/10">
|
||||
@foreach ($this->tenants() as $tenant)
|
||||
<tr>
|
||||
<td class="py-2 pr-4 font-medium">{{ $tenant->name }}</td>
|
||||
<td class="py-2 pr-4 text-gray-500 dark:text-gray-400">{{ $tenant->slug }}</td>
|
||||
<td class="py-2 pr-4">
|
||||
<x-filament::badge :color="$tenant->is_active ? 'success' : 'danger'">
|
||||
{{ $tenant->is_active ? 'aktiv' : 'gesperrt' }}
|
||||
</x-filament::badge>
|
||||
</td>
|
||||
<td class="py-2">{{ $tenant->services_count }} von {{ $this->wiredServiceCount() }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</x-filament::section>
|
||||
|
||||
<x-filament::section>
|
||||
<x-slot name="heading">Grenzen für alle Mandanten</x-slot>
|
||||
<x-slot name="description">
|
||||
Ein Mandant kann sie in seinem Admin verschärfen, aber nicht überschreiten. Geändert werden sie unter
|
||||
<strong>Einstellungen</strong>; dort gilt ein leeres Feld als „Wert aus der <code>.env</code> des Servers“.
|
||||
</x-slot>
|
||||
|
||||
<dl class="divide-y divide-gray-200 dark:divide-white/10">
|
||||
@foreach ($this->limits() as $row)
|
||||
<div class="grid gap-1 py-2 sm:grid-cols-3">
|
||||
<dt class="text-gray-500 dark:text-gray-400">{{ $row['label'] }}</dt>
|
||||
<dd class="font-medium">{{ $row['value'] }}</dd>
|
||||
<dd class="text-xs text-gray-500 dark:text-gray-400">{{ $row['note'] }}</dd>
|
||||
</div>
|
||||
@endforeach
|
||||
</dl>
|
||||
</x-filament::section>
|
||||
|
||||
<x-filament::section>
|
||||
<x-slot name="heading">Gilt für den ganzen Server</x-slot>
|
||||
|
||||
<dl class="divide-y divide-gray-200 dark:divide-white/10">
|
||||
@foreach ($this->global() as $row)
|
||||
<div class="grid gap-1 py-2 sm:grid-cols-3">
|
||||
<dt class="text-gray-500 dark:text-gray-400">{{ $row['label'] }}</dt>
|
||||
<dd class="font-medium">{{ $row['value'] }}</dd>
|
||||
<dd class="text-xs text-gray-500 dark:text-gray-400">{{ $row['note'] }}</dd>
|
||||
</div>
|
||||
@endforeach
|
||||
</dl>
|
||||
</x-filament::section>
|
||||
|
||||
<x-filament::section>
|
||||
<x-slot name="heading">Zugriffe des Betreibers</x-slot>
|
||||
<x-slot name="description">Wer wann den Admin eines Mandanten geöffnet hat. Support-Zugriff bleibt sichtbar.</x-slot>
|
||||
|
||||
@if ($this->accessLog()->isEmpty())
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400">Noch kein Zugriff aufgezeichnet.</p>
|
||||
@else
|
||||
<ul class="divide-y divide-gray-200 text-sm dark:divide-white/10">
|
||||
@foreach ($this->accessLog() as $entry)
|
||||
<li class="flex flex-wrap gap-x-2 py-2">
|
||||
<span class="text-gray-500 dark:text-gray-400">{{ $entry->created_at?->format('d.m.Y H:i') }}</span>
|
||||
<span class="font-medium">{{ $entry->user?->name ?? 'Unbekannt' }}</span>
|
||||
<span class="text-gray-500 dark:text-gray-400">öffnete</span>
|
||||
<span class="font-medium">{{ $entry->tenant?->name ?? 'gelöschter Mandant' }}</span>
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
</x-filament::section>
|
||||
</x-filament-panels::page>
|
||||
@@ -0,0 +1,22 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>Webseite nicht erreichbar</title>
|
||||
<style>
|
||||
body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
|
||||
background: #f6f5f3; color: #2f2f2d; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; }
|
||||
main { max-width: 32rem; padding: 2rem; text-align: center; }
|
||||
h1 { font-size: 1.25rem; font-weight: 600; margin: 0 0 0.75rem; }
|
||||
p { margin: 0; line-height: 1.6; color: #5b5b57; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Webseite nicht erreichbar</h1>
|
||||
<p>{{ $message }}</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -8,13 +8,17 @@
|
||||
use App\Mail\NewReservation;
|
||||
use App\Mail\ReservationReceived;
|
||||
use App\Models\Property;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Settings;
|
||||
use App\Tenancy\TenantConfig;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Mail\MailManager;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
@@ -26,6 +30,7 @@ class OperationsModeTest extends TestCase
|
||||
public function test_new_installations_start_in_test_mode_with_the_notification_address(): void
|
||||
{
|
||||
config(['fewo.mail_redirect_to' => null, 'fewo.notification_email' => 'fewo@example.com']);
|
||||
$this->landlord(['notification_emails' => null, 'test_recipient' => null]);
|
||||
|
||||
$this->assertFalse(Settings::isLive());
|
||||
$this->assertSame('fewo@example.com', Settings::mailRedirect());
|
||||
@@ -34,7 +39,7 @@ public function test_new_installations_start_in_test_mode_with_the_notification_
|
||||
public function test_in_test_mode_every_mail_goes_to_the_test_recipient_only(): void
|
||||
{
|
||||
config(['fewo.mail_redirect_to' => null, 'mail.default' => 'array']);
|
||||
Settings::save([Settings::MODE => Settings::MODE_TEST, Settings::TEST_RECIPIENT => 'test@example.com']);
|
||||
$this->landlord(['operating_mode' => Settings::MODE_TEST, 'test_recipient' => 'test@example.com']);
|
||||
|
||||
Mail::raw('Hallo', fn ($message) => $message->to('gast@example.com')->cc('vermieterin@example.com')->subject('Angebot'));
|
||||
|
||||
@@ -45,7 +50,7 @@ public function test_in_test_mode_every_mail_goes_to_the_test_recipient_only():
|
||||
public function test_switched_live_mails_reach_their_real_recipients(): void
|
||||
{
|
||||
config(['fewo.mail_redirect_to' => null, 'mail.default' => 'array']);
|
||||
Settings::save([Settings::MODE => Settings::MODE_LIVE]);
|
||||
$this->landlord(['operating_mode' => Settings::MODE_LIVE]);
|
||||
|
||||
Mail::raw('Hallo', fn ($message) => $message->to('gast@example.com')->subject('Angebot'));
|
||||
|
||||
@@ -54,9 +59,12 @@ public function test_switched_live_mails_reach_their_real_recipients(): void
|
||||
$this->assertNull(Settings::mailRedirect());
|
||||
}
|
||||
|
||||
public function test_addresses_of_the_internal_communication_are_set_in_the_admin(): void
|
||||
public function test_addresses_and_landlord_data_of_the_internal_communication_are_set_in_the_admin(): void
|
||||
{
|
||||
config(['fewo.mail_redirect_to' => null]);
|
||||
$this->seed(PropertySeeder::class);
|
||||
$tenant = Tenant::query()->where('slug', 'stommer')->firstOrFail();
|
||||
app(TenantContext::class)->set($tenant);
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
Livewire::test(Operations::class)
|
||||
@@ -65,14 +73,16 @@ public function test_addresses_of_the_internal_communication_are_set_in_the_admi
|
||||
->set('data.contact_email', 'info@example.com')
|
||||
->set('data.sender_name', 'FeWo Test')
|
||||
->set('data.sender_email', 'versand@example.com')
|
||||
->set('data.owner_name', 'Brigitte Beispiel')
|
||||
->set('data.bank_iban', 'DE02120300000000202051')
|
||||
->call('save')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$this->assertSame(['brigitte@example.com', 'lars@example.com'], Settings::notificationRecipients());
|
||||
$this->assertSame(['info@example.com', 'versand@example.com', 'FeWo Test'], [config('fewo.owner.email'), config('mail.from.address'), config('mail.from.name')]);
|
||||
$this->assertSame(['Brigitte Beispiel', 'DE02120300000000202051'], [config('fewo.owner.name'), config('fewo.bank.iban')]);
|
||||
|
||||
Mail::fake();
|
||||
$this->seed(PropertySeeder::class);
|
||||
$booking = app(CreateReservation::class)->handle(Property::sole(), new StayRequest(CarbonImmutable::parse('2026-12-01'), CarbonImmutable::parse('2026-12-05'), 2), ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'erika@example.com']);
|
||||
|
||||
Mail::assertSent(NewReservation::class, fn (NewReservation $mail): bool => $mail->hasTo('brigitte@example.com') && $mail->hasTo('lars@example.com'));
|
||||
@@ -80,8 +90,45 @@ public function test_addresses_of_the_internal_communication_are_set_in_the_admi
|
||||
$this->assertNotNull($booking);
|
||||
}
|
||||
|
||||
public function test_the_bank_details_are_stored_encrypted(): void
|
||||
{
|
||||
$tenant = $this->landlord(['bank_iban' => 'DE02120300000000202051']);
|
||||
|
||||
$stored = DB::table('tenants')->where('id', $tenant->id)->value('bank_iban');
|
||||
$this->assertNotSame('DE02120300000000202051', $stored);
|
||||
$this->assertSame('DE02120300000000202051', $tenant->fresh()->bank_iban);
|
||||
}
|
||||
|
||||
public function test_a_landlord_cannot_relax_a_retention_period_or_the_bot_protection(): void
|
||||
{
|
||||
config(['fewo.guest_retention_years' => 10, 'fewo.spam.per_ip_per_hour' => 5, 'fewo.spam.min_seconds' => 4]);
|
||||
|
||||
$this->landlord([
|
||||
'guest_retention_years' => 25,
|
||||
'spam_per_ip_per_hour' => 50,
|
||||
'spam_min_seconds' => 1,
|
||||
'deposit_due_days' => 21,
|
||||
]);
|
||||
|
||||
$this->assertSame(10, config('fewo.guest_retention_years'));
|
||||
$this->assertSame(5, config('fewo.spam.per_ip_per_hour'));
|
||||
$this->assertSame(4, config('fewo.spam.min_seconds'));
|
||||
$this->assertSame(21, config('fewo.deposit_due_days'));
|
||||
}
|
||||
|
||||
public function test_a_landlord_may_tighten_a_retention_period(): void
|
||||
{
|
||||
config(['fewo.guest_retention_years' => 10, 'fewo.spam.min_seconds' => 4]);
|
||||
|
||||
$this->landlord(['guest_retention_years' => 3, 'spam_min_seconds' => 9]);
|
||||
|
||||
$this->assertSame(3, config('fewo.guest_retention_years'));
|
||||
$this->assertSame(9, config('fewo.spam.min_seconds'));
|
||||
}
|
||||
|
||||
public function test_invalid_notification_addresses_are_rejected(): void
|
||||
{
|
||||
$this->landlord();
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
Livewire::test(Operations::class)
|
||||
@@ -93,7 +140,7 @@ public function test_invalid_notification_addresses_are_rejected(): void
|
||||
public function test_server_override_always_wins(): void
|
||||
{
|
||||
config(['fewo.mail_redirect_to' => 'server@example.com']);
|
||||
Settings::save([Settings::MODE => Settings::MODE_LIVE]);
|
||||
$this->landlord(['operating_mode' => Settings::MODE_LIVE]);
|
||||
|
||||
$this->assertSame('server@example.com', Settings::mailRedirect());
|
||||
}
|
||||
@@ -101,6 +148,7 @@ public function test_server_override_always_wins(): void
|
||||
public function test_administrator_switches_the_mode_in_the_admin_and_sees_the_banner(): void
|
||||
{
|
||||
config(['fewo.mail_redirect_to' => null]);
|
||||
$this->landlord();
|
||||
$this->actingAs(User::factory()->create());
|
||||
|
||||
$this->get(Operations::getUrl())->assertOk()->assertSee('Testbetrieb:');
|
||||
@@ -118,4 +166,18 @@ public function test_administrator_switches_the_mode_in_the_admin_and_sees_the_b
|
||||
$this->actingAs(User::factory()->role(UserRole::Rentals)->create());
|
||||
$this->get(Operations::getUrl())->assertForbidden();
|
||||
}
|
||||
|
||||
/**
|
||||
* The only landlord, with the operating data under test applied to the configuration.
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
private function landlord(array $attributes = []): Tenant
|
||||
{
|
||||
$tenant = Tenant::factory()->create($attributes);
|
||||
app(TenantContext::class)->set($tenant);
|
||||
app(TenantConfig::class)->refresh();
|
||||
|
||||
return $tenant;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Filament\Operator\Pages\SystemSettingsPage;
|
||||
use App\Models\SystemSetting;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Support\Settings;
|
||||
use App\Support\SystemSettings;
|
||||
use App\Tenancy\TenantConfig;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Filament\Facades\Filament;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Settings of the whole installation, owned by the operator. They are the baseline a landlord may tighten
|
||||
* but not exceed, so they have to win over the .env and lose to nobody's landlord.
|
||||
*/
|
||||
class SystemSettingsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
SystemSettings::forget();
|
||||
}
|
||||
|
||||
public function test_a_stored_value_wins_over_the_env_and_an_empty_one_gives_it_back(): void
|
||||
{
|
||||
config(['fewo.spam.total_per_hour' => 30]);
|
||||
|
||||
SystemSettings::save(['fewo.spam.total_per_hour' => '120']);
|
||||
$this->assertSame(120, config('fewo.spam.total_per_hour'));
|
||||
$this->assertSame(120, SystemSettings::get('fewo.spam.total_per_hour'));
|
||||
|
||||
SystemSettings::save(['fewo.spam.total_per_hour' => '']);
|
||||
config(['fewo.spam.total_per_hour' => 30]);
|
||||
SystemSettings::apply();
|
||||
|
||||
$this->assertSame(30, config('fewo.spam.total_per_hour'), 'Leer = der Wert der .env gilt wieder.');
|
||||
$this->assertSame(0, SystemSetting::query()->count());
|
||||
}
|
||||
|
||||
public function test_a_secret_is_stored_encrypted(): void
|
||||
{
|
||||
SystemSettings::save(['mail.mailers.smtp.password' => 'geheim']);
|
||||
|
||||
$stored = DB::table('system_settings')->where('key', 'mail.mailers.smtp.password')->first();
|
||||
|
||||
$this->assertNotSame('geheim', $stored?->value);
|
||||
$this->assertTrue((bool) $stored?->is_secret);
|
||||
$this->assertSame('geheim', SystemSettings::get('mail.mailers.smtp.password'));
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole point of the ceiling: what the operator sets here binds every landlord.
|
||||
*/
|
||||
public function test_the_stored_limit_becomes_the_ceiling_for_a_landlord(): void
|
||||
{
|
||||
config(['fewo.guest_retention_years' => 10]);
|
||||
SystemSettings::save(['fewo.guest_retention_years' => '4']);
|
||||
|
||||
$tenant = Tenant::factory()->create(['guest_retention_years' => 9]);
|
||||
app(TenantContext::class)->set($tenant);
|
||||
app(TenantConfig::class)->refresh();
|
||||
|
||||
$this->assertSame(4, config('fewo.guest_retention_years'), 'Der Mandant darf die Obergrenze nicht überschreiten.');
|
||||
}
|
||||
|
||||
public function test_the_operator_edits_the_settings_and_a_landlords_administrator_cannot_reach_the_page(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create();
|
||||
app(TenantContext::class)->set($tenant);
|
||||
|
||||
$admin = User::factory()->create();
|
||||
$this->actingAs($admin)->get('/betreiber/einstellungen')->assertForbidden();
|
||||
|
||||
$admin->forceFill(['is_operator' => true])->saveQuietly();
|
||||
$this->actingAs($admin);
|
||||
Filament::setCurrentPanel('operator');
|
||||
|
||||
$this->get('/betreiber/einstellungen')->assertOk()->assertSee('Systemweite Einstellungen');
|
||||
|
||||
Livewire::test(SystemSettingsPage::class)
|
||||
->set('data.fewo__spam__total_per_hour', '77')
|
||||
->set('data.fewo__mail_redirect_to', 'auffang@example.com')
|
||||
->call('save')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$this->assertSame(77, SystemSettings::get('fewo.spam.total_per_hour'));
|
||||
$this->assertSame('auffang@example.com', config('fewo.mail_redirect_to'));
|
||||
}
|
||||
|
||||
/**
|
||||
* The hard redirect is the net that keeps a test server from writing to real guests. It is editable on
|
||||
* purpose, so it must be obvious that emptying it hands the decision back to each landlord.
|
||||
*/
|
||||
public function test_emptying_the_hard_redirect_leaves_only_the_landlords_own_test_mode(): void
|
||||
{
|
||||
SystemSettings::save(['fewo.mail_redirect_to' => 'auffang@example.com']);
|
||||
|
||||
$live = Tenant::factory()->create(['operating_mode' => 'live', 'notification_emails' => 'wirt@example.com']);
|
||||
app(TenantContext::class)->set($live);
|
||||
|
||||
$this->assertSame('auffang@example.com', Settings::mailRedirect());
|
||||
|
||||
SystemSettings::save(['fewo.mail_redirect_to' => '']);
|
||||
|
||||
$this->assertNull(Settings::mailRedirect(), 'Ohne harte Umleitung entscheidet der Mandant allein.');
|
||||
}
|
||||
}
|
||||
@@ -133,8 +133,10 @@ public function test_a_suspended_landlord_is_closed_except_for_the_operator(): v
|
||||
app(TenantContext::class)->set($tenant);
|
||||
$admin = User::factory()->create();
|
||||
|
||||
$this->get('/')->assertNotFound();
|
||||
$this->actingAs($admin)->get('/admin')->assertNotFound();
|
||||
// Visitors and the landlord's own people see a notice, not a dead link; 503 keeps the pages in the
|
||||
// search index, because a suspended landlord is a temporary state.
|
||||
$this->get('/')->assertStatus(503)->assertSee('nicht erreichbar');
|
||||
$this->actingAs($admin)->get('/admin')->assertStatus(503);
|
||||
|
||||
$admin->forceFill(['is_operator' => true])->saveQuietly();
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Filament\Operator\Tenants\Pages\CreateTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\EditTenant;
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Filament\Facades\Filament;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Setting a landlord up is the operator's job: the hosting and the addresses are theirs. A landlord the
|
||||
* operator created must be reachable straight away – otherwise nobody can get in to finish the job.
|
||||
*/
|
||||
class TenantProvisioningTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->withoutVite();
|
||||
}
|
||||
|
||||
public function test_a_landlord_created_by_the_operator_is_reachable_at_once(): void
|
||||
{
|
||||
$this->asOperator();
|
||||
|
||||
Livewire::test(CreateTenant::class)
|
||||
->fillForm([
|
||||
'name' => 'Ferienhaus Düne',
|
||||
'slug' => 'duene',
|
||||
'is_active' => true,
|
||||
'websites' => [['name' => 'Ferienhaus Düne', 'hosts' => ['duene.test', 'www.duene.test']]],
|
||||
])
|
||||
->call('create')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$tenant = Tenant::query()->where('slug', 'duene')->sole();
|
||||
$site = Site::withoutGlobalScope('tenant')->where('tenant_id', $tenant->id)->sole();
|
||||
|
||||
$this->assertSame(['duene.test', 'www.duene.test'], $site->domains()->orderBy('host')->pluck('host')->all());
|
||||
$this->assertSame('duene.test', $site->domain, 'Die erste Adresse ist die Hauptadresse.');
|
||||
|
||||
// Without a home page the website would answer 404 and the landlord could never get in.
|
||||
$this->assertTrue(
|
||||
app(TenantContext::class)->run($tenant, fn (): bool => $site->pages()->where('slug', Page::HOME)->exists()),
|
||||
);
|
||||
|
||||
$this->get('http://duene.test/')->assertOk()->assertSee('Ferienhaus Düne');
|
||||
$this->get('http://www.duene.test/')->assertOk();
|
||||
}
|
||||
|
||||
public function test_a_suspended_landlord_shows_a_notice_instead_of_a_dead_link(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create(['is_active' => true]);
|
||||
$site = $this->websiteFor($tenant, 'duene.test');
|
||||
$this->assertNotNull($site);
|
||||
|
||||
Tenant::factory()->create(); // a second landlord, so hosts really decide
|
||||
|
||||
$this->get('http://duene.test/')->assertOk();
|
||||
|
||||
$tenant->update(['is_active' => false, 'suspended_message' => 'Die Vermietung pausiert bis Frühjahr.']);
|
||||
|
||||
$response = $this->get('http://duene.test/');
|
||||
$response->assertStatus(503);
|
||||
$response->assertSee('Die Vermietung pausiert bis Frühjahr.');
|
||||
$response->assertSee('nicht erreichbar');
|
||||
}
|
||||
|
||||
public function test_the_default_notice_applies_when_none_was_written(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create(['is_active' => false]);
|
||||
$this->websiteFor($tenant, 'duene.test');
|
||||
Tenant::factory()->create();
|
||||
|
||||
$this->get('http://duene.test/')->assertStatus(503)->assertSee('Bitte versuchen Sie es später noch einmal.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Links on a website have to carry the address the visitor arrived on. APP_URL is a single value, so
|
||||
* without this every link of a second landlord would point at the first landlord's host.
|
||||
*/
|
||||
public function test_links_carry_the_address_the_visitor_came_in_on(): void
|
||||
{
|
||||
config(['app.url' => 'https://erster.test']);
|
||||
$first = Tenant::factory()->create();
|
||||
$this->websiteFor($first, 'erster.test');
|
||||
|
||||
$second = Tenant::factory()->create();
|
||||
$this->websiteFor($second, 'zweiter.test');
|
||||
|
||||
$html = $this->get('http://zweiter.test/')->assertOk()->getContent();
|
||||
|
||||
$this->assertStringNotContainsString('erster.test', (string) $html);
|
||||
}
|
||||
|
||||
public function test_the_operator_adds_an_address_to_an_existing_landlord(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create();
|
||||
$site = $this->websiteFor($tenant, 'duene.test');
|
||||
Tenant::factory()->create();
|
||||
|
||||
$this->get('http://neu.duene.test/')->assertNotFound();
|
||||
|
||||
$this->asOperator();
|
||||
|
||||
Livewire::test(EditTenant::class, ['record' => $tenant->getRouteKey()])
|
||||
->fillForm(['websites' => [[
|
||||
'id' => $site->id,
|
||||
'name' => $site->name,
|
||||
'hosts' => ['duene.test', 'neu.duene.test'],
|
||||
]]])
|
||||
->call('save')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$this->get('http://neu.duene.test/')->assertOk();
|
||||
$this->get('http://duene.test/')->assertOk();
|
||||
}
|
||||
|
||||
private function asOperator(): void
|
||||
{
|
||||
$operator = User::factory()->create();
|
||||
$operator->forceFill(['is_operator' => true])->saveQuietly();
|
||||
$this->actingAs($operator);
|
||||
Filament::setCurrentPanel('operator');
|
||||
}
|
||||
|
||||
private function websiteFor(Tenant $tenant, string $host): Site
|
||||
{
|
||||
return app(TenantContext::class)->run($tenant, function () use ($tenant, $host): Site {
|
||||
$site = Site::query()->create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'name' => 'Website von '.$tenant->name,
|
||||
'domain' => $host,
|
||||
'is_default' => true,
|
||||
'theme' => config('themes.base'),
|
||||
]);
|
||||
|
||||
Page::query()->create([
|
||||
'site_id' => $site->id,
|
||||
'slug' => Page::HOME,
|
||||
'title' => $site->name,
|
||||
'sections' => [],
|
||||
'is_published' => true,
|
||||
]);
|
||||
|
||||
return $site;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* A service the operator has locked must not be reachable by any route: not by the scheduler, not by the
|
||||
* public feed, and not by a user whose role would otherwise allow it.
|
||||
*/
|
||||
class TenantServiceGateTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_a_locked_portal_service_stops_the_import_and_the_feed(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create();
|
||||
app(TenantContext::class)->set($tenant);
|
||||
$channel = Channel::factory()->create();
|
||||
|
||||
$this->assertTrue($channel->importsOccupations());
|
||||
$this->get(route('channels.feed', ['token' => $channel->export_token]))->assertOk();
|
||||
|
||||
$this->lock($tenant, TenantServiceKey::PortalSync);
|
||||
|
||||
$this->assertFalse($channel->fresh()->importsOccupations());
|
||||
$this->get(route('channels.feed', ['token' => $channel->export_token]))->assertNotFound();
|
||||
}
|
||||
|
||||
public function test_the_sync_command_skips_a_landlord_without_the_service(): void
|
||||
{
|
||||
$allowed = Tenant::factory()->create(['name' => 'Mit Dienst']);
|
||||
$locked = Tenant::factory()->create(['name' => 'Ohne Dienst']);
|
||||
|
||||
app(TenantContext::class)->set($allowed);
|
||||
$allowedChannel = Channel::factory()->create();
|
||||
|
||||
app(TenantContext::class)->set($locked);
|
||||
$lockedChannel = Channel::factory()->create();
|
||||
$this->lock($locked, TenantServiceKey::PortalSync);
|
||||
|
||||
app(TenantContext::class)->forget();
|
||||
|
||||
$this->assertTrue($allowedChannel->fresh()->importsOccupations());
|
||||
$this->assertFalse($lockedChannel->fresh()->importsOccupations());
|
||||
}
|
||||
|
||||
public function test_a_locked_service_closes_the_admin_screens_whatever_the_role_says(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create();
|
||||
app(TenantContext::class)->set($tenant);
|
||||
|
||||
$admin = User::factory()->role(UserRole::Admin)->create();
|
||||
$this->actingAs($admin);
|
||||
|
||||
$this->assertTrue(Gate::forUser($admin)->allows('viewAny', ChannelTask::class));
|
||||
|
||||
$this->lock($tenant, TenantServiceKey::PortalSync);
|
||||
$this->lock($tenant, TenantServiceKey::PortalMail);
|
||||
|
||||
$this->assertFalse(Gate::forUser($admin)->allows('viewAny', ChannelTask::class));
|
||||
$this->assertFalse(Gate::forUser($admin)->allows('viewAny', PortalEmail::class));
|
||||
|
||||
// The role itself is untouched – the landlord simply does not have the service.
|
||||
$this->assertTrue(Gate::forUser($admin)->allows('viewAny', Booking::class));
|
||||
}
|
||||
|
||||
public function test_the_mailbox_fast_path_stays_open_while_only_the_sync_is_locked(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create();
|
||||
app(TenantContext::class)->set($tenant);
|
||||
|
||||
$admin = User::factory()->role(UserRole::Admin)->create();
|
||||
|
||||
$this->lock($tenant, TenantServiceKey::PortalSync);
|
||||
|
||||
$this->assertTrue(Gate::forUser($admin)->allows('viewAny', PortalEmail::class));
|
||||
}
|
||||
|
||||
public function test_the_system_page_shows_the_limits_and_stays_closed_for_a_landlords_administrator(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create(['name' => 'Beispiel GbR']);
|
||||
app(TenantContext::class)->set($tenant);
|
||||
config(['fewo.spam.total_per_hour' => 30, 'fewo.guest_retention_years' => 10]);
|
||||
|
||||
$admin = User::factory()->role(UserRole::Admin)->create();
|
||||
$this->actingAs($admin)->get('/betreiber/system')->assertForbidden();
|
||||
|
||||
$admin->forceFill(['is_operator' => true])->saveQuietly();
|
||||
|
||||
$this->actingAs($admin)->get('/betreiber/system')
|
||||
->assertOk()
|
||||
->assertSee('Beispiel GbR')
|
||||
->assertSee('30 je Stunde')
|
||||
->assertSee('10 Jahre');
|
||||
}
|
||||
|
||||
private function lock(Tenant $tenant, TenantServiceKey $service): void
|
||||
{
|
||||
$tenant->services()->updateOrCreate(['service' => $service->value], ['is_enabled' => false]);
|
||||
app(TenantFeatures::class)->forget($tenant);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Filament\Operator\Tenants\Pages\CreateTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\EditTenant;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Support\Content;
|
||||
use App\Support\Settings;
|
||||
use App\Tenancy\TenantConfig;
|
||||
use App\Tenancy\TenantContext;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
use Filament\Facades\Filament;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Phase 3: operating data and texts belong to the landlord, not to the installation.
|
||||
*/
|
||||
class TenantSettingsTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
public function test_each_landlord_has_its_own_imprint_bank_and_operating_mode(): void
|
||||
{
|
||||
config(['fewo.mail_redirect_to' => null]);
|
||||
|
||||
$first = Tenant::factory()->create([
|
||||
'bank_iban' => 'DE02120300000000202051',
|
||||
'operating_mode' => Settings::MODE_LIVE,
|
||||
'owner_name' => 'Brigitte Beispiel',
|
||||
]);
|
||||
$second = Tenant::factory()->create([
|
||||
'bank_iban' => 'DE02500105170137075030',
|
||||
'operating_mode' => Settings::MODE_TEST,
|
||||
'test_recipient' => 'test@zweiter.example',
|
||||
'owner_name' => 'Zweiter Vermieter',
|
||||
]);
|
||||
|
||||
$context = app(TenantContext::class);
|
||||
|
||||
$context->set($first);
|
||||
Content::save(['legal.imprint' => 'Impressum des ersten Vermieters']);
|
||||
$this->assertSame('Impressum des ersten Vermieters', Content::get('legal.imprint'));
|
||||
$this->assertSame('DE02120300000000202051', config('fewo.bank.iban'));
|
||||
$this->assertSame('Brigitte Beispiel', config('fewo.owner.name'));
|
||||
$this->assertTrue(Settings::isLive());
|
||||
$this->assertNull(Settings::mailRedirect());
|
||||
|
||||
$context->set($second);
|
||||
$this->assertNull(Content::get('legal.imprint'));
|
||||
Content::save(['legal.imprint' => 'Impressum des zweiten Vermieters']);
|
||||
$this->assertSame('DE02500105170137075030', config('fewo.bank.iban'));
|
||||
$this->assertSame('Zweiter Vermieter', config('fewo.owner.name'));
|
||||
$this->assertFalse(Settings::isLive());
|
||||
$this->assertSame('test@zweiter.example', Settings::mailRedirect());
|
||||
|
||||
$context->set($first);
|
||||
$this->assertSame('Impressum des ersten Vermieters', Content::get('legal.imprint'));
|
||||
}
|
||||
|
||||
public function test_without_a_landlord_the_configuration_of_the_installation_applies(): void
|
||||
{
|
||||
config(['fewo.owner.name' => 'Aus der Konfiguration']);
|
||||
$first = Tenant::factory()->create(['owner_name' => 'Brigitte Beispiel']);
|
||||
Tenant::factory()->create();
|
||||
|
||||
$context = app(TenantContext::class);
|
||||
$context->set($first);
|
||||
$this->assertSame('Brigitte Beispiel', config('fewo.owner.name'));
|
||||
|
||||
$context->forget();
|
||||
$this->assertSame('Aus der Konfiguration', config('fewo.owner.name'));
|
||||
$this->assertNull(Settings::tenant());
|
||||
}
|
||||
|
||||
public function test_only_services_the_application_really_asks_about_are_offered(): void
|
||||
{
|
||||
$this->assertSame(
|
||||
[TenantServiceKey::PortalSync, TenantServiceKey::PortalMail],
|
||||
TenantServiceKey::wired(),
|
||||
);
|
||||
|
||||
foreach (TenantServiceKey::cases() as $service) {
|
||||
if (! $service->isWired()) {
|
||||
$this->assertFalse($service->enabledByDefault(), $service->value.' darf nicht vorgegeben an sein, solange nichts danach fragt.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function test_a_landlord_without_a_decision_keeps_the_portal_services(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create();
|
||||
|
||||
$this->assertSame(0, $tenant->services()->count());
|
||||
$this->assertTrue(app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $tenant));
|
||||
$this->assertFalse(app(TenantFeatures::class)->enabled(TenantServiceKey::AiOffers, $tenant));
|
||||
}
|
||||
|
||||
public function test_the_operator_creates_a_landlord_in_the_operator_panel(): void
|
||||
{
|
||||
$existing = Tenant::factory()->create();
|
||||
app(TenantContext::class)->set($existing);
|
||||
$operator = User::factory()->create();
|
||||
$operator->forceFill(['is_operator' => true])->saveQuietly();
|
||||
$this->actingAs($operator);
|
||||
Filament::setCurrentPanel('operator');
|
||||
|
||||
$this->get('/betreiber/tenants')->assertOk()->assertSee('Neuen Mandanten anlegen');
|
||||
$this->get('/betreiber/tenants/create')->assertOk();
|
||||
|
||||
Livewire::test(CreateTenant::class)
|
||||
->fillForm([
|
||||
'name' => 'Ferienhaus Düne',
|
||||
'slug' => 'duene',
|
||||
'is_active' => true,
|
||||
'websites' => [['name' => 'Ferienhaus Düne', 'hosts' => ['duene.example']]],
|
||||
'services.'.TenantServiceKey::PortalSync->value.'.is_enabled' => true,
|
||||
'services.'.TenantServiceKey::PortalMail->value.'.is_enabled' => false,
|
||||
])
|
||||
->call('create')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$created = Tenant::query()->where('slug', 'duene')->sole();
|
||||
|
||||
$this->assertSame('Ferienhaus Düne', $created->name);
|
||||
$this->assertTrue(app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $created));
|
||||
$this->assertFalse(app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $created));
|
||||
|
||||
// A new landlord must not inherit anything from the one the operator happened to be looking at.
|
||||
$this->assertNull($created->contact_email);
|
||||
$this->assertSame(Settings::MODE_TEST, $created->operating_mode);
|
||||
}
|
||||
|
||||
public function test_the_operator_switches_a_service_on_the_tenant_form(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create();
|
||||
app(TenantContext::class)->set($tenant);
|
||||
$operator = User::factory()->create();
|
||||
$operator->forceFill(['is_operator' => true])->saveQuietly();
|
||||
$this->actingAs($operator);
|
||||
Filament::setCurrentPanel('operator');
|
||||
|
||||
Livewire::test(EditTenant::class, ['record' => $tenant->getRouteKey()])
|
||||
->fillForm([
|
||||
'services.'.TenantServiceKey::PortalSync->value.'.is_enabled' => false,
|
||||
'services.'.TenantServiceKey::PortalMail->value.'.is_enabled' => true,
|
||||
])
|
||||
->call('save')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$this->assertFalse($tenant->services()->where('service', TenantServiceKey::PortalSync->value)->sole()->is_enabled);
|
||||
$this->assertTrue($tenant->services()->where('service', TenantServiceKey::PortalMail->value)->sole()->is_enabled);
|
||||
$this->assertSame(0, $tenant->services()->where('service', TenantServiceKey::AiOffers->value)->count());
|
||||
|
||||
$this->assertFalse(app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $tenant));
|
||||
}
|
||||
|
||||
/**
|
||||
* The data a new landlord starts with comes from the installation, never from the landlord that happens
|
||||
* to be current – otherwise the migration would copy one landlord's address into the next one.
|
||||
*/
|
||||
public function test_the_defaults_of_a_new_landlord_come_from_the_configuration_not_from_the_current_one(): void
|
||||
{
|
||||
config(['fewo.owner.name' => 'Aus der Konfiguration', 'fewo.owner.email' => 'konfiguration@example.com']);
|
||||
|
||||
$current = Tenant::factory()->create(['owner_name' => 'Erster Vermieter', 'contact_email' => 'erster@example.com']);
|
||||
app(TenantContext::class)->set($current);
|
||||
$this->assertSame('Erster Vermieter', config('fewo.owner.name'));
|
||||
|
||||
$next = Tenant::factory()->create();
|
||||
|
||||
$this->assertSame('Aus der Konfiguration', $next->owner_name);
|
||||
$this->assertSame('konfiguration@example.com', $next->contact_email);
|
||||
}
|
||||
|
||||
public function test_the_landlord_of_the_context_decides_the_sender(): void
|
||||
{
|
||||
$tenant = Tenant::factory()->create(['sender_email' => 'versand@vermieter.example', 'sender_name' => 'Vermieter']);
|
||||
|
||||
app(TenantContext::class)->set($tenant);
|
||||
app(TenantConfig::class)->refresh();
|
||||
|
||||
$this->assertSame(['versand@vermieter.example', 'Vermieter'], [config('mail.from.address'), config('mail.from.name')]);
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,17 @@
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Actions\SendOffer;
|
||||
use App\Filament\Operator\Tenants\Pages\EditTenant;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Page;
|
||||
use App\Models\Property;
|
||||
use App\Models\Site;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Livewire\Features\SupportTesting\Testable;
|
||||
use Livewire\Livewire;
|
||||
use Tests\TestCase;
|
||||
|
||||
class WebsiteTenancyTest extends TestCase
|
||||
@@ -40,6 +45,42 @@ public function test_a_second_landlord_is_reached_only_on_their_own_address(): v
|
||||
$this->get('http://unbekannt.test/')->assertNotFound();
|
||||
}
|
||||
|
||||
/**
|
||||
* The trap that would take a live site down: as long as there is one landlord every address works, so
|
||||
* nobody notices that no host is entered. The second landlord turns every unentered address into a 404 –
|
||||
* including "www", which is a host of its own.
|
||||
*/
|
||||
public function test_a_website_answers_on_every_address_entered_for_it(): void
|
||||
{
|
||||
$site = $this->website('Nordhaus', 'nordhaus.test');
|
||||
$this->website('Südheim', 'suedheim.test');
|
||||
|
||||
$this->get('http://www.nordhaus.test/')->assertNotFound();
|
||||
|
||||
$this->editHosts($site, ['www.nordhaus.test', 'https://ALT.nordhaus.test/'])->assertHasNoFormErrors();
|
||||
|
||||
$this->get('http://nordhaus.test/')->assertOk()->assertSee('Nordhaus');
|
||||
$this->get('http://www.nordhaus.test/')->assertOk()->assertSee('Nordhaus');
|
||||
$this->get('http://alt.nordhaus.test/')->assertOk()->assertSee('Nordhaus');
|
||||
$this->get('http://unbekannt.test/')->assertNotFound();
|
||||
|
||||
$this->assertSame(
|
||||
['alt.nordhaus.test', 'nordhaus.test', 'www.nordhaus.test'],
|
||||
$site->domains()->orderBy('host')->pluck('host')->all(),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_a_host_of_another_website_cannot_be_taken_over(): void
|
||||
{
|
||||
$nord = $this->website('Nordhaus', 'nordhaus.test');
|
||||
$sued = $this->website('Südheim', 'suedheim.test');
|
||||
|
||||
$this->editHosts($nord, ['suedheim.test'])->assertHasFormErrors();
|
||||
|
||||
$this->get('http://suedheim.test/')->assertOk()->assertSee('Südheim')->assertDontSee('Nordhaus');
|
||||
$this->assertSame([$sued->id], $sued->domains()->pluck('site_id')->all());
|
||||
}
|
||||
|
||||
public function test_the_offer_link_uses_the_website_address(): void
|
||||
{
|
||||
$site = $this->website('Nordhaus', 'nordhaus.test');
|
||||
@@ -55,6 +96,28 @@ public function test_the_offer_link_uses_the_website_address(): void
|
||||
$this->assertStringContainsString('signature=', $url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enters the addresses the way they are really entered: by the operator, on the landlord. The form's
|
||||
* own defences are under test with them.
|
||||
*
|
||||
* @param list<string> $hosts
|
||||
*/
|
||||
private function editHosts(Site $site, array $hosts): Testable
|
||||
{
|
||||
$operator = User::factory()->create();
|
||||
$operator->forceFill(['is_operator' => true])->saveQuietly();
|
||||
$this->actingAs($operator);
|
||||
Filament::setCurrentPanel('operator');
|
||||
|
||||
return Livewire::test(EditTenant::class, ['record' => $site->tenant->getRouteKey()])
|
||||
->fillForm(['websites' => [[
|
||||
'id' => $site->id,
|
||||
'name' => $site->name,
|
||||
'hosts' => [$site->domain, ...$hosts],
|
||||
]]])
|
||||
->call('save');
|
||||
}
|
||||
|
||||
private function website(string $name, ?string $domain = null): Site
|
||||
{
|
||||
$tenant = Tenant::factory()->create();
|
||||
|
||||
Reference in new issue
Block a user