Compare commits
111
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d42c42059c | ||
|
|
f5f18cd984 | ||
|
|
1c757f7429 | ||
|
|
70a39315e2 | ||
|
|
b9225f5fb8 | ||
|
|
876a0a20f3 | ||
|
|
4e6ad792eb | ||
|
|
d2b1a853dc | ||
|
|
791786ed3e | ||
|
|
d02f3e05c7 | ||
|
|
8bcda9a4bc | ||
|
|
e74033a958 | ||
|
|
add2367869 | ||
|
|
8b36e07dc4 | ||
|
|
a0497fcccd | ||
|
|
678e15256d | ||
|
|
2ae48e77fa | ||
|
|
386e2cf0a9 | ||
|
|
54efd3b858 | ||
|
|
7d998e2b81 | ||
|
|
e7efb06277 | ||
|
|
94df35e702 | ||
|
|
bc3872c01f | ||
|
|
0bba50bd7b | ||
|
|
5bffe44435 | ||
|
|
4389894959 | ||
|
|
2b2e732612 | ||
|
|
78aafd7c28 | ||
|
|
13f1b5856c | ||
|
|
f19d698203 | ||
|
|
f369018a68 | ||
|
|
c74199e978 | ||
|
|
4186872b3f | ||
|
|
f80c0f9f3b | ||
|
|
1fb839b24e | ||
|
|
2dca2bccfa | ||
|
|
952f8574c8 | ||
|
|
089d7f894b | ||
|
|
606ef8850f | ||
|
|
7c7955b982 | ||
|
|
e9db98701b | ||
|
|
c4ebccbbea | ||
|
|
8927f2eeb1 | ||
|
|
25b5a61461 | ||
|
|
e5a083ce71 | ||
|
|
0be1cfcdb8 | ||
|
|
2893192344 | ||
|
|
511faa64d2 | ||
|
|
98eabaeb0c | ||
|
|
1f59cbb9a5 | ||
|
|
783068501c | ||
|
|
6fe5bbc6e3 | ||
|
|
06df80e4db | ||
|
|
86374b1659 | ||
|
|
1b03689c46 | ||
|
|
e7f79e4075 | ||
|
|
f5d8be5eaf | ||
|
|
92fb01da9d | ||
|
|
01900d6550 | ||
|
|
8eae37e11d | ||
|
|
92ccf40312 | ||
|
|
6d8f1d6692 | ||
|
|
abf0e9004b | ||
|
|
3a0bb6e40f | ||
|
|
361acfa12a | ||
|
|
c459f7f83c | ||
|
|
4e66add1f0 | ||
|
|
f686996122 | ||
|
|
2c5b5fc2d7 | ||
|
|
9cd39f791f | ||
|
|
c55937d20e | ||
|
|
c2cf632ad5 | ||
|
|
f2e78446a8 | ||
|
|
03ad4667ac | ||
|
|
d9383cf3e5 | ||
|
|
e0e8c1d856 | ||
|
|
2f2aceb3bd | ||
|
|
2e3f2ca938 | ||
|
|
fd2a7f7ded | ||
|
|
220ec6bfdb | ||
|
|
afffa79289 | ||
|
|
f143a4f5f4 | ||
|
|
e6d4d89141 | ||
|
|
12e4079126 | ||
|
|
1871c04507 | ||
|
|
dfd3f77a5d | ||
|
|
f7cbc66451 | ||
|
|
04b5189bd8 | ||
|
|
9b8a851ce9 | ||
|
|
b3114cdfe3 | ||
|
|
faf2133232 | ||
|
|
d2f53ceb84 | ||
|
|
ab1dffc72f | ||
|
|
fc61369c4a | ||
|
|
cec49da1be | ||
|
|
8ebc1a3878 | ||
|
|
d9e52c4789 | ||
|
|
3621f7e924 | ||
|
|
6930d3ab0f | ||
|
|
c215da0590 | ||
|
|
e49f160496 | ||
|
|
bc2b175556 | ||
|
|
5416b37dfc | ||
|
|
30e9aa7b26 | ||
|
|
4951f227f1 | ||
|
|
a9ad4dbf0b | ||
|
|
e276cd0548 | ||
|
|
0c98d82cf2 | ||
|
|
749537342e | ||
|
|
b681327d3a | ||
|
|
bde99657cf |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git merge *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -35,9 +35,9 @@ MAIL_MAILER=smtp
|
||||
MAIL_HOST=smtp.strato.de
|
||||
MAIL_PORT=465
|
||||
MAIL_SCHEME=smtps
|
||||
MAIL_USERNAME=fewo@stommer.de
|
||||
MAIL_USERNAME=info@fewo-stommer.de
|
||||
MAIL_PASSWORD=
|
||||
MAIL_FROM_ADDRESS="fewo@stommer.de"
|
||||
MAIL_FROM_ADDRESS="info@fewo-stommer.de"
|
||||
MAIL_FROM_NAME="${APP_NAME}"
|
||||
|
||||
FEWO_OWNER_NAME="Brigitte Stommer"
|
||||
|
||||
+46
-88
@@ -1,105 +1,63 @@
|
||||
# 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
|
||||
|
||||
name: Deploy FeWo mit PipelineManager
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
branches: [develop, main]
|
||||
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'
|
||||
# Raspi5-Paperless: existing host runner; all PHP/Node work happens inside the image.
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PIPELINE_IMAGE: pipeline-manager:0.1.1
|
||||
PIPELINE_HOME: /home/lars/docker/pipeline-manager
|
||||
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
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
|
||||
- name: SSH key
|
||||
- name: Anwendung im Manager-Container vorbereiten und testen
|
||||
id: build
|
||||
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
|
||||
set -eu
|
||||
case "$GITHUB_REF" in
|
||||
refs/heads/develop) TARGET=staging ;;
|
||||
refs/heads/main) TARGET=production ;;
|
||||
*) echo 'Unzulässiger Branch'; exit 1 ;;
|
||||
esac
|
||||
docker image inspect "$PIPELINE_IMAGE" >/dev/null
|
||||
STATUS=0
|
||||
docker run --rm --user "$(id -u):$(id -g)" \
|
||||
-v "$(pwd -P):/workspace:ro" "$PIPELINE_IMAGE" \
|
||||
pipeline-manager check --environment "$TARGET" || STATUS=$?
|
||||
if [ "$STATUS" = 3 ]; then
|
||||
echo 'enabled=false' >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
test "$STATUS" = 0
|
||||
umask 077
|
||||
mkdir -p "$PIPELINE_HOME/cache/composer" "$PIPELINE_HOME/cache/npm" "$PIPELINE_HOME/backups" .pipeline
|
||||
docker run --rm --user "$(id -u):$(id -g)" --cpus=2 --memory=2g --pids-limit=512 \
|
||||
-e HOME=/tmp \
|
||||
-v "$(pwd -P):/workspace" \
|
||||
-v "$PIPELINE_HOME/cache:/cache" "$PIPELINE_IMAGE" \
|
||||
pipeline-manager prepare
|
||||
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
|
||||
echo 'enabled=true' >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Deploy
|
||||
- name: Sichern und nach Strato übertragen
|
||||
if: steps.build.outputs.enabled == 'true'
|
||||
env:
|
||||
TARGET: ${{ steps.build.outputs.target }}
|
||||
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 }}
|
||||
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
export DEPLOY_SSH_KEY="$HOME/.ssh/deploy_key"
|
||||
bash scripts/deploy.sh "${{ inputs.environment || 'production' }}" deploy
|
||||
set -eu
|
||||
docker run --rm --user "$(id -u):$(id -g)" --cpus=1 --memory=512m --pids-limit=128 \
|
||||
-e GITHUB_REF -e GITHUB_SHA -e DEPLOY_HOST -e DEPLOY_USER -e DEPLOY_SSH_KEY -e DEPLOY_KNOWN_HOSTS \
|
||||
-v /etc/passwd:/etc/passwd:ro \
|
||||
-v "$(pwd -P):/workspace:ro" \
|
||||
-v "$PIPELINE_HOME/backups:/backups" "$PIPELINE_IMAGE" \
|
||||
pipeline-manager deploy --environment "$TARGET" --backup-root /backups
|
||||
@@ -24,6 +24,7 @@
|
||||
/storage/*.key
|
||||
/storage/pail
|
||||
/vendor
|
||||
/.pipeline/
|
||||
_ide_helper.php
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
@@ -32,3 +33,4 @@ Thumbs.db
|
||||
# Deployment settings with access data
|
||||
/scripts/deploy.*.env
|
||||
!/scripts/deploy.example.env
|
||||
storage/app/private/exports/
|
||||
@@ -1,8 +1,8 @@
|
||||
# Ferienwohnung Stommer
|
||||
|
||||
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`. **Current state and next steps: `docs/STATUS.md` – start there and update it after larger changes.** Parallel sessions (e.g. theme design on another machine): follow `docs/ZUSAMMENARBEIT.md` (branches, file ownership, deploy only from an up-to-date `main`).
|
||||
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`. **Current state and next steps: `docs/STATUS.md` – start there and update it after larger changes.** Parallel sessions (e.g. theme design on another machine): follow `docs/ZUSAMMENARBEIT.md` (branches and file ownership; `develop` deploys staging, a merge from `develop` to `main` deploys production once enabled).
|
||||
|
||||
- Hosting target: Strato shared webhosting (PHP + MySQL, no Node at runtime) – build assets locally.
|
||||
- Hosting target: Strato shared webhosting (PHP + MySQL, no Node at runtime) – CI builds assets in the versioned PipelineManager image on the Pi, independently of the development machine.
|
||||
- UI and all user-facing texts are German; code, identifiers and PHPDoc are English.
|
||||
- Money is stored as integer euro cents; edit via `App\Filament\Forms\Components\EuroInput`, display via `->money('EUR', divideBy: 100, locale: 'de')`.
|
||||
- Season periods are half-open: a night belongs to a season when `starts_on <= night < ends_on`.
|
||||
@@ -16,11 +16,11 @@ # Ferienwohnung Stommer
|
||||
- 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 every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
|
||||
- Deployment: `.gitea/workflows/deploy.yml` runs the separate PipelineManager image using this project's `pipeline.toml`: push `develop` -> staging; merge commit `develop` -> `main` -> production, currently disabled. Manager source and agent instructions: `C:\dev\pipelinemanager`, https://gitea.stommer.de/Lars/PipelineManager. No permanent API service or new container image per application deployment; the runner starts containers from an existing released image. Secrets stay in Gitea Secrets. Strato retains only the active release; the workflow commit and server `REVISION` identify deployments. Legacy maintenance fallback: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (its manual deploy creates Git tags). Read docs/DEPLOYMENT.md before use. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Internal addresses are admin settings too: send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly); contact/reply-to (`fewo.owner.email`) and sender (`mail.from`) are overridden at boot by `Settings::applyAddressOverrides()`. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
|
||||
- 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`.
|
||||
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`; development/integration branch `develop`, production branch `main`.
|
||||
|
||||
<laravel-boost-guidelines>
|
||||
=== foundation rules ===
|
||||
|
||||
@@ -17,7 +17,7 @@ # Ferienwohnung Stommer
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
|
||||
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Findings detected repeatedly (e.g. by the 5-minute sync) go through `AppSupportInbox` (admin Postfach, fingerprint per tenant, repeated only per the tenant's `reminder_interval_days`), never straight to mail; daily/weekly summaries: `SendDigests` + `DigestReport` (sections `DigestSection`). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
|
||||
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
|
||||
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
|
||||
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Content;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
@@ -41,7 +42,7 @@ public function handle(Booking $booking, int $offerVersion): void
|
||||
$this->confirm->handle($booking);
|
||||
|
||||
try {
|
||||
Mail::to(config('fewo.notification_email'))->send(new OfferAnswered($booking, accepted: true));
|
||||
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: true));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ICal\ICalAnalysis;
|
||||
use App\Channels\ICal\ICalConnector;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class AnalyzeChannelCalendar
|
||||
{
|
||||
public function handle(Channel $channel): Channel
|
||||
{
|
||||
if ($channel->connector !== 'ical' || blank($channel->setting('import_url')) || ! $channel->servesItsLandlord()) {
|
||||
throw new ChannelSyncException('Für die Analyse eine iCal-Importadresse hinterlegen und den Kalenderdienst freischalten.');
|
||||
}
|
||||
$url = $channel->setting('import_url');
|
||||
$analysis = app(ICalAnalysis::class)->summarize(app(ICalConnector::class)->fetchDocument($channel));
|
||||
|
||||
return DB::transaction(function () use ($channel, $url, $analysis): Channel {
|
||||
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
if ($locked->setting('import_url') !== $url) {
|
||||
throw new ChannelSyncException('Die Importadresse wurde während der Analyse geändert. Bitte erneut analysieren.');
|
||||
}
|
||||
$locked->forceFill(['ical_analysis' => $analysis, 'ical_analyzed_at' => now()])->save();
|
||||
|
||||
return $locked;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,14 @@ public function handle(): int
|
||||
->whereNull('anonymized_at')
|
||||
->whereDate('created_at', '<', $cutoff)
|
||||
->whereDoesntHave('bookings', fn ($query) => $query->whereDate('departure', '>=', $cutoff))
|
||||
->whereDoesntHave('portalStays', fn ($query) => $query->withTrashed()->whereDate('ends_on', '>=', $cutoff))
|
||||
->get();
|
||||
|
||||
$inquiryCutoff = now()->subMonths(config('fewo.retention.inquiry_months'));
|
||||
$inquiriesOnly = Guest::query()
|
||||
->whereNull('anonymized_at')
|
||||
->whereDoesntHave('bookings', fn ($query) => $query->whereNotNull('confirmed_at'))
|
||||
->whereDoesntHave('portalStays', fn ($query) => $query->withTrashed())
|
||||
->whereDoesntHave('bookings', fn ($query) => $query->where('updated_at', '>=', $inquiryCutoff))
|
||||
->where('updated_at', '<', $inquiryCutoff)
|
||||
->get();
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ICal\ICalRuleEngine;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ApplyChannelRules
|
||||
{
|
||||
public function attributes(Channel $channel, ?BlockedPeriod $block, array $properties): array
|
||||
{
|
||||
$result = app(ICalRuleEngine::class)->evaluate($channel, $properties);
|
||||
$attributes = ['ical_interpretation' => $result, 'ical_event_type' => $result['event_type'],
|
||||
'leading_priority' => $result['representation'] === 'leading_candidate' ? max(1, 10001 - $result['priority']) : 0];
|
||||
$previousOrigin = $block?->ical_interpretation['origin_channel_id'] ?? null;
|
||||
if ($block === null || ($block->occupation_kind === null && $block->reviewed_at === null && ($block->origin_channel_id === null || $block->origin_channel_id === $previousOrigin))) {
|
||||
$attributes['origin_channel_id'] = $result['origin_channel_id'];
|
||||
}
|
||||
|
||||
return $attributes;
|
||||
}
|
||||
|
||||
public function store(BlockedPeriod $block, array $attributes): void
|
||||
{
|
||||
foreach ($attributes as $field => $value) {
|
||||
if ($block->getAttribute($field) !== $value) {
|
||||
$block->forceFill([$field => $value]);
|
||||
}
|
||||
}
|
||||
if ($block->isDirty()) {
|
||||
$block->saveQuietly();
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array{classified: int, missing_raw: int} */
|
||||
public function handle(Channel $channel): array
|
||||
{
|
||||
return DB::transaction(function () use ($channel): array {
|
||||
$channel = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
app(ICalRuleEngine::class)->validate($channel, $channel->ical_rules ?? []);
|
||||
$channel->forceFill(['ical_active_rules' => $channel->ical_rules ?? []])->save();
|
||||
Property::query()->whereKey($channel->property_id)->lockForUpdate()->firstOrFail();
|
||||
$events = collect($channel->ical_analysis['events'] ?? [])->keyBy('uid');
|
||||
$counts = ['classified' => 0, 'missing_raw' => 0];
|
||||
foreach ($channel->blockedPeriods()->where('source', 'channel')->lockForUpdate()->get() as $block) {
|
||||
$event = $events->get($block->external_uid);
|
||||
if ($event && $block->ical_raw !== null && $channel->ical_analyzed_at !== null
|
||||
&& $block->updated_at->greaterThan($channel->ical_analyzed_at) && $block->ical_raw !== $event['raw']) {
|
||||
if (! $this->hasEquivalentTimestampUpdate($channel, $block, $event)) {
|
||||
throw ValidationException::withMessages(['rules' => 'Der Importbestand hat sich seit der Vorschau geändert. Den Kalender erneut analysieren und die Vorschau prüfen.']);
|
||||
}
|
||||
$event = [...$event, 'properties' => $block->ical_properties, 'raw' => $block->ical_raw];
|
||||
}
|
||||
$properties = $event['properties'] ?? $block->ical_properties;
|
||||
if ($properties === null) {
|
||||
$counts['missing_raw']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$attributes = $this->attributes($channel, $block, $properties);
|
||||
if ($event && $event['starts_on'] !== null && ($block->starts_on->toDateString() !== $event['starts_on'] || $block->ends_on->toDateString() !== $event['ends_on'])) {
|
||||
$attributes = [...$attributes, 'needs_review' => true, 'review_note' => 'Die Analyse meldet einen anderen Zeitraum. Die Klassifikation ändert keine Termine; Kalenderabgleich und Zuordnung prüfen.'];
|
||||
}
|
||||
$this->store($block, [...$attributes, 'ical_properties' => $properties, 'ical_raw' => $event['raw'] ?? $block->ical_raw]);
|
||||
$counts['classified']++;
|
||||
}
|
||||
app(ReconcileChannelRepresentations::class)->handle($channel->property);
|
||||
|
||||
return $counts;
|
||||
});
|
||||
}
|
||||
|
||||
private function hasEquivalentTimestampUpdate(Channel $channel, BlockedPeriod $block, array $event): bool
|
||||
{
|
||||
if ($block->ical_properties === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$withoutTimestamps = fn (string $raw): string => preg_replace('/^(?:DTSTAMP|LAST-MODIFIED)(?:;[^:\r\n]*)?:[^\r\n]*(?:\r\n|\n|$)/mi', '', $raw);
|
||||
if ($withoutTimestamps($block->ical_raw) !== $withoutTimestamps($event['raw'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$engine = app(ICalRuleEngine::class);
|
||||
|
||||
return $engine->evaluate($channel, $block->ical_properties) === $engine->evaluate($channel, $event['properties']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\OccupationKind;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Guest;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class AssignOccupationGuest
|
||||
{
|
||||
/** @param array{first_name?: string, last_name?: ?string, email?: ?string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string, notes?: ?string, tags?: ?array} $details */
|
||||
public function handle(Booking|BlockedPeriod $occupation, ?int $guestId, array $details = []): Guest
|
||||
{
|
||||
Gate::authorize('update', $occupation);
|
||||
|
||||
return DB::transaction(function () use ($occupation, $guestId, $details): Guest {
|
||||
$record = $occupation->newQuery()->whereKey($occupation->id)->lockForUpdate()->firstOrFail();
|
||||
if ($record instanceof BlockedPeriod && ($record->occupationKind() !== OccupationKind::Reservation || $record->is_representation)) {
|
||||
throw ValidationException::withMessages(['guest_id' => 'Zuerst als eigenständige Portalreservierung einordnen. Darstellungen werden an der führenden Buchung gepflegt.']);
|
||||
}
|
||||
if ($guestId !== null) {
|
||||
$guest = Guest::query()->where('tenant_id', $record->tenant_id)->whereNull('anonymized_at')->findOrFail($guestId);
|
||||
Gate::authorize('view', $guest);
|
||||
} else {
|
||||
Gate::authorize('create', Guest::class);
|
||||
$data = Validator::make($details, [
|
||||
'first_name' => ['required', 'string', 'max:255'],
|
||||
'last_name' => ['nullable', 'string', 'max:255'],
|
||||
'email' => ['nullable', 'email', 'max:255'],
|
||||
'phone' => ['nullable', 'string', 'max:50'],
|
||||
'street' => ['nullable', 'string', 'max:255'],
|
||||
'postal_code' => ['nullable', 'string', 'max:20'],
|
||||
'city' => ['nullable', 'string', 'max:255'],
|
||||
'country' => ['nullable', 'string', 'size:2', 'regex:/^[A-Z]{2}$/'],
|
||||
'notes' => ['nullable', 'string'],
|
||||
'tags' => ['nullable', 'array'],
|
||||
'tags.*' => ['string', 'max:255'],
|
||||
])->validate();
|
||||
$guest = new Guest([...$data, 'last_name' => $data['last_name'] ?? '', 'email' => filled($data['email'] ?? null) ? mb_strtolower(trim($data['email'])) : null, 'country' => $data['country'] ?? 'DE']);
|
||||
$guest->forceFill(['tenant_id' => $record->tenant_id])->save();
|
||||
}
|
||||
$record->forceFill(['guest_id' => $guest->id])->save();
|
||||
|
||||
return $guest;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BlockedPeriodPurpose;
|
||||
use App\Enums\OccupationKind;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ClassifyPortalOccupation
|
||||
{
|
||||
/** @param array{block_purpose?: BlockedPeriodPurpose|string|null, block_note?: string|null, is_private?: bool} $details */
|
||||
public function handle(BlockedPeriod $occupation, OccupationKind $kind, ?int $originId = null, array $details = []): void
|
||||
{
|
||||
Gate::authorize('update', $occupation);
|
||||
if (($details['block_purpose'] ?? null) instanceof BlockedPeriodPurpose) {
|
||||
$details['block_purpose'] = $details['block_purpose']->value;
|
||||
}
|
||||
$details = Validator::make($details, [
|
||||
'block_purpose' => ['nullable', Rule::enum(BlockedPeriodPurpose::class)],
|
||||
'block_note' => ['nullable', 'string', 'max:255'],
|
||||
'is_private' => ['sometimes', 'boolean'],
|
||||
])->validate();
|
||||
if (($details['is_private'] ?? false) && $originId !== null) {
|
||||
throw ValidationException::withMessages(['origin_channel_id' => 'Privat und ein externer Buchungskanal können nicht gleichzeitig gewählt werden.']);
|
||||
}
|
||||
DB::transaction(function () use ($occupation, $kind, $originId, $details): void {
|
||||
Property::query()->whereKey($occupation->property_id)->lockForUpdate()->firstOrFail();
|
||||
$record = BlockedPeriod::query()->whereKey($occupation->id)->lockForUpdate()->firstOrFail();
|
||||
if (! in_array($record->source, ['channel', 'email'], true) || $record->is_representation) {
|
||||
throw ValidationException::withMessages(['occupation_kind' => 'Nur eigenständige Portalereignisse können hier eingeordnet werden.']);
|
||||
}
|
||||
if ($originId !== null && ! Channel::query()->where('property_id', $record->property_id)->whereKey($originId)->exists()) {
|
||||
throw ValidationException::withMessages(['origin_channel_id' => 'Der Ursprungskanal muss zur selben Wohnung gehören.']);
|
||||
}
|
||||
$record->forceFill([
|
||||
'occupation_kind' => $kind,
|
||||
'origin_channel_id' => $originId,
|
||||
'is_private' => $details['is_private'] ?? false,
|
||||
'block_purpose' => $kind === OccupationKind::Block ? (array_key_exists('block_purpose', $details) ? $details['block_purpose'] : $record->block_purpose) : null,
|
||||
'block_note' => $kind === OccupationKind::Block ? (array_key_exists('block_note', $details) ? $details['block_note'] : $record->block_note) : null,
|
||||
])->save();
|
||||
app(ReconcileChannelRepresentations::class)->handle($record->property);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ICal\ICalFeed;
|
||||
use App\Channels\ICal\ICalParser;
|
||||
use App\Enums\ChannelStatus;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ConfigureChannel
|
||||
{
|
||||
/** @param array<string, mixed> $data */
|
||||
public function handle(Property $property, array $data, ?Channel $channel = null): Channel
|
||||
{
|
||||
return DB::transaction(function () use ($property, $data, $channel): Channel {
|
||||
$stored = $channel ? $property->channels()->whereKey($channel->id)->lockForUpdate()->firstOrFail() : null;
|
||||
$candidate = $stored ? clone $stored : new Channel;
|
||||
$candidate->fill($data);
|
||||
$candidate->property_id = $property->id;
|
||||
$candidate->tenant_id = $property->tenant_id;
|
||||
if ($stored && $stored->setting('import_url') !== $candidate->setting('import_url')) {
|
||||
$candidate->forceFill(['ical_analysis' => null, 'ical_analyzed_at' => null]);
|
||||
}
|
||||
if ($stored) {
|
||||
$candidate->is_active = $candidate->status === ChannelStatus::Active;
|
||||
}
|
||||
if ($candidate->import_enabled && blank($candidate->setting('import_url'))) {
|
||||
throw ValidationException::withMessages(['settings.import_url' => 'Für einen aktivierten Import ist eine Kalenderadresse erforderlich.']);
|
||||
}
|
||||
if ($stored && $stored->setting('import_url') !== $candidate->setting('import_url') && $stored->blockedPeriods()->withTrashed()->exists()) {
|
||||
throw ValidationException::withMessages(['settings.import_url' => 'Bei bestehendem Importbestand die Quelladresse nicht ungeprüft ersetzen. Einen neuen Kanal anlegen oder die Bestandsumstellung gesondert freigeben.']);
|
||||
}
|
||||
if ($stored && $stored->exportsOccupations() && ! $candidate->exportsOccupations() && $stored->export_snapshot === null) {
|
||||
$body = app(ICalFeed::class)->build($stored);
|
||||
app(ICalParser::class)->parse($body);
|
||||
$candidate->forceFill(['export_snapshot' => $body, 'export_snapshot_at' => now()]);
|
||||
}
|
||||
if ($stored && $stored->importsOccupations() !== $candidate->importsOccupations()) {
|
||||
$stored->blockedPeriods()->where('source', 'channel')->update(['missing_imports' => 0]);
|
||||
}
|
||||
$candidate->save();
|
||||
|
||||
return $candidate->refresh();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ICal\ICalExportFields;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ConfigureChannelExport
|
||||
{
|
||||
public function handle(Channel $channel, array $mapping, bool $allowNames): Channel
|
||||
{
|
||||
Validator::make(['export_mapping' => $mapping], [
|
||||
'export_mapping' => ['array', 'max:3'],
|
||||
'export_mapping.*.field' => ['required', 'distinct', Rule::in(array_keys(ICalExportFields::ICAL_FIELDS))],
|
||||
'export_mapping.*.items' => ['required', 'array', 'min:1'],
|
||||
'export_mapping.*.items.*' => ['required', Rule::in(array_keys(ICalExportFields::FIELDS))],
|
||||
'export_mapping.*.separator' => ['nullable', 'string', 'max:30'],
|
||||
])->validate();
|
||||
|
||||
return DB::transaction(function () use ($channel, $mapping, $allowNames): Channel {
|
||||
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
$locked->forceFill(['ical_export_mapping' => array_values($mapping), 'ical_export_names' => $allowNames])->save();
|
||||
|
||||
return $locked;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,10 @@ public function __construct(
|
||||
*/
|
||||
public function handle(Booking $booking, bool $notifyGuest = true): void
|
||||
{
|
||||
if ($notifyGuest && blank($booking->guest?->email)) {
|
||||
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
|
||||
}
|
||||
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'bestätigt');
|
||||
}
|
||||
|
||||
@@ -2,11 +2,16 @@
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\ChannelExportMode;
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\Property;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
@@ -23,7 +28,7 @@ class CreateChannelTasks
|
||||
/**
|
||||
* @return list<ChannelTask>
|
||||
*/
|
||||
public function handle(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn, ChannelTaskAction $action, string $reason, ?int $exceptChannelId = null): array
|
||||
public function handle(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn, ChannelTaskAction $action, string $reason, ?int $exceptChannelId = null, ?int $originChannelId = null, bool $external = false): array
|
||||
{
|
||||
if ($endsOn->lessThanOrEqualTo(today())) {
|
||||
return [];
|
||||
@@ -32,20 +37,31 @@ public function handle(Property $property, CarbonInterface $startsOn, CarbonInte
|
||||
$channels = $property->channels()->active()
|
||||
->where('requires_manual_blocking', true)
|
||||
->when($exceptChannelId, fn ($query) => $query->whereKeyNot($exceptChannelId))
|
||||
->get();
|
||||
->when($originChannelId, fn ($query) => $query->whereKeyNot($originChannelId))
|
||||
->get()->filter(fn (Channel $channel): bool => $channel->exportsOccupations()
|
||||
&& (! ($external || $exceptChannelId !== null || $originChannelId !== null) || $channel->export_mode === ChannelExportMode::Regular));
|
||||
|
||||
$tasks = $channels->map(fn (Channel $channel): ChannelTask => $channel->tasks()->create([
|
||||
'action' => $action,
|
||||
'starts_on' => $startsOn->toDateString(),
|
||||
'ends_on' => $endsOn->toDateString(),
|
||||
'reason' => $reason,
|
||||
]))->all();
|
||||
$tasks = [];
|
||||
foreach ($channels as $channel) {
|
||||
$segments = $action === ChannelTaskAction::Unblock ? $this->freeSegments($property, $startsOn, $endsOn) : [[$startsOn, $endsOn]];
|
||||
foreach ($segments as [$start, $end]) {
|
||||
$task = $channel->tasks()->where('action', $action)->where('status', ChannelTaskStatus::Open)
|
||||
->whereDate('starts_on', $start)->whereDate('ends_on', $end)->first()
|
||||
?? $channel->tasks()->create([
|
||||
'action' => $action, 'starts_on' => $start->toDateString(), 'ends_on' => $end->toDateString(),
|
||||
'status' => ChannelTaskStatus::Open, 'reason' => $reason,
|
||||
]);
|
||||
if ($task->wasRecentlyCreated) {
|
||||
$tasks[] = $task;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($tasks === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelTasksNotification($tasks)));
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelTasksNotification($tasks)));
|
||||
|
||||
foreach ($tasks as $task) {
|
||||
$this->sendToAutomation($task);
|
||||
@@ -60,6 +76,30 @@ public function handle(Property $property, CarbonInterface $startsOn, CarbonInte
|
||||
*/
|
||||
public function sendToAutomation(ChannelTask $task): void
|
||||
{
|
||||
$task->refresh();
|
||||
if ($task->status !== ChannelTaskStatus::Open) {
|
||||
return;
|
||||
}
|
||||
if (! $task->channel->exportsOccupations()) {
|
||||
$task->update(['automation_error' => 'Kanalexport ist pausiert; keine automatische Portaländerung.']);
|
||||
|
||||
return;
|
||||
}
|
||||
if ($task->action === ChannelTaskAction::Unblock && ! app(AvailabilityChecker::class)->isAvailable($task->channel->property, $task->starts_on, $task->ends_on)) {
|
||||
$task->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Zeitraum ist inzwischen wieder belegt; nicht entsperren.']);
|
||||
|
||||
return;
|
||||
}
|
||||
if ($task->action === ChannelTaskAction::Block) {
|
||||
$occupied = app(AvailabilityChecker::class)->occupiedNights($task->channel->property, $task->starts_on, $task->ends_on);
|
||||
for ($night = $task->starts_on; $night->lessThan($task->ends_on); $night = $night->addDay()) {
|
||||
if (! isset($occupied[$night->toDateString()])) {
|
||||
$task->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Sperraufgabe ist durch eine Belegungsänderung überholt; aktuellen Zeitraum prüfen.']);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
$url = config('fewo.automation.webhook_url');
|
||||
$secret = config('fewo.automation.secret');
|
||||
if (blank($url) || blank($secret)) {
|
||||
@@ -89,4 +129,27 @@ public function sendToAutomation(ChannelTask $task): void
|
||||
$task->update(['automation_error' => $exception->getMessage()]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return list<array{CarbonImmutable, CarbonImmutable}> */
|
||||
private function freeSegments(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn): array
|
||||
{
|
||||
$start = CarbonImmutable::instance($startsOn);
|
||||
$end = CarbonImmutable::instance($endsOn);
|
||||
$occupied = app(AvailabilityChecker::class)->occupiedNights($property, $start, $end);
|
||||
$segments = [];
|
||||
$segmentStart = null;
|
||||
for ($night = $start; $night->lessThan($end); $night = $night->addDay()) {
|
||||
if (! isset($occupied[$night->toDateString()])) {
|
||||
$segmentStart ??= $night;
|
||||
} elseif ($segmentStart !== null) {
|
||||
$segments[] = [$segmentStart, $night];
|
||||
$segmentStart = null;
|
||||
}
|
||||
}
|
||||
if ($segmentStart !== null) {
|
||||
$segments[] = [$segmentStart, $end];
|
||||
}
|
||||
|
||||
return $segments;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,9 @@
|
||||
use App\Pricing\PriceCalculator;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Settings;
|
||||
use App\Tenancy\TenantContext;
|
||||
use App\Tenancy\TenantContextMissing;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
@@ -37,6 +40,24 @@ public function __construct(
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
|
||||
{
|
||||
$tenant = $property->tenant;
|
||||
|
||||
if ($tenant === null) {
|
||||
throw new TenantContextMissing(Property::class);
|
||||
}
|
||||
|
||||
return app(TenantContext::class)->run(
|
||||
$tenant,
|
||||
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
|
||||
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
|
||||
*/
|
||||
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution): Booking
|
||||
{
|
||||
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
|
||||
Property::whereKey($property->getKey())->lockForUpdate()->first();
|
||||
@@ -90,7 +111,11 @@ private function guestFor(array $guestData): array
|
||||
$guest = Guest::query()->where('email', $email)->first();
|
||||
|
||||
if ($guest === null) {
|
||||
return [Guest::create([...$guestData, 'email' => $email]), []];
|
||||
return [Guest::create([
|
||||
...$guestData,
|
||||
'email' => $email,
|
||||
'tenant_id' => app(TenantContext::class)->id(),
|
||||
]), []];
|
||||
}
|
||||
|
||||
$labels = ['first_name' => 'Vorname', 'last_name' => 'Nachname', 'phone' => 'Telefon', 'street' => 'Straße', 'postal_code' => 'PLZ', 'city' => 'Ort', 'country' => 'Land'];
|
||||
@@ -119,7 +144,7 @@ private function sendMails(Booking $booking): void
|
||||
{
|
||||
try {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
|
||||
Mail::to(config('fewo.notification_email'))->send(new NewReservation($booking));
|
||||
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@ class DeclineBooking
|
||||
*/
|
||||
public function handle(Booking $booking, bool $notifyGuest = true): void
|
||||
{
|
||||
if ($notifyGuest && blank($booking->guest?->email)) {
|
||||
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
|
||||
}
|
||||
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt');
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Mail\ReservationExpired;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
@@ -24,7 +25,7 @@ public function handle(): int
|
||||
foreach ($expired as $booking) {
|
||||
$booking->update(['status' => BookingStatus::Expired]);
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new ReservationExpired($booking));
|
||||
Mail::to(Settings::notificationRecipients())->send(new ReservationExpired($booking));
|
||||
}
|
||||
|
||||
return $expired->count();
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
use App\Mail\ChannelSyncAlert;
|
||||
use App\Mail\MailboxAlert;
|
||||
use App\Models\Channel;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
@@ -24,7 +25,7 @@ public function handle(): int
|
||||
->filter(fn (Channel $channel): bool => $channel->isStale());
|
||||
|
||||
foreach ($channels as $channel) {
|
||||
Mail::to(config('fewo.notification_email'))->send(new ChannelSyncAlert($channel));
|
||||
Mail::to(Settings::notificationRecipients())->send(new ChannelSyncAlert($channel));
|
||||
$channel->forceFill(['alerted_at' => now()])->save();
|
||||
}
|
||||
|
||||
@@ -37,7 +38,7 @@ public static function mailboxIsStale(): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
$lastSuccess = Cache::get(MailboxReader::LAST_SUCCESS_KEY);
|
||||
$lastSuccess = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY));
|
||||
|
||||
return $lastSuccess === null
|
||||
|| CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes')));
|
||||
@@ -55,7 +56,7 @@ private function monitorMailbox(): int
|
||||
return 0;
|
||||
}
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new MailboxAlert(Cache::get(MailboxReader::LAST_ERROR_KEY)));
|
||||
Mail::to(Settings::notificationRecipients())->send(new MailboxAlert(Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY))));
|
||||
Cache::forever(self::MAILBOX_ALERTED_KEY, true);
|
||||
|
||||
return 1;
|
||||
|
||||
@@ -8,11 +8,14 @@
|
||||
use App\Channels\Mail\PortalMailParser;
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\PortalEmailType;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Mail\PortalMailNotification;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Support\Settings;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
@@ -39,6 +42,11 @@ public function handle(PortalMail $mail): ?PortalEmail
|
||||
return null;
|
||||
}
|
||||
|
||||
// The fast path is a service of its own: a landlord without it keeps the mail unprocessed.
|
||||
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parsed = $this->parser->parse($mail->subject, $mail->text);
|
||||
$conflicts = [];
|
||||
|
||||
@@ -68,11 +76,11 @@ public function handle(PortalMail $mail): ?PortalEmail
|
||||
});
|
||||
|
||||
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new PortalMailNotification($record)));
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
|
||||
}
|
||||
|
||||
if ($conflicts !== []) {
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelConflict($channel, $conflicts)));
|
||||
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
|
||||
}
|
||||
|
||||
return $record;
|
||||
@@ -85,7 +93,7 @@ public function channelFor(string $from): ?Channel
|
||||
{
|
||||
$from = mb_strtolower($from);
|
||||
|
||||
return Channel::query()->active()->get()->first(function (Channel $channel) use ($from): bool {
|
||||
$matches = Channel::query()->active()->get()->filter(function (Channel $channel) use ($from): bool {
|
||||
foreach ($this->senders($channel) as $sender) {
|
||||
if (str_contains($from, $sender)) {
|
||||
return true;
|
||||
@@ -94,6 +102,16 @@ public function channelFor(string $from): ?Channel
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
if ($matches->count() > 1) {
|
||||
foreach ($matches as $channel) {
|
||||
$channel->forceFill(['sync_warnings' => array_values(array_unique([
|
||||
...($channel->sync_warnings ?? []), 'Portal-Mail-Absender passt zu mehreren Kanälen. Keine automatische Wohnungszuordnung vorgenommen.',
|
||||
]))])->saveQuietly();
|
||||
}
|
||||
}
|
||||
|
||||
return $matches->count() === 1 ? $matches->first() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -108,7 +126,7 @@ public function senders(Channel $channel): array
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $conflicts
|
||||
* @param array<string, CarbonInterface> $conflicts description => first night
|
||||
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
|
||||
*/
|
||||
private function block(Channel $channel, ParsedPortalMail $parsed, array &$conflicts): array
|
||||
@@ -117,11 +135,13 @@ private function block(Channel $channel, ParsedPortalMail $parsed, array &$confl
|
||||
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();
|
||||
$known = $parsed->reference === null ? null : $channel->blockedPeriods()
|
||||
->whereIn('external_uid', ['email:'.$parsed->reference, $parsed->reference])->first();
|
||||
if ($known) {
|
||||
if ($known->source === 'email') {
|
||||
$known->update(['starts_on' => $parsed->startsOn->toDateString(), 'ends_on' => $parsed->endsOn->toDateString()]);
|
||||
}
|
||||
|
||||
return [PortalEmailStatus::AlreadyKnown, $known, null];
|
||||
}
|
||||
|
||||
@@ -131,10 +151,14 @@ private function block(Channel $channel, ParsedPortalMail $parsed, array &$confl
|
||||
'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')),
|
||||
'external_uid' => 'email:'.($parsed->reference ?? bin2hex(random_bytes(16))),
|
||||
]);
|
||||
|
||||
$conflicts = $this->conflictDetector->conflictsFor($block);
|
||||
if ($channel->blockedPeriods()->whereKeyNot($block->id)->overlapping($block->starts_on, $block->ends_on)->exists()) {
|
||||
$block->forceFill(['needs_review' => true, 'review_note' => 'Überlappende Portalrepräsentationen ohne gemeinsame Kennung persönlich prüfen.'])->saveQuietly();
|
||||
}
|
||||
|
||||
$conflicts = array_fill_keys($this->conflictDetector->conflictsFor($block), $block->starts_on);
|
||||
|
||||
return [PortalEmailStatus::Blocked, $block, null];
|
||||
}
|
||||
@@ -150,7 +174,6 @@ private function release(Channel $channel, ParsedPortalMail $parsed): array
|
||||
|
||||
$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,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\ChannelEchoBehavior;
|
||||
use App\Enums\OccupationKind;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Property;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ReconcileChannelRepresentations
|
||||
{
|
||||
public const OVERLAP_NOTE = 'Mehrere Belegungsrepräsentationen oder Überschneidungen prüfen; keine automatische Zusammenführung anhand von Terminen.';
|
||||
|
||||
private const LINK_NOTE = 'Automatisch als Kalenderspiegelung einer eindeutig passenden führenden Portalreservierung zugeordnet.';
|
||||
|
||||
private const RECHECK_NOTE = 'Automatische Kalenderspiegelung nicht mehr eindeutig. Quellen, Termine und mögliche Stornierung prüfen; der weiterhin gemeldete Zeitraum bleibt belegt.';
|
||||
|
||||
/** @return array{linked: int, unlinked: int} */
|
||||
public function handle(Property $property): array
|
||||
{
|
||||
return DB::transaction(function () use ($property): array {
|
||||
$property = Property::query()->whereKey($property->id)->lockForUpdate()->firstOrFail();
|
||||
$blocks = $property->blockedPeriods()->with('channel')->withCount('channelRepresentations')->orderBy('id')->lockForUpdate()->get()->keyBy('id');
|
||||
$independent = $blocks->filter(fn (BlockedPeriod $block): bool => ! $block->is_representation || $block->representation_automatic);
|
||||
$mirrors = $independent->filter(fn (BlockedPeriod $block): bool => $this->isMirror($block));
|
||||
$leaders = $independent->filter(fn (BlockedPeriod $block): bool => $this->isLeader($block));
|
||||
$bookings = $property->bookings()->occupying()->get(['id', 'arrival', 'departure']);
|
||||
$targets = [];
|
||||
foreach ($mirrors as $mirror) {
|
||||
$matches = $leaders->filter(fn (BlockedPeriod $leader): bool => $leader->channel_id !== $mirror->channel_id && $this->sameDates($leader, $mirror));
|
||||
if ($matches->count() !== 1) {
|
||||
continue;
|
||||
}
|
||||
$leader = $matches->sole();
|
||||
$contradiction = $independent->contains(fn (BlockedPeriod $other): bool => $other->id !== $mirror->id && $other->id !== $leader->id
|
||||
&& $other->starts_on->lessThan($leader->ends_on) && $other->ends_on->greaterThan($leader->starts_on)
|
||||
&& ! ($mirrors->has($other->id) && $this->sameDates($other, $leader)));
|
||||
if ($contradiction || $bookings->contains(fn ($booking): bool => $booking->arrival->lessThan($leader->ends_on) && $booking->departure->greaterThan($leader->starts_on))) {
|
||||
continue;
|
||||
}
|
||||
$targets[$mirror->id] = $leader;
|
||||
}
|
||||
|
||||
$counts = ['linked' => 0, 'unlinked' => 0];
|
||||
foreach ($blocks as $block) {
|
||||
$leader = $targets[$block->id] ?? null;
|
||||
if ($leader === null) {
|
||||
if ($block->representation_automatic) {
|
||||
$block->forceFill(['representation_automatic' => false, 'is_representation' => false, 'canonical_block_id' => null, 'export_approved' => false,
|
||||
'needs_review' => true, 'review_note' => self::RECHECK_NOTE])->save();
|
||||
$counts['unlinked']++;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
$newLink = ! $block->is_representation || $block->canonical_block_id !== $leader->id;
|
||||
$block->forceFill(['representation_automatic' => true, 'is_representation' => true, 'canonical_block_id' => $leader->id,
|
||||
'needs_review' => false, 'review_note' => self::LINK_NOTE]);
|
||||
if ($block->isDirty()) {
|
||||
$block->save();
|
||||
}
|
||||
$counts['linked'] += (int) $newLink;
|
||||
if ($leader->reviewed_at === null) {
|
||||
if ($leader->channel?->echo_behavior !== ChannelEchoBehavior::Reexports) {
|
||||
$leader->forceFill(['export_approved' => true]);
|
||||
}
|
||||
if ($leader->review_note === self::OVERLAP_NOTE) {
|
||||
$leader->forceFill(['needs_review' => false, 'review_note' => null]);
|
||||
}
|
||||
if ($leader->isDirty()) {
|
||||
$leader->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $counts;
|
||||
});
|
||||
}
|
||||
|
||||
private function isMirror(BlockedPeriod $block): bool
|
||||
{
|
||||
$interpretation = $block->ical_interpretation ?? [];
|
||||
|
||||
return $block->source === 'channel' && $block->channel_id !== null && $block->missing_imports === 0
|
||||
&& $block->occupation_kind === null && $block->guest_id === null && ! $block->is_private
|
||||
&& $block->block_purpose === null && blank($block->block_note) && $block->reviewed_at === null
|
||||
&& $block->origin_channel_id === null && $block->linked_booking_id === null && $block->channel_representations_count === 0
|
||||
&& $block->ical_event_type === 'block' && ($interpretation['matched'] ?? false)
|
||||
&& ($interpretation['representation'] ?? null) === 'additional_block' && ($interpretation['origin_channel_id'] ?? null) === null
|
||||
&& blank($interpretation['fields']['booking_reference'] ?? null) && blank($interpretation['fields']['guest_full_name'] ?? null)
|
||||
&& blank($interpretation['fields']['guest_first_name'] ?? null) && $this->hasCompatibleReview($block);
|
||||
}
|
||||
|
||||
private function isLeader(BlockedPeriod $block): bool
|
||||
{
|
||||
return $block->source === 'channel' && $block->channel_id !== null && ! $block->is_representation
|
||||
&& $block->occupationKind() === OccupationKind::Reservation && $block->ical_event_type === 'portal_reservation'
|
||||
&& $block->missing_imports === 0 && ! $block->is_private && $block->leading_priority > 0
|
||||
&& $block->origin_channel_id === $block->channel_id && ($block->ical_interpretation['matched'] ?? false)
|
||||
&& ($block->ical_interpretation['representation'] ?? null) === 'leading_candidate' && $this->hasCompatibleReview($block);
|
||||
}
|
||||
|
||||
private function hasCompatibleReview(BlockedPeriod $block): bool
|
||||
{
|
||||
return ! $block->needs_review || in_array($block->review_note, [self::OVERLAP_NOTE, self::LINK_NOTE, self::RECHECK_NOTE], true);
|
||||
}
|
||||
|
||||
private function sameDates(BlockedPeriod $first, BlockedPeriod $second): bool
|
||||
{
|
||||
return $first->starts_on->equalTo($second->starts_on) && $first->ends_on->equalTo($second->ends_on);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
@@ -34,7 +35,7 @@ public function handle(Booking $booking, int $offerVersion): void
|
||||
]);
|
||||
|
||||
try {
|
||||
Mail::to(config('fewo.notification_email'))->send(new OfferAnswered($booking, accepted: false));
|
||||
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: false));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
}
|
||||
|
||||
@@ -4,18 +4,25 @@
|
||||
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Reminds the landlord once about blocking tasks that are still open after the reminder time.
|
||||
* Reminds the landlord about blocking tasks that are still open after the reminder time, and again after
|
||||
* the landlord's reminder interval while they stay open (Settings::reminderIntervalDays(), 0 = only once).
|
||||
*/
|
||||
class RemindChannelTasks
|
||||
{
|
||||
public function handle(): int
|
||||
{
|
||||
$interval = Settings::reminderIntervalDays();
|
||||
|
||||
$tasks = ChannelTask::query()
|
||||
->open()
|
||||
->whereNull('reminded_at')
|
||||
->where(fn (Builder $query) => $query
|
||||
->whereNull('reminded_at')
|
||||
->when($interval > 0, fn (Builder $query) => $query->orWhere('reminded_at', '<=', now()->subDays($interval))))
|
||||
->where('created_at', '<=', now()->subMinutes(config('fewo.channels.task_reminder_after_minutes')))
|
||||
->with('channel')
|
||||
->get();
|
||||
@@ -24,7 +31,7 @@ public function handle(): int
|
||||
return 0;
|
||||
}
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new ChannelTasksNotification($tasks->all(), reminder: true));
|
||||
Mail::to(Settings::notificationRecipients())->send(new ChannelTasksNotification($tasks->all(), reminder: true));
|
||||
ChannelTask::whereKey($tasks->modelKeys())->update(['reminded_at' => now()]);
|
||||
|
||||
return $tasks->count();
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\InboxMessageKind;
|
||||
use App\Filament\Pages\OccupancyCalendar;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Models\Channel;
|
||||
use App\Support\Inbox;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Reports possible double bookings found while importing portal occupations (calendar sync or portal
|
||||
* e-mail). Every conflict lands in the admin inbox once; only conflicts not reported before are e-mailed,
|
||||
* so a lasting overlap does not trigger a mail on every sync. Unread ones are repeated after the landlord's
|
||||
* reminder interval while the overlap persists (App\Support\Inbox).
|
||||
*/
|
||||
class ReportChannelConflicts
|
||||
{
|
||||
public function __construct(private Inbox $inbox) {}
|
||||
|
||||
/**
|
||||
* @param array<string, CarbonInterface> $conflicts description => first night of the portal occupation
|
||||
* @return list<string> the conflicts e-mailed now (new ones and due reminders)
|
||||
*/
|
||||
public function handle(Channel $channel, array $conflicts): array
|
||||
{
|
||||
$new = [];
|
||||
$reminders = [];
|
||||
foreach ($conflicts as $description => $startsOn) {
|
||||
$message = $this->inbox->post(
|
||||
InboxMessageKind::ChannelConflict,
|
||||
$channel->id.':'.sha1($description),
|
||||
'Mögliche Doppelbuchung über '.$channel->name,
|
||||
$description,
|
||||
$channel,
|
||||
OccupancyCalendar::getUrl(['monat' => $startsOn->format('Y-m'), 'wohnung' => $channel->property_id]),
|
||||
);
|
||||
if ($message?->wasRecentlyCreated) {
|
||||
$new[] = $description;
|
||||
} elseif ($message) {
|
||||
$reminders[] = $description;
|
||||
}
|
||||
}
|
||||
|
||||
if ($new !== [] || $reminders !== []) {
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $new, $reminders)));
|
||||
}
|
||||
|
||||
return [...$new, ...$reminders];
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ public function handle(): int
|
||||
->whereDate('departure', '<=', $latestDeparture)
|
||||
->whereDate('departure', '>', $latestDeparture->copy()->subDays(30))
|
||||
->whereDoesntHave('review')
|
||||
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at'))
|
||||
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
|
||||
->with('guest')
|
||||
->get();
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ResolveChannelOccupation
|
||||
{
|
||||
public function handle(BlockedPeriod $block, string $resolution, ?int $targetId = null, ?int $originId = null): BlockedPeriod
|
||||
{
|
||||
return DB::transaction(function () use ($block, $resolution, $targetId, $originId): BlockedPeriod {
|
||||
Property::query()->whereKey($block->property_id)->lockForUpdate()->firstOrFail();
|
||||
$block = BlockedPeriod::query()->whereKey($block->id)->lockForUpdate()->firstOrFail();
|
||||
if (! in_array($block->source, ['channel', 'email'], true)) {
|
||||
throw ValidationException::withMessages(['resolution' => 'Nur importierte Portalereignisse benötigen diese Zuordnung.']);
|
||||
}
|
||||
if (! in_array($resolution, ['independent', 'block', 'booking'], true)) {
|
||||
throw ValidationException::withMessages(['resolution' => 'Bitte eine gültige Klärung wählen.']);
|
||||
}
|
||||
if ($originId !== null && ! Channel::query()->whereKey($originId)->where('property_id', $block->property_id)->exists()) {
|
||||
throw ValidationException::withMessages(['origin_channel_id' => 'Der Ursprungskanal muss zur selben Wohnung gehören.']);
|
||||
}
|
||||
$attributes = ['is_representation' => false, 'canonical_block_id' => null, 'linked_booking_id' => null,
|
||||
'origin_channel_id' => $originId, 'is_private' => $originId === null && $block->is_private, 'export_approved' => true, 'needs_review' => false,
|
||||
'reviewed_at' => now(), 'review_note' => 'Als eigenständige Belegung persönlich bestätigt.'];
|
||||
if ($resolution !== 'independent') {
|
||||
$query = $resolution === 'booking' ? Booking::query()->occupying() : BlockedPeriod::query()->occupying()->whereKeyNot($block->id);
|
||||
$target = $query->where('property_id', $block->property_id)->whereKey($targetId)->lockForUpdate()->first();
|
||||
$start = $resolution === 'booking' ? $target?->arrival : $target?->starts_on;
|
||||
$end = $resolution === 'booking' ? $target?->departure : $target?->ends_on;
|
||||
if ($target === null || ! $block->starts_on->equalTo($start) || ! $block->ends_on->equalTo($end)) {
|
||||
throw ValidationException::withMessages(['target_id' => 'Eine belegende Buchung oder führende Sperre derselben Wohnung mit genau diesem Zeitraum wählen.']);
|
||||
}
|
||||
if (BlockedPeriod::query()->where('canonical_block_id', $block->id)->exists()) {
|
||||
throw ValidationException::withMessages(['target_id' => 'Diese Sperre führt bereits andere Kalenderdarstellungen. Die Zuordnung an der untergeordneten Darstellung ändern.']);
|
||||
}
|
||||
$attributes = [...$attributes, 'is_representation' => true, 'export_approved' => false,
|
||||
'canonical_block_id' => $resolution === 'block' ? $target->id : null,
|
||||
'linked_booking_id' => $resolution === 'booking' ? $target->id : null,
|
||||
'review_note' => 'Persönlich zugeordnet; nur die führende Belegung steuert Verfügbarkeit und Export.'];
|
||||
}
|
||||
$block->forceFill(['representation_automatic' => false])->fill($attributes)->save();
|
||||
app(ReconcileChannelRepresentations::class)->handle($block->property);
|
||||
|
||||
return $block->refresh();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class RotateChannelToken
|
||||
{
|
||||
public function handle(Channel $channel, int $graceHours = 168): Channel
|
||||
{
|
||||
return DB::transaction(function () use ($channel, $graceHours): Channel {
|
||||
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
if ($graceHours < 24 || $graceHours > 720 || $locked->previous_export_token_expires_at?->isFuture()) {
|
||||
throw ValidationException::withMessages(['grace_hours' => '24 bis 720 Stunden wählen; eine laufende Token-Übergangsphase muss zuerst ablaufen.']);
|
||||
}
|
||||
$locked->forceFill([
|
||||
'previous_export_token' => $locked->export_token,
|
||||
'previous_export_token_expires_at' => now()->addHours($graceHours),
|
||||
'export_token' => Str::random(48),
|
||||
])->save();
|
||||
|
||||
return $locked->refresh();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ICal\ICalRuleEngine;
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class SaveChannelRules
|
||||
{
|
||||
public function handle(Channel $channel, array $rules): Channel
|
||||
{
|
||||
return DB::transaction(function () use ($channel, $rules): Channel {
|
||||
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
$validated = app(ICalRuleEngine::class)->validate($locked, $rules);
|
||||
$locked->forceFill(['ical_rules' => $validated])->save();
|
||||
|
||||
return $locked;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -82,7 +82,7 @@ public function handle(): array
|
||||
private function bookings(callable $constraints): Collection
|
||||
{
|
||||
return $constraints(Booking::query()->with(['guest', 'property', 'payments']))
|
||||
->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at'))
|
||||
->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
|
||||
->get()
|
||||
->toBase();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\DigestSection;
|
||||
use App\Mail\Digest;
|
||||
use App\Models\Tenant;
|
||||
use App\Support\DigestReport;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Sends the landlord's daily and/or weekly summary once the chosen hour has come (System › Betrieb ›
|
||||
* Benachrichtigungen). On the weekly day only the weekly summary goes out, never both. Runs per landlord
|
||||
* from the scheduler; the sent dates on the landlord make every summary go out at most once a day.
|
||||
*/
|
||||
class SendDigests
|
||||
{
|
||||
public function __construct(private DigestReport $report) {}
|
||||
|
||||
/**
|
||||
* @return 'daily'|'weekly'|null which summary was due (also when it was skipped for being empty)
|
||||
*/
|
||||
public function handle(Tenant $tenant): ?string
|
||||
{
|
||||
$now = CarbonImmutable::now();
|
||||
$today = $now->startOfDay();
|
||||
if ($now->hour < $tenant->digest_hour) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$weekly = $tenant->digest_weekly && $today->isoWeekday() === $tenant->digest_weekday && ! $tenant->digest_weekly_sent_on?->isSameDay($today);
|
||||
$daily = $tenant->digest_daily && ! $tenant->digest_daily_sent_on?->isSameDay($today);
|
||||
if (! $weekly && ! $daily) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->send($tenant, $weekly);
|
||||
$tenant->forceFill([
|
||||
'digest_daily_sent_on' => $today->toDateString(),
|
||||
...($weekly ? ['digest_weekly_sent_on' => $today->toDateString()] : []),
|
||||
])->save();
|
||||
|
||||
return $weekly ? 'weekly' : 'daily';
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds and mails one summary. Without anything to report it is skipped unless the landlord wants it
|
||||
* anyway or $force is set (button „Zusammenfassung jetzt senden“).
|
||||
*
|
||||
* @return bool whether a mail was sent
|
||||
*/
|
||||
public function send(Tenant $tenant, bool $weekly, bool $force = false): bool
|
||||
{
|
||||
$since = CarbonImmutable::now()->sub($weekly ? '7 days' : '1 day');
|
||||
$sections = $this->report->build(DigestSection::chosen($tenant->digest_sections), $weekly, $since);
|
||||
|
||||
if ($sections === [] && ! $tenant->digest_when_empty && ! $force) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Mail::to(Settings::notificationRecipients())->send(new Digest($weekly, $sections));
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,10 @@ public function __construct(
|
||||
*/
|
||||
public function handle(Booking $booking, array $changes = [], bool $sendMail = true): Booking
|
||||
{
|
||||
if ($sendMail && blank($booking->guest?->email)) {
|
||||
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
|
||||
}
|
||||
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
|
||||
}
|
||||
@@ -98,7 +102,10 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
||||
*/
|
||||
public function offerUrl(Booking $booking): string
|
||||
{
|
||||
return URL::temporarySignedRoute('offers.show', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]);
|
||||
$parameters = ['booking' => $booking, 'v' => $booking->offer_version];
|
||||
|
||||
return $booking->website()?->temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters)
|
||||
?? URL::temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use App\Mail\NewReview;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Review;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use RuntimeException;
|
||||
|
||||
@@ -32,7 +33,7 @@ public function handle(Booking $booking, array $data): Review
|
||||
'stayed_on' => $booking->arrival,
|
||||
]);
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new NewReview($review));
|
||||
Mail::to(Settings::notificationRecipients())->send(new NewReview($review));
|
||||
|
||||
return $review;
|
||||
}
|
||||
|
||||
+124
-101
@@ -5,18 +5,17 @@
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ConflictDetector;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Enums\ChannelEchoBehavior;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
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).
|
||||
*/
|
||||
/** Imports one complete channel snapshot without guessing that overlapping events are identical. */
|
||||
class SyncChannel
|
||||
{
|
||||
public function __construct(private ConflictDetector $conflictDetector = new ConflictDetector) {}
|
||||
@@ -24,105 +23,129 @@ public function __construct(private ConflictDetector $conflictDetector = new Con
|
||||
public function handle(Channel $channel): ChannelSyncLog
|
||||
{
|
||||
$startedAt = microtime(true);
|
||||
|
||||
$lock = Cache::lock("channel-sync:{$channel->tenant_id}:{$channel->id}", 120);
|
||||
if (! $lock->get()) {
|
||||
return $channel->syncLogs()->create(['successful' => false, 'message' => 'Für diesen Kanal läuft bereits ein Abgleich.']);
|
||||
}
|
||||
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(),
|
||||
// The portal's SUMMARY is not stored: it may contain guest names (data minimisation).
|
||||
'reason' => $channel->name,
|
||||
'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));
|
||||
$channel->refresh();
|
||||
if (! $channel->importsOccupations()) {
|
||||
return $channel->syncLogs()->create(['successful' => false, 'message' => 'Import ist pausiert oder noch nicht eingerichtet.']);
|
||||
}
|
||||
$importUrl = $channel->setting('import_url');
|
||||
$periods = $channel->connector()->fetchOccupations($channel);
|
||||
$suffix = config('channels.uid_suffix');
|
||||
if (! is_string($suffix) || $suffix === '') {
|
||||
throw new ChannelSyncException('Der UID-Echofilter ist nicht eingerichtet.');
|
||||
}
|
||||
$today = CarbonImmutable::today();
|
||||
$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];
|
||||
$warnings = [];
|
||||
$conflicts = [];
|
||||
DB::transaction(function () use ($channel, $periods, $importUrl, $today, &$counts, &$warnings, &$conflicts): void {
|
||||
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
if (! $locked->importsOccupations() || $locked->setting('import_url') !== $importUrl) {
|
||||
throw new ChannelSyncException('Die Kanalkonfiguration wurde während des Abrufs geändert.');
|
||||
}
|
||||
Property::query()->whereKey($channel->property_id)->lockForUpdate()->firstOrFail();
|
||||
$rows = $channel->blockedPeriods()->withTrashed()->where('source', 'channel')->get();
|
||||
if ($rows->groupBy('external_uid')->contains(fn ($group): bool => $group->count() > 1) || $rows->contains(fn (BlockedPeriod $block): bool => blank($block->external_uid))) {
|
||||
throw new ChannelSyncException('Vorhandene Kalender-Dubletten oder fehlende UIDs benötigen eine manuelle Prüfung. Der Bestand bleibt erhalten.');
|
||||
}
|
||||
$existing = $rows->keyBy('external_uid');
|
||||
$emails = $channel->blockedPeriods()->where('source', 'email')->get();
|
||||
$seen = [];
|
||||
foreach ($periods as $period) {
|
||||
$seen[$period->uid] = true;
|
||||
$block = $existing->get($period->uid);
|
||||
$matchedMail = $block ? null : $emails->firstWhere('external_uid', 'email:'.$period->uid);
|
||||
$attributes = ['property_id' => $channel->property_id, 'starts_on' => $period->startsOn->toDateString(),
|
||||
'ends_on' => $period->endsOn->toDateString(), 'reason' => $channel->name, 'source' => 'channel',
|
||||
'external_uid' => $period->uid, 'missing_imports' => 0];
|
||||
$interpretation = $period->properties !== [] ? app(ApplyChannelRules::class)->attributes($locked, $block ?? $matchedMail, $period->properties) : [];
|
||||
if ($matchedMail) {
|
||||
$block = $matchedMail;
|
||||
$block->update($attributes);
|
||||
$emails = $emails->reject(fn (BlockedPeriod $mail): bool => $mail->is($block));
|
||||
$counts['changed']++;
|
||||
} elseif ($block) {
|
||||
if ($block->trashed()) {
|
||||
$block->fill($attributes)->restore();
|
||||
$counts['added']++;
|
||||
} elseif (! $block->starts_on->equalTo($period->startsOn) || ! $block->ends_on->equalTo($period->endsOn)) {
|
||||
$block->update($attributes);
|
||||
$counts['changed']++;
|
||||
} elseif ($block->missing_imports !== 0) {
|
||||
$block->forceFill(['missing_imports' => 0])->saveQuietly();
|
||||
}
|
||||
} else {
|
||||
$overlap = $channel->property->blockedPeriods()->occupying()->overlapping($period->startsOn, $period->endsOn)->exists()
|
||||
|| $channel->property->bookings()->occupying()->overlapping($period->startsOn, $period->endsOn)->exists();
|
||||
$attributes['export_approved'] = ! $overlap && $locked->echo_behavior !== ChannelEchoBehavior::Reexports;
|
||||
$block = new BlockedPeriod($attributes);
|
||||
$block->forceFill($interpretation);
|
||||
$channel->blockedPeriods()->save($block);
|
||||
$counts['added']++;
|
||||
}
|
||||
if ($period->properties !== []) {
|
||||
app(ApplyChannelRules::class)->store($block, [...$interpretation, 'ical_properties' => $period->properties, 'ical_raw' => $period->raw]);
|
||||
}
|
||||
$existing->put($period->uid, $block);
|
||||
}
|
||||
$missing = $rows->filter(fn (BlockedPeriod $block): bool => ! $block->trashed() && ! isset($seen[$block->external_uid]) && $block->ends_on->greaterThan($today));
|
||||
if ($missing->count() > config('channels.max_automatic_removals', 5)) {
|
||||
$warnings[] = 'Ungewöhnlich viele Ereignisse fehlen. Keine automatische Entfernung; Portalkalender persönlich prüfen.';
|
||||
foreach ($missing as $block) {
|
||||
$block->forceFill(['needs_review' => true, 'review_note' => end($warnings)])->saveQuietly();
|
||||
}
|
||||
} else {
|
||||
foreach ($missing as $block) {
|
||||
$block->increment('missing_imports');
|
||||
if ($block->missing_imports >= config('channels.removal_confirmation_runs', 2)) {
|
||||
$block->delete();
|
||||
$counts['removed']++;
|
||||
} else {
|
||||
$warnings[] = 'Fehlende Ereignisse bleiben bis zum nächsten bestätigenden Kalenderstand gesperrt.';
|
||||
}
|
||||
}
|
||||
}
|
||||
app(ReconcileChannelRepresentations::class)->handle($channel->property);
|
||||
foreach ($channel->blockedPeriods()->with(['canonicalBlock', 'linkedBooking'])->where('source', 'channel')->whereIn('external_uid', array_keys($seen))->get() as $block) {
|
||||
$overlap = $channel->blockedPeriods()->occupying()->overlapping($block->starts_on, $block->ends_on)->whereKeyNot($block->id)->exists();
|
||||
$foundConflicts = $block->is_representation ? [] : $this->conflictDetector->conflictsFor($block);
|
||||
$linked = $block->canonicalBlock ?? $block->linkedBooking;
|
||||
$linkedStart = $linked instanceof Booking ? $linked->arrival : $linked?->starts_on;
|
||||
$linkedEnd = $linked instanceof Booking ? $linked->departure : $linked?->ends_on;
|
||||
$representationChanged = $block->is_representation && ($linked === null || ! $block->starts_on->equalTo($linkedStart) || ! $block->ends_on->equalTo($linkedEnd));
|
||||
if ($representationChanged || (! $block->is_representation && $block->reviewed_at === null && ($overlap || $emails->isNotEmpty() || $foundConflicts !== [] || ! $block->export_approved))) {
|
||||
$note = ReconcileChannelRepresentations::OVERLAP_NOTE;
|
||||
$block->forceFill(['needs_review' => true, 'review_note' => $note])->saveQuietly();
|
||||
foreach ($emails as $mailBlock) {
|
||||
$mailBlock->forceFill(['needs_review' => true, 'review_note' => $note])->saveQuietly();
|
||||
}
|
||||
$warnings[] = $note;
|
||||
}
|
||||
foreach ($foundConflicts as $conflict) {
|
||||
$conflicts[$conflict] ??= $block->starts_on;
|
||||
}
|
||||
}
|
||||
$warnings = array_values(array_unique($warnings));
|
||||
$locked->forceFill(['last_synced_at' => now(), 'last_success_at' => now(), 'last_error' => null,
|
||||
'alerted_at' => null, 'last_import_events' => count($periods), 'sync_warnings' => $warnings])->save();
|
||||
});
|
||||
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
|
||||
|
||||
$stale = $existing->reject(fn (BlockedPeriod $block, string $uid): bool => isset($seen[$uid]) || $block->ends_on->lessThanOrEqualTo($today));
|
||||
$stale->each->delete();
|
||||
$counts['removed'] = $stale->count();
|
||||
});
|
||||
return $channel->syncLogs()->create(['successful' => true, 'events' => count($periods), ...$counts,
|
||||
'conflicts' => count($conflicts), 'warnings' => $warnings,
|
||||
'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000)]);
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$channel->forceFill(['last_synced_at' => now(), 'last_error_at' => now(), 'last_error' => $exception->getMessage()])->save();
|
||||
|
||||
$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' => false, 'message' => $exception->getMessage(),
|
||||
'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000)]);
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ public function isAvailable(Property $property, CarbonImmutable $from, CarbonImm
|
||||
->when($ignore, fn ($query) => $query->whereKeyNot($ignore->getKey()))
|
||||
->exists();
|
||||
|
||||
return ! $bookingConflict && ! $property->blockedPeriods()->overlapping($from, $until)->exists();
|
||||
return ! $bookingConflict && ! $property->blockedPeriods()->occupying()->overlapping($from, $until)->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,7 +33,7 @@ public function occupiedNights(Property $property, CarbonImmutable $from, Carbon
|
||||
{
|
||||
$periods = $property->bookings()->occupying()->overlapping($from, $until)->get(['arrival', 'departure'])
|
||||
->map(fn (Booking $booking): array => [$booking->arrival, $booking->departure])
|
||||
->concat($property->blockedPeriods()->overlapping($from, $until)->get(['starts_on', 'ends_on'])
|
||||
->concat($property->blockedPeriods()->occupying()->overlapping($from, $until)->get(['starts_on', 'ends_on'])
|
||||
->map(fn (BlockedPeriod $period): array => [$period->starts_on, $period->ends_on]));
|
||||
|
||||
$nights = [];
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Availability;
|
||||
|
||||
use App\Models\Property;
|
||||
use App\Pricing\PriceCalculator;
|
||||
use App\Pricing\PriceQuote;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\StayRequest;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
|
||||
/**
|
||||
* The next bookable stays from tomorrow on, for the "next free dates" in the hero section: free nights
|
||||
* that the PriceCalculator accepts (minimum stay, offers applied), at least $nights long, not overlapping.
|
||||
* Cached briefly per apartment because each candidate is a full price calculation (dates as strings: the cache
|
||||
* does not unserialize objects).
|
||||
*/
|
||||
class NextFreeStays
|
||||
{
|
||||
public const HORIZON_DAYS = 120;
|
||||
|
||||
public const MAX_NIGHTS = 7;
|
||||
|
||||
public function __construct(
|
||||
private AvailabilityChecker $availability,
|
||||
private PriceCalculator $calculator,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return list<array{arrival: CarbonImmutable, departure: CarbonImmutable, nights: int, total: int, url: string}>
|
||||
*/
|
||||
public function for(Property $property, int $count = 3, int $nights = 3, int $guests = 2): array
|
||||
{
|
||||
$key = "next-free-stays:{$property->id}:{$count}:{$nights}:{$guests}:".today()->toDateString();
|
||||
|
||||
$stays = Cache::remember($key, now()->addMinutes(10), fn (): array => $this->find($property, $count, $nights, min($guests, $property->max_guests)));
|
||||
|
||||
return array_map(fn (array $stay): array => [
|
||||
...$stay,
|
||||
'arrival' => CarbonImmutable::parse($stay['arrival']),
|
||||
'departure' => CarbonImmutable::parse($stay['departure']),
|
||||
], $stays);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{arrival: string, departure: string, nights: int, total: int, url: string}>
|
||||
*/
|
||||
private function find(Property $property, int $count, int $nights, int $guests): array
|
||||
{
|
||||
$from = CarbonImmutable::tomorrow();
|
||||
$until = $from->addDays(self::HORIZON_DAYS + self::MAX_NIGHTS);
|
||||
$occupied = $this->availability->occupiedNights($property, $from, $until);
|
||||
$stays = [];
|
||||
|
||||
for ($arrival = $from; count($stays) < $count && $arrival->lessThan($from->addDays(self::HORIZON_DAYS)); $arrival = $arrival->addDay()) {
|
||||
if (isset($occupied[$arrival->toDateString()])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$quote = $this->firstPricedStay($property, $arrival, $nights, $guests, $occupied);
|
||||
if ($quote === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$stays[] = [
|
||||
'arrival' => $quote->arrival->toDateString(),
|
||||
'departure' => $quote->departure->toDateString(),
|
||||
'nights' => $quote->nights(),
|
||||
'total' => $quote->total(),
|
||||
'url' => route('booking.create', ['anreise' => $quote->arrival->toDateString(), 'abreise' => $quote->departure->toDateString(), 'personen' => $guests]),
|
||||
];
|
||||
$arrival = $quote->departure->subDay();
|
||||
}
|
||||
|
||||
return $stays;
|
||||
}
|
||||
|
||||
/**
|
||||
* The shortest stay of at least $nights from $arrival that is free and priceable, if any.
|
||||
*
|
||||
* @param array<string, true> $occupied
|
||||
*/
|
||||
private function firstPricedStay(Property $property, CarbonImmutable $arrival, int $nights, int $guests, array $occupied): ?PriceQuote
|
||||
{
|
||||
for ($length = 1; $length <= self::MAX_NIGHTS; $length++) {
|
||||
if (isset($occupied[$arrival->addDays($length - 1)->toDateString()])) {
|
||||
return null;
|
||||
}
|
||||
if ($length < $nights) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->calculator->calculate($property, new StayRequest($arrival, $arrival->addDays($length), $guests));
|
||||
} catch (QuoteException) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Availability;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Filament\Resources\Guests\GuestResource;
|
||||
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
|
||||
class OccupancyOverview
|
||||
{
|
||||
/**
|
||||
* One read model over local booking workflows and their external calendar counterparts.
|
||||
* Source records retain their identities; linked representations never become a second stay.
|
||||
*
|
||||
* @return Collection<int|string, array<string, mixed>>
|
||||
*/
|
||||
public function records(?int $propertyId = null, ?int $guestId = null, bool $includeBlocks = false, ?CarbonImmutable $from = null, ?CarbonImmutable $until = null): Collection
|
||||
{
|
||||
Gate::authorize('viewAny', Booking::class);
|
||||
$representations = ['channelRepresentations' => fn ($query) => $query->select(['id', 'channel_id', 'canonical_block_id', 'linked_booking_id'])->with('channel:id,name')];
|
||||
$bookings = Booking::query()->with(['guest', 'property', 'originChannel', 'importChannel'])->with($representations)->withCount('channelRepresentations')
|
||||
->when($propertyId, fn ($query) => $query->where('property_id', $propertyId))
|
||||
->when($guestId, fn ($query) => $query->where('guest_id', $guestId))
|
||||
->when($from, fn ($query) => $query->whereDate('departure', '>=', $from))
|
||||
->when($until, fn ($query) => $query->whereDate('arrival', '<', $until))
|
||||
->get();
|
||||
$records = collect();
|
||||
foreach ($bookings as $booking) {
|
||||
$records->put($booking->id, [
|
||||
'record_type' => 'booking', 'record_id' => $booking->id, 'reference' => $booking->reference,
|
||||
'kind' => 'booking', 'kind_label' => 'Anfrage / Buchung',
|
||||
'property_id' => $booking->property_id, 'property' => $booking->property->name,
|
||||
'arrival' => $booking->arrival->toDateString(), 'departure' => $booking->departure->toDateString(),
|
||||
'nights' => $booking->nights(), 'persons' => $booking->guests, 'total' => $booking->total,
|
||||
'guest_id' => $booking->guest_id, 'guest' => $booking->guest?->full_name ?? 'Gastzuordnung offen',
|
||||
'guest_email' => $booking->guest?->email, 'guest_assigned' => $booking->guest_id !== null,
|
||||
'source' => $booking->bookingChannelLabel(), 'status' => $booking->status->getLabel(),
|
||||
'status_key' => $booking->status->value, 'color' => $booking->status->getColor(),
|
||||
'occupies' => in_array($booking->status, BookingStatus::occupying(), true) || $booking->isHoldActive(),
|
||||
'needs_review' => false, 'review_note' => null, 'reason' => null, 'archived' => false,
|
||||
'representations' => $booking->channel_representations_count,
|
||||
'mirrored_channels' => $booking->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(),
|
||||
'url' => BookingResource::getUrl('view', ['record' => $booking->id]),
|
||||
'guest_url' => $booking->guest_id ? GuestResource::getUrl('edit', ['record' => $booking->guest_id]) : null,
|
||||
]);
|
||||
}
|
||||
$blocks = BlockedPeriod::query()->select(['id', 'tenant_id', 'property_id', 'guest_id', 'channel_id', 'origin_channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'occupation_kind', 'block_purpose', 'block_note', 'is_private', 'ical_event_type', 'ical_interpretation', 'is_representation', 'needs_review', 'review_note', 'deleted_at'])->withTrashed()->occupying()->with(['guest', 'property', 'channel', 'originChannel'])->with($representations)->withCount('channelRepresentations')
|
||||
->when(! $includeBlocks, fn ($query) => $query->reservations())
|
||||
->when($propertyId, fn ($query) => $query->where('property_id', $propertyId))
|
||||
->when($guestId, fn ($query) => $query->where('guest_id', $guestId)->reservations())
|
||||
->when($from, fn ($query) => $query->whereDate('ends_on', '>=', $from))
|
||||
->when($until, fn ($query) => $query->whereDate('starts_on', '<', $until))
|
||||
->get();
|
||||
foreach ($blocks as $block) {
|
||||
$kind = $block->occupationKind();
|
||||
$records->put('portal-'.$block->id, [
|
||||
'record_type' => 'portal', 'record_id' => $block->id,
|
||||
'reference' => $block->ical_interpretation['fields']['booking_reference'] ?? 'Kalender-'.$block->id,
|
||||
'kind' => $kind->value, 'kind_label' => $kind->getLabel(),
|
||||
'property_id' => $block->property_id, 'property' => $block->property->name,
|
||||
'arrival' => $block->starts_on->toDateString(), 'departure' => $block->ends_on->toDateString(),
|
||||
'nights' => (int) $block->starts_on->diffInDays($block->ends_on), 'persons' => null, 'total' => null,
|
||||
'guest_id' => $block->guest_id, 'guest' => $block->guestName() ?? 'Gastzuordnung offen',
|
||||
'guest_email' => $block->guest?->email, 'guest_assigned' => $block->guest_id !== null,
|
||||
'source' => $block->bookingChannelLabel(),
|
||||
'status' => $block->trashed() ? 'Nicht mehr im Kalenderfeed' : ($block->needs_review ? 'Klärung erforderlich' : 'Im Kalender geführt'),
|
||||
'status_key' => $block->trashed() ? 'archived' : 'imported', 'color' => $block->needs_review ? 'warning' : $kind->getColor(),
|
||||
'occupies' => ! $block->trashed(), 'needs_review' => $block->needs_review, 'review_note' => $block->review_note, 'reason' => $block->blockDescription(),
|
||||
'archived' => $block->trashed(), 'representations' => $block->channel_representations_count,
|
||||
'mirrored_channels' => $block->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(),
|
||||
'url' => $block->source === 'manual' ? BlockedPeriodResource::getUrl() : PortalOccupationResource::getUrl('view', ['record' => $block->id]),
|
||||
'guest_url' => $block->guest_id ? GuestResource::getUrl('edit', ['record' => $block->guest_id]) : null,
|
||||
]);
|
||||
}
|
||||
|
||||
return $records;
|
||||
}
|
||||
|
||||
/** @return array{month: CarbonImmutable, days: array, rows: Collection, free: int, occupied: int} */
|
||||
public function calendar(Property $property, CarbonImmutable $month): array
|
||||
{
|
||||
$month = $month->startOfMonth();
|
||||
$until = $month->addMonth();
|
||||
$records = $this->records($property->id, includeBlocks: true, from: $month, until: $until);
|
||||
$occupying = $records->where('occupies', true);
|
||||
$days = [];
|
||||
for ($date = $month; $date->lessThan($until); $date = $date->addDay()) {
|
||||
$day = $date->toDateString();
|
||||
$nights = $occupying->filter(fn (array $record): bool => $record['arrival'] <= $day && $day < $record['departure']);
|
||||
$departures = $occupying->where('departure', $day);
|
||||
$days[] = ['date' => $date, 'free' => $nights->isEmpty(), 'occupations' => $nights->values()->all(), 'departures' => $departures->values()->all(), 'overlap' => $nights->count() > 1];
|
||||
}
|
||||
$free = collect($days)->where('free', true)->count();
|
||||
|
||||
return ['month' => $month, 'days' => $days, 'rows' => $records->sortBy('arrival'), 'free' => $free, 'occupied' => count($days) - $free];
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ public function conflictsFor(BlockedPeriod $block): array
|
||||
->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()
|
||||
->occupying()
|
||||
->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)))
|
||||
|
||||
@@ -14,5 +14,7 @@ public function __construct(
|
||||
public CarbonImmutable $startsOn,
|
||||
public CarbonImmutable $endsOn,
|
||||
public ?string $summary = null,
|
||||
public array $properties = [],
|
||||
public ?string $raw = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
class ICalAnalysis
|
||||
{
|
||||
/** @return array<string, mixed> */
|
||||
public function summarize(array $document): array
|
||||
{
|
||||
$events = [];
|
||||
$fields = [];
|
||||
$engine = new ICalRuleEngine;
|
||||
foreach ($document['events'] as $event) {
|
||||
$period = $event['period'];
|
||||
$events[] = ['uid' => $event['uid'], 'properties' => $event['properties'], 'raw' => $event['raw'],
|
||||
'starts_on' => $period?->startsOn->toDateString(), 'ends_on' => $period?->endsOn->toDateString(), 'occupying' => $period !== null];
|
||||
foreach (array_keys($event['properties']) as $field) {
|
||||
$fields[$field] ??= ['count' => 0, 'values' => [], 'patterns' => []];
|
||||
$fields[$field]['count']++;
|
||||
foreach (array_unique($engine->values($event['properties'], $field)) as $value) {
|
||||
$fields[$field]['values'][$value] = ($fields[$field]['values'][$value] ?? 0) + 1;
|
||||
$pattern = $value;
|
||||
foreach ([' - ', ': ', ' / '] as $delimiter) {
|
||||
if (($position = mb_strpos($value, $delimiter)) !== false) {
|
||||
$pattern = mb_substr($value, 0, $position + mb_strlen($delimiter)).'…';
|
||||
break;
|
||||
}
|
||||
}
|
||||
$fields[$field]['patterns'][$pattern] = ($fields[$field]['patterns'][$pattern] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
ksort($fields);
|
||||
foreach ($fields as &$field) {
|
||||
arsort($field['values']);
|
||||
arsort($field['patterns']);
|
||||
$field['values'] = array_slice($field['values'], 0, 10, true);
|
||||
$field['patterns'] = array_slice($field['patterns'], 0, 10, true);
|
||||
}
|
||||
|
||||
return ['count' => count($events), 'events' => $events, 'fields' => $fields, 'calendar' => $document['calendar']];
|
||||
}
|
||||
}
|
||||
@@ -32,9 +32,11 @@ public static function settingsSchema(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('settings.import_url')
|
||||
->label('iCal-Export-Adresse des Portals')
|
||||
->label('Importadresse: iCal-Export des externen Portals')
|
||||
->helperText('Im Vermieterbereich des Portals unter „Kalender exportieren“. Leer lassen, wenn das Portal keinen Kalender anbietet.')
|
||||
->url()
|
||||
->password()
|
||||
->revealable()
|
||||
->maxLength(2048),
|
||||
];
|
||||
}
|
||||
@@ -45,6 +47,17 @@ public function canImport(Channel $channel): bool
|
||||
}
|
||||
|
||||
public function fetchOccupations(Channel $channel): array
|
||||
{
|
||||
return $this->parser->parse($this->fetchCalendar($channel));
|
||||
}
|
||||
|
||||
/** @return array{events: list<array>, calendar: array} */
|
||||
public function fetchDocument(Channel $channel): array
|
||||
{
|
||||
return $this->parser->parseDocument($this->fetchCalendar($channel));
|
||||
}
|
||||
|
||||
private function fetchCalendar(Channel $channel): string
|
||||
{
|
||||
$url = preg_replace('#^webcals?://#i', 'https://', (string) $channel->setting('import_url'));
|
||||
|
||||
@@ -55,9 +68,9 @@ public function fetchOccupations(Channel $channel): array
|
||||
->get($url)
|
||||
->throw();
|
||||
} catch (ConnectionException|RequestException $exception) {
|
||||
throw new ChannelSyncException('Kalender konnte nicht abgerufen werden: '.$exception->getMessage(), previous: $exception);
|
||||
throw new ChannelSyncException('Kalender konnte nicht abgerufen werden. Netzwerkverbindung und Portaladresse prüfen.', previous: $exception);
|
||||
}
|
||||
|
||||
return $this->parser->parse($response->body());
|
||||
return $response->body();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ICalExport
|
||||
{
|
||||
public function __construct(private ICalFeed $feed, private ICalParser $parser) {}
|
||||
|
||||
public function build(Channel $channel, string $method = 'GET', ?string $userAgent = null): ?string
|
||||
{
|
||||
$requestedAt = now();
|
||||
|
||||
return DB::transaction(function () use ($channel, $method, $userAgent, $requestedAt): ?string {
|
||||
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
|
||||
if ($locked->exportsOccupations()) {
|
||||
$body = $this->feed->build($locked);
|
||||
$this->parser->parse($body);
|
||||
$locked->forceFill(['export_snapshot' => $body, 'export_snapshot_at' => now()]);
|
||||
}
|
||||
$lastRequest = $locked->last_export_requested_at;
|
||||
$locked->forceFill(['last_export_requested_at' => $lastRequest?->greaterThan($requestedAt) ? $lastRequest : $requestedAt])->saveQuietly();
|
||||
$userAgent = str_replace(array_filter([$locked->export_token, $locked->previous_export_token]), '[Token entfernt]', $userAgent ?? '');
|
||||
$locked->exportRequests()->create([
|
||||
'requested_at' => $requestedAt,
|
||||
'method' => $method,
|
||||
'user_agent' => filled($userAgent) ? mb_substr(str_replace(["\r", "\n"], ' ', $userAgent), 0, 512) : null,
|
||||
'response_status' => $locked->export_snapshot === null ? 503 : 200,
|
||||
'export_state' => $locked->export_snapshot === null ? 'unavailable' : ($locked->exportsOccupations() ? 'live' : 'frozen'),
|
||||
]);
|
||||
$expired = $locked->exportRequests()->skip(max(1, (int) config('channels.export_request_history_limit', 100)))->take(1000)->pluck('id');
|
||||
if ($expired->isNotEmpty()) {
|
||||
$locked->exportRequests()->whereIn('id', $expired)->delete();
|
||||
}
|
||||
|
||||
return $locked->export_snapshot;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
|
||||
class ICalExportFields
|
||||
{
|
||||
public const FIELDS = ['occupation_label' => 'Belegungsbeschreibung', 'guest_first_name' => 'Gastvorname / Namensbestandteil', 'guest_full_name' => 'Vollständiger Gastname', 'booking_reference' => 'Buchungsreferenz', 'note' => 'Zusätzliche Textinformation', 'property_name' => 'Wohnungsname', 'channel_name' => 'Bekannter Ursprung / Importkanal', 'arrival' => 'Anreise', 'departure' => 'Abreise', 'nights' => 'Anzahl Nächte'];
|
||||
|
||||
public const ICAL_FIELDS = ['SUMMARY' => 'SUMMARY – Bezeichnung', 'DESCRIPTION' => 'DESCRIPTION – Beschreibung', 'LOCATION' => 'LOCATION – Ort / Wohnung'];
|
||||
|
||||
/** @return array<string, string> */
|
||||
public function properties(Channel $channel, Booking|BlockedPeriod $occupation): array
|
||||
{
|
||||
$context = $this->context($occupation);
|
||||
if (! $channel->ical_export_names) {
|
||||
unset($context['guest_first_name'], $context['guest_full_name']);
|
||||
}
|
||||
$properties = ['SUMMARY' => 'Belegt'];
|
||||
foreach ($channel->ical_export_mapping ?? [] as $mapping) {
|
||||
if (! isset(self::ICAL_FIELDS[$mapping['field'] ?? ''])) {
|
||||
continue;
|
||||
}
|
||||
$parts = [];
|
||||
foreach ($mapping['items'] ?? [] as $item) {
|
||||
if (isset(self::FIELDS[$item]) && filled($context[$item] ?? null)) {
|
||||
$parts[] = $context[$item];
|
||||
}
|
||||
}
|
||||
if ($parts !== []) {
|
||||
$properties[$mapping['field']] = implode($mapping['separator'] ?? ' – ', $parts);
|
||||
}
|
||||
}
|
||||
|
||||
return $properties;
|
||||
}
|
||||
|
||||
/** @return array<string, string|null> */
|
||||
public function context(Booking|BlockedPeriod $occupation): array
|
||||
{
|
||||
$booking = $occupation instanceof Booking;
|
||||
$start = $booking ? $occupation->arrival : $occupation->starts_on;
|
||||
$end = $booking ? $occupation->departure : $occupation->ends_on;
|
||||
$context = ['occupation_label' => $booking ? 'Buchung' : (ICalRuleEngine::TYPES[$occupation->ical_event_type] ?? 'Belegt'),
|
||||
'property_name' => $occupation->property->name, 'arrival' => $start->format('d.m.Y'), 'departure' => $end->format('d.m.Y'),
|
||||
'nights' => (string) (int) $start->diffInDays($end),
|
||||
'channel_name' => $booking ? null : ($occupation->originChannel?->name ?? $occupation->channel?->name)];
|
||||
if ($booking) {
|
||||
return [...$context, 'guest_first_name' => $occupation->guest?->first_name, 'guest_full_name' => $occupation->guest?->full_name, 'booking_reference' => $occupation->reference];
|
||||
}
|
||||
$fields = array_intersect_key($occupation->ical_interpretation['fields'] ?? [], self::FIELDS);
|
||||
if ($occupation->guest !== null) {
|
||||
$fields['guest_first_name'] = $occupation->guest->anonymized_at === null ? $occupation->guest->first_name : null;
|
||||
$fields['guest_full_name'] = $occupation->guest->anonymized_at === null && filled($occupation->guest->last_name) ? $occupation->guest->full_name : null;
|
||||
}
|
||||
|
||||
return [...$context, ...$fields];
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Enums\ChannelExportMode;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use Carbon\CarbonImmutable;
|
||||
@@ -23,21 +24,32 @@ public function build(Channel $channel): string
|
||||
|
||||
$events = [];
|
||||
|
||||
foreach ($property->bookings()->occupying()->overlapping($from, $until)->get() as $booking) {
|
||||
$bookings = $property->bookings()->occupying()->overlapping($from, $until);
|
||||
if ($channel->export_mode === ChannelExportMode::Test) {
|
||||
$bookings->whereNull('import_channel_id')->whereNull('origin_channel_id')->whereIn('source', Booking::DIRECT_SOURCES);
|
||||
} else {
|
||||
$bookings->where(fn ($query) => $query->whereNull('import_channel_id')->orWhere('import_channel_id', '!=', $channel->id))
|
||||
->where(fn ($query) => $query->whereNull('origin_channel_id')->orWhere('origin_channel_id', '!=', $channel->id));
|
||||
}
|
||||
foreach ($bookings->with(['guest', 'property'])->orderBy('id')->get() as $booking) {
|
||||
/** @var Booking $booking */
|
||||
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at);
|
||||
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at, (new ICalExportFields)->properties($channel, $booking));
|
||||
}
|
||||
|
||||
$blocks = $property->blockedPeriods()
|
||||
->occupying()->where('export_approved', true)
|
||||
->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);
|
||||
->where(fn ($query) => $query->whereNull('origin_channel_id')->orWhere('origin_channel_id', '!=', $channel->id));
|
||||
if ($channel->export_mode === ChannelExportMode::Test) {
|
||||
$blocks->whereNull('channel_id')->whereNull('origin_channel_id')->where('source', 'manual');
|
||||
}
|
||||
|
||||
return implode("\r\n", [
|
||||
foreach ($blocks->with(['property', 'channel', 'originChannel', 'guest'])->orderBy('id')->get() as $block) {
|
||||
$events[] = $this->event("block-{$block->id}{$suffix}", $block->starts_on, $block->ends_on, $block->updated_at, (new ICalExportFields)->properties($channel, $block));
|
||||
}
|
||||
|
||||
$lines = [
|
||||
'BEGIN:VCALENDAR',
|
||||
'VERSION:2.0',
|
||||
'PRODID:-//Ferienwohnung Stommer//Belegung//DE',
|
||||
@@ -46,10 +58,12 @@ public function build(Channel $channel): string
|
||||
'X-WR-CALNAME:'.$this->escape($property->name),
|
||||
...$events,
|
||||
'END:VCALENDAR',
|
||||
])."\r\n";
|
||||
];
|
||||
|
||||
return implode("\r\n", array_map(fn (string $line): string => $this->fold($line), explode("\r\n", implode("\r\n", $lines))))."\r\n";
|
||||
}
|
||||
|
||||
private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified): string
|
||||
private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified, array $properties): string
|
||||
{
|
||||
return implode("\r\n", [
|
||||
'BEGIN:VEVENT',
|
||||
@@ -57,7 +71,7 @@ private function event(string $uid, CarbonInterface $start, CarbonInterface $end
|
||||
'DTSTAMP:'.($modified ?? now())->utc()->format('Ymd\THis\Z'),
|
||||
'DTSTART;VALUE=DATE:'.$start->format('Ymd'),
|
||||
'DTEND;VALUE=DATE:'.$end->format('Ymd'),
|
||||
'SUMMARY:Belegt',
|
||||
...array_map(fn (string $field, string $value): string => $field.':'.$this->escape($value), array_keys($properties), array_values($properties)),
|
||||
'TRANSP:OPAQUE',
|
||||
'END:VEVENT',
|
||||
]);
|
||||
@@ -65,6 +79,21 @@ private function event(string $uid, CarbonInterface $start, CarbonInterface $end
|
||||
|
||||
private function escape(string $text): string
|
||||
{
|
||||
return str_replace(['\\', ';', ',', "\n"], ['\\\\', '\\;', '\\,', '\\n'], $text);
|
||||
return str_replace(['\\', ';', ',', "\n"], ['\\\\', '\\;', '\\,', '\\n'], str_replace(["\r\n", "\r"], "\n", $text));
|
||||
}
|
||||
|
||||
private function fold(string $line): string
|
||||
{
|
||||
$parts = [];
|
||||
$limit = 75;
|
||||
while (strlen($line) > $limit) {
|
||||
$part = mb_strcut($line, 0, $limit, 'UTF-8');
|
||||
$parts[] = $part;
|
||||
$line = substr($line, strlen($part));
|
||||
$limit = 74;
|
||||
}
|
||||
$parts[] = $line;
|
||||
|
||||
return implode("\r\n ", $parts);
|
||||
}
|
||||
}
|
||||
@@ -5,117 +5,240 @@
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
/** Complete non-recurring availability snapshots; damaged feeds never become deletions. */
|
||||
class ICalParser
|
||||
{
|
||||
/**
|
||||
* @return list<ExternalPeriod>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
/** @return list<ExternalPeriod> */
|
||||
public function parse(string $ics): array
|
||||
{
|
||||
if (! str_contains($ics, 'BEGIN:VCALENDAR')) {
|
||||
throw new ChannelSyncException('Die Antwort ist kein iCal-Kalender.');
|
||||
return array_values(array_filter(array_column($this->parseDocument($ics)['events'], 'period')));
|
||||
}
|
||||
|
||||
/** @return array{events: list<array>, calendar: array} */
|
||||
public function parseDocument(string $ics): array
|
||||
{
|
||||
if (str_starts_with($ics, "\xEF\xBB\xBF")) {
|
||||
$ics = substr($ics, 3);
|
||||
}
|
||||
|
||||
$lines = explode("\n", preg_replace("/\r?\n[ \t]/", '', str_replace("\r\n", "\n", $ics)));
|
||||
|
||||
$ics = preg_replace("/\r?\n[ \t]/", '', $ics);
|
||||
if (! mb_check_encoding($ics, 'UTF-8') || str_contains($ics, "\0")) {
|
||||
throw new ChannelSyncException('Kalender enthält ungültige Zeichen.');
|
||||
}
|
||||
$lines = explode("\n", str_replace("\r\n", "\n", $ics));
|
||||
$stack = [];
|
||||
$calendar = [];
|
||||
$event = [];
|
||||
$periods = [];
|
||||
$event = null;
|
||||
$properties = [];
|
||||
$eventLines = [];
|
||||
$identities = [];
|
||||
$propertyIdentities = [];
|
||||
$started = false;
|
||||
$closed = false;
|
||||
foreach ($lines as $line) {
|
||||
$line = rtrim($line, "\r");
|
||||
|
||||
if ($line === 'BEGIN:VEVENT') {
|
||||
$event = [];
|
||||
|
||||
if (in_array('VEVENT', $stack, true)) {
|
||||
$eventLines[] = $line;
|
||||
}
|
||||
if ($line === '' && $stack === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($line === 'END:VEVENT') {
|
||||
if ($event !== null && ($period = $this->toPeriod($event))) {
|
||||
$periods[] = $period;
|
||||
if ($closed || ! preg_match('/^((?:[^:"]|"[^"]*")*):(.*)$/D', $line, $match)) {
|
||||
throw new ChannelSyncException('Kalender ist unvollständig oder enthält ungültige Inhaltszeilen.');
|
||||
}
|
||||
$parts = preg_split('/;(?=(?:[^"]*"[^"]*")*[^"]*$)/', $match[1]);
|
||||
$name = strtoupper(array_shift($parts));
|
||||
$value = $match[2];
|
||||
if (! preg_match('/^[A-Z0-9-]+$/D', $name)) {
|
||||
throw new ChannelSyncException('Ungültige Kalendereigenschaft.');
|
||||
}
|
||||
if ($name === 'BEGIN') {
|
||||
$component = strtoupper($value);
|
||||
if ($stack === []) {
|
||||
if ($started || $component !== 'VCALENDAR') {
|
||||
throw new ChannelSyncException('Die Antwort ist kein vollständiger iCal-Kalender.');
|
||||
}
|
||||
$started = true;
|
||||
} elseif ($component === 'VCALENDAR' || ($component === 'VEVENT' && $stack !== ['VCALENDAR'])) {
|
||||
throw new ChannelSyncException('Ungültig verschachtelte Kalenderkomponente.');
|
||||
}
|
||||
$event = null;
|
||||
if ($stack === ['VCALENDAR'] && ! in_array($component, ['VEVENT', 'VTIMEZONE'], true)) {
|
||||
throw new ChannelSyncException('Nicht unterstützte Kalenderkomponente im Belegungsfeed.');
|
||||
}
|
||||
if ($component === 'VEVENT') {
|
||||
$event = [];
|
||||
$properties = [];
|
||||
$eventLines = [$line];
|
||||
}
|
||||
$stack[] = $component;
|
||||
|
||||
continue;
|
||||
}
|
||||
if ($name === 'END') {
|
||||
if ($stack === [] || end($stack) !== strtoupper($value)) {
|
||||
throw new ChannelSyncException('Kalenderkomponente ist nicht vollständig geschlossen.');
|
||||
}
|
||||
if (end($stack) === 'VEVENT') {
|
||||
$uid = trim($event['UID']['value'] ?? '');
|
||||
if ($uid === '') {
|
||||
throw new ChannelSyncException('Ein Kalenderereignis hat keine eindeutige UID.');
|
||||
}
|
||||
$period = $this->toPeriod($event);
|
||||
$identity = $period ? $period->startsOn->toDateString().'|'.$period->endsOn->toDateString() : 'not-occupying';
|
||||
if (isset($identities[$uid]) && $identities[$uid] !== $identity) {
|
||||
throw new ChannelSyncException('Eine UID enthält widersprüchliche Ereignisse; bitte den Portalkalender prüfen.');
|
||||
}
|
||||
$normalized = $properties;
|
||||
ksort($normalized);
|
||||
if (isset($propertyIdentities[$uid]) && $propertyIdentities[$uid] !== $normalized) {
|
||||
throw new ChannelSyncException('Eine UID enthält widersprüchliche Originalangaben; bitte den Kalender prüfen.');
|
||||
}
|
||||
$propertyIdentities[$uid] = $normalized;
|
||||
if (! isset($identities[$uid])) {
|
||||
$raw = implode("\r\n", $eventLines)."\r\n";
|
||||
$enriched = $period === null ? null : new ExternalPeriod($period->uid, $period->startsOn, $period->endsOn, $period->summary, $properties, $raw);
|
||||
$periods[] = ['uid' => $uid, 'properties' => $properties, 'raw' => $raw, 'period' => $enriched];
|
||||
}
|
||||
$identities[$uid] = $identity;
|
||||
}
|
||||
array_pop($stack);
|
||||
if ($stack === []) {
|
||||
$closed = true;
|
||||
}
|
||||
|
||||
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)];
|
||||
continue;
|
||||
}
|
||||
if ($stack === []) {
|
||||
throw new ChannelSyncException('Inhalt außerhalb des Kalenders.');
|
||||
}
|
||||
$property = ['value' => $value, 'params' => $parts];
|
||||
if ($stack === ['VCALENDAR']) {
|
||||
if (isset($calendar[$name]) && in_array($name, ['VERSION', 'PRODID', 'METHOD'], true)) {
|
||||
throw new ChannelSyncException('Doppelte Kalender-Kopfdaten.');
|
||||
}
|
||||
$calendar[$name] = $property;
|
||||
} elseif ($stack === ['VCALENDAR', 'VEVENT']) {
|
||||
if (isset($event[$name]) && in_array($name, ['UID', 'DTSTART', 'DTEND', 'DTSTAMP', 'LAST-MODIFIED', 'STATUS'], true)) {
|
||||
throw new ChannelSyncException('Doppelte Identitäts- oder Datumsangaben im Kalenderereignis.');
|
||||
}
|
||||
$event[$name] = $property;
|
||||
}
|
||||
if (in_array('VEVENT', $stack, true)) {
|
||||
$prefix = count($stack) > 2 ? implode('.', array_slice($stack, 2)).'.' : '';
|
||||
$properties[$prefix.$name][] = $property;
|
||||
}
|
||||
}
|
||||
if (! $closed || $stack !== [] || ($calendar['VERSION']['value'] ?? '') !== '2.0' || blank($calendar['PRODID']['value'] ?? null)) {
|
||||
throw new ChannelSyncException('Kalender ist unvollständig; VERSION, PRODID und geschlossene Komponenten sind erforderlich.');
|
||||
}
|
||||
if (isset($calendar['METHOD']) && strtoupper($calendar['METHOD']['value']) !== 'PUBLISH') {
|
||||
throw new ChannelSyncException('Erwartet wird ein vollständiger Kalenderstand, keine einzelne Kalendernachricht.');
|
||||
}
|
||||
|
||||
return $periods;
|
||||
return ['events' => $periods, 'calendar' => $calendar];
|
||||
}
|
||||
|
||||
public static function text(string $value): string
|
||||
{
|
||||
return preg_replace_callback('/\\\\([nN,;\\\\])/', fn (array $match): string => in_array($match[1], ['n', 'N'], true) ? "\n" : $match[1], $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Availability feeds may omit DTSTAMP. Validate event-level LAST-MODIFIED in its place,
|
||||
* retaining the actual original properties and rejecting an invalid present DTSTAMP.
|
||||
*
|
||||
* @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') {
|
||||
$stamp = $event['DTSTAMP']['value'] ?? $event['LAST-MODIFIED']['value'] ?? '';
|
||||
try {
|
||||
if (! preg_match('/^\d{8}T\d{6}Z$/D', $stamp) || CarbonImmutable::createFromFormat('!Ymd\THis\Z', $stamp, 'UTC')->format('Ymd\THis\Z') !== $stamp) {
|
||||
throw new \RuntimeException;
|
||||
}
|
||||
} catch (Throwable) {
|
||||
throw new ChannelSyncException('Ein Ereignis benötigt einen gültigen UTC-Zeitstempel (DTSTAMP oder ersatzweise LAST-MODIFIED).');
|
||||
}
|
||||
foreach (['RRULE', 'RDATE', 'EXDATE', 'RECURRENCE-ID', 'DURATION'] as $unsupported) {
|
||||
if (isset($event[$unsupported])) {
|
||||
throw new ChannelSyncException('Serien oder Dauerangaben werden für diesen Belegungskalender nicht unterstützt.');
|
||||
}
|
||||
}
|
||||
if (strtoupper($event['STATUS']['value'] ?? '') === 'CANCELLED') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (! isset($event['DTSTART'])) {
|
||||
throw new ChannelSyncException('Einem Kalenderereignis fehlt die Anreise.');
|
||||
}
|
||||
$start = $this->toDate($event['DTSTART']);
|
||||
$end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start?->addDay();
|
||||
|
||||
if ($start === null || $end === null || $end->lessThanOrEqualTo($start)) {
|
||||
if (! isset($event['DTEND']) && ! preg_match('/^\d{8}$/D', $event['DTSTART']['value'])) {
|
||||
throw new ChannelSyncException('Zeitgebundene Ereignisse benötigen eine ausdrückliche Abreise.');
|
||||
}
|
||||
$end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start->addDay();
|
||||
if (isset($event['DTEND']) && preg_match('/^\d{8}$/D', $event['DTSTART']['value']) !== preg_match('/^\d{8}$/D', $event['DTEND']['value'])) {
|
||||
throw new ChannelSyncException('An- und Abreise verwenden verschiedene Datumstypen.');
|
||||
}
|
||||
if ($end->lessThanOrEqualTo($start)) {
|
||||
throw new ChannelSyncException('Ein Kalenderereignis hat keinen positiven Übernachtungszeitraum.');
|
||||
}
|
||||
if (strtoupper($event['TRANSP']['value'] ?? '') === 'TRANSPARENT') {
|
||||
return null;
|
||||
}
|
||||
$summary = $event['SUMMARY']['value'] ?? null;
|
||||
|
||||
$uid = $event['UID']['value'] ?? sha1($start->toDateString().'|'.$end->toDateString());
|
||||
|
||||
return new ExternalPeriod($uid, $start, $end, $this->unescape($event['SUMMARY']['value'] ?? null));
|
||||
return new ExternalPeriod($event['UID']['value'], $start, $end, $summary === null ? null : self::text($summary));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{value: string, params: list<string>} $property
|
||||
*/
|
||||
private function toDate(array $property): ?CarbonImmutable
|
||||
/** @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);
|
||||
foreach ($property['params'] as $param) {
|
||||
if (str_starts_with(strtoupper($param), 'VALUE=')) {
|
||||
$type = strtoupper(trim(substr($param, 6), '"'));
|
||||
if (! in_array($type, ['DATE', 'DATE-TIME'], true) || ($type === 'DATE') !== (preg_match('/^\d{8}$/D', $value) === 1)) {
|
||||
throw new ChannelSyncException('Ungültiger Datumswerttyp.');
|
||||
}
|
||||
}
|
||||
if (str_starts_with(strtoupper($param), 'TZID=') && (preg_match('/^\d{8}$/D', $value) || str_ends_with($value, 'Z'))) {
|
||||
throw new ChannelSyncException('Unzulässige Kombination von Datum und Zeitzone.');
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
try {
|
||||
if (preg_match('/^\d{8}$/D', $value)) {
|
||||
$date = CarbonImmutable::createFromFormat('!Ymd', $value);
|
||||
if ($date->format('Ymd') === $value) {
|
||||
return $date;
|
||||
}
|
||||
} elseif (preg_match('/^(\d{8})T(\d{6})(Z?)$/D', $value, $match)) {
|
||||
$zone = $match[3] === 'Z' ? 'UTC' : $this->timezone($property['params']);
|
||||
$date = CarbonImmutable::createFromFormat('!YmdHis', $match[1].$match[2], $zone);
|
||||
if ($date->format('YmdHis') === $match[1].$match[2]) {
|
||||
return $date->setTimezone(config('app.timezone'))->startOfDay();
|
||||
}
|
||||
}
|
||||
} catch (Throwable) {
|
||||
throw new ChannelSyncException('Ungültiges Kalenderdatum oder unbekannte Zeitzone.');
|
||||
}
|
||||
|
||||
return null;
|
||||
throw new ChannelSyncException('Ungültiges Kalenderdatum.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $params
|
||||
*/
|
||||
/** @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), '"');
|
||||
$zone = trim(substr($param, 5), '"');
|
||||
if (! in_array($zone, timezone_identifiers_list(), true)) {
|
||||
throw new ChannelSyncException('Unbekannte Kalenderzeitzone.');
|
||||
}
|
||||
|
||||
return in_array($tz, timezone_identifiers_list(), true) ? $tz : config('app.timezone');
|
||||
return $zone;
|
||||
}
|
||||
}
|
||||
|
||||
return config('app.timezone');
|
||||
}
|
||||
|
||||
private function unescape(?string $text): ?string
|
||||
{
|
||||
return $text === null ? null : str_replace(['\\n', '\\N', '\\,', '\\;', '\\\\'], ["\n", "\n", ',', ';', '\\'], $text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ICalRuleEngine
|
||||
{
|
||||
public const OPERATORS = ['equals' => 'Ist gleich', 'not_equals' => 'Ist nicht gleich', 'starts_with' => 'Beginnt mit', 'ends_with' => 'Endet mit', 'contains' => 'Enthält', 'exists' => 'Ist vorhanden', 'empty' => 'Ist leer'];
|
||||
|
||||
public const TYPES = ['unknown' => 'Nicht erkannt', 'portal_reservation' => 'Portalreservierung', 'block' => 'Allgemeine Sperre'];
|
||||
|
||||
public const REPRESENTATIONS = ['unspecified' => 'Unbestimmt', 'leading_candidate' => 'Kandidat für führende Belegung', 'additional_block' => 'Zusätzliche Sperre'];
|
||||
|
||||
public const TARGETS = ['guest_first_name' => 'Gastvorname / Namensbestandteil', 'guest_full_name' => 'Vollständiger Gastname', 'booking_reference' => 'Buchungsreferenz', 'occupation_label' => 'Belegungsbeschreibung', 'note' => 'Zusätzliche Textinformation'];
|
||||
|
||||
public const EXTRACTIONS = ['whole' => 'Gesamter Text', 'after' => 'Text nach', 'before' => 'Text vor', 'between' => 'Text zwischen'];
|
||||
|
||||
/** @return list<string> */
|
||||
public function values(array $properties, string $field): array
|
||||
{
|
||||
return array_map(fn (array $property): string => ICalParser::text($property['value']), $properties[$field] ?? []);
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function evaluate(Channel $channel, array $properties, ?array $rules = null): array
|
||||
{
|
||||
$rules = collect($rules ?? $channel->ical_active_rules ?? [])->values()
|
||||
->map(fn (array $rule, int $index): array => [...$rule, '_index' => $index])
|
||||
->sortBy(fn (array $rule): array => [(int) ($rule['priority'] ?? 100), $rule['_index']]);
|
||||
foreach ($rules as $rule) {
|
||||
if (! ($rule['enabled'] ?? true) || empty($rule['conditions'])) {
|
||||
continue;
|
||||
}
|
||||
$matches = array_map(fn (array $condition): bool => $this->matches($properties, $condition, (bool) ($rule['case_sensitive'] ?? false)), array_values($rule['conditions']));
|
||||
if (($rule['match'] ?? 'all') === 'any' ? ! in_array(true, $matches, true) : in_array(false, $matches, true)) {
|
||||
continue;
|
||||
}
|
||||
$fields = [];
|
||||
foreach ($rule['extractions'] ?? [] as $extraction) {
|
||||
$value = $this->extract($this->values($properties, $extraction['field'] ?? '')[0] ?? '', $extraction);
|
||||
if (isset(self::TARGETS[$extraction['target'] ?? '']) && filled($value)) {
|
||||
$fields[$extraction['target']] = $value;
|
||||
}
|
||||
}
|
||||
$origin = $rule['origin'] ?? 'unknown';
|
||||
|
||||
return ['matched' => true, 'rule' => $rule['name'] ?? 'Unbenannte Regel', 'rule_index' => $rule['_index'],
|
||||
'event_type' => $rule['event_type'] ?? 'unknown', 'representation' => $rule['representation'] ?? 'unspecified',
|
||||
'priority' => (int) ($rule['priority'] ?? 100),
|
||||
'origin_channel_id' => $origin === 'current' ? $channel->id : (str_starts_with($origin, 'channel:') ? (int) substr($origin, 8) : null), 'fields' => $fields];
|
||||
}
|
||||
|
||||
return ['matched' => false, 'rule' => null, 'event_type' => 'unknown', 'representation' => 'unspecified', 'origin_channel_id' => null, 'priority' => 0, 'fields' => []];
|
||||
}
|
||||
|
||||
private function matches(array $properties, array $condition, bool $caseSensitive): bool
|
||||
{
|
||||
$field = $condition['field'] ?? '';
|
||||
if ($field === '') {
|
||||
return false;
|
||||
}
|
||||
$values = $this->values($properties, $field);
|
||||
$operator = $condition['operator'] ?? 'equals';
|
||||
if ($operator === 'exists') {
|
||||
return array_key_exists($field, $properties);
|
||||
}
|
||||
if ($operator === 'empty') {
|
||||
return $values === [] || collect($values)->every(fn (string $value): bool => trim($value) === '');
|
||||
}
|
||||
$expected = (string) ($condition['value'] ?? '');
|
||||
if (! $caseSensitive) {
|
||||
$expected = mb_strtolower($expected);
|
||||
$values = array_map(mb_strtolower(...), $values);
|
||||
}
|
||||
if ($operator === 'not_equals') {
|
||||
return $values !== [] && ! in_array($expected, $values, true);
|
||||
}
|
||||
|
||||
return collect($values)->contains(fn (string $value): bool => match ($operator) {
|
||||
'equals' => $value === $expected,
|
||||
'starts_with' => str_starts_with($value, $expected),
|
||||
'ends_with' => str_ends_with($value, $expected),
|
||||
'contains' => str_contains($value, $expected),
|
||||
default => false,
|
||||
});
|
||||
}
|
||||
|
||||
private function extract(string $text, array $extraction): ?string
|
||||
{
|
||||
$method = $extraction['method'] ?? 'whole';
|
||||
if (in_array($method, ['after', 'between'], true)) {
|
||||
$start = (string) ($extraction['start'] ?? '');
|
||||
$position = $start === '' ? false : mb_strpos($text, $start);
|
||||
if ($position === false) {
|
||||
return null;
|
||||
}
|
||||
$text = mb_substr($text, $position + mb_strlen($start));
|
||||
}
|
||||
if (in_array($method, ['before', 'between'], true)) {
|
||||
$end = (string) ($extraction['end'] ?? '');
|
||||
$position = $end === '' ? false : mb_strpos($text, $end);
|
||||
if ($position === false) {
|
||||
return null;
|
||||
}
|
||||
$text = mb_substr($text, 0, $position);
|
||||
}
|
||||
|
||||
return trim($text);
|
||||
}
|
||||
|
||||
/** @return list<array<string, mixed>> */
|
||||
public function validate(Channel $channel, array $rules): array
|
||||
{
|
||||
$fields = array_keys($channel->ical_analysis['fields'] ?? []);
|
||||
$origins = ['unknown', 'current', ...$channel->property->channels()->pluck('id')->map(fn ($id): string => 'channel:'.$id)->all()];
|
||||
Validator::make(['rules' => $rules], [
|
||||
'rules' => ['array'], 'rules.*.name' => ['required', 'string', 'max:120'],
|
||||
'rules.*.enabled' => ['boolean'], 'rules.*.priority' => ['required', 'integer', 'min:0', 'max:10000'],
|
||||
'rules.*.match' => ['required', Rule::in(['all', 'any'])], 'rules.*.case_sensitive' => ['boolean'],
|
||||
'rules.*.conditions' => ['required', 'array', 'min:1', 'max:30'],
|
||||
'rules.*.conditions.*.field' => ['required', Rule::in($fields)],
|
||||
'rules.*.conditions.*.operator' => ['required', Rule::in(array_keys(self::OPERATORS))],
|
||||
'rules.*.conditions.*.value' => ['nullable', 'string', 'max:2000'],
|
||||
'rules.*.event_type' => ['required', Rule::in(array_keys(self::TYPES))],
|
||||
'rules.*.origin' => ['required', Rule::in($origins)],
|
||||
'rules.*.representation' => ['required', Rule::in(array_keys(self::REPRESENTATIONS))],
|
||||
'rules.*.extractions' => ['array', 'max:20'],
|
||||
'rules.*.extractions.*.field' => ['required', Rule::in($fields)],
|
||||
'rules.*.extractions.*.target' => ['required', Rule::in(array_keys(self::TARGETS))],
|
||||
'rules.*.extractions.*.method' => ['required', Rule::in(array_keys(self::EXTRACTIONS))],
|
||||
'rules.*.extractions.*.start' => ['nullable', 'string', 'max:500'],
|
||||
'rules.*.extractions.*.end' => ['nullable', 'string', 'max:500'],
|
||||
])->validate();
|
||||
foreach ($rules as $index => $rule) {
|
||||
foreach ($rule['extractions'] ?? [] as $extraction) {
|
||||
if ((in_array($extraction['method'], ['after', 'between'], true) && blank($extraction['start'] ?? null))
|
||||
|| (in_array($extraction['method'], ['before', 'between'], true) && blank($extraction['end'] ?? null))) {
|
||||
throw ValidationException::withMessages(['rules.'.$index.'.extractions' => 'Für die Textextraktion die benötigten Anfangs- und Endtexte angeben.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($rules);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Throwable;
|
||||
@@ -17,11 +18,31 @@ class MailboxReader
|
||||
{
|
||||
public const LAST_SUCCESS_KEY = 'mailbox:last_success_at';
|
||||
|
||||
/**
|
||||
* The state of one landlord's mailbox. Without the landlord in the key, two landlords would report
|
||||
* each other's last success and alerts would be raised for the wrong one.
|
||||
*/
|
||||
public static function key(string $base): string
|
||||
{
|
||||
return $base.':'.(Settings::tenant()?->id ?? 0);
|
||||
}
|
||||
|
||||
public const LAST_ERROR_KEY = 'mailbox:last_error';
|
||||
|
||||
/**
|
||||
* The mailbox of the current landlord. Each landlord reads their own; an empty one means the fast path
|
||||
* is off for them.
|
||||
*
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public static function configuration(): ?array
|
||||
{
|
||||
return Settings::tenant()?->mailbox();
|
||||
}
|
||||
|
||||
public static function isConfigured(): bool
|
||||
{
|
||||
return filled(config('fewo.mailbox.host')) && filled(config('fewo.mailbox.username'));
|
||||
return self::configuration() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -32,7 +53,11 @@ public static function isConfigured(): bool
|
||||
*/
|
||||
public function fetch(array $senders): array
|
||||
{
|
||||
$config = config('fewo.mailbox');
|
||||
$config = self::configuration();
|
||||
|
||||
if ($config === null) {
|
||||
throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.');
|
||||
}
|
||||
|
||||
try {
|
||||
$client = (new ClientManager)->make([
|
||||
@@ -62,13 +87,13 @@ public function fetch(array $senders): array
|
||||
|
||||
$client->disconnect();
|
||||
} catch (Throwable $exception) {
|
||||
Cache::forever(self::LAST_ERROR_KEY, $exception->getMessage());
|
||||
Cache::forever(self::key(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);
|
||||
Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String());
|
||||
Cache::forget(self::key(self::LAST_ERROR_KEY));
|
||||
|
||||
return $mails;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\ImageWorlds\ImageWorldManifest;
|
||||
use App\ImageWorlds\ImageWorldRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('image-worlds:check')]
|
||||
#[Description('Check every picture world: does each slot in the manifest have its SVG file?')]
|
||||
class CheckImageWorlds extends Command
|
||||
{
|
||||
/**
|
||||
* A slot without a file is not an error at runtime – templates simply get no decoration. That makes it
|
||||
* easy to miss, so it is reported here instead of silently leaving a page bare.
|
||||
*/
|
||||
public function handle(ImageWorldRegistry $registry): int
|
||||
{
|
||||
$worlds = $registry->all();
|
||||
|
||||
if ($worlds === []) {
|
||||
$this->warn('Keine Bildwelt gefunden.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$incomplete = 0;
|
||||
|
||||
foreach ($worlds as $world) {
|
||||
$missing = $world->missingFiles();
|
||||
|
||||
if ($missing === []) {
|
||||
$this->info(sprintf('✓ %s (%s): %d Plätze', $world->name, $world->key, count($world->slots)));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$incomplete++;
|
||||
$this->error(sprintf('✗ %s (%s): ohne Datei – %s', $world->name, $world->key, implode(', ', $missing)));
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->line($this->slotOverview($worlds));
|
||||
|
||||
return $incomplete === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which slot is filled by which world – so a template author sees what they may rely on.
|
||||
*
|
||||
* @param array<string, ImageWorldManifest> $worlds
|
||||
*/
|
||||
private function slotOverview(array $worlds): string
|
||||
{
|
||||
$slots = [];
|
||||
|
||||
foreach ($worlds as $world) {
|
||||
foreach (array_keys($world->slots) as $slot) {
|
||||
$slots[$slot][] = $world->key;
|
||||
}
|
||||
}
|
||||
|
||||
ksort($slots);
|
||||
|
||||
return collect($slots)
|
||||
->map(fn (array $keys, string $slot): string => sprintf(' %-18s %s', $slot, implode(', ', $keys)))
|
||||
->implode(PHP_EOL);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
@@ -13,7 +15,7 @@
|
||||
use function Laravel\Prompts\select;
|
||||
use function Laravel\Prompts\text;
|
||||
|
||||
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content}')]
|
||||
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content} {--tenant= : Kurzname des Mandanten}')]
|
||||
#[Description('Create an admin panel account (the password is entered interactively and never passed as an argument)')]
|
||||
class CreateUser extends Command
|
||||
{
|
||||
@@ -22,6 +24,12 @@ class CreateUser extends Command
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$tenant = $this->resolveTenant();
|
||||
|
||||
if ($tenant === false) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$email = $this->argument('email') ?? text('E-Mail-Adresse', required: true, validate: ['email' => 'email']);
|
||||
$email = mb_strtolower(trim($email));
|
||||
|
||||
@@ -51,7 +59,12 @@ public function handle(): int
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
|
||||
$user = User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
|
||||
|
||||
if ($tenant instanceof Tenant) {
|
||||
app(TenantContext::class)->set($tenant);
|
||||
$user->attachCurrentRole($tenant);
|
||||
}
|
||||
|
||||
$this->info("Benutzer {$email} ({$role->getLabel()}) angelegt.");
|
||||
|
||||
@@ -59,4 +72,35 @@ public function handle(): int
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* One landlord is used automatically. Several landlords need --tenant. None is allowed:
|
||||
* the account exists and is attached later.
|
||||
*/
|
||||
private function resolveTenant(): Tenant|false|null
|
||||
{
|
||||
$slug = $this->option('tenant');
|
||||
|
||||
if (is_string($slug) && $slug !== '') {
|
||||
$tenant = Tenant::query()->where('slug', $slug)->first();
|
||||
|
||||
if ($tenant === null) {
|
||||
$this->error("Kein Mandant mit dem Kurznamen {$slug}.");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $tenant;
|
||||
}
|
||||
|
||||
$count = Tenant::query()->count();
|
||||
|
||||
if ($count > 1) {
|
||||
$this->error('Es gibt mehrere Mandanten. Bitte --tenant=kurzname angeben.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $count === 1 ? Tenant::query()->first() : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantArchive;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
use function Laravel\Prompts\confirm;
|
||||
|
||||
#[Signature('tenants:delete {slug : Kurzname des Mandanten} {--keep-export : Nicht vorher exportieren} {--force : Ohne Rückfrage}')]
|
||||
#[Description('Export a landlord and then remove them with all their data and files')]
|
||||
class DeleteTenant extends Command
|
||||
{
|
||||
/**
|
||||
* Exports first, unless told otherwise: a deletion that cannot be undone should leave something behind.
|
||||
*/
|
||||
public function handle(TenantArchive $archive): int
|
||||
{
|
||||
$tenant = Tenant::query()->where('slug', $this->argument('slug'))->first();
|
||||
|
||||
if ($tenant === null) {
|
||||
$this->error('Kein Mandant mit dem Kurznamen '.$this->argument('slug').'.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (! $this->option('keep-export')) {
|
||||
$path = $archive->export($tenant, storage_path('app/private/exports'));
|
||||
$this->info('Export geschrieben: '.$path);
|
||||
}
|
||||
|
||||
if (! $this->option('force') && ! confirm('Mandant '.$tenant->name.' mit allen Daten und Dateien endgültig löschen?', default: false)) {
|
||||
$this->line('Abgebrochen.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$removed = $archive->delete($tenant);
|
||||
|
||||
foreach ($removed as $table => $count) {
|
||||
$this->line(sprintf(' %-22s %d', $table, $count));
|
||||
}
|
||||
|
||||
$this->info('Mandant '.$tenant->name.' gelöscht.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -3,22 +3,26 @@
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\ExpireReservations;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantRunner;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('bookings:expire-holds')]
|
||||
#[Description('Mark reservations with an elapsed hold time as expired and notify the landlord')]
|
||||
#[Description('Mark reservations with an elapsed hold time as expired and notify the landlord – once per landlord')]
|
||||
class ExpireReservationHolds extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ExpireReservations $expireReservations): int
|
||||
public function handle(ExpireReservations $expireReservations, TenantRunner $runner): int
|
||||
{
|
||||
$count = $expireReservations->handle();
|
||||
$runner->each(function (Tenant $tenant) use ($expireReservations): void {
|
||||
$count = $expireReservations->handle();
|
||||
|
||||
$this->info("{$count} Vormerkung(en) abgelaufen.");
|
||||
$this->info("{$tenant->name}: {$count} Vormerkung(en) abgelaufen.");
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantArchive;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('tenants:export {slug : Kurzname des Mandanten} {--to= : Zielordner, sonst storage/app/private/exports}')]
|
||||
#[Description('Write all data and files of one landlord into a zip archive')]
|
||||
class ExportTenant extends Command
|
||||
{
|
||||
public function handle(TenantArchive $archive): int
|
||||
{
|
||||
$tenant = Tenant::query()->where('slug', $this->argument('slug'))->first();
|
||||
|
||||
if ($tenant === null) {
|
||||
$this->error('Kein Mandant mit dem Kurznamen '.$this->argument('slug').'.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$path = $archive->export($tenant, (string) ($this->option('to') ?: storage_path('app/private/exports')));
|
||||
|
||||
$this->info('Export von '.$tenant->name.': '.$path.' ('.$this->size($path).')');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function size(string $path): string
|
||||
{
|
||||
$bytes = (int) (filesize($path) ?: 0);
|
||||
|
||||
return $bytes > 1048576
|
||||
? round($bytes / 1048576, 1).' MB'
|
||||
: round($bytes / 1024).' KB';
|
||||
}
|
||||
}
|
||||
@@ -5,24 +5,40 @@
|
||||
use App\Actions\ProcessPortalMail;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
use App\Tenancy\TenantRunner;
|
||||
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')]
|
||||
#[Description('Read booking notifications of the portals from each landlord\'s mailbox and block recognised bookings immediately')]
|
||||
class FetchPortalMail extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
* Execute the console command. Every landlord has their own mailbox, so every landlord gets their own
|
||||
* run – one landlord's credentials are never used to read another one's mail.
|
||||
*/
|
||||
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail): int
|
||||
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail, TenantRunner $runner): int
|
||||
{
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
$this->line('Kein Postfach konfiguriert (FEWO_MAILBOX_HOST).');
|
||||
$runner->each(fn (Tenant $tenant) => $this->fetchForCurrentLandlord($reader, $processPortalMail, $tenant));
|
||||
|
||||
return self::SUCCESS;
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function fetchForCurrentLandlord(MailboxReader $reader, ProcessPortalMail $processPortalMail, Tenant $tenant): void
|
||||
{
|
||||
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $tenant)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
$this->line("{$tenant->name}: kein Postfach hinterlegt.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$senders = Channel::query()->active()->get()
|
||||
@@ -32,25 +48,23 @@ public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMa
|
||||
->all();
|
||||
|
||||
if ($senders === []) {
|
||||
$this->line('Für kein Portal sind Absender hinterlegt.');
|
||||
$this->line("{$tenant->name}: für kein Portal sind Absender hinterlegt.");
|
||||
|
||||
return self::SUCCESS;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$mails = $reader->fetch($senders);
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
$this->error("{$tenant->name}: {$exception->getMessage()}");
|
||||
|
||||
return self::FAILURE;
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($mails as $mail) {
|
||||
if ($record = $processPortalMail->handle($mail)) {
|
||||
$this->info("{$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
|
||||
$this->info("{$tenant->name} – {$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Site;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('sites:import-stommer-brand {site : ID der bestehenden Stommer-Website}')]
|
||||
#[Description('Copy the legacy Stommer brand into its own website without replacing uploaded graphics')]
|
||||
class ImportSiteBrand extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$site = Site::withoutGlobalScope('tenant')->with('tenant')->find($this->argument('site'));
|
||||
|
||||
if ($site === null || $site->tenant?->slug !== 'stommer') {
|
||||
$this->error('Nur die bestehende Stommer-Website darf diese Marke übernehmen.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$seebad = $site->theme === 'seebad';
|
||||
$sources = [
|
||||
Site::BRAND_LOGO => $seebad ? resource_path('themes/seebad/img/logo-bildmarke-720.webp') : public_path('brand/logo.svg'),
|
||||
Site::BRAND_FAVICON => $seebad ? resource_path('themes/seebad/img/favicon.svg') : public_path('brand/favicon.svg'),
|
||||
Site::BRAND_DOCUMENT_LOGO => public_path('brand/logo-600.png'),
|
||||
];
|
||||
|
||||
foreach ($sources as $collection => $path) {
|
||||
if (! $site->hasMedia($collection) && ! is_file($path)) {
|
||||
$this->error('Markenquelle fehlt: '.$path);
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
|
||||
app(TenantContext::class)->run($site->tenant, function () use ($site, $sources): void {
|
||||
foreach ($sources as $collection => $path) {
|
||||
if ($site->hasMedia($collection)) {
|
||||
$this->line($collection.': vorhandene Grafik beibehalten.');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$site->addMedia($path)->preservingOriginal()->toMediaCollection($collection);
|
||||
$this->info($collection.': übernommen.');
|
||||
}
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('users:promote-operator {email : E-Mail-Adresse}')]
|
||||
#[Description('Grant the operator flag. The account keeps its password, two-factor setup and any landlord role.')]
|
||||
class PromoteOperator extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$email = mb_strtolower(trim((string) $this->argument('email')));
|
||||
$user = User::query()->where('email', $email)->first();
|
||||
|
||||
if ($user === null) {
|
||||
$this->error('Kein Benutzer mit dieser E-Mail.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$user->forceFill(['is_operator' => true])->save();
|
||||
|
||||
$this->info("{$email} ist jetzt Betreiber. Eine bestehende Mandanten-Rolle bleibt.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ class SendTestMail extends Command
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$to = (string) ($this->argument('to') ?: config('fewo.notification_email'));
|
||||
$to = (string) ($this->argument('to') ?: Settings::notificationRecipients()[0] ?? config('fewo.owner.email'));
|
||||
$mailer = (string) config('mail.default');
|
||||
$redirect = Settings::mailRedirect();
|
||||
|
||||
@@ -40,7 +40,11 @@ public function handle(): int
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info('Übergeben an den Mailserver – bitte Posteingang (und Spam-Ordner) prüfen.');
|
||||
if ($mailer === 'log') {
|
||||
$this->line('Mail erzeugt, aber nicht zugestellt (Versandweg "log").');
|
||||
} else {
|
||||
$this->info('Übergeben an den Mailserver – bitte Posteingang (und Spam-Ordner) prüfen.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
@@ -4,18 +4,27 @@
|
||||
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Models\Channel;
|
||||
use App\Tenancy\TenantRunner;
|
||||
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')]
|
||||
#[Description('Import the occupations of all active portals (or one) and report conflicts – once per landlord')]
|
||||
class SyncChannels extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
* Execute the console command. Runs per landlord so that conflict mails carry the right sender and
|
||||
* reach the right people.
|
||||
*/
|
||||
public function handle(SyncChannel $syncChannel): int
|
||||
public function handle(SyncChannel $syncChannel, TenantRunner $runner): int
|
||||
{
|
||||
$runner->each(fn () => $this->syncCurrentLandlord($syncChannel));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function syncCurrentLandlord(SyncChannel $syncChannel): void
|
||||
{
|
||||
$channels = Channel::query()->active()
|
||||
->when($this->argument('channel'), fn ($query, $id) => $query->whereKey($id))
|
||||
@@ -29,7 +38,5 @@ public function handle(SyncChannel $syncChannel): int
|
||||
? $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;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Documents;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Site;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
@@ -18,11 +19,20 @@ class RentalContract
|
||||
public function generate(Booking $booking, bool $draft = false): string
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
$path = $draft
|
||||
$filename = $draft
|
||||
? "contracts/Angebot-{$booking->reference}-v{$booking->offer_version}.pdf"
|
||||
: "contracts/Mietvertrag-{$booking->reference}.pdf";
|
||||
$path = "contracts/tenants/{$booking->tenant_id}/bookings/{$booking->id}/".basename($filename);
|
||||
|
||||
Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', ['booking' => $booking, 'draft' => $draft])->setPaper('a4')->output());
|
||||
// The logo is embedded as a file: the PDF is rendered on the server and must not depend on
|
||||
// fetching anything over the network. Each website has its own (A14).
|
||||
$logo = $booking->website()?->brandPath(Site::BRAND_DOCUMENT_LOGO);
|
||||
|
||||
Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', [
|
||||
'booking' => $booking,
|
||||
'draft' => $draft,
|
||||
'logo' => $logo,
|
||||
])->setPaper('a4')->output());
|
||||
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path]);
|
||||
|
||||
return $path;
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use App\Filament\Pages\OccupancyCalendar;
|
||||
use App\Filament\Pages\PricesAndOffers;
|
||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use App\Filament\Resources\Guests\GuestResource;
|
||||
use App\Filament\Resources\Photos\PhotoResource;
|
||||
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
|
||||
use App\Filament\Resources\Reviews\ReviewResource;
|
||||
use Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
@@ -26,11 +29,15 @@ enum AdminMode: string implements HasDescription, HasLabel
|
||||
* @var list<class-string>
|
||||
*/
|
||||
public const SIMPLE_NAVIGATION = [
|
||||
OccupancyCalendar::class,
|
||||
InboxMessageResource::class,
|
||||
BookingResource::class,
|
||||
PortalOccupationResource::class,
|
||||
BlockedPeriodResource::class,
|
||||
PricesAndOffers::class,
|
||||
GuestResource::class,
|
||||
ChannelTaskResource::class,
|
||||
ChannelResource::class,
|
||||
ReviewResource::class,
|
||||
PhotoResource::class,
|
||||
];
|
||||
@@ -46,8 +53,8 @@ public function getLabel(): string
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Simple => 'Das Tägliche: Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Portal-Aufgaben, Bewertungen, Fotos',
|
||||
self::Expert => 'Alle Einstellungen: Preise, Angebote, Portale, Webseite, System',
|
||||
self::Simple => 'Das Tägliche: Postfach, Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Kalenderabgleich (iCal), Portal-Aufgaben, Bewertungen, Fotos',
|
||||
self::Expert => 'Alle Einstellungen: Preise, Angebote, Kalenderabgleich (iCal), Webseite, System',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum BlockedPeriodPurpose: string implements HasLabel
|
||||
{
|
||||
case OwnUse = 'own_use';
|
||||
case Maintenance = 'maintenance';
|
||||
case Other = 'other';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::OwnUse => 'Eigenbelegung',
|
||||
self::Maintenance => 'Wartung / Renovierung',
|
||||
self::Other => 'Sonstige Sperre',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelBookingModel: string implements HasLabel
|
||||
{
|
||||
case Inquiry = 'inquiry';
|
||||
case PortalBooking = 'portal_booking';
|
||||
case Mixed = 'mixed';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Inquiry => 'Vermittlung / Anfrage',
|
||||
self::PortalBooking => 'Portalbuchung',
|
||||
self::Mixed => 'Gemischt',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelEchoBehavior: string implements HasLabel
|
||||
{
|
||||
case Unverified = 'unverified';
|
||||
case NoReexport = 'no_reexport';
|
||||
case Reexports = 'reexports';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Unverified => 'Noch ungeprüft',
|
||||
self::NoReexport => 'Im geprüften Fall keine Weitergabe importierter Ereignisse',
|
||||
self::Reexports => 'Gibt importierte Ereignisse weiter – neue Belegungen erst klären',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelExportMode: string implements HasLabel
|
||||
{
|
||||
case Test = 'test';
|
||||
case Regular = 'regular';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Test => 'Testbetrieb: nur eigene Belegungen',
|
||||
self::Regular => 'Regulär: alle übrigen Kanäle einbeziehen',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelStatus: string implements HasLabel
|
||||
{
|
||||
case Setup = 'setup';
|
||||
case Active = 'active';
|
||||
case Paused = 'paused';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Setup => 'Noch nicht eingerichtet',
|
||||
self::Active => 'Aktiv',
|
||||
self::Paused => 'Pausiert',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* The parts of the daily/weekly summary a landlord can choose (System › Betrieb › Benachrichtigungen).
|
||||
*/
|
||||
enum DigestSection: string implements HasDescription, HasLabel
|
||||
{
|
||||
case Inbox = 'inbox';
|
||||
case Requests = 'requests';
|
||||
case News = 'news';
|
||||
case Stays = 'stays';
|
||||
case Payments = 'payments';
|
||||
case Portals = 'portals';
|
||||
case Reviews = 'reviews';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Inbox => 'Postfach',
|
||||
self::Requests => 'Offene Anfragen und Angebote',
|
||||
self::News => 'Neu seit der letzten Übersicht',
|
||||
self::Stays => 'An- und Abreisen',
|
||||
self::Payments => 'Überfällige Zahlungen',
|
||||
self::Portals => 'Portale: Aufgaben und Klärungsfälle',
|
||||
self::Reviews => 'Bewertungen zur Freigabe',
|
||||
};
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Inbox => 'Ungelesene Meldungen, z. B. mögliche Doppelbuchungen',
|
||||
self::Requests => 'Anfragen und Angebote, die auf Sie oder den Gast warten, mit Frist',
|
||||
self::News => 'Neue Anfragen, Buchungen, Stornierungen und Portalbuchungen',
|
||||
self::Stays => 'Heute und morgen, in der Wochenübersicht die nächsten 7 Tage',
|
||||
self::Payments => 'Anzahlungen und Restzahlungen nach Fälligkeit',
|
||||
self::Portals => 'Offene Portal-Aufgaben, zu prüfende Portal-Mails und Kalendereinträge, Abgleichsfehler',
|
||||
self::Reviews => 'Neue Bewertungen, die noch nicht freigegeben sind',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string>|null $values stored choice; null = everything
|
||||
* @return list<self>
|
||||
*/
|
||||
public static function chosen(?array $values): array
|
||||
{
|
||||
return $values === null ? self::cases() : array_values(array_filter(self::cases(), fn (self $section): bool => in_array($section->value, $values, true)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* What an inbox message is about.
|
||||
*/
|
||||
enum InboxMessageKind: string implements HasColor, HasLabel
|
||||
{
|
||||
case ChannelConflict = 'channel_conflict';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::ChannelConflict => 'Mögliche Doppelbuchung',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::ChannelConflict => 'danger',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum OccupationKind: string implements HasColor, HasLabel
|
||||
{
|
||||
case Reservation = 'reservation';
|
||||
case Block = 'block';
|
||||
case Unknown = 'unknown';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Reservation => 'Portalreservierung',
|
||||
self::Block => 'Sperrzeit',
|
||||
self::Unknown => 'Ungeklärte Belegung',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Reservation => 'info',
|
||||
self::Block => 'gray',
|
||||
self::Unknown => 'warning',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* What a role may do inside the current landlord. A new role is a new case on UserRole plus a list here.
|
||||
*/
|
||||
enum Permission: string
|
||||
{
|
||||
case Bookings = 'bookings';
|
||||
case Properties = 'properties';
|
||||
case Guests = 'guests';
|
||||
case Reviews = 'reviews';
|
||||
case Channels = 'channels';
|
||||
case Content = 'content';
|
||||
case Users = 'users';
|
||||
case Settings = 'settings';
|
||||
}
|
||||
@@ -9,6 +9,8 @@ enum PhotoCategory: string implements HasLabel
|
||||
case Apartment = 'apartment';
|
||||
case Outdoor = 'outdoor';
|
||||
case Area = 'area';
|
||||
/** Floor plans and drawings: chosen explicitly (e.g. for the interactive floor plan), never shown in galleries. */
|
||||
case Plan = 'plan';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
@@ -16,6 +18,17 @@ public function getLabel(): string
|
||||
self::Apartment => 'Wohnung',
|
||||
self::Outdoor => 'Terrasse & Garten',
|
||||
self::Area => 'Kühlungsborn & Umgebung',
|
||||
self::Plan => 'Grundriss & Pläne',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Categories a gallery or an automatic photo may show.
|
||||
*
|
||||
* @return list<self>
|
||||
*/
|
||||
public static function forGalleries(): array
|
||||
{
|
||||
return array_values(array_filter(self::cases(), fn (self $category): bool => $category !== self::Plan));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* Services the operator unlocks per landlord. `isWired()` says whether the application really asks before
|
||||
* it acts – a service that nothing asks for must not be offered as a switch, because switching it would
|
||||
* promise something that does not happen.
|
||||
*/
|
||||
enum TenantServiceKey: string
|
||||
{
|
||||
case PortalSync = 'portal_sync';
|
||||
case PortalMail = 'portal_mail';
|
||||
case AiOffers = 'ai_offers';
|
||||
case AiMarketing = 'ai_marketing';
|
||||
case AiGuestMail = 'ai_guest_mail';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::PortalSync => 'Portal-Abgleich (iCal)',
|
||||
self::PortalMail => 'Portal-Postfach (Schnellweg)',
|
||||
self::AiOffers => 'KI: Angebotsentwürfe',
|
||||
self::AiMarketing => 'KI: Vermarktungsassistent',
|
||||
self::AiGuestMail => 'KI: Gästekommunikation',
|
||||
};
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::PortalSync => 'Belegungen der Portale über iCal einlesen und den eigenen Kalender als Feed anbieten.',
|
||||
self::PortalMail => 'Buchungsmails der Portale aus dem Postfach lesen und Termine sofort sperren.',
|
||||
self::AiOffers, self::AiMarketing, self::AiGuestMail => 'Noch nicht gebaut.',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the application asks this switch before it acts. Only wired services are offered for switching.
|
||||
*/
|
||||
public function isWired(): bool
|
||||
{
|
||||
return match ($this) {
|
||||
self::PortalSync, self::PortalMail => true,
|
||||
self::AiOffers, self::AiMarketing, self::AiGuestMail => false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What applies to a landlord the operator has not decided about yet. The portal services were part of
|
||||
* the product before there were landlords, so switching tenancy on must not silently stop them.
|
||||
*/
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return $this->isWired();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the landlord's own API key is of any use. Nothing calls out yet, so no service has one.
|
||||
*/
|
||||
public function usesApiKey(): bool
|
||||
{
|
||||
return match ($this) {
|
||||
self::AiOffers, self::AiMarketing, self::AiGuestMail => true,
|
||||
self::PortalSync, self::PortalMail => false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<self>
|
||||
*/
|
||||
public static function wired(): array
|
||||
{
|
||||
return array_values(array_filter(self::cases(), fn (self $service): bool => $service->isWired()));
|
||||
}
|
||||
}
|
||||
+30
-2
@@ -14,7 +14,7 @@ enum UserRole: string implements HasDescription, HasLabel
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Admin => 'Administrator',
|
||||
self::Admin => 'Mandanten-Administrator',
|
||||
self::Rentals => 'Vermietung',
|
||||
self::Content => 'Inhalte',
|
||||
};
|
||||
@@ -23,9 +23,37 @@ public function getLabel(): string
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Admin => 'Alles, inklusive Benutzerverwaltung',
|
||||
self::Admin => 'Alles im eigenen Mandanten, inklusive Benutzerverwaltung',
|
||||
self::Rentals => 'Buchungen, Gäste, Preise, Angebote und Bewertungen',
|
||||
self::Content => 'Bilder, Texte, FAQ, Hinweise und Bewertungen',
|
||||
};
|
||||
}
|
||||
|
||||
public function grants(Permission $permission): bool
|
||||
{
|
||||
return in_array($permission, $this->permissions(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Abilities inside the current landlord. The operator is not a role here.
|
||||
*
|
||||
* @return list<Permission>
|
||||
*/
|
||||
public function permissions(): array
|
||||
{
|
||||
return match ($this) {
|
||||
self::Admin => Permission::cases(),
|
||||
self::Rentals => [
|
||||
Permission::Bookings,
|
||||
Permission::Properties,
|
||||
Permission::Guests,
|
||||
Permission::Reviews,
|
||||
Permission::Channels,
|
||||
],
|
||||
self::Content => [
|
||||
Permission::Content,
|
||||
Permission::Reviews,
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Actions;
|
||||
|
||||
use App\Actions\AssignOccupationGuest;
|
||||
use App\Enums\OccupationKind;
|
||||
use App\Filament\Resources\Guests\Schemas\GuestForm;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Guest;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
|
||||
class AssignGuestAction
|
||||
{
|
||||
public static function make(): Action
|
||||
{
|
||||
return Action::make('assignGuest')->label('Gast zuordnen')
|
||||
->modalWidth('3xl')
|
||||
->visible(fn (Booking|BlockedPeriod $record): bool => auth()->user()?->can('update', $record)
|
||||
&& ($record instanceof Booking || (! $record->trashed() && ! $record->is_representation && $record->occupationKind() === OccupationKind::Reservation)))
|
||||
->authorize(fn (Booking|BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false)
|
||||
->modalDescription('Einen vorhandenen Gast persönlich auswählen oder einen neuen Gast anlegen. Ein Namensfragment ist kein Identitätsnachweis. Die Zuordnung versendet keine Nachricht und ändert keine Belegungszeiträume.')
|
||||
->fillForm(fn (Booking|BlockedPeriod $record): array => [
|
||||
'mode' => 'existing', 'guest_id' => $record->guest_id, 'country' => 'DE',
|
||||
'first_name' => $record instanceof BlockedPeriod ? ($record->ical_interpretation['fields']['guest_first_name'] ?? '') : '',
|
||||
])
|
||||
->schema([
|
||||
Select::make('mode')->label('Zuordnung')->options(['existing' => 'Vorhandenen Gast auswählen', 'new' => 'Neuen Gast anlegen'])->required()->live(),
|
||||
Select::make('guest_id')->label('Gast')->searchable()
|
||||
->getSearchResultsUsing(fn (string $search): array => Guest::query()->whereNull('anonymized_at')
|
||||
->where(fn ($query) => $query->where('first_name', 'like', '%'.$search.'%')->orWhere('last_name', 'like', '%'.$search.'%')->orWhere('email', 'like', '%'.$search.'%'))
|
||||
->orderBy('last_name')->orderBy('id')->limit(50)->get()->mapWithKeys(fn (Guest $guest): array => [$guest->id => $guest->full_name.($guest->email ? ' · '.$guest->email : ' · E-Mail unbekannt')])->all())
|
||||
->getOptionLabelUsing(fn ($value): ?string => Guest::find($value)?->full_name)
|
||||
->visible(fn (Get $get): bool => $get('mode') === 'existing')->required(fn (Get $get): bool => $get('mode') === 'existing'),
|
||||
Section::make('Kontakt & Adresse')->columns(2)->visible(fn (Get $get): bool => $get('mode') === 'new')
|
||||
->schema(GuestForm::contactFields()),
|
||||
Section::make('Notizen & Markierungen')->visible(fn (Get $get): bool => $get('mode') === 'new')
|
||||
->schema(GuestForm::personalFields()),
|
||||
])
|
||||
->action(function (Booking|BlockedPeriod $record, array $data, AssignOccupationGuest $assign): void {
|
||||
$assign->handle($record, $data['mode'] === 'existing' ? (int) $data['guest_id'] : null, $data);
|
||||
$record->refresh()->load('guest');
|
||||
Notification::make()->title('Gast zugeordnet')->success()->send();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Concerns;
|
||||
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
|
||||
/**
|
||||
* Limits a resource list to the apartment chosen in the admin menu (CurrentProperty).
|
||||
* Records stay reachable by URL; opening one switches to its apartment (SelectsRecordProperty).
|
||||
*/
|
||||
trait ListsCurrentProperty
|
||||
{
|
||||
protected function getTableQuery(): Builder|Relation|null
|
||||
{
|
||||
$query = parent::getTableQuery();
|
||||
$property = app(CurrentProperty::class)->get();
|
||||
|
||||
return $query instanceof Builder && $property !== null ? $this->scopeToProperty($query, $property) : $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Model> $query
|
||||
* @return Builder<Model>
|
||||
*/
|
||||
protected function scopeToProperty(Builder $query, Property $property): Builder
|
||||
{
|
||||
return $query->where($query->qualifyColumn('property_id'), $property->id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Concerns;
|
||||
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use Closure;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Opening a record of another apartment (e.g. from a notification e-mail) switches the admin to that apartment,
|
||||
* so the menu always shows the apartment the open record belongs to.
|
||||
*/
|
||||
trait SelectsRecordProperty
|
||||
{
|
||||
public static function resolveRecordRouteBinding(int|string $key, ?Closure $modifyQuery = null): ?Model
|
||||
{
|
||||
$record = parent::resolveRecordRouteBinding($key, $modifyQuery);
|
||||
$propertyId = $record !== null ? static::recordPropertyId($record) : null;
|
||||
|
||||
if ($propertyId !== null && $propertyId !== app(CurrentProperty::class)->id() && ($property = Property::query()->find($propertyId))) {
|
||||
app(CurrentProperty::class)->select($property);
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
public static function recordPropertyId(Model $record): ?int
|
||||
{
|
||||
$id = $record->getAttribute('property_id');
|
||||
|
||||
return $id !== null ? (int) $id : null;
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,8 @@ public static function optionLabel(Photo $photo): string
|
||||
? '<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>';
|
||||
$seasons = $photo->appearanceNames() === [] ? '' : ' <em style="opacity:.75">· nur '.e(implode(', ', $photo->appearanceNames())).'</em>';
|
||||
|
||||
return '<span style="display:flex;align-items:center;gap:.75rem">'.$image.'<span>'.e($photo->alt_text).$hidden.'</span></span>';
|
||||
return '<span style="display:flex;align-items:center;gap:.75rem">'.$image.'<span>'.e($photo->alt_text).$seasons.$hidden.'</span></span>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
|
||||
/**
|
||||
* The service switches of the tenant form. They live in their own table, so the form state is read and
|
||||
* written separately from the landlord's own columns. Only wired services are written – a switch for a
|
||||
* service nothing asks about would promise something that does not happen.
|
||||
*
|
||||
* Holds no Filament hooks; EditsTenantSetup calls these.
|
||||
*/
|
||||
trait EditsTenantServices
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function fillServices(array $data): array
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $data; // creating: there is nothing to read yet
|
||||
}
|
||||
|
||||
$stored = $tenant->services->keyBy('service');
|
||||
|
||||
$data['services'] = collect(TenantServiceKey::wired())
|
||||
->mapWithKeys(fn (TenantServiceKey $service): array => [$service->value => [
|
||||
'is_enabled' => $stored->get($service->value)?->is_enabled ?? $service->enabledByDefault(),
|
||||
]])
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function takeServices(array $data): array
|
||||
{
|
||||
$this->services = is_array($data['services'] ?? null) ? $data['services'] : [];
|
||||
|
||||
unset($data['services']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function saveServices(): void
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (TenantServiceKey::wired() as $service) {
|
||||
$state = $this->services[$service->value] ?? [];
|
||||
|
||||
$tenant->services()->updateOrCreate(
|
||||
['service' => $service->value],
|
||||
['is_enabled' => (bool) ($state['is_enabled'] ?? false)],
|
||||
);
|
||||
}
|
||||
|
||||
$tenant->unsetRelation('services');
|
||||
app(TenantFeatures::class)->forget($tenant);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
/**
|
||||
* Everything the operator sets up for a landlord that does not live in the tenants table itself:
|
||||
* the websites with their entry addresses, and the services that are unlocked.
|
||||
*/
|
||||
trait EditsTenantSetup
|
||||
{
|
||||
use EditsTenantServices;
|
||||
use EditsTenantWebsites;
|
||||
|
||||
/** @var array<string, array<string, mixed>> */
|
||||
public array $services = [];
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
public array $websites = [];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
return $this->fillWebsites($this->fillServices($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
return $this->takeWebsites($this->takeServices($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
return $this->takeWebsites($this->takeServices($data));
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
$this->saveServices();
|
||||
$this->saveWebsites();
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
$this->saveServices();
|
||||
$this->saveWebsites();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Models\SiteDomain;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* The websites of a landlord and the addresses they answer on. These belong to the operator: the webspace
|
||||
* and the hosting are the operator's, and a landlord must not be able to point an address at themselves.
|
||||
*
|
||||
* Wiring a new domain to this directory stays a manual step at the hoster. What is kept here is the other
|
||||
* half: which host belongs to which website, and through it to which landlord.
|
||||
*
|
||||
* Holds no Filament hooks; EditsTenantSetup calls these.
|
||||
*/
|
||||
trait EditsTenantWebsites
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function fillWebsites(array $data): array
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$data['websites'] = $tenant->sites()->withoutGlobalScope('tenant')->with('domains')->get()
|
||||
->map(fn (Site $site): array => [
|
||||
'id' => $site->id,
|
||||
'name' => $site->name,
|
||||
'hosts' => $site->domains->pluck('host')->all(),
|
||||
])
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function takeWebsites(array $data): array
|
||||
{
|
||||
$this->websites = is_array($data['websites'] ?? null) ? array_values($data['websites']) : [];
|
||||
|
||||
$this->normaliseWebsites();
|
||||
|
||||
unset($data['websites']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans the entered addresses and refuses what already belongs elsewhere, before anything is written.
|
||||
*/
|
||||
private function normaliseWebsites(): void
|
||||
{
|
||||
$seen = [];
|
||||
|
||||
foreach ($this->websites as $index => $website) {
|
||||
$hosts = [];
|
||||
|
||||
foreach ((array) ($website['hosts'] ?? []) as $host) {
|
||||
$host = SiteDomain::normalise(is_string($host) ? $host : null);
|
||||
|
||||
if ($host === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($host, $seen, true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'data.websites' => 'Die Adresse '.$host.' ist mehrfach eingetragen.',
|
||||
]);
|
||||
}
|
||||
|
||||
$seen[] = $host;
|
||||
$hosts[] = $host;
|
||||
}
|
||||
|
||||
$this->websites[$index]['hosts'] = $hosts;
|
||||
}
|
||||
|
||||
$this->refuseForeignHosts($seen);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $hosts
|
||||
*/
|
||||
private function refuseForeignHosts(array $hosts): void
|
||||
{
|
||||
$ownIds = collect($this->websites)->pluck('id')->filter()->all();
|
||||
|
||||
$taken = SiteDomain::query()
|
||||
->whereIn('host', $hosts)
|
||||
->whereNotIn('site_id', $ownIds ?: [0])
|
||||
->pluck('host');
|
||||
|
||||
if ($taken->isNotEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'data.websites' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the websites. A website that is new gets an empty home page straight away, because a website
|
||||
* without one answers 404 and the landlord would have no way in.
|
||||
*/
|
||||
private function saveWebsites(): void
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
app(TenantContext::class)->run($tenant, function () use ($tenant): void {
|
||||
$keep = [];
|
||||
|
||||
foreach ($this->websites as $website) {
|
||||
$name = trim((string) ($website['name'] ?? ''));
|
||||
|
||||
if ($name === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hosts = (array) ($website['hosts'] ?? []);
|
||||
$site = $this->siteFor($tenant, $website['id'] ?? null, $name, $hosts);
|
||||
|
||||
$keep[] = $site->id;
|
||||
|
||||
$site->domains()->whereNotIn('host', $hosts ?: [''])->delete();
|
||||
|
||||
foreach ($hosts as $host) {
|
||||
SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]);
|
||||
}
|
||||
}
|
||||
|
||||
$tenant->sites()->whereNotIn('id', $keep ?: [0])->each(fn (Site $site) => $site->delete());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $hosts
|
||||
*/
|
||||
private function siteFor(Tenant $tenant, mixed $id, string $name, array $hosts): Site
|
||||
{
|
||||
$site = $id ? Site::query()->whereKey($id)->first() : null;
|
||||
|
||||
if ($site !== null) {
|
||||
$site->update(['name' => $name, 'domain' => $hosts[0] ?? null]);
|
||||
|
||||
return $site;
|
||||
}
|
||||
|
||||
$site = Site::query()->create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'name' => $name,
|
||||
'domain' => $hosts[0] ?? null,
|
||||
'is_default' => $tenant->sites()->count() === 0,
|
||||
'theme' => config('themes.base'),
|
||||
]);
|
||||
|
||||
Page::query()->create([
|
||||
'site_id' => $site->id,
|
||||
'slug' => Page::HOME,
|
||||
'title' => $name,
|
||||
'sections' => [],
|
||||
'is_published' => true,
|
||||
]);
|
||||
|
||||
return $site;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Pages;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantAccessLog;
|
||||
use App\Tenancy\TenantConfig;
|
||||
use BackedEnum;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* What applies to the whole installation: the limits every landlord is bound by, the delivery path, and
|
||||
* who opened whose admin. These values come from the server's .env and are deliberately not editable here –
|
||||
* they protect the system against the landlords, so a landlord's admin must not be able to reach them.
|
||||
*/
|
||||
class SystemOverview extends Page
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedServerStack;
|
||||
|
||||
protected static ?string $navigationLabel = 'System';
|
||||
|
||||
protected static ?string $title = 'System';
|
||||
|
||||
protected static ?string $slug = 'system';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
protected string $view = 'filament.operator.system-overview';
|
||||
|
||||
/**
|
||||
* The ceilings a landlord may tighten but never exceed.
|
||||
*
|
||||
* @return list<array{label: string, value: string, note: string}>
|
||||
*/
|
||||
public function limits(): array
|
||||
{
|
||||
$config = app(TenantConfig::class);
|
||||
|
||||
$rows = [
|
||||
['Gästedaten löschen nach', 'fewo.guest_retention_years', 'Jahre', 'Ein Mandant kann kürzer löschen, nicht länger aufbewahren.'],
|
||||
['Nicht gebuchte Anfragen löschen nach', 'fewo.retention.inquiry_months', 'Monate', ''],
|
||||
['Portal-Mail-Auszug löschen nach', 'fewo.retention.portal_email_excerpt_days', 'Tage', ''],
|
||||
['Herkunftsangaben löschen nach', 'fewo.retention.attribution_months', 'Monate', ''],
|
||||
['Bot-Schutz: Mindestzeit im Formular', 'fewo.spam.min_seconds', 'Sekunden', 'Ein Mandant kann länger warten lassen, nicht kürzer.'],
|
||||
['Bot-Schutz: Anfragen je IP und Stunde', 'fewo.spam.per_ip_per_hour', '', ''],
|
||||
['Bot-Schutz: Anfragen je E-Mail und Tag', 'fewo.spam.per_email_per_day', '', ''],
|
||||
['Bot-Schutz: offene Anfragen je E-Mail', 'fewo.spam.open_requests_per_email', '', ''],
|
||||
['Bot-Schutz: Links im Text', 'fewo.spam.max_links', '', ''],
|
||||
];
|
||||
|
||||
return array_map(fn (array $row): array => [
|
||||
'label' => $row[0],
|
||||
'value' => trim($config->baselineValue($row[1]).' '.$row[2]),
|
||||
'note' => $row[3],
|
||||
], $rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Values that belong to the whole installation and to no landlord.
|
||||
*
|
||||
* @return list<array{label: string, value: string, note: string}>
|
||||
*/
|
||||
public function global(): array
|
||||
{
|
||||
$redirect = config('fewo.mail_redirect_to');
|
||||
|
||||
return [
|
||||
[
|
||||
'label' => 'Anfragen aller Websites zusammen',
|
||||
'value' => config('fewo.spam.total_per_hour').' je Stunde',
|
||||
'note' => 'Flutgrenze über alle Mandanten. Kein Mandant kann sie anheben.',
|
||||
],
|
||||
[
|
||||
'label' => 'Harte Mail-Umleitung',
|
||||
'value' => filled($redirect) ? (string) $redirect : 'nicht gesetzt',
|
||||
'note' => filled($redirect)
|
||||
? 'FEWO_MAIL_REDIRECT_TO: jede E-Mail dieses Servers geht hierhin, auch bei scharf geschalteten Mandanten.'
|
||||
: 'Ohne Umleitung entscheidet die Betriebsart des jeweiligen Mandanten.',
|
||||
],
|
||||
[
|
||||
'label' => 'Versandweg',
|
||||
'value' => (string) config('mail.default'),
|
||||
'note' => 'SMTP-Zugang und Datenbank sind Infrastruktur und liegen in der .env des Servers.',
|
||||
],
|
||||
[
|
||||
'label' => 'Datenbank-Sicherungen',
|
||||
'value' => config('fewo.backup.keep').' Stück',
|
||||
'note' => 'Eine Sicherung der ganzen Datenbank, über alle Mandanten.',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Tenant>
|
||||
*/
|
||||
public function tenants(): Collection
|
||||
{
|
||||
return Tenant::query()->withCount(['services' => fn ($query) => $query->where('is_enabled', true)])->orderBy('name')->get();
|
||||
}
|
||||
|
||||
public function wiredServiceCount(): int
|
||||
{
|
||||
return count(TenantServiceKey::wired());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, TenantAccessLog>
|
||||
*/
|
||||
public function accessLog(): Collection
|
||||
{
|
||||
return TenantAccessLog::query()->with(['tenant', 'user'])->latest('created_at')->limit(20)->get();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Pages;
|
||||
|
||||
use App\Support\SystemSettings;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Actions;
|
||||
use Filament\Schemas\Components\EmbeddedSchema;
|
||||
use Filament\Schemas\Components\Form;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
|
||||
/**
|
||||
* The settings of the whole installation. They are the baseline every landlord is bound by, and a
|
||||
* landlord's admin never reaches this page.
|
||||
*
|
||||
* Empty means: the value from the server's .env applies again. Database credentials and APP_KEY are not
|
||||
* here and cannot be – they are needed to open the database and to decrypt what is stored in it.
|
||||
*/
|
||||
class SystemSettingsPage extends Page
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsHorizontal;
|
||||
|
||||
protected static ?string $navigationLabel = 'Einstellungen';
|
||||
|
||||
protected static ?string $title = 'Systemweite Einstellungen';
|
||||
|
||||
protected static ?string $slug = 'einstellungen';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
/** @var array<string, mixed> */
|
||||
public array $data = [];
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->form->fill(collect(SystemSettings::EDITABLE)
|
||||
->mapWithKeys(fn (array $definition, string $key): array => [self::field($key) => SystemSettings::get($key)])
|
||||
->all());
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
$sections = collect(SystemSettings::EDITABLE)
|
||||
->groupBy(fn (array $definition): string => $definition[2], preserveKeys: true)
|
||||
->map(fn ($group, string $section) => Section::make($section)
|
||||
->columns(2)
|
||||
->schema($group->keys()->map(fn (string $key) => $this->field_($key))->all()));
|
||||
|
||||
return $schema
|
||||
->statePath('data')
|
||||
->components([
|
||||
Text::make('Leer lassen heißt: der Wert aus der .env des Servers gilt wieder. Datenbank-Zugang und APP_KEY stehen bewusst nicht hier – sie werden gebraucht, um die Datenbank überhaupt zu öffnen und das Gespeicherte zu entschlüsseln.'),
|
||||
...$sections->values()->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
Form::make([EmbeddedSchema::make('form')])
|
||||
->id('form')
|
||||
->livewireSubmitHandler('save')
|
||||
->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
|
||||
SystemSettings::save(collect(SystemSettings::EDITABLE)
|
||||
->mapWithKeys(fn (array $definition, string $key): array => [$key => $data[self::field($key)] ?? null])
|
||||
->all());
|
||||
|
||||
Notification::make()->title('Gespeichert')->success()->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Config keys contain dots, which Filament would read as nesting.
|
||||
*/
|
||||
private static function field(string $key): string
|
||||
{
|
||||
return str_replace('.', '__', $key);
|
||||
}
|
||||
|
||||
private function field_(string $key): TextInput|Select
|
||||
{
|
||||
[$label, $kind, , $help] = SystemSettings::EDITABLE[$key];
|
||||
$name = self::field($key);
|
||||
|
||||
if ($kind === 'mailer') {
|
||||
return Select::make($name)
|
||||
->label($label)
|
||||
->helperText($help)
|
||||
->options(['smtp' => 'SMTP (echter Versand)', 'log' => 'Nur Logdatei (kein Versand)', 'array' => 'Verwerfen (nur für Tests)']);
|
||||
}
|
||||
|
||||
$field = TextInput::make($name)->label($label)->helperText($help);
|
||||
|
||||
return match ($kind) {
|
||||
'int' => $field->numeric()->integer()->minValue(0),
|
||||
'secret' => $field->password()->revealable()->autocomplete(false),
|
||||
default => $field,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Filament\Operator\Tenants\Pages\CreateTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\EditTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\ListTenants;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantAccessLog;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class TenantResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Tenant::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBuildingOffice;
|
||||
|
||||
protected static ?string $modelLabel = 'Mandant';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Mandanten';
|
||||
|
||||
protected static ?string $navigationLabel = 'Mandanten';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
TextInput::make('name')
|
||||
->label('Name')
|
||||
->required()
|
||||
->maxLength(255),
|
||||
TextInput::make('slug')
|
||||
->label('Kurzname')
|
||||
->required()
|
||||
->alphaDash()
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(255),
|
||||
Toggle::make('is_active')
|
||||
->label('Zugang freigeschaltet')
|
||||
->helperText('Ausgeschaltet sehen Besucher statt der Webseite nur den Hinweis unten. Der Betreiber kommt weiter hinein.')
|
||||
->default(true)
|
||||
->live(),
|
||||
Textarea::make('suspended_message')
|
||||
->label('Hinweis bei gesperrtem Zugang')
|
||||
->placeholder('Diese Webseite ist zurzeit nicht erreichbar. Bitte versuchen Sie es später noch einmal.')
|
||||
->helperText('Leer = der Standardtext. Wird mit Status 503 ausgeliefert, damit Suchmaschinen die Seite nicht aus dem Index werfen.')
|
||||
->rows(2)
|
||||
->columnSpanFull(),
|
||||
Section::make('Einsprungsadressen')
|
||||
->description('Unter welchen Adressen dieser Mandant antwortet. Die Adresse muss zusätzlich beim Hoster einmalig auf dieses Verzeichnis gelegt werden – das passiert nicht hier. Ab dem zweiten Mandanten bekommt jede nicht eingetragene Adresse eine Fehlerseite.')
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
Repeater::make('websites')
|
||||
->label('Websites')
|
||||
->addActionLabel('Weitere Website')
|
||||
->defaultItems(1)
|
||||
->itemLabel(fn (array $state): ?string => $state['name'] ?? null)
|
||||
->schema([
|
||||
Hidden::make('id'),
|
||||
TextInput::make('name')
|
||||
->label('Name der Website')
|
||||
->required()
|
||||
->maxLength(120),
|
||||
TagsInput::make('hosts')
|
||||
->label('Adressen')
|
||||
->placeholder('beispiel.de')
|
||||
->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Die erste gilt als Hauptadresse und steht in Links an Gäste.')
|
||||
->nestedRecursiveRules(['string', 'max:190']),
|
||||
]),
|
||||
]),
|
||||
Section::make('Dienste')
|
||||
->description('Was dieser Mandant nutzen darf. Ein gesperrter Dienst verschwindet auch aus seinem Admin – die Rolle eines Benutzers kann das nicht aufwiegen.')
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
...array_map(fn (TenantServiceKey $service): Toggle => Toggle::make('services.'.$service->value.'.is_enabled')
|
||||
->label($service->label())
|
||||
->helperText($service->description()), TenantServiceKey::wired()),
|
||||
Text::make('Noch nicht gebaut und deshalb nicht schaltbar: '.implode(', ', array_map(
|
||||
fn (TenantServiceKey $service): string => $service->label(),
|
||||
array_values(array_filter(TenantServiceKey::cases(), fn (TenantServiceKey $service): bool => ! $service->isWired())),
|
||||
)).'. Diese Dienste erscheinen hier, sobald die Anwendung sie wirklich abfragt; eigene API-Schlüssel gehören dann in den Admin des Mandanten.'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Name')->searchable(),
|
||||
TextColumn::make('slug')->label('Kurzname'),
|
||||
TextColumn::make('services_count')
|
||||
->label('Dienste frei')
|
||||
->counts(['services' => fn (Builder $query): Builder => $query->where('is_enabled', true)])
|
||||
->suffix(' von '.count(TenantServiceKey::wired())),
|
||||
ToggleColumn::make('is_active')->label('Aktiv'),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
Action::make('openAdmin')
|
||||
->label('Im Admin öffnen')
|
||||
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
|
||||
->action(function (Tenant $record) {
|
||||
TenantAccessLog::query()->create([
|
||||
'tenant_id' => $record->id,
|
||||
'user_id' => auth()->id(),
|
||||
]);
|
||||
|
||||
$domain = $record->sites()->withoutGlobalScope('tenant')->whereNotNull('domain')->value('domain');
|
||||
|
||||
return redirect(is_string($domain) && $domain !== '' ? 'https://'.$domain.'/admin' : url('/admin'));
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListTenants::route('/'),
|
||||
'create' => CreateTenant::route('/create'),
|
||||
'edit' => EditTenant::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\Concerns\EditsTenantSetup;
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateTenant extends CreateRecord
|
||||
{
|
||||
use EditsTenantSetup;
|
||||
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\Concerns\EditsTenantSetup;
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditTenant extends EditRecord
|
||||
{
|
||||
use EditsTenantSetup;
|
||||
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
|
||||
class ListTenants extends ListRecords
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()
|
||||
->label('Neuen Mandanten anlegen')
|
||||
->icon(Heroicon::OutlinedPlus),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Availability\OccupancyOverview;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use BackedEnum;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Url;
|
||||
use UnitEnum;
|
||||
|
||||
class OccupancyCalendar extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected string $view = 'filament.pages.occupancy-calendar';
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCalendarDays;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $title = 'Belegungsplan';
|
||||
|
||||
protected static ?string $navigationLabel = 'Belegungsplan';
|
||||
|
||||
protected static ?string $slug = 'belegungsplan';
|
||||
|
||||
protected static ?int $navigationSort = 0;
|
||||
|
||||
#[Url(as: 'monat')]
|
||||
public string $month = '';
|
||||
|
||||
#[Url(as: 'wohnung')]
|
||||
public ?int $propertyId = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return Gate::allows('viewAny', Booking::class);
|
||||
}
|
||||
|
||||
public function getSubheading(): ?string
|
||||
{
|
||||
return app(CurrentProperty::class)->hasChoice() ? Property::query()->find($this->propertyId)?->name : null;
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->month = $this->month ?: now()->format('Y-m');
|
||||
$this->propertyId = app(CurrentProperty::class)->followUrl($this->propertyId);
|
||||
}
|
||||
|
||||
#[Computed]
|
||||
public function calendar(): ?array
|
||||
{
|
||||
Validator::make(['month' => $this->month], ['month' => ['required', 'date_format:Y-m']])->validate();
|
||||
if ($this->propertyId === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return app(OccupancyOverview::class)->calendar(Property::findOrFail($this->propertyId), CarbonImmutable::createFromFormat('!Y-m', $this->month));
|
||||
}
|
||||
|
||||
public function moveMonth(int $direction): void
|
||||
{
|
||||
Validator::make(['month' => $this->month, 'direction' => $direction], ['month' => ['required', 'date_format:Y-m'], 'direction' => ['in:-1,1']])->validate();
|
||||
$this->month = CarbonImmutable::createFromFormat('!Y-m', $this->month)->addMonths($direction)->format('Y-m');
|
||||
unset($this->calendar);
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,23 @@
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Actions\SendDigests;
|
||||
use App\Enums\DigestSection;
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Models\Tenant;
|
||||
use App\Support\Settings;
|
||||
use App\Tenancy\TenantConfig;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\CheckboxList;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Actions;
|
||||
@@ -22,13 +32,36 @@
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Operating mode: test mode sends every e-mail to one test recipient only; switching live delivers to the
|
||||
* real recipients (guests, landlord). Administrators only.
|
||||
* Operating data of the landlord: operating mode (test mode sends every e-mail to one test recipient only;
|
||||
* live delivers to the real recipients), the addresses of the internal communication, the landlord's own
|
||||
* address and bank details, reminders and summaries, and the periods. Administrators only.
|
||||
*/
|
||||
class Operations extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
/** Periods and counters the landlord may set (column => label). Empty means the system default. */
|
||||
private const PERIODS = [
|
||||
'deposit_due_days' => 'Anzahlung fällig nach (Tage)',
|
||||
'review_request_after_days' => 'Bewertungsbitte nach Abreise (Tage)',
|
||||
'guest_retention_years' => 'Gästedaten löschen nach (Jahre)',
|
||||
'retention_inquiry_months' => 'Nicht gebuchte Anfragen löschen nach (Monate)',
|
||||
'retention_portal_email_excerpt_days' => 'Portal-Mail-Auszug löschen nach (Tage)',
|
||||
'retention_attribution_months' => 'Herkunftsangaben löschen nach (Monate)',
|
||||
'spam_min_seconds' => 'Bot-Schutz: Mindestzeit im Formular (Sekunden)',
|
||||
'spam_per_ip_per_hour' => 'Bot-Schutz: Anfragen je IP und Stunde',
|
||||
'spam_per_email_per_day' => 'Bot-Schutz: Anfragen je E-Mail und Tag',
|
||||
'spam_open_requests_per_email' => 'Bot-Schutz: gleichzeitig offene Anfragen je E-Mail',
|
||||
'spam_max_links' => 'Bot-Schutz: erlaubte Links im Text',
|
||||
'channel_stale_after_minutes' => 'Portal-Abgleich gilt als veraltet nach (Minuten)',
|
||||
'channel_task_reminder_after_minutes' => 'Erinnerung an Portal-Aufgaben nach (Minuten)',
|
||||
];
|
||||
|
||||
/** Choices for repeating open findings (days => label). */
|
||||
public const REMINDER_INTERVALS = [0 => 'Nur einmal', 1 => 'Täglich', 2 => 'Alle 2 Tage', 3 => 'Alle 3 Tage', 7 => 'Wöchentlich'];
|
||||
|
||||
public const WEEKDAYS = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag'];
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPower;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||||
@@ -41,7 +74,7 @@ class Operations extends Page
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
/** @var array<string, ?string> */
|
||||
/** @var array<string, mixed> */
|
||||
public array $data = [];
|
||||
|
||||
public static function canAccess(): bool
|
||||
@@ -51,9 +84,38 @@ public static function canAccess(): bool
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$tenant = $this->tenant();
|
||||
|
||||
$this->form->fill([
|
||||
'mode' => Settings::get(Settings::MODE, Settings::MODE_TEST),
|
||||
'test_recipient' => Settings::get(Settings::TEST_RECIPIENT) ?? auth()->user()?->email,
|
||||
'mode' => $tenant->operating_mode ?: Settings::MODE_TEST,
|
||||
'test_recipient' => $tenant->test_recipient ?: auth()->user()?->email,
|
||||
'notification_recipients' => $tenant->notificationRecipients(),
|
||||
'contact_email' => $tenant->contact_email,
|
||||
'sender_name' => $tenant->sender_name,
|
||||
'sender_email' => $tenant->sender_email,
|
||||
'owner_name' => $tenant->owner_name,
|
||||
'owner_street' => $tenant->owner_street,
|
||||
'owner_city' => $tenant->owner_city,
|
||||
'owner_phone' => $tenant->owner_phone,
|
||||
'bank_account_holder' => $tenant->bank_account_holder,
|
||||
'bank_name' => $tenant->bank_name,
|
||||
'bank_iban' => $tenant->bank_iban,
|
||||
'bank_bic' => $tenant->bank_bic,
|
||||
'tax_note' => $tenant->tax_note,
|
||||
'mailbox_host' => $tenant->mailbox_host,
|
||||
'mailbox_port' => $tenant->mailbox_port,
|
||||
'mailbox_username' => $tenant->mailbox_username,
|
||||
'mailbox_password' => $tenant->mailbox_password,
|
||||
'mailbox_encryption' => $tenant->mailbox_encryption,
|
||||
'mailbox_folder' => $tenant->mailbox_folder,
|
||||
'reminder_interval_days' => $tenant->reminder_interval_days,
|
||||
'digest_daily' => $tenant->digest_daily,
|
||||
'digest_weekly' => $tenant->digest_weekly,
|
||||
'digest_weekday' => $tenant->digest_weekday,
|
||||
'digest_hour' => $tenant->digest_hour,
|
||||
'digest_sections' => array_map(fn (DigestSection $section): string => $section->value, DigestSection::chosen($tenant->digest_sections)),
|
||||
'digest_when_empty' => $tenant->digest_when_empty,
|
||||
...$this->periodValues($tenant),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -82,6 +144,117 @@ public function form(Schema $schema): Schema
|
||||
? 'Hinweis: Auf diesem Server ist zusätzlich FEWO_MAIL_REDIRECT_TO='.config('fewo.mail_redirect_to').' gesetzt – diese Umleitung gilt immer, auch wenn hier scharf geschaltet ist.'
|
||||
: ''),
|
||||
]),
|
||||
Section::make('Adressen der internen Kommunikation')
|
||||
->description('Gelten sofort für alle E-Mails, die Webseite und den Mietvertrag. Im Testbetrieb gehen trotzdem alle E-Mails nur an die Testadresse.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TagsInput::make('notification_recipients')
|
||||
->label('Benachrichtigungen an')
|
||||
->helperText('Neue Anfragen, angenommene/abgelehnte Angebote, abgelaufene Fristen, Bewertungen, Portal-Mails und -Aufgaben, Kopie der Zahlungserinnerungen. Mehrere Adressen möglich (Enter nach jeder Adresse).')
|
||||
->placeholder('adresse@beispiel.de')
|
||||
->nestedRecursiveRules(['email'])
|
||||
->required()
|
||||
->columnSpanFull(),
|
||||
TextInput::make('contact_email')
|
||||
->label('Kontakt- und Antwortadresse')
|
||||
->helperText('Steht auf der Webseite und im Mietvertrag; Antworten der Gäste auf unsere E-Mails gehen hierhin.')
|
||||
->email()
|
||||
->required(),
|
||||
TextInput::make('sender_name')
|
||||
->label('Absendername')
|
||||
->required()
|
||||
->maxLength(100),
|
||||
TextInput::make('sender_email')
|
||||
->label('Absenderadresse')
|
||||
->helperText(fn (): string => 'Muss das Postfach sein, mit dem der Server versendet (SMTP-Anmeldung: '.(config('mail.mailers.smtp.username') ?: 'nicht gesetzt').') – sonst lehnt Strato den Versand ab.')
|
||||
->email()
|
||||
->required(),
|
||||
Text::make(fn (Get $get): string => filled(config('mail.mailers.smtp.username')) && filled($get('sender_email')) && strcasecmp((string) $get('sender_email'), (string) config('mail.mailers.smtp.username')) !== 0
|
||||
? '⚠ Die Absenderadresse weicht vom SMTP-Postfach ('.config('mail.mailers.smtp.username').') ab. Strato stellt solche E-Mails in der Regel nicht zu.'
|
||||
: '')
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Vermieterin')
|
||||
->description('Steht in E-Mails, im Angebot, im Mietvertrag und auf der Webseite.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('owner_name')->label('Name')->required()->maxLength(255),
|
||||
TextInput::make('owner_phone')->label('Telefon')->maxLength(50),
|
||||
TextInput::make('owner_street')->label('Straße und Hausnummer')->maxLength(255),
|
||||
TextInput::make('owner_city')->label('PLZ und Ort')->maxLength(255),
|
||||
]),
|
||||
Section::make('Bankverbindung und Steuer')
|
||||
->description('Steht im Mietvertrag und in den Zahlungsaufforderungen. Die Angaben liegen verschlüsselt in der Datenbank.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('bank_account_holder')->label('Kontoinhaber')->maxLength(255),
|
||||
TextInput::make('bank_name')->label('Bank')->maxLength(255),
|
||||
TextInput::make('bank_iban')->label('IBAN')->maxLength(40),
|
||||
TextInput::make('bank_bic')->label('BIC')->maxLength(20),
|
||||
TextInput::make('tax_note')
|
||||
->label('Steuerangabe')
|
||||
->helperText('Zum Beispiel die Steuernummer oder der Hinweis auf die Kleinunternehmerregelung.')
|
||||
->maxLength(255)
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Benachrichtigungen')
|
||||
->description('Wie oft offene Meldungen wiederholt werden und welche Zusammenfassungen Sie per E-Mail erhalten. Empfänger sind die Adressen unter „Benachrichtigungen an“.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
Select::make('reminder_interval_days')
|
||||
->label('Offene Meldungen erneut senden')
|
||||
->helperText('Gilt für mögliche Doppelbuchungen (solange sie im Postfach ungelesen sind und weiter bestehen) und offene Portal-Aufgaben.')
|
||||
->options(self::REMINDER_INTERVALS)
|
||||
->selectablePlaceholder(false)
|
||||
->required()
|
||||
->columnSpanFull(),
|
||||
Toggle::make('digest_daily')->label('Tägliche Zusammenfassung'),
|
||||
Toggle::make('digest_weekly')->label('Wöchentliche Zusammenfassung')->live(),
|
||||
Select::make('digest_hour')
|
||||
->label('Versand ab')
|
||||
->options(collect(range(5, 21))->mapWithKeys(fn (int $hour): array => [$hour => sprintf('%02d:00 Uhr', $hour)])->all())
|
||||
->selectablePlaceholder(false)
|
||||
->required(),
|
||||
Select::make('digest_weekday')
|
||||
->label('Wochentag der Wochenübersicht')
|
||||
->helperText('An diesem Tag kommt nur die Wochenübersicht, nicht zusätzlich die tägliche.')
|
||||
->options(self::WEEKDAYS)
|
||||
->selectablePlaceholder(false)
|
||||
->visible(fn (Get $get): bool => (bool) $get('digest_weekly'))
|
||||
->required(),
|
||||
CheckboxList::make('digest_sections')
|
||||
->label('Inhalt der Zusammenfassung')
|
||||
->options(DigestSection::class)
|
||||
->descriptions(collect(DigestSection::cases())->mapWithKeys(fn (DigestSection $section): array => [$section->value => $section->getDescription()])->all())
|
||||
->columns(2)
|
||||
->required()
|
||||
->columnSpanFull(),
|
||||
Toggle::make('digest_when_empty')
|
||||
->label('Auch senden, wenn nichts ansteht')
|
||||
->helperText('Sonst entfällt die Zusammenfassung an Tagen ohne offene Punkte.')
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Portal-Postfach')
|
||||
->description('Aus diesem Postfach werden die Buchungsmails der Portale gelesen, damit ein Termin sofort gesperrt wird. Leerer Server = ausgeschaltet. Das Passwort liegt verschlüsselt in der Datenbank.')
|
||||
->columns(2)
|
||||
->collapsed()
|
||||
->visible(fn (): bool => app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail))
|
||||
->schema([
|
||||
TextInput::make('mailbox_host')->label('IMAP-Server')->maxLength(190),
|
||||
TextInput::make('mailbox_port')->label('Port')->numeric()->integer()->placeholder('993'),
|
||||
TextInput::make('mailbox_username')->label('Benutzer')->maxLength(190),
|
||||
TextInput::make('mailbox_password')->label('Passwort')->password()->revealable()->autocomplete(false)->maxLength(190),
|
||||
Select::make('mailbox_encryption')
|
||||
->label('Verschlüsselung')
|
||||
->options(['ssl' => 'SSL', 'tls' => 'TLS', 'starttls' => 'STARTTLS'])
|
||||
->placeholder('SSL'),
|
||||
TextInput::make('mailbox_folder')->label('Ordner')->placeholder('INBOX')->maxLength(190),
|
||||
]),
|
||||
Section::make('Fristen und Grenzen')
|
||||
->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.')
|
||||
->columns(3)
|
||||
->collapsed()
|
||||
->schema($this->periodFields()),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -95,19 +268,128 @@ public function content(Schema $schema): Schema
|
||||
]);
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('sendDigest')
|
||||
->label('Zusammenfassung jetzt senden')
|
||||
->icon(Heroicon::OutlinedPaperAirplane)
|
||||
->color('gray')
|
||||
->modalDescription('Schickt die Zusammenfassung mit den gespeicherten Einstellungen sofort an die Benachrichtigungsadressen – auch wenn nichts ansteht. Der reguläre Versand bleibt unverändert.')
|
||||
->schema([
|
||||
Radio::make('weekly')
|
||||
->label('Welche?')
|
||||
->options([0 => 'Tagesübersicht', 1 => 'Wochenübersicht'])
|
||||
->default(0)
|
||||
->required(),
|
||||
])
|
||||
->action(function (array $data): void {
|
||||
app(SendDigests::class)->send($this->tenant(), (bool) $data['weekly'], force: true);
|
||||
|
||||
Notification::make()->title('Zusammenfassung gesendet')->body(Settings::isLive() ? null : 'Testbetrieb: Sie geht an die Testadresse.')->success()->send();
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
$tenant = $this->tenant();
|
||||
$wasLive = $tenant->isLive();
|
||||
|
||||
if ($data['mode'] === Settings::MODE_LIVE && Settings::get(Settings::MODE) !== Settings::MODE_LIVE) {
|
||||
$tenant->update([
|
||||
'operating_mode' => $data['mode'],
|
||||
'test_recipient' => $data['test_recipient'] ?? $tenant->test_recipient,
|
||||
'notification_emails' => implode(', ', Settings::addressList(implode(',', $data['notification_recipients'] ?? []))),
|
||||
'contact_email' => $data['contact_email'],
|
||||
'sender_name' => $data['sender_name'],
|
||||
'sender_email' => $data['sender_email'],
|
||||
'owner_name' => $data['owner_name'],
|
||||
'owner_street' => $data['owner_street'] ?? null,
|
||||
'owner_city' => $data['owner_city'] ?? null,
|
||||
'owner_phone' => $data['owner_phone'] ?? null,
|
||||
'bank_account_holder' => $data['bank_account_holder'] ?? null,
|
||||
'bank_name' => $data['bank_name'] ?? null,
|
||||
'bank_iban' => $data['bank_iban'] ?? null,
|
||||
'bank_bic' => $data['bank_bic'] ?? null,
|
||||
'tax_note' => $data['tax_note'] ?? null,
|
||||
'mailbox_host' => $data['mailbox_host'] ?? null,
|
||||
'mailbox_port' => filled($data['mailbox_port'] ?? null) ? (int) $data['mailbox_port'] : null,
|
||||
'mailbox_username' => $data['mailbox_username'] ?? null,
|
||||
'mailbox_password' => $data['mailbox_password'] ?? null,
|
||||
'mailbox_encryption' => $data['mailbox_encryption'] ?? null,
|
||||
'mailbox_folder' => $data['mailbox_folder'] ?? null,
|
||||
'reminder_interval_days' => (int) $data['reminder_interval_days'],
|
||||
'digest_daily' => (bool) $data['digest_daily'],
|
||||
'digest_weekly' => (bool) $data['digest_weekly'],
|
||||
'digest_weekday' => (int) ($data['digest_weekday'] ?? $tenant->digest_weekday),
|
||||
'digest_hour' => (int) $data['digest_hour'],
|
||||
'digest_sections' => count($data['digest_sections']) === count(DigestSection::cases()) ? null : array_values($data['digest_sections']),
|
||||
'digest_when_empty' => (bool) $data['digest_when_empty'],
|
||||
...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)),
|
||||
]);
|
||||
|
||||
app(TenantConfig::class)->refresh();
|
||||
|
||||
if ($data['mode'] === Settings::MODE_LIVE && ! $wasLive) {
|
||||
Notification::make()->title('Scharf geschaltet')->body('Ab jetzt erhalten Gäste und Vermieterin die E-Mails direkt.')->warning()->send();
|
||||
} else {
|
||||
Notification::make()->title('Gespeichert')->success()->send();
|
||||
}
|
||||
}
|
||||
|
||||
Settings::save([
|
||||
Settings::MODE => $data['mode'],
|
||||
Settings::TEST_RECIPIENT => $data['test_recipient'] ?? Settings::get(Settings::TEST_RECIPIENT),
|
||||
]);
|
||||
/**
|
||||
* The landlord this page edits: the one of the request, else the only one there is.
|
||||
*/
|
||||
private function tenant(): Tenant
|
||||
{
|
||||
$tenant = Settings::tenant();
|
||||
|
||||
abort_if($tenant === null, 404);
|
||||
|
||||
return $tenant;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, ?int>
|
||||
*/
|
||||
private function periodValues(Tenant $tenant): array
|
||||
{
|
||||
return array_combine(array_keys(self::PERIODS), array_map(fn (string $column): ?int => $tenant->{$column}, array_keys(self::PERIODS)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function periodInput(array $data): array
|
||||
{
|
||||
return array_combine(array_keys(self::PERIODS), array_map(fn (string $column): mixed => $data[$column] ?? null, array_keys(self::PERIODS)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<TextInput>
|
||||
*/
|
||||
private function periodFields(): array
|
||||
{
|
||||
return array_map(function (string $column) {
|
||||
$field = TextInput::make($column)
|
||||
->label(self::PERIODS[$column])
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(0);
|
||||
|
||||
$config = app(TenantConfig::class);
|
||||
|
||||
if (($ceiling = $config->ceilingFor($column)) !== null) {
|
||||
return $field->maxValue($ceiling)->helperText('Vorgabe des Systems: höchstens '.$ceiling);
|
||||
}
|
||||
|
||||
if (($floor = $config->floorFor($column)) !== null) {
|
||||
return $field->minValue($floor)->helperText('Vorgabe des Systems: mindestens '.$floor);
|
||||
}
|
||||
|
||||
return $field;
|
||||
}, array_keys(self::PERIODS));
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,8 @@
|
||||
use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\SpecialOffersRelationManager;
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use BackedEnum;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Livewire;
|
||||
use Filament\Schemas\Components\Tabs;
|
||||
@@ -39,7 +39,7 @@ class PricesAndOffers extends Page
|
||||
|
||||
protected static ?string $slug = 'preise-und-angebote';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
#[Url(as: 'wohnung')]
|
||||
public ?int $propertyId = null;
|
||||
@@ -49,9 +49,14 @@ public static function canAccess(): bool
|
||||
return (bool) auth()->user()?->hasRole(UserRole::Admin, UserRole::Rentals);
|
||||
}
|
||||
|
||||
public function getSubheading(): ?string
|
||||
{
|
||||
return app(CurrentProperty::class)->hasChoice() ? Property::query()->find($this->propertyId)?->name : null;
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->propertyId ??= Property::query()->where('is_active', true)->value('id') ?? Property::query()->value('id');
|
||||
$this->propertyId = app(CurrentProperty::class)->followUrl($this->propertyId);
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
@@ -64,12 +69,6 @@ public function content(Schema $schema): Schema
|
||||
$context = ['ownerRecord' => $property, 'pageClass' => EditProperty::class];
|
||||
|
||||
return $schema->components([
|
||||
Select::make('propertyId')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->live()
|
||||
->afterStateUpdated(fn () => $this->redirect(static::getUrl(['wohnung' => $this->propertyId])))
|
||||
->visible(fn (): bool => Property::query()->count() > 1),
|
||||
Tabs::make('prices')
|
||||
->persistTabInQueryString()
|
||||
->tabs([
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\Amenities;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Concerns\SelectsRecordProperty;
|
||||
use App\Filament\Resources\Amenities\Pages\CreateAmenity;
|
||||
use App\Filament\Resources\Amenities\Pages\EditAmenity;
|
||||
use App\Filament\Resources\Amenities\Pages\ListAmenities;
|
||||
@@ -18,7 +19,7 @@
|
||||
|
||||
class AmenityResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
use FollowsAdminMode, SelectsRecordProperty;
|
||||
|
||||
protected static ?string $model = Amenity::class;
|
||||
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
namespace App\Filament\Resources\Amenities\Pages;
|
||||
|
||||
use App\Filament\Concerns\ListsCurrentProperty;
|
||||
use App\Filament\Resources\Amenities\AmenityResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListAmenities extends ListRecords
|
||||
{
|
||||
use ListsCurrentProperty;
|
||||
|
||||
protected static string $resource = AmenityResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Enums\AmenityArea;
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
@@ -28,7 +29,7 @@ public static function configure(Schema $schema): Schema
|
||||
Select::make('property_id')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->pluck('name', 'id')->all())
|
||||
->default(fn (): ?int => Property::query()->value('id'))
|
||||
->default(fn (): ?int => app(CurrentProperty::class)->id())
|
||||
->required(),
|
||||
Toggle::make('is_highlight')
|
||||
->label('Highlight (auf der Startseite hervorheben)'),
|
||||
|
||||
@@ -2,21 +2,15 @@
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Schemas;
|
||||
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Models\Appearance;
|
||||
use App\Models\Page;
|
||||
use App\Models\Photo;
|
||||
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;
|
||||
@@ -45,20 +39,13 @@ public static function configure(Schema $schema): Schema
|
||||
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).')
|
||||
Section::make('Bilder')
|
||||
->description('Welche Fotos in diesem Erscheinungsbild erscheinen, legen Sie beim Foto fest: Webseite › Fotos › „Zeigen in“. Ein Foto kann zu mehreren Erscheinungsbildern gehören; Fotos ohne Angabe erscheinen ganzjährig.')
|
||||
->schema([
|
||||
PhotoSelect::make('hero_photo_id')
|
||||
->label('Titelbild')
|
||||
->placeholder('Bild der Seite verwenden'),
|
||||
Text::make(fn (?Appearance $record): string => self::photoSummary($record)),
|
||||
]),
|
||||
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.')
|
||||
->description('Leer lassen = Text der Seite. Banner pflegen Sie unter Webseite › Banner & Hinweise – dort auch nur für dieses Erscheinungsbild.')
|
||||
->columns(2)
|
||||
->collapsible()
|
||||
->schema(collect(Appearance::OVERRIDABLE)
|
||||
@@ -75,57 +62,21 @@ public static function configure(Schema $schema): Schema
|
||||
}
|
||||
|
||||
/**
|
||||
* 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>
|
||||
* How many photos are made for this appearance.
|
||||
*/
|
||||
public static function sectionPhotoFields(int|string|null $siteId): array
|
||||
public static function photoSummary(?Appearance $appearance): string
|
||||
{
|
||||
$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);
|
||||
}
|
||||
if ($appearance === null) {
|
||||
return 'Nach dem Speichern können Sie Fotos diesem Erscheinungsbild zuordnen.';
|
||||
}
|
||||
|
||||
return $groups ?: [Text::make('Auf den Seiten gibt es noch keine Bausteine mit Bildern.')];
|
||||
$count = Photo::query()->get(['id', 'appearance_ids'])->filter(fn (Photo $photo): bool => $photo->isMadeFor($appearance))->count();
|
||||
|
||||
return match ($count) {
|
||||
0 => 'Noch keine Fotos zugeordnet – es erscheinen die ganzjährigen Fotos.',
|
||||
1 => '1 Foto ist diesem Erscheinungsbild zugeordnet.',
|
||||
default => "{$count} Fotos sind diesem Erscheinungsbild zugeordnet.",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,17 +2,29 @@
|
||||
|
||||
namespace App\Filament\Resources\BlockedPeriods;
|
||||
|
||||
use App\Actions\ResolveChannelOccupation;
|
||||
use App\Channels\ICal\ICalRuleEngine;
|
||||
use App\Enums\BlockedPeriodPurpose;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Concerns\SelectsRecordProperty;
|
||||
use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods;
|
||||
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
@@ -22,12 +34,12 @@
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* All blocked periods of all apartments in one place (own use, renovation, portal occupations).
|
||||
* Portal and e-mail blocks are maintained by the sync and can only be viewed here.
|
||||
* Explicit blocks of all apartments. Imported reservations and unresolved periods have their own views.
|
||||
* Portal dates remain maintained by the sync; business classification can be edited separately.
|
||||
*/
|
||||
class BlockedPeriodResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
use FollowsAdminMode, SelectsRecordProperty;
|
||||
|
||||
protected static ?string $model = BlockedPeriod::class;
|
||||
|
||||
@@ -39,7 +51,7 @@ class BlockedPeriodResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Sperrzeiten';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
@@ -49,53 +61,102 @@ public static function form(Schema $schema): Schema
|
||||
Select::make('property_id')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->default(fn (): ?int => Property::query()->where('is_active', true)->value('id'))
|
||||
->default(fn (): ?int => app(CurrentProperty::class)->id())
|
||||
->required()
|
||||
->columnSpanFull()
|
||||
->hidden(fn (): bool => Property::query()->count() <= 1)
|
||||
->dehydratedWhenHidden(),
|
||||
DatePicker::make('starts_on')->label('Von (erste gesperrte Nacht)')->required(),
|
||||
DatePicker::make('ends_on')->label('Bis (erster freier Tag)')->after('starts_on')->required(),
|
||||
...static::purposeFields(),
|
||||
Select::make('is_private')->label('Buchungskanal')->options([0 => 'Nicht angegeben', 1 => 'Privat'])
|
||||
->default(0)->formatStateUsing(fn (mixed $state): int => (int) $state)->required(),
|
||||
TextInput::make('reason')
|
||||
->label('Grund')
|
||||
->label('Bisheriger Sperrgrund / zusätzliche Angabe')
|
||||
->placeholder('z. B. Eigennutzung, Renovierung')
|
||||
->maxLength(255)
|
||||
->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
return parent::getEloquentQuery()->explicitBlocks()->occupying();
|
||||
}
|
||||
|
||||
/** @return array<Select|TextInput> */
|
||||
public static function purposeFields(): array
|
||||
{
|
||||
return [
|
||||
Select::make('block_purpose')->label('Zweck der Sperrzeit')->options(BlockedPeriodPurpose::class)->placeholder('Noch nicht angegeben'),
|
||||
TextInput::make('block_note')->label('Hinweis zum Zweck')->maxLength(255)->placeholder('z. B. Aufenthalt der Familie'),
|
||||
];
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->description('Zeiträume, in denen die Wohnung nicht vermietet wird. Belegungen aus Portalen erscheinen hier automatisch.')
|
||||
->description('Eigennutzung, Wartung und ausdrücklich als Sperrzeit bestätigte Zeiträume. Portalreservierungen stehen unter Anfragen & Buchungen; unbekannte Zeiten unter Ungeklärte Belegungen.')
|
||||
->defaultSort('starts_on')
|
||||
->columns([
|
||||
TextColumn::make('starts_on')->label('Von')->date('D, d.m.Y')->sortable(),
|
||||
TextColumn::make('ends_on')->label('Bis')->date('D, d.m.Y'),
|
||||
TextColumn::make('reason')->label('Grund')->placeholder('–'),
|
||||
TextColumn::make('property.name')->label('Wohnung')->visible(fn (): bool => Property::query()->count() > 1),
|
||||
TextColumn::make('source')
|
||||
->label('Quelle')
|
||||
->formatStateUsing(fn (string $state): string => match ($state) {
|
||||
'manual' => 'von Hand',
|
||||
'channel' => 'Portal-Kalender',
|
||||
'email' => 'Portal-E-Mail',
|
||||
default => $state,
|
||||
})
|
||||
->badge(),
|
||||
TextColumn::make('ends_on')->label('Bis / erster freier Tag')->date('D, d.m.Y'),
|
||||
TextColumn::make('purpose')->label('Zweck / Grund')->state(fn (BlockedPeriod $record): ?string => $record->blockDescription())->placeholder('–'),
|
||||
TextColumn::make('booking_channel')->label('Buchungskanal')->state(fn (BlockedPeriod $record): string => $record->bookingChannelLabel()),
|
||||
TextColumn::make('property.name')->label('Wohnung'),
|
||||
TextColumn::make('channel.name')->label('Kalenderquelle')->placeholder('Eigene Sperre'),
|
||||
])
|
||||
->filters([
|
||||
Filter::make('upcoming')
|
||||
->label('Nur kommende')
|
||||
->default()
|
||||
Filter::make('upcoming')->label('Nur kommende')->default()
|
||||
->query(fn (Builder $query): Builder => $query->whereDate('ends_on', '>=', today())),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('viewPortal')->label('Details')->visible(fn (BlockedPeriod $record): bool => $record->source !== 'manual')
|
||||
->url(fn (BlockedPeriod $record): string => PortalOccupationResource::getUrl('view', ['record' => $record->id])),
|
||||
EditAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
|
||||
PortalOccupationResource::classificationAction(),
|
||||
DeleteAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function portalActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('icalOriginal')->label('iCal-Original & Erkennung')->visible(fn (BlockedPeriod $record): bool => $record->ical_raw !== null)
|
||||
->modalSubmitAction(false)->modalCancelActionLabel('Schließen')->schema([
|
||||
TextEntry::make('recognized_rule')->label('Treffende Regel')->state(fn (BlockedPeriod $record): string => $record->ical_interpretation['rule'] ?? 'Keine'),
|
||||
TextEntry::make('recognized_representation')->label('Fachliche Einordnung')->state(fn (BlockedPeriod $record): string => ICalRuleEngine::REPRESENTATIONS[$record->ical_interpretation['representation'] ?? 'unspecified']),
|
||||
TextEntry::make('original')->label('Originalereignis (entfaltet)')->state(fn (BlockedPeriod $record): string => $record->ical_raw)->wrap()->extraAttributes(['style' => 'white-space:pre-wrap;overflow-wrap:anywhere']),
|
||||
]),
|
||||
Action::make('resolve')->label('Belegung zuordnen / klären')
|
||||
->visible(fn (BlockedPeriod $record): bool => ! $record->trashed() && in_array($record->source, ['channel', 'email'], true))
|
||||
->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false)
|
||||
->modalDescription('Nur nach persönlicher Prüfung zuordnen. Eine Darstellung steuert keine eigene Belegung mehr; die führende Buchung oder Sperre übernimmt Änderungen und Stornierungen. Kalenderereignisse und UIDs bleiben nachvollziehbar erhalten.')
|
||||
->schema([
|
||||
Select::make('resolution')->label('Fachliche Klärung')->options(['independent' => 'Eigenständige Belegung bestätigen', 'block' => 'Weitere Darstellung einer Kalenderbelegung (Portalreservierung oder Sperrzeit)', 'booking' => 'Weitere Darstellung einer eigenen Buchung'])->default('independent')->required()->live(),
|
||||
Select::make('target_id')->label('Führende Belegung mit demselben Zeitraum')
|
||||
->visible(fn (Get $get): bool => $get('resolution') !== 'independent')
|
||||
->required(fn (Get $get): bool => $get('resolution') !== 'independent')
|
||||
->options(function (BlockedPeriod $record, Get $get): array {
|
||||
if ($get('resolution') === 'booking') {
|
||||
return Booking::query()->where('property_id', $record->property_id)->occupying()->whereDate('arrival', $record->starts_on)->whereDate('departure', $record->ends_on)->get()
|
||||
->mapWithKeys(fn (Booking $booking): array => [$booking->id => 'Buchung '.$booking->reference])->all();
|
||||
}
|
||||
|
||||
return BlockedPeriod::query()->where('property_id', $record->property_id)->occupying()->whereKeyNot($record->id)->whereDate('starts_on', $record->starts_on)->whereDate('ends_on', $record->ends_on)->orderByDesc('leading_priority')->orderBy('id')->get()
|
||||
->mapWithKeys(fn (BlockedPeriod $block): array => [$block->id => '#'.$block->id.' · '.$block->occupationKind()->getLabel().' · '.($block->reason ?? 'Kalenderbelegung').($block->leading_priority ? ' · bevorzugter Führungskandidat' : '')])->all();
|
||||
}),
|
||||
Select::make('origin_channel_id')->label('Ursprünglicher Buchungskanal, sofern persönlich bekannt')
|
||||
->options(fn (BlockedPeriod $record): array => Channel::query()->where('property_id', $record->property_id)->pluck('name', 'id')->all())
|
||||
->default(fn (BlockedPeriod $record): ?int => $record->origin_channel_id)->placeholder('Unbekannt / eigene Vermietung'),
|
||||
])
|
||||
->action(function (BlockedPeriod $record, array $data, ResolveChannelOccupation $resolve): void {
|
||||
$resolve->handle($record, $data['resolution'], filled($data['target_id'] ?? null) ? (int) $data['target_id'] : null, filled($data['origin_channel_id'] ?? null) ? (int) $data['origin_channel_id'] : null);
|
||||
Notification::make()->title('Belegungszuordnung gespeichert')->success()->send();
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
namespace App\Filament\Resources\BlockedPeriods\Pages;
|
||||
|
||||
use App\Filament\Concerns\ListsCurrentProperty;
|
||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ManageRecords;
|
||||
|
||||
class ManageBlockedPeriods extends ManageRecords
|
||||
{
|
||||
use ListsCurrentProperty;
|
||||
|
||||
protected static string $resource = BlockedPeriodResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Concerns\SelectsRecordProperty;
|
||||
use App\Filament\Resources\Bookings\Pages\CreateBooking;
|
||||
use App\Filament\Resources\Bookings\Pages\ListBookings;
|
||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||
@@ -21,7 +22,7 @@
|
||||
|
||||
class BookingResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
use FollowsAdminMode, SelectsRecordProperty;
|
||||
|
||||
protected static ?string $model = Booking::class;
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace App\Filament\Resources\Bookings\Pages;
|
||||
|
||||
use App\Filament\Pages\OccupancyCalendar;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
@@ -13,6 +15,7 @@ class ListBookings extends ListRecords
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('calendar')->label('Belegungsplan')->url(OccupancyCalendar::getUrl()),
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Actions\AssignGuestAction;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Models\Booking;
|
||||
use App\Pricing\PriceCalculator;
|
||||
@@ -45,6 +46,7 @@ public function getTitle(): string
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
AssignGuestAction::make(),
|
||||
Action::make('sendOffer')
|
||||
->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot senden')
|
||||
->icon(Heroicon::OutlinedPaperAirplane)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\Bookings\Schemas;
|
||||
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
@@ -26,7 +27,7 @@ public static function configure(Schema $schema): Schema
|
||||
Select::make('property_id')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->default(fn (): ?int => Property::query()->value('id'))
|
||||
->default(fn (): ?int => app(CurrentProperty::class)->id())
|
||||
->required(),
|
||||
TextInput::make('guests')
|
||||
->label('Personen')
|
||||
|
||||
@@ -68,7 +68,7 @@ public static function configure(Schema $schema): Schema
|
||||
TextEntry::make('hold_expires_at')->label('Vorgemerkt bis')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->hold_expires_at !== null),
|
||||
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('source')->label('Buchungskanal / Quelle')->state(fn (Booking $record): string => $record->bookingChannelLabel()),
|
||||
TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'),
|
||||
TextEntry::make('utm')
|
||||
->label('Kampagne (UTM)')
|
||||
@@ -78,7 +78,7 @@ public static function configure(Schema $schema): Schema
|
||||
Section::make('Gast')
|
||||
->schema([
|
||||
TextEntry::make('guest.full_name')->label('Name'),
|
||||
TextEntry::make('guest.email')->label('E-Mail')->copyable(),
|
||||
TextEntry::make('guest.email')->label('E-Mail')->placeholder('Unbekannt')->copyable(),
|
||||
TextEntry::make('guest.phone')->label('Telefon')->placeholder('–'),
|
||||
TextEntry::make('guest_address')
|
||||
->label('Adresse')
|
||||
|
||||
@@ -2,72 +2,76 @@
|
||||
|
||||
namespace App\Filament\Resources\Bookings\Tables;
|
||||
|
||||
use App\Availability\OccupancyOverview;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Money;
|
||||
use Filament\Actions\ViewAction;
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\Filter;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
|
||||
class BookingsTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
public static function configure(Table $table, ?int $guestId = null): Table
|
||||
{
|
||||
return $table
|
||||
->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property', 'payments']))
|
||||
->defaultSort('created_at', 'desc')
|
||||
->description('Eigene Anfragen und Buchungen sowie erkannte Portalreservierungen in einer Liste. Fehlende Gastzuordnungen lassen sich in den Details ergänzen; unbekannte Belegungen haben einen eigenen Klärungsbereich.')
|
||||
->records(function (?string $search, ?string $sortColumn, ?string $sortDirection, array $filters, int $page, int|string $recordsPerPage) use ($guestId, $table): LengthAwarePaginator {
|
||||
$propertyId = filled($filters['property']['value'] ?? null) ? (int) $filters['property']['value'] : null;
|
||||
$records = app(OccupancyOverview::class)->records($propertyId, $guestId);
|
||||
if (filled($search)) {
|
||||
$term = mb_strtolower($search);
|
||||
$records = $records->filter(fn (array $record): bool => str_contains(mb_strtolower(implode(' ', [$record['reference'], $record['guest'], $record['guest_email'], $record['source'], $record['property']])), $term));
|
||||
}
|
||||
if ($filters['upcoming']['isActive'] ?? false) {
|
||||
$records = $records->filter(fn (array $record): bool => $record['departure'] >= today()->toDateString());
|
||||
}
|
||||
if ($filters['without_guest']['isActive'] ?? false) {
|
||||
$records = $records->where('guest_assigned', false);
|
||||
}
|
||||
if (filled($filters['kind']['value'] ?? null)) {
|
||||
$records = $records->where('record_type', $filters['kind']['value']);
|
||||
}
|
||||
if (filled($filters['status']['values'] ?? [])) {
|
||||
$records = $records->whereIn('status_key', $filters['status']['values']);
|
||||
}
|
||||
$column = in_array($sortColumn, ['arrival', 'departure', 'reference', 'guest', 'source', 'total'], true) ? $sortColumn : 'arrival';
|
||||
$records = $records->sortBy($column, SORT_REGULAR, $sortDirection === 'desc');
|
||||
$perPage = $recordsPerPage === 'all' ? max(1, $records->count()) : $recordsPerPage;
|
||||
|
||||
return new LengthAwarePaginator($records->forPage($page, $perPage), $records->count(), $perPage, $page, ['pageName' => $table->getLivewire()->getTablePaginationPageName()]);
|
||||
})
|
||||
->defaultSort('arrival')->searchable()->recordAction(null)
|
||||
->columns([
|
||||
TextColumn::make('reference')
|
||||
->label('Nr.')
|
||||
->searchable(),
|
||||
TextColumn::make('status')
|
||||
->label('Status')
|
||||
->badge()
|
||||
->description(fn (Booking $record): ?string => $record->isHoldActive() ? 'bis '.$record->hold_expires_at->format('d.m. H:i') : null),
|
||||
TextColumn::make('guest.last_name')
|
||||
->label('Gast')
|
||||
->formatStateUsing(fn (Booking $record): string => $record->guest->full_name)
|
||||
->description(fn (Booking $record): string => $record->guest->email)
|
||||
->searchable(['first_name', 'last_name', 'email']),
|
||||
TextColumn::make('property.name')
|
||||
->label('Wohnung')
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
TextColumn::make('arrival')
|
||||
->label('Anreise')
|
||||
->date('D, d.m.Y')
|
||||
->sortable(),
|
||||
TextColumn::make('departure')
|
||||
->label('Abreise')
|
||||
->date('D, d.m.Y')
|
||||
->description(fn (Booking $record): string => $record->nights().' Nächte'),
|
||||
TextColumn::make('guests')
|
||||
->label('Pers.'),
|
||||
TextColumn::make('total')
|
||||
->label('Gesamt')
|
||||
->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),
|
||||
TextColumn::make('created_at')
|
||||
->label('Eingang')
|
||||
->since()
|
||||
->sortable(),
|
||||
TextColumn::make('reference')->label('Nr. / Referenz')->sortable(),
|
||||
TextColumn::make('kind_label')->label('Art')->badge(),
|
||||
TextColumn::make('status')->label('Status')->badge()->color(fn (array $record): string => $record['color']),
|
||||
TextColumn::make('guest')->label('Gast / Namensinformation')->sortable()
|
||||
->description(fn (array $record): string => $record['guest_assigned'] ? ($record['guest_email'] ?? 'E-Mail unbekannt') : 'Gastzuordnung offen'),
|
||||
TextColumn::make('source')->label('Buchungskanal / Quelle')->sortable(),
|
||||
TextColumn::make('arrival')->label('Anreise')->date('d.m.Y')->sortable(),
|
||||
TextColumn::make('departure')->label('Abreise')->date('d.m.Y')->sortable()
|
||||
->description(fn (array $record): string => $record['nights'].' Nächte'),
|
||||
TextColumn::make('persons')->label('Personen')->placeholder('Unbekannt')->toggleable(isToggledHiddenByDefault: true),
|
||||
TextColumn::make('total')->label('Bekannter Gesamtpreis')->money('EUR', divideBy: 100, locale: 'de')->placeholder('Unbekannt')->toggleable(isToggledHiddenByDefault: true),
|
||||
TextColumn::make('property')->label('Wohnung')->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->filters([
|
||||
SelectFilter::make('status')
|
||||
->label('Status')
|
||||
->options(BookingStatus::class)
|
||||
->multiple(),
|
||||
Filter::make('upcoming')
|
||||
->label('Nur kommende Aufenthalte')
|
||||
->query(fn (Builder $query): Builder => $query->whereDate('departure', '>=', today())),
|
||||
SelectFilter::make('property')->label('Wohnung')->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
// The booking list starts with the apartment chosen in the menu; a guest's bookings show all apartments.
|
||||
->default(fn (): ?int => $guestId === null ? app(CurrentProperty::class)->id() : null),
|
||||
SelectFilter::make('kind')->label('Buchungsweg')->options(['booking' => 'Eigene Anfragen & Buchungen', 'portal' => 'Portalreservierungen']),
|
||||
SelectFilter::make('status')->label('Status')->multiple()->options([
|
||||
...collect(BookingStatus::cases())->mapWithKeys(fn (BookingStatus $status): array => [$status->value => $status->getLabel()])->all(),
|
||||
'imported' => 'Im Portalkalender geführt', 'archived' => 'Nicht mehr im Kalenderfeed',
|
||||
]),
|
||||
Filter::make('upcoming')->label('Nur kommende Aufenthalte'),
|
||||
Filter::make('without_guest')->label('Gastzuordnung offen'),
|
||||
])
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
]);
|
||||
->recordUrl(fn (array $record): string => $record['url'])
|
||||
->recordActions([Action::make('view')->label('Details')->url(fn (array $record): string => $record['url'])]);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,20 @@
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks\Pages;
|
||||
|
||||
use App\Filament\Concerns\ListsCurrentProperty;
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use App\Models\Property;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class ListChannelTasks extends ListRecords
|
||||
{
|
||||
use ListsCurrentProperty;
|
||||
|
||||
protected static string $resource = ChannelTaskResource::class;
|
||||
|
||||
protected function scopeToProperty(Builder $query, Property $property): Builder
|
||||
{
|
||||
return $query->whereHas('channel', fn (Builder $channel) => $channel->where('property_id', $property->id));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 521 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user