Pakete 8, 5 und 6: Beträge und Zahlungen, Ändern und Stornieren, A6 im Vorgang
Deploy FeWo mit PipelineManager / deploy (push) Successful in 4m44s
Deploy FeWo mit PipelineManager / deploy (push) Successful in 4m44s
- Paket 8: Zahlungsarten (Gast an uns, laut Portal, Auszahlung, Erstattung), Portalbeträge als Angaben mit Quelle, Übersicht nach Zuständigkeit (R09). - Paket 5: Ändern mit Folgenvorschau, vereinbart oder dem Gast vorgeschlagen (signierter Link), ein Stornoweg mit Grund und Erstattung, Portalstorno erst nach Bestätigung. - Paket 6: eigene Nutzung, Besuch und Sperre als Vorgang mit Kurabgabe und Aufenthaltsbestätigung; Bestandsübernahme der Sperren mit identischem Export. - Wirksame Einstellungen (Expertenansicht), Abnahmekatalog T01–T14, Ergebnis-, Abnahme- und Konfigurationsdokument. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
33f8f899d6
commit
3bcfc09417
77 files changed
+3638
-122
No files matched your search
@@ -5,11 +5,13 @@
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Enums\Responsibility;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\BookingCancelled;
|
||||
use App\Mail\CancellationRequested;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Process\CaseLog;
|
||||
use App\Support\CancellationCost;
|
||||
use App\Support\Money;
|
||||
use App\Support\Settings;
|
||||
@@ -19,45 +21,53 @@
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The landlord cancels a binding booking. The dates are free again; the guest and the landlord are informed by mail
|
||||
* (the guest mail can be switched off, e.g. when the guest cancelled by phone and was told already) and a task for
|
||||
* the cancellation costs is created. Open cancellation requests of the guest are completed.
|
||||
* The one way to cancel a binding booking (package 5). Own bookings: the dates are free again; the guest and the
|
||||
* landlord are informed by e-mail – the guest's e-mail can be switched off, e.g. when the guest cancelled by phone –, the
|
||||
* cancellation is recorded with who initiated it, why and who entered it, a task for the cancellation costs and – when
|
||||
* the guest paid us more than the costs – a refund task are created. Open cancellation requests of the guest are done.
|
||||
*
|
||||
* Bookings binding on a portal (A3–A5) are cancelled where the contract was made: here the cancellation is only
|
||||
* requested (task "Stornierung im Portal veranlassen bzw. prüfen", the dates stay occupied) until somebody confirms that
|
||||
* it is effective on the portal ({@see confirmOnPortal()}) – nothing is released silently.
|
||||
*/
|
||||
class CancelBooking
|
||||
{
|
||||
public const INITIATORS = ['guest' => 'vom Gast', 'landlord' => 'vom Vermieter', 'portal' => 'über das Portal'];
|
||||
|
||||
/**
|
||||
* @return bool whether the guest has been informed (true as well when no mail was wanted; false when it failed)
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung', string $initiatedBy = 'landlord'): bool
|
||||
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung', string $initiatedBy = 'landlord', ?string $reason = null, bool $confirmedOnPortal = false): bool
|
||||
{
|
||||
if ($booking->caseType()->isExternallyBinding() && ! $confirmedOnPortal) {
|
||||
$this->requestOnPortal($booking, $by, $initiatedBy, $reason);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($notifyGuest && blank($booking->guest?->email)) {
|
||||
throw new ReservationException('Der Gast hat keine E-Mail-Adresse – bitte ohne Mail an den Gast stornieren oder die Adresse ergänzen.');
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy): void {
|
||||
DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy, $reason): void {
|
||||
$booking->lockForTransition();
|
||||
|
||||
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
|
||||
}
|
||||
|
||||
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
|
||||
app(RecordCancellation::class)->handle($booking, $initiatedBy);
|
||||
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now(), 'portal_cancellation_requested_at' => null]);
|
||||
app(RecordCancellation::class)->handle($booking, $initiatedBy)->update(['reason' => $reason, 'recorded_by' => $by]);
|
||||
|
||||
if ($booking->caseType()->isExternallyBinding()) {
|
||||
// The contract was made on the portal: the cancellation has to happen (or be checked) there as well.
|
||||
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::PortalCancellation], [
|
||||
'status' => BookingTaskStatus::Open,
|
||||
'due_on' => today(),
|
||||
'note' => 'Stornierung auch im Portal „'.($booking->processChannel()?->name ?? 'Portal').'“ veranlassen bzw. prüfen, ob sie dort wirksam ist.',
|
||||
]);
|
||||
}
|
||||
|
||||
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->where('status', BookingTaskStatus::Open)
|
||||
BookingTask::query()->where('booking_id', $booking->id)
|
||||
->whereIn('kind', [BookingTaskKind::CancellationRequest, BookingTaskKind::PortalCancellation, BookingTaskKind::PortalCancellationReported])
|
||||
->where('status', BookingTaskStatus::Open)
|
||||
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
|
||||
|
||||
$this->refundTask($booking);
|
||||
|
||||
if ($costsTask) {
|
||||
$cost = CancellationCost::calculate($booking);
|
||||
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], [
|
||||
@@ -73,6 +83,60 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa
|
||||
return $this->notify($booking, $notifyGuest);
|
||||
}
|
||||
|
||||
/**
|
||||
* A booking binding on a portal was cancelled there (the landlord saw it on the portal, or the portal reported it):
|
||||
* now the case is cancelled as well. The portal informs the guest; costs are a task only when we collect the money.
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function confirmOnPortal(Booking $booking, string $by, string $initiatedBy = 'portal', ?string $reason = null): bool
|
||||
{
|
||||
return $this->handle($booking, notifyGuest: false, costsTask: $booking->process()->payments() === Responsibility::Landlord, by: $by, initiatedBy: $initiatedBy, reason: $reason, confirmedOnPortal: true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
private function requestOnPortal(Booking $booking, string $by, string $initiatedBy, ?string $reason): void
|
||||
{
|
||||
DB::transaction(function () use ($booking, $by, $initiatedBy, $reason): void {
|
||||
$booking->lockForTransition();
|
||||
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
|
||||
}
|
||||
|
||||
$portal = $booking->processChannel()?->name ?? 'Portal';
|
||||
$booking->update(['portal_cancellation_requested_at' => now()]);
|
||||
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::PortalCancellation], [
|
||||
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'completed_by' => null, 'completed_at' => null,
|
||||
'note' => 'Stornierung im Portal „'.$portal.'“ veranlassen und prüfen, ob sie dort wirksam ist. Erst dann „Stornierung bestätigen“ – bis dahin bleibt der Zeitraum belegt.',
|
||||
]);
|
||||
CaseLog::record($booking, 'status', 'Stornierung beim Portal '.$portal.' veranlasst ('.(self::INITIATORS[$initiatedBy] ?? $initiatedBy).') – der Vorgang bleibt gebucht, bis sie bestätigt ist', $reason, actor: $by);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* When the guest paid us more than the cancellation costs, the difference is a refund to check.
|
||||
*/
|
||||
private function refundTask(Booking $booking): void
|
||||
{
|
||||
if ($booking->process()->payments() !== Responsibility::Landlord || $booking->paidToUs() <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$cost = CancellationCost::calculate($booking);
|
||||
$fee = $cost['fee'] ?? null;
|
||||
$paid = $booking->paidToUs();
|
||||
if ($fee !== null && $paid <= $fee) {
|
||||
return;
|
||||
}
|
||||
|
||||
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::RefundCheck], [
|
||||
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'completed_by' => null, 'completed_at' => null,
|
||||
'note' => 'Bezahlt: '.Money::format($paid).($fee !== null ? ' · Stornokosten laut Regel: '.Money::format($fee).' · zu erstatten: '.Money::format($paid - $fee) : ' · Stornokosten von Hand festlegen, den Rest erstatten').'. Erstattung als Zahlung „Erstattung an den Gast“ erfassen.',
|
||||
]);
|
||||
}
|
||||
|
||||
private function notify(Booking $booking, bool $notifyGuest): bool
|
||||
{
|
||||
$informed = true;
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Enums\ChangeBasis;
|
||||
use App\Enums\ChangeStatus;
|
||||
use App\Enums\QuoteLineType;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\BookingChanged;
|
||||
use App\Mail\ChangeProposed;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingChange;
|
||||
use App\Models\BookingTask;
|
||||
use App\Models\Channel;
|
||||
use App\Pricing\PortalPrice;
|
||||
use App\Pricing\PriceCalculator;
|
||||
use App\Pricing\PriceQuote;
|
||||
use App\Pricing\PrivateStayPrice;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\QuoteLine;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Process\CaseLog;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Changes a booking after it became binding (package 5, UMSETZUNGSPLAN §4.6): dates, length of stay, number of guests,
|
||||
* services and price. Before anything changes the consequences are put together – calendar and portals, price and its
|
||||
* origin, payment plan, refund or additional payment, confirmation – and the person confirms them.
|
||||
*
|
||||
* Two ways, kept strictly apart:
|
||||
* - **agreed**: the change was already agreed with the guest (phone, e-mail, in person, on the portal); it takes effect
|
||||
* at once and the case keeps who asked, why, from when and on which basis. An updated confirmation only informs the
|
||||
* guest – it is not taken as the guest's consent.
|
||||
* - **proposed**: the guest still has to agree; nothing changes until the guest accepts through the signed link.
|
||||
*
|
||||
* Own bookings get their price recalculated (kept adjustments, or an agreed price); bookings binding on a portal take the
|
||||
* portal's new total; internal cases (A6) keep their agreed rent and recalculate services and tourist tax.
|
||||
*/
|
||||
class ChangeBooking
|
||||
{
|
||||
public const REQUESTED_BY = ['guest', 'landlord', 'portal'];
|
||||
|
||||
public function __construct(
|
||||
private PriceCalculator $calculator,
|
||||
private PrivateStayPrice $privateStay,
|
||||
private AvailabilityChecker $availability,
|
||||
private PortalPrice $portalPrice,
|
||||
private RecordPayment $payments,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The consequences of a change, without changing anything.
|
||||
*
|
||||
* @param array{arrival?: ?string, departure?: ?string, guests?: ?int, extras?: ?array<int, int>, portal_total?: ?int, agreed_total?: ?int, agreed_total_label?: ?string, rent?: ?int, tourist_tax_persons?: ?int} $changes
|
||||
* @return array{errors: list<string>, before: array<string, mixed>, after: array<string, mixed>, summary: list<string>, calendar: list<string>, portals: list<string>, price: array{before: ?int, after: ?int, difference: ?int, source: string}, payment: list<string>, refund: int, confirmation: bool}
|
||||
*/
|
||||
public function preview(Booking $booking, array $changes): array
|
||||
{
|
||||
$booking->loadMissing(['property', 'payments', 'guest']);
|
||||
$errors = [];
|
||||
$before = self::snapshot($booking);
|
||||
|
||||
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
|
||||
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
|
||||
$guests = array_key_exists('guests', $changes) && filled($changes['guests']) ? (int) $changes['guests'] : $booking->guests;
|
||||
$extras = array_key_exists('extras', $changes) && is_array($changes['extras']) ? array_filter(array_map('intval', $changes['extras'])) : (array) ($booking->extras ?? []);
|
||||
|
||||
if ($departure->lessThanOrEqualTo($arrival)) {
|
||||
$errors[] = 'Die Abreise muss nach der Anreise liegen.';
|
||||
} elseif (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
|
||||
$errors[] = 'Der neue Zeitraum ist nicht frei.';
|
||||
}
|
||||
if ($guests !== null && $guests > $booking->property->max_guests) {
|
||||
$errors[] = 'Höchstens '.$booking->property->max_guests.' Personen.';
|
||||
}
|
||||
|
||||
[$quote, $source, $priceError] = $departure->greaterThan($arrival) ? $this->price($booking, $changes, $arrival, $departure, $guests, $extras) : [null, '–', null];
|
||||
if ($priceError !== null) {
|
||||
$errors[] = $priceError;
|
||||
}
|
||||
|
||||
$paid = $booking->paidAmount();
|
||||
$total = $quote !== null ? $quote['total'] : $booking->total;
|
||||
$depositPaid = $booking->deposit !== null && $paid >= $booking->deposit && $paid > 0;
|
||||
$deposit = $quote === null ? $booking->deposit : ($depositPaid ? $booking->deposit : ($quote['deposit'] ?? $booking->deposit));
|
||||
$after = [
|
||||
'arrival' => $arrival->toDateString(), 'departure' => $departure->toDateString(), 'guests' => $guests, 'extras' => $extras,
|
||||
'quote' => $quote['quote'] ?? $booking->quote, 'total' => $total, 'deposit' => $deposit,
|
||||
'balance_due_on' => $quote['balance_due_on'] ?? $booking->balance_due_on?->toDateString(),
|
||||
'rent' => $changes['rent'] ?? null, 'tourist_tax_persons' => array_key_exists('tourist_tax_persons', $changes) ? $changes['tourist_tax_persons'] : $booking->tourist_tax_persons,
|
||||
];
|
||||
|
||||
[$calendar, $portals] = $this->calendarConsequences($booking, $arrival, $departure);
|
||||
$difference = $total !== null && $booking->total !== null ? $total - $booking->total : null;
|
||||
$refund = $total !== null ? max(0, $paid - $total) : 0;
|
||||
$payment = array_values(array_filter([
|
||||
$booking->wantsPaymentTasks() || ($total !== null && $total > 0 && $booking->process()->payments()->value === 'landlord' && ! $booking->isInternal()) ? 'Bezahlt bisher: '.Money::format($paid).' · danach offen: '.Money::format(max(0, (int) $total - $paid)) : null,
|
||||
$refund > 0 ? 'Der Gast hat mehr bezahlt als der neue Preis: '.Money::format($refund).' zu erstatten (Aufgabe wird angelegt).' : null,
|
||||
$depositPaid ? 'Die Anzahlung ist bezahlt und bleibt unverändert.' : null,
|
||||
$after['balance_due_on'] !== ($booking->balance_due_on?->toDateString()) && $after['balance_due_on'] !== null && ! $booking->isInternal() ? 'Restzahlung neu fällig am '.CarbonImmutable::parse($after['balance_due_on'])->format('d.m.Y').'.' : null,
|
||||
$booking->process()->payments()->value === 'portal' ? 'Die Zahlung läuft weiter über das Portal.' : null,
|
||||
]));
|
||||
|
||||
return [
|
||||
'errors' => $errors,
|
||||
'before' => $before,
|
||||
'after' => $after,
|
||||
'summary' => self::summary($before, $after),
|
||||
'calendar' => $calendar,
|
||||
'portals' => $portals,
|
||||
'price' => ['before' => $booking->total, 'after' => $total, 'difference' => $difference, 'source' => $source],
|
||||
'payment' => $payment,
|
||||
'refund' => $refund,
|
||||
'confirmation' => ! $booking->isInternal() && filled($booking->guest?->email),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* An agreed change (or a change of an internal case): takes effect at once.
|
||||
*
|
||||
* @param array<string, mixed> $changes
|
||||
* @param array{requested_by: string, reason: string, basis: ChangeBasis, agreed_at?: ?string, effective_on?: ?string, send_confirmation?: bool} $meta
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function apply(Booking $booking, array $changes, array $meta, ?string $by = null): BookingChange
|
||||
{
|
||||
$this->guard($booking);
|
||||
if ($meta['basis'] === ChangeBasis::GuestLink) {
|
||||
throw new ReservationException('Eine Zustimmung über den Link entsteht nur, wenn der Gast selbst annimmt.');
|
||||
}
|
||||
|
||||
$change = DB::transaction(function () use ($booking, $changes, $meta, $by): BookingChange {
|
||||
$booking->lockForTransition();
|
||||
$preview = $this->preview($booking, $changes);
|
||||
if ($preview['errors'] !== []) {
|
||||
throw new ReservationException(implode(' ', $preview['errors']));
|
||||
}
|
||||
|
||||
$change = $booking->changes()->create([
|
||||
'status' => ChangeStatus::Applied, 'requested_by' => $meta['requested_by'], 'basis' => $meta['basis'],
|
||||
'reason' => trim((string) $meta['reason']), 'effective_on' => $meta['effective_on'] ?? today()->toDateString(),
|
||||
'agreed_at' => $meta['basis'] === ChangeBasis::NotNeeded ? null : ($meta['agreed_at'] ?? now()),
|
||||
'agreed_by' => $meta['basis'] === ChangeBasis::NotNeeded ? null : ($booking->guest?->full_name ?? 'Gast'),
|
||||
'before' => $preview['before'], 'after' => $preview['after'], 'consequences' => self::consequences($preview),
|
||||
'applied_at' => now(), 'recorded_by' => $by,
|
||||
]);
|
||||
$change->tenant_id = $booking->tenant_id;
|
||||
$change->save();
|
||||
|
||||
$this->write($booking, $preview, $meta['reason'], $by, $change);
|
||||
|
||||
return $change;
|
||||
});
|
||||
|
||||
if ($meta['send_confirmation'] ?? false) {
|
||||
$this->confirm($booking->fresh(), $change);
|
||||
}
|
||||
|
||||
return $change->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* A change the guest still has to agree to: nothing changes; the guest gets a link to accept or decline.
|
||||
*
|
||||
* @param array<string, mixed> $changes
|
||||
* @param array{requested_by: string, reason: string, effective_on?: ?string, valid_days?: int} $meta
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function propose(Booking $booking, array $changes, array $meta, ?string $by = null): BookingChange
|
||||
{
|
||||
$this->guard($booking);
|
||||
if ($booking->isInternal() || $booking->caseType()->isExternallyBinding()) {
|
||||
throw new ReservationException('Ein Vorschlag mit Zustimmungslink ist nur für eigene Buchungen möglich – Portalbuchungen werden im Portal geändert.');
|
||||
}
|
||||
if (blank($booking->guest?->email)) {
|
||||
throw new ReservationException('Für einen Vorschlag wird die E-Mail-Adresse des Gastes benötigt.');
|
||||
}
|
||||
if ($booking->changes()->where('status', ChangeStatus::Proposed)->exists()) {
|
||||
throw new ReservationException('Es liegt schon ein Änderungsvorschlag beim Gast. Bitte zuerst zurückziehen.');
|
||||
}
|
||||
|
||||
$preview = $this->preview($booking, $changes);
|
||||
if ($preview['errors'] !== []) {
|
||||
throw new ReservationException(implode(' ', $preview['errors']));
|
||||
}
|
||||
|
||||
$change = $booking->changes()->create([
|
||||
'status' => ChangeStatus::Proposed, 'requested_by' => $meta['requested_by'], 'reason' => trim((string) $meta['reason']),
|
||||
'effective_on' => $meta['effective_on'] ?? null, 'before' => $preview['before'], 'after' => $preview['after'],
|
||||
'consequences' => self::consequences($preview), 'expires_at' => now()->addDays((int) ($meta['valid_days'] ?? 7)), 'recorded_by' => $by,
|
||||
]);
|
||||
$change->tenant_id = $booking->tenant_id;
|
||||
$change->save();
|
||||
CaseLog::record($booking, 'change', 'Änderung dem Gast vorgeschlagen: '.implode(' · ', $preview['summary']), $meta['reason'], data: ['booking_change_id' => $change->id]);
|
||||
|
||||
try {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ChangeProposed($booking, $change, $this->link($change)));
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Änderungsvorschlag nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
throw new ReservationException('Der Vorschlag ist gespeichert, aber die E-Mail konnte nicht versendet werden.');
|
||||
}
|
||||
|
||||
return $change;
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest accepts a proposed change through the signed link: the dates are checked again, then it takes effect.
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function accept(BookingChange $change, ?string $ip = null): BookingChange
|
||||
{
|
||||
return DB::transaction(function () use ($change, $ip): BookingChange {
|
||||
$booking = $change->booking;
|
||||
$booking->lockForTransition();
|
||||
$change = BookingChange::query()->whereKey($change->id)->lockForUpdate()->firstOrFail();
|
||||
if ($change->status !== ChangeStatus::Proposed) {
|
||||
throw new ReservationException('Dieser Vorschlag ist nicht mehr offen.');
|
||||
}
|
||||
if ($change->expires_at !== null && $change->expires_at->isPast()) {
|
||||
$change->update(['status' => ChangeStatus::Expired]);
|
||||
throw new ReservationException('Dieser Vorschlag ist abgelaufen. Bitte melden Sie sich bei uns.');
|
||||
}
|
||||
|
||||
$after = (array) $change->after;
|
||||
$preview = $this->preview($booking, [...$after, 'agreed_total' => $after['total'] ?? null, 'portal_total' => null]);
|
||||
if ($preview['errors'] !== []) {
|
||||
throw new ReservationException('Die Änderung ist leider nicht mehr möglich: '.implode(' ', $preview['errors']));
|
||||
}
|
||||
|
||||
$change->update(['status' => ChangeStatus::Applied, 'basis' => ChangeBasis::GuestLink, 'agreed_at' => now(), 'agreed_by' => $booking->guest?->full_name,
|
||||
'decided_at' => now(), 'decision_ip_hash' => $ip ? hash('sha256', $ip) : null, 'applied_at' => now()]);
|
||||
CaseLog::context(fn () => $this->write($booking, $preview, (string) $change->reason, CaseLog::GUEST, $change), actor: CaseLog::GUEST);
|
||||
|
||||
return $change->fresh();
|
||||
});
|
||||
}
|
||||
|
||||
public function decline(BookingChange $change, ?string $ip = null): void
|
||||
{
|
||||
if ($change->status !== ChangeStatus::Proposed) {
|
||||
return;
|
||||
}
|
||||
|
||||
$change->update(['status' => ChangeStatus::Declined, 'decided_at' => now(), 'decision_ip_hash' => $ip ? hash('sha256', $ip) : null]);
|
||||
CaseLog::record($change->booking, 'change', 'Änderungsvorschlag vom Gast abgelehnt', actor: CaseLog::GUEST, data: ['booking_change_id' => $change->id]);
|
||||
}
|
||||
|
||||
public function withdraw(BookingChange $change, ?string $by = null): void
|
||||
{
|
||||
if ($change->status === ChangeStatus::Proposed) {
|
||||
$change->update(['status' => ChangeStatus::Withdrawn, 'decided_at' => now()]);
|
||||
CaseLog::record($change->booking, 'change', 'Änderungsvorschlag zurückgezogen', actor: $by);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest's signed link to a proposed change (valid while the proposal is).
|
||||
*/
|
||||
public function link(BookingChange $change): string
|
||||
{
|
||||
$until = $change->expires_at ?? now()->addDays(7);
|
||||
|
||||
return $change->booking->website()?->temporarySignedRoute('changes.show', $until, ['change' => $change])
|
||||
?? URL::temporarySignedRoute('changes.show', $until, ['change' => $change]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the updated confirmation of an agreed change (information, not consent).
|
||||
*/
|
||||
public function confirm(Booking $booking, BookingChange $change): bool
|
||||
{
|
||||
if ($booking->isInternal() || blank($booking->guest?->email)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingChanged($booking, $change));
|
||||
$change->update(['confirmation_sent_at' => now()]);
|
||||
|
||||
return true;
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Änderungsbestätigung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
private function guard(Booking $booking): void
|
||||
{
|
||||
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||
throw new ReservationException('Ändern lässt sich nur eine bestehende Buchung oder Belegung. Ein Angebot wird über „Angebot ändern & neu senden“ geändert.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the new state on the case (inside the transaction of the caller).
|
||||
*
|
||||
* @param array<string, mixed> $preview
|
||||
*/
|
||||
private function write(Booking $booking, array $preview, string $reason, ?string $by, BookingChange $change): void
|
||||
{
|
||||
$after = $preview['after'];
|
||||
$booking->update([
|
||||
'arrival' => $after['arrival'], 'departure' => $after['departure'], 'guests' => $after['guests'], 'extras' => $after['extras'],
|
||||
'quote' => $after['quote'], 'total' => $after['total'], 'deposit' => $after['deposit'], 'balance_due_on' => $after['balance_due_on'],
|
||||
'tourist_tax_persons' => $after['tourist_tax_persons'],
|
||||
]);
|
||||
CaseLog::record($booking, 'change', 'Geändert: '.implode(' · ', $preview['summary']), $reason, data: ['booking_change_id' => $change->id], actor: $by);
|
||||
$this->payments->updateStatus($booking->fresh());
|
||||
|
||||
if ($preview['refund'] > 0) {
|
||||
BookingTask::query()->updateOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::RefundCheck], [
|
||||
'tenant_id' => $booking->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(),
|
||||
'note' => 'Nach der Änderung zu viel bezahlt: '.Money::format($preview['refund']).' an den Gast erstatten (als „Erstattung“ erfassen).',
|
||||
'completed_by' => null, 'completed_at' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The new price and where it comes from.
|
||||
*
|
||||
* @param array<string, mixed> $changes
|
||||
* @param array<int, int> $extras
|
||||
* @return array{0: ?array{quote: array<string, mixed>, total: int, deposit: ?int, balance_due_on: ?string}, 1: string, 2: ?string}
|
||||
*/
|
||||
private function price(Booking $booking, array $changes, CarbonImmutable $arrival, CarbonImmutable $departure, ?int $guests, array $extras): array
|
||||
{
|
||||
if ($booking->isInternal()) {
|
||||
try {
|
||||
$rent = array_key_exists('rent', $changes) && $changes['rent'] !== null ? (int) $changes['rent'] : PrivateStayPrice::rentOf($booking->quote);
|
||||
$taxPersons = array_key_exists('tourist_tax_persons', $changes) ? ($changes['tourist_tax_persons'] === null ? null : (int) $changes['tourist_tax_persons']) : $booking->tourist_tax_persons;
|
||||
$quote = $this->privateStay->quote($booking->property, $arrival, $departure, $guests, $extras, $rent, $taxPersons);
|
||||
|
||||
return [['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => null, 'balance_due_on' => null], 'vereinbart (Miete, Leistungen, Kurabgabe)', null];
|
||||
} catch (QuoteException $exception) {
|
||||
return [null, '–', $exception->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
if ($booking->caseType()->isExternallyBinding() || ($booking->quote['source'] ?? null) === 'portal') {
|
||||
$total = filled($changes['portal_total'] ?? null) ? (int) $changes['portal_total'] : $booking->total;
|
||||
if ($total === null) {
|
||||
return [null, 'laut Portal – noch nicht bekannt', null];
|
||||
}
|
||||
$columns = $this->portalPrice->columns($booking->property, $arrival, $departure, $guests, $total, $booking->processChannel()?->name);
|
||||
|
||||
return [['quote' => $columns['quote'], 'total' => (int) $columns['total'], 'deposit' => $columns['deposit'], 'balance_due_on' => $columns['balance_due_on']],
|
||||
filled($changes['portal_total'] ?? null) ? 'neuer Gesamtpreis laut Portal' : 'Gesamtpreis laut Portal unverändert – bitte neuen Betrag eintragen, falls das Portal ihn geändert hat', null];
|
||||
}
|
||||
|
||||
$agreed = filled($changes['agreed_total'] ?? null) ? (int) $changes['agreed_total'] : null;
|
||||
try {
|
||||
$quote = $this->calculator->calculate($booking->property, new StayRequest($arrival, $departure, max(1, (int) $guests), $extras, $booking->promo_code));
|
||||
foreach ((array) ($booking->quote['lines'] ?? []) as $line) {
|
||||
if (($line['type'] ?? null) === QuoteLineType::Adjustment->value) {
|
||||
$quote = $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, (string) $line['label'], 1, (int) $line['amount'], (int) $line['amount']));
|
||||
}
|
||||
}
|
||||
$source = 'aus Ihren Preisen neu berechnet';
|
||||
} catch (QuoteException $exception) {
|
||||
if ($agreed === null) {
|
||||
return [null, '–', 'Preis: '.$exception->getMessage().' Bitte einen vereinbarten Preis eintragen.'];
|
||||
}
|
||||
$quote = new PriceQuote($arrival, $departure, (int) $guests, [new QuoteLine(QuoteLineType::Accommodation, 'Vereinbarter Preis', 1, $agreed, $agreed)], $booking->property->deposit_percent, $arrival->subDays($booking->property->balance_due_days_before_arrival));
|
||||
$source = 'vereinbarter Preis';
|
||||
}
|
||||
|
||||
if ($agreed !== null && $agreed !== $quote->total()) {
|
||||
$label = trim((string) ($changes['agreed_total_label'] ?? '')) ?: 'Vereinbarte Preisanpassung';
|
||||
$quote = $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, $label, 1, $agreed - $quote->total(), $agreed - $quote->total()));
|
||||
$source = 'vereinbarter Preis';
|
||||
}
|
||||
|
||||
return [['quote' => $quote->toArray(), 'total' => $quote->total(), 'deposit' => $quote->deposit(), 'balance_due_on' => $quote->balanceDueOn->toDateString()], $source, null];
|
||||
}
|
||||
|
||||
/**
|
||||
* What happens in the calendar and on the portals that are blocked by hand.
|
||||
*
|
||||
* @return array{0: list<string>, 1: list<string>}
|
||||
*/
|
||||
private function calendarConsequences(Booking $booking, CarbonImmutable $arrival, CarbonImmutable $departure): array
|
||||
{
|
||||
$oldStart = $booking->arrival;
|
||||
$oldEnd = $booking->departure;
|
||||
if ($arrival->equalTo($oldStart) && $departure->equalTo($oldEnd)) {
|
||||
return [['Kalender unverändert.'], []];
|
||||
}
|
||||
|
||||
$added = array_values(array_filter([
|
||||
$arrival->lessThan($oldStart) ? [$arrival, $oldStart->min($departure)] : null,
|
||||
$departure->greaterThan($oldEnd) ? [$oldEnd->max($arrival), $departure] : null,
|
||||
]));
|
||||
$freed = array_values(array_filter([
|
||||
$oldStart->lessThan($arrival) ? [$oldStart, $arrival->min($oldEnd)] : null,
|
||||
$oldEnd->greaterThan($departure) ? [$departure->max($oldStart), $oldEnd] : null,
|
||||
]));
|
||||
$range = fn (array $pair): string => $pair[0]->format('d.m.').'–'.$pair[1]->format('d.m.Y');
|
||||
|
||||
$calendar = [
|
||||
...array_map(fn (array $pair): string => 'Neu belegt: '.$range($pair), $added),
|
||||
...array_map(fn (array $pair): string => 'Wieder frei: '.$range($pair), $freed),
|
||||
'Die Kalender für die Portale zeigen den neuen Zeitraum beim nächsten Abruf.',
|
||||
];
|
||||
|
||||
$origin = $booking->origin_channel_id ?? $booking->import_channel_id;
|
||||
$portals = $booking->property->channels()->active()->where('requires_manual_blocking', true)->get()
|
||||
->filter(fn (Channel $channel): bool => $channel->exportsOccupations() && $channel->id !== $origin)
|
||||
->map(fn (Channel $channel): string => 'Aufgabe für '.$channel->name.': '.implode(', ', [...array_map(fn (array $pair): string => 'sperren '.$range($pair), $added), ...array_map(fn (array $pair): string => 'freigeben '.$range($pair), $freed)]))
|
||||
->values()->all();
|
||||
if ($booking->caseType()->isExternallyBinding()) {
|
||||
$portals[] = 'Die Änderung selbst muss im Portal „'.($booking->processChannel()?->name ?? 'Portal').'“ vorliegen – hier wird sie nur nachgetragen.';
|
||||
}
|
||||
|
||||
return [$calendar, $portals];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function snapshot(Booking $booking): array
|
||||
{
|
||||
return [
|
||||
'arrival' => $booking->arrival->toDateString(), 'departure' => $booking->departure->toDateString(), 'guests' => $booking->guests,
|
||||
'extras' => (array) ($booking->extras ?? []), 'quote' => $booking->quote, 'total' => $booking->total, 'deposit' => $booking->deposit,
|
||||
'balance_due_on' => $booking->balance_due_on?->toDateString(), 'tourist_tax_persons' => $booking->tourist_tax_persons,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $before
|
||||
* @param array<string, mixed> $after
|
||||
* @return list<string>
|
||||
*/
|
||||
private static function summary(array $before, array $after): array
|
||||
{
|
||||
$date = fn (?string $value): string => $value ? CarbonImmutable::parse($value)->format('d.m.Y') : '–';
|
||||
$lines = [];
|
||||
if ($before['arrival'] !== $after['arrival'] || $before['departure'] !== $after['departure']) {
|
||||
$lines[] = 'Zeitraum '.$date($before['arrival']).'–'.$date($before['departure']).' → '.$date($after['arrival']).'–'.$date($after['departure']);
|
||||
}
|
||||
if ($before['guests'] !== $after['guests']) {
|
||||
$lines[] = 'Personen '.($before['guests'] ?? '?').' → '.($after['guests'] ?? '?');
|
||||
}
|
||||
if ((array) $before['extras'] != (array) $after['extras']) {
|
||||
$lines[] = 'Zusatzleistungen geändert';
|
||||
}
|
||||
if ($before['total'] !== $after['total']) {
|
||||
$lines[] = 'Preis '.($before['total'] === null ? '–' : Money::format($before['total'])).' → '.($after['total'] === null ? '–' : Money::format($after['total']));
|
||||
}
|
||||
|
||||
return $lines === [] ? ['keine inhaltliche Änderung'] : $lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $preview
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private static function consequences(array $preview): array
|
||||
{
|
||||
return ['summary' => $preview['summary'], 'calendar' => $preview['calendar'], 'portals' => $preview['portals'], 'price' => $preview['price'], 'payment' => $preview['payment'], 'refund' => $preview['refund']];
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Mail\BookingConfirmed;
|
||||
use App\Mail\BookingDocumentation;
|
||||
use App\Mail\StayConfirmed;
|
||||
use App\Models\Booking;
|
||||
use App\Process\CaseLog;
|
||||
use App\Support\Inbox;
|
||||
@@ -108,7 +109,11 @@ public function deliver(Booking $booking, bool $notifyGuest = true, ?DocumentKin
|
||||
return true;
|
||||
}
|
||||
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send($kind === DocumentKind::ExternalRecord ? new BookingDocumentation($booking) : new BookingConfirmed($booking));
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(match ($kind) {
|
||||
DocumentKind::ExternalRecord => new BookingDocumentation($booking),
|
||||
DocumentKind::StayConfirmation => new StayConfirmed($booking),
|
||||
default => new BookingConfirmed($booking),
|
||||
});
|
||||
$booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->save();
|
||||
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\IntakeKind;
|
||||
use App\Enums\InternalKind;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Guest;
|
||||
use App\Models\Property;
|
||||
use App\Pricing\PrivateStayPrice;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Process\CaseLog;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Own use, a private stay or a block as a case (A6, package 6): the dates are occupied at once and the portals are
|
||||
* blocked like for any booking. A block has nothing but dates and an occasion; own use and private stays may have
|
||||
* guests, services, an agreed rent (0 by default), the tourist tax and payments – but never a rental contract, payment
|
||||
* reminders, reviews or marketing (the A6 profile switches them off).
|
||||
*/
|
||||
class CreateInternalCase
|
||||
{
|
||||
public function __construct(private AvailabilityChecker $availability, private PrivateStayPrice $price) {}
|
||||
|
||||
/**
|
||||
* @param array{occasion?: ?string, guest?: ?array<string, ?string>, guests?: ?int, extras?: ?array<int, int>, rent?: ?int, tourist_tax_persons?: ?int, tourist_tax_note?: ?string, notes?: ?string} $data
|
||||
*
|
||||
* @throws ReservationException
|
||||
* @throws QuoteException
|
||||
*/
|
||||
public function handle(Property $property, InternalKind $kind, CarbonImmutable $arrival, CarbonImmutable $departure, array $data = []): Booking
|
||||
{
|
||||
if ($departure->lessThanOrEqualTo($arrival)) {
|
||||
throw new ReservationException('Das Ende muss nach dem Beginn liegen.');
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($property, $kind, $arrival, $departure, $data): Booking {
|
||||
Property::query()->whereKey($property->id)->lockForUpdate()->firstOrFail();
|
||||
if (! $this->availability->isAvailable($property, $arrival, $departure)) {
|
||||
throw ReservationException::notAvailable();
|
||||
}
|
||||
|
||||
$guests = $kind === InternalKind::Block ? null : (filled($data['guests'] ?? null) ? (int) $data['guests'] : null);
|
||||
$extras = $kind === InternalKind::Block ? [] : array_filter(array_map('intval', (array) ($data['extras'] ?? [])));
|
||||
$taxPersons = $kind === InternalKind::Block ? null : (filled($data['tourist_tax_persons'] ?? null) ? (int) $data['tourist_tax_persons'] : null);
|
||||
$quote = $kind === InternalKind::Block ? null : $this->price->quote($property, $arrival, $departure, $guests, $extras, (int) ($data['rent'] ?? 0), $taxPersons);
|
||||
$guest = $kind->hasGuests() ? $this->guest((array) ($data['guest'] ?? [])) : null;
|
||||
|
||||
$booking = $property->bookings()->create([
|
||||
'guest_id' => $guest?->id,
|
||||
'status' => BookingStatus::Confirmed,
|
||||
'source' => 'internal',
|
||||
'intake' => IntakeKind::Internal,
|
||||
'internal_kind' => $kind,
|
||||
'occasion' => filled($data['occasion'] ?? null) ? trim((string) $data['occasion']) : null,
|
||||
'arrival' => $arrival->toDateString(),
|
||||
'departure' => $departure->toDateString(),
|
||||
'guests' => $guests,
|
||||
'extras' => $extras,
|
||||
'quote' => $quote?->toArray(),
|
||||
'total' => $quote?->total(),
|
||||
'tourist_tax_persons' => $taxPersons,
|
||||
'tourist_tax_note' => filled($data['tourist_tax_note'] ?? null) ? trim((string) $data['tourist_tax_note']) : null,
|
||||
'confirmed_at' => now(),
|
||||
'internal_notes' => filled($data['notes'] ?? null) ? trim((string) $data['notes']) : null,
|
||||
]);
|
||||
CaseLog::record($booking, 'intake', $kind->getLabel().' eingetragen'.($booking->occasion ? ': '.$booking->occasion : ''));
|
||||
|
||||
return $booking;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest of a private stay – only with a real name; a known e-mail address finds the existing guest.
|
||||
*
|
||||
* @param array<string, ?string> $data
|
||||
*/
|
||||
private function guest(array $data): ?Guest
|
||||
{
|
||||
$data = array_map(fn ($value) => filled($value) ? trim((string) $value) : null, Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']));
|
||||
if (blank($data['first_name'] ?? null) || blank($data['last_name'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$email = filled($data['email'] ?? null) ? mb_strtolower($data['email']) : null;
|
||||
if ($email !== null && ($known = Guest::query()->where('email', $email)->whereNull('anonymized_at')->first()) !== null) {
|
||||
return $known;
|
||||
}
|
||||
|
||||
return Guest::query()->create([...array_filter($data, fn ($value) => $value !== null), 'email' => $email ?? '']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\InternalKind;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
use App\Process\CaseLog;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Lifts a block or calls off an own use / private stay (A6). It is no cancellation: no costs, no refund rule, no mails –
|
||||
* the dates are free again and the portals are released like for any booking that ends.
|
||||
*/
|
||||
class EndInternalCase
|
||||
{
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, string $reason, ?string $by = null): void
|
||||
{
|
||||
if (! $booking->isInternal()) {
|
||||
throw new ReservationException('Nur eigene Nutzung, private Aufenthalte und Sperren werden so beendet.');
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($booking, $reason, $by): void {
|
||||
$booking->lockForTransition();
|
||||
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'aufgehoben');
|
||||
}
|
||||
|
||||
CaseLog::context(fn () => $booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]), actor: $by, reason: $reason);
|
||||
CaseLog::record($booking, 'status', self::label($booking), $reason, actor: $by);
|
||||
});
|
||||
}
|
||||
|
||||
public static function label(Booking $booking): string
|
||||
{
|
||||
return $booking->internal_kind === InternalKind::Block ? 'Sperre aufgehoben' : 'Aufenthalt abgesagt';
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\PaymentKind;
|
||||
use App\Enums\PaymentMethod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Payment;
|
||||
@@ -10,20 +11,25 @@
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Records a received payment (or a refund with a negative amount) and moves the booking along:
|
||||
* Bestätigt → Anzahlung erhalten → Bezahlt.
|
||||
* Records a payment of a case with its kind (package 8): the guest paid us, the portal reports the guest paid it, the
|
||||
* portal paid out to us, or we refunded the guest. Only the guest's payments move the booking along
|
||||
* (Bestätigt → Anzahlung erhalten → Bezahlt); a refund is stored as a negative amount.
|
||||
*/
|
||||
class RecordPayment
|
||||
{
|
||||
public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null): Payment
|
||||
public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null, PaymentKind $kind = PaymentKind::Guest, ?string $source = null): Payment
|
||||
{
|
||||
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy): Payment {
|
||||
$amount = $kind === PaymentKind::Refund ? -abs($amount) : $amount;
|
||||
|
||||
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy, $kind, $source): Payment {
|
||||
$payment = $booking->payments()->create([
|
||||
'amount' => $amount,
|
||||
'paid_on' => $paidOn->toDateString(),
|
||||
'method' => $method,
|
||||
'note' => $note,
|
||||
'recorded_by' => $recordedBy,
|
||||
'kind' => $kind,
|
||||
'source' => $source,
|
||||
]);
|
||||
|
||||
$booking->unsetRelation('payments');
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\AmountKind;
|
||||
use App\Enums\PaymentKind;
|
||||
use App\Enums\PaymentMethod;
|
||||
use App\Models\Booking;
|
||||
use App\Pricing\PortalPrice;
|
||||
use App\Process\CaseAutomation;
|
||||
use App\Process\CaseLog;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Takes over what a portal shows about a booking (package 8): the guest's total as the agreed price ("Gesamtpreis laut
|
||||
* Portal"), and – as far as the portal shows them – price positions, collective amounts, commission, announced payouts,
|
||||
* instalments and what the guest has paid to the portal. Every value is stored with its source and date as stated; the
|
||||
* total is never recalculated from the positions, and a statement entered twice is stored once.
|
||||
*/
|
||||
class RecordPortalAmounts
|
||||
{
|
||||
public function __construct(private PortalPrice $price, private RecordPayment $payments) {}
|
||||
|
||||
/**
|
||||
* @param list<array{kind: AmountKind|string, label?: ?string, amount: int, due_on?: ?string, note?: ?string}> $amounts
|
||||
* @param list<array{amount: int, paid_on: string}> $paidViaPortal instalments the portal shows as paid by the guest
|
||||
*/
|
||||
public function handle(Booking $booking, ?int $guestTotal, array $amounts, array $paidViaPortal, string $source, ?CarbonImmutable $statedOn = null, ?string $by = null): void
|
||||
{
|
||||
$statedOn ??= CarbonImmutable::today();
|
||||
|
||||
DB::transaction(function () use ($booking, $guestTotal, $amounts, $paidViaPortal, $source, $statedOn, $by): void {
|
||||
if ($guestTotal !== null && $guestTotal !== $booking->total) {
|
||||
$before = $booking->total;
|
||||
$booking->update($this->price->columns($booking->property, $booking->arrival, $booking->departure, $booking->guests, $guestTotal, $source));
|
||||
CaseLog::record($booking, 'price', 'Gesamtpreis laut '.$source.': '.Money::format($guestTotal).($before !== null ? ' (vorher '.Money::format($before).')' : ''));
|
||||
}
|
||||
|
||||
foreach ($amounts as $row) {
|
||||
$kind = $row['kind'] instanceof AmountKind ? $row['kind'] : AmountKind::from((string) $row['kind']);
|
||||
$label = filled($row['label'] ?? null) ? trim((string) $row['label']) : null;
|
||||
$exists = $booking->amounts()->where('kind', $kind)->where('amount', (int) $row['amount'])->where('source', $source)
|
||||
->where(fn ($query) => $label === null ? $query->whereNull('label') : $query->where('label', $label))->exists();
|
||||
if ($exists) {
|
||||
continue;
|
||||
}
|
||||
$booking->amounts()->create([
|
||||
'kind' => $kind, 'label' => $label, 'amount' => (int) $row['amount'], 'source' => $source,
|
||||
'stated_on' => $statedOn->toDateString(), 'due_on' => filled($row['due_on'] ?? null) ? $row['due_on'] : null,
|
||||
'note' => filled($row['note'] ?? null) ? trim((string) $row['note']) : null, 'recorded_by' => $by,
|
||||
]);
|
||||
}
|
||||
|
||||
foreach ($paidViaPortal as $row) {
|
||||
$paidOn = CarbonImmutable::parse($row['paid_on']);
|
||||
$known = $booking->payments()->where('kind', PaymentKind::GuestViaPortal)->where('amount', (int) $row['amount'])->whereDate('paid_on', $paidOn)->exists();
|
||||
if (! $known) {
|
||||
$this->payments->handle($booking, (int) $row['amount'], $paidOn, PaymentMethod::Other, 'laut '.$source, $by, PaymentKind::GuestViaPortal, $source);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
app(CaseAutomation::class)->advance($booking->fresh());
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ public static function kindFor(Booking $booking): DocumentKind
|
||||
{
|
||||
$kind = DocumentKind::forCase($booking);
|
||||
|
||||
return in_array($kind, [DocumentKind::Confirmation, DocumentKind::ExternalRecord], true) ? $kind : DocumentKind::Confirmation;
|
||||
return in_array($kind, [DocumentKind::Confirmation, DocumentKind::ExternalRecord, DocumentKind::StayConfirmation], true) ? $kind : DocumentKind::Confirmation;
|
||||
}
|
||||
|
||||
private function send(Booking $booking, DocumentComposition $composition, bool $acknowledged, bool $automatic): bool
|
||||
|
||||
Reference in new issue
Block a user