Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
+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
|
||||
|
||||
@@ -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`.
|
||||
- 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 ===
|
||||
|
||||
@@ -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,12 +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;
|
||||
@@ -24,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 [];
|
||||
@@ -33,14 +37,25 @@ 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 [];
|
||||
@@ -61,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)) {
|
||||
@@ -90,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;
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
@@ -93,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;
|
||||
@@ -102,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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,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];
|
||||
}
|
||||
|
||||
@@ -139,9 +151,13 @@ 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))),
|
||||
]);
|
||||
|
||||
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 = $this->conflictDetector->conflictsFor($block);
|
||||
|
||||
return [PortalEmailStatus::Blocked, $block, null];
|
||||
@@ -158,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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
+120
-95
@@ -5,19 +5,20 @@
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ConflictDetector;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use App\Enums\ChannelEchoBehavior;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use App\Models\Property;
|
||||
use App\Support\Settings;
|
||||
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) {}
|
||||
@@ -25,105 +26,129 @@ public function __construct(private ConflictDetector $conflictDetector = new Con
|
||||
public function handle(Channel $channel): ChannelSyncLog
|
||||
{
|
||||
$startedAt = microtime(true);
|
||||
|
||||
try {
|
||||
$periods = $channel->connector()->fetchOccupations($channel);
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$channel->forceFill(['last_synced_at' => now(), 'last_error' => $exception->getMessage()])->save();
|
||||
|
||||
return $channel->syncLogs()->create([
|
||||
'successful' => false,
|
||||
'message' => $exception->getMessage(),
|
||||
'duration_ms' => $this->elapsed($startedAt),
|
||||
]);
|
||||
$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.']);
|
||||
}
|
||||
|
||||
$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;
|
||||
try {
|
||||
$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.');
|
||||
}
|
||||
|
||||
$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;
|
||||
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.');
|
||||
}
|
||||
|
||||
if ($block) {
|
||||
$block->update($attributes);
|
||||
$counts['changed']++;
|
||||
$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 {
|
||||
$block = $channel->blockedPeriods()->create([...$attributes, 'external_uid' => $period->uid]);
|
||||
$counts['added']++;
|
||||
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.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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));
|
||||
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;
|
||||
}
|
||||
array_push($conflicts, ...$foundConflicts);
|
||||
}
|
||||
$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();
|
||||
});
|
||||
if ($conflicts !== []) {
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, array_values(array_unique($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(array_unique($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(Settings::notificationRecipients())->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,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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -19,9 +19,10 @@ 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);
|
||||
|
||||
// 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).
|
||||
|
||||
@@ -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,14 @@ enum AdminMode: string implements HasDescription, HasLabel
|
||||
* @var list<class-string>
|
||||
*/
|
||||
public const SIMPLE_NAVIGATION = [
|
||||
OccupancyCalendar::class,
|
||||
BookingResource::class,
|
||||
PortalOccupationResource::class,
|
||||
BlockedPeriodResource::class,
|
||||
PricesAndOffers::class,
|
||||
GuestResource::class,
|
||||
ChannelTaskResource::class,
|
||||
ChannelResource::class,
|
||||
ReviewResource::class,
|
||||
PhotoResource::class,
|
||||
];
|
||||
@@ -46,8 +52,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: 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,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,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,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Availability\OccupancyOverview;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Property;
|
||||
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 mount(): void
|
||||
{
|
||||
$this->month = $this->month ?: now()->format('Y-m');
|
||||
$this->propertyId ??= Property::query()->where('is_active', true)->value('id') ?? Property::query()->value('id');
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -2,17 +2,27 @@
|
||||
|
||||
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\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 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,8 +32,8 @@
|
||||
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
|
||||
{
|
||||
@@ -39,7 +49,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
|
||||
{
|
||||
@@ -56,46 +66,95 @@ public static function form(Schema $schema): Schema
|
||||
->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,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)
|
||||
|
||||
@@ -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,73 @@
|
||||
|
||||
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 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()),
|
||||
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'])]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Channels\Pages\ChannelRules;
|
||||
use App\Filament\Resources\Channels\Pages\CreateChannel;
|
||||
use App\Filament\Resources\Channels\Pages\EditChannel;
|
||||
use App\Filament\Resources\Channels\Pages\ListChannels;
|
||||
use App\Filament\Resources\Channels\Schemas\ChannelForm;
|
||||
use App\Filament\Resources\Channels\Tables\ChannelsTable;
|
||||
use App\Models\Channel;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use UnitEnum;
|
||||
|
||||
class ChannelResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Channel::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedArrowsRightLeft;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $navigationLabel = 'Kalenderabgleich (iCal)';
|
||||
|
||||
protected static ?string $modelLabel = 'iCal-Verbindung';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Kalenderabgleich (iCal)';
|
||||
|
||||
protected static ?int $navigationSort = 4;
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'name';
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return ChannelForm::configure($schema, selectProperty: true);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return ChannelsTable::configure($table);
|
||||
}
|
||||
|
||||
public static function canDelete(Model $record): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListChannels::route('/'),
|
||||
'create' => CreateChannel::route('/create'),
|
||||
'edit' => EditChannel::route('/{record}/edit'),
|
||||
'rules' => ChannelRules::route('/{record}/rules'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels\Pages;
|
||||
|
||||
use App\Actions\AnalyzeChannelCalendar;
|
||||
use App\Actions\ApplyChannelRules;
|
||||
use App\Actions\ConfigureChannelExport;
|
||||
use App\Actions\SaveChannelRules;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ICal\ICalExportFields;
|
||||
use App\Channels\ICal\ICalFeed;
|
||||
use App\Channels\ICal\ICalParser;
|
||||
use App\Channels\ICal\ICalRuleEngine;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\View;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class ChannelRules extends EditRecord
|
||||
{
|
||||
protected static string $resource = ChannelResource::class;
|
||||
|
||||
protected static ?string $title = 'Kalenderanalyse, Regeln & Exportfelder';
|
||||
|
||||
public function fieldOptions(): array
|
||||
{
|
||||
return collect(array_keys($this->record->ical_analysis['fields'] ?? []))->mapWithKeys(fn (string $field): array => [$field => $field])->all();
|
||||
}
|
||||
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
return ['rules' => $this->record->ical_rules ?? [], 'export_names' => (bool) $this->record->ical_export_names, 'export_mapping' => $this->record->ical_export_mapping ?? []];
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
TextEntry::make('rule_status')->label('Gespeicherter Regelstand')
|
||||
->state(fn (): string => $this->savedRulesStatus())
|
||||
->helperText('Speichern legt einen Entwurf ab. „Speichern & anwenden“ aktiviert ihn für vorhandene Einträge und die nächsten Importe.')
|
||||
->columnSpanFull(),
|
||||
Section::make('1. Gefundene Kalenderfelder und Originalereignisse')->description('„Kalender analysieren“ liest die hinterlegte Adresse. Die Analyse verändert keine Belegungen.')
|
||||
->schema([View::make('filament.resources.channels.rule-analysis')]),
|
||||
Section::make('2. Erkennungsregeln')->description('Kleinere Prioritätszahlen zuerst. Bei mehreren Treffern gilt die erste passende aktive Regel. „Entwurf speichern“ und „Speichern & anwenden“ stehen oben auf dieser Seite.')
|
||||
->schema([
|
||||
Repeater::make('rules')->label('Regeln')->defaultItems(0)->addActionLabel('Regel hinzufügen')->live(debounce: 600)
|
||||
->itemLabel(fn (array $state): string => $state['name'] ?? 'Neue Regel')
|
||||
->schema([
|
||||
TextInput::make('name')->label('Regelname')->required()->maxLength(120),
|
||||
TextInput::make('priority')->label('Priorität (kleinere Zahl zuerst)')->integer()->minValue(0)->maxValue(10000)->default(100)->required(),
|
||||
Toggle::make('enabled')->label('Regel aktiviert')->default(true),
|
||||
Toggle::make('case_sensitive')->label('Groß-/Kleinschreibung beachten')->default(false),
|
||||
Select::make('match')->label('Bedingungen verknüpfen')->options(['all' => 'UND – alle Bedingungen', 'any' => 'ODER – mindestens eine Bedingung'])->default('all')->required(),
|
||||
Repeater::make('conditions')->label('Wenn')->minItems(1)->defaultItems(1)->addActionLabel('Bedingung hinzufügen')->columns(3)->schema([
|
||||
Select::make('field')->label('Gefundenes Feld')->options(fn (): array => $this->fieldOptions())->required()->searchable(),
|
||||
Select::make('operator')->label('Vergleich')->options(ICalRuleEngine::OPERATORS)->default('equals')->required()->live(),
|
||||
TextInput::make('value')->label('Vergleichstext')->maxLength(2000)->visible(fn (Get $get): bool => ! in_array($get('operator'), ['exists', 'empty'], true))->live(debounce: 600),
|
||||
])->columnSpanFull(),
|
||||
Select::make('event_type')->label('Dann: Ereignistyp')->options(ICalRuleEngine::TYPES)->default('unknown')->required(),
|
||||
Select::make('origin')->label('Ursprünglicher Buchungskanal')->options(fn (): array => ['unknown' => 'Unbekannt', 'current' => 'Dieser Portalkanal', ...$this->record->property->channels()->get()->mapWithKeys(fn (Channel $channel): array => ['channel:'.$channel->id => $channel->name])->all()])->default('unknown')->required(),
|
||||
Select::make('representation')->label('Fachliche Einordnung')->options(ICalRuleEngine::REPRESENTATIONS)->default('unspecified')->required()->columnSpanFull()
|
||||
->helperText('Eine allgemeine Sperre mit „Zusätzliche Sperre“ und unbekanntem Ursprung kann automatisch einer eindeutigen führenden Portalreservierung desselben Zeitraums zugeordnet werden. Eigene Buchungsmerkmale und persönliche Entscheidungen verhindern dies.'),
|
||||
Repeater::make('extractions')->label('Informationen aus Text übernehmen')
|
||||
->helperText('Ein Name im Original wird erst mit einer Textextraktion angezeigt. Für einen vollständigen Namen das passende Kalenderfeld und „Vollständiger Gastname“ wählen. Die Vorschau prüft das Ergebnis; es wird kein Gast automatisch angelegt.')
|
||||
->defaultItems(0)->addActionLabel('Textextraktion hinzufügen')->columns(2)->schema([
|
||||
Select::make('field')->label('Aus Kalenderfeld')->options(fn (): array => $this->fieldOptions())->required(),
|
||||
Select::make('target')->label('Übernehmen als')->options(ICalRuleEngine::TARGETS)->required(),
|
||||
Select::make('method')->label('Textauswahl')->options(ICalRuleEngine::EXTRACTIONS)->default('whole')->required()->live(),
|
||||
TextInput::make('start')->label('Text nach / Anfangstext')->maxLength(500)->visible(fn (Get $get): bool => in_array($get('method'), ['after', 'between'], true))->live(debounce: 600),
|
||||
TextInput::make('end')->label('Text vor / Endtext')->maxLength(500)->visible(fn (Get $get): bool => in_array($get('method'), ['before', 'between'], true))->live(debounce: 600),
|
||||
])->columnSpanFull(),
|
||||
])->columns(2),
|
||||
]),
|
||||
Section::make('3. Live-Vorschau')->description('Auswertung des gespeicherten echten Kalenderstands mit dem aktuellen Regelentwurf. Identische Termine sind lediglich Zuordnungskandidaten.')
|
||||
->schema([View::make('filament.resources.channels.rule-preview')]),
|
||||
Section::make('4. Informationen im Export an diesen Zielkanal')->description('Diese Exportkonfiguration wird beim Speichern wirksam. Die Vorschau zeigt den aktuell berechneten Inhalt; ein pausierter Export bleibt eingefroren. Nicht vorhandene Informationen werden ausgelassen.')
|
||||
->schema([
|
||||
Toggle::make('export_names')->label('Gastnamen ausdrücklich an diesen Zielkanal weitergeben')->default(false)->live()
|
||||
->helperText('Gilt für neu erzeugte Exporte. Ein pausierter Export behält seinen gespeicherten Stand bis zur Reaktivierung.'),
|
||||
Repeater::make('export_mapping')->label('iCal-Felder befüllen')->maxItems(3)->defaultItems(0)->live(debounce: 600)->addActionLabel('Exportfeld hinzufügen')->schema([
|
||||
Select::make('field')->label('iCal-Zielfeld')->options(ICalExportFields::ICAL_FIELDS)->required(),
|
||||
Select::make('items')->label('Enthaltene Informationen (in dieser Reihenfolge)')->options(ICalExportFields::FIELDS)->multiple()->required(),
|
||||
TextInput::make('separator')->label('Trennzeichen')->default(' – ')->maxLength(30),
|
||||
]),
|
||||
View::make('filament.resources.channels.export-preview'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function preview(): array
|
||||
{
|
||||
$engine = app(ICalRuleEngine::class);
|
||||
$rules = array_values($this->data['rules'] ?? []);
|
||||
$counts = array_fill(0, count($rules), 0);
|
||||
$unmatched = 0;
|
||||
$rows = [];
|
||||
$occupations = $this->record->property->blockedPeriods()->with('channel')->get();
|
||||
$blocks = $occupations->where('is_representation', false);
|
||||
foreach ($this->record->ical_analysis['events'] ?? [] as $event) {
|
||||
$result = $engine->evaluate($this->record, $event['properties'], $rules);
|
||||
if ($result['matched']) {
|
||||
$counts[$result['rule_index']]++;
|
||||
} else {
|
||||
$unmatched++;
|
||||
}
|
||||
$candidates = $blocks->filter(fn (BlockedPeriod $block): bool => $block->starts_on->toDateString() === $event['starts_on'] && $block->ends_on->toDateString() === $event['ends_on'] && ! ($block->channel_id === $this->record->id && $block->external_uid === $event['uid']))->sortByDesc('leading_priority');
|
||||
$occupation = $occupations->first(fn (BlockedPeriod $block): bool => $block->channel_id === $this->record->id && $block->external_uid === $event['uid']);
|
||||
$rows[] = [...$event, 'summary' => $engine->values($event['properties'], 'SUMMARY')[0] ?? '(ohne SUMMARY)', 'result' => $result,
|
||||
'occupation_url' => $occupation ? PortalOccupationResource::getUrl('view', ['record' => $occupation->id]) : null,
|
||||
'candidates' => $candidates->map(fn (BlockedPeriod $block): array => [
|
||||
'id' => $block->id, 'reason' => $block->channel?->name ?? $block->reason,
|
||||
'priority' => $block->leading_priority, 'kind' => $block->occupationKind()->getLabel(),
|
||||
'url' => in_array($block->source, ['channel', 'email'], true) ? PortalOccupationResource::getUrl('view', ['record' => $block->id]) : null,
|
||||
])->all()];
|
||||
}
|
||||
|
||||
return ['rows' => $rows, 'counts' => $counts, 'rules' => $rules, 'unmatched' => $unmatched];
|
||||
}
|
||||
|
||||
public function savedRulesStatus(): string
|
||||
{
|
||||
$draft = $this->record->ical_rules ?? [];
|
||||
$active = $this->record->ical_active_rules ?? [];
|
||||
|
||||
if ($draft !== $active) {
|
||||
return 'Gespeicherte Regeln sind noch nicht aktiv. Entwurf: '.count($draft).' Regeln; aktiv: '.count($active).' Regeln.';
|
||||
}
|
||||
|
||||
return $active === [] ? 'Es sind noch keine Erkennungsregeln aktiviert.' : 'Gespeicherter Entwurf und aktive Regeln stimmen überein. Aktiv: '.count($active).' Regeln.';
|
||||
}
|
||||
|
||||
public function exportPreview(): array
|
||||
{
|
||||
$channel = clone $this->record;
|
||||
$channel->forceFill(['ical_export_names' => (bool) ($this->data['export_names'] ?? false), 'ical_export_mapping' => array_values($this->data['export_mapping'] ?? [])]);
|
||||
|
||||
return app(ICalParser::class)->parseDocument(app(ICalFeed::class)->build($channel))['events'];
|
||||
}
|
||||
|
||||
protected function handleRecordUpdate(Model $record, array $data): Model
|
||||
{
|
||||
DB::transaction(function () use ($record, $data): Model {
|
||||
$channel = app(SaveChannelRules::class)->handle($record, array_values($data['rules'] ?? []));
|
||||
|
||||
return app(ConfigureChannelExport::class)->handle($channel, array_values($data['export_mapping'] ?? []), (bool) ($data['export_names'] ?? false));
|
||||
});
|
||||
|
||||
return $record->refresh();
|
||||
}
|
||||
|
||||
protected function getSavedNotificationTitle(): ?string
|
||||
{
|
||||
return 'Regelentwurf und Exportkonfiguration gespeichert';
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('saveDraft')->label('Entwurf speichern')->color('gray')
|
||||
->action(function (): void {
|
||||
$this->save(shouldRedirect: false);
|
||||
}),
|
||||
Action::make('analyze')->label('Kalender analysieren')->action(function (AnalyzeChannelCalendar $analyze): void {
|
||||
try {
|
||||
$this->record = $analyze->handle($this->record);
|
||||
Notification::make()->title($this->record->ical_analysis['count'].' Originalereignisse analysiert')->success()->send();
|
||||
} catch (ChannelSyncException $exception) {
|
||||
Notification::make()->title('Analyse nicht möglich')->body($exception->getMessage())->danger()->send();
|
||||
}
|
||||
}),
|
||||
Action::make('applyRules')->label('Speichern & anwenden')->requiresConfirmation()
|
||||
->modalDescription('Der Regelentwurf wird aktiviert und der vorhandene Kalenderbestand neu klassifiziert. IDs, Termine und persönliche Zuordnungen bleiben erhalten. Bekannte Herkunft beeinflusst den kanalspezifischen Export. Bei Namensfreigabe werden die gewählten Exportinformationen ebenfalls gespeichert.')
|
||||
->action(function (ApplyChannelRules $apply, Action $action): void {
|
||||
try {
|
||||
$counts = DB::transaction(function () use ($apply): array {
|
||||
$this->record = $this->handleRecordUpdate($this->record, $this->form->getState());
|
||||
|
||||
return $apply->handle($this->record);
|
||||
});
|
||||
} catch (ValidationException $exception) {
|
||||
$this->record->refresh();
|
||||
$this->setErrorBag($exception->errors());
|
||||
Notification::make()->title('Regeln wurden nicht angewendet')
|
||||
->body(collect($exception->errors())->flatten()->unique()->implode(' '))
|
||||
->danger()->persistent()->send();
|
||||
$action->cancel();
|
||||
}
|
||||
$this->record->refresh();
|
||||
$this->rememberData();
|
||||
Notification::make()->title($counts['classified'].' Einträge neu klassifiziert')
|
||||
->body($counts['missing_raw'].' Einträge ohne Originaldaten unverändert. Eindeutige allgemeine Belegtmeldungen werden als Kalenderspiegelung zugeordnet; widersprüchliche Einträge bleiben zur Klärung sichtbar.')
|
||||
->success()->send();
|
||||
}),
|
||||
Action::make('configuration')->label('Kalenderverbindung')->url(fn (): string => ChannelResource::getUrl('edit', ['record' => $this->record])),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels\Pages;
|
||||
|
||||
use App\Actions\ConfigureChannel;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use App\Models\Property;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class CreateChannel extends CreateRecord
|
||||
{
|
||||
protected static string $resource = ChannelResource::class;
|
||||
|
||||
protected function handleRecordCreation(array $data): Model
|
||||
{
|
||||
$property = Property::query()->findOrFail($data['property_id']);
|
||||
|
||||
return app(ConfigureChannel::class)->handle($property, $data);
|
||||
}
|
||||
|
||||
protected function getCreatedNotificationTitle(): ?string
|
||||
{
|
||||
return 'iCal-Verbindung angelegt – Exportlink automatisch erzeugt';
|
||||
}
|
||||
|
||||
protected function getRedirectUrl(): string
|
||||
{
|
||||
return ChannelResource::getUrl('index');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels\Pages;
|
||||
|
||||
use App\Actions\AnalyzeChannelCalendar;
|
||||
use App\Actions\ConfigureChannel;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class EditChannel extends EditRecord
|
||||
{
|
||||
protected static string $resource = ChannelResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('rules')->label('Regeln & Exportfelder')->url(fn (): string => ChannelResource::getUrl('rules', ['record' => $this->record])),
|
||||
Action::make('analyze')->label('Kalender analysieren')->action(function (AnalyzeChannelCalendar $analyze): void {
|
||||
try {
|
||||
$analyze->handle($this->record);
|
||||
$this->redirect(ChannelResource::getUrl('rules', ['record' => $this->record]));
|
||||
} catch (ChannelSyncException $exception) {
|
||||
Notification::make()->title('Analyse nicht möglich')->body($exception->getMessage())->danger()->send();
|
||||
}
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
return [...$data, 'settings' => $this->record->settings];
|
||||
}
|
||||
|
||||
protected function handleRecordUpdate(Model $record, array $data): Model
|
||||
{
|
||||
return app(ConfigureChannel::class)->handle($record->property, $data, $record);
|
||||
}
|
||||
|
||||
protected function getRedirectUrl(): string
|
||||
{
|
||||
return ChannelResource::getUrl('index');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels\Pages;
|
||||
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListChannels extends ListRecords
|
||||
{
|
||||
protected static string $resource = ChannelResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()->label('iCal-Verbindung anlegen'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels\Schemas;
|
||||
|
||||
use App\Channels\ChannelRegistry;
|
||||
use App\Enums\ChannelBookingModel;
|
||||
use App\Enums\ChannelEchoBehavior;
|
||||
use App\Enums\ChannelExportMode;
|
||||
use App\Enums\ChannelStatus;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class ChannelForm
|
||||
{
|
||||
public static function configure(Schema $schema, bool $selectProperty = false): Schema
|
||||
{
|
||||
$registry = app(ChannelRegistry::class);
|
||||
|
||||
return $schema
|
||||
->columns(2)
|
||||
->components([
|
||||
...($selectProperty ? [Select::make('property_id')->label('Wohnung')->required()
|
||||
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->default(fn (): ?int => Property::query()->where('is_active', true)->value('id'))
|
||||
->disabled(fn (?Channel $record): bool => $record !== null)->dehydrated()->columnSpanFull()] : []),
|
||||
TextEntry::make('export_url')
|
||||
->label('Eigener iCal-Exportlink')
|
||||
->state(fn (?Channel $record): ?string => $record?->exportUrl())
|
||||
->visible(fn (?Channel $record): bool => $record?->exists ?? false)
|
||||
->copyable()
|
||||
->copyMessage('Exportlink kopiert')
|
||||
->wrap()
|
||||
->extraAttributes(['style' => 'overflow-wrap:anywhere'])
|
||||
->columnSpanFull(),
|
||||
TextInput::make('name')
|
||||
->label('Name der Kalenderverbindung')
|
||||
->placeholder('z. B. FeWo-direkt')
|
||||
->required()
|
||||
->maxLength(100),
|
||||
Select::make('status')->label('Kanalstatus')->options(ChannelStatus::class)->default(ChannelStatus::Setup)->required(),
|
||||
Select::make('booking_model')->label('Buchungsmodell')->options(ChannelBookingModel::class)->default(ChannelBookingModel::Mixed)->required()
|
||||
->helperText('Fachliche Einordnung; löst keine automatischen Buchungsentscheidungen aus.'),
|
||||
Select::make('connector')
|
||||
->label('Kalenderanbindung')
|
||||
->helperText('Diese Verbindung gleicht Belegungszeiträume über iCal ab. Weitere Portalfunktionen benötigen eine eigene Anbindung.')
|
||||
->options($registry->options())
|
||||
->default('ical')
|
||||
->live()
|
||||
->required(),
|
||||
Group::make()
|
||||
->columnSpanFull()
|
||||
->schema(fn (Get $get): array => filled($get('connector')) ? $registry->connectors()[$get('connector')]::settingsSchema() : []),
|
||||
Toggle::make('import_enabled')->label('Import aktiviert')->default(false)
|
||||
->helperText('Abruf durch FewoPortal alle fünf Minuten, sofern der Kanal aktiv ist.'),
|
||||
Toggle::make('export_enabled')->label('Export aktiviert')->default(false)
|
||||
->helperText('Ausgeschaltet bleibt der letzte gültige Export eingefroren erreichbar. Ohne Stand: HTTP 503, kein leerer Kalender.'),
|
||||
Select::make('export_mode')->label('Exportmodus')->options(ChannelExportMode::class)->default(ChannelExportMode::Test)->required()
|
||||
->helperText('Testbetrieb exportiert keine Fremdbelegungen und gewährleistet keine vollständige kanalübergreifende Sperrung. Regulär nur nach bewusster Freigabe wählen.')
|
||||
->columnSpanFull(),
|
||||
TextInput::make('external_poll_minutes')->label('Erwarteter externer Abrufabstand (Minuten)')
|
||||
->integer()->minValue(1)->maxValue(43200)
|
||||
->helperText('Nur eine Annahme zum Portal; verändert weder unseren Abruf noch bestätigt sie eine Übernahme.'),
|
||||
Select::make('echo_behavior')->label('Beobachtetes Rückkopplungsverhalten')->options(ChannelEchoBehavior::class)->default(ChannelEchoBehavior::Unverified)->required()->columnSpanFull()
|
||||
->helperText('Bei Weitergabe mit neuen UIDs bleiben neue Importereignisse bis zur persönlichen Klärung vom Export ausgeschlossen. Sie sperren intern weiterhin.'),
|
||||
Textarea::make('echo_notes')->label('Nachweis / Beobachtung zum Rückkopplungsverhalten')->maxLength(4000)->columnSpanFull(),
|
||||
DateTimePicker::make('portal_verified_at')->label('Tatsächliche Übernahme im Portal zuletzt persönlich geprüft')->seconds(false)
|
||||
->helperText('Nur nach Sichtkontrolle im Portal eintragen. Wird durch einen Feedabruf nicht automatisch gesetzt.'),
|
||||
Textarea::make('operating_notes')->label('Zusätzliche Anforderungen dieses Portals')->maxLength(4000)->columnSpanFull()
|
||||
->helperText('Zum Beispiel eine zusätzliche Bestätigung, dass der Belegungskalender gepflegt ist.'),
|
||||
TextInput::make('settings.email_senders')
|
||||
->label('Absender der Buchungs-E-Mails (Schnellerkennung)')
|
||||
->helperText('Komma-getrennt, z. B. „fewo-direkt.de, vrbo.com“. Buchungsbestätigungen dieser Absender werden sofort gesperrt.')
|
||||
->maxLength(500)
|
||||
->columnSpanFull(),
|
||||
Toggle::make('requires_manual_blocking')
|
||||
->label('Zusätzlich von Hand sperren (Sofortbuchung)')
|
||||
->helperText('Bei jeder Belegung über andere Wege entsteht eine Aufgabe „Im Portal sperren“ – für Portale, die unseren Kalender zu selten abholen.')
|
||||
->live()
|
||||
->columnSpanFull(),
|
||||
TextInput::make('manage_url')
|
||||
->label('Link zum Kalender im Vermieterbereich')
|
||||
->url()
|
||||
->maxLength(2048)
|
||||
->visible(fn (Get $get): bool => (bool) $get('requires_manual_blocking'))
|
||||
->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Channels\Tables;
|
||||
|
||||
use App\Actions\AnalyzeChannelCalendar;
|
||||
use App\Actions\ConfigureChannel;
|
||||
use App\Actions\RotateChannelToken;
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ICal\ICalFeed;
|
||||
use App\Channels\ICal\ICalParser;
|
||||
use App\Filament\Resources\Channels\ChannelResource;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use App\Models\Property;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Infolists\Components\RepeatableEntry;
|
||||
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\Layout\Stack;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class ChannelsTable
|
||||
{
|
||||
public static function configure(Table $table, ?Property $owner = null): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('name')
|
||||
->defaultSort('id')
|
||||
->contentGrid(['md' => 2, '2xl' => 3])
|
||||
->emptyStateHeading('Noch keine iCal-Verbindungen')
|
||||
->emptyStateDescription('Legen Sie eine Kalenderverbindung für eine Ihrer Wohnungen an. Ihr eigener iCal-Exportlink wird beim Speichern automatisch erzeugt.')
|
||||
->description('Hier verwalten Sie ausschließlich den Belegungsabgleich über iCal. Weitere Portalfunktionen werden separat angebunden.')
|
||||
->modifyQueryUsing(fn (Builder $query) => $query->withCount(['blockedPeriods as review_count' => fn ($blocks) => $blocks->where('needs_review', true)]))
|
||||
->columns([
|
||||
Stack::make([
|
||||
TextColumn::make('name')->label('Kalenderverbindung')->weight('bold')->searchable()->sortable()->wrap()->extraAttributes(['style' => 'overflow-wrap:anywhere']),
|
||||
TextColumn::make('property.name')->label('Wohnung')->visible($owner === null)->searchable()->color('gray')->wrap(),
|
||||
TextColumn::make('channel_state')->label('Status')->badge()->wrap()
|
||||
->state(fn (Channel $record): string => match (true) {
|
||||
! $record->importsOccupations() => $record->status->getLabel(),
|
||||
$record->last_error !== null => 'Importfehler',
|
||||
$record->last_success_at === null => 'Erster Import ausstehend',
|
||||
$record->isStale() => 'Import veraltet',
|
||||
default => $record->status->getLabel(),
|
||||
})
|
||||
->color(fn (Channel $record): string => match (true) {
|
||||
! $record->is_active => 'gray',
|
||||
! $record->importsOccupations() => 'success',
|
||||
$record->last_error !== null => 'danger',
|
||||
$record->last_success_at === null => 'warning',
|
||||
$record->isStale() => 'danger',
|
||||
default => 'success',
|
||||
})
|
||||
->description(fn (Channel $record): ?string => $record->review_count || count($record->sync_warnings ?? []) ? 'Prüffälle: '.$record->review_count.' · Hinweise: '.count($record->sync_warnings ?? []) : null)
|
||||
->tooltip(fn (Channel $record): ?string => $record->last_error),
|
||||
TextColumn::make('directions')->label('Richtungen')->color('gray')->wrap()
|
||||
->state(fn (Channel $record): string => ($record->importsOccupations() ? 'Import aktiv' : 'Import aus').' · '.($record->exportsOccupations() ? 'Export aktiv' : ($record->export_snapshot_at ? 'Export eingefroren' : 'Export aus'))),
|
||||
TextColumn::make('last_sync')->label('Letzter Sync-Lauf')->wrap()
|
||||
->state(fn (Channel $record): string => 'Letzter Sync: '.($record->last_synced_at?->format('d.m.Y H:i') ?? 'noch kein Lauf'))
|
||||
->description(fn (Channel $record): ?string => $record->last_error !== null ? 'Letzter Lauf mit Fehler' : null),
|
||||
TextColumn::make('last_export_request')->label('Letzter Kalenderabruf')->wrap()->color('gray')
|
||||
->state(fn (Channel $record): string => 'Letzter Abruf: '.($record->last_export_requested_at?->format('d.m.Y H:i') ?? 'noch keiner'))
|
||||
->tooltip('Empfangener Aufruf dieses Kanalfeeds. Client und tatsächliche Übernahme im Portal sind damit nicht bestätigt.'),
|
||||
])->space(2),
|
||||
])
|
||||
->headerActions($owner ? [
|
||||
CreateAction::make()->label('iCal-Verbindung anlegen')->using(fn (array $data): Channel => app(ConfigureChannel::class)->handle($owner, $data))
|
||||
->modalDescription('Kalenderverbindung benennen und iCal-Anbindung wählen. Der eigene Exportlink entsteht automatisch beim Speichern. Weitere Portalfunktionen sind gesonderte Anbindungen.')
|
||||
->successNotificationTitle('iCal-Verbindung angelegt – Exportlink automatisch erzeugt'),
|
||||
] : [])
|
||||
->recordActions([
|
||||
Action::make('exportLink')->label('Exportlink')->icon(Heroicon::OutlinedLink)->button()
|
||||
->modalDescription('Diese Adresse erlaubt den Kalenderabruf. Nur dem vorgesehenen Portal geben. Ein Abruf beweist keine tatsächliche Übernahme.')
|
||||
->schema([
|
||||
TextEntry::make('export_url')->label('Vertrauliche Kalenderadresse')->state(fn (Channel $record): string => $record->exportUrl())->copyable()->wrap()->extraAttributes(['style' => 'overflow-wrap:anywhere']),
|
||||
TextEntry::make('token_transition')->label('Bisheriger Link bleibt gültig bis')->state(fn (Channel $record): string => $record->previous_export_token_expires_at?->format('d.m.Y H:i') ?? 'Keine Übergangsphase'),
|
||||
])->modalSubmitAction(false)->modalCancelActionLabel('Schließen'),
|
||||
...($owner ? [EditAction::make()->mutateRecordDataUsing(fn (array $data, Channel $record): array => [...$data, 'settings' => $record->settings])
|
||||
->using(fn (Channel $record, array $data): Channel => app(ConfigureChannel::class)->handle($owner, $data, $record))] : [EditAction::make()]),
|
||||
ActionGroup::make([
|
||||
Action::make('rules')->label('Regeln & Exportfelder')->url(fn (Channel $record): string => ChannelResource::getUrl('rules', ['record' => $record])),
|
||||
Action::make('analyze')->label('Kalender analysieren')->action(function (Channel $record, AnalyzeChannelCalendar $analyze, $livewire): void {
|
||||
try {
|
||||
$analyze->handle($record);
|
||||
$livewire->redirect(ChannelResource::getUrl('rules', ['record' => $record]));
|
||||
} catch (ChannelSyncException $exception) {
|
||||
Notification::make()->title('Analyse nicht möglich')->body($exception->getMessage())->danger()->send();
|
||||
}
|
||||
}),
|
||||
Action::make('coverage')->label('Exportumfang prüfen')->modalSubmitAction(false)->modalCancelActionLabel('Schließen')
|
||||
->modalDescription('Aktuell berechneter Umfang der nächsten aktiven Ausgabe. Bei pausiertem Export bleibt der gespeicherte Stand maßgeblich.')
|
||||
->schema([
|
||||
TextEntry::make('export_events')->label('Ereignisse im berechneten Feed')->state(fn (Channel $record): int => count(app(ICalParser::class)->parse(app(ICalFeed::class)->build($record)))),
|
||||
TextEntry::make('held_events')->label('Importe in persönlicher Klärung oder zugeordnete Darstellungen')->state(fn (Channel $record): int => $record->property->blockedPeriods()->where(fn ($query) => $query->where('export_approved', false)->orWhere('is_representation', true))->count()),
|
||||
]),
|
||||
Action::make('exportRequests')->label('Kalenderabrufe')->icon(Heroicon::OutlinedClock)
|
||||
->modalDescription('Die letzten 100 empfangenen Aufrufe dieses Kanalfeeds. Die vom Client gemeldete Kennung ist unbestätigt; auch Browser oder Tests können hier erscheinen. Ein Abruf beweist keine Übernahme im Portal.')
|
||||
->modalSubmitAction(false)->modalCancelActionLabel('Schließen')
|
||||
->schema([
|
||||
RepeatableEntry::make('requests')->label('Abrufhistorie')
|
||||
->state(fn (Channel $record): array => $record->exportRequests()->get()->map(fn ($entry): array => [
|
||||
'time' => $entry->requested_at->format('d.m.Y H:i:s'),
|
||||
'result' => $entry->method.' · HTTP '.$entry->response_status.' · '.match ($entry->export_state) {
|
||||
'live' => 'Aktueller Stand', 'frozen' => 'Eingefrorener Stand', default => 'Kein Stand verfügbar'
|
||||
},
|
||||
'client' => $entry->user_agent ?? 'Keine Clientkennung übermittelt',
|
||||
])->all())
|
||||
->schema([TextEntry::make('time')->label('Empfangen'), TextEntry::make('result')->label('Antwort'), TextEntry::make('client')->label('Clientangabe (unbestätigt)')->wrap()]),
|
||||
]),
|
||||
Action::make('rotateToken')->label('Exporttoken wechseln')->requiresConfirmation()
|
||||
->modalDescription('Eine neue Adresse entsteht. Die bisherige bleibt während der Übergangsphase gültig. Die neue Adresse selbst im Portal eintragen; danach Ablauf beachten.')
|
||||
->schema([TextInput::make('grace_hours')->label('Übergangsphase in Stunden')->integer()->minValue(24)->maxValue(720)->default(168)->required()])
|
||||
->action(function (Channel $record, array $data, RotateChannelToken $rotate): void {
|
||||
$rotate->handle($record, (int) $data['grace_hours']);
|
||||
Notification::make()->title('Token gewechselt – neuen Exportlink im Portal eintragen')->success()->send();
|
||||
}),
|
||||
Action::make('sync')
|
||||
->label('Jetzt abgleichen')
|
||||
->icon(Heroicon::OutlinedArrowPath)
|
||||
->visible(fn (Channel $record): bool => $record->importsOccupations())
|
||||
->action(function (Channel $record, SyncChannel $syncChannel): void {
|
||||
$log = $syncChannel->handle($record);
|
||||
|
||||
$log->successful
|
||||
? Notification::make()->title("{$log->events} Belegungen eingelesen")->body("Neu: {$log->added}, geändert: {$log->changed}, entfernt: {$log->removed}, Konflikte: {$log->conflicts}")->success()->send()
|
||||
: Notification::make()->title('Abgleich fehlgeschlagen')->body($log->message)->danger()->send();
|
||||
}),
|
||||
Action::make('logs')
|
||||
->label('Protokoll')
|
||||
->icon(Heroicon::OutlinedListBullet)
|
||||
->color('gray')
|
||||
->modalSubmitAction(false)
|
||||
->modalCancelActionLabel('Schließen')
|
||||
->schema([
|
||||
RepeatableEntry::make('recentLogs')
|
||||
->hiddenLabel()
|
||||
->state(fn (Channel $record): array => $record->syncLogs()->limit(30)->get()->map(fn (ChannelSyncLog $log): array => [
|
||||
'time' => $log->created_at->format('d.m. H:i'),
|
||||
'result' => $log->successful ? "✓ {$log->events} Belegungen (+{$log->added} ~{$log->changed} -{$log->removed})" : '✗ '.$log->message,
|
||||
'conflicts' => $log->conflicts ?: '',
|
||||
'warnings' => implode(' ', $log->warnings ?? []),
|
||||
])->all())
|
||||
->table([
|
||||
TableColumn::make('Zeit'),
|
||||
TableColumn::make('Ergebnis'),
|
||||
TableColumn::make('Konflikte'),
|
||||
TableColumn::make('Hinweise'),
|
||||
])
|
||||
->schema([
|
||||
TextEntry::make('time'),
|
||||
TextEntry::make('result'),
|
||||
TextEntry::make('conflicts'),
|
||||
TextEntry::make('warnings'),
|
||||
]),
|
||||
]),
|
||||
])->label('Weitere Aktionen')->icon(Heroicon::OutlinedEllipsisVertical),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ class GuestResource extends Resource
|
||||
|
||||
protected static ?string $recordTitleAttribute = 'last_name';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
protected static ?int $navigationSort = 4;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
|
||||
@@ -2,11 +2,8 @@
|
||||
|
||||
namespace App\Filament\Resources\Guests\RelationManagers;
|
||||
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Models\Booking;
|
||||
use Filament\Actions\ViewAction;
|
||||
use App\Filament\Resources\Bookings\Tables\BookingsTable;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class BookingsRelationManager extends RelationManager
|
||||
@@ -22,18 +19,6 @@ public function isReadOnly(): bool
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('reference')
|
||||
->columns([
|
||||
TextColumn::make('reference')->label('Nr.'),
|
||||
TextColumn::make('arrival')->label('Anreise')->date('d.m.Y'),
|
||||
TextColumn::make('departure')->label('Abreise')->date('d.m.Y'),
|
||||
TextColumn::make('guests')->label('Pers.'),
|
||||
TextColumn::make('status')->label('Status')->badge(),
|
||||
TextColumn::make('total')->label('Gesamt')->money('EUR', divideBy: 100, locale: 'de'),
|
||||
])
|
||||
->recordActions([
|
||||
ViewAction::make()->url(fn (Booking $record): string => BookingResource::getUrl('view', ['record' => $record])),
|
||||
]);
|
||||
return BookingsTable::configure($table, $this->getOwnerRecord()->id);
|
||||
}
|
||||
}
|
||||
@@ -21,26 +21,11 @@ public static function configure(Schema $schema): Schema
|
||||
Section::make('Kontakt')
|
||||
->columnSpan(2)
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('first_name')->label('Vorname')->required()->maxLength(255),
|
||||
TextInput::make('last_name')->label('Nachname')->required()->maxLength(255),
|
||||
TextInput::make('email')->label('E-Mail')->email()->required()->maxLength(255),
|
||||
TextInput::make('phone')->label('Telefon')->tel()->maxLength(50),
|
||||
TextInput::make('street')->label('Straße')->maxLength(255),
|
||||
TextInput::make('postal_code')->label('PLZ')->maxLength(20),
|
||||
TextInput::make('city')->label('Ort')->maxLength(255),
|
||||
Select::make('country')
|
||||
->label('Land')
|
||||
->options(['DE' => 'Deutschland', 'AT' => 'Österreich', 'CH' => 'Schweiz', 'NL' => 'Niederlande', 'DK' => 'Dänemark', 'PL' => 'Polen'])
|
||||
->default('DE')
|
||||
->required(),
|
||||
]),
|
||||
->schema(static::contactFields()),
|
||||
Section::make('Verwaltung')
|
||||
->columnSpan(1)
|
||||
->schema([
|
||||
TagsInput::make('tags')
|
||||
->label('Markierungen')
|
||||
->suggestions(['Stammgast', 'Familie', 'Empfehlung', 'Nicht wieder vermieten']),
|
||||
...static::personalFields(),
|
||||
TextEntry::make('marketing_consent_at')
|
||||
->label('Einwilligung Angebote per E-Mail')
|
||||
->state(fn (?Guest $record): string => $record?->marketing_consent_at ? 'bestätigt am '.$record->marketing_consent_at->format('d.m.Y') : 'keine'),
|
||||
@@ -48,8 +33,33 @@ public static function configure(Schema $schema): Schema
|
||||
->label('Anonymisiert')
|
||||
->dateTime('d.m.Y')
|
||||
->visible(fn (?Guest $record): bool => $record?->anonymized_at !== null),
|
||||
Textarea::make('notes')->label('Notizen')->rows(5),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
/** @return array<TextInput|Select> */
|
||||
public static function contactFields(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('first_name')->label('Vorname')->required()->maxLength(255),
|
||||
TextInput::make('last_name')->label('Nachname')->maxLength(255)->dehydrateStateUsing(fn (?string $state): string => $state ?? ''),
|
||||
TextInput::make('email')->label('E-Mail')->email()->maxLength(255)->dehydrateStateUsing(fn (?string $state): ?string => filled($state) ? $state : null)->helperText('Bei Portalgästen gegebenenfalls noch unbekannt. Keine Ersatzadresse eintragen.'),
|
||||
TextInput::make('phone')->label('Telefon')->tel()->maxLength(50),
|
||||
TextInput::make('street')->label('Straße')->maxLength(255),
|
||||
TextInput::make('postal_code')->label('PLZ')->maxLength(20),
|
||||
TextInput::make('city')->label('Ort')->maxLength(255),
|
||||
Select::make('country')->label('Land')
|
||||
->options(['DE' => 'Deutschland', 'AT' => 'Österreich', 'CH' => 'Schweiz', 'NL' => 'Niederlande', 'DK' => 'Dänemark', 'PL' => 'Polen'])
|
||||
->default('DE')->required(),
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<TagsInput|Textarea> */
|
||||
public static function personalFields(): array
|
||||
{
|
||||
return [
|
||||
TagsInput::make('tags')->label('Markierungen')->suggestions(['Stammgast', 'Familie', 'Empfehlung', 'Nicht wieder vermieten']),
|
||||
Textarea::make('notes')->label('Notizen')->rows(5),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -20,25 +20,26 @@ public static function configure(Table $table): Table
|
||||
$countedBookings = ['bookings' => fn (Builder $query): Builder => $query->whereIn('status', BookingStatus::occupying())];
|
||||
|
||||
return $table
|
||||
->modifyQueryUsing(fn (Builder $query): Builder => $query->withCount('portalStays'))
|
||||
->defaultSort('last_name')
|
||||
->columns([
|
||||
TextColumn::make('last_name')
|
||||
->label('Name')
|
||||
->formatStateUsing(fn (Guest $record): string => "{$record->last_name}, {$record->first_name}")
|
||||
->description(fn (Guest $record): string => $record->email)
|
||||
->formatStateUsing(fn (Guest $record): string => $record->full_name)
|
||||
->description(fn (Guest $record): string => $record->email ?? 'E-Mail unbekannt')
|
||||
->searchable(['first_name', 'last_name', 'email'])
|
||||
->sortable(),
|
||||
TextColumn::make('phone')->label('Telefon')->placeholder('–'),
|
||||
TextColumn::make('city')->label('Ort')->placeholder('–')->toggleable(),
|
||||
TextColumn::make('tags')->label('Markierungen')->badge(),
|
||||
TextColumn::make('bookings_count')->label('Aufenthalte')->counts($countedBookings)->sortable(),
|
||||
TextColumn::make('bookings_sum_total')->label('Umsatz')->sum($countedBookings, 'total')->money('EUR', divideBy: 100, locale: 'de')->sortable(),
|
||||
TextColumn::make('bookings_count')->label('Aufenthalte')->counts($countedBookings)->formatStateUsing(fn (Guest $record, int $state): int => $state + $record->portal_stays_count)->description('Eigene und zugeordnete Portalaufenthalte'),
|
||||
TextColumn::make('bookings_sum_total')->label('Umsatz eigener Buchungen')->sum($countedBookings, 'total')->money('EUR', divideBy: 100, locale: 'de')->sortable(),
|
||||
IconColumn::make('marketing_consent_at')->label('Angebote')->boolean()->getStateUsing(fn (Guest $record): bool => $record->marketing_consent_at !== null),
|
||||
])
|
||||
->filters([
|
||||
Filter::make('returning')
|
||||
->label('Stammgäste (ab 2 Aufenthalten)')
|
||||
->query(fn (Builder $query): Builder => $query->has('bookings', '>=', 2)),
|
||||
->query(fn (Builder $query): Builder => $query->where(fn (Builder $query) => $query->whereHas('bookings', fn (Builder $query) => $query->whereIn('status', BookingStatus::occupying()), '>=', 2)->orWhereHas('portalStays', null, '>=', 2)->orWhere(fn (Builder $query) => $query->whereHas('bookings', fn (Builder $query) => $query->whereIn('status', BookingStatus::occupying()))->whereHas('portalStays')))),
|
||||
TernaryFilter::make('marketing_consent_at')
|
||||
->label('Einwilligung Angebote')
|
||||
->nullable(),
|
||||
|
||||
@@ -28,7 +28,7 @@ public static function configure(Schema $schema): Schema
|
||||
->schema([
|
||||
Builder::make('sections')
|
||||
->hiddenLabel()
|
||||
->blocks(fn (): array => app(SectionRegistry::class)->blocks())
|
||||
->blocks(fn (callable $get): array => app(SectionRegistry::class)->blocks($get('site_id')))
|
||||
->addActionLabel('Baustein hinzufügen')
|
||||
->collapsible()
|
||||
->collapsed()
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalOccupations\Pages;
|
||||
|
||||
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
|
||||
use Filament\Resources\Pages\ManageRecords;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class ManagePortalOccupations extends ManageRecords
|
||||
{
|
||||
protected static string $resource = PortalOccupationResource::class;
|
||||
|
||||
public function getTabs(): array
|
||||
{
|
||||
return [
|
||||
'unclear' => Tab::make('Ungeklärt')->modifyQueryUsing(fn (Builder $query) => $query->whereNull('deleted_at')->unclear()),
|
||||
'all' => Tab::make('Alle Importereignisse')->modifyQueryUsing(fn (Builder $query) => $query->whereNull('deleted_at')),
|
||||
'archive' => Tab::make('Nicht mehr im Feed')->modifyQueryUsing(fn (Builder $query) => $query->onlyTrashed()),
|
||||
];
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalOccupations\Pages;
|
||||
|
||||
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
|
||||
class ViewPortalOccupation extends ViewRecord
|
||||
{
|
||||
protected static string $resource = PortalOccupationResource::class;
|
||||
|
||||
public function getTitle(): string
|
||||
{
|
||||
return $this->record->occupationKind()->getLabel().' · '.$this->record->starts_on->format('d.m.Y').'–'.$this->record->ends_on->format('d.m.Y');
|
||||
}
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return PortalOccupationResource::occupationActions();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalOccupations;
|
||||
|
||||
use App\Actions\ClassifyPortalOccupation;
|
||||
use App\Enums\OccupationKind;
|
||||
use App\Filament\Actions\AssignGuestAction;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Filament\Resources\Guests\GuestResource;
|
||||
use App\Filament\Resources\PortalOccupations\Pages\ManagePortalOccupations;
|
||||
use App\Filament\Resources\PortalOccupations\Pages\ViewPortalOccupation;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use UnitEnum;
|
||||
|
||||
class PortalOccupationResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = BlockedPeriod::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedQuestionMarkCircle;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $navigationLabel = 'Ungeklärte Belegungen';
|
||||
|
||||
protected static ?string $modelLabel = 'Portalbelegung';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Portalbelegungen & Klärung';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
return parent::getEloquentQuery()->withTrashed()->whereIn('source', ['channel', 'email'])->with(['guest', 'channel', 'originChannel', 'property', 'linkedBooking.guest', 'canonicalBlock.guest']);
|
||||
}
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$count = BlockedPeriod::query()->unclear()->count();
|
||||
|
||||
return $count ? (string) $count : null;
|
||||
}
|
||||
|
||||
public static function getNavigationBadgeColor(): string
|
||||
{
|
||||
return 'warning';
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table->description('Unbekannte Belegungen und mögliche Mehrfachdarstellungen persönlich klären. Auch ungeklärte führende Einträge halten ihre Nächte belegt.')
|
||||
->defaultSort('starts_on')->columns([
|
||||
TextColumn::make('starts_on')->label('Anreise / Beginn')->date('d.m.Y')->sortable(),
|
||||
TextColumn::make('ends_on')->label('Abreise / Ende')->date('d.m.Y'),
|
||||
TextColumn::make('business_kind')->label('Einordnung')->state(fn (BlockedPeriod $record): string => $record->is_representation ? 'Kalenderspiegelung' : $record->occupationKind()->getLabel())->badge(),
|
||||
TextColumn::make('guest_name')->label('Gast / Namensinformation')->state(fn (BlockedPeriod $record): ?string => $record->guestName())->placeholder('Zuordnung offen')
|
||||
->description(fn (BlockedPeriod $record): string => $record->guest_id ? 'Gast zugeordnet' : 'Keine bestätigte Gastzuordnung'),
|
||||
TextColumn::make('channel.name')->label('Importkanal'),
|
||||
TextColumn::make('property.name')->label('Wohnung')->toggleable(),
|
||||
TextColumn::make('needs_review')->label('Prüffall')->formatStateUsing(fn (bool $state): string => $state ? 'Bitte prüfen' : '–')->description(fn (BlockedPeriod $record): ?string => $record->review_note),
|
||||
])->recordActions([ViewAction::make(), ActionGroup::make(static::occupationActions())->label('Weitere Aktionen')]);
|
||||
}
|
||||
|
||||
public static function occupationActions(): array
|
||||
{
|
||||
return [
|
||||
AssignGuestAction::make(),
|
||||
static::classificationAction(),
|
||||
...BlockedPeriodResource::portalActions(),
|
||||
];
|
||||
}
|
||||
|
||||
public static function classificationAction(): Action
|
||||
{
|
||||
return Action::make('classify')->label('Belegungsart / Zweck bearbeiten')
|
||||
->visible(fn (BlockedPeriod $record): bool => in_array($record->source, ['channel', 'email'], true) && ! $record->is_representation && ! $record->trashed())
|
||||
->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false)
|
||||
->modalDescription('Nur bekannte Sachverhalte bestätigen. Die Einordnung ändert keine Termine, hebt keine Sperre auf und führt keine Ereignisse automatisch zusammen. Überschneidungen bleiben gesonderte Prüffälle.')
|
||||
->fillForm(fn (BlockedPeriod $record): array => ['occupation_kind' => $record->occupationKind()->value, 'origin_channel_id' => $record->is_private ? 'private' : $record->origin_channel_id, 'block_purpose' => $record->block_purpose?->value, 'block_note' => $record->block_note])
|
||||
->schema([
|
||||
Select::make('occupation_kind')->label('Fachliche Einordnung')->options(OccupationKind::class)->required()->live(),
|
||||
Section::make('Zweck der Sperrzeit')->columns(2)->schema(BlockedPeriodResource::purposeFields())
|
||||
->visible(fn (Get $get): bool => in_array($get('occupation_kind'), [OccupationKind::Block, OccupationKind::Block->value], true)),
|
||||
Select::make('origin_channel_id')->label('Buchungskanal, sofern persönlich bekannt')->placeholder('Unbekannt')
|
||||
->helperText('Privat bezeichnet den fachlichen Ursprung. Der Importkanal bleibt als Kalenderquelle erhalten.')
|
||||
->options(fn (BlockedPeriod $record): array => ['private' => 'Privat'] + Channel::query()->where('property_id', $record->property_id)->pluck('name', 'id')->all()),
|
||||
])->action(function (BlockedPeriod $record, array $data, ClassifyPortalOccupation $classify): void {
|
||||
$private = ($data['origin_channel_id'] ?? null) === 'private';
|
||||
$classify->handle($record, $data['occupation_kind'] instanceof OccupationKind ? $data['occupation_kind'] : OccupationKind::from($data['occupation_kind']), ! $private && filled($data['origin_channel_id'] ?? null) ? (int) $data['origin_channel_id'] : null, [
|
||||
'block_purpose' => $data['block_purpose'] ?? null, 'block_note' => $data['block_note'] ?? null, 'is_private' => $private,
|
||||
]);
|
||||
$record->refresh();
|
||||
Notification::make()->title('Belegungsart gespeichert')->success()->send();
|
||||
});
|
||||
}
|
||||
|
||||
public static function infolist(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
Section::make('Portalbelegung')->columns(3)->schema([
|
||||
TextEntry::make('property.name')->label('Wohnung'),
|
||||
TextEntry::make('starts_on')->label('Anreise / Beginn')->date('d.m.Y'),
|
||||
TextEntry::make('ends_on')->label('Abreise / erster freier Tag')->date('d.m.Y'),
|
||||
TextEntry::make('kind')->label('Einordnung')->state(fn (BlockedPeriod $record): string => $record->is_representation ? 'Kalenderspiegelung' : $record->occupationKind()->getLabel()),
|
||||
TextEntry::make('booking_channel')->label('Buchungskanal')->state(fn (BlockedPeriod $record): string => $record->bookingChannelLabel()),
|
||||
TextEntry::make('block_description')->label('Zweck / Grund der Sperrzeit')->state(fn (BlockedPeriod $record): ?string => $record->blockDescription())
|
||||
->visible(fn (BlockedPeriod $record): bool => $record->occupationKind() === OccupationKind::Block)->placeholder('Noch nicht angegeben'),
|
||||
TextEntry::make('channel.name')->label('Importiert über'),
|
||||
TextEntry::make('guest_name')->label('Gast / Namensinformation')->state(fn (BlockedPeriod $record): ?string => $record->guestName())->placeholder('Unbekannt')
|
||||
->url(fn (BlockedPeriod $record): ?string => $record->assignedGuest() ? GuestResource::getUrl('edit', ['record' => $record->assignedGuest()->id]) : null),
|
||||
TextEntry::make('guest_email')->label('E-Mail')->state(fn (BlockedPeriod $record): ?string => $record->assignedGuest()?->email)->placeholder('Unbekannt'),
|
||||
TextEntry::make('assignment')->label('Gastzuordnung')->state(fn (BlockedPeriod $record): string => $record->is_representation ? 'Wird an der führenden Belegung gepflegt' : ($record->guest_id ? 'Persönlich zugeordnet' : 'Noch offen; Namensfragment allein ist kein Identitätsnachweis')),
|
||||
TextEntry::make('calendar_state')->label('Kalenderstatus')->state(fn (BlockedPeriod $record): string => $record->trashed() ? 'Nicht mehr im Feed – keine Aussage über den Stornogrund' : ($record->is_representation ? 'Weitere Darstellung einer führenden Belegung' : 'Belegt den Zeitraum')),
|
||||
TextEntry::make('leading_record')->label('Führende Belegung')->state(fn (BlockedPeriod $record): string => $record->linkedBooking ? 'Buchung '.$record->linkedBooking->reference : ($record->canonical_block_id ? 'Kalenderbelegung #'.$record->canonical_block_id : 'Dieser Eintrag'))
|
||||
->url(fn (BlockedPeriod $record): ?string => $record->linked_booking_id ? BookingResource::getUrl('view', ['record' => $record->linked_booking_id]) : ($record->canonical_block_id ? static::getUrl('view', ['record' => $record->canonical_block_id]) : null)),
|
||||
TextEntry::make('representation_assignment')->label('Zuordnung der Kalenderdarstellung')
|
||||
->state(fn (BlockedPeriod $record): string => $record->representation_automatic ? 'Automatisch; wird bei jedem Abgleich erneut geprüft' : 'Persönlich bestätigt')
|
||||
->visible(fn (BlockedPeriod $record): bool => $record->is_representation),
|
||||
TextEntry::make('review_note')->label('Prüfhinweis')->placeholder('Kein zusätzlicher Prüfhinweis')->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Kalenderquelle')->schema([
|
||||
TextEntry::make('external_uid')->label('Externe Ereignis-ID'),
|
||||
TextEntry::make('import_note')->hiddenLabel()->state('Kalenderdaten liefern Belegungszeiträume. Preis, Personenanzahl, Zahlungsstand und Vertragsstatus sind daraus nicht gesichert bekannt.'),
|
||||
TextEntry::make('ical_raw')->label('Originalereignis')->placeholder('Keine iCal-Originaldaten vorhanden')->wrap()->extraAttributes(['style' => 'white-space:pre-wrap;overflow-wrap:anywhere']),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return ['index' => ManagePortalOccupations::route('/'), 'view' => ViewPortalOccupation::route('/{record}')];
|
||||
}
|
||||
}
|
||||
+12
-3
@@ -2,11 +2,14 @@
|
||||
|
||||
namespace App\Filament\Resources\Properties\RelationManagers;
|
||||
|
||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
|
||||
use App\Models\BlockedPeriod;
|
||||
use Filament\Actions\CreateAction;
|
||||
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\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Schema;
|
||||
@@ -42,19 +45,24 @@ public function form(Schema $schema): Schema
|
||||
->placeholder('z. B. Eigennutzung, Renovierung')
|
||||
->maxLength(255)
|
||||
->columnSpanFull(),
|
||||
...BlockedPeriodResource::purposeFields(),
|
||||
Select::make('is_private')->label('Buchungskanal')->options([0 => 'Nicht angegeben', 1 => 'Privat'])
|
||||
->default(0)->formatStateUsing(fn (mixed $state): int => (int) $state)->required(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->modifyQueryUsing(fn (Builder $query): Builder => $query->explicitBlocks()->occupying())
|
||||
->recordTitleAttribute('reason')
|
||||
->description('Manuelle Sperren (z. B. Eigennutzung). Belegungen aus Portalen erscheinen hier später automatisch.')
|
||||
->description('Ausdrückliche Sperrzeiten. Alle Belegungen stehen im Belegungsplan; Portalreservierungen unter Anfragen & Buchungen.')
|
||||
->defaultSort('starts_on')
|
||||
->columns([
|
||||
TextColumn::make('starts_on')->label('Von')->date('D, d.m.Y'),
|
||||
TextColumn::make('ends_on')->label('Bis')->date('D, d.m.Y'),
|
||||
TextColumn::make('reason')->label('Grund')->placeholder('–'),
|
||||
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('source')->label('Quelle'),
|
||||
])
|
||||
->filters([
|
||||
@@ -64,10 +72,11 @@ public function table(Table $table): Table
|
||||
->query(fn (Builder $query): Builder => $query->whereDate('ends_on', '>=', today())),
|
||||
])
|
||||
->headerActions([
|
||||
CreateAction::make(),
|
||||
CreateAction::make()->mutateDataUsing(fn (array $data): array => [...$data, 'source' => 'manual']),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
|
||||
PortalOccupationResource::classificationAction(),
|
||||
DeleteAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -2,159 +2,29 @@
|
||||
|
||||
namespace App\Filament\Resources\Properties\RelationManagers;
|
||||
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Channels\ChannelRegistry;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Infolists\Components\RepeatableEntry;
|
||||
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use App\Filament\Resources\Channels\Schemas\ChannelForm;
|
||||
use App\Filament\Resources\Channels\Tables\ChannelsTable;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Components\Group;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class ChannelsRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'channels';
|
||||
|
||||
protected static ?string $title = 'Portale & Kanäle';
|
||||
protected static ?string $title = 'Kalenderabgleich (iCal)';
|
||||
|
||||
protected static ?string $modelLabel = 'Portal';
|
||||
protected static ?string $modelLabel = 'iCal-Verbindung';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Portale';
|
||||
protected static ?string $pluralModelLabel = 'iCal-Verbindungen';
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
$registry = app(ChannelRegistry::class);
|
||||
|
||||
return $schema
|
||||
->columns(2)
|
||||
->components([
|
||||
TextInput::make('name')
|
||||
->label('Name')
|
||||
->placeholder('z. B. FeWo-direkt')
|
||||
->required()
|
||||
->maxLength(100),
|
||||
Select::make('connector')
|
||||
->label('Anbindung')
|
||||
->options($registry->options())
|
||||
->default('ical')
|
||||
->live()
|
||||
->required(),
|
||||
Group::make()
|
||||
->columnSpanFull()
|
||||
->schema(fn (Get $get): array => filled($get('connector')) ? $registry->connectors()[$get('connector')]::settingsSchema() : []),
|
||||
TextEntry::make('export_url')
|
||||
->label('Unsere Kalender-Adresse für dieses Portal')
|
||||
->helperText('Diese Adresse im Portal unter „Kalender importieren“ eintragen. Sie enthält alle Belegungen außer denen dieses Portals.')
|
||||
->state(fn (?Channel $record): ?string => $record?->exportUrl())
|
||||
->copyable()
|
||||
->visible(fn (?Channel $record): bool => $record !== null)
|
||||
->columnSpanFull(),
|
||||
TextInput::make('settings.email_senders')
|
||||
->label('Absender der Buchungs-E-Mails (Schnellerkennung)')
|
||||
->helperText('Komma-getrennt, z. B. „fewo-direkt.de, vrbo.com“. Buchungsbestätigungen dieser Absender werden sofort gesperrt.')
|
||||
->maxLength(500)
|
||||
->columnSpanFull(),
|
||||
Toggle::make('requires_manual_blocking')
|
||||
->label('Zusätzlich von Hand sperren (Sofortbuchung)')
|
||||
->helperText('Bei jeder Belegung über andere Wege entsteht eine Aufgabe „Im Portal sperren“ – für Portale, die unseren Kalender zu selten abholen.')
|
||||
->live()
|
||||
->columnSpanFull(),
|
||||
TextInput::make('manage_url')
|
||||
->label('Link zum Kalender im Vermieterbereich')
|
||||
->url()
|
||||
->maxLength(2048)
|
||||
->visible(fn (Get $get): bool => (bool) $get('requires_manual_blocking'))
|
||||
->columnSpanFull(),
|
||||
Toggle::make('is_active')
|
||||
->label('Aktiv')
|
||||
->default(true),
|
||||
]);
|
||||
return ChannelForm::configure($schema);
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('name')
|
||||
->description('Unser System ist führend: Belegungen der Portale werden alle 5 Minuten eingelesen, jedes Portal erhält einen eigenen Kalender mit allen übrigen Belegungen.')
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Portal')->weight('medium'),
|
||||
TextColumn::make('status')
|
||||
->label('Status')
|
||||
->badge()
|
||||
->state(fn (Channel $record): string => match (true) {
|
||||
! $record->is_active => 'Inaktiv',
|
||||
! $record->importsOccupations() => 'Nur Export',
|
||||
$record->last_error !== null => 'Fehler',
|
||||
$record->isStale() => 'Veraltet',
|
||||
default => 'OK',
|
||||
})
|
||||
->color(fn (string $state): string => match ($state) {
|
||||
'OK' => 'success',
|
||||
'Fehler', 'Veraltet' => 'danger',
|
||||
default => 'gray',
|
||||
})
|
||||
->tooltip(fn (Channel $record): ?string => $record->last_error),
|
||||
TextColumn::make('last_success_at')->label('Letzter Abgleich')->since()->placeholder('–'),
|
||||
TextColumn::make('requires_manual_blocking')
|
||||
->label('Handpflege')
|
||||
->formatStateUsing(fn (bool $state): string => $state ? 'ja' : '–'),
|
||||
])
|
||||
->headerActions([
|
||||
CreateAction::make(),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('sync')
|
||||
->label('Jetzt abgleichen')
|
||||
->icon(Heroicon::OutlinedArrowPath)
|
||||
->visible(fn (Channel $record): bool => $record->importsOccupations())
|
||||
->action(function (Channel $record, SyncChannel $syncChannel): void {
|
||||
$log = $syncChannel->handle($record);
|
||||
|
||||
$log->successful
|
||||
? Notification::make()->title("{$log->events} Belegungen eingelesen")->body("Neu: {$log->added}, geändert: {$log->changed}, entfernt: {$log->removed}, Konflikte: {$log->conflicts}")->success()->send()
|
||||
: Notification::make()->title('Abgleich fehlgeschlagen')->body($log->message)->danger()->send();
|
||||
}),
|
||||
Action::make('logs')
|
||||
->label('Protokoll')
|
||||
->icon(Heroicon::OutlinedListBullet)
|
||||
->color('gray')
|
||||
->modalSubmitAction(false)
|
||||
->modalCancelActionLabel('Schließen')
|
||||
->schema([
|
||||
RepeatableEntry::make('recentLogs')
|
||||
->hiddenLabel()
|
||||
->state(fn (Channel $record): array => $record->syncLogs()->limit(30)->get()->map(fn (ChannelSyncLog $log): array => [
|
||||
'time' => $log->created_at->format('d.m. H:i'),
|
||||
'result' => $log->successful ? "✓ {$log->events} Belegungen (+{$log->added} ~{$log->changed} -{$log->removed})" : '✗ '.$log->message,
|
||||
'conflicts' => $log->conflicts ?: '',
|
||||
])->all())
|
||||
->table([
|
||||
TableColumn::make('Zeit'),
|
||||
TableColumn::make('Ergebnis'),
|
||||
TableColumn::make('Konflikte'),
|
||||
])
|
||||
->schema([
|
||||
TextEntry::make('time'),
|
||||
TextEntry::make('result'),
|
||||
TextEntry::make('conflicts'),
|
||||
]),
|
||||
]),
|
||||
EditAction::make(),
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
return ChannelsTable::configure($table, $this->getOwnerRecord());
|
||||
}
|
||||
}
|
||||
@@ -68,12 +68,12 @@ public static function configure(Schema $schema): Schema
|
||||
SpatieMediaLibraryFileUpload::make('logo')
|
||||
->label('Logo')
|
||||
->collection(Site::BRAND_LOGO)
|
||||
->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp'])
|
||||
->helperText('SVG bevorzugt – bleibt in jeder Größe scharf.'),
|
||||
->acceptedFileTypes(['image/png', 'image/webp'])
|
||||
->helperText('PNG oder WebP. SVG-Dateien werden nur aus geprüften Quellen übernommen.'),
|
||||
SpatieMediaLibraryFileUpload::make('favicon')
|
||||
->label('Favicon')
|
||||
->collection(Site::BRAND_FAVICON)
|
||||
->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/x-icon'])
|
||||
->acceptedFileTypes(['image/png', 'image/x-icon'])
|
||||
->helperText('Das kleine Zeichen im Browser-Tab.'),
|
||||
SpatieMediaLibraryFileUpload::make('document_logo')
|
||||
->label('Logo für E-Mail und Vertrag')
|
||||
|
||||
@@ -66,7 +66,7 @@ private function occupancy(CarbonImmutable $from, CarbonImmutable $until): int
|
||||
$nights = [];
|
||||
$periods = Booking::query()->whereIn('status', BookingStatus::occupying())->overlapping($from, $until)->get(['arrival', 'departure'])
|
||||
->map(fn (Booking $booking): array => [$booking->arrival, $booking->departure])
|
||||
->concat(BlockedPeriod::query()->whereNotNull('channel_id')->overlapping($from, $until)->get(['starts_on', 'ends_on'])
|
||||
->concat(BlockedPeriod::query()->occupying()->whereNotNull('channel_id')->overlapping($from, $until)->get(['starts_on', 'ends_on'])
|
||||
->map(fn (BlockedPeriod $block): array => [$block->starts_on, $block->ends_on]));
|
||||
|
||||
foreach ($periods as [$start, $end]) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
use App\Actions\MonitorChannels;
|
||||
use App\Actions\ProcessPortalMail;
|
||||
use App\Channels\ICal\ICalFeed;
|
||||
use App\Channels\ICal\ICalExport;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Channels\Mail\PortalMail;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
@@ -23,16 +23,23 @@
|
||||
*/
|
||||
class ChannelController extends Controller
|
||||
{
|
||||
public function feed(string $token, ICalFeed $feed): Response
|
||||
public function feed(string $token, ICalExport $feed, Request $request): Response
|
||||
{
|
||||
$channel = Channel::query()->where('export_token', $token)->where('is_active', true)->firstOrFail();
|
||||
$channel = Channel::query()->where(fn ($query) => $query->where('export_token', $token)
|
||||
->orWhere(fn ($previous) => $previous->where('previous_export_token', $token)->where('previous_export_token_expires_at', '>', now())))->firstOrFail();
|
||||
|
||||
abort_unless($channel->servesItsLandlord(), 404);
|
||||
|
||||
return response($feed->build($channel), 200, [
|
||||
$body = $feed->build($channel, $request->method(), $request->userAgent());
|
||||
if ($body === null) {
|
||||
return response('Der Export ist pausiert; es liegt noch kein gültiger Kalenderstand vor.', 503, ['Retry-After' => '300', 'Cache-Control' => 'no-store']);
|
||||
}
|
||||
|
||||
return response($body, 200, [
|
||||
'Content-Type' => 'text/calendar; charset=utf-8',
|
||||
'Content-Disposition' => 'inline; filename="belegung.ics"',
|
||||
'Cache-Control' => 'no-cache, max-age=0',
|
||||
'X-Fewo-Export-State' => $channel->exportsOccupations() ? 'live' : 'frozen',
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,28 +2,37 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\BlockedPeriodPurpose;
|
||||
use App\Enums\OccupationKind;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use App\Models\Concerns\HasChannelProvenance;
|
||||
use App\Observers\BlockedPeriodObserver;
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\BlockedPeriodFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
/**
|
||||
* Dates that are not bookable (own use, maintenance, bookings from portals).
|
||||
* Like bookings, ends_on is the first free day again.
|
||||
*/
|
||||
#[ObservedBy(BlockedPeriodObserver::class)]
|
||||
#[Fillable(['property_id', 'channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid'])]
|
||||
#[Hidden(['ical_properties', 'ical_raw', 'ical_interpretation'])]
|
||||
#[Fillable(['property_id', 'channel_id', 'origin_channel_id', 'guest_id', 'occupation_kind', 'block_purpose', 'block_note', 'is_private', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid', 'needs_review', 'review_note', 'missing_imports', 'is_representation', 'canonical_block_id', 'linked_booking_id', 'export_approved', 'reviewed_at'])]
|
||||
class BlockedPeriod extends Model
|
||||
{
|
||||
/** @use HasFactory<BlockedPeriodFactory> */
|
||||
use BelongsToTenant, HasFactory;
|
||||
use BelongsToTenant, HasChannelProvenance, HasFactory, SoftDeletes;
|
||||
|
||||
protected $attributes = ['is_representation' => false, 'representation_automatic' => false, 'export_approved' => true];
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
@@ -33,8 +42,21 @@ class BlockedPeriod extends Model
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'block_purpose' => BlockedPeriodPurpose::class,
|
||||
'is_private' => 'boolean',
|
||||
'occupation_kind' => OccupationKind::class,
|
||||
'starts_on' => 'immutable_date',
|
||||
'ends_on' => 'immutable_date',
|
||||
'needs_review' => 'boolean',
|
||||
'missing_imports' => 'integer',
|
||||
'is_representation' => 'boolean',
|
||||
'representation_automatic' => 'boolean',
|
||||
'export_approved' => 'boolean',
|
||||
'reviewed_at' => 'immutable_datetime',
|
||||
'ical_properties' => 'encrypted:array',
|
||||
'ical_raw' => 'encrypted',
|
||||
'ical_interpretation' => 'encrypted:array',
|
||||
'leading_priority' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -54,6 +76,119 @@ public function channel(): BelongsTo
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Channel, $this> */
|
||||
public function originChannel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<BlockedPeriod, $this> */
|
||||
public function canonicalBlock(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(self::class, 'canonical_block_id')->withTrashed();
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Booking, $this> */
|
||||
public function linkedBooking(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Booking::class, 'linked_booking_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Guest, $this> */
|
||||
public function guest(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Guest::class);
|
||||
}
|
||||
|
||||
public function occupationKind(): OccupationKind
|
||||
{
|
||||
if ($this->source === 'manual') {
|
||||
return OccupationKind::Block;
|
||||
}
|
||||
|
||||
return $this->occupation_kind ?? ($this->ical_event_type === 'portal_reservation' ? OccupationKind::Reservation : OccupationKind::Unknown);
|
||||
}
|
||||
|
||||
public function guestName(): ?string
|
||||
{
|
||||
if ($this->is_representation) {
|
||||
return $this->linkedBooking?->guest?->full_name ?? $this->canonicalBlock?->guestName();
|
||||
}
|
||||
|
||||
return $this->guest?->full_name ?? ($this->ical_interpretation['fields']['guest_full_name'] ?? $this->ical_interpretation['fields']['guest_first_name'] ?? null);
|
||||
}
|
||||
|
||||
public function bookingChannelLabel(): string
|
||||
{
|
||||
if ($this->is_representation) {
|
||||
return $this->canonicalBlock?->bookingChannelLabel() ?? $this->linkedBooking?->bookingChannelLabel() ?? 'Führende Belegung nicht verfügbar';
|
||||
}
|
||||
|
||||
return $this->is_private ? 'Privat' : ($this->originChannel?->name ?? $this->channel?->name ?? ($this->source === 'manual' ? 'Eigene Sperre' : 'Ursprung unbekannt'));
|
||||
}
|
||||
|
||||
public function blockDescription(): ?string
|
||||
{
|
||||
if ($this->occupationKind() !== OccupationKind::Block) {
|
||||
return $this->reason;
|
||||
}
|
||||
|
||||
return collect([$this->block_purpose?->getLabel(), $this->block_note])->filter()->implode(' · ') ?: $this->reason;
|
||||
}
|
||||
|
||||
public function assignedGuest(): ?Guest
|
||||
{
|
||||
return $this->is_representation ? ($this->linkedBooking?->guest ?? $this->canonicalBlock?->assignedGuest()) : $this->guest;
|
||||
}
|
||||
|
||||
/** @return HasMany<BlockedPeriod, $this> */
|
||||
public function channelRepresentations(): HasMany
|
||||
{
|
||||
return $this->hasMany(self::class, 'canonical_block_id');
|
||||
}
|
||||
|
||||
/** @param Builder<BlockedPeriod> $query
|
||||
* @return Builder<BlockedPeriod>
|
||||
*/
|
||||
#[Scope]
|
||||
protected function reservations(Builder $query): Builder
|
||||
{
|
||||
return $query->whereIn('source', ['channel', 'email'])->where(fn (Builder $query) => $query
|
||||
->where('occupation_kind', OccupationKind::Reservation)
|
||||
->orWhere(fn (Builder $query) => $query->whereNull('occupation_kind')->where('ical_event_type', 'portal_reservation')));
|
||||
}
|
||||
|
||||
/** @param Builder<BlockedPeriod> $query
|
||||
* @return Builder<BlockedPeriod>
|
||||
*/
|
||||
#[Scope]
|
||||
protected function explicitBlocks(Builder $query): Builder
|
||||
{
|
||||
return $query->where(fn (Builder $query) => $query->where('source', 'manual')->orWhere('occupation_kind', OccupationKind::Block));
|
||||
}
|
||||
|
||||
/** @param Builder<BlockedPeriod> $query
|
||||
* @return Builder<BlockedPeriod>
|
||||
*/
|
||||
#[Scope]
|
||||
protected function unclear(Builder $query): Builder
|
||||
{
|
||||
return $query->whereIn('source', ['channel', 'email'])->where(fn (Builder $query) => $query
|
||||
->where('needs_review', true)
|
||||
->orWhere(fn (Builder $query) => $query->where('is_representation', false)->where(fn (Builder $query) => $query
|
||||
->where('occupation_kind', OccupationKind::Unknown)
|
||||
->orWhere(fn (Builder $query) => $query->whereNull('occupation_kind')->where(fn (Builder $query) => $query->whereNull('ical_event_type')->orWhere('ical_event_type', '!=', 'portal_reservation'))))));
|
||||
}
|
||||
|
||||
/** @param Builder<BlockedPeriod> $query
|
||||
* @return Builder<BlockedPeriod>
|
||||
*/
|
||||
#[Scope]
|
||||
protected function occupying(Builder $query): Builder
|
||||
{
|
||||
return $query->where('is_representation', false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<BlockedPeriod> $query
|
||||
* @return Builder<BlockedPeriod>
|
||||
|
||||
+41
-1
@@ -5,6 +5,7 @@
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ReferralSource;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use App\Models\Concerns\HasChannelProvenance;
|
||||
use App\Observers\BookingObserver;
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\BookingFactory;
|
||||
@@ -28,6 +29,8 @@
|
||||
'guest_id',
|
||||
'status',
|
||||
'source',
|
||||
'import_channel_id',
|
||||
'origin_channel_id',
|
||||
'referral_source',
|
||||
'utm_source',
|
||||
'utm_medium',
|
||||
@@ -66,7 +69,14 @@
|
||||
class Booking extends Model
|
||||
{
|
||||
/** @use HasFactory<BookingFactory> */
|
||||
use BelongsToTenant, HasFactory;
|
||||
use BelongsToTenant, HasChannelProvenance, HasFactory;
|
||||
|
||||
public const DIRECT_SOURCES = ['website', 'manual', 'phone', 'direct', 'email'];
|
||||
|
||||
public function isDirect(): bool
|
||||
{
|
||||
return $this->import_channel_id === null && $this->origin_channel_id === null && in_array($this->source, self::DIRECT_SOURCES, true);
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
@@ -147,6 +157,36 @@ public function guest(): BelongsTo
|
||||
return $this->belongsTo(Guest::class);
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Channel, $this> */
|
||||
public function originChannel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class, 'origin_channel_id');
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Channel, $this> */
|
||||
public function importChannel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class, 'import_channel_id');
|
||||
}
|
||||
|
||||
/** @return HasMany<BlockedPeriod, $this> */
|
||||
public function channelRepresentations(): HasMany
|
||||
{
|
||||
return $this->hasMany(BlockedPeriod::class, 'linked_booking_id');
|
||||
}
|
||||
|
||||
public function bookingChannelLabel(): string
|
||||
{
|
||||
return $this->originChannel?->name ?? $this->importChannel?->name ?? match ($this->source) {
|
||||
'website' => 'Eigene Webseite',
|
||||
'manual' => 'Manuell / direkt',
|
||||
'phone' => 'Telefon',
|
||||
'email' => 'E-Mail',
|
||||
'direct' => 'Direkt',
|
||||
default => $this->source,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Bookings that currently occupy their dates: confirmed ones and requests/offers whose hold has not expired.
|
||||
*
|
||||
|
||||
+51
-4
@@ -4,6 +4,10 @@
|
||||
|
||||
use App\Channels\ChannelRegistry;
|
||||
use App\Channels\Contracts\ChannelConnector;
|
||||
use App\Enums\ChannelBookingModel;
|
||||
use App\Enums\ChannelEchoBehavior;
|
||||
use App\Enums\ChannelExportMode;
|
||||
use App\Enums\ChannelStatus;
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
@@ -22,18 +26,31 @@
|
||||
* A sales channel (portal) of a property. Our system leads: occupations are imported from the
|
||||
* channel and every channel gets its own export feed without its own occupations.
|
||||
*/
|
||||
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url'])]
|
||||
#[Hidden(['export_token'])]
|
||||
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at'])]
|
||||
#[Hidden(['export_token', 'previous_export_token', 'export_snapshot', 'settings', 'ical_analysis'])]
|
||||
class Channel extends Model
|
||||
{
|
||||
/** @use HasFactory<ChannelFactory> */
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
protected $attributes = [
|
||||
'status' => 'setup', 'booking_model' => 'mixed', 'import_enabled' => false,
|
||||
'export_enabled' => false, 'export_mode' => 'test',
|
||||
'echo_behavior' => 'unverified',
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (Channel $channel): void {
|
||||
$channel->export_token ??= Str::random(48);
|
||||
});
|
||||
static::saving(function (Channel $channel): void {
|
||||
if ($channel->isDirty('status')) {
|
||||
$channel->is_active = $channel->status === ChannelStatus::Active;
|
||||
} elseif ($channel->isDirty('is_active')) {
|
||||
$channel->status = $channel->is_active ? ChannelStatus::Active : ChannelStatus::Paused;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -45,6 +62,24 @@ protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'settings' => 'array',
|
||||
'ical_analysis' => 'encrypted:array',
|
||||
'ical_analyzed_at' => 'immutable_datetime',
|
||||
'ical_rules' => 'array',
|
||||
'ical_active_rules' => 'array',
|
||||
'ical_export_mapping' => 'array',
|
||||
'ical_export_names' => 'boolean',
|
||||
'status' => ChannelStatus::class,
|
||||
'booking_model' => ChannelBookingModel::class,
|
||||
'echo_behavior' => ChannelEchoBehavior::class,
|
||||
'portal_verified_at' => 'immutable_datetime',
|
||||
'export_mode' => ChannelExportMode::class,
|
||||
'import_enabled' => 'boolean',
|
||||
'export_enabled' => 'boolean',
|
||||
'sync_warnings' => 'array',
|
||||
'last_error_at' => 'immutable_datetime',
|
||||
'export_snapshot_at' => 'immutable_datetime',
|
||||
'last_export_requested_at' => 'immutable_datetime',
|
||||
'previous_export_token_expires_at' => 'immutable_datetime',
|
||||
'is_active' => 'boolean',
|
||||
'requires_manual_blocking' => 'boolean',
|
||||
'last_synced_at' => 'immutable_datetime',
|
||||
@@ -77,6 +112,12 @@ public function syncLogs(): HasMany
|
||||
return $this->hasMany(ChannelSyncLog::class)->latest('id');
|
||||
}
|
||||
|
||||
/** @return HasMany<ChannelExportRequest, $this> */
|
||||
public function exportRequests(): HasMany
|
||||
{
|
||||
return $this->hasMany(ChannelExportRequest::class)->latest('requested_at')->latest('id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<ChannelTask, $this>
|
||||
*/
|
||||
@@ -92,7 +133,7 @@ public function tasks(): HasMany
|
||||
#[Scope]
|
||||
protected function active(Builder $query): Builder
|
||||
{
|
||||
return $query->where('is_active', true);
|
||||
return $query->where('is_active', true)->where('status', ChannelStatus::Active);
|
||||
}
|
||||
|
||||
public function connector(): ChannelConnector
|
||||
@@ -102,7 +143,13 @@ public function connector(): ChannelConnector
|
||||
|
||||
public function importsOccupations(): bool
|
||||
{
|
||||
return $this->is_active && $this->servesItsLandlord() && $this->connector()->canImport($this);
|
||||
return $this->is_active && $this->status === ChannelStatus::Active && $this->import_enabled
|
||||
&& $this->servesItsLandlord() && $this->connector()->canImport($this);
|
||||
}
|
||||
|
||||
public function exportsOccupations(): bool
|
||||
{
|
||||
return $this->is_active && $this->status === ChannelStatus::Active && $this->export_enabled && $this->servesItsLandlord();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable(['channel_id', 'requested_at', 'method', 'user_agent', 'response_status', 'export_state'])]
|
||||
class ChannelExportRequest extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
/** @return array<string, string> */
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['requested_at' => 'immutable_datetime', 'response_status' => 'integer'];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Channel, $this> */
|
||||
public function channel(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Channel::class);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
#[Fillable(['channel_id', 'successful', 'events', 'added', 'changed', 'removed', 'conflicts', 'message', 'duration_ms'])]
|
||||
#[Fillable(['channel_id', 'successful', 'events', 'added', 'changed', 'removed', 'conflicts', 'message', 'duration_ms', 'warnings'])]
|
||||
class ChannelSyncLog extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
@@ -23,6 +23,7 @@ protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'successful' => 'boolean',
|
||||
'warnings' => 'array',
|
||||
'created_at' => 'immutable_datetime',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
@@ -61,6 +62,14 @@ protected function open(Builder $query): Builder
|
||||
|
||||
public function complete(string $completedBy): void
|
||||
{
|
||||
if ($this->status !== ChannelTaskStatus::Open) {
|
||||
return;
|
||||
}
|
||||
if ($this->action === ChannelTaskAction::Unblock && ! app(AvailabilityChecker::class)->isAvailable($this->channel->property, $this->starts_on, $this->ends_on)) {
|
||||
$this->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Aktuell belegt – Entsperraufgabe nicht mehr gültig.']);
|
||||
|
||||
return;
|
||||
}
|
||||
$this->update([
|
||||
'status' => ChannelTaskStatus::Done,
|
||||
'completed_by' => $completedBy,
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Concerns;
|
||||
|
||||
use App\Models\Channel;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
trait HasChannelProvenance
|
||||
{
|
||||
public static function bootHasChannelProvenance(): void
|
||||
{
|
||||
static::saving(function (Model $model): void {
|
||||
foreach (['channel_id', 'import_channel_id', 'origin_channel_id'] as $field) {
|
||||
$id = $model->getAttribute($field);
|
||||
if ($id !== null && ! Channel::withoutGlobalScope('tenant')->whereKey($id)->where('property_id', $model->property_id)->exists()) {
|
||||
throw ValidationException::withMessages([$field => 'Der Kanal muss zur selben Wohnung gehören.']);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -42,12 +42,18 @@ public function bookings(): HasMany
|
||||
return $this->hasMany(Booking::class)->latest('arrival');
|
||||
}
|
||||
|
||||
/** @return HasMany<BlockedPeriod, $this> */
|
||||
public function portalStays(): HasMany
|
||||
{
|
||||
return $this->hasMany(BlockedPeriod::class)->reservations()->occupying()->latest('starts_on');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Attribute<string, never>
|
||||
*/
|
||||
protected function fullName(): Attribute
|
||||
{
|
||||
return Attribute::get(fn (): string => "{$this->first_name} {$this->last_name}");
|
||||
return Attribute::get(fn (): string => trim("{$this->first_name} {$this->last_name}"));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -5,41 +5,63 @@
|
||||
use App\Actions\CreateChannelTasks;
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Property;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Manual blocks and occupations imported from one portal must also reach the manually maintained
|
||||
* portals – except the portal they came from.
|
||||
*/
|
||||
class BlockedPeriodObserver implements ShouldHandleEventsAfterCommit
|
||||
class BlockedPeriodObserver
|
||||
{
|
||||
public function __construct(private CreateChannelTasks $createChannelTasks) {}
|
||||
|
||||
public function created(BlockedPeriod $block): void
|
||||
{
|
||||
$this->tasks($block, $block->starts_on, $block->ends_on, ChannelTaskAction::Block);
|
||||
if (! $block->is_representation && $block->export_approved) {
|
||||
$this->tasks($block, $block->starts_on, $block->ends_on, ChannelTaskAction::Block);
|
||||
}
|
||||
}
|
||||
|
||||
public function restored(BlockedPeriod $block): void
|
||||
{
|
||||
$this->created($block);
|
||||
}
|
||||
|
||||
public function updated(BlockedPeriod $block): void
|
||||
{
|
||||
if (! $block->wasChanged(['starts_on', 'ends_on'])) {
|
||||
if (! $block->wasChanged(['starts_on', 'ends_on', 'is_representation', 'export_approved'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->tasks($block, CarbonImmutable::parse($block->getOriginal('starts_on')), CarbonImmutable::parse($block->getOriginal('ends_on')), ChannelTaskAction::Unblock);
|
||||
$this->tasks($block, $block->starts_on, $block->ends_on, ChannelTaskAction::Block);
|
||||
$this->tasks($block, CarbonImmutable::parse($block->getRawOriginal('starts_on')), CarbonImmutable::parse($block->getRawOriginal('ends_on')), ChannelTaskAction::Unblock);
|
||||
if (! $block->is_representation && $block->export_approved && ! $block->trashed()) {
|
||||
$this->tasks($block, $block->starts_on, $block->ends_on, ChannelTaskAction::Block);
|
||||
}
|
||||
}
|
||||
|
||||
public function deleted(BlockedPeriod $block): void
|
||||
{
|
||||
$this->tasks($block, $block->starts_on, $block->ends_on, ChannelTaskAction::Unblock);
|
||||
if (! $block->is_representation) {
|
||||
$this->tasks($block, $block->starts_on, $block->ends_on, ChannelTaskAction::Unblock);
|
||||
}
|
||||
}
|
||||
|
||||
private function tasks(BlockedPeriod $block, CarbonImmutable $startsOn, CarbonImmutable $endsOn, ChannelTaskAction $action): void
|
||||
{
|
||||
$reason = $block->channel ? "Belegung über {$block->channel->name}" : 'Sperrzeit'.($block->reason ? ": {$block->reason}" : '');
|
||||
|
||||
$this->createChannelTasks->handle($block->property, $startsOn, $endsOn, $action, $reason, $block->channel_id);
|
||||
$propertyId = $block->property_id;
|
||||
$channelId = $block->channel_id;
|
||||
$originId = $block->origin_channel_id;
|
||||
$external = $channelId !== null || $originId !== null || $block->source !== 'manual';
|
||||
DB::afterCommit(function () use ($propertyId, $channelId, $originId, $external, $startsOn, $endsOn, $action, $reason): void {
|
||||
$property = Property::withoutGlobalScope('tenant')->find($propertyId);
|
||||
if ($property !== null) {
|
||||
app(TenantContext::class)->run($property->tenant, fn () => $this->createChannelTasks->handle($property, $startsOn, $endsOn, $action, $reason, $channelId, $originId, $external));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,15 @@
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit;
|
||||
use App\Models\Property;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Keeps manually maintained portals in step when a booking starts or stops occupying the calendar.
|
||||
*/
|
||||
class BookingObserver implements ShouldHandleEventsAfterCommit
|
||||
class BookingObserver
|
||||
{
|
||||
public function __construct(private CreateChannelTasks $createChannelTasks) {}
|
||||
|
||||
@@ -24,17 +27,18 @@ public function created(Booking $booking): void
|
||||
|
||||
public function updated(Booking $booking): void
|
||||
{
|
||||
if (! $booking->wasChanged('status')) {
|
||||
if (! $booking->wasChanged(['status', 'arrival', 'departure'])) {
|
||||
return;
|
||||
}
|
||||
|
||||
$before = $this->occupies($booking->getOriginal('status'));
|
||||
$before = $this->occupies($booking->getRawOriginal('status'));
|
||||
$after = $this->occupies($booking->status);
|
||||
|
||||
if (! $before && $after) {
|
||||
if ($before && (! $after || $booking->wasChanged(['arrival', 'departure']))) {
|
||||
$this->tasks($booking, ChannelTaskAction::Unblock, CarbonImmutable::parse($booking->getRawOriginal('arrival')), CarbonImmutable::parse($booking->getRawOriginal('departure')));
|
||||
}
|
||||
if ($after && (! $before || $booking->wasChanged(['arrival', 'departure']))) {
|
||||
$this->tasks($booking, ChannelTaskAction::Block);
|
||||
} elseif ($before && ! $after) {
|
||||
$this->tasks($booking, ChannelTaskAction::Unblock);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,14 +49,20 @@ private function occupies(BookingStatus|string|null $status): bool
|
||||
return in_array($status, BookingStatus::occupying(), true);
|
||||
}
|
||||
|
||||
private function tasks(Booking $booking, ChannelTaskAction $action): void
|
||||
private function tasks(Booking $booking, ChannelTaskAction $action, ?CarbonImmutable $startsOn = null, ?CarbonImmutable $endsOn = null): void
|
||||
{
|
||||
$property = $booking->property()->withoutGlobalScope('tenant')->first();
|
||||
|
||||
if ($property === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->createChannelTasks->handle($property, $booking->arrival, $booking->departure, $action, "Buchung {$booking->reference}");
|
||||
$propertyId = $booking->property_id;
|
||||
$channelId = $booking->import_channel_id;
|
||||
$originId = $booking->origin_channel_id;
|
||||
$external = ! $booking->isDirect();
|
||||
$startsOn ??= $booking->arrival;
|
||||
$endsOn ??= $booking->departure;
|
||||
$reason = "Buchung {$booking->reference}";
|
||||
DB::afterCommit(function () use ($propertyId, $channelId, $originId, $external, $startsOn, $endsOn, $action, $reason): void {
|
||||
$property = Property::withoutGlobalScope('tenant')->find($propertyId);
|
||||
if ($property !== null) {
|
||||
app(TenantContext::class)->run($property->tenant, fn () => $this->createChannelTasks->handle($property, $startsOn, $endsOn, $action, $reason, $channelId, $originId, $external));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Enums\Permission;
|
||||
|
||||
class ChannelPolicy extends RolePolicy
|
||||
{
|
||||
protected function permission(): Permission
|
||||
{
|
||||
return Permission::Channels;
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
namespace App\Tenancy;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Photo;
|
||||
use App\Models\Site;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use RuntimeException;
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
use ZipArchive;
|
||||
@@ -28,6 +31,7 @@ class TenantArchive
|
||||
private const DELETE_ORDER = [
|
||||
'floor_plans',
|
||||
'channel_sync_logs',
|
||||
'channel_export_requests',
|
||||
'channel_tasks',
|
||||
'portal_emails',
|
||||
'payments',
|
||||
@@ -192,25 +196,39 @@ private function rowsOf(string $table, Tenant $tenant): array
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos keep their files through Spatie's media library; they hang off the photo, not off the landlord,
|
||||
* so they are collected through the photos of this landlord.
|
||||
* Include media metadata, original files, conversions and every retained document version.
|
||||
*/
|
||||
private function addFiles(ZipArchive $zip, Tenant $tenant): void
|
||||
{
|
||||
foreach ($this->mediaOf($tenant) as $media) {
|
||||
$mediaItems = $this->mediaOf($tenant);
|
||||
$zip->addFromString('daten/media.json', (string) $mediaItems->toJson(JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
|
||||
foreach ($mediaItems as $media) {
|
||||
$path = $media->getPath();
|
||||
|
||||
if (is_string($path) && File::exists($path)) {
|
||||
$zip->addFile($path, 'dateien/'.$media->id.'-'.$media->file_name);
|
||||
$directory = dirname($path);
|
||||
foreach (File::allFiles($directory) as $file) {
|
||||
$relative = str_replace('\\', '/', substr($file->getPathname(), strlen($directory) + 1));
|
||||
$zip->addFile($file->getPathname(), 'dateien/'.$media->id.'-'.$relative);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($this->documentPaths($tenant) as $path) {
|
||||
$zip->addFile(Storage::disk('local')->path($path), 'dateien/local/'.$path);
|
||||
}
|
||||
}
|
||||
|
||||
private function deleteFiles(Tenant $tenant): void
|
||||
{
|
||||
$documents = $this->documentPaths($tenant);
|
||||
|
||||
foreach ($this->mediaOf($tenant) as $media) {
|
||||
$media->delete(); // removes the stored file as well
|
||||
}
|
||||
|
||||
Storage::disk('local')->delete($documents);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -220,10 +238,43 @@ private function mediaOf(Tenant $tenant): Collection
|
||||
{
|
||||
return app(TenantContext::class)->run(
|
||||
$tenant,
|
||||
fn () => Photo::query()->with('media')->get()->flatMap(fn (Photo $photo) => $photo->media),
|
||||
fn () => Photo::query()->with('media')->get()->flatMap(fn (Photo $photo) => $photo->media)
|
||||
->concat(Site::query()->with('media')->get()->flatMap(fn (Site $site) => $site->media)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* New documents have a tenant directory, including earlier offer versions. Existing installations
|
||||
* also have flat paths: accept only those explicitly referenced by this tenant and never a shared file.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function documentPaths(Tenant $tenant): array
|
||||
{
|
||||
$disk = Storage::disk('local');
|
||||
$paths = $disk->allFiles('contracts/tenants/'.$tenant->id);
|
||||
$bookings = Booking::withoutGlobalScope('tenant')->where('tenant_id', $tenant->id)->get(['contract_path', 'offer_path']);
|
||||
|
||||
foreach ($bookings as $booking) {
|
||||
foreach ([$booking->contract_path, $booking->offer_path] as $path) {
|
||||
if (! is_string($path) || ! preg_match('~\Acontracts/[^/\\\\]+\.pdf\z~', $path) || ! $disk->exists($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$shared = Booking::withoutGlobalScope('tenant')->where('tenant_id', '!=', $tenant->id)
|
||||
->where(fn ($query) => $query->where('contract_path', $path)->orWhere('offer_path', $path))->exists();
|
||||
|
||||
if ($shared) {
|
||||
throw new RuntimeException('Vertragsdatei ist mehreren Mandanten zugeordnet: '.$path);
|
||||
}
|
||||
|
||||
$paths[] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($paths));
|
||||
}
|
||||
|
||||
private function hasTenantColumn(string $table): bool
|
||||
{
|
||||
static $known = [];
|
||||
|
||||
@@ -59,6 +59,7 @@ class TenantConfig
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const OWNED = [
|
||||
'app.name' => 'name',
|
||||
'fewo.owner.name' => 'owner_name',
|
||||
'fewo.owner.street' => 'owner_street',
|
||||
'fewo.owner.city' => 'owner_city',
|
||||
|
||||
@@ -3,18 +3,19 @@
|
||||
namespace App\Themes;
|
||||
|
||||
use App\Models\Appearance;
|
||||
use App\Models\Property;
|
||||
use App\Themes\Sections\Section;
|
||||
use Filament\Forms\Components\Builder\Block;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Support\Facades\View as ViewFactory;
|
||||
|
||||
/**
|
||||
* The section catalogue from config/themes.php: builder blocks for the admin and rendering for the website.
|
||||
*
|
||||
* Every placed section carries data.id (a stable UUID, see Page::assignSectionIds) so appearances can
|
||||
* address it, and data.appearances (appearance ids; empty = always shown).
|
||||
* address it, data.appearances (appearance ids; empty = always shown), and an optional data.property_id
|
||||
* (an active property of this website; empty = primary property).
|
||||
*/
|
||||
class SectionRegistry
|
||||
{
|
||||
@@ -38,7 +39,7 @@ public function get(string $key): ?Section
|
||||
/**
|
||||
* @return list<Block>
|
||||
*/
|
||||
public function blocks(): array
|
||||
public function blocks(?int $siteId = null): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (string $class): Block => Block::make($class::key())
|
||||
@@ -47,6 +48,17 @@ public function blocks(): array
|
||||
->schema([
|
||||
Hidden::make('id'),
|
||||
...$class::schema(),
|
||||
Select::make('property_id')
|
||||
->label('Wohnung')
|
||||
->placeholder('Hauptwohnung')
|
||||
->helperText('Leer = Hauptwohnung dieser Website.')
|
||||
->options(fn (): array => Property::query()
|
||||
->where('site_id', $siteId)
|
||||
->whereNotNull('site_id')
|
||||
->where('is_active', true)
|
||||
->orderBy('name')
|
||||
->pluck('name', 'id')
|
||||
->all()),
|
||||
Select::make('appearances')
|
||||
->label('Nur anzeigen im Erscheinungsbild')
|
||||
->helperText('Leer = immer anzeigen. Z. B. ein Weihnachts-Baustein nur im Erscheinungsbild „Weihnachten“.')
|
||||
@@ -70,11 +82,11 @@ public function isVisible(Theme $theme, array $data): bool
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the stored sections of a page; unknown or failing types are skipped (and reported),
|
||||
* so a page never breaks because of one section.
|
||||
* Prepares the stored sections for deferred rendering. Unknown types, missing views, hidden sections
|
||||
* and unavailable property assignments are skipped.
|
||||
*
|
||||
* @param list<array{type: string, data?: array<string, mixed>}>|null $sections
|
||||
* @return list<View>
|
||||
* @return list<SectionView>
|
||||
*/
|
||||
public function render(Theme $theme, ?array $sections): array
|
||||
{
|
||||
@@ -85,11 +97,24 @@ public function render(Theme $theme, ?array $sections): array
|
||||
continue;
|
||||
}
|
||||
|
||||
$views[] = ViewFactory::make($section->view(), [
|
||||
...$section->data($theme, $stored['data'] ?? []),
|
||||
'theme' => $theme,
|
||||
'sectionId' => $section::key().'-'.$index,
|
||||
]);
|
||||
$data = $stored['data'] ?? [];
|
||||
$property = filled($data['property_id'] ?? null)
|
||||
? $theme->site->properties()->where('is_active', true)->whereKey($data['property_id'])->first()
|
||||
: $theme->property();
|
||||
|
||||
if (filled($data['property_id'] ?? null) && $property === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$views[] = $theme->runForProperty($property, fn (): SectionView => new SectionView(
|
||||
$theme,
|
||||
$property,
|
||||
ViewFactory::make($section->view(), [
|
||||
...$section->data($theme, $data),
|
||||
'theme' => $theme,
|
||||
'sectionId' => $section::key().'-'.$index,
|
||||
]),
|
||||
));
|
||||
}
|
||||
|
||||
return $views;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Themes;
|
||||
|
||||
use App\Models\Property;
|
||||
use Illuminate\Contracts\Support\Renderable;
|
||||
use Illuminate\Contracts\View\View;
|
||||
|
||||
/**
|
||||
* Keeps the section's property active when the page eventually renders its Blade view and partials.
|
||||
*/
|
||||
class SectionView implements Renderable
|
||||
{
|
||||
public function __construct(
|
||||
private Theme $theme,
|
||||
private ?Property $property,
|
||||
private View $view,
|
||||
) {}
|
||||
|
||||
public function render(): string
|
||||
{
|
||||
return $this->theme->runForProperty($this->property, fn (): string => $this->view->render());
|
||||
}
|
||||
}
|
||||
@@ -174,6 +174,29 @@ public function property(): ?Property
|
||||
return $this->property;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a section with its property, restoring the previous cache even when rendering fails.
|
||||
*
|
||||
* @template T
|
||||
*
|
||||
* @param callable(): T $callback
|
||||
* @return T
|
||||
*/
|
||||
public function runForProperty(?Property $property, callable $callback): mixed
|
||||
{
|
||||
$previousProperty = $this->property;
|
||||
$previousResolved = $this->propertyResolved;
|
||||
$this->property = $property;
|
||||
$this->propertyResolved = true;
|
||||
|
||||
try {
|
||||
return $callback();
|
||||
} finally {
|
||||
$this->property = $previousProperty;
|
||||
$this->propertyResolved = $previousResolved;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Published pages of a menu location ("main" or "footer").
|
||||
*
|
||||
|
||||
@@ -14,6 +14,12 @@
|
||||
health: '/up',
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
$middleware->trimStrings(except: [
|
||||
'components.*.updates.data.rules.*.conditions.*.value',
|
||||
'components.*.updates.data.rules.*.extractions.*.start',
|
||||
'components.*.updates.data.rules.*.extractions.*.end',
|
||||
'components.*.updates.data.export_mapping.*.separator',
|
||||
]);
|
||||
$middleware->web(append: [ResolveTheme::class]);
|
||||
$middleware->append(SecurityHeaders::class);
|
||||
})
|
||||
|
||||
@@ -25,4 +25,8 @@
|
||||
*/
|
||||
'uid_suffix' => '@fewo-stommer',
|
||||
|
||||
'removal_confirmation_runs' => 2,
|
||||
'max_automatic_removals' => 5,
|
||||
'export_request_history_limit' => 100,
|
||||
|
||||
];
|
||||
@@ -24,6 +24,10 @@ public function definition(): array
|
||||
'connector' => 'ical',
|
||||
'settings' => ['import_url' => 'https://portal.example/ical/'.fake()->uuid().'.ics'],
|
||||
'is_active' => true,
|
||||
'status' => 'active',
|
||||
'import_enabled' => true,
|
||||
'export_enabled' => true,
|
||||
'export_mode' => 'regular',
|
||||
'requires_manual_blocking' => false,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('channels', function (Blueprint $table) {
|
||||
$table->string('status')->default('setup');
|
||||
$table->string('booking_model')->default('mixed');
|
||||
$table->boolean('import_enabled')->default(false);
|
||||
$table->boolean('export_enabled')->default(false);
|
||||
$table->string('export_mode')->default('test');
|
||||
$table->unsignedInteger('external_poll_minutes')->nullable();
|
||||
$table->dateTime('last_error_at')->nullable();
|
||||
$table->unsignedInteger('last_import_events')->default(0);
|
||||
$table->json('sync_warnings')->nullable();
|
||||
$table->longText('export_snapshot')->nullable();
|
||||
$table->dateTime('export_snapshot_at')->nullable();
|
||||
$table->dateTime('last_export_requested_at')->nullable();
|
||||
$table->string('previous_export_token', 64)->nullable()->unique();
|
||||
$table->dateTime('previous_export_token_expires_at')->nullable();
|
||||
});
|
||||
Schema::table('blocked_periods', function (Blueprint $table) {
|
||||
$table->foreignId('origin_channel_id')->nullable()->constrained('channels')->restrictOnDelete();
|
||||
$table->boolean('needs_review')->default(false);
|
||||
$table->text('review_note')->nullable();
|
||||
$table->unsignedInteger('missing_imports')->default(0);
|
||||
});
|
||||
Schema::table('bookings', function (Blueprint $table) {
|
||||
$table->foreignId('import_channel_id')->nullable()->constrained('channels')->restrictOnDelete();
|
||||
$table->foreignId('origin_channel_id')->nullable()->constrained('channels')->restrictOnDelete();
|
||||
});
|
||||
Schema::table('channel_sync_logs', fn (Blueprint $table) => $table->json('warnings')->nullable());
|
||||
|
||||
/** Preserve existing directions and export scope without changing any occupancy. */
|
||||
DB::table('channels')->orderBy('id')->each(function (object $channel): void {
|
||||
$settings = json_decode($channel->settings ?? '{}', true) ?: [];
|
||||
DB::table('channels')->where('id', $channel->id)->update([
|
||||
'status' => $channel->is_active ? 'active' : 'paused',
|
||||
'import_enabled' => $channel->is_active && filled($settings['import_url'] ?? null),
|
||||
'export_enabled' => (bool) $channel->is_active,
|
||||
'export_mode' => 'regular',
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('bookings', function (Blueprint $table) {
|
||||
$table->dropConstrainedForeignId('origin_channel_id');
|
||||
$table->dropConstrainedForeignId('import_channel_id');
|
||||
});
|
||||
Schema::table('blocked_periods', function (Blueprint $table) {
|
||||
$table->dropConstrainedForeignId('origin_channel_id');
|
||||
$table->dropColumn(['needs_review', 'review_note', 'missing_imports']);
|
||||
});
|
||||
Schema::table('channel_sync_logs', fn (Blueprint $table) => $table->dropColumn('warnings'));
|
||||
Schema::table('channels', fn (Blueprint $table) => $table->dropUnique(['previous_export_token']));
|
||||
Schema::table('channels', fn (Blueprint $table) => $table->dropColumn([
|
||||
'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes',
|
||||
'last_error_at', 'last_import_events', 'sync_warnings', 'export_snapshot', 'export_snapshot_at',
|
||||
'last_export_requested_at', 'previous_export_token', 'previous_export_token_expires_at',
|
||||
]));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('channels', function (Blueprint $table): void {
|
||||
$table->string('echo_behavior')->default('unverified');
|
||||
$table->text('echo_notes')->nullable();
|
||||
$table->text('operating_notes')->nullable();
|
||||
$table->dateTime('portal_verified_at')->nullable();
|
||||
});
|
||||
Schema::table('blocked_periods', function (Blueprint $table): void {
|
||||
$table->softDeletes();
|
||||
$table->boolean('is_representation')->default(false);
|
||||
$table->foreignId('canonical_block_id')->nullable()->constrained('blocked_periods')->nullOnDelete();
|
||||
$table->foreignId('linked_booking_id')->nullable()->constrained('bookings')->nullOnDelete();
|
||||
$table->boolean('export_approved')->default(true);
|
||||
$table->dateTime('reviewed_at')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('blocked_periods', function (Blueprint $table): void {
|
||||
$table->dropConstrainedForeignId('canonical_block_id');
|
||||
$table->dropConstrainedForeignId('linked_booking_id');
|
||||
$table->dropColumn(['is_representation', 'export_approved', 'reviewed_at']);
|
||||
$table->dropSoftDeletes();
|
||||
});
|
||||
Schema::table('channels', fn (Blueprint $table) => $table->dropColumn(['echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at']));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('channel_export_requests', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('channel_id')->constrained()->cascadeOnDelete();
|
||||
$table->dateTime('requested_at');
|
||||
$table->string('method', 8);
|
||||
$table->string('user_agent', 512)->nullable();
|
||||
$table->unsignedSmallInteger('response_status');
|
||||
$table->string('export_state', 20);
|
||||
$table->index(['channel_id', 'requested_at']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('channel_export_requests');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('channels', function (Blueprint $table): void {
|
||||
$table->longText('ical_analysis')->nullable();
|
||||
$table->dateTime('ical_analyzed_at')->nullable();
|
||||
$table->json('ical_rules')->nullable();
|
||||
$table->json('ical_active_rules')->nullable();
|
||||
$table->json('ical_export_mapping')->nullable();
|
||||
$table->boolean('ical_export_names')->default(false);
|
||||
});
|
||||
Schema::table('blocked_periods', function (Blueprint $table): void {
|
||||
$table->longText('ical_properties')->nullable();
|
||||
$table->longText('ical_raw')->nullable();
|
||||
$table->longText('ical_interpretation')->nullable();
|
||||
$table->string('ical_event_type')->default('unknown');
|
||||
$table->unsignedInteger('leading_priority')->default(0);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('blocked_periods', fn (Blueprint $table) => $table->dropColumn(['ical_properties', 'ical_raw', 'ical_interpretation', 'ical_event_type', 'leading_priority']));
|
||||
Schema::table('channels', fn (Blueprint $table) => $table->dropColumn(['ical_analysis', 'ical_analyzed_at', 'ical_rules', 'ical_active_rules', 'ical_export_mapping', 'ical_export_names']));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('blocked_periods', function (Blueprint $table) {
|
||||
$table->foreignId('guest_id')->nullable()->constrained()->nullOnDelete();
|
||||
$table->string('occupation_kind', 30)->nullable();
|
||||
});
|
||||
Schema::table('guests', function (Blueprint $table) {
|
||||
$table->string('email')->nullable()->change();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
if (DB::table('guests')->whereNull('email')->exists()) {
|
||||
throw new RuntimeException('Gäste ohne E-Mail zuerst vervollständigen; das vorherige Schema erlaubt keine fehlenden E-Mail-Adressen.');
|
||||
}
|
||||
Schema::table('guests', function (Blueprint $table) {
|
||||
$table->string('email')->nullable(false)->change();
|
||||
});
|
||||
Schema::table('blocked_periods', function (Blueprint $table) {
|
||||
$table->dropConstrainedForeignId('guest_id');
|
||||
$table->dropColumn('occupation_kind');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('blocked_periods', function (Blueprint $table) {
|
||||
$table->string('block_purpose', 30)->nullable();
|
||||
$table->string('block_note')->nullable();
|
||||
$table->boolean('is_private')->default(false);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
* Removing these fields discards manual purpose and private-origin assignments; prefer a forward fix on shared systems.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('blocked_periods', function (Blueprint $table) {
|
||||
$table->dropColumn(['block_purpose', 'block_note', 'is_private']);
|
||||
});
|
||||
}
|
||||
};
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('blocked_periods', function (Blueprint $table) {
|
||||
$table->boolean('representation_automatic')->default(false);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
if (DB::table('blocked_periods')->where('representation_automatic', true)->exists()) {
|
||||
throw new RuntimeException('Automatische Kalenderspiegelungen zuerst auflösen; ihre Kennzeichnung darf nicht verloren gehen.');
|
||||
}
|
||||
Schema::table('blocked_periods', function (Blueprint $table) {
|
||||
$table->dropColumn('representation_automatic');
|
||||
});
|
||||
}
|
||||
};
|
||||
+72
-7
@@ -1,6 +1,6 @@
|
||||
# Betrieb: Umgebungen, Zugänge, Einrichtung
|
||||
|
||||
Stand: 22.10.2026. Dieses Dokument beschreibt den **tatsächlichen Stand** der Installationen, damit jede neue Arbeitssitzung (Mensch oder KI) ohne Vorwissen weitermachen kann. Allgemeine Abläufe des Deployments stehen in [DEPLOYMENT.md](DEPLOYMENT.md), das fachliche Konzept in [KONZEPT.md](KONZEPT.md).
|
||||
Stand: 27.10.2026. Aktuell bestätigt: Test unter **www.stommer.info** und `stommer.info`, SSH-Serverpfad **`test.fewo-stommer.de/`**. `dev.fewo-stommer.de/` existiert nicht. Produktion ist noch nicht eingerichtet: ein vorhandener leerer Ordner ist keine fertige Umgebung; eigene MariaDB, `.env`, persistente Daten und Domainzuordnung fehlen. Produktion bleibt in `pipeline.toml` gesperrt. Entwicklung und Testdeploy laufen über `develop` und PipelineManager; die manuellen Skripte unten sind Wartungswerkzeuge. Weitere Abläufe: [DEPLOYMENT.md](DEPLOYMENT.md).
|
||||
|
||||
> **Geheimnisse stehen nie im Repository und nie im Chat.** Passwörter (Datenbank, E-Mail), `APP_KEY`, Tokens und private SSH-Schlüssel liegen nur in `shared/.env` auf dem Server bzw. im Vaultwarden von Lars. Hier ist nur dokumentiert, *wo* sie liegen.
|
||||
|
||||
@@ -9,15 +9,15 @@ ## 1. Überblick
|
||||
| | Testbetrieb (staging) | Produktion |
|
||||
|---|---|---|
|
||||
| Adresse | **https://stommer.info** | später https://www.fewo-stommer.de (heute noch WordPress) |
|
||||
| Ordner auf dem Webspace | `test.fewo-stommer.de/` | noch nicht angelegt (Vorschlag: `fewo-production/`) |
|
||||
| Ordner auf dem Webspace | `test.fewo-stommer.de/` | `prod.fewo-stommer.de/` angelegt; `.env`/Datenbank und Freigabe noch offen |
|
||||
| Deploy-Konfiguration (lokal, nicht committet) | `scripts/deploy.staging.env` | `scripts/deploy.production.env` (anlegen aus `deploy.example.env`) |
|
||||
| Datenbank | MariaDB 11.8, siehe §3 | eigene Datenbank anlegen |
|
||||
| E-Mail | `MAIL_MAILER=log` – **verschickt nichts** | Strato-SMTP |
|
||||
| Postfach-Abruf (Portal-Mails) | aus (`FEWO_MAILBOX_HOST` leer) | `imap.strato.de` |
|
||||
| Suchmaschinen | `noindex` (alles außer `APP_ENV=production`) | indexiert |
|
||||
| Cronjob | **noch offen** (§6) | einrichten |
|
||||
| Scheduler-Auslöser | **n8n veröffentlicht und aktiv**, automatische Kalenderimporte im Fünf-Minuten-Abstand nachgewiesen (§6) | einrichten |
|
||||
|
||||
Git: `https://gitea.stommer.de/Lars/fewo-stommer.git`, Branch `main`. Gebaut und ausgeliefert wird immer der **letzte Commit**.
|
||||
Git: `https://gitea.stommer.de/Lars/fewo-stommer.git`. Automatischer Testdeploy nach Push auf `develop`; Produktion über Merge-Commit von `develop` nach `main`, derzeit gesperrt. Gebaut wird der **exakte Workflow-Commit** mit PipelineManager; Details in [DEPLOYMENT.md](DEPLOYMENT.md).
|
||||
|
||||
## 2. Strato-Paket (Hosting Pro)
|
||||
|
||||
@@ -88,11 +88,76 @@ ## 6. Erledigt / offen im Testbetrieb
|
||||
Offen:
|
||||
- **Konto für Brigitte** anlegen: System › Benutzer, Rolle Administrator, Ansicht Einfach (§7).
|
||||
- **E-Mail im Testbetrieb** einschalten (§5a): Versandweg SMTP + Passwort; Betriebsart steht auf Testbetrieb mit Testadresse lars@stommer.com.
|
||||
- **Cronjob** (Kundenlogin › Cronjobs), jede Minute:
|
||||
`/opt/RZphp84/bin/php-cli /mnt/web508/e3/26/51539426/htdocs/test.fewo-stommer.de/current/artisan schedule:run`
|
||||
Falls Strato nicht minütlich erlaubt: n8n ruft jede Minute `https://stommer.info/automation/scheduler` mit Header `Authorization: Bearer <FEWO_SCHEDULER_TOKEN>` auf.
|
||||
- Bankdaten, Vertrags- und AGB-Texte, Rechtstexte prüfen.
|
||||
|
||||
### Automatische Zeitsteuerung (n8n)
|
||||
|
||||
Lars hat am 27.10.2026 im Strato-Kundenbereich als kleinstes Intervall stündliche Ausführung festgestellt. Das genügt nicht für den vorgesehenen Kalenderimport alle fünf Minuten. Deshalb ist ein externer minütlicher Aufruf über n8n eingerichtet; kein zusätzlicher stündlicher Strato-Scheduler für dieselbe Instanz.
|
||||
|
||||
Auf dem bestehenden Pi läuft n8n **2.7.5**. Vor der Einrichtung wurden die 29 vorhandenen Workflows auf einen bereits vorhandenen FewoPortal-/stommer.info-Aufruf geprüft; keiner gefunden. Die tokenfreie Vorlage [scripts/n8n-fewo-scheduler.json](../scripts/n8n-fewo-scheduler.json) ist gegen die installierten Schedule- und HTTP-Node-Schemata geprüft. Sie ruft jede volle Minute `https://stommer.info/automation/scheduler` auf. Laravel führt die jeweils fälligen Aufgaben aus, einschließlich aktiver Kalenderimporte alle fünf Minuten; auch die anderen in `routes/console.php` definierten Aufgaben werden dadurch zeitgesteuert ausgeführt.
|
||||
|
||||
Der Header `Authorization: Bearer <FEWO_SCHEDULER_TOKEN>` liegt nach ausdrücklicher Freigabe in der verschlüsselten n8n-Zugangsdatenverbindung **FewoPortal Scheduler (stommer.info)** vom Typ **Header Auth**, Feldname `Authorization`. Der [veröffentlichte Workflow](http://localhost:15678/workflow/23581e4b70324812) ist angelegt; die gespeicherte verschlüsselte Form und die korrekte Zuordnung wurden lesend bestätigt. Die Repository-Vorlage enthält nur eine Platzhalterreferenz. Token weder in die Workflow-Datei noch in eine URL oder das Repository schreiben. Erfolgreiche Ausführungsdaten werden nicht dauerhaft gespeichert; HTTP-Fehler bleiben Fehler.
|
||||
|
||||
Der separat freigegebene einmalige manuelle Workflow-Test hat am **27.10.2026 um 20:42:47 Uhr MEZ** eine gültige authentifizierte JSON-Antwort des Schedulers erhalten. Für den parallelen CLI-Test wurde ausschließlich im Testprozess ein anderer lokaler Task-Broker-Port verwendet; die laufende n8n-Instanz wurde nicht neu gestartet. Der Test lag außerhalb einer Fünf-Minuten-Marke und führte deshalb keinen Kalenderimport aus. Lesend um 20:43 bestätigt: Kanal 1 importfähig, letzter erfolgreicher Import weiterhin 19:21:17 Uhr; Kanal 2 Import ausgeschaltet. Dieser einmalige Verbindungstest ist vom nachfolgenden Nachweis automatischer Kalenderimporte zu unterscheiden.
|
||||
|
||||
**Betriebsnachweis vom 27.10.2026:** Lars hat den Workflow in der Oberfläche veröffentlicht. Aktive Version und registrierter Zeitplan lesend bestätigt. Anschließend zwei automatische Importe des FeWo-direkt-Kanals 1 um **20:55:03 und 21:00:03 Uhr MEZ**, Protokolle 5 und 6, erfolgreich nachgewiesen: exakt 300 Sekunden Abstand; jeweils 11 Ereignisse, keine neuen, geänderten oder entfernten Belegungen, keine Konflikte. `last_success_at` am Kanal ist 21:00:03 Uhr, kein aktueller Importfehler. Die Beobachtung hat keinen manuellen Abgleich ausgelöst. Der Ostseeklar-Kanal 2 bleibt ein reiner Exportkanal mit ausgeschaltetem Import.
|
||||
|
||||
Die Automatik läuft unabhängig vom Browser und dem lokalen SSH-Tunnel auf dem Pi. Pi, n8n und dessen Internetverbindung müssen verfügbar bleiben. Die Kanalübersicht zeigt den letzten erfolgreichen Import und auftretende Fehler; zwei erfolgreiche Läufe belegen diesen konkreten Betriebsbeginn, keine dauerhafte Verfügbarkeitsgarantie. Die [n8n-CLI-Dokumentation](https://github.com/n8n-io/n8n-docs/blob/main/docs/deploy/host-n8n/configure-n8n/use-the-command-line.md) verlangt nach CLI-Veröffentlichung einen Neustart; Veröffentlichung in der Oberfläche vermeidet diesen zusätzlichen Neustart. Tokenfreier lokaler Nachweis: `storage/app/private/n8n-scheduler/setup-result.json` (Git-ignoriert).
|
||||
|
||||
### Zugang zur n8n-Oberfläche (27.10.2026)
|
||||
|
||||
**Nutzungsentscheidung vom 28.10.2026:** Aktuell benötigt Lars keinen externen Zugriff. Vorgesehener Betrieb: Verwaltung ausschließlich im Heimnetz über das bereits geprüfte NAS-HTTPS auf Port 5678. Die Zertifikatsadresse `privat.stommer.com` soll dafür intern direkt auf NAS `192.168.2.63` auflösen; damit ist kein dauerhafter lokaler SSH-Tunnel erforderlich. Öffentliche n8n-Portfreigabe wieder schließen, Heimnetzfreigabe für `192.168.2.0/24` erhalten. Dies ist die vereinbarte Zielrichtung; DNS-, Router- und Firewalländerungen wurden durch den Agenten noch nicht umgesetzt. Der ausgehende Fewo-Scheduler benötigt diese öffentliche Freigabe nicht. Die kostenpflichtige zentrale MFA-Erzwingung und persönliche Konto-2FA unter Settings → Personal sind unterschiedliche Funktionen; ein kostenpflichtiges Upgrade ist für den internen Betrieb nicht erforderlich. Aktualisierungen und Sicherungen bleiben erforderlich.
|
||||
|
||||
**Öffentlicher Zugriff wiederhergestellt und Sicherheitskurzprüfung (28.10.2026):** Lars bestätigt, dass die Freigabe des Ports in der NAS-Firewall den externen Zugriff wiederhergestellt hat. Anschließender HTTPS-Prüfabruf gegen `privat.stommer.com:5678`: Startseite und `/healthz` HTTP 200, `/rest/workflows`, `/rest/credentials` und `/api/v1/workflows` jeweils unangemeldet HTTP 401. Damit ist die zuvor vermutete Firewallblockade durch die Nutzeränderung und den erneuten Abruf nachvollzogen. Die früheren Zeitüberschreitungen unten beschreiben den Zustand vor dieser Freigabe.
|
||||
|
||||
Installiert ist weiterhin **n8n 2.7.5**, lesend über die Container-CLI geprüft. Container läuft als `node`, nicht privilegiert, ohne eingebundenen Docker-Socket; diese Isolation ersetzt keine aktuellen Anwendungspatches. Version 2.7.5 liegt beispielsweise im vom Hersteller angegebenen betroffenen Bereich der [Form-Expression-Sicherheitslücke GHSA-75g8-rv7v-32f7](https://github.com/n8n-io/n8n/security/advisories/GHSA-75g8-rv7v-32f7). Deren praktische Ausnutzbarkeit hängt von einer bestimmten Form-Workflow-Konfiguration ab und wurde hier nicht geprüft. Kein Exploitversuch und kein vollständiger Sicherheits- oder Kompromittierungsaudit. 2FA laut Lars nicht aktiviert beziehungsweise unklar; bisher benötigt nur er die Verwaltung, später möglicherweise weitere Personen.
|
||||
|
||||
**Empfohlene nächste Schritte, noch nicht umgesetzt:** Öffentliche Verwaltung vorerst wieder beschränken und über vorhandenen lokalen Tunnel beziehungsweise einen einzurichtenden Heimnetz-VPN-Zugang verwenden; n8n nach Sicherung und Kompatibilitätsprüfung auf einen aktuell gepflegten Patchstand aktualisieren; persönliche 2FA unter Settings → Personal aktivieren und Wiederherstellungscodes sicher aufbewahren; Sicherung und Updatebetrieb für Pi, NAS und FRITZ!Box sicherstellen. Spätere öffentliche Webhooks getrennt von der Verwaltung planen. Der Fewo-Scheduler sendet ausgehend Anfragen an stommer.info und benötigt selbst keinen öffentlich erreichbaren n8n-Eingang. Während dieser Prüfung keine Firewallregel, Kontoeinstellung oder Serverkonfiguration geändert und keinen Workflow ausgeführt.
|
||||
|
||||
**Ergänzung und Korrektur vom 28.10.2026:** HTTPS wird auf dem Synology-NAS bereitgestellt, nicht auf dem Pi. Lars bestätigt die Weiterleitung der öffentlichen Adresse durch die FRITZ!Box zum NAS. Direkte Prüfung aus dem Heimnetz gegen NAS `192.168.2.63:5678` mit TLS-Servername `privat.stommer.com`: TLS 1.3, Zertifikat von der lokalen Vertrauenskette akzeptiert und für diesen Hostnamen passend, gültig bis 11.12.2026, HTTP 200 und n8n-Seitentitel. Der Pi selbst bleibt unter HTTP `192.168.2.49:5678` erreichbar. Die vorherige Aussage über einen ungeklärten HTTPS-Aufbau bezog sich auf den direkten Pi-Zugang und war für den gesamten Zugriffsweg unvollständig.
|
||||
|
||||
Öffentliches DNS liefert IPv4 `5.63.35.136` und IPv6 `2a01:41e3:0:1::3387`; Verbindungsprüfung von diesem Arbeitsplatz auf Port 5678: IPv4-Zeitüberschreitung und IPv6-Verbindung abgewiesen. Auch vom Pi ist der öffentliche Aufruf nicht erreichbar. Das vom Nutzer gezeigte NAS-Firewallprofil erlaubt das Heimnetz `192.168.2.0/24` vollständig und verweigert übrige Verbindungen nach den vorherigen Dienstfreigaben; eine eigene Freigabe für TCP 5678 ist nicht erkennbar. **Wenn die Routerweiterleitung auf NAS-Port 5678 zeigt**, ist dessen Freigabe für die gewünschten externen Quelladressen vor der abschließenden Verweigern-Regel zu prüfen. Die vollständigen Ports der ersten Dienstregel sowie der genaue Zielport der Routerfreigabe wurden noch nicht eingesehen; die Firewall ist ein begründeter Verdacht, keine abschließend bestätigte Ursache. Eine erfolgreiche externe Abnahme steht aus. Keine Router-, NAS-, Zertifikats- oder n8n-Konfiguration geändert.
|
||||
|
||||
Der beendete lokale SSH-Tunnel wurde am 28.10. erneut ausschließlich an `127.0.0.1:15678` gestartet, mit SSH-Verbindungserhaltung. Startseite und n8n-Gesundheitsprüfung HTTP 200; direkte Pfade `/signin` und `/workflow/23581e4b70324812` liefern bei unangemeldeten HTTP-Prüfabrufen aktuell 404. Für den provisorischen Zugang die Startseite `http://localhost:15678/` verwenden. Eine erneute Anmeldung wurde noch nicht durch den Nutzer bestätigt. Der lokale Tunnel verändert den öffentlichen NAS-Zugang nicht. Die folgenden Absätze beschreiben den früheren Befund vom 27.10.
|
||||
|
||||
n8n läuft auf dem Pi unter `http://192.168.2.49:5678`; Container und Oberfläche wurden mit HTTP 200 geprüft. Auf diesem Port ist kein TLS eingerichtet: Ein HTTPS-Verbindungsversuch an den internen n8n-Port scheitert mit `WRONG_VERSION_NUMBER`. Die in n8n hinterlegte `N8N_EDITOR_BASE_URL=https://privat.stommer.com:5678` wurde zunächst als Workflowlink übernommen, ist jedoch kein nachgewiesen funktionierender HTTPS-Zugang. Die Einstellung einer Editoradresse richtet selbst kein TLS ein. Der öffentliche Aufruf auf Port 5678 lief bei der Prüfung in eine Zeitüberschreitung.
|
||||
|
||||
Für den aktuellen Arbeitsplatz wurde ein nur an `127.0.0.1:15678` gebundener SSH-Tunnel zum Pi eingerichtet. Zugang: **http://localhost:15678**, [Scheduler-Workflow](http://localhost:15678/workflow/23581e4b70324812). HTTP-Antworten für Oberfläche, Anmeldung und Workflowroute geprüft; Lars hat die erfolgreiche Anmeldung mit seinem bestehenden Konto bestätigt. Die Verbindung vom Rechner zum Pi wird durch SSH verschlüsselt. Die Secure-Cookie-Einstellung bleibt eingeschaltet, Serverkonfiguration und n8n-Container wurden für diese Zugangslösung nicht verändert oder neu gestartet.
|
||||
|
||||
Die lokalen Links gelten nur auf dem Rechner mit laufendem Tunnel. Nach dessen Beendigung beziehungsweise einem Rechnerneustart lässt sich der Zugang in einer lokalen SSH-Sitzung wiederherstellen:
|
||||
|
||||
```sh
|
||||
ssh -N -L 127.0.0.1:15678:127.0.0.1:5678 -o ExitOnForwardFailure=yes pi
|
||||
```
|
||||
|
||||
Ein dauerhafter öffentlicher HTTPS-Zugang ist damit nicht repariert. Dafür sind die tatsächlich verwendete öffentliche Adresse, deren Weiterleitung und TLS-Terminierung zu klären. n8n beschreibt dafür [TLS am Reverse Proxy oder Zertifikate direkt an n8n](https://github.com/n8n-io/n8n-docs/blob/main/docs/deploy/host-n8n/configure-n8n/security/set-up-ssl.md). Durch diese Diagnose wurden keine Zertifikate, Weiterleitungen oder n8n-Anmeldedaten geändert.
|
||||
|
||||
### n8n-Upgradeversuch und Wiederherstellung (28.10.2026)
|
||||
|
||||
**Wiederherstellung nach dem folgenden Vorfall:** Lars konnte den Testcontainer schließlich in Portainer stoppen. Danach antworteten SSH sowie n8n-Gesundheit/Bereitschaft und Portainer mit HTTP 200. 58 Container laufen, keiner der vorhandenen Healthchecks meldet „unhealthy“; keine vollständige fachliche Prüfung aller Anwendungen. Originalcontainer `n8n` und `portainer` mit Neustartzähler 0 vorgefunden; kein Hostneustart vorgenommen. Gestoppten Testcontainer gezielt entfernt; separates Testvolume und Sicherung erhalten. Privater Nachweis `recovery-result.json` im Sicherungsverzeichnis. Ein erneut erfolgreicher automatischer Fewo-Kalenderimport wurde auf stommer.info am 28.10. um **09:55:04 MEZ** lesend bestätigt; Kanal ohne aktuellen Importfehler.
|
||||
|
||||
**Ressourcenbefund nach Wiederherstellung:** Pi hat rund 8 GB RAM; rund 2 GB Swap fast vollständig belegt. In der anschließenden vmstat-Stichprobe keine aktive Auslagerung und CPU überwiegend frei. Docker meldet `MemoryLimit=false`, `SwapLimit=false` und entsprechende Warnungen. Container-Speicheranzeigen `0B / 0B` sind deshalb keine brauchbare Verbrauchsmessung. Ein bloßes `--memory` wäre auf diesem unveränderten Host keine verlässliche Absicherung. Keine Kernel-OOM-Kill- oder I/O-Fehlermeldung im geprüften Zweistundenfenster. Der Zusammenhang zwischen zusätzlichem parallelem n8n und der Überlastung ist plausibel und durch Erholung nach dessen Stopp gestützt; ein eindeutiger OOM-Kill ist nicht nachgewiesen. Ressourcen-/Kernelunterstützung hätte der Agent vor dem Test prüfen müssen. Keine Kernel-, Boot- oder Swapkonfiguration geändert, kein weiterer Test gestartet.
|
||||
|
||||
**Weiterer Upgradebedarf:** Das produktive n8n ist noch nicht aktualisiert. Image 2.45.5 ist bereits geladen; ein Pull allein verändert einen laufenden Container nicht. Nach stabilisiertem Betrieb wäre der reguläre Weg: aktuelle Sicherung, Compose-Image auf einen geprüften festen Zielstand setzen und ausschließlich Dienst `n8n` mit dem neuen Image neu erstellen. Datenbankmigrationen können einen Rückbau zusammen mit dem passenden Datenbackup erfordern. Kein weiterer unbeschränkter Parallelbetrieb auf diesem gemeinsam genutzten Pi. Die folgenden Absätze protokollieren Vorbereitung und Störung vor der Wiederherstellung.
|
||||
|
||||
n8n läuft auf Raspberry Pi `raspberrypi5` (`192.168.2.49`), Debian GNU/Linux 12 (bookworm), aarch64; Docker Engine 28.3.1 und Docker Compose 2.38.1. Produktiver Container `n8n`, bisher Version 2.7.5 aus Image `n8nio/n8n`, Compose-Projekt `/home/lars/n8n/docker-compose.yml`, Dienst `n8n`. Persistente Daten im Docker-Volume `n8n_n8n_data` unter `/home/node/.n8n`; zusätzliche Bind-Einhängung `/mindnet → /data/mindnet`. Das NAS ist HTTPS-Proxy, kein n8n-Containerhost.
|
||||
|
||||
Am 28.10. wurde 2.45.5 als offizieller stabiler Stand über npm-Dist-Tags und [Herstellerrelease](https://github.com/n8n-io/n8n/releases/tag/n8n%402.45.5) bestätigt. Image `n8nio/n8n:2.45.5` geladen, Registry-Digest `sha256:9f6d0a5987ab5a297c4b0b38fbf1a22285dd1364551478e93f03d506908fa74c`. Ursprüngliches Image lokal weiter vorhanden: `sha256:e5438c4c4cd05211840006910ca860ab962280a0c41f4a526b1643b2aab08e6a`.
|
||||
|
||||
**Sicherung:** `/home/lars/n8n-backups/upgrade-20261028T080618Z`, nur für den Eigentümer zugänglich. Enthält ursprüngliche Compose-Datei, Containerkonfiguration, konsistenten SQLite-Snapshot über `VACUUM INTO`, übrige Datenvolume-Dateien einschließlich Schlüsselkonfiguration und Community-Paket `n8n-nodes-imap` 2.14.1 sowie tokenfreie Bestandszahlen/Prüffingerprints. Geheimnisse verbleiben in dieser privaten Sicherung auf demselben Pi. Bestand: 30 Workflows, 3 aktiv, 9 Credentials; SQLite-Schnellprüfung ok. Datenbank-Snapshot ist durch freigegebene SQLite-Seiten wesentlich kleiner als die laufende Datei, kein Hinweis auf fehlende Datensätze.
|
||||
|
||||
**Testlauf:** Container `n8n-upgrade-test-20261028t080618z`, separates Volume `n8n_upgrade_test_20261028t080618z`; Netzwerk `none`, keine veröffentlichten Ports, kein produktiver Dateimount. Nur in der Kopie wurden aktive Workflows deaktiviert und wartende Ausführungen auf abgebrochen gesetzt. Migration startete, `/healthz` und `/healthz/readiness` lieferten HTTP 200. Weitere Fingerprint-/Entschlüsselungs- und Knotentyp-Prüfungen konnten nicht abgeschlossen werden. Der Testcontainer hatte kein festes Speicherlimit; bei einem erneuten Test Ressourcen vorher begrenzen und die vorhandene Systemauslastung prüfen.
|
||||
|
||||
**Aktuelle Störung:** Während der Zusatzprüfungen reagiert der Pi weiterhin auf Ping, neue SSH-Verbindungen hängen jedoch beim Banner-Austausch. Auch n8n- und Portainer-HTTP-Prüfungen laufen in Zeitüberschreitungen. Speicher-/Ressourcenengpass ist ein Verdacht, kein belegter Befund; Systemprotokolle noch nicht lesbar. Produktives Compose und produktives Volume wurden nicht auf die neue Version umgestellt. Die gezielten Stoppversuche über SSH konnten noch nicht ausgeführt werden. Kein Neustart des gesamten Pi oder anderer Dienste durch den Agenten.
|
||||
|
||||
**Nächster Schritt über lokale Pi-Konsole oder erreichbare Containerverwaltung:** ausschließlich den Testcontainer stoppen:
|
||||
|
||||
```sh
|
||||
docker stop -t 3 n8n-upgrade-test-20261028t080618z
|
||||
```
|
||||
|
||||
Danach freien Speicher, Last und OOM-/Kernelmeldungen prüfen; Gesundheit und Version des ursprünglichen Containers `n8n` kontrollieren. Erst anschließend über Fortsetzung entscheiden. Ein Downgrade nach späterer produktiver Datenbankmigration würde neben dem alten Image auch eine passende vollständige Datensicherung benötigen; kein `down -v`, keine pauschale Container-/Volume-Bereinigung. Die Zugangsnotizen im vorherigen Abschnitt beschreiben die Befunde vor diesem Upgradeversuch.
|
||||
|
||||
### Fotos aus dem alten WordPress übernehmen
|
||||
|
||||
Die Auswahl (39 aktuelle Fotos: Wohnung, Garten/Terrasse/Luftbilder, Umgebung – ohne Theme-Platzhalter, Logos, Vorschaugrößen und veraltete Einrichtung) mit Kategorie und Bildbeschreibung steht in [database/data/wordpress-photos.csv](../database/data/wordpress-photos.csv). Der Import **liest** die Dateien nur aus dem WordPress-Ordner (dort wird nichts verändert), legt Original + WebP-Größen in `shared/storage/app/public` ab und überspringt bereits importierte Fotos (wiederholbar):
|
||||
|
||||
+15
-5
@@ -1,11 +1,12 @@
|
||||
# Deployment auf Strato
|
||||
|
||||
Stand: 22.10.2026 · Skript: `scripts/deploy.sh` · CI: `.gitea/workflows/deploy.yml`
|
||||
Stand: 26.10.2026 · Gemeinsamer Manager: [PipelineManager](https://gitea.stommer.de/Lars/PipelineManager) · Pilotkonfiguration: `pipeline.toml` · CI: `.gitea/workflows/deploy.yml`
|
||||
|
||||
## 1. Prinzip
|
||||
|
||||
```
|
||||
Gitea (main/Tag) ──► Build (CI oder lokal): git-Stand · composer --no-dev · npm run build
|
||||
Gitea (develop/main) ──► PipelineManager-Container auf Raspi5-Paperless
|
||||
│ exakter Git-Commit · Abhängigkeiten · Tests · fertige Assets
|
||||
│ tar.gz
|
||||
▼ SSH
|
||||
Strato <DEPLOY_PATH>/
|
||||
@@ -20,6 +21,10 @@ ## 1. Prinzip
|
||||
|
||||
Auf dem Server werden nur **bash, tar und PHP-CLI** gebraucht – kein Composer, kein Node, kein Git, kein rsync.
|
||||
|
||||
Die Werkzeugumgebung wird im eigenen Repository `C:\dev\pipelinemanager` entwickelt und als lokales Image `pipeline-manager:0.1.1` auf dem Pi freigegeben. Das Image bleibt nach dem Entfernen eines Job-Containers erhalten. Der Ablauf folgt Tsumugus Docker-Aufträgen auf dem vorhandenen Host-Runner (`ubuntu-latest`), führt Tests jedoch am exakten Commit vor dem Upload aus. Keine PHP-/Node-Installation auf dem Host und kein Build auf dem Entwicklungsrechner für automatische Deployments.
|
||||
|
||||
FeWo definiert nur seine prepare/test/finalize-Befehle, erforderlichen Dateien, Laravel-Hooks, persistenten Pfade und Ziele in `pipeline.toml`. Gemeinsame Paket-, Sicherungs-, Upload- und Rückfalllogik liegt im PipelineManager. Der bisherige manuelle Weg über `scripts/deploy.sh` bleibt als bestehender Wartungsweg erhalten, bis die neue Anbindung vollständig auf Test bestätigt ist.
|
||||
|
||||
## 2. SSH oder SFTP?
|
||||
|
||||
**Empfehlung: SSH.** Das Skript führt nach dem Hochladen Befehle auf dem Server aus (Archiv entpacken, Datenbank migrieren, Caches erzeugen, Version umschalten, ggf. zurückschalten). Das geht nur mit SSH.
|
||||
@@ -77,9 +82,14 @@ ## 4. Tägliche Nutzung
|
||||
|
||||
## 5. Automatisch über Gitea Actions
|
||||
|
||||
- Workflow `.gitea/workflows/deploy.yml`: **Tests bei jedem Push**; **Deployment** bei Tags `v*` (z. B. `git tag v1.0.0 && git push --tags`) oder per Knopfdruck (Actions › Deploy › Run workflow, Ziel production/staging).
|
||||
- Voraussetzung: Gitea Actions aktiviert und ein **act_runner** registriert – passt gut auf den privaten Server (Docker). Anleitung: Gitea-Doku „Act Runner“.
|
||||
- Repository-Secrets: `DEPLOY_SSH_KEY` (privater Schlüssel, dessen öffentlicher Teil bei Strato hinterlegt ist), `DEPLOY_HOST`, `DEPLOY_USER`, `DEPLOY_PATH`, `DEPLOY_PHP`, `DEPLOY_URL`.
|
||||
- Push auf `develop`: Manager-Image prüfen, FeWo vorbereiten und die Feature-Suite im Container ausführen, danach nach `test.fewo-stommer.de/` unter https://stommer.info deployen. Merge-Commit von `develop` nach `main`: derselbe Ablauf für `prod.fewo-stommer.de/`, sobald dieses Ziel ausdrücklich in `pipeline.toml` aktiviert ist.
|
||||
- Produktion ist derzeit `enabled=false`: Der Workflow überspringt Vorbereitung und Deployment. Eigenständige Produktionsdatenbank, `.env` und Domain-Zuordnung müssen vor Freigabe eingerichtet werden. Das bestehende WordPress-Verzeichnis `www.fewo-stommer.de/` bleibt unangetastet.
|
||||
- Die 18 Manager-Tests liegen im separaten Repository; die Anwendung behält ihre 285 Feature-Tests. Kein `setup-php`, kein `setup-node`, keine Toolinstallation auf dem Pi-Host. Der bisherige Node-24-/PHP-Setup-Fehler entfällt damit.
|
||||
- Build und Deployment laufen in getrennten Containeraufrufen mit UID/GID des Runners und Ressourcenlimits. Nur der Deployment-Container erhält die Strato-Zugänge. Er bekommt weder den Docker-Socket noch Verzeichnisse anderer Anwendungen.
|
||||
- OpenSSH benötigt eine auflösbare lokale UID: Der Deployment-Container erhält `/etc/passwd` des Linux-Runners schreibgeschützt, keine Passwort-Hashes. Docker meldet auf dem Pi fehlende Memory-Cgroup-Unterstützung; `--memory` wird dort derzeit nicht durchgesetzt. Die PHP-Tests haben zusätzlich ein eigenes Limit von 512 MB. Eine Änderung der Pi-Kernelkonfiguration gehört nicht zum Anwendungsdeploy.
|
||||
- Persistente Verzeichnisse auf dem Pi: `/home/lars/docker/pipeline-manager/cache` (Composer/npm) und `backups/<project>/<environment>` (Datenbank, Medien und Server-Konfiguration). Backups werden vor dem Upload geprüft; ein Fehler verhindert die Auslieferung. Eine Sperre auf Strato verhindert parallele Umschaltungen desselben Ziels.
|
||||
- Repository-Secrets sind eingerichtet: `DEPLOY_HOST`, `DEPLOY_USER`, `DEPLOY_SSH_KEY` (eigener Pipeline-Schlüssel), `DEPLOY_KNOWN_HOSTS` (geprüfter Hostschlüssel). Geheimnisse bleiben außerhalb von Image und Repository. Der Manager schreibt sie nur vorübergehend in geschützte Dateien.
|
||||
- Die auf dem Pi freigegebene Image-Version muss vor dem FeWo-Workflow vorhanden sein. Für weitere Runner mit anderer Architektur ist eine entsprechende Imagebereitstellung erforderlich. Erst nach erfolgreichem Pilotlauf wird der alte manuelle Deploy-Weg ersetzt.
|
||||
|
||||
## 6. Getestet / offen
|
||||
|
||||
|
||||
+14
-8
@@ -1,10 +1,10 @@
|
||||
# Mandantenfähigkeit – Umbauplan
|
||||
|
||||
Stand: 24.10.2026 · **Phasen 1 bis 5 umgesetzt**, Phase 6 auf der Anwendungsseite ebenfalls. Offen: der Theme-Teil von Phase 6 (§6 der Zusammenarbeit) und Phase 7 · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md) · Design: [DESIGN-KONZEPT.md](DESIGN-KONZEPT.md) §7 · Übergabe: [STATUS.md](STATUS.md) Abschnitt 7
|
||||
Stand: 26.10.2026 · **Phasen 1–6 und Kern von Phase 7 umgesetzt und ausgeliefert.** Mandantenabschluss: Commit `06df80e`, Pipeline-Lauf 4661 erfolgreich; Abnahme siehe STATUS. Neue Wohnungsübersichts-/Suchbausteine und Subscription/Abrechnung gehören zur funktionalen Weiterentwicklung. Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md).
|
||||
|
||||
Kein Portal, kein Marktplatz. Das Produkt bleibt die eigene Website eines Vermieters mit Vermietung. Wenige Mandanten, eine gemeinsame Datenbank, Laravel und Filament bleiben die Basis. Ein Python-Dienst ist nicht Teil dieses Umbaus.
|
||||
|
||||
Weiterarbeiten auf einem neuen Branch ab `main`. `feature/mandanten` ist zusammengeführt. Phasen 1–5 sind der Grundumbau. Marke/Bildwelt (Phase 6) und mehrere Wohnungen je Website (Phase 7) folgen in der festgelegten Reihenfolge und starten erst, wenn die Theme-Sitzung die Vertragsänderung aus [ZUSAMMENARBEIT.md](ZUSAMMENARBEIT.md) §6 übernehmen kann. `resources/themes/**` bleibt bis dahin unangetastet.
|
||||
Weiterarbeiten auf einem neuen Branch ab aktuellem `develop`; Zusammenführen und Testdeploy ebenfalls über `develop`. `feature/mandanten` ist zusammengeführt. Phasen 1–5 sind der Grundumbau. Die Anwendungsseite von Marke/Bildwelt (Phase 6) und die Wohnungswahl je Baustein (Phase 7) sind fertig, ohne Theme-Dateien zu ändern. Der verbleibende Theme-Teil von Phase 6 und spätere neue Bausteine brauchen die Abstimmung des Vorlagen-Vertrags aus [ZUSAMMENARBEIT.md](ZUSAMMENARBEIT.md) §6. `resources/themes/**` bleibt außerhalb dieser Arbeiten unangetastet.
|
||||
|
||||
---
|
||||
|
||||
@@ -205,7 +205,7 @@ ## 7. Domain, Cron, Mails
|
||||
|
||||
## 8. Phasen
|
||||
|
||||
Abgeschlossene Phasen liegen auf `main`. Die nächste Phase bekommt einen eigenen Branch ab `main`, grüne Tests (`php artisan test --compact --testsuite=Feature` auf die betroffenen Dateien, am Ende der Phase die Feature-Suite) und ist für sich nach `main` zusammenführbar. `php artisan test` ohne `--testsuite=Feature` bricht ab, weil `tests/Unit` nicht existiert. Ausgeliefert wird nur aus `main`. `resources/themes/**` wird nicht geändert. Nach dem Zusammenführen schreibt die Sitzung `docs/STATUS.md`. Eine Änderung am Vorlagen-Vertrag gibt es in Phase 1–5 nicht; §6 von ZUSAMMENARBEIT bleibt deshalb in diesen Phasen leer.
|
||||
Die abgeschlossenen Anwendungsphasen wurden ursprünglich nach `main` zusammengeführt. Für weitere Arbeiten gilt jetzt der PipelineManager-Ablauf: eigener Branch ab `develop`, grüne Tests (`php artisan test --compact --testsuite=Feature` auf die betroffenen Dateien, am Ende der Phase die Feature-Suite), Zusammenführen nach `develop` und automatischer Testdeploy. Produktion folgt über Merge-Commit `develop` → `main`, sobald ausdrücklich freigegeben; derzeit gesperrt. `php artisan test` ohne `--testsuite=Feature` bricht ab, weil `tests/Unit` nicht existiert. `resources/themes/**` wird nicht geändert. Nach dem Zusammenführen schreibt die Sitzung `docs/STATUS.md`. Eine Änderung am Vorlagen-Vertrag gibt es in Phase 1–5 nicht; §6 von ZUSAMMENARBEIT bleibt deshalb in diesen Phasen leer.
|
||||
|
||||
### Phase 1 – Mandant und Daten
|
||||
|
||||
@@ -261,7 +261,7 @@ ### Phase 5 – Abnahme der Trennung und Kündigung · umgesetzt
|
||||
|
||||
Tests: Nach der Löschung von A ist B vollständig da, inklusive Dateien und Buchungsnummern. Export von A enthält keine Zeile von B.
|
||||
|
||||
### Phase 6 – Marke und Bildwelt · Anwendungsseite umgesetzt (24.10.), Theme-Teil offen
|
||||
### Phase 6 – Marke und Bildwelt · vollständig umgesetzt (26.10.)
|
||||
|
||||
A14, A18, A19, A20, A22. Nicht zusammen mit Phase 1–5, und nicht solange der Branch `theme/<key>` die Vorlagen noch nicht nachziehen kann.
|
||||
|
||||
@@ -271,15 +271,21 @@ ### Phase 6 – Marke und Bildwelt · Anwendungsseite umgesetzt (24.10.), Theme-
|
||||
|
||||
**Umgesetzt am 24.10. (ohne eine Theme-Datei zu ändern):** Bildwelten als Pakete in `resources/image-worlds/<key>/`, Registry, Auswahl an der Website, Überschreibung an der Wohnung; `$theme->motif()`/`hasMotif()`/`imageWorld()` als Platz-API; `image-worlds:check`. Marke als Medien der Website mit `$theme->brand()`, eingebettet im Mietvertrag. Die Ostsee-Grafiken wurden **kopiert**, nicht verschoben.
|
||||
|
||||
**Offen und ein Vertragsfall (ZUSAMMENARBEIT.md §6):** `ostsee-licht` von `partials/brand` auf Plätze umstellen, das Favicon in beiden Themes zuerst bei `$theme->brand('favicon')` erfragen, und Seebads `motifs/`-Ordner gegen die Bildwelt tauschen. `public/brand/` entfällt erst danach.
|
||||
**Abschluss 26.10.:** Beide Themes nutzen Website-Marke und Bildwelt-Plätze; ohne Marke wird keine fremde Identität angezeigt. Alte Grafikdateien bleiben nur als Importquellen erhalten. `sites:import-stommer-brand <site-id>` übernimmt die vorhandene Stommer-Marke ohne Überschreiben. Auch HTML-/Textmails sind mandanteneigen. Verträge und Angebote haben getrennte Speicherpfade; Export/Löschung schließen Website-Medien und Vertragsdateien ein. Regressionstests: `TenantBrandRenderingTest`, `TenantFilesTest`. Der Vorlagenvertrag ist in ZUSAMMENARBEIT §6 eingetragen.
|
||||
|
||||
### Phase 7 – Mehrere Wohnungen je Website (zuletzt, eigene Sitzung)
|
||||
### Phase 7 – Mehrere Wohnungen je Website · Kern umgesetzt und ausgeliefert (26.10.)
|
||||
|
||||
A21. Die Seite bleibt bei einer Wohnung, solange ein Baustein keine nennt.
|
||||
|
||||
- Im Seiten-Baukasten kann ein Baustein eine Wohnung dieser Website wählen. Ohne Wahl gilt `primaryProperty()` wie heute.
|
||||
- Der Renderer setzt diese Wohnung, bevor der Baustein läuft. Bestehende Vorlagen, die `$theme->property()` rufen, bleiben gültig. Eine neue Übersicht auf der Startseite und eine Suche über mehrere Wohnungen sind neue Bausteine im Katalog; auch das ist ein Eintrag in §6, bevor eine Theme-Datei entsteht.
|
||||
|
||||
**Abgeschlossener Umfang:** gemeinsames Auswahlfeld `data.property_id` im Seiten-Baukasten, beschränkt auf aktive Wohnungen derselben Website. Ohne Auswahl gilt die Hauptwohnung. `SectionRegistry` prüft die Zuordnung beim Rendern erneut; fremde, inaktive oder gelöschte Wohnungen führen zum Überspringen des Bausteins. `Theme::runForProperty()` setzt den Kontext auch während der verzögerten Ausgabe durch `SectionView` einschließlich Blade/Livewire und stellt ihn im `finally` bei Fehlern und verschachtelten Aufrufen wieder her. Damit folgt auch die Bildwelt der gewählten Wohnung. Keine Theme-Datei, Tabelle, Migration oder Abhängigkeit geändert.
|
||||
|
||||
**Nachweis:** `tests/Feature/SectionPropertyTest.php` mit 13 Fällen für gemischte Wohnungen, Hauptwohnungs-Fallback, Buchungsformular, verzögerte Ausgabe, Verschachtelung/Fehler und Website-/Mandantengrenzen. Gesamtsuite: **285 Tests, 1289 Assertions grün**, zuletzt erneut im automatischen Pipeline-Lauf [4658](https://gitea.stommer.de/Lars/fewo-stommer/actions/runs/4658). Ursprüngliche Auslieferung: Commit `abf0e90`, Release `20261026072521`; auch im per PipelineManager ausgelieferten Stand enthalten. Details und technische Übergabe: [STATUS.md](STATUS.md) Abschnitt 7.
|
||||
|
||||
**Separat und optional:** Neue Übersichts- und Suchbausteine sind nicht Teil dieses abgeschlossenen Kerns. Sie benötigen einen eigenen Auftrag und vor Theme-Änderungen den Eintrag in ZUSAMMENARBEIT.md §6. Die bereits abgeschlossene Wohnungswahl nicht erneut implementieren.
|
||||
|
||||
---
|
||||
|
||||
## 9. Betrieb und Abgrenzung
|
||||
@@ -295,8 +301,8 @@ ## 9. Betrieb und Abgrenzung
|
||||
|
||||
## 10. Freigabe
|
||||
|
||||
**Phasen 1 bis 5 sind umgesetzt und ausgeliefert**, von Phase 6 die Anwendungsseite (auf `main`, noch nicht ausgeliefert). Der Grundumbau ist damit fertig: Daten, Rollen, Einstellungen, Domains, Hintergrundläufe, Export und Kündigung, dazu Bildwelten und die Marke je Website. **Phase 7 schließt eine eigene Sitzung ab**; die Übergabe dafür steht in [STATUS.md](STATUS.md) Abschnitt 7. Die bisherigen Daten gehören zum Mandanten Stommer, `lars@stommer.com` ist Betreiber. Ausgelieferter Stand und Übergabe: [STATUS.md](STATUS.md) Abschnitt 7.
|
||||
**Phasen 1 bis 5, die Anwendungsseite von Phase 6 und der Kern von Phase 7 sind umgesetzt und ausgeliefert.** Der Grundumbau ist fertig: Daten, Rollen, Einstellungen, Domains, Hintergrundläufe, Export und Kündigung, dazu Bildwelten, Marke je Website und Wohnungswahl je Baustein. Phase 7 braucht keine weitere Implementierung oder gesonderte Freigabe für diesen Kern. Die bisherigen Daten gehören zum Mandanten Stommer, `lars@stommer.com` ist Betreiber. Auslieferungsnachweise und Übergabe: [STATUS.md](STATUS.md) Abschnitt 7.
|
||||
|
||||
Offen und **nicht** Teil dieses Plans: Subscription und Abrechnung (§9 schließt sie aus; `service_usages` liegt als Grundlage bereit) sowie die Frage, ob Strato für die Domain eines Mandanten ein Zertifikat ausstellt – davon hängt ab, ob das Modell „Mandant bringt seine Domain mit" auf diesem Hosting trägt. Phase 6 und 7 warten auf eine eigene Freigabe und einen Eintrag in [ZUSAMMENARBEIT.md](ZUSAMMENARBEIT.md) §6.
|
||||
Offen und **nicht** Teil dieses Plans: Subscription und Abrechnung (§9 schließt sie aus; `service_usages` liegt als Grundlage bereit) sowie die Frage, ob Strato für die Domain eines Mandanten ein Zertifikat ausstellt – davon hängt ab, ob das Modell „Mandant bringt seine Domain mit" auf diesem Hosting trägt. Nur der verbleibende Theme-Teil von Phase 6 und optionale neue Bausteine benötigen weitere Abstimmung und vor Theme-Änderungen einen Eintrag in [ZUSAMMENARBEIT.md](ZUSAMMENARBEIT.md) §6.
|
||||
|
||||
Die Sicherheitsregel in §1 gilt: Passwort und 2FA gehören zum Konto, die Rolle zur Mitgliedschaft. Der Betreiber darf zusätzlich Mandanten-Administrator der eigenen Wohnung sein.
|
||||
@@ -1,7 +1,11 @@
|
||||
# Portal-Analyse: Kalender-Abgleich, Buchungshoheit, Empfehlung
|
||||
|
||||
**MVP-Folgeauftrag 27.10.2026:** [Bereitstellung und Benutzung](architecture/ical-mvp-inbetriebnahme-2026-10-27.md) beschreibt die automatische Generierung eines eigenen Exportlinks je Portal in der vorhandenen Oberfläche, persönliche Zuordnung mehrfacher Kalenderdarstellungen und konfigurierbares Echoverhalten. Die offene Frage zur zusätzlichen Kalenderpflege-Bestätigung bei Ostseeklar wird dort festgehalten. Reale Importadressen werden vom externen Portal bezogen und in der Oberfläche eingetragen.
|
||||
|
||||
Stand: 22.10.2026 · Grundlage: öffentliche Hilfeseiten und Vertragsunterlagen der Anbieter (Quellen unten). Konditionen, die nur Dritte nennen oder die vertragsabhängig sind, sind als **„prüfen“** markiert.
|
||||
|
||||
**Implementierungsergänzung 27.10.2026, noch nicht ausgeliefert:** [Generische iCal-Kanalkonfiguration](architecture/ical-kanalkonfiguration.md) dokumentiert die lokale Erweiterung mit unabhängigen Richtungen, Test-/Regulärmodus, eingefrorenen Exporten, Herkunft, sicherer Änderung/Entfernung und Tests. Die folgenden Anbieterangaben bleiben Recherche vom 22.10., keine neue Verifikation. Die frühere Beschreibung einer Mail/iCal-Übernahme anhand gleicher Termine in Abschnitt 4b ist im neuen Stand ersetzt: Zusammenführung nur über gemeinsame Referenz/UID; unbekannte Zuordnungen bleiben Prüffälle. Im Testmodus werden Fremdbelegungen auch nicht an andere Portale weitergegeben. Die von Lars berichtete erfolgreiche FeWo-direkt-Probe ist dort als einzelner Nutzerbericht getrennt von automatisierten Nachweisen erfasst.
|
||||
|
||||
## 1. Kurzfazit
|
||||
|
||||
1. **Die meisten genannten Portale nehmen Kalender per iCal an** – FeWo-direkt, Ostseeklar und ferienundwohnen.de (automatisch nur im Premium-Inserat). Echtes „wir müssen führend sein“ verlangen vor allem **Systeme mit Online-Buchung über eine Software-Schnittstelle**: das Buchungssystem der Tourist-Information (DS Destination Solutions) und jedes Portal, sobald es per Channel-Manager-API angebunden ist (dann schaltet z. B. FeWo-direkt den iCal-Import ab).
|
||||
|
||||
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user