Compare commits
25
Commits
No files matched your search
@@ -73,3 +73,14 @@ FEWO_BANK_BIC=
|
||||
FEWO_BANK_NAME=
|
||||
FEWO_REVIEW_REQUEST_AFTER_DAYS=2
|
||||
FEWO_GUEST_RETENTION_YEARS=10
|
||||
FEWO_CHANNEL_STALE_AFTER_MINUTES=60
|
||||
FEWO_CHANNEL_TASK_REMINDER_AFTER_MINUTES=120
|
||||
FEWO_HEALTH_TOKEN=
|
||||
FEWO_AUTOMATION_WEBHOOK_URL=
|
||||
FEWO_AUTOMATION_SECRET=
|
||||
FEWO_MAILBOX_HOST=
|
||||
FEWO_MAILBOX_PORT=993
|
||||
FEWO_MAILBOX_ENCRYPTION=ssl
|
||||
FEWO_MAILBOX_USERNAME=
|
||||
FEWO_MAILBOX_PASSWORD=
|
||||
FEWO_MAILBOX_FOLDER=INBOX
|
||||
@@ -0,0 +1,63 @@
|
||||
# Production settings – copy to <DEPLOY_PATH>/shared/.env on the server and fill in.
|
||||
# Generate APP_KEY locally once: php artisan key:generate --show
|
||||
|
||||
APP_NAME="Ferienwohnung Stommer"
|
||||
APP_ENV=production
|
||||
APP_KEY=
|
||||
APP_DEBUG=false
|
||||
APP_URL=https://www.fewo-stommer.de
|
||||
APP_TIMEZONE=Europe/Berlin
|
||||
APP_LOCALE=de
|
||||
APP_FALLBACK_LOCALE=de
|
||||
APP_FAKER_LOCALE=de_DE
|
||||
APP_MAINTENANCE_DRIVER=file
|
||||
|
||||
LOG_CHANNEL=daily
|
||||
LOG_LEVEL=warning
|
||||
|
||||
# Strato MariaDB 11.8 (Kundenlogin › Datenbanken und Webspace › Datenbanken verwalten)
|
||||
DB_CONNECTION=mariadb
|
||||
DB_HOST=
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=
|
||||
DB_USERNAME=
|
||||
DB_PASSWORD=
|
||||
|
||||
SESSION_DRIVER=database
|
||||
SESSION_LIFETIME=120
|
||||
SESSION_SECURE_COOKIE=true
|
||||
CACHE_STORE=database
|
||||
QUEUE_CONNECTION=sync
|
||||
FILESYSTEM_DISK=local
|
||||
|
||||
# Strato mailbox fewo@stommer.de
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=smtp.strato.de
|
||||
MAIL_PORT=465
|
||||
MAIL_SCHEME=smtps
|
||||
MAIL_USERNAME=fewo@stommer.de
|
||||
MAIL_PASSWORD=
|
||||
MAIL_FROM_ADDRESS="fewo@stommer.de"
|
||||
MAIL_FROM_NAME="${APP_NAME}"
|
||||
|
||||
FEWO_OWNER_NAME="Brigitte Stommer"
|
||||
FEWO_OWNER_EMAIL=fewo@stommer.de
|
||||
FEWO_NOTIFICATION_EMAIL=fewo@stommer.de
|
||||
FEWO_BANK_ACCOUNT_HOLDER=
|
||||
FEWO_BANK_IBAN=
|
||||
FEWO_BANK_BIC=
|
||||
FEWO_BANK_NAME=
|
||||
|
||||
# Portal booking e-mails (fast path)
|
||||
FEWO_MAILBOX_HOST=imap.strato.de
|
||||
FEWO_MAILBOX_PORT=993
|
||||
FEWO_MAILBOX_ENCRYPTION=ssl
|
||||
FEWO_MAILBOX_USERNAME=fewo@stommer.de
|
||||
FEWO_MAILBOX_PASSWORD=
|
||||
FEWO_MAILBOX_FOLDER=INBOX
|
||||
|
||||
# Monitoring / automation (long random values, e.g. php -r "echo bin2hex(random_bytes(24));")
|
||||
FEWO_HEALTH_TOKEN=
|
||||
FEWO_SCHEDULER_TOKEN=
|
||||
FEWO_AUTOMATION_SECRET=
|
||||
FEWO_AUTOMATION_WEBHOOK_URL=
|
||||
@@ -0,0 +1,105 @@
|
||||
# Tests on every push; deployment to Strato for tags "v*" or by hand (Gitea › Actions › Deploy › Run workflow).
|
||||
# Needs a Gitea act_runner (e.g. on the private server) and these repository secrets:
|
||||
# DEPLOY_SSH_KEY private key whose public key is stored at Strato (SFTP & SSH)
|
||||
# DEPLOY_HOST package-specific SSH server, e.g. 51539426.ssh.w1.strato.hosting (not ssh.strato.de)
|
||||
# DEPLOY_USER SSH user from the Strato customer login
|
||||
# DEPLOY_PATH e.g. fewo-production
|
||||
# DEPLOY_PHP e.g. /opt/RZphp84/bin/php-cli
|
||||
# DEPLOY_URL e.g. https://www.fewo-stommer.de
|
||||
name: Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
environment:
|
||||
description: Ziel
|
||||
type: choice
|
||||
options: [production, staging]
|
||||
default: production
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
mariadb:
|
||||
image: mariadb:11.8
|
||||
env:
|
||||
MARIADB_DATABASE: fewo_test
|
||||
MARIADB_ROOT_PASSWORD: test
|
||||
ports: ['3306:3306']
|
||||
options: >-
|
||||
--health-cmd="healthcheck.sh --connect --innodb_initialized"
|
||||
--health-interval=5s --health-timeout=5s --health-retries=20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.4'
|
||||
extensions: mbstring, intl, gd, exif, zip, pdo_sqlite, sqlite3, pdo_mysql, fileinfo, openssl
|
||||
tools: composer:v2
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
|
||||
- name: Install
|
||||
run: |
|
||||
composer install --no-interaction --no-progress --prefer-dist
|
||||
npm ci --no-audit --no-fund
|
||||
npm run build
|
||||
cp .env.example .env
|
||||
php artisan key:generate
|
||||
|
||||
- name: Tests (SQLite)
|
||||
run: php artisan test --compact
|
||||
|
||||
- name: Tests (MariaDB 11.8, wie auf Strato)
|
||||
env:
|
||||
DB_CONNECTION: mariadb
|
||||
DB_HOST: 127.0.0.1
|
||||
DB_PORT: '3306'
|
||||
DB_DATABASE: fewo_test
|
||||
DB_USERNAME: root
|
||||
DB_PASSWORD: test
|
||||
run: php artisan test --compact
|
||||
|
||||
deploy:
|
||||
needs: test
|
||||
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.4'
|
||||
extensions: mbstring, intl, gd, exif, zip, fileinfo, openssl
|
||||
tools: composer:v2
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
|
||||
- name: SSH key
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
printf '%s\n' "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy_key
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
ssh-keyscan -H "${{ secrets.DEPLOY_HOST }}" >> ~/.ssh/known_hosts
|
||||
|
||||
- name: Deploy
|
||||
env:
|
||||
DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
|
||||
DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
|
||||
DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }}
|
||||
DEPLOY_PHP: ${{ secrets.DEPLOY_PHP }}
|
||||
DEPLOY_URL: ${{ secrets.DEPLOY_URL }}
|
||||
run: |
|
||||
export DEPLOY_SSH_KEY="$HOME/.ssh/deploy_key"
|
||||
bash scripts/deploy.sh "${{ inputs.environment || 'production' }}" deploy
|
||||
@@ -28,3 +28,7 @@ _ide_helper.php
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
Thumbs.db
|
||||
|
||||
# Deployment settings with access data
|
||||
/scripts/deploy.*.env
|
||||
!/scripts/deploy.example.env
|
||||
@@ -10,7 +10,11 @@ # Ferienwohnung Stommer
|
||||
- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded.
|
||||
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
|
||||
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
|
||||
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/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 admins via `RequireTwoFactorForAdmins`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
|
||||
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
|
||||
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
|
||||
|
||||
@@ -10,7 +10,11 @@ # Ferienwohnung Stommer
|
||||
- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded.
|
||||
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
|
||||
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
|
||||
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/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 admins via `RequireTwoFactorForAdmins`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
|
||||
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
|
||||
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\BookingConfirmed;
|
||||
@@ -11,11 +12,16 @@
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* The landlord accepts a reservation. Expired reservations can still be confirmed while the dates are free.
|
||||
* The landlord accepts a reservation: the booking becomes binding, payment due dates are fixed,
|
||||
* the rental contract is generated and sent with the confirmation.
|
||||
* Expired reservations can still be confirmed while the dates are free.
|
||||
*/
|
||||
class ConfirmBooking
|
||||
{
|
||||
public function __construct(private AvailabilityChecker $availability) {}
|
||||
public function __construct(
|
||||
private AvailabilityChecker $availability,
|
||||
private RentalContract $contract,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
@@ -35,9 +41,12 @@ public function handle(Booking $booking, bool $notifyGuest = true): void
|
||||
'status' => BookingStatus::Confirmed,
|
||||
'hold_expires_at' => null,
|
||||
'confirmed_at' => now(),
|
||||
'deposit_due_on' => today()->addDays(config('fewo.deposit_due_days'))->toDateString(),
|
||||
]);
|
||||
});
|
||||
|
||||
$this->contract->generate($booking);
|
||||
|
||||
if ($notifyGuest) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Creates blocking/unblocking tasks for every portal that must be maintained by hand
|
||||
* (e.g. instant booking portals whose calendar import is too slow), notifies the landlord
|
||||
* and hands the task to an optional external automation.
|
||||
*/
|
||||
class CreateChannelTasks
|
||||
{
|
||||
/**
|
||||
* @return list<ChannelTask>
|
||||
*/
|
||||
public function handle(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn, ChannelTaskAction $action, string $reason, ?int $exceptChannelId = null): array
|
||||
{
|
||||
if ($endsOn->lessThanOrEqualTo(today())) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$channels = $property->channels()->active()
|
||||
->where('requires_manual_blocking', true)
|
||||
->when($exceptChannelId, fn ($query) => $query->whereKeyNot($exceptChannelId))
|
||||
->get();
|
||||
|
||||
$tasks = $channels->map(fn (Channel $channel): ChannelTask => $channel->tasks()->create([
|
||||
'action' => $action,
|
||||
'starts_on' => $startsOn->toDateString(),
|
||||
'ends_on' => $endsOn->toDateString(),
|
||||
'reason' => $reason,
|
||||
]))->all();
|
||||
|
||||
if ($tasks === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelTasksNotification($tasks)));
|
||||
|
||||
foreach ($tasks as $task) {
|
||||
$this->sendToAutomation($task);
|
||||
}
|
||||
|
||||
return $tasks;
|
||||
}
|
||||
|
||||
/**
|
||||
* POSTs the task to the automation webhook, signed with HMAC-SHA256 (header X-Signature).
|
||||
* The automation confirms via the signed callback URL contained in the payload.
|
||||
*/
|
||||
public function sendToAutomation(ChannelTask $task): void
|
||||
{
|
||||
$url = config('fewo.automation.webhook_url');
|
||||
$secret = config('fewo.automation.secret');
|
||||
if (blank($url) || blank($secret)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$body = json_encode([
|
||||
'task_id' => $task->id,
|
||||
'channel' => $task->channel->name,
|
||||
'connector' => $task->channel->connector,
|
||||
'action' => $task->action->value,
|
||||
'starts_on' => $task->starts_on->toDateString(),
|
||||
'ends_on' => $task->ends_on->toDateString(),
|
||||
'manage_url' => $task->channel->manage_url,
|
||||
'callback_url' => URL::route('channel-tasks.complete', $task),
|
||||
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
try {
|
||||
Http::timeout(10)
|
||||
->withHeaders(['X-Signature' => hash_hmac('sha256', $body, $secret)])
|
||||
->withBody($body, 'application/json')
|
||||
->post($url)
|
||||
->throw();
|
||||
|
||||
$task->update(['automation_sent_at' => now(), 'automation_error' => null]);
|
||||
} catch (Throwable $exception) {
|
||||
$task->update(['automation_error' => $exception->getMessage()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
use App\Pricing\PriceCalculator;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\StayRequest;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
@@ -30,13 +31,14 @@ public function __construct(
|
||||
|
||||
/**
|
||||
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
|
||||
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution where the guest came from
|
||||
*
|
||||
* @throws QuoteException
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true): Booking
|
||||
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
|
||||
{
|
||||
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source): Booking {
|
||||
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
|
||||
Property::whereKey($property->getKey())->lockForUpdate()->first();
|
||||
|
||||
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
|
||||
@@ -52,6 +54,7 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
|
||||
'guest_id' => $guest->id,
|
||||
'status' => BookingStatus::Reserved,
|
||||
'source' => $source,
|
||||
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
|
||||
'arrival' => $stay->arrival->toDateString(),
|
||||
'departure' => $stay->departure->toDateString(),
|
||||
'guests' => $stay->guests,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Mail\ChannelSyncAlert;
|
||||
use App\Mail\MailboxAlert;
|
||||
use App\Models\Channel;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Alerts the landlord once per incident when a portal import or the mailbox fast path fails
|
||||
* or has not succeeded for too long. The alert is reset by the next success.
|
||||
*/
|
||||
class MonitorChannels
|
||||
{
|
||||
private const MAILBOX_ALERTED_KEY = 'mailbox:alerted';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$channels = Channel::query()->active()->whereNull('alerted_at')->get()
|
||||
->filter(fn (Channel $channel): bool => $channel->isStale());
|
||||
|
||||
foreach ($channels as $channel) {
|
||||
Mail::to(config('fewo.notification_email'))->send(new ChannelSyncAlert($channel));
|
||||
$channel->forceFill(['alerted_at' => now()])->save();
|
||||
}
|
||||
|
||||
return $channels->count() + $this->monitorMailbox();
|
||||
}
|
||||
|
||||
public static function mailboxIsStale(): bool
|
||||
{
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$lastSuccess = Cache::get(MailboxReader::LAST_SUCCESS_KEY);
|
||||
|
||||
return $lastSuccess === null
|
||||
|| CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes')));
|
||||
}
|
||||
|
||||
private function monitorMailbox(): int
|
||||
{
|
||||
if (! self::mailboxIsStale()) {
|
||||
Cache::forget(self::MAILBOX_ALERTED_KEY);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (Cache::has(self::MAILBOX_ALERTED_KEY)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new MailboxAlert(Cache::get(MailboxReader::LAST_ERROR_KEY)));
|
||||
Cache::forever(self::MAILBOX_ALERTED_KEY, true);
|
||||
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ConflictDetector;
|
||||
use App\Channels\Mail\ParsedPortalMail;
|
||||
use App\Channels\Mail\PortalMail;
|
||||
use App\Channels\Mail\PortalMailParser;
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\PortalEmailType;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Mail\PortalMailNotification;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\PortalEmail;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Fast path for portal bookings: the notification e-mail usually arrives within a minute, long before
|
||||
* the portal's calendar export is read. A recognised booking is blocked immediately; the later calendar
|
||||
* sync confirms the block. Anything not recognised with confidence is flagged for review – never guessed.
|
||||
*/
|
||||
class ProcessPortalMail
|
||||
{
|
||||
public function __construct(
|
||||
private PortalMailParser $parser,
|
||||
private ConflictDetector $conflictDetector,
|
||||
) {}
|
||||
|
||||
public function handle(PortalMail $mail): ?PortalEmail
|
||||
{
|
||||
if (PortalEmail::where('message_id', $mail->messageId)->exists()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$channel = $this->channelFor($mail->from);
|
||||
if ($channel === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parsed = $this->parser->parse($mail->subject, $mail->text);
|
||||
$conflicts = [];
|
||||
|
||||
$record = DB::transaction(function () use ($mail, $channel, $parsed, &$conflicts): PortalEmail {
|
||||
[$status, $block, $note] = match ($parsed->type) {
|
||||
PortalEmailType::Booking => $this->block($channel, $parsed, $conflicts),
|
||||
PortalEmailType::Cancellation => $this->release($channel, $parsed),
|
||||
PortalEmailType::Inquiry => [PortalEmailStatus::Ignored, null, 'Anfrage – keine Sperre nötig.'],
|
||||
PortalEmailType::Unknown => [PortalEmailStatus::NeedsReview, null, 'Inhalt nicht erkannt.'],
|
||||
};
|
||||
|
||||
return PortalEmail::create([
|
||||
'channel_id' => $channel->id,
|
||||
'message_id' => $mail->messageId,
|
||||
'from' => mb_substr($mail->from, 0, 255),
|
||||
'subject' => mb_substr($mail->subject, 0, 255),
|
||||
'received_at' => $mail->receivedAt,
|
||||
'type' => $parsed->type,
|
||||
'status' => $status,
|
||||
'starts_on' => $parsed->startsOn?->toDateString(),
|
||||
'ends_on' => $parsed->endsOn?->toDateString(),
|
||||
'reference' => $parsed->reference,
|
||||
'blocked_period_id' => $block?->id,
|
||||
'excerpt' => mb_substr(trim(preg_replace('/\s+/u', ' ', strip_tags($mail->text))), 0, 500),
|
||||
'note' => $note,
|
||||
]);
|
||||
});
|
||||
|
||||
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new PortalMailNotification($record)));
|
||||
}
|
||||
|
||||
if ($conflicts !== []) {
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelConflict($channel, $conflicts)));
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Channels list the sender addresses or domains of their notification e-mails in settings.email_senders.
|
||||
*/
|
||||
public function channelFor(string $from): ?Channel
|
||||
{
|
||||
$from = mb_strtolower($from);
|
||||
|
||||
return Channel::query()->active()->get()->first(function (Channel $channel) use ($from): bool {
|
||||
foreach ($this->senders($channel) as $sender) {
|
||||
if (str_contains($from, $sender)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function senders(Channel $channel): array
|
||||
{
|
||||
return array_values(array_filter(array_map(
|
||||
fn (string $sender): string => mb_strtolower(trim($sender)),
|
||||
explode(',', (string) $channel->setting('email_senders')),
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $conflicts
|
||||
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
|
||||
*/
|
||||
private function block(Channel $channel, ParsedPortalMail $parsed, array &$conflicts): array
|
||||
{
|
||||
if (! $parsed->hasPeriod()) {
|
||||
return [PortalEmailStatus::NeedsReview, null, 'Buchung erkannt, aber An-/Abreise nicht sicher lesbar.'];
|
||||
}
|
||||
|
||||
$known = $channel->blockedPeriods()
|
||||
->whereDate('starts_on', $parsed->startsOn)
|
||||
->whereDate('ends_on', $parsed->endsOn)
|
||||
->first();
|
||||
if ($known) {
|
||||
return [PortalEmailStatus::AlreadyKnown, $known, null];
|
||||
}
|
||||
|
||||
$block = $channel->blockedPeriods()->create([
|
||||
'property_id' => $channel->property_id,
|
||||
'starts_on' => $parsed->startsOn->toDateString(),
|
||||
'ends_on' => $parsed->endsOn->toDateString(),
|
||||
'reason' => "{$channel->name} (E-Mail)".($parsed->reference ? ": {$parsed->reference}" : ''),
|
||||
'source' => 'email',
|
||||
'external_uid' => 'email:'.($parsed->reference ?? $parsed->startsOn->format('Ymd').'-'.$parsed->endsOn->format('Ymd')),
|
||||
]);
|
||||
|
||||
$conflicts = $this->conflictDetector->conflictsFor($block);
|
||||
|
||||
return [PortalEmailStatus::Blocked, $block, null];
|
||||
}
|
||||
|
||||
/**
|
||||
* Only blocks created from e-mails are released here; calendar blocks disappear with the next sync.
|
||||
*
|
||||
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
|
||||
*/
|
||||
private function release(Channel $channel, ParsedPortalMail $parsed): array
|
||||
{
|
||||
$emailBlocks = $channel->blockedPeriods()->where('source', 'email');
|
||||
|
||||
$block = match (true) {
|
||||
$parsed->reference !== null => (clone $emailBlocks)->where('external_uid', 'email:'.$parsed->reference)->first(),
|
||||
$parsed->hasPeriod() => (clone $emailBlocks)->whereDate('starts_on', $parsed->startsOn)->whereDate('ends_on', $parsed->endsOn)->first(),
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($block) {
|
||||
$block->delete();
|
||||
|
||||
return [PortalEmailStatus::Released, null, 'Sperre aus E-Mail aufgehoben.'];
|
||||
}
|
||||
|
||||
return [PortalEmailStatus::NeedsReview, null, 'Stornierung erkannt – bitte prüfen; Kalender-Sperren verschwinden mit dem nächsten Abgleich.'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\PaymentMethod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Payment;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Records a received payment (or a refund with a negative amount) and moves the booking along:
|
||||
* Bestätigt → Anzahlung erhalten → Bezahlt.
|
||||
*/
|
||||
class RecordPayment
|
||||
{
|
||||
public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null): Payment
|
||||
{
|
||||
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy): Payment {
|
||||
$payment = $booking->payments()->create([
|
||||
'amount' => $amount,
|
||||
'paid_on' => $paidOn->toDateString(),
|
||||
'method' => $method,
|
||||
'note' => $note,
|
||||
'recorded_by' => $recordedBy,
|
||||
]);
|
||||
|
||||
$booking->unsetRelation('payments');
|
||||
$this->updateStatus($booking);
|
||||
|
||||
return $payment;
|
||||
});
|
||||
}
|
||||
|
||||
public function updateStatus(Booking $booking): void
|
||||
{
|
||||
$paymentStatuses = [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid];
|
||||
if (! in_array($booking->status, $paymentStatuses, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$paid = $booking->paidAmount();
|
||||
$status = match (true) {
|
||||
$paid >= $booking->total => BookingStatus::Paid,
|
||||
$paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid,
|
||||
default => BookingStatus::Confirmed,
|
||||
};
|
||||
|
||||
if ($status !== $booking->status) {
|
||||
$booking->update(['status' => $status]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\ChannelTask;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Reminds the landlord once about blocking tasks that are still open after the reminder time.
|
||||
*/
|
||||
class RemindChannelTasks
|
||||
{
|
||||
public function handle(): int
|
||||
{
|
||||
$tasks = ChannelTask::query()
|
||||
->open()
|
||||
->whereNull('reminded_at')
|
||||
->where('created_at', '<=', now()->subMinutes(config('fewo.channels.task_reminder_after_minutes')))
|
||||
->with('channel')
|
||||
->get();
|
||||
|
||||
if ($tasks->isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new ChannelTasksNotification($tasks->all(), reminder: true));
|
||||
ChannelTask::whereKey($tasks->modelKeys())->update(['reminded_at' => now()]);
|
||||
|
||||
return $tasks->count();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Mail\ArrivalInformation;
|
||||
use App\Mail\PaymentReminder;
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Daily booking workflow: payment requests and reminders, arrival information, completion after departure.
|
||||
* Every message is sent at most once per booking.
|
||||
*/
|
||||
class SendBookingReminders
|
||||
{
|
||||
private const BALANCE_REQUEST_DAYS_BEFORE = 7;
|
||||
|
||||
private const ARRIVAL_INFO_DAYS_BEFORE = 7;
|
||||
|
||||
/**
|
||||
* @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int}
|
||||
*/
|
||||
public function handle(): array
|
||||
{
|
||||
$today = today();
|
||||
$unpaid = [BookingStatus::Confirmed, BookingStatus::DepositPaid];
|
||||
|
||||
$depositOverdue = $this->bookings(fn (Builder $query) => $query
|
||||
->where('status', BookingStatus::Confirmed)
|
||||
->whereNull('deposit_reminded_at')
|
||||
->whereDate('deposit_due_on', '<', $today))
|
||||
->filter(fn (Booking $booking): bool => $booking->openDeposit() > 0);
|
||||
$this->remind($depositOverdue, PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at');
|
||||
|
||||
$balanceRequest = $this->bookings(fn (Builder $query) => $query
|
||||
->whereIn('status', $unpaid)
|
||||
->whereNull('balance_requested_at')
|
||||
->whereDate('balance_due_on', '>=', $today)
|
||||
->whereDate('balance_due_on', '<=', $today->copy()->addDays(self::BALANCE_REQUEST_DAYS_BEFORE)))
|
||||
->filter(fn (Booking $booking): bool => ! $booking->requiresFullPayment() && $booking->openAmount() > 0 && $booking->status === BookingStatus::DepositPaid);
|
||||
$this->remind($balanceRequest, PaymentReminder::BALANCE_REQUEST, 'balance_requested_at');
|
||||
|
||||
$balanceOverdue = $this->bookings(fn (Builder $query) => $query
|
||||
->whereIn('status', $unpaid)
|
||||
->whereNull('balance_reminded_at')
|
||||
->whereDate('balance_due_on', '<', $today))
|
||||
->filter(fn (Booking $booking): bool => $booking->openAmount() > 0 && ($booking->status === BookingStatus::DepositPaid || $booking->requiresFullPayment()));
|
||||
$this->remind($balanceOverdue, PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at');
|
||||
|
||||
$arrivals = $this->bookings(fn (Builder $query) => $query
|
||||
->whereIn('status', BookingStatus::occupying())
|
||||
->whereNull('arrival_info_sent_at')
|
||||
->whereDate('arrival', '>=', $today)
|
||||
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_DAYS_BEFORE)));
|
||||
foreach ($arrivals as $booking) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
|
||||
$booking->update(['arrival_info_sent_at' => now()]);
|
||||
}
|
||||
|
||||
$completed = Booking::query()
|
||||
->where('status', BookingStatus::Paid)
|
||||
->whereDate('departure', '<', $today)
|
||||
->get();
|
||||
$completed->each->update(['status' => BookingStatus::Completed]);
|
||||
|
||||
return [
|
||||
'deposit_overdue' => $depositOverdue->count(),
|
||||
'balance_request' => $balanceRequest->count(),
|
||||
'balance_overdue' => $balanceOverdue->count(),
|
||||
'arrival_info' => $arrivals->count(),
|
||||
'completed' => $completed->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(Builder<Booking>): Builder<Booking> $constraints
|
||||
* @return Collection<int, Booking>
|
||||
*/
|
||||
private function bookings(callable $constraints): Collection
|
||||
{
|
||||
return $constraints(Booking::query()->with(['guest', 'property', 'payments']))
|
||||
->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at'))
|
||||
->get()
|
||||
->toBase();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Booking> $bookings
|
||||
*/
|
||||
private function remind(Collection $bookings, string $kind, string $sentAtColumn): void
|
||||
{
|
||||
foreach ($bookings as $booking) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind));
|
||||
$booking->update([$sentAtColumn => now()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ConflictDetector;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Imports the occupations of one portal as blocked periods and reports overlaps with
|
||||
* occupations from anywhere else immediately (possible double booking).
|
||||
*/
|
||||
class SyncChannel
|
||||
{
|
||||
public function __construct(private ConflictDetector $conflictDetector = new ConflictDetector) {}
|
||||
|
||||
public function handle(Channel $channel): ChannelSyncLog
|
||||
{
|
||||
$startedAt = microtime(true);
|
||||
|
||||
try {
|
||||
$periods = $channel->connector()->fetchOccupations($channel);
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$channel->forceFill(['last_synced_at' => now(), 'last_error' => $exception->getMessage()])->save();
|
||||
|
||||
return $channel->syncLogs()->create([
|
||||
'successful' => false,
|
||||
'message' => $exception->getMessage(),
|
||||
'duration_ms' => $this->elapsed($startedAt),
|
||||
]);
|
||||
}
|
||||
|
||||
$today = CarbonImmutable::today();
|
||||
$suffix = config('channels.uid_suffix');
|
||||
$periods = array_values(array_filter(
|
||||
$periods,
|
||||
fn (ExternalPeriod $period): bool => $period->endsOn->greaterThan($today) && ! str_ends_with($period->uid, $suffix),
|
||||
));
|
||||
|
||||
$counts = ['added' => 0, 'changed' => 0, 'removed' => 0];
|
||||
$conflicts = [];
|
||||
|
||||
DB::transaction(function () use ($channel, $periods, $today, &$counts, &$conflicts): void {
|
||||
$existing = $channel->blockedPeriods()->where('source', 'channel')->get()->keyBy('external_uid');
|
||||
$fromEmails = $channel->blockedPeriods()->where('source', 'email')->get();
|
||||
$seen = [];
|
||||
|
||||
foreach ($periods as $period) {
|
||||
$seen[$period->uid] = true;
|
||||
$block = $existing->get($period->uid);
|
||||
|
||||
if ($block && $block->starts_on->equalTo($period->startsOn) && $block->ends_on->equalTo($period->endsOn)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attributes = [
|
||||
'property_id' => $channel->property_id,
|
||||
'starts_on' => $period->startsOn->toDateString(),
|
||||
'ends_on' => $period->endsOn->toDateString(),
|
||||
'reason' => "{$channel->name}".($period->summary ? ": {$period->summary}" : ''),
|
||||
'source' => 'channel',
|
||||
];
|
||||
|
||||
$confirmedEmailBlock = $block ? null : $fromEmails->first(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->equalTo($period->startsOn) && $emailBlock->ends_on->equalTo($period->endsOn));
|
||||
|
||||
if ($confirmedEmailBlock) {
|
||||
// Already blocked from the portal's e-mail; the calendar only confirms it.
|
||||
$confirmedEmailBlock->update([...$attributes, 'external_uid' => $period->uid]);
|
||||
$fromEmails = $fromEmails->reject(fn (BlockedPeriod $emailBlock): bool => $emailBlock->is($confirmedEmailBlock));
|
||||
$counts['changed']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($block) {
|
||||
$block->update($attributes);
|
||||
$counts['changed']++;
|
||||
} else {
|
||||
$block = $channel->blockedPeriods()->create([...$attributes, 'external_uid' => $period->uid]);
|
||||
$counts['added']++;
|
||||
}
|
||||
|
||||
// E-mail blocks of this portal overlapping the calendar entry describe the same booking with deviating dates.
|
||||
$superseded = $fromEmails->filter(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->lessThan($block->ends_on) && $emailBlock->ends_on->greaterThan($block->starts_on));
|
||||
$superseded->each->delete();
|
||||
$fromEmails = $fromEmails->diff($superseded);
|
||||
|
||||
array_push($conflicts, ...$this->conflictDetector->conflictsFor($block));
|
||||
}
|
||||
|
||||
$stale = $existing->reject(fn (BlockedPeriod $block, string $uid): bool => isset($seen[$uid]) || $block->ends_on->lessThanOrEqualTo($today));
|
||||
$stale->each->delete();
|
||||
$counts['removed'] = $stale->count();
|
||||
});
|
||||
|
||||
$channel->forceFill([
|
||||
'last_synced_at' => now(),
|
||||
'last_success_at' => now(),
|
||||
'last_error' => null,
|
||||
'alerted_at' => null,
|
||||
])->save();
|
||||
|
||||
if ($conflicts !== []) {
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelConflict($channel, $conflicts)));
|
||||
}
|
||||
|
||||
return $channel->syncLogs()->create([
|
||||
'successful' => true,
|
||||
'events' => count($periods),
|
||||
...$counts,
|
||||
'conflicts' => count($conflicts),
|
||||
'duration_ms' => $this->elapsed($startedAt),
|
||||
]);
|
||||
}
|
||||
|
||||
private function elapsed(float $startedAt): int
|
||||
{
|
||||
return (int) round((microtime(true) - $startedAt) * 1000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Availability;
|
||||
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Free gaps in the calendar: runs of free nights with an occupied night (booking or block) directly
|
||||
* before and after. Open-ended free periods (nothing booked behind them yet) are not gaps.
|
||||
*/
|
||||
class GapFinder
|
||||
{
|
||||
/** How far around a stay we look for the neighbouring occupations. */
|
||||
private const LOOKAROUND_NIGHTS = 60;
|
||||
|
||||
public function __construct(private AvailabilityChecker $availability = new AvailabilityChecker) {}
|
||||
|
||||
/**
|
||||
* Length in nights of the gap that contains the whole stay, or null if the stay is not inside a gap
|
||||
* (because a night is occupied or the free period is not closed on both sides).
|
||||
*/
|
||||
public function gapContaining(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure): ?int
|
||||
{
|
||||
$from = $arrival->subDays(self::LOOKAROUND_NIGHTS);
|
||||
$until = $departure->addDays(self::LOOKAROUND_NIGHTS);
|
||||
$occupied = $this->availability->occupiedNights($property, $from, $until);
|
||||
|
||||
for ($night = $arrival; $night->lessThan($departure); $night = $night->addDay()) {
|
||||
if (isset($occupied[$night->toDateString()])) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$start = $arrival;
|
||||
while (! isset($occupied[$start->subDay()->toDateString()])) {
|
||||
$start = $start->subDay();
|
||||
if ($start->lessThanOrEqualTo($from)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$end = $departure;
|
||||
while (! isset($occupied[$end->toDateString()])) {
|
||||
$end = $end->addDay();
|
||||
if ($end->greaterThanOrEqualTo($until)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return (int) $start->diffInDays($end);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gaps of 1 … $maxNights nights starting within [$from, $until), as [arrival, departure] pairs.
|
||||
*
|
||||
* @return list<array{0: CarbonImmutable, 1: CarbonImmutable}>
|
||||
*/
|
||||
public function gaps(Property $property, CarbonImmutable $from, CarbonImmutable $until, int $maxNights): array
|
||||
{
|
||||
$occupied = $this->availability->occupiedNights($property, $from->subDay(), $until->addDays($maxNights + 1));
|
||||
|
||||
$gaps = [];
|
||||
$night = $from;
|
||||
while ($night->lessThan($until)) {
|
||||
$isGapStart = ! isset($occupied[$night->toDateString()]) && isset($occupied[$night->subDay()->toDateString()]);
|
||||
if (! $isGapStart) {
|
||||
$night = $night->addDay();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$end = $night;
|
||||
while (! isset($occupied[$end->toDateString()]) && $night->diffInDays($end) <= $maxNights) {
|
||||
$end = $end->addDay();
|
||||
}
|
||||
|
||||
if (isset($occupied[$end->toDateString()]) && $night->diffInDays($end) <= $maxNights) {
|
||||
$gaps[] = [$night, $end];
|
||||
}
|
||||
|
||||
$night = $end->addDay();
|
||||
}
|
||||
|
||||
return $gaps;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use App\Channels\Contracts\ChannelConnector;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Resolves the connectors registered in config/channels.php.
|
||||
*/
|
||||
class ChannelRegistry
|
||||
{
|
||||
/**
|
||||
* @return array<string, class-string<ChannelConnector>>
|
||||
*/
|
||||
public function connectors(): array
|
||||
{
|
||||
return collect(config('channels.connectors'))
|
||||
->mapWithKeys(fn (string $class): array => [$class::key() => $class])
|
||||
->all();
|
||||
}
|
||||
|
||||
public function resolve(string $key): ChannelConnector
|
||||
{
|
||||
$class = $this->connectors()[$key] ?? throw new InvalidArgumentException("Unknown channel connector [{$key}].");
|
||||
|
||||
return app($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function options(): array
|
||||
{
|
||||
return array_map(fn (string $class): string => $class::label(), $this->connectors());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class ChannelSyncException extends RuntimeException {}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
|
||||
/**
|
||||
* Finds occupations from other sources that overlap a block reported by a portal
|
||||
* (a possible double booking). Blocks of the same portal never conflict with each other.
|
||||
*/
|
||||
class ConflictDetector
|
||||
{
|
||||
/**
|
||||
* @return list<string> human readable descriptions
|
||||
*/
|
||||
public function conflictsFor(BlockedPeriod $block): array
|
||||
{
|
||||
$property = $block->property;
|
||||
$channelName = $block->channel->name ?? 'Sperre';
|
||||
$period = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y');
|
||||
|
||||
$bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get()
|
||||
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guest->full_name}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
|
||||
|
||||
$blocks = $property->blockedPeriods()
|
||||
->overlapping($block->starts_on, $block->ends_on)
|
||||
->whereKeyNot($block->getKey())
|
||||
->when($block->channel_id, fn ($query) => $query->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $block->channel_id)))
|
||||
->with('channel')
|
||||
->get()
|
||||
->map(fn (BlockedPeriod $other): string => "{$channelName} meldet {$period}, überschneidet sich mit Sperre „".($other->channel->name ?? $other->reason ?? 'manuell')."“ ({$other->starts_on->format('d.m.Y')} – {$other->ends_on->format('d.m.Y')})");
|
||||
|
||||
return [...$bookings->all(), ...$blocks->all()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Contracts;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use App\Models\Channel;
|
||||
use Filament\Schemas\Components\Component;
|
||||
|
||||
/**
|
||||
* Connects one kind of portal or channel manager. Register implementations in config/channels.php.
|
||||
*/
|
||||
interface ChannelConnector
|
||||
{
|
||||
/**
|
||||
* Stable identifier stored on the channel, e.g. "ical".
|
||||
*/
|
||||
public static function key(): string;
|
||||
|
||||
public static function label(): string;
|
||||
|
||||
/**
|
||||
* Admin form fields for the connector's settings; use state paths below "settings.".
|
||||
*
|
||||
* @return list<Component>
|
||||
*/
|
||||
public static function settingsSchema(): array;
|
||||
|
||||
/**
|
||||
* Whether occupations can currently be imported (e.g. an import URL is configured).
|
||||
*/
|
||||
public function canImport(Channel $channel): bool;
|
||||
|
||||
/**
|
||||
* All occupations the portal currently reports.
|
||||
*
|
||||
* @return list<ExternalPeriod>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
public function fetchOccupations(Channel $channel): array;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* An occupation reported by a portal: nights from startsOn up to (excluding) endsOn.
|
||||
*/
|
||||
final readonly class ExternalPeriod
|
||||
{
|
||||
public function __construct(
|
||||
public string $uid,
|
||||
public CarbonImmutable $startsOn,
|
||||
public CarbonImmutable $endsOn,
|
||||
public ?string $summary = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Contracts\ChannelConnector;
|
||||
use App\Models\Channel;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
/**
|
||||
* Generic calendar connection that works with almost every portal: we read the portal's iCal export
|
||||
* and the portal reads our feed for this channel.
|
||||
*/
|
||||
class ICalConnector implements ChannelConnector
|
||||
{
|
||||
public function __construct(private ICalParser $parser) {}
|
||||
|
||||
public static function key(): string
|
||||
{
|
||||
return 'ical';
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Kalender-Abgleich (iCal)';
|
||||
}
|
||||
|
||||
public static function settingsSchema(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('settings.import_url')
|
||||
->label('iCal-Export-Adresse des Portals')
|
||||
->helperText('Im Vermieterbereich des Portals unter „Kalender exportieren“. Leer lassen, wenn das Portal keinen Kalender anbietet.')
|
||||
->url()
|
||||
->maxLength(2048),
|
||||
];
|
||||
}
|
||||
|
||||
public function canImport(Channel $channel): bool
|
||||
{
|
||||
return filled($channel->setting('import_url'));
|
||||
}
|
||||
|
||||
public function fetchOccupations(Channel $channel): array
|
||||
{
|
||||
$url = preg_replace('#^webcals?://#i', 'https://', (string) $channel->setting('import_url'));
|
||||
|
||||
try {
|
||||
$response = Http::timeout(20)
|
||||
->retry(2, 1000)
|
||||
->withHeaders(['Accept' => 'text/calendar'])
|
||||
->get($url)
|
||||
->throw();
|
||||
} catch (ConnectionException|RequestException $exception) {
|
||||
throw new ChannelSyncException('Kalender konnte nicht abgerufen werden: '.$exception->getMessage(), previous: $exception);
|
||||
}
|
||||
|
||||
return $this->parser->parse($response->body());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
|
||||
/**
|
||||
* The calendar a portal imports from us: every occupation of the property except the ones that
|
||||
* came from this very portal (otherwise the portal would block its own bookings twice).
|
||||
* Events carry no guest data.
|
||||
*/
|
||||
class ICalFeed
|
||||
{
|
||||
public function build(Channel $channel): string
|
||||
{
|
||||
$property = $channel->property;
|
||||
$from = CarbonImmutable::today()->subDays(30);
|
||||
$until = CarbonImmutable::today()->addYears(2);
|
||||
$suffix = config('channels.uid_suffix');
|
||||
|
||||
$events = [];
|
||||
|
||||
foreach ($property->bookings()->occupying()->overlapping($from, $until)->get() as $booking) {
|
||||
/** @var Booking $booking */
|
||||
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at);
|
||||
}
|
||||
|
||||
$blocks = $property->blockedPeriods()
|
||||
->overlapping($from, $until)
|
||||
->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $channel->id))
|
||||
->get();
|
||||
|
||||
foreach ($blocks as $block) {
|
||||
$events[] = $this->event("block-{$block->id}{$suffix}", $block->starts_on, $block->ends_on, $block->updated_at);
|
||||
}
|
||||
|
||||
return implode("\r\n", [
|
||||
'BEGIN:VCALENDAR',
|
||||
'VERSION:2.0',
|
||||
'PRODID:-//Ferienwohnung Stommer//Belegung//DE',
|
||||
'CALSCALE:GREGORIAN',
|
||||
'METHOD:PUBLISH',
|
||||
'X-WR-CALNAME:'.$this->escape($property->name),
|
||||
...$events,
|
||||
'END:VCALENDAR',
|
||||
])."\r\n";
|
||||
}
|
||||
|
||||
private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified): string
|
||||
{
|
||||
return implode("\r\n", [
|
||||
'BEGIN:VEVENT',
|
||||
"UID:{$uid}",
|
||||
'DTSTAMP:'.($modified ?? now())->utc()->format('Ymd\THis\Z'),
|
||||
'DTSTART;VALUE=DATE:'.$start->format('Ymd'),
|
||||
'DTEND;VALUE=DATE:'.$end->format('Ymd'),
|
||||
'SUMMARY:Belegt',
|
||||
'TRANSP:OPAQUE',
|
||||
'END:VEVENT',
|
||||
]);
|
||||
}
|
||||
|
||||
private function escape(string $text): string
|
||||
{
|
||||
return str_replace(['\\', ';', ',', "\n"], ['\\\\', '\\;', '\\,', '\\n'], $text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Minimal RFC 5545 reader for availability feeds: VEVENTs with DTSTART/DTEND (date or date-time),
|
||||
* UID and SUMMARY. Cancelled events and events without a positive length are skipped.
|
||||
*/
|
||||
class ICalParser
|
||||
{
|
||||
/**
|
||||
* @return list<ExternalPeriod>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
public function parse(string $ics): array
|
||||
{
|
||||
if (! str_contains($ics, 'BEGIN:VCALENDAR')) {
|
||||
throw new ChannelSyncException('Die Antwort ist kein iCal-Kalender.');
|
||||
}
|
||||
|
||||
$lines = explode("\n", preg_replace("/\r?\n[ \t]/", '', str_replace("\r\n", "\n", $ics)));
|
||||
|
||||
$periods = [];
|
||||
$event = null;
|
||||
foreach ($lines as $line) {
|
||||
$line = rtrim($line, "\r");
|
||||
|
||||
if ($line === 'BEGIN:VEVENT') {
|
||||
$event = [];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($line === 'END:VEVENT') {
|
||||
if ($event !== null && ($period = $this->toPeriod($event))) {
|
||||
$periods[] = $period;
|
||||
}
|
||||
$event = null;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($event !== null && str_contains($line, ':')) {
|
||||
[$nameWithParams, $value] = explode(':', $line, 2);
|
||||
$parts = explode(';', $nameWithParams);
|
||||
$event[strtoupper($parts[0])] = ['value' => $value, 'params' => array_slice($parts, 1)];
|
||||
}
|
||||
}
|
||||
|
||||
return $periods;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array{value: string, params: list<string>}> $event
|
||||
*/
|
||||
private function toPeriod(array $event): ?ExternalPeriod
|
||||
{
|
||||
if (! isset($event['DTSTART']) || strtoupper($event['STATUS']['value'] ?? '') === 'CANCELLED') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$start = $this->toDate($event['DTSTART']);
|
||||
$end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start?->addDay();
|
||||
|
||||
if ($start === null || $end === null || $end->lessThanOrEqualTo($start)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$uid = $event['UID']['value'] ?? sha1($start->toDateString().'|'.$end->toDateString());
|
||||
|
||||
return new ExternalPeriod($uid, $start, $end, $this->unescape($event['SUMMARY']['value'] ?? null));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{value: string, params: list<string>} $property
|
||||
*/
|
||||
private function toDate(array $property): ?CarbonImmutable
|
||||
{
|
||||
$value = trim($property['value']);
|
||||
|
||||
if (preg_match('/^\d{8}$/', $value)) {
|
||||
return CarbonImmutable::createFromFormat('!Ymd', $value);
|
||||
}
|
||||
|
||||
if (preg_match('/^(\d{8})T(\d{6})(Z?)$/', $value, $match)) {
|
||||
$timezone = $match[3] === 'Z' ? 'UTC' : $this->timezone($property['params']);
|
||||
|
||||
return CarbonImmutable::createFromFormat('YmdHis', $match[1].$match[2], $timezone)
|
||||
->setTimezone(config('app.timezone'))
|
||||
->startOfDay();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $params
|
||||
*/
|
||||
private function timezone(array $params): string
|
||||
{
|
||||
foreach ($params as $param) {
|
||||
if (str_starts_with(strtoupper($param), 'TZID=')) {
|
||||
$tz = trim(substr($param, 5), '"');
|
||||
|
||||
return in_array($tz, timezone_identifiers_list(), true) ? $tz : config('app.timezone');
|
||||
}
|
||||
}
|
||||
|
||||
return config('app.timezone');
|
||||
}
|
||||
|
||||
private function unescape(?string $text): ?string
|
||||
{
|
||||
return $text === null ? null : str_replace(['\\n', '\\N', '\\,', '\\;', '\\\\'], ["\n", "\n", ',', ';', '\\'], $text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Throwable;
|
||||
use Webklex\PHPIMAP\ClientManager;
|
||||
use Webklex\PHPIMAP\Message;
|
||||
|
||||
/**
|
||||
* Reads recent e-mails of the given senders from the configured IMAP mailbox without marking them as read.
|
||||
* Works without the PHP imap extension.
|
||||
*/
|
||||
class MailboxReader
|
||||
{
|
||||
public const LAST_SUCCESS_KEY = 'mailbox:last_success_at';
|
||||
|
||||
public const LAST_ERROR_KEY = 'mailbox:last_error';
|
||||
|
||||
public static function isConfigured(): bool
|
||||
{
|
||||
return filled(config('fewo.mailbox.host')) && filled(config('fewo.mailbox.username'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $senders addresses or domains
|
||||
* @return list<PortalMail>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
public function fetch(array $senders): array
|
||||
{
|
||||
$config = config('fewo.mailbox');
|
||||
|
||||
try {
|
||||
$client = (new ClientManager)->make([
|
||||
'host' => $config['host'],
|
||||
'port' => $config['port'],
|
||||
'encryption' => $config['encryption'],
|
||||
'validate_cert' => true,
|
||||
'username' => $config['username'],
|
||||
'password' => $config['password'],
|
||||
'protocol' => 'imap',
|
||||
]);
|
||||
$client->connect();
|
||||
$folder = $client->getFolderByPath($config['folder']);
|
||||
|
||||
$mails = [];
|
||||
foreach ($senders as $sender) {
|
||||
$messages = $folder->query()
|
||||
->whereSince(CarbonImmutable::today()->subDays($config['lookback_days']))
|
||||
->whereFrom($sender)
|
||||
->leaveUnread()
|
||||
->get();
|
||||
|
||||
foreach ($messages as $message) {
|
||||
$mails[] = $this->toPortalMail($message);
|
||||
}
|
||||
}
|
||||
|
||||
$client->disconnect();
|
||||
} catch (Throwable $exception) {
|
||||
Cache::forever(self::LAST_ERROR_KEY, $exception->getMessage());
|
||||
|
||||
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
|
||||
}
|
||||
|
||||
Cache::forever(self::LAST_SUCCESS_KEY, now()->toIso8601String());
|
||||
Cache::forget(self::LAST_ERROR_KEY);
|
||||
|
||||
return $mails;
|
||||
}
|
||||
|
||||
private function toPortalMail(Message $message): PortalMail
|
||||
{
|
||||
$text = $message->getTextBody();
|
||||
if (trim($text) === '') {
|
||||
$text = strip_tags(preg_replace('#<(br|p|div|tr|li)[^>]*>#i', "\n", $message->getHTMLBody()));
|
||||
}
|
||||
|
||||
$from = $message->getFrom()->first();
|
||||
$date = $message->getDate()->first();
|
||||
|
||||
return new PortalMail(
|
||||
messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)),
|
||||
from: (string) ($from->mail ?? ''),
|
||||
subject: (string) $message->getSubject()->first(),
|
||||
text: $text,
|
||||
receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use App\Enums\PortalEmailType;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
final readonly class ParsedPortalMail
|
||||
{
|
||||
public function __construct(
|
||||
public PortalEmailType $type,
|
||||
public ?CarbonImmutable $startsOn = null,
|
||||
public ?CarbonImmutable $endsOn = null,
|
||||
public ?string $reference = null,
|
||||
) {}
|
||||
|
||||
public function hasPeriod(): bool
|
||||
{
|
||||
return $this->startsOn !== null && $this->endsOn !== null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook.
|
||||
*/
|
||||
final readonly class PortalMail
|
||||
{
|
||||
public function __construct(
|
||||
public string $messageId,
|
||||
public string $from,
|
||||
public string $subject,
|
||||
public string $text,
|
||||
public CarbonImmutable $receivedAt,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use App\Enums\PortalEmailType;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Reads booking notifications of portals (German and English). It only extracts what it can find
|
||||
* with confidence; everything else is left empty so that the e-mail is flagged for review.
|
||||
*/
|
||||
class PortalMailParser
|
||||
{
|
||||
private const CANCELLATION = ['storniert', 'stornierung', 'cancelled', 'canceled', 'cancellation', 'abgesagt'];
|
||||
|
||||
private const BOOKING = ['neue buchung', 'buchung bestätigt', 'buchungsbestätigung', 'reservierung bestätigt', 'sofortbuchung', 'hat gebucht', 'ist gebucht', 'new booking', 'booking confirmed', 'reservation confirmed', 'instant booking', 'you have a new reservation', 'neue reservierung'];
|
||||
|
||||
/** Checked before bookings: "Neue Buchungsanfrage" is not a confirmed booking. */
|
||||
private const INQUIRY = ['buchungsanfrage', 'booking request', 'reservation request', 'anfrage', 'inquiry', 'enquiry'];
|
||||
|
||||
private const MONTHS = [
|
||||
'jan' => 1, 'januar' => 1, 'january' => 1,
|
||||
'feb' => 2, 'februar' => 2, 'february' => 2,
|
||||
'mär' => 3, 'märz' => 3, 'mrz' => 3, 'mar' => 3, 'march' => 3,
|
||||
'apr' => 4, 'april' => 4,
|
||||
'mai' => 5, 'may' => 5,
|
||||
'jun' => 6, 'juni' => 6, 'june' => 6,
|
||||
'jul' => 7, 'juli' => 7, 'july' => 7,
|
||||
'aug' => 8, 'august' => 8,
|
||||
'sep' => 9, 'sept' => 9, 'september' => 9,
|
||||
'okt' => 10, 'oktober' => 10, 'oct' => 10, 'october' => 10,
|
||||
'nov' => 11, 'november' => 11,
|
||||
'dez' => 12, 'dezember' => 12, 'dec' => 12, 'december' => 12,
|
||||
];
|
||||
|
||||
public function parse(string $subject, string $text): ParsedPortalMail
|
||||
{
|
||||
$content = $this->normalize($subject."\n".$text);
|
||||
|
||||
$type = $this->type(mb_strtolower($subject))
|
||||
?? $this->type(mb_strtolower($this->normalize($text)))
|
||||
?? PortalEmailType::Unknown;
|
||||
|
||||
[$startsOn, $endsOn] = $this->period($content);
|
||||
|
||||
return new ParsedPortalMail($type, $startsOn, $endsOn, $this->reference($content));
|
||||
}
|
||||
|
||||
/**
|
||||
* The subject decides first; the body only when the subject is not conclusive.
|
||||
*/
|
||||
private function type(string $text): ?PortalEmailType
|
||||
{
|
||||
return match (true) {
|
||||
$this->containsAny($text, self::CANCELLATION) => PortalEmailType::Cancellation,
|
||||
$this->containsAny($text, self::INQUIRY) => PortalEmailType::Inquiry,
|
||||
$this->containsAny($text, self::BOOKING) => PortalEmailType::Booking,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{?CarbonImmutable, ?CarbonImmutable}
|
||||
*/
|
||||
private function period(string $content): array
|
||||
{
|
||||
$dates = $this->dates($content);
|
||||
|
||||
$arrival = $this->dateAfterLabel($content, $dates, '/\b(anreise|ankunft|check-?in|arrival)\b/iu');
|
||||
$departure = $this->dateAfterLabel($content, $dates, '/\b(abreise|check-?out|departure)\b/iu');
|
||||
|
||||
if ($arrival === null || $departure === null) {
|
||||
[$arrival, $departure] = $this->firstPlausiblePair($dates);
|
||||
}
|
||||
|
||||
if ($arrival === null || $departure === null || ! $this->isPlausible($arrival, $departure)) {
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
return [$arrival, $departure];
|
||||
}
|
||||
|
||||
/**
|
||||
* All dates in the text with their offsets, in order of appearance.
|
||||
*
|
||||
* @return list<array{offset: int, date: CarbonImmutable}>
|
||||
*/
|
||||
private function dates(string $content): array
|
||||
{
|
||||
$monthNames = implode('|', array_map(fn (string $name): string => preg_quote($name, '/'), array_keys(self::MONTHS)));
|
||||
$patterns = [
|
||||
'/\b(?<d>\d{1,2})\.(?<m>\d{1,2})\.(?<y>\d{4}|\d{2})\b/u',
|
||||
'/\b(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})\b/u',
|
||||
'/\b(?<d>\d{1,2})\.?\s+(?<mn>'.$monthNames.')\.?\s+(?<y>\d{4})\b/iu',
|
||||
'/\b(?<mn>'.$monthNames.')\.?\s+(?<d>\d{1,2}),?\s+(?<y>\d{4})\b/iu',
|
||||
];
|
||||
|
||||
$dates = [];
|
||||
foreach ($patterns as $pattern) {
|
||||
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
|
||||
foreach ($matches as $match) {
|
||||
$month = isset($match['mn']) && $match['mn'][0] !== '' ? self::MONTHS[mb_strtolower($match['mn'][0])] ?? null : (int) $match['m'][0];
|
||||
$year = (int) $match['y'][0];
|
||||
$year = $year < 100 ? 2000 + $year : $year;
|
||||
|
||||
if ($month !== null && checkdate($month, (int) $match['d'][0], $year)) {
|
||||
$dates[] = ['offset' => $match[0][1], 'date' => CarbonImmutable::create($year, $month, (int) $match['d'][0])];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
usort($dates, fn (array $a, array $b): int => $a['offset'] <=> $b['offset']);
|
||||
|
||||
return $dates;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{offset: int, date: CarbonImmutable}> $dates
|
||||
*/
|
||||
private function dateAfterLabel(string $content, array $dates, string $labelPattern): ?CarbonImmutable
|
||||
{
|
||||
if (! preg_match($labelPattern, $content, $label, PREG_OFFSET_CAPTURE)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$labelEnd = $label[0][1] + strlen($label[0][0]);
|
||||
foreach ($dates as $date) {
|
||||
if ($date['offset'] >= $labelEnd && $date['offset'] - $labelEnd <= 80) {
|
||||
return $date['date'];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{offset: int, date: CarbonImmutable}> $dates
|
||||
* @return array{?CarbonImmutable, ?CarbonImmutable}
|
||||
*/
|
||||
private function firstPlausiblePair(array $dates): array
|
||||
{
|
||||
foreach ($dates as $index => $first) {
|
||||
foreach (array_slice($dates, $index + 1) as $second) {
|
||||
if ($this->isPlausible($first['date'], $second['date'])) {
|
||||
return [$first['date'], $second['date']];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
private function isPlausible(CarbonImmutable $arrival, CarbonImmutable $departure): bool
|
||||
{
|
||||
return $departure->greaterThan($arrival)
|
||||
&& $arrival->diffInDays($departure) <= 90
|
||||
&& $arrival->greaterThanOrEqualTo(CarbonImmutable::today()->subDays(2))
|
||||
&& $arrival->lessThanOrEqualTo(CarbonImmutable::today()->addYears(3));
|
||||
}
|
||||
|
||||
private function reference(string $content): ?string
|
||||
{
|
||||
if (preg_match('/\b(HA-[A-Z0-9]{5,})\b/', $content, $match)) {
|
||||
return $match[1];
|
||||
}
|
||||
|
||||
if (preg_match('/(?:buchungsnummer|buchungs-nr\.?|reservierungsnummer|reservation id|reservation number|booking id|booking number)\s*[:#]?\s*([A-Z0-9][A-Z0-9-]{4,})/iu', $content, $match)) {
|
||||
return $match[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function normalize(string $text): string
|
||||
{
|
||||
$text = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
|
||||
|
||||
return preg_replace('/[ \t\x{00A0}\x{202F}]+/u', ' ', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $needles
|
||||
*/
|
||||
private function containsAny(string $haystack, array $needles): bool
|
||||
{
|
||||
foreach ($needles as $needle) {
|
||||
if (str_contains($haystack, $needle)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Themes\ThemeChecker;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('themes:check {theme? : Key des Themes (leer = alle)}')]
|
||||
#[Description('Check themes against the theme contract (docs/THEME-ERSTELLUNG.md): manifest, build, required markup, colours, contrast')]
|
||||
class CheckTheme extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ThemeRegistry $registry, ThemeChecker $checker): int
|
||||
{
|
||||
$key = $this->argument('theme');
|
||||
if ($key !== null && ! isset($registry->all()[$key])) {
|
||||
$this->error("Theme „{$key}“ nicht gefunden. Installiert: ".implode(', ', array_keys($registry->all())));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$themes = $key !== null ? [$registry->all()[$key]] : array_values($registry->all());
|
||||
$failed = false;
|
||||
|
||||
foreach ($themes as $theme) {
|
||||
['errors' => $errors, 'warnings' => $warnings] = $checker->check($theme);
|
||||
$this->line('');
|
||||
$this->line("<options=bold>{$theme->name}</> ({$theme->key} {$theme->version}".($theme->parent ? ", Eltern-Theme {$theme->parent}" : '').')');
|
||||
|
||||
foreach ($errors as $error) {
|
||||
$this->line(" <fg=red>✗</> {$error}");
|
||||
}
|
||||
foreach ($warnings as $warning) {
|
||||
$this->line(" <fg=yellow>!</> {$warning}");
|
||||
}
|
||||
if ($errors === [] && $warnings === []) {
|
||||
$this->line(' <fg=green>✓</> Alles in Ordnung.');
|
||||
}
|
||||
|
||||
$failed = $failed || $errors !== [];
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
use function Laravel\Prompts\password;
|
||||
use function Laravel\Prompts\select;
|
||||
use function Laravel\Prompts\text;
|
||||
|
||||
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content}')]
|
||||
#[Description('Create an admin panel account (the password is entered interactively and never passed as an argument)')]
|
||||
class CreateUser extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$email = $this->argument('email') ?? text('E-Mail-Adresse', required: true, validate: ['email' => 'email']);
|
||||
$email = mb_strtolower(trim($email));
|
||||
|
||||
if (User::where('email', $email)->exists()) {
|
||||
$this->error("Es gibt bereits einen Benutzer mit {$email}.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$name = $this->option('name') ?? text('Name', required: true);
|
||||
|
||||
$role = $this->option('role') !== null
|
||||
? UserRole::tryFrom($this->option('role'))
|
||||
: UserRole::from(select('Rolle', collect(UserRole::cases())->mapWithKeys(fn (UserRole $role): array => [$role->value => "{$role->getLabel()} – {$role->getDescription()}"])->all(), default: UserRole::Admin->value));
|
||||
|
||||
if ($role === null) {
|
||||
$this->error('Unbekannte Rolle. Erlaubt: '.implode(', ', array_column(UserRole::cases(), 'value')));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$password = password('Passwort (mind. 12 Zeichen)', required: true, validate: ['password' => Password::min(12)]);
|
||||
|
||||
if (password('Passwort wiederholen', required: true) !== $password) {
|
||||
$this->error('Die Passwörter stimmen nicht überein.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
|
||||
|
||||
$this->info("Benutzer {$email} ({$role->getLabel()}) angelegt.");
|
||||
|
||||
if ($role === UserRole::Admin) {
|
||||
$this->line('Bei der ersten Anmeldung wird die Zwei-Faktor-Anmeldung mit einer Authenticator-App eingerichtet.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\ProcessPortalMail;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('channels:fetch-mail')]
|
||||
#[Description('Read booking notifications of the portals from the mailbox and block recognised bookings immediately')]
|
||||
class FetchPortalMail extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail): int
|
||||
{
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
$this->line('Kein Postfach konfiguriert (FEWO_MAILBOX_HOST).');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$senders = Channel::query()->active()->get()
|
||||
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
if ($senders === []) {
|
||||
$this->line('Für kein Portal sind Absender hinterlegt.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
try {
|
||||
$mails = $reader->fetch($senders);
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
foreach ($mails as $mail) {
|
||||
if ($record = $processPortalMail->handle($mail)) {
|
||||
$this->info("{$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -8,41 +8,111 @@
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
|
||||
#[Signature('photos:import {directory : Folder with JPG/PNG/WebP files} {--category=apartment : apartment, outdoor or area}')]
|
||||
#[Description('Import all images of a folder as website photos (e.g. when migrating from the old website)')]
|
||||
#[Signature('photos:import {directory : Folder with JPG/PNG/WebP files} {--category=apartment : apartment, outdoor or area} {--manifest= : CSV "file;category;alt_text" with paths relative to the folder (chooses and describes the photos)}')]
|
||||
#[Description('Import images as website photos (e.g. when migrating from the old website); the source files are only read')]
|
||||
class ImportPhotos extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$directory = rtrim((string) $this->argument('directory'), '/\\');
|
||||
$entries = $this->option('manifest') !== null
|
||||
? $this->manifestEntries((string) $this->option('manifest'), $directory)
|
||||
: $this->folderEntries($directory);
|
||||
|
||||
if ($entries === null) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$propertyId = Property::query()->value('id');
|
||||
$sort = (int) Photo::max('sort_order');
|
||||
$imported = 0;
|
||||
|
||||
foreach ($entries as ['file' => $file, 'category' => $category, 'alt_text' => $altText]) {
|
||||
$source = str_replace('\\', '/', substr($file, strlen($directory) + 1));
|
||||
|
||||
if (! is_file($file)) {
|
||||
$this->warn("Fehlt: {$source}");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Media::query()->where('collection_name', Photo::COLLECTION)->where('custom_properties->source', $source)->exists()) {
|
||||
$this->line("– bereits vorhanden: {$source}");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$photo = Photo::create([
|
||||
'property_id' => $category === PhotoCategory::Area ? null : $propertyId,
|
||||
'category' => $category,
|
||||
'alt_text' => $altText,
|
||||
'sort_order' => ++$sort,
|
||||
]);
|
||||
$photo->addMedia($file)
|
||||
->preservingOriginal()
|
||||
->withCustomProperties(['source' => $source])
|
||||
->toMediaCollection(Photo::COLLECTION);
|
||||
|
||||
$imported++;
|
||||
$this->line("✓ {$photo->alt_text}");
|
||||
}
|
||||
|
||||
$this->info("{$imported} Bilder importiert.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{file: string, category: PhotoCategory, alt_text: string}>|null
|
||||
*/
|
||||
private function folderEntries(string $directory): ?array
|
||||
{
|
||||
$category = PhotoCategory::tryFrom((string) $this->option('category'));
|
||||
if ($category === null) {
|
||||
$this->error('Unbekannte Kategorie. Erlaubt: '.implode(', ', array_column(PhotoCategory::cases(), 'value')));
|
||||
|
||||
return self::FAILURE;
|
||||
return null;
|
||||
}
|
||||
|
||||
$files = glob(rtrim((string) $this->argument('directory'), '/\\').'/*.{jpg,jpeg,png,webp,JPG,JPEG,PNG,WEBP}', GLOB_BRACE) ?: [];
|
||||
$propertyId = $category === PhotoCategory::Area ? null : Property::query()->value('id');
|
||||
$sort = (int) Photo::max('sort_order');
|
||||
$files = glob($directory.'/*.{jpg,jpeg,png,webp,JPG,JPEG,PNG,WEBP}', GLOB_BRACE) ?: [];
|
||||
|
||||
foreach ($files as $file) {
|
||||
$photo = Photo::create([
|
||||
'property_id' => $propertyId,
|
||||
'category' => $category,
|
||||
'alt_text' => str(pathinfo($file, PATHINFO_FILENAME))->replace(['_', '-'], ' ')->squish()->ucfirst()->toString(),
|
||||
'sort_order' => ++$sort,
|
||||
]);
|
||||
$photo->addMedia($file)->preservingOriginal()->toMediaCollection(Photo::COLLECTION);
|
||||
return array_map(fn (string $file): array => [
|
||||
'file' => $file,
|
||||
'category' => $category,
|
||||
'alt_text' => str(pathinfo($file, PATHINFO_FILENAME))->replace(['_', '-'], ' ')->squish()->ucfirst()->toString(),
|
||||
], $files);
|
||||
}
|
||||
|
||||
$this->line("✓ {$photo->alt_text}");
|
||||
/**
|
||||
* @return list<array{file: string, category: PhotoCategory, alt_text: string}>|null
|
||||
*/
|
||||
private function manifestEntries(string $manifest, string $directory): ?array
|
||||
{
|
||||
if (! is_file($manifest)) {
|
||||
$this->error("Liste nicht gefunden: {$manifest}");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->info(count($files).' Bilder importiert.');
|
||||
$entries = [];
|
||||
foreach (array_slice(file($manifest, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [], 1) as $number => $line) {
|
||||
[$file, $category, $altText] = array_pad(str_getcsv($line, ';', '"', ''), 3, '');
|
||||
$category = PhotoCategory::tryFrom(trim($category));
|
||||
|
||||
return self::SUCCESS;
|
||||
if ($category === null || trim($file) === '' || trim($altText) === '') {
|
||||
$this->error('Ungültige Zeile '.($number + 2).": {$line}");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$entries[] = ['file' => $directory.'/'.ltrim(trim($file), '/'), 'category' => $category, 'alt_text' => trim($altText)];
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Themes\ThemeManifest;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
#[Signature('themes:make {key : Ordner/Key, z. B. ostsee-nacht} {--name= : Anzeigename} {--parent= : Eltern-Theme (Standard: Basis-Theme)} {--description= : Beschreibung für die Theme-Auswahl}')]
|
||||
#[Description('Create a new theme next to the existing ones (never overwrites) – inherits everything until views are added')]
|
||||
class MakeTheme extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ThemeRegistry $registry): int
|
||||
{
|
||||
$key = (string) $this->argument('key');
|
||||
$parent = (string) ($this->option('parent') ?: config('themes.base'));
|
||||
$themesPath = rtrim((string) (config('themes.paths')[0] ?? resource_path('themes')), '/\\');
|
||||
$path = "{$themesPath}/{$key}";
|
||||
$folder = str_replace('\\', '/', ltrim(substr($path, strlen(base_path())), '/\\'));
|
||||
|
||||
if (! preg_match('/^[a-z0-9]+(-[a-z0-9]+)*$/', $key)) {
|
||||
$this->error('Key: nur Kleinbuchstaben, Ziffern und Bindestriche, z. B. ostsee-nacht.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if (File::exists($path) || isset($registry->all()[$key])) {
|
||||
$this->error("Theme „{$key}“ gibt es schon – es wird nichts überschrieben.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if (! isset($registry->all()[$parent])) {
|
||||
$this->error("Eltern-Theme „{$parent}“ ist nicht installiert.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$name = (string) ($this->option('name') ?: str($key)->replace('-', ' ')->title());
|
||||
$manifest = [
|
||||
'key' => $key,
|
||||
'name' => $name,
|
||||
'version' => '0.1.0',
|
||||
'parent' => $parent,
|
||||
'description' => (string) ($this->option('description') ?: "Neues Theme auf Basis von „{$registry->get($parent)->name}“."),
|
||||
'assets' => ['css' => "{$folder}/theme.css", 'js' => "{$folder}/theme.js"],
|
||||
'tokens' => $registry->tokens($parent),
|
||||
];
|
||||
|
||||
File::ensureDirectoryExists("{$path}/views/sections");
|
||||
File::ensureDirectoryExists("{$path}/views/partials");
|
||||
File::put("{$path}/views/sections/.gitkeep", '');
|
||||
File::put("{$path}/views/partials/.gitkeep", '');
|
||||
File::put("{$path}/theme.json", json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n");
|
||||
File::put("{$path}/theme.css", $this->css($name, $parent, $path, $registry));
|
||||
File::put("{$path}/theme.js", $this->js($name, ThemeManifest::relativePath($path, $registry->get($parent)->path).'/theme.js'));
|
||||
File::put("{$path}/README.md", $this->readme($name, $key, $parent));
|
||||
|
||||
$this->info("Theme „{$name}“ angelegt: {$folder}");
|
||||
$this->line('Es erbt zunächst alles von „'.$parent.'“. Vorlagen nach views/ kopieren und umgestalten – Anleitung: docs/THEME-ERSTELLUNG.md');
|
||||
$this->line("Prüfen: php artisan themes:check {$key} · Bauen: npm run build · Auswählen: Admin › System › Websites › Theme (dort „Vorschau“).");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Child theme CSS: Tailwind, the reusable styles of the nearest ancestor that has a theme-base.css,
|
||||
* and the template sources of all ancestors, the booking forms and the theme itself.
|
||||
*/
|
||||
private function css(string $name, string $parent, string $path, ThemeRegistry $registry): string
|
||||
{
|
||||
$ancestors = $registry->chain($parent);
|
||||
$base = collect($ancestors)->first(fn (ThemeManifest $theme): bool => is_file($theme->path.'/theme-base.css')) ?? $ancestors[0];
|
||||
$import = ThemeManifest::relativePath($path, $base->path).'/theme-base.css';
|
||||
$sources = collect($ancestors)
|
||||
->map(fn (ThemeManifest $theme): string => "@source '".ThemeManifest::relativePath($path, $theme->viewsPath())."';")
|
||||
->push("@source '".ThemeManifest::relativePath($path, resource_path('views/livewire'))."';")
|
||||
->push("@source './views';")
|
||||
->implode("\n");
|
||||
|
||||
return <<<CSS
|
||||
/*
|
||||
* Theme „{$name}“ – Child von „{$parent}“ (Anleitung: docs/THEME-ERSTELLUNG.md).
|
||||
* theme-base.css des Eltern-Themes bringt Schriften, Token-Mapping und Basis-Klassen (.eyebrow,
|
||||
* .heading-display, .btn-primary, .btn-accent, .prose-theme, .reveal). Hier nur Abweichungen ergänzen.
|
||||
*/
|
||||
@import 'tailwindcss';
|
||||
@import '{$import}';
|
||||
|
||||
/* Eigene Schriften selbst hosten: npm install @fontsource/<schrift> und hier importieren, z. B.
|
||||
@import '@fontsource/fraunces/400.css';
|
||||
*/
|
||||
|
||||
/* Vorlagen, deren Klassen gebaut werden: geerbte, Buchungsformulare, eigene. */
|
||||
{$sources}
|
||||
|
||||
@theme inline {
|
||||
/* --font-display: 'Fraunces', Georgia, serif; */
|
||||
/* --font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif; */
|
||||
}
|
||||
|
||||
@layer components {
|
||||
}
|
||||
|
||||
CSS;
|
||||
}
|
||||
|
||||
private function js(string $name, string $import): string
|
||||
{
|
||||
return <<<JS
|
||||
/**
|
||||
* Theme „{$name}“: übernimmt Lightbox, Verfügbarkeitssuche und rollierende Angebote vom Eltern-Theme.
|
||||
* Eigene Verbesserungen darunter – alles muss auch ohne JavaScript funktionieren.
|
||||
*/
|
||||
import '{$import}';
|
||||
|
||||
JS;
|
||||
}
|
||||
|
||||
private function readme(string $name, string $key, string $parent): string
|
||||
{
|
||||
return <<<MD
|
||||
# Theme „{$name}“ (`{$key}`)
|
||||
|
||||
Child-Theme von `{$parent}`. Vorlagen, die hier fehlen, kommen vom Eltern-Theme.
|
||||
|
||||
- Anleitung und Vorlagen-Vertrag: `docs/THEME-ERSTELLUNG.md`, `docs/THEMES.md` §5
|
||||
- Prüfen: `php artisan themes:check {$key}`
|
||||
- Ansehen ohne Umschalten: Admin › System › Websites › Theme „{$name}“ wählen › „Vorschau“ (erst danach speichern)
|
||||
|
||||
## Eigene Vorlagen
|
||||
|
||||
| Datei | Zweck |
|
||||
|---|---|
|
||||
| | |
|
||||
|
||||
MD;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Themes\ThemeFactory;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
#[Signature('themes:preview {theme : Key des Themes} {--hours=24 : Gültigkeit der Links}')]
|
||||
#[Description('Print signed preview links: every page of the site with the theme, in every appearance – without switching the site')]
|
||||
class PreviewTheme extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ThemeRegistry $registry, ThemeFactory $factory): int
|
||||
{
|
||||
$key = (string) $this->argument('theme');
|
||||
if (! isset($registry->all()[$key])) {
|
||||
$this->error("Theme „{$key}“ nicht gefunden. Installiert: ".implode(', ', array_keys($registry->all())));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$site = $factory->site();
|
||||
$expires = now()->addHours((int) $this->option('hours'));
|
||||
$pages = $site->exists ? $site->pages()->where('is_published', true)->orderBy('sort_order')->get() : collect();
|
||||
$appearances = $site->exists ? $site->appearances()->orderByDesc('is_default')->orderBy('starts_md')->get() : collect();
|
||||
|
||||
$this->info("Vorschau „{$registry->get($key)->name}“ für {$site->name} (gültig bis {$expires->format('d.m.Y H:i')}):");
|
||||
foreach ($pages as $page) {
|
||||
$this->line('');
|
||||
$this->line("<options=bold>{$page->title}</>");
|
||||
$this->line(' heute: '.$this->url($page, ['theme' => $key], $expires));
|
||||
foreach ($appearances as $appearance) {
|
||||
$this->line(str_pad(" {$appearance->name}:", 16).$this->url($page, ['theme' => $key, 'vorschau' => $appearance->id], $expires));
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $parameters
|
||||
*/
|
||||
private function url(Page $page, array $parameters, \DateTimeInterface $expires): string
|
||||
{
|
||||
return $page->isHome()
|
||||
? URL::temporarySignedRoute('home', $expires, $parameters)
|
||||
: URL::temporarySignedRoute('page', $expires, ['slug' => $page->slug, ...$parameters]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('channels:sync {channel? : ID of a single channel}')]
|
||||
#[Description('Import the occupations of all active portals (or one) and report conflicts')]
|
||||
class SyncChannels extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(SyncChannel $syncChannel): int
|
||||
{
|
||||
$channels = Channel::query()->active()
|
||||
->when($this->argument('channel'), fn ($query, $id) => $query->whereKey($id))
|
||||
->get()
|
||||
->filter(fn (Channel $channel): bool => $channel->importsOccupations());
|
||||
|
||||
foreach ($channels as $channel) {
|
||||
$log = $syncChannel->handle($channel);
|
||||
|
||||
$log->successful
|
||||
? $this->info("✓ {$channel->name}: {$log->events} Belegungen, +{$log->added} ~{$log->changed} -{$log->removed}, Konflikte: {$log->conflicts}")
|
||||
: $this->error("✗ {$channel->name}: {$log->message}");
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Documents;
|
||||
|
||||
use App\Models\Booking;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* The rental contract as PDF. It is generated once at confirmation and stored, so later changes
|
||||
* of texts or prices do not alter a contract the guest already received.
|
||||
*/
|
||||
class RentalContract
|
||||
{
|
||||
private const DISK = 'local';
|
||||
|
||||
public function generate(Booking $booking): string
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
$path = "contracts/Mietvertrag-{$booking->reference}.pdf";
|
||||
|
||||
Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', ['booking' => $booking])->setPaper('a4')->output());
|
||||
$booking->update(['contract_path' => $path]);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function absolutePath(Booking $booking): ?string
|
||||
{
|
||||
return $booking->contract_path && Storage::disk(self::DISK)->exists($booking->contract_path)
|
||||
? Storage::disk(self::DISK)->path($booking->contract_path)
|
||||
: null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelTaskAction: string implements HasColor, HasLabel
|
||||
{
|
||||
case Block = 'block';
|
||||
case Unblock = 'unblock';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Block => 'Sperren',
|
||||
self::Unblock => 'Freigeben',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Block => 'danger',
|
||||
self::Unblock => 'success',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelTaskStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
case Open = 'open';
|
||||
case Done = 'done';
|
||||
case Dismissed = 'dismissed';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Open => 'Offen',
|
||||
self::Done => 'Erledigt',
|
||||
self::Dismissed => 'Verworfen',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Open => 'warning',
|
||||
self::Done => 'success',
|
||||
self::Dismissed => 'gray',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,9 @@ enum DiscountType: string implements HasLabel
|
||||
/** discount_value = number of cheapest nights that are free */
|
||||
case FreeNights = 'free_nights';
|
||||
|
||||
/** discount_value = package price in euro cents for all nights of the stay */
|
||||
case FixedStayPrice = 'fixed_stay_price';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
@@ -25,6 +28,12 @@ public function getLabel(): string
|
||||
self::AmountPerStay => 'Rabatt in € pro Aufenthalt',
|
||||
self::NightlyRate => 'Sonderpreis pro Nacht',
|
||||
self::FreeNights => 'Gratis-Nächte',
|
||||
self::FixedStayPrice => 'Pauschalpreis für den Aufenthalt',
|
||||
};
|
||||
}
|
||||
|
||||
public function isMoney(): bool
|
||||
{
|
||||
return in_array($this, [self::AmountPerStay, self::NightlyRate, self::FixedStayPrice], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* How an offer finds its stays. All kinds are priced by PriceCalculator and advertised by OfferShowcase.
|
||||
*/
|
||||
enum OfferKind: string implements HasDescription, HasLabel
|
||||
{
|
||||
/** Conditions only (last minute, early bird, from N nights, weekend …). */
|
||||
case Rule = 'rule';
|
||||
|
||||
/** One fixed arrival and departure (stay_from / stay_until), e.g. a week as a package. */
|
||||
case FixedDates = 'fixed_dates';
|
||||
|
||||
/** Free gaps of at most max_gap_nights between two occupations, found automatically. */
|
||||
case GapFiller = 'gap_filler';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Rule => 'Rabattaktion (nach Bedingungen)',
|
||||
self::FixedDates => 'Fester Termin',
|
||||
self::GapFiller => 'Lückenfüller (Kalenderlücken)',
|
||||
};
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Rule => 'Gilt für jeden Aufenthalt, der die Bedingungen erfüllt, z. B. Last Minute oder „ab 3 Nächten −10 %“.',
|
||||
self::FixedDates => 'Ein bestimmter Zeitraum, z. B. „7 Nächte vom 07. bis 14.11.“ – wird nur beworben, solange er frei ist.',
|
||||
self::GapFiller => 'Findet freie Lücken zwischen zwei Buchungen automatisch und bewirbt sie mit konkreten Terminen.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum PaymentMethod: string implements HasLabel
|
||||
{
|
||||
case Transfer = 'transfer';
|
||||
case Cash = 'cash';
|
||||
case Other = 'other';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Transfer => 'Überweisung',
|
||||
self::Cash => 'Bar',
|
||||
self::Other => 'Sonstiges',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum PortalEmailStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
/** A new block was created from the e-mail. */
|
||||
case Blocked = 'blocked';
|
||||
|
||||
/** The period was already blocked (e.g. by the calendar sync). */
|
||||
case AlreadyKnown = 'already_known';
|
||||
|
||||
/** A cancellation released a block created from an e-mail. */
|
||||
case Released = 'released';
|
||||
|
||||
case NeedsReview = 'needs_review';
|
||||
case Reviewed = 'reviewed';
|
||||
case Ignored = 'ignored';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Blocked => 'Gesperrt',
|
||||
self::AlreadyKnown => 'Bereits gesperrt',
|
||||
self::Released => 'Freigegeben',
|
||||
self::NeedsReview => 'Bitte prüfen',
|
||||
self::Reviewed => 'Geprüft',
|
||||
self::Ignored => 'Ignoriert',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Blocked, self::Released => 'success',
|
||||
self::AlreadyKnown, self::Reviewed, self::Ignored => 'gray',
|
||||
self::NeedsReview => 'danger',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum PortalEmailType: string implements HasLabel
|
||||
{
|
||||
case Booking = 'booking';
|
||||
case Cancellation = 'cancellation';
|
||||
case Inquiry = 'inquiry';
|
||||
case Unknown = 'unknown';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Booking => 'Buchung',
|
||||
self::Cancellation => 'Stornierung',
|
||||
self::Inquiry => 'Anfrage',
|
||||
self::Unknown => 'Unbekannt',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* "How did you find us?" – answered by the guest in the request form.
|
||||
*/
|
||||
enum ReferralSource: string implements HasLabel
|
||||
{
|
||||
case SearchEngine = 'search_engine';
|
||||
case FewoDirekt = 'fewo_direkt';
|
||||
case Ostseeklar = 'ostseeklar';
|
||||
case FerienUndWohnen = 'ferienundwohnen';
|
||||
case TouristInformation = 'tourist_information';
|
||||
case SocialMedia = 'social_media';
|
||||
case Recommendation = 'recommendation';
|
||||
case ReturningGuest = 'returning_guest';
|
||||
case Other = 'other';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::SearchEngine => 'Suchmaschine (z. B. Google)',
|
||||
self::FewoDirekt => 'FeWo-direkt',
|
||||
self::Ostseeklar => 'Ostseeklar',
|
||||
self::FerienUndWohnen => 'ferienundwohnen.de',
|
||||
self::TouristInformation => 'Tourist-Information Kühlungsborn',
|
||||
self::SocialMedia => 'Social Media',
|
||||
self::Recommendation => 'Empfehlung',
|
||||
self::ReturningGuest => 'Ich war schon Gast',
|
||||
self::Other => 'Sonstiges',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Forms\Components;
|
||||
|
||||
use App\Models\Photo;
|
||||
use Filament\Forms\Components\Select;
|
||||
|
||||
/**
|
||||
* Chooses website photos with a thumbnail next to each description, grouped by category,
|
||||
* so editors see what they insert.
|
||||
*/
|
||||
class PhotoSelect extends Select
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this
|
||||
->options(fn (): array => self::photoOptions())
|
||||
->allowHtml()
|
||||
->searchable()
|
||||
->native(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
public static function photoOptions(): array
|
||||
{
|
||||
return Photo::query()->with('media')->orderBy('category')->orderBy('sort_order')->get()
|
||||
->groupBy(fn (Photo $photo): string => $photo->category->getLabel())
|
||||
->map(fn ($photos): array => $photos->mapWithKeys(fn (Photo $photo): array => [$photo->id => self::optionLabel($photo)])->all())
|
||||
->all();
|
||||
}
|
||||
|
||||
public static function optionLabel(Photo $photo): string
|
||||
{
|
||||
$thumbnail = $photo->url('sm');
|
||||
$image = $thumbnail !== ''
|
||||
? '<img src="'.e($thumbnail).'" alt="" loading="lazy" style="width:4.5rem;height:3rem;object-fit:cover;border-radius:.25rem;flex-shrink:0">'
|
||||
: '<span style="width:4.5rem;height:3rem;border-radius:.25rem;background:#e5e7eb;flex-shrink:0"></span>';
|
||||
$hidden = $photo->is_published ? '' : ' <em style="opacity:.6">(ausgeblendet)</em>';
|
||||
|
||||
return '<span style="display:flex;align-items:center;gap:.75rem">'.$image.'<span>'.e($photo->alt_text).$hidden.'</span></span>';
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\Photo;
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Support\Content;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
@@ -39,7 +39,7 @@ class EditContent extends Page
|
||||
|
||||
protected static ?string $slug = 'texte';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
/** @var array<string, ?string> */
|
||||
public array $data = [];
|
||||
@@ -120,10 +120,8 @@ private function field(string $key, array $field): TextInput|Textarea|RichEditor
|
||||
'richtext' => RichEditor::make($name)
|
||||
->label($field['label'])
|
||||
->toolbarButtons([['bold', 'italic', 'link'], ['h2', 'h3'], ['bulletList', 'orderedList'], ['undo', 'redo']]),
|
||||
'photo' => Select::make($name)
|
||||
'photo' => PhotoSelect::make($name)
|
||||
->label($field['label'])
|
||||
->options(fn (): array => Photo::query()->orderBy('category')->orderBy('sort_order')->pluck('alt_text', 'id')->all())
|
||||
->searchable()
|
||||
->placeholder('Kein Bild gewählt')
|
||||
->helperText('Bilder verwalten Sie unter „Webseite › Bilder“.'),
|
||||
default => TextInput::make($name)->label($field['label'])->maxLength(255),
|
||||
|
||||
@@ -27,7 +27,7 @@ class AmenityResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Ausstattung';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
protected static ?int $navigationSort = 4;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances;
|
||||
|
||||
use App\Filament\Resources\Appearances\Pages\CreateAppearance;
|
||||
use App\Filament\Resources\Appearances\Pages\EditAppearance;
|
||||
use App\Filament\Resources\Appearances\Pages\ListAppearances;
|
||||
use App\Filament\Resources\Appearances\Schemas\AppearanceForm;
|
||||
use App\Filament\Resources\Appearances\Tables\AppearancesTable;
|
||||
use App\Models\Appearance;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class AppearanceResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Appearance::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSwatch;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
|
||||
|
||||
protected static ?string $modelLabel = 'Erscheinungsbild';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Erscheinungsbilder';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return AppearanceForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return AppearancesTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListAppearances::route('/'),
|
||||
'create' => CreateAppearance::route('/create'),
|
||||
'edit' => EditAppearance::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Pages;
|
||||
|
||||
use App\Filament\Resources\Appearances\AppearanceResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateAppearance extends CreateRecord
|
||||
{
|
||||
protected static string $resource = AppearanceResource::class;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Pages;
|
||||
|
||||
use App\Filament\Resources\Appearances\AppearanceResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditAppearance extends EditRecord
|
||||
{
|
||||
protected static string $resource = AppearanceResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Pages;
|
||||
|
||||
use App\Filament\Resources\Appearances\AppearanceResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListAppearances extends ListRecords
|
||||
{
|
||||
protected static string $resource = AppearanceResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Schemas;
|
||||
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Models\Appearance;
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Themes\SectionRegistry;
|
||||
use App\Themes\Sections\Section as SectionBlock;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Closure;
|
||||
use Filament\Forms\Components\ColorPicker;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Component;
|
||||
use Filament\Schemas\Components\Fieldset;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class AppearanceForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(2)
|
||||
->components([
|
||||
Section::make('Zeitraum')
|
||||
->description('Wiederholt sich jedes Jahr. Überschneiden sich Zeiträume, gilt die höhere Priorität (z. B. Silvester vor Winter). Ohne Zeitraum greift das Standard-Erscheinungsbild.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('name')->label('Name')->placeholder('z. B. Weihnachten')->required()->maxLength(60),
|
||||
Select::make('site_id')
|
||||
->label('Website')
|
||||
->options(fn (): array => Site::query()->pluck('name', 'id')->all())
|
||||
->default(fn (): ?int => Site::query()->where('is_default', true)->value('id'))
|
||||
->required(),
|
||||
self::dayField('starts_md', 'Von (TT.MM.)'),
|
||||
self::dayField('ends_md', 'Bis einschließlich (TT.MM.)'),
|
||||
TextInput::make('priority')->label('Priorität')->integer()->minValue(0)->default(10),
|
||||
Toggle::make('is_default')->label('Standard (wenn kein Zeitraum passt)')->inline(false),
|
||||
Toggle::make('is_active')->label('Aktiv')->default(true)->inline(false),
|
||||
]),
|
||||
Section::make('Titelbild')
|
||||
->description('Gilt für alle Titelbereiche und als Vorschaubild beim Teilen in sozialen Medien – einzelne Bausteine können unten ein eigenes Bild bekommen. Sonderangebote werden unabhängig vom Erscheinungsbild beworben (Wohnung › Sonderangebote).')
|
||||
->schema([
|
||||
PhotoSelect::make('hero_photo_id')
|
||||
->label('Titelbild')
|
||||
->placeholder('Bild der Seite verwenden'),
|
||||
]),
|
||||
Section::make('Bilder je Baustein')
|
||||
->description('Für jeden Baustein mit Bildern ein eigenes Saisonbild wählen. Leer = Bild aus der Seite. Neue Bilder laden Sie unter Webseite › Fotos hoch.')
|
||||
->collapsible()
|
||||
->columnSpanFull()
|
||||
->schema(fn (Get $get): array => self::sectionPhotoFields($get('site_id'))),
|
||||
Section::make('Texte')
|
||||
->description('Leer lassen = Text der Seite bzw. kein Banner.')
|
||||
->columns(2)
|
||||
->collapsible()
|
||||
->schema(collect(Appearance::OVERRIDABLE)
|
||||
->map(fn (string $label, string $key) => TextInput::make('overrides.'.$key)->label($label)->maxLength(255))
|
||||
->values()
|
||||
->all()),
|
||||
Section::make('Farben')
|
||||
->description('Nur ändern, was anders aussehen soll; leere Felder übernehmen die Farben des Themes.')
|
||||
->columns(3)
|
||||
->collapsible()
|
||||
->collapsed()
|
||||
->schema(fn (Get $get): array => self::tokenFields($get('site_id'))),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* One group per page and one field set per placed section that has photo slots
|
||||
* (see Section::photoSlots); stored in section_photos[<section id>][<slot>].
|
||||
*
|
||||
* @return list<Component>
|
||||
*/
|
||||
public static function sectionPhotoFields(int|string|null $siteId): array
|
||||
{
|
||||
$registry = app(SectionRegistry::class);
|
||||
$pages = Page::query()->where('site_id', $siteId)->orderBy('sort_order')->get();
|
||||
|
||||
$groups = [];
|
||||
foreach ($pages as $page) {
|
||||
$fieldsets = [];
|
||||
foreach ($page->sections ?? [] as $stored) {
|
||||
$class = $registry->all()[$stored['type'] ?? ''] ?? null;
|
||||
$sectionId = $stored['data']['id'] ?? null;
|
||||
if ($class === null || blank($sectionId) || $class::photoSlots() === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fields = [];
|
||||
foreach ($class::photoSlots() as $slot => $definition) {
|
||||
$field = PhotoSelect::make("section_photos.{$sectionId}.{$slot}")
|
||||
->label($definition['label'])
|
||||
->placeholder('Standard (Bild aus der Seite)')
|
||||
->multiple($definition['type'] !== SectionBlock::SLOT_SINGLE);
|
||||
if (isset($definition['max'])) {
|
||||
$field->maxItems($definition['max']);
|
||||
}
|
||||
$fields[] = $field;
|
||||
|
||||
if ($definition['type'] === SectionBlock::SLOT_COLLECTION) {
|
||||
$fields[] = Radio::make("section_photos.{$sectionId}.mode")
|
||||
->label('Saisonbilder')
|
||||
->options(['replace' => 'ersetzen die Bilder des Bausteins', 'prepend' => 'kommen zuerst, danach die übrigen'])
|
||||
->default('replace')
|
||||
->inline();
|
||||
}
|
||||
}
|
||||
|
||||
$fieldsets[] = Fieldset::make(collect([$class::label(), $class::summary($stored['data'] ?? [])])->filter()->implode(' · '))
|
||||
->columns(1)
|
||||
->schema($fields);
|
||||
}
|
||||
|
||||
if ($fieldsets !== []) {
|
||||
$groups[] = Section::make($page->title)->compact()->collapsible()->schema($fieldsets);
|
||||
}
|
||||
}
|
||||
|
||||
return $groups ?: [Text::make('Auf den Seiten gibt es noch keine Bausteine mit Bildern.')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<ColorPicker>
|
||||
*/
|
||||
public static function tokenFields(int|string|null $siteId, string $statePath = 'tokens', ?string $themeKey = null): array
|
||||
{
|
||||
$theme = $themeKey ?: (Site::find($siteId)?->theme ?? config('themes.base'));
|
||||
|
||||
return collect(app(ThemeRegistry::class)->tokens($theme))
|
||||
->map(fn (array $token, string $key): ColorPicker => ColorPicker::make("{$statePath}.{$key}")->label($token['label'])->placeholder($token['default']))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Day of the year entered as "TT.MM." and stored as "MM-DD".
|
||||
*/
|
||||
private static function dayField(string $name, string $label): TextInput
|
||||
{
|
||||
return TextInput::make($name)
|
||||
->label($label)
|
||||
->placeholder('24.12.')
|
||||
->formatStateUsing(fn (?string $state): ?string => $state ? substr($state, 3, 2).'.'.substr($state, 0, 2).'.' : null)
|
||||
->dehydrateStateUsing(fn (?string $state): ?string => self::toMonthDay($state))
|
||||
->rule(fn (): Closure => function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if (filled($value) && self::toMonthDay((string) $value) === null) {
|
||||
$fail('Bitte als TT.MM. eingeben, z. B. 24.12.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static function toMonthDay(?string $value): ?string
|
||||
{
|
||||
if (blank($value) || ! preg_match('/^\s*(\d{1,2})\.(\d{1,2})\.?\s*$/', $value, $match)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return checkdate((int) $match[2], (int) $match[1], 2024) ? sprintf('%02d-%02d', $match[2], $match[1]) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Tables;
|
||||
|
||||
use App\Models\Appearance;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
class AppearancesTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('priority', 'desc')
|
||||
->description('Die Webseite wechselt automatisch nach Datum. Mit „Vorschau“ sehen Sie ein Erscheinungsbild schon vorher.')
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Erscheinungsbild')->weight('medium'),
|
||||
TextColumn::make('period')
|
||||
->label('Zeitraum')
|
||||
->state(fn (Appearance $record): string => $record->is_default && ! $record->starts_md ? 'Standard' : self::day($record->starts_md).' – '.self::day($record->ends_md)),
|
||||
TextColumn::make('priority')->label('Priorität')->sortable(),
|
||||
IconColumn::make('current')
|
||||
->label('Jetzt aktiv')
|
||||
->boolean()
|
||||
->state(fn (Appearance $record): bool => $record->site?->appearanceOn(today())?->is($record) ?? false),
|
||||
ToggleColumn::make('is_active')->label('Aktiv'),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('preview')
|
||||
->label('Vorschau')
|
||||
->icon(Heroicon::OutlinedEye)
|
||||
->color('gray')
|
||||
->url(fn (Appearance $record): string => URL::temporarySignedRoute('home', now()->addDay(), ['vorschau' => $record->id]), shouldOpenInNewTab: true),
|
||||
EditAction::make(),
|
||||
DeleteAction::make()->visible(fn (Appearance $record): bool => ! $record->is_default),
|
||||
]);
|
||||
}
|
||||
|
||||
private static function day(?string $monthDay): string
|
||||
{
|
||||
return $monthDay ? substr($monthDay, 3, 2).'.'.substr($monthDay, 0, 2).'.' : '?';
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
use App\Filament\Resources\Bookings\Pages\CreateBooking;
|
||||
use App\Filament\Resources\Bookings\Pages\ListBookings;
|
||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager;
|
||||
use App\Filament\Resources\Bookings\Schemas\BookingForm;
|
||||
use App\Filament\Resources\Bookings\Schemas\BookingInfolist;
|
||||
use App\Filament\Resources\Bookings\Tables\BookingsTable;
|
||||
@@ -63,6 +64,13 @@ public static function getNavigationBadgeColor(): string
|
||||
return 'warning';
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
PaymentsRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Actions\ConfirmBooking;
|
||||
use App\Actions\DeclineBooking;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
@@ -75,7 +76,23 @@ protected function getHeaderActions(): array
|
||||
|
||||
Notification::make()->title('Vorgemerkt bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send();
|
||||
}),
|
||||
Action::make('contract')
|
||||
->label('Mietvertrag')
|
||||
->icon(Heroicon::OutlinedDocumentText)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => $this->record->contract_path !== null)
|
||||
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record) ?? abort(404), "Mietvertrag-{$this->record->reference}.pdf")),
|
||||
ActionGroup::make([
|
||||
Action::make('regenerateContract')
|
||||
->label('Mietvertrag neu erzeugen')
|
||||
->icon(Heroicon::OutlinedArrowPath)
|
||||
->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying()], true))
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Der Vertrag wird mit den aktuellen Texten neu erstellt. Der Gast erhält ihn nicht automatisch.')
|
||||
->action(function (RentalContract $contract): void {
|
||||
$contract->generate($this->record);
|
||||
Notification::make()->title('Mietvertrag neu erzeugt')->success()->send();
|
||||
}),
|
||||
Action::make('notes')
|
||||
->label('Interne Notiz bearbeiten')
|
||||
->icon(Heroicon::OutlinedPencilSquare)
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Bookings\RelationManagers;
|
||||
|
||||
use App\Actions\RecordPayment;
|
||||
use App\Enums\PaymentMethod;
|
||||
use App\Filament\Forms\Components\EuroInput;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Payment;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
/**
|
||||
* @property Booking $ownerRecord
|
||||
*/
|
||||
class PaymentsRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'payments';
|
||||
|
||||
protected static ?string $title = 'Zahlungen';
|
||||
|
||||
public function isReadOnly(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('amount')
|
||||
->description(fn (): string => 'Bezahlt: '.Money::format($this->ownerRecord->paidAmount()).' · offen: '.Money::format($this->ownerRecord->openAmount()))
|
||||
->columns([
|
||||
TextColumn::make('paid_on')->label('Eingang')->date('d.m.Y'),
|
||||
TextColumn::make('amount')->label('Betrag')->money('EUR', divideBy: 100, locale: 'de'),
|
||||
TextColumn::make('method')->label('Art'),
|
||||
TextColumn::make('note')->label('Notiz')->placeholder('–'),
|
||||
TextColumn::make('recorded_by')->label('Erfasst von')->placeholder('–'),
|
||||
])
|
||||
->headerActions([
|
||||
Action::make('record')
|
||||
->label('Zahlung erfassen')
|
||||
->icon(Heroicon::OutlinedBanknotes)
|
||||
->fillForm(fn (): array => [
|
||||
'amount' => number_format(($this->ownerRecord->openDeposit() ?: $this->ownerRecord->openAmount()) / 100, 2, '.', ''),
|
||||
'paid_on' => today(),
|
||||
'method' => PaymentMethod::Transfer,
|
||||
])
|
||||
->schema([
|
||||
EuroInput::make('amount')->label('Betrag')->helperText('Erstattungen mit Minus erfassen.')->minValue(null)->required(),
|
||||
DatePicker::make('paid_on')->label('Zahlungseingang')->required(),
|
||||
Select::make('method')->label('Art')->options(PaymentMethod::class)->required(),
|
||||
TextInput::make('note')->label('Notiz')->maxLength(255),
|
||||
])
|
||||
->action(function (array $data, RecordPayment $recordPayment): void {
|
||||
$recordPayment->handle(
|
||||
$this->ownerRecord,
|
||||
(int) $data['amount'],
|
||||
CarbonImmutable::parse($data['paid_on']),
|
||||
$data['method'] instanceof PaymentMethod ? $data['method'] : PaymentMethod::from($data['method']),
|
||||
$data['note'] ?: null,
|
||||
auth()->user()?->name,
|
||||
);
|
||||
|
||||
Notification::make()->title('Zahlung erfasst – Status: '.$this->ownerRecord->fresh()->status->getLabel())->success()->send();
|
||||
}),
|
||||
])
|
||||
->recordActions([
|
||||
DeleteAction::make()->after(fn (Payment $record) => app(RecordPayment::class)->updateStatus($this->ownerRecord->fresh())),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,9 @@ public static function configure(Schema $schema): Schema
|
||||
TextEntry::make('deposit')->label('Anzahlung')->money('EUR', divideBy: 100, locale: 'de'),
|
||||
TextEntry::make('balance')->label('Restzahlung')->state(fn (Booking $record): string => Money::format($record->total - $record->deposit)),
|
||||
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y'),
|
||||
TextEntry::make('paid')->label('Bezahlt')->state(fn (Booking $record): string => Money::format($record->paidAmount())),
|
||||
TextEntry::make('open')->label('Offen')->state(fn (Booking $record): string => Money::format($record->openAmount()))->color(fn (Booking $record): string => $record->openAmount() > 0 ? 'danger' : 'success'),
|
||||
TextEntry::make('deposit_due_on')->label('Anzahlung fällig am')->date('d.m.Y')->placeholder('–'),
|
||||
]),
|
||||
]),
|
||||
Section::make('Nachricht des Gastes')
|
||||
@@ -66,6 +69,11 @@ public static function configure(Schema $schema): Schema
|
||||
TextEntry::make('confirmed_at')->label('Bestätigt am')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->confirmed_at !== null),
|
||||
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'),
|
||||
TextEntry::make('source')->label('Quelle'),
|
||||
TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'),
|
||||
TextEntry::make('utm')
|
||||
->label('Kampagne (UTM)')
|
||||
->state(fn (Booking $record): ?string => collect([$record->utm_source, $record->utm_medium, $record->utm_campaign])->filter()->implode(' / ') ?: null)
|
||||
->visible(fn (Booking $record): bool => filled($record->utm_source)),
|
||||
]),
|
||||
Section::make('Gast')
|
||||
->schema([
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Money;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\Filter;
|
||||
@@ -16,7 +17,7 @@ class BookingsTable
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property']))
|
||||
->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property', 'payments']))
|
||||
->defaultSort('created_at', 'desc')
|
||||
->columns([
|
||||
TextColumn::make('reference')
|
||||
@@ -46,7 +47,8 @@ public static function configure(Table $table): Table
|
||||
->label('Pers.'),
|
||||
TextColumn::make('total')
|
||||
->label('Gesamt')
|
||||
->money('EUR', divideBy: 100, locale: 'de'),
|
||||
->money('EUR', divideBy: 100, locale: 'de')
|
||||
->description(fn (Booking $record): ?string => in_array($record->status, BookingStatus::occupying(), true) && $record->openAmount() > 0 ? 'offen '.Money::format($record->openAmount()) : null),
|
||||
TextColumn::make('source')
|
||||
->label('Quelle')
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks;
|
||||
|
||||
use App\Filament\Resources\ChannelTasks\Pages\ListChannelTasks;
|
||||
use App\Filament\Resources\ChannelTasks\Tables\ChannelTasksTable;
|
||||
use App\Models\ChannelTask;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class ChannelTaskResource extends Resource
|
||||
{
|
||||
protected static ?string $model = ChannelTask::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentCheck;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $modelLabel = 'Portal-Aufgabe';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Portal-Aufgaben';
|
||||
|
||||
protected static ?int $navigationSort = 4;
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return ChannelTasksTable::configure($table);
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$open = ChannelTask::query()->open()->count();
|
||||
|
||||
return $open > 0 ? (string) $open : null;
|
||||
}
|
||||
|
||||
public static function getNavigationBadgeColor(): string
|
||||
{
|
||||
return 'danger';
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListChannelTasks::route('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks\Pages;
|
||||
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListChannelTasks extends ListRecords
|
||||
{
|
||||
protected static string $resource = ChannelTaskResource::class;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks\Tables;
|
||||
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Models\ChannelTask;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class ChannelTasksTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('created_at', 'desc')
|
||||
->description('Diese Portale werden zusätzlich von Hand gepflegt. Bitte die Änderung im Portal vornehmen und hier abhaken.')
|
||||
->columns([
|
||||
TextColumn::make('channel.name')->label('Portal')->weight('medium'),
|
||||
TextColumn::make('action')->label('Aktion')->badge(),
|
||||
TextColumn::make('period')->label('Zeitraum')->state(fn (ChannelTask $record): string => $record->period()),
|
||||
TextColumn::make('reason')->label('Anlass')->wrap(),
|
||||
TextColumn::make('status')->label('Status')->badge()
|
||||
->description(fn (ChannelTask $record): ?string => $record->completed_by ? "{$record->completed_by}, {$record->completed_at?->format('d.m. H:i')}" : null),
|
||||
TextColumn::make('created_at')->label('Seit')->since(),
|
||||
TextColumn::make('automation_error')->label('Automatisierung')->placeholder('–')->limit(40)->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->filters([
|
||||
SelectFilter::make('status')
|
||||
->label('Status')
|
||||
->options(ChannelTaskStatus::class)
|
||||
->default(ChannelTaskStatus::Open->value),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('openPortal')
|
||||
->label('Portal öffnen')
|
||||
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
|
||||
->color('gray')
|
||||
->url(fn (ChannelTask $record): ?string => $record->channel->manage_url, shouldOpenInNewTab: true)
|
||||
->visible(fn (ChannelTask $record): bool => filled($record->channel->manage_url)),
|
||||
Action::make('done')
|
||||
->label('Erledigt')
|
||||
->icon(Heroicon::OutlinedCheck)
|
||||
->color('success')
|
||||
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open)
|
||||
->action(fn (ChannelTask $record) => $record->complete(auth()->user()->name)),
|
||||
Action::make('dismiss')
|
||||
->label('Verwerfen')
|
||||
->icon(Heroicon::OutlinedXMark)
|
||||
->color('gray')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open)
|
||||
->action(fn (ChannelTask $record) => $record->update(['status' => ChannelTaskStatus::Dismissed])),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ class FaqResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Häufige Fragen';
|
||||
|
||||
protected static ?int $navigationSort = 4;
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
|
||||
@@ -27,7 +27,7 @@ class NoticeResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Hinweis-Banner';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
protected static ?int $navigationSort = 6;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages;
|
||||
|
||||
use App\Filament\Resources\Pages\Pages\CreatePage;
|
||||
use App\Filament\Resources\Pages\Pages\EditPage;
|
||||
use App\Filament\Resources\Pages\Pages\ListPages;
|
||||
use App\Filament\Resources\Pages\Schemas\PageForm;
|
||||
use App\Filament\Resources\Pages\Tables\PagesTable;
|
||||
use App\Models\Page;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class PageResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Page::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedDocumentDuplicate;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
|
||||
|
||||
protected static ?string $modelLabel = 'Seite';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Seiten';
|
||||
|
||||
protected static ?int $navigationSort = 0;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return PageForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return PagesTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListPages::route('/'),
|
||||
'create' => CreatePage::route('/create'),
|
||||
'edit' => EditPage::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Pages;
|
||||
|
||||
use App\Filament\Resources\Pages\PageResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreatePage extends CreateRecord
|
||||
{
|
||||
protected static string $resource = PageResource::class;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Pages;
|
||||
|
||||
use App\Filament\Resources\Pages\PageResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditPage extends EditRecord
|
||||
{
|
||||
protected static string $resource = PageResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Pages;
|
||||
|
||||
use App\Filament\Resources\Pages\PageResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListPages extends ListRecords
|
||||
{
|
||||
protected static string $resource = PageResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Schemas;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Themes\SectionRegistry;
|
||||
use Filament\Forms\Components\Builder;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Validation\Rules\Unique;
|
||||
|
||||
class PageForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(3)
|
||||
->components([
|
||||
Section::make('Bausteine')
|
||||
->description('Die Seite besteht aus Bausteinen. Reihenfolge per Ziehen, Inhalte je Baustein. Wie sie aussehen, bestimmt das Theme.')
|
||||
->columnSpan(2)
|
||||
->schema([
|
||||
Builder::make('sections')
|
||||
->hiddenLabel()
|
||||
->blocks(fn (): array => app(SectionRegistry::class)->blocks())
|
||||
->addActionLabel('Baustein hinzufügen')
|
||||
->collapsible()
|
||||
->collapsed()
|
||||
->cloneable()
|
||||
->blockNumbers(false)
|
||||
->blockPickerColumns(2),
|
||||
]),
|
||||
Section::make('Seite')
|
||||
->columnSpan(1)
|
||||
->schema([
|
||||
Hidden::make('site_id')->default(fn (): ?int => Site::query()->where('is_default', true)->value('id') ?? Site::query()->value('id')),
|
||||
TextInput::make('title')->label('Titel')->required()->maxLength(120),
|
||||
TextInput::make('slug')
|
||||
->label('Adresse')
|
||||
->prefix('/')
|
||||
->helperText('Die Startseite heißt „start“.')
|
||||
->required()
|
||||
->alphaDash()
|
||||
->maxLength(80)
|
||||
->disabled(fn (?Page $record): bool => $record?->isHome() ?? false)
|
||||
->dehydrated()
|
||||
->unique(ignoreRecord: true, modifyRuleUsing: fn (Unique $rule, callable $get) => $rule->where('site_id', $get('site_id'))),
|
||||
TextInput::make('menu_label')->label('Name im Menü (optional)')->maxLength(60),
|
||||
Select::make('menu_location')->label('Menü')->options(Page::MENU_LOCATIONS)->default('main')->required(),
|
||||
Toggle::make('is_published')->label('Veröffentlicht')->default(true),
|
||||
]),
|
||||
Section::make('Suchmaschinen')
|
||||
->columnSpan(1)
|
||||
->collapsed()
|
||||
->schema([
|
||||
TextInput::make('seo_title')->label('Seitentitel (Google)')->maxLength(70),
|
||||
Textarea::make('seo_description')->label('Beschreibung (Google)')->rows(3)->maxLength(170),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Tables;
|
||||
|
||||
use App\Models\Page;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class PagesTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->reorderable('sort_order')
|
||||
->defaultSort('sort_order')
|
||||
->paginated(false)
|
||||
->description('Reihenfolge per Ziehen = Reihenfolge im Menü.')
|
||||
->columns([
|
||||
TextColumn::make('title')->label('Seite')->weight('medium')->description(fn (Page $record): string => $record->isHome() ? '/' : '/'.$record->slug),
|
||||
TextColumn::make('menu_location')->label('Menü')->formatStateUsing(fn (string $state): string => Page::MENU_LOCATIONS[$state] ?? $state)->badge(),
|
||||
TextColumn::make('sections')->label('Bausteine')->state(fn (Page $record): int => count($record->sections ?? [])),
|
||||
ToggleColumn::make('is_published')->label('Veröffentlicht'),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('open')
|
||||
->label('Ansehen')
|
||||
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
|
||||
->color('gray')
|
||||
->url(fn (Page $record): string => $record->url(), shouldOpenInNewTab: true),
|
||||
EditAction::make(),
|
||||
DeleteAction::make()->visible(fn (Page $record): bool => ! $record->isHome()),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ class PhotoResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Bilder';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalEmails\Pages;
|
||||
|
||||
use App\Filament\Resources\PortalEmails\PortalEmailResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListPortalEmails extends ListRecords
|
||||
{
|
||||
protected static string $resource = PortalEmailResource::class;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalEmails;
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Filament\Resources\PortalEmails\Pages\ListPortalEmails;
|
||||
use App\Filament\Resources\PortalEmails\Tables\PortalEmailsTable;
|
||||
use App\Models\PortalEmail;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class PortalEmailResource extends Resource
|
||||
{
|
||||
protected static ?string $model = PortalEmail::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedEnvelopeOpen;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $modelLabel = 'Portal-E-Mail';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Portal-E-Mails';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return PortalEmailsTable::configure($table);
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$review = PortalEmail::query()->where('status', PortalEmailStatus::NeedsReview)->count();
|
||||
|
||||
return $review > 0 ? (string) $review : null;
|
||||
}
|
||||
|
||||
public static function getNavigationBadgeColor(): string
|
||||
{
|
||||
return 'danger';
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListPortalEmails::route('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalEmails\Tables;
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Models\PortalEmail;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class PortalEmailsTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('received_at', 'desc')
|
||||
->description('Buchungs-E-Mails der Portale werden jede Minute gelesen. Erkannte Buchungen werden sofort gesperrt; unklare E-Mails bitte prüfen.')
|
||||
->columns([
|
||||
TextColumn::make('received_at')->label('Eingang')->dateTime('d.m. H:i')->sortable(),
|
||||
TextColumn::make('channel.name')->label('Portal'),
|
||||
TextColumn::make('type')->label('Art')->badge(),
|
||||
TextColumn::make('status')->label('Ergebnis')->badge()->description(fn (PortalEmail $record): ?string => $record->note),
|
||||
TextColumn::make('period')->label('Zeitraum')->state(fn (PortalEmail $record): ?string => $record->period())->placeholder('–'),
|
||||
TextColumn::make('reference')->label('Buchungsnr.')->placeholder('–'),
|
||||
TextColumn::make('subject')->label('Betreff')->limit(50)->tooltip(fn (PortalEmail $record): ?string => $record->excerpt),
|
||||
])
|
||||
->filters([
|
||||
SelectFilter::make('status')->label('Ergebnis')->options(PortalEmailStatus::class),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('block')
|
||||
->label('Sperre anlegen')
|
||||
->icon(Heroicon::OutlinedLockClosed)
|
||||
->color('danger')
|
||||
->visible(fn (PortalEmail $record): bool => $record->status === PortalEmailStatus::NeedsReview)
|
||||
->fillForm(fn (PortalEmail $record): array => ['starts_on' => $record->starts_on, 'ends_on' => $record->ends_on])
|
||||
->schema([
|
||||
DatePicker::make('starts_on')->label('Anreise')->required(),
|
||||
DatePicker::make('ends_on')->label('Abreise')->after('starts_on')->required(),
|
||||
])
|
||||
->action(function (PortalEmail $record, array $data): void {
|
||||
$block = $record->channel->blockedPeriods()->create([
|
||||
'property_id' => $record->channel->property_id,
|
||||
'starts_on' => $data['starts_on'],
|
||||
'ends_on' => $data['ends_on'],
|
||||
'reason' => "{$record->channel->name} (E-Mail, geprüft)".($record->reference ? ": {$record->reference}" : ''),
|
||||
'source' => 'email',
|
||||
'external_uid' => 'email:'.($record->reference ?? $record->message_id),
|
||||
]);
|
||||
$record->update(['status' => PortalEmailStatus::Blocked, 'blocked_period_id' => $block->id, 'starts_on' => $data['starts_on'], 'ends_on' => $data['ends_on']]);
|
||||
|
||||
Notification::make()->title('Zeitraum gesperrt')->success()->send();
|
||||
}),
|
||||
Action::make('reviewed')
|
||||
->label('Als geprüft markieren')
|
||||
->icon(Heroicon::OutlinedCheck)
|
||||
->color('gray')
|
||||
->visible(fn (PortalEmail $record): bool => $record->status === PortalEmailStatus::NeedsReview)
|
||||
->action(fn (PortalEmail $record) => $record->update(['status' => PortalEmailStatus::Reviewed])),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
use App\Filament\Resources\Properties\Pages\EditProperty;
|
||||
use App\Filament\Resources\Properties\Pages\ListProperties;
|
||||
use App\Filament\Resources\Properties\RelationManagers\BlockedPeriodsRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\ExtrasRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\SpecialOffersRelationManager;
|
||||
@@ -50,6 +51,7 @@ public static function getRelations(): array
|
||||
SpecialOffersRelationManager::class,
|
||||
ExtrasRelationManager::class,
|
||||
BlockedPeriodsRelationManager::class,
|
||||
ChannelsRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Properties\RelationManagers;
|
||||
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Channels\ChannelRegistry;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Infolists\Components\RepeatableEntry;
|
||||
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class ChannelsRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'channels';
|
||||
|
||||
protected static ?string $title = 'Portale & Kanäle';
|
||||
|
||||
protected static ?string $modelLabel = 'Portal';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Portale';
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
$registry = app(ChannelRegistry::class);
|
||||
|
||||
return $schema
|
||||
->columns(2)
|
||||
->components([
|
||||
TextInput::make('name')
|
||||
->label('Name')
|
||||
->placeholder('z. B. FeWo-direkt')
|
||||
->required()
|
||||
->maxLength(100),
|
||||
Select::make('connector')
|
||||
->label('Anbindung')
|
||||
->options($registry->options())
|
||||
->default('ical')
|
||||
->live()
|
||||
->required(),
|
||||
Group::make()
|
||||
->columnSpanFull()
|
||||
->schema(fn (Get $get): array => filled($get('connector')) ? $registry->connectors()[$get('connector')]::settingsSchema() : []),
|
||||
TextEntry::make('export_url')
|
||||
->label('Unsere Kalender-Adresse für dieses Portal')
|
||||
->helperText('Diese Adresse im Portal unter „Kalender importieren“ eintragen. Sie enthält alle Belegungen außer denen dieses Portals.')
|
||||
->state(fn (?Channel $record): ?string => $record?->exportUrl())
|
||||
->copyable()
|
||||
->visible(fn (?Channel $record): bool => $record !== null)
|
||||
->columnSpanFull(),
|
||||
TextInput::make('settings.email_senders')
|
||||
->label('Absender der Buchungs-E-Mails (Schnellerkennung)')
|
||||
->helperText('Komma-getrennt, z. B. „fewo-direkt.de, vrbo.com“. Buchungsbestätigungen dieser Absender werden sofort gesperrt.')
|
||||
->maxLength(500)
|
||||
->columnSpanFull(),
|
||||
Toggle::make('requires_manual_blocking')
|
||||
->label('Zusätzlich von Hand sperren (Sofortbuchung)')
|
||||
->helperText('Bei jeder Belegung über andere Wege entsteht eine Aufgabe „Im Portal sperren“ – für Portale, die unseren Kalender zu selten abholen.')
|
||||
->live()
|
||||
->columnSpanFull(),
|
||||
TextInput::make('manage_url')
|
||||
->label('Link zum Kalender im Vermieterbereich')
|
||||
->url()
|
||||
->maxLength(2048)
|
||||
->visible(fn (Get $get): bool => (bool) $get('requires_manual_blocking'))
|
||||
->columnSpanFull(),
|
||||
Toggle::make('is_active')
|
||||
->label('Aktiv')
|
||||
->default(true),
|
||||
]);
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('name')
|
||||
->description('Unser System ist führend: Belegungen der Portale werden alle 5 Minuten eingelesen, jedes Portal erhält einen eigenen Kalender mit allen übrigen Belegungen.')
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Portal')->weight('medium'),
|
||||
TextColumn::make('status')
|
||||
->label('Status')
|
||||
->badge()
|
||||
->state(fn (Channel $record): string => match (true) {
|
||||
! $record->is_active => 'Inaktiv',
|
||||
! $record->importsOccupations() => 'Nur Export',
|
||||
$record->last_error !== null => 'Fehler',
|
||||
$record->isStale() => 'Veraltet',
|
||||
default => 'OK',
|
||||
})
|
||||
->color(fn (string $state): string => match ($state) {
|
||||
'OK' => 'success',
|
||||
'Fehler', 'Veraltet' => 'danger',
|
||||
default => 'gray',
|
||||
})
|
||||
->tooltip(fn (Channel $record): ?string => $record->last_error),
|
||||
TextColumn::make('last_success_at')->label('Letzter Abgleich')->since()->placeholder('–'),
|
||||
TextColumn::make('requires_manual_blocking')
|
||||
->label('Handpflege')
|
||||
->formatStateUsing(fn (bool $state): string => $state ? 'ja' : '–'),
|
||||
])
|
||||
->headerActions([
|
||||
CreateAction::make(),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('sync')
|
||||
->label('Jetzt abgleichen')
|
||||
->icon(Heroicon::OutlinedArrowPath)
|
||||
->visible(fn (Channel $record): bool => $record->importsOccupations())
|
||||
->action(function (Channel $record, SyncChannel $syncChannel): void {
|
||||
$log = $syncChannel->handle($record);
|
||||
|
||||
$log->successful
|
||||
? Notification::make()->title("{$log->events} Belegungen eingelesen")->body("Neu: {$log->added}, geändert: {$log->changed}, entfernt: {$log->removed}, Konflikte: {$log->conflicts}")->success()->send()
|
||||
: Notification::make()->title('Abgleich fehlgeschlagen')->body($log->message)->danger()->send();
|
||||
}),
|
||||
Action::make('logs')
|
||||
->label('Protokoll')
|
||||
->icon(Heroicon::OutlinedListBullet)
|
||||
->color('gray')
|
||||
->modalSubmitAction(false)
|
||||
->modalCancelActionLabel('Schließen')
|
||||
->schema([
|
||||
RepeatableEntry::make('recentLogs')
|
||||
->hiddenLabel()
|
||||
->state(fn (Channel $record): array => $record->syncLogs()->limit(30)->get()->map(fn (ChannelSyncLog $log): array => [
|
||||
'time' => $log->created_at->format('d.m. H:i'),
|
||||
'result' => $log->successful ? "✓ {$log->events} Belegungen (+{$log->added} ~{$log->changed} -{$log->removed})" : '✗ '.$log->message,
|
||||
'conflicts' => $log->conflicts ?: '',
|
||||
])->all())
|
||||
->table([
|
||||
TableColumn::make('Zeit'),
|
||||
TableColumn::make('Ergebnis'),
|
||||
TableColumn::make('Konflikte'),
|
||||
])
|
||||
->schema([
|
||||
TextEntry::make('time'),
|
||||
TextEntry::make('result'),
|
||||
TextEntry::make('conflicts'),
|
||||
]),
|
||||
]),
|
||||
EditAction::make(),
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
+94
-19
@@ -3,8 +3,8 @@
|
||||
namespace App\Filament\Resources\Properties\RelationManagers;
|
||||
|
||||
use App\Enums\DiscountType;
|
||||
use App\Enums\OfferKind;
|
||||
use App\Models\SpecialOffer;
|
||||
use App\Support\Money;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
@@ -12,12 +12,14 @@
|
||||
use Filament\Forms\Components\CheckboxList;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
@@ -33,10 +35,48 @@ class SpecialOffersRelationManager extends RelationManager
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Sonderangebote';
|
||||
|
||||
/**
|
||||
* Starting points for typical offers in the create form.
|
||||
*
|
||||
* @var array<string, array{label: string, values: array<string, mixed>}>
|
||||
*/
|
||||
private const PRESETS = [
|
||||
'last_minute' => ['label' => 'Last Minute (−15 %, bis 14 Tage vor Anreise)', 'values' => ['kind' => 'rule', 'name' => 'Last Minute', 'discount_type' => 'percent', 'discount_value' => 15, 'max_days_before_arrival' => 14]],
|
||||
'early_bird' => ['label' => 'Frühbucher (−5 %, ab 180 Tage vor Anreise)', 'values' => ['kind' => 'rule', 'name' => 'Frühbucher', 'discount_type' => 'percent', 'discount_value' => 5, 'min_days_before_arrival' => 180]],
|
||||
'long_stay' => ['label' => 'Längerer Aufenthalt (ab 3 Nächten −10 %)', 'values' => ['kind' => 'rule', 'name' => 'Ab 3 Nächten', 'discount_type' => 'percent', 'discount_value' => 10, 'min_nights' => 3]],
|
||||
'week' => ['label' => '7 = 6 (eine Nacht gratis ab 7 Nächten)', 'values' => ['kind' => 'rule', 'name' => '7 Nächte bleiben, 6 bezahlen', 'discount_type' => 'free_nights', 'discount_value' => 1, 'min_nights' => 7]],
|
||||
'weekend' => ['label' => 'Special Weekend (Anreise Freitag, 2 Nächte)', 'values' => ['kind' => 'rule', 'name' => 'Special Weekend', 'discount_type' => 'percent', 'discount_value' => 10, 'arrival_weekdays' => [5], 'min_nights' => 2, 'max_nights' => 2]],
|
||||
'gap' => ['label' => 'Lückenfüller (Lücken bis 4 Nächte −20 %)', 'values' => ['kind' => 'gap_filler', 'name' => 'Kurzfristige Lücke', 'discount_type' => 'percent', 'discount_value' => 20, 'max_gap_nights' => 4, 'waives_min_stay' => true]],
|
||||
'fixed_week' => ['label' => 'Fester Termin (eine Woche zum Pauschalpreis)', 'values' => ['kind' => 'fixed_dates', 'name' => 'Ostsee-Woche', 'discount_type' => 'fixed_stay_price']],
|
||||
];
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Section::make('Art des Angebots')
|
||||
->columns(2)
|
||||
->schema([
|
||||
Select::make('preset')
|
||||
->label('Vorlage (optional)')
|
||||
->helperText('Füllt typische Einstellungen vor – alles bleibt änderbar.')
|
||||
->options(collect(self::PRESETS)->map(fn (array $preset): string => $preset['label'])->all())
|
||||
->dehydrated(false)
|
||||
->live()
|
||||
->afterStateUpdated(function (?string $state, Set $set): void {
|
||||
foreach (self::PRESETS[$state]['values'] ?? [] as $field => $value) {
|
||||
$set($field, $value);
|
||||
}
|
||||
})
|
||||
->visibleOn('create'),
|
||||
Radio::make('kind')
|
||||
->label('Art')
|
||||
->options(OfferKind::class)
|
||||
->default(OfferKind::Rule)
|
||||
->live()
|
||||
->required()
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Angebot')
|
||||
->columns(2)
|
||||
->schema([
|
||||
@@ -60,24 +100,54 @@ public function form(Schema $schema): Schema
|
||||
DiscountType::AmountPerStay => 'Rabatt pro Aufenthalt',
|
||||
DiscountType::NightlyRate => 'Sonderpreis pro Nacht',
|
||||
DiscountType::FreeNights => 'Anzahl Gratis-Nächte',
|
||||
DiscountType::FixedStayPrice => 'Pauschalpreis für alle Nächte',
|
||||
})
|
||||
->suffix(fn (Get $get): string => match ($this->discountType($get)) {
|
||||
DiscountType::Percent => '%',
|
||||
DiscountType::FreeNights => 'Nächte',
|
||||
default => '€',
|
||||
})
|
||||
->helperText(fn (Get $get): ?string => $this->discountType($get) === DiscountType::FreeNights ? 'Die günstigsten Nächte des Aufenthalts sind gratis.' : null)
|
||||
->helperText(fn (Get $get): ?string => match ($this->discountType($get)) {
|
||||
DiscountType::FreeNights => 'Die günstigsten Nächte des Aufenthalts sind gratis.',
|
||||
DiscountType::FixedStayPrice => 'Übernachtungen zusammen; Endreinigung und Extras kommen dazu.',
|
||||
default => null,
|
||||
})
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->required()
|
||||
->formatStateUsing(fn (?int $state, ?SpecialOffer $record): int|string|null => $state !== null && $this->isMoney($record?->discount_type) ? number_format($state / 100, 2, '.', '') : $state)
|
||||
->dehydrateStateUsing(fn (string|int|float|null $state, Get $get): int => $this->isMoney($this->discountType($get)) ? (int) round((float) $state * 100) : (int) $state),
|
||||
->formatStateUsing(fn (?int $state, ?SpecialOffer $record): int|string|null => $state !== null && $record?->discount_type?->isMoney() ? number_format($state / 100, 2, '.', '') : $state)
|
||||
->dehydrateStateUsing(fn (string|int|float|null $state, Get $get): int => $this->discountType($get)->isMoney() ? (int) round((float) $state * 100) : (int) $state),
|
||||
Toggle::make('is_active')->label('Aktiv')->default(true),
|
||||
Toggle::make('is_public')->label('Auf der Webseite bewerben')->default(true),
|
||||
Toggle::make('is_combinable')
|
||||
->label('Mit anderen kombinierbaren Angeboten kombinierbar')
|
||||
->helperText('Sonst erhält der Gast automatisch das für ihn beste Einzelangebot.')
|
||||
->columnSpanFull(),
|
||||
->helperText('Sonst erhält der Gast automatisch das für ihn beste Einzelangebot.'),
|
||||
]),
|
||||
Section::make('Bewerbung auf der Webseite')
|
||||
->description('Welche Angebote gerade erscheinen, ergibt sich automatisch: aktiv, ohne Aktionscode, im Buchungszeitraum, feste Termine nur solange frei, Lückenfüller je gefundener Lücke. Mehrere gleichzeitig werden im Baustein „Sonderangebote“ nebeneinander, als Liste oder rollierend gezeigt.')
|
||||
->columns(3)
|
||||
->schema([
|
||||
Toggle::make('is_public')->label('Auf der Webseite bewerben')->default(true),
|
||||
Toggle::make('is_featured')->label('Hervorheben')->helperText('Steht vorne, ist farbig markiert und erscheint im Titelbereich.'),
|
||||
TextInput::make('priority')->label('Priorität')->helperText('Höher = weiter vorne')->integer()->default(0),
|
||||
]),
|
||||
Section::make('Termin')
|
||||
->description('Der Gast muss genau diesen Zeitraum buchen. Beworben wird er nur, solange er frei ist.')
|
||||
->columns(2)
|
||||
->visible(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates)
|
||||
->schema([
|
||||
DatePicker::make('stay_from')->label('Anreise')->required(),
|
||||
DatePicker::make('stay_until')->label('Abreise')->after('stay_from')->required(),
|
||||
]),
|
||||
Section::make('Kalenderlücken')
|
||||
->description('Freie Zeiträume zwischen zwei Buchungen oder Sperrzeiten. Die Webseite zeigt bis zu drei gefundene Lücken mit Termin und Preis.')
|
||||
->columns(2)
|
||||
->visible(fn (Get $get): bool => $this->kind($get) === OfferKind::GapFiller)
|
||||
->schema([
|
||||
TextInput::make('max_gap_nights')->label('Lücken bis höchstens … Nächte')->integer()->minValue(1)->default(4)->required(),
|
||||
Toggle::make('waives_min_stay')
|
||||
->label('Mindestaufenthalt der Saison aufheben')
|
||||
->helperText('Damit auch kurze Lücken (z. B. 2 Nächte bei 5 Nächten Mindestaufenthalt) buchbar werden.')
|
||||
->default(true),
|
||||
]),
|
||||
Section::make('Bedingungen')
|
||||
->description('Leere Felder bedeuten: keine Einschränkung.')
|
||||
@@ -103,15 +173,15 @@ public function form(Schema $schema): Schema
|
||||
->helperText('Frühbucher, z. B. 180')
|
||||
->integer()
|
||||
->minValue(0),
|
||||
TextInput::make('min_nights')->label('Mindestens Nächte')->integer()->minValue(1),
|
||||
TextInput::make('max_nights')->label('Höchstens Nächte')->integer()->minValue(1),
|
||||
TextInput::make('min_nights')->label('Mindestens Nächte')->integer()->minValue(1)->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
TextInput::make('max_nights')->label('Höchstens Nächte')->integer()->minValue(1)->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
CheckboxList::make('arrival_weekdays')
|
||||
->label('Anreise nur am')
|
||||
->options([1 => 'Mo', 2 => 'Di', 3 => 'Mi', 4 => 'Do', 5 => 'Fr', 6 => 'Sa', 7 => 'So'])
|
||||
->columns(7)
|
||||
->columnSpanFull(),
|
||||
DatePicker::make('stay_from')->label('Aufenthalt frühestens ab'),
|
||||
DatePicker::make('stay_until')->label('Abreise spätestens am'),
|
||||
DatePicker::make('stay_from')->label('Aufenthalt frühestens ab')->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
DatePicker::make('stay_until')->label('Abreise spätestens am')->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
DateTimePicker::make('bookable_from')->label('Buchbar ab')->seconds(false),
|
||||
DateTimePicker::make('bookable_until')->label('Buchbar bis')->seconds(false),
|
||||
]),
|
||||
@@ -122,19 +192,22 @@ public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('name')
|
||||
->defaultSort('priority', 'desc')
|
||||
->description('Sonderangebote werden bei jeder Preisberechnung automatisch geprüft und angewendet.')
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Angebot')
|
||||
->description(fn (SpecialOffer $record): ?string => $record->public_description),
|
||||
TextColumn::make('kind')->label('Art')->badge(),
|
||||
TextColumn::make('discount')
|
||||
->label('Vorteil')
|
||||
->state(fn (SpecialOffer $record): string => match ($record->discount_type) {
|
||||
DiscountType::Percent => "−{$record->discount_value} %",
|
||||
DiscountType::AmountPerStay => '−'.Money::format($record->discount_value),
|
||||
DiscountType::NightlyRate => Money::format($record->discount_value).' / Nacht',
|
||||
DiscountType::FreeNights => "{$record->discount_value} Nacht/Nächte gratis",
|
||||
}),
|
||||
->state(fn (SpecialOffer $record): string => $record->advantageLabel()),
|
||||
TextColumn::make('conditions')
|
||||
->label('Bedingungen')
|
||||
->state(fn (SpecialOffer $record): string => implode(' · ', $record->conditionSummary()) ?: '–')
|
||||
->wrap(),
|
||||
IconColumn::make('is_featured')->label('Hervorgehoben')->boolean(),
|
||||
TextColumn::make('priority')->label('Priorität')->sortable(),
|
||||
TextColumn::make('code')->label('Code')->placeholder('automatisch')->badge(),
|
||||
TextColumn::make('season_names')->label('Saisons')->badge()->placeholder('alle'),
|
||||
IconColumn::make('is_combinable')->label('Kombinierbar')->boolean(),
|
||||
@@ -157,8 +230,10 @@ private function discountType(Get $get): DiscountType
|
||||
return $type instanceof DiscountType ? $type : (DiscountType::tryFrom((string) $type) ?? DiscountType::Percent);
|
||||
}
|
||||
|
||||
private function isMoney(?DiscountType $type): bool
|
||||
private function kind(Get $get): OfferKind
|
||||
{
|
||||
return in_array($type, [DiscountType::AmountPerStay, DiscountType::NightlyRate], true);
|
||||
$kind = $get('kind');
|
||||
|
||||
return $kind instanceof OfferKind ? $kind : (OfferKind::tryFrom((string) $kind) ?? OfferKind::Rule);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace App\Filament\Resources\Properties\Schemas;
|
||||
|
||||
use App\Filament\Forms\Components\EuroInput;
|
||||
use App\Models\Site;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\TimePicker;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
@@ -46,6 +48,10 @@ public static function configure(Schema $schema): Schema
|
||||
TimePicker::make('check_out_time')
|
||||
->label('Abreise bis')
|
||||
->seconds(false),
|
||||
Select::make('site_id')
|
||||
->label('Website')
|
||||
->options(fn (): array => Site::query()->pluck('name', 'id')->all())
|
||||
->placeholder('keine'),
|
||||
Toggle::make('is_active')
|
||||
->label('Aktiv (auf der Webseite buchbar)')
|
||||
->default(true),
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Sites\Pages;
|
||||
|
||||
use App\Filament\Resources\Sites\SiteResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateSite extends CreateRecord
|
||||
{
|
||||
protected static string $resource = SiteResource::class;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Sites\Pages;
|
||||
|
||||
use App\Filament\Resources\Sites\SiteResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditSite extends EditRecord
|
||||
{
|
||||
protected static string $resource = SiteResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Sites\Pages;
|
||||
|
||||
use App\Filament\Resources\Sites\SiteResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListSites extends ListRecords
|
||||
{
|
||||
protected static string $resource = SiteResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Sites\Schemas;
|
||||
|
||||
use App\Filament\Resources\Appearances\Schemas\AppearanceForm;
|
||||
use App\Models\Site;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
class SiteForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(2)
|
||||
->components([
|
||||
Section::make('Website')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('name')->label('Name')->required()->maxLength(120),
|
||||
TextInput::make('domain')
|
||||
->label('Domain')
|
||||
->placeholder('www.fewo-stommer.de')
|
||||
->helperText('Leer = Standard-Website für alle Adressen ohne eigene Zuordnung.')
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(190),
|
||||
Select::make('theme')
|
||||
->label('Theme')
|
||||
->options(fn (): array => app(ThemeRegistry::class)->options())
|
||||
->default(config('themes.base'))
|
||||
->required()
|
||||
->live()
|
||||
->helperText(fn (Get $get): ?string => filled($get('theme')) ? app(ThemeRegistry::class)->get($get('theme'))->description : null)
|
||||
->hintAction(
|
||||
Action::make('previewTheme')
|
||||
->label('Vorschau')
|
||||
->icon('heroicon-o-eye')
|
||||
->url(fn (Get $get): string => URL::temporarySignedRoute('home', now()->addDay(), ['theme' => $get('theme') ?: config('themes.base')]), shouldOpenInNewTab: true),
|
||||
),
|
||||
Toggle::make('is_default')->label('Standard-Website')->inline(false),
|
||||
]),
|
||||
Section::make('Farben des Themes')
|
||||
->description('Grundfarben dieser Website; saisonale Erscheinungsbilder können einzelne Farben zusätzlich ändern.')
|
||||
->columns(3)
|
||||
->collapsible()
|
||||
->schema(fn (Get $get, ?Site $record): array => AppearanceForm::tokenFields($record?->id, 'theme_settings.tokens', $get('theme'))),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Sites;
|
||||
|
||||
use App\Filament\Resources\Sites\Pages\CreateSite;
|
||||
use App\Filament\Resources\Sites\Pages\EditSite;
|
||||
use App\Filament\Resources\Sites\Pages\ListSites;
|
||||
use App\Filament\Resources\Sites\Schemas\SiteForm;
|
||||
use App\Filament\Resources\Sites\Tables\SitesTable;
|
||||
use App\Models\Site;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class SiteResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Site::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedGlobeAlt;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||||
|
||||
protected static ?string $modelLabel = 'Website';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Websites';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return SiteForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return SitesTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListSites::route('/'),
|
||||
'create' => CreateSite::route('/create'),
|
||||
'edit' => EditSite::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Sites\Tables;
|
||||
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class SitesTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Website')->weight('medium'),
|
||||
TextColumn::make('domain')->label('Domain')->placeholder('alle übrigen Adressen'),
|
||||
TextColumn::make('theme')->label('Theme')->formatStateUsing(fn (string $state): string => app(ThemeRegistry::class)->get($state)->name),
|
||||
TextColumn::make('properties_count')->label('Wohnungen')->counts('properties'),
|
||||
IconColumn::make('is_default')->label('Standard')->boolean(),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Widgets;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Widgets\StatsOverviewWidget;
|
||||
use Filament\Widgets\StatsOverviewWidget\Stat;
|
||||
|
||||
class BookingStats extends StatsOverviewWidget
|
||||
{
|
||||
protected static ?int $sort = 1;
|
||||
|
||||
public static function canView(): bool
|
||||
{
|
||||
return (bool) auth()->user()?->hasRole(UserRole::Admin, UserRole::Rentals);
|
||||
}
|
||||
|
||||
protected function getStats(): array
|
||||
{
|
||||
$today = CarbonImmutable::today();
|
||||
$openRequests = Booking::query()->where('status', BookingStatus::Reserved)->count();
|
||||
$arrivals = Booking::query()->whereIn('status', BookingStatus::occupying())->whereBetween('arrival', [$today, $today->addDays(14)])->count();
|
||||
|
||||
$unpaid = Booking::query()->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid])->with('payments')->get();
|
||||
$overdue = $unpaid->filter(fn (Booking $booking): bool => ($booking->deposit_due_on?->isPast() && $booking->openDeposit() > 0)
|
||||
|| ($booking->balance_due_on->isPast() && $booking->openAmount() > 0));
|
||||
|
||||
$portalProblems = Channel::query()->active()->get()->filter(fn (Channel $channel): bool => $channel->isStale())->count()
|
||||
+ ChannelTask::query()->open()->count()
|
||||
+ PortalEmail::query()->where('status', PortalEmailStatus::NeedsReview)->count();
|
||||
|
||||
return [
|
||||
Stat::make('Offene Anfragen', $openRequests)
|
||||
->description($openRequests > 0 ? 'warten auf Ihre Bestätigung' : 'alles bearbeitet')
|
||||
->color($openRequests > 0 ? 'warning' : 'success')
|
||||
->url(BookingResource::getUrl('index', ['filters' => ['status' => ['values' => [BookingStatus::Reserved->value]]]])),
|
||||
Stat::make('Anreisen (14 Tage)', $arrivals),
|
||||
Stat::make('Offene Zahlungen', Money::format($unpaid->sum(fn (Booking $booking): int => $booking->openAmount())))
|
||||
->description($overdue->isEmpty() ? 'nichts überfällig' : "{$overdue->count()} überfällig")
|
||||
->color($overdue->isEmpty() ? 'success' : 'danger'),
|
||||
Stat::make('Auslastung '.$today->year, $this->occupancy($today->startOfYear(), $today->endOfYear()->startOfDay()->addDay()).' %')
|
||||
->description('eigene Buchungen und Portale'),
|
||||
Stat::make('Portale', $portalProblems === 0 ? 'OK' : "{$portalProblems} offen")
|
||||
->description('Abgleich, Aufgaben, E-Mails')
|
||||
->color($portalProblems === 0 ? 'success' : 'danger')
|
||||
->url(ChannelTaskResource::getUrl('index')),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Share of nights in [$from, $until) occupied by bookings or portal occupations (own blocks do not count).
|
||||
*/
|
||||
private function occupancy(CarbonImmutable $from, CarbonImmutable $until): int
|
||||
{
|
||||
$nights = [];
|
||||
$periods = Booking::query()->whereIn('status', BookingStatus::occupying())->overlapping($from, $until)->get(['arrival', 'departure'])
|
||||
->map(fn (Booking $booking): array => [$booking->arrival, $booking->departure])
|
||||
->concat(BlockedPeriod::query()->whereNotNull('channel_id')->overlapping($from, $until)->get(['starts_on', 'ends_on'])
|
||||
->map(fn (BlockedPeriod $block): array => [$block->starts_on, $block->ends_on]));
|
||||
|
||||
foreach ($periods as [$start, $end]) {
|
||||
for ($night = $start->max($from); $night->lessThan($end) && $night->lessThan($until); $night = $night->addDay()) {
|
||||
$nights[$night->toDateString()] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return (int) round(count($nights) / max(1, $from->diffInDays($until)) * 100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Widgets;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Money;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Filament\Widgets\TableWidget;
|
||||
|
||||
class UpcomingStays extends TableWidget
|
||||
{
|
||||
protected static ?int $sort = 2;
|
||||
|
||||
protected int|string|array $columnSpan = 'full';
|
||||
|
||||
protected static ?string $heading = 'Nächste Aufenthalte (30 Tage)';
|
||||
|
||||
public static function canView(): bool
|
||||
{
|
||||
return (bool) auth()->user()?->hasRole(UserRole::Admin, UserRole::Rentals);
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->query(fn () => Booking::query()
|
||||
->with(['guest', 'payments'])
|
||||
->whereIn('status', BookingStatus::occupying())
|
||||
->whereDate('departure', '>=', today())
|
||||
->whereDate('arrival', '<=', today()->addDays(30)))
|
||||
->defaultSort('arrival')
|
||||
->paginated(false)
|
||||
->emptyStateHeading('Keine Aufenthalte in den nächsten 30 Tagen')
|
||||
->recordUrl(fn (Booking $record): string => BookingResource::getUrl('view', ['record' => $record]))
|
||||
->columns([
|
||||
TextColumn::make('arrival')->label('Anreise')->date('D, d.m.')
|
||||
->description(fn (Booking $record): ?string => $record->arrival->isToday() ? 'heute' : ($record->arrival->isPast() ? 'läuft' : null)),
|
||||
TextColumn::make('departure')->label('Abreise')->date('D, d.m.'),
|
||||
TextColumn::make('guest.last_name')->label('Gast')->formatStateUsing(fn (Booking $record): string => $record->guest->full_name),
|
||||
TextColumn::make('guests')->label('Pers.'),
|
||||
TextColumn::make('status')->label('Status')->badge(),
|
||||
TextColumn::make('open')->label('Offen')
|
||||
->state(fn (Booking $record): string => $record->openAmount() > 0 ? Money::format($record->openAmount()) : '–')
|
||||
->color(fn (Booking $record): ?string => $record->openAmount() > 0 ? 'danger' : null),
|
||||
TextColumn::make('arrival_info_sent_at')->label('Anreiseinfo')->since()->placeholder('noch nicht'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Actions\MonitorChannels;
|
||||
use App\Actions\ProcessPortalMail;
|
||||
use App\Channels\ICal\ICalFeed;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Channels\Mail\PortalMail;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
/**
|
||||
* Public endpoints of the channel synchronisation: export feeds for portals, the health check for
|
||||
* external monitoring and the callback of the optional blocking automation.
|
||||
*/
|
||||
class ChannelController extends Controller
|
||||
{
|
||||
public function feed(string $token, ICalFeed $feed): Response
|
||||
{
|
||||
$channel = Channel::query()->where('export_token', $token)->where('is_active', true)->firstOrFail();
|
||||
|
||||
return response($feed->build($channel), 200, [
|
||||
'Content-Type' => 'text/calendar; charset=utf-8',
|
||||
'Content-Disposition' => 'inline; filename="belegung.ics"',
|
||||
'Cache-Control' => 'no-cache, max-age=0',
|
||||
]);
|
||||
}
|
||||
|
||||
public function health(Request $request): JsonResponse
|
||||
{
|
||||
$token = config('fewo.channels.health_token');
|
||||
abort_if(blank($token) || ! hash_equals($token, (string) $request->query('token')), 404);
|
||||
|
||||
$channels = Channel::query()->active()->get()->map(fn (Channel $channel): array => [
|
||||
'name' => $channel->name,
|
||||
'imports' => $channel->importsOccupations(),
|
||||
'ok' => ! $channel->isStale(),
|
||||
'last_success_at' => $channel->last_success_at?->toIso8601String(),
|
||||
'last_error' => $channel->last_error,
|
||||
]);
|
||||
$openTasks = ChannelTask::query()->open()->count();
|
||||
$mailbox = [
|
||||
'configured' => MailboxReader::isConfigured(),
|
||||
'ok' => ! MonitorChannels::mailboxIsStale(),
|
||||
'last_success_at' => Cache::get(MailboxReader::LAST_SUCCESS_KEY),
|
||||
'last_error' => Cache::get(MailboxReader::LAST_ERROR_KEY),
|
||||
];
|
||||
|
||||
$ok = $channels->every(fn (array $channel): bool => $channel['ok']) && $mailbox['ok'];
|
||||
|
||||
return response()->json([
|
||||
'status' => $ok ? 'ok' : 'degraded',
|
||||
'open_tasks' => $openTasks,
|
||||
'mailbox' => $mailbox,
|
||||
'channels' => $channels->values(),
|
||||
], $ok ? 200 : 503);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the task scheduler once (fallback for hosting without suitable cron jobs).
|
||||
*/
|
||||
public function scheduler(Request $request): JsonResponse
|
||||
{
|
||||
$token = config('fewo.scheduler_token');
|
||||
abort_if(blank($token) || ! hash_equals($token, (string) $request->query('token')), 404);
|
||||
|
||||
Artisan::call('schedule:run');
|
||||
|
||||
return response()->json(['ran_at' => now()->toIso8601String(), 'output' => trim(Artisan::output())]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push variant of the e-mail fast path, e.g. from an n8n IMAP trigger:
|
||||
* JSON {message_id, from, subject, text, received_at}, signed like the automation webhook.
|
||||
*/
|
||||
public function portalMail(Request $request, ProcessPortalMail $processPortalMail): JsonResponse
|
||||
{
|
||||
$this->verifySignature($request);
|
||||
|
||||
$data = $request->validate([
|
||||
'message_id' => ['required', 'string', 'max:255'],
|
||||
'from' => ['required', 'string', 'max:255'],
|
||||
'subject' => ['required', 'string', 'max:500'],
|
||||
'text' => ['required', 'string', 'max:200000'],
|
||||
'received_at' => ['nullable', 'date'],
|
||||
]);
|
||||
|
||||
$record = $processPortalMail->handle(new PortalMail(
|
||||
messageId: $data['message_id'],
|
||||
from: $data['from'],
|
||||
subject: $data['subject'],
|
||||
text: $data['text'],
|
||||
receivedAt: isset($data['received_at']) ? CarbonImmutable::parse($data['received_at']) : CarbonImmutable::now(),
|
||||
));
|
||||
|
||||
return response()->json([
|
||||
'processed' => $record !== null,
|
||||
'type' => $record?->type->value,
|
||||
'status' => $record?->status->value,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The automation reports a task as done. The raw body must be signed like the outgoing webhook.
|
||||
*/
|
||||
public function completeTask(Request $request, ChannelTask $task): JsonResponse
|
||||
{
|
||||
$this->verifySignature($request);
|
||||
|
||||
if ($task->status === ChannelTaskStatus::Open) {
|
||||
$task->complete('Automatisierung');
|
||||
}
|
||||
|
||||
return response()->json(['status' => $task->status->value]);
|
||||
}
|
||||
|
||||
private function verifySignature(Request $request): void
|
||||
{
|
||||
$secret = config('fewo.automation.secret');
|
||||
$signature = (string) $request->header('X-Signature');
|
||||
|
||||
abort_if(blank($secret) || ! hash_equals(hash_hmac('sha256', $request->getContent(), $secret), $signature), 403);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Support\Content;
|
||||
use App\Themes\SectionRegistry;
|
||||
use App\Themes\Theme;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\Response;
|
||||
|
||||
/**
|
||||
* Renders the website pages of the current site with the active theme.
|
||||
*/
|
||||
class PageController extends Controller
|
||||
{
|
||||
public function __construct(private SectionRegistry $sections) {}
|
||||
|
||||
/**
|
||||
* Resolved per call: the controller is built before the middleware has determined site and appearance.
|
||||
*/
|
||||
private function theme(): Theme
|
||||
{
|
||||
return app(Theme::class);
|
||||
}
|
||||
|
||||
public function home(): View
|
||||
{
|
||||
return $this->show(Page::HOME);
|
||||
}
|
||||
|
||||
public function show(string $slug): View
|
||||
{
|
||||
abort_unless($this->theme()->site->exists, 404);
|
||||
|
||||
$page = $this->theme()->site->pages()
|
||||
->where('slug', $slug)
|
||||
->where('is_published', true)
|
||||
->firstOrFail();
|
||||
|
||||
return view('theme::page', [
|
||||
'page' => $page,
|
||||
'sections' => $this->sections->render($this->theme(), $page->sections),
|
||||
'title' => $page->isHome() ? null : ($page->seo_title ?: $page->title),
|
||||
'description' => $page->seo_description ?: ($page->isHome() ? Content::get('seo.home.description') : null),
|
||||
'ogImage' => $this->theme()->heroPhoto()?->url('lg') ?: null,
|
||||
'structuredData' => $page->isHome() ? $this->structuredData() : null,
|
||||
]);
|
||||
}
|
||||
|
||||
public function sitemap(): Response
|
||||
{
|
||||
$pages = $this->theme()->site->exists
|
||||
? $this->theme()->site->pages()->where('is_published', true)->get()
|
||||
: collect();
|
||||
|
||||
return response()->view('sitemap', ['pages' => $pages], 200, ['Content-Type' => 'application/xml']);
|
||||
}
|
||||
|
||||
public function robots(): Response
|
||||
{
|
||||
return response(implode("\n", [
|
||||
'User-agent: *',
|
||||
'Disallow: /admin',
|
||||
'Disallow: /livewire',
|
||||
'Disallow: /automation',
|
||||
'Disallow: /bewertung',
|
||||
'Disallow: /angebote',
|
||||
'Sitemap: '.route('sitemap'),
|
||||
'',
|
||||
]), 200, ['Content-Type' => 'text/plain; charset=UTF-8']);
|
||||
}
|
||||
|
||||
/**
|
||||
* schema.org data of the property for search engines.
|
||||
*
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function structuredData(): ?array
|
||||
{
|
||||
$property = $this->theme()->property();
|
||||
if ($property === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return array_filter([
|
||||
'@context' => 'https://schema.org',
|
||||
'@type' => 'VacationRental',
|
||||
'name' => $property->name,
|
||||
'url' => route('home'),
|
||||
'image' => $this->theme()->heroPhoto()?->url('lg') ?: null,
|
||||
'address' => ['@type' => 'PostalAddress', 'streetAddress' => str($property->address)->before(',')->trim()->toString(), 'addressLocality' => 'Kühlungsborn', 'postalCode' => '18225', 'addressCountry' => 'DE'],
|
||||
'containsPlace' => ['@type' => 'Accommodation', 'floorSize' => ['@type' => 'QuantitativeValue', 'value' => $property->size_sqm, 'unitCode' => 'MTK'], 'occupancy' => ['@type' => 'QuantitativeValue', 'maxValue' => $property->max_guests]],
|
||||
'telephone' => config('fewo.owner.phone'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\User;
|
||||
use Closure;
|
||||
use Filament\Auth\MultiFactor\Http\Middleware\EnsureMultiFactorAuthenticationIsEnabled;
|
||||
use Filament\Facades\Filament;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* Filament evaluates "two-factor required" once per panel; this narrows it to administrators.
|
||||
* Other roles may set it up voluntarily in their profile.
|
||||
*/
|
||||
class RequireTwoFactorForAdmins extends EnsureMultiFactorAuthenticationIsEnabled
|
||||
{
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $user->hasRole(UserRole::Admin)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
return parent::handle($request, $next);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Themes\Theme;
|
||||
use App\Themes\ThemeFactory;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Determines site, theme and appearance for the website and activates the "theme::" views.
|
||||
*/
|
||||
class ResolveTheme
|
||||
{
|
||||
public function __construct(private ThemeFactory $factory) {}
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
app()->instance(Theme::class, $this->factory->forRequest($request)->activate());
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
use App\Actions\CreateReservation;
|
||||
use App\Actions\RequestMarketingConsent;
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\ReferralSource;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Extra;
|
||||
@@ -17,6 +18,7 @@
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
@@ -66,6 +68,12 @@ class BookingRequest extends Component
|
||||
/** Optional opt-in for offer e-mails (confirmed by double opt-in). */
|
||||
public bool $marketingOptIn = false;
|
||||
|
||||
public string $referralSource = '';
|
||||
|
||||
/** @var array{utm_source?: string, utm_medium?: string, utm_campaign?: string} UTM parameters of the landing URL */
|
||||
#[Locked]
|
||||
public array $utm = [];
|
||||
|
||||
/** Honeypot, must stay empty. */
|
||||
public string $website = '';
|
||||
|
||||
@@ -76,6 +84,11 @@ public function mount(?Property $property = null): void
|
||||
{
|
||||
$this->propertyId = ($property ?? Property::query()->where('is_active', true)->firstOrFail())->id;
|
||||
$this->month = CarbonImmutable::today()->format('Y-m');
|
||||
$this->prefillFromSearch();
|
||||
$this->utm = collect(request()->only(['utm_source', 'utm_medium', 'utm_campaign']))
|
||||
->filter(fn ($value): bool => is_string($value) && $value !== '')
|
||||
->map(fn (string $value): string => mb_substr($value, 0, 100))
|
||||
->all();
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
@@ -228,6 +241,7 @@ public function submit(CreateReservation $createReservation): void
|
||||
'city' => $this->city ?: null,
|
||||
],
|
||||
$this->message ?: null,
|
||||
attribution: [...$this->utm, 'referral_source' => $this->referralSource ?: null],
|
||||
);
|
||||
} catch (QuoteException|ReservationException $exception) {
|
||||
$this->addError('arrival', $exception->getMessage());
|
||||
@@ -262,6 +276,7 @@ protected function rules(): array
|
||||
'postalCode' => ['nullable', 'string', 'max:20'],
|
||||
'city' => ['nullable', 'string', 'max:255'],
|
||||
'message' => ['nullable', 'string', 'max:5000'],
|
||||
'referralSource' => ['nullable', Rule::enum(ReferralSource::class)],
|
||||
'privacyAccepted' => ['accepted'],
|
||||
];
|
||||
}
|
||||
@@ -300,6 +315,26 @@ private function stayRequest(): StayRequest
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dates and guests from the availability search of the hero section (?anreise=…&abreise=…&personen=…).
|
||||
*/
|
||||
private function prefillFromSearch(): void
|
||||
{
|
||||
$arrival = rescue(fn () => CarbonImmutable::createFromFormat('!Y-m-d', (string) request()->query('anreise')) ?: null, null, false);
|
||||
$departure = rescue(fn () => CarbonImmutable::createFromFormat('!Y-m-d', (string) request()->query('abreise')) ?: null, null, false);
|
||||
|
||||
if ($arrival && $departure && $departure->greaterThan($arrival) && $arrival->greaterThanOrEqualTo(CarbonImmutable::today())) {
|
||||
$this->arrival = $arrival->toDateString();
|
||||
$this->departure = $departure->toDateString();
|
||||
$this->month = $arrival->format('Y-m');
|
||||
}
|
||||
|
||||
$guests = (int) request()->query('personen');
|
||||
if ($guests >= 1 && $guests <= $this->property->max_guests) {
|
||||
$this->guests = $guests;
|
||||
}
|
||||
}
|
||||
|
||||
private function firstMonth(): CarbonImmutable
|
||||
{
|
||||
return CarbonImmutable::createFromFormat('!Y-m', $this->month);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Address;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Sent about a week before arrival: times, how to get in, house rules (texts from the admin).
|
||||
*/
|
||||
class ArrivalInformation extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public Booking $booking) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Bald geht es los: Ihre Anreise am '.$this->booking->arrival->format('d.m.Y'),
|
||||
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'mail.arrival-information',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Documents\RentalContract;
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Address;
|
||||
use Illuminate\Mail\Mailables\Attachment;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
@@ -33,4 +35,14 @@ public function content(): Content
|
||||
markdown: 'mail.booking-confirmed',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<Attachment>
|
||||
*/
|
||||
public function attachments(): array
|
||||
{
|
||||
$path = app(RentalContract::class)->absolutePath($this->booking);
|
||||
|
||||
return $path ? [Attachment::fromPath($path)->as("Mietvertrag-{$this->booking->reference}.pdf")->withMime('application/pdf')] : [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Reports overlaps between a newly imported portal occupation and occupations from elsewhere.
|
||||
*/
|
||||
class ChannelConflict extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
/** @param list<string> $conflicts */
|
||||
public function __construct(public Channel $channel, public array $conflicts) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Achtung: mögliche Doppelbuchung über '.$this->channel->name,
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'mail.channel-conflict',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Alerts the landlord that a portal import fails or is outdated.
|
||||
*/
|
||||
class ChannelSyncAlert extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public Channel $channel) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Kalender-Abgleich gestört: '.$this->channel->name,
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'mail.channel-sync-alert',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\ChannelTask;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Lists portal calendars that have to be blocked or released by hand.
|
||||
*/
|
||||
class ChannelTasksNotification extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
/** @param list<ChannelTask> $tasks */
|
||||
public function __construct(public array $tasks, public bool $reminder = false) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: ($this->reminder ? 'Erinnerung: ' : '').count($this->tasks).' Kalender-Aufgabe(n) auf Portalen',
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'mail.channel-tasks',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Alerts the landlord that portal notification e-mails cannot be read any more.
|
||||
*/
|
||||
class MailboxAlert extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public ?string $lastError) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Postfach-Abruf gestört: Portal-Buchungen werden nur noch über den Kalender erkannt',
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'mail.mailbox-alert',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Address;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Payment request or reminder to the guest. Overdue reminders are copied to the landlord.
|
||||
*/
|
||||
class PaymentReminder extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public const DEPOSIT_OVERDUE = 'deposit_overdue';
|
||||
|
||||
public const BALANCE_REQUEST = 'balance_request';
|
||||
|
||||
public const BALANCE_OVERDUE = 'balance_overdue';
|
||||
|
||||
public function __construct(public Booking $booking, public string $kind) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: match ($this->kind) {
|
||||
self::BALANCE_REQUEST => "Restzahlung für Ihre Buchung {$this->booking->reference}",
|
||||
default => "Zahlungserinnerung zu Ihrer Buchung {$this->booking->reference}",
|
||||
},
|
||||
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
|
||||
bcc: $this->kind === self::BALANCE_REQUEST ? [] : [new Address(config('fewo.notification_email'))],
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'mail.payment-reminder',
|
||||
with: [
|
||||
'amount' => $this->kind === self::DEPOSIT_OVERDUE && ! $this->booking->requiresFullPayment() ? $this->booking->openDeposit() : $this->booking->openAmount(),
|
||||
'dueOn' => $this->kind === self::DEPOSIT_OVERDUE ? $this->booking->deposit_due_on : $this->booking->balance_due_on,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Models\PortalEmail;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Tells the landlord what was done with a portal notification e-mail.
|
||||
*/
|
||||
class PortalMailNotification extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public PortalEmail $portalEmail) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
$channel = $this->portalEmail->channel->name;
|
||||
|
||||
return new Envelope(
|
||||
subject: match ($this->portalEmail->status) {
|
||||
PortalEmailStatus::Blocked => "{$channel}-Buchung erkannt und gesperrt: {$this->portalEmail->period()}",
|
||||
PortalEmailStatus::Released => "{$channel}-Stornierung: {$this->portalEmail->period()} wieder frei",
|
||||
default => "Bitte prüfen: E-Mail von {$channel}",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
markdown: 'mail.portal-mail',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\AppearanceFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* A seasonal look of a site (e.g. summer, winter, Christmas, New Year's Eve): colour tokens, hero photo,
|
||||
* photos per section, texts and banner change – the page structure does not (sections may be limited to
|
||||
* appearances, see SectionRegistry). Offers are advertised by their own rules (OfferShowcase). The period recurs every year ("MM-DD" to "MM-DD",
|
||||
* inclusive; a period may run over the turn of the year). The default appearance applies when none matches.
|
||||
*/
|
||||
#[Fillable(['site_id', 'name', 'starts_md', 'ends_md', 'priority', 'is_default', 'is_active', 'tokens', 'overrides', 'hero_photo_id', 'section_photos'])]
|
||||
class Appearance extends Model
|
||||
{
|
||||
/** @use HasFactory<AppearanceFactory> */
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* Texts an appearance can replace, with their admin labels. Sections read them through Theme::text().
|
||||
*/
|
||||
public const OVERRIDABLE = [
|
||||
'banner.text' => 'Banner: Text',
|
||||
'banner.link_label' => 'Banner: Link-Text',
|
||||
'banner.link_url' => 'Banner: Link-Ziel',
|
||||
'hero.eyebrow' => 'Titelbereich: kleine Überschrift',
|
||||
'hero.title' => 'Titelbereich: Überschrift',
|
||||
'hero.text' => 'Titelbereich: Text',
|
||||
'cta.title' => 'Abschluss: Überschrift',
|
||||
'cta.text' => 'Abschluss: Text',
|
||||
];
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_default' => 'boolean',
|
||||
'is_active' => 'boolean',
|
||||
'tokens' => 'array',
|
||||
'overrides' => 'array',
|
||||
'section_photos' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Site, $this>
|
||||
*/
|
||||
public function site(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Site::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Photo, $this>
|
||||
*/
|
||||
public function heroPhoto(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Photo::class, 'hero_photo_id');
|
||||
}
|
||||
|
||||
public function covers(CarbonInterface $date): bool
|
||||
{
|
||||
if ($this->starts_md === null || $this->ends_md === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$day = $date->format('m-d');
|
||||
|
||||
return $this->starts_md <= $this->ends_md
|
||||
? $day >= $this->starts_md && $day <= $this->ends_md
|
||||
: $day >= $this->starts_md || $day <= $this->ends_md;
|
||||
}
|
||||
|
||||
public function override(string $key): ?string
|
||||
{
|
||||
$value = data_get($this->overrides, $key);
|
||||
|
||||
return filled($value) ? (string) $value : null;
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Observers\BlockedPeriodObserver;
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\BlockedPeriodFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -15,7 +17,8 @@
|
||||
* Dates that are not bookable (own use, maintenance, bookings from portals).
|
||||
* Like bookings, ends_on is the first free day again.
|
||||
*/
|
||||
#[Fillable(['property_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid'])]
|
||||
#[ObservedBy(BlockedPeriodObserver::class)]
|
||||
#[Fillable(['property_id', 'channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid'])]
|
||||
class BlockedPeriod extends Model
|
||||
{
|
||||
/** @use HasFactory<BlockedPeriodFactory> */
|
||||
@@ -42,6 +45,14 @@ public function property(): BelongsTo
|
||||
return $this->belongsTo(Property::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Channel, $this>
|
||||
*/
|
||||
public function channel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<BlockedPeriod> $query
|
||||
* @return Builder<BlockedPeriod>
|
||||
|
||||
Loaded 100 of 260 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user