Files

173 lines
8.5 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Process;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\CaseMoney;
use App\Support\Money;
use Illuminate\Support\Collection;
/**
* The two closings of a case (package 9, operator decision): **stay closed** – the activities the stay needs are done or
* handed over (status "Abgeschlossen") – and **commercially settled** – claims, payments, refunds and portal payouts are
* clear (`settled_at`). They are separate statements: a stay can be closed while the payout of the portal is still
* outstanding, and open money never disappears because the stay is closed.
*
* Nothing here is a status of its own: what keeps a case open is derived from its tasks and its money.
*/
final class CaseClosure
{
/** Kinds of financial clarification that allow settling an open portal payout (decision O5). */
public const PAYOUT_CLARIFICATIONS = [
'offset' => 'Verrechnung dokumentiert',
'difference_booked' => 'Differenz geklärt und verbucht',
'written_off' => 'Forderung ausgebucht',
self::CLAIM_OPEN => 'Als offene Forderung weiterführen',
];
public const CLAIM_OPEN = 'open_claim';
public const AUTOMATIC = 'automatisch';
/**
* Open tasks of the stay itself (services, issues, a portal change to check) that keep the stay from being closed.
*
* @return Collection<int, BookingTask>
*/
public static function stayBlockers(Booking $booking): Collection
{
return BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get()
->filter(fn (BookingTask $task): bool => $task->kind->blocksStay())->values();
}
/**
* What is still open commercially, in plain words (empty: nothing open). Only cases whose stay is closed or that were
* cancelled have a commercial closing; for all others the money is simply still running.
*
* @return list<string>
*/
public static function commercialPoints(Booking $booking): array
{
$points = [];
$tasks = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get()
->filter(fn (BookingTask $task): bool => $task->kind->isCommercial());
if ($booking->status !== BookingStatus::Cancelled) {
$money = CaseMoney::of($booking);
$points = match ($money->collector()) {
Responsibility::Landlord => self::ourMoney($booking, $money),
Responsibility::Portal => self::portalMoney($booking, $money),
default => $booking->total !== null && $booking->total > 0 && $booking->paidAmount() < $booking->total
? ['Vereinbarte Zahlung noch offen: '.Money::format($booking->total - $booking->paidAmount()).' (ohne Erinnerungen).']
: [],
};
}
foreach ($tasks as $task) {
$points[] = 'Aufgabe offen: '.$task->label().'.';
}
return array_values(array_unique($points));
}
/**
* Closes or reopens the commercial side after anything that may have changed it (payment, task, stay closed).
* A settlement the landlord made by hand stays unless a commercial task is opened again.
*/
public static function refresh(Booking $booking): void
{
if (! in_array($booking->status, [BookingStatus::Completed, BookingStatus::Cancelled], true)) {
return;
}
$booking->unsetRelation('payments');
$points = self::commercialPoints($booking);
$openTasks = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get()
->contains(fn (BookingTask $task): bool => $task->kind->isCommercial());
if ($booking->settled_at === null && $points === []) {
$booking->forceFill(['settled_at' => now(), 'settled_by' => self::AUTOMATIC, 'settled_note' => null])->save();
CaseLog::record($booking, 'settled', 'Kaufmännisch abgeschlossen – nichts mehr offen');
} elseif ($booking->settled_at !== null && ($openTasks || ($booking->settled_by === self::AUTOMATIC && $points !== []))) {
$booking->forceFill(['settled_at' => null, 'settled_by' => null, 'settled_note' => null])->save();
CaseLog::record($booking, 'settled', 'Kaufmännischer Abschluss wieder geöffnet: '.implode(' ', $points));
}
}
/**
* The landlord settles the case although points are open (e.g. a small payout difference accepted); open commercial
* tasks are closed with the same note. The reason is required and kept.
*/
public static function settle(Booking $booking, string $note, string $by, ?string $clarification = null): void
{
// Decision O5: with portal collection, an open or deviating payout is settled only after its financial
// clarification – a reason alone is not enough, and a portal's report of a payout is no proof of the receipt.
$payoutPoints = $booking->status !== BookingStatus::Cancelled && CaseMoney::of($booking)->collector() === Responsibility::Portal
? self::portalMoney($booking, CaseMoney::of($booking)) : [];
if ($payoutPoints !== [] && ! array_key_exists((string) $clarification, self::PAYOUT_CLARIFICATIONS)) {
throw new ReservationException('Bei Inkasso durch das Portal ist der kaufmännische Abschluss erst nach finanzieller Klärung möglich: Auszahlung eingegangen, Verrechnung, verbuchte Differenz oder ausgebuchte Forderung. Offen: '.implode(' ', $payoutPoints));
}
if ($clarification === self::CLAIM_OPEN) {
// The claim stays traceable: an open task of its own, the case stays commercially open.
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::OpenClaim, 'status' => BookingTaskStatus::Open], ['tenant_id' => $booking->tenant_id, 'due_on' => today()->addDays(14), 'note' => mb_substr($note, 0, 1000)]);
CaseLog::record($booking, 'settled', 'Als offene Forderung weitergeführt', reason: $note, data: ['open_points' => $payoutPoints, 'clarification' => $clarification], actor: $by);
return;
}
if ($clarification !== null && isset(self::PAYOUT_CLARIFICATIONS[$clarification])) {
$note = self::PAYOUT_CLARIFICATIONS[$clarification].': '.$note;
}
foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) {
if ($task->kind->isCommercial()) {
$task->complete($by, 'Mit dem kaufmännischen Abschluss geklärt: '.$note);
}
}
$points = self::commercialPoints($booking);
$booking->forceFill(['settled_at' => now(), 'settled_by' => $by, 'settled_note' => mb_substr($note, 0, 500)])->save();
CaseLog::record($booking, 'settled', 'Kaufmännisch abgeschlossen (von Hand)', reason: $note, data: ['open_points' => $points], actor: $by);
}
/**
* @return list<string>
*/
private static function ourMoney(Booking $booking, CaseMoney $money): array
{
if ($booking->total === null) {
return ['Der Preis ist nicht bekannt.'];
}
$paid = $booking->paidAmount();
return array_values(array_filter([
$money->openForUs() > 0 ? 'Noch offen vom Gast: '.Money::format($money->openForUs()).'.' : null,
$paid > $booking->total ? 'Überzahlung von '.Money::format($paid - $booking->total).' – Erstattung klären.' : null,
]));
}
/**
* @return list<string>
*/
private static function portalMoney(Booking $booking, CaseMoney $money): array
{
$portal = $booking->processChannel()?->name ?? 'dem Portal';
if ($booking->total === null) {
return ['Der Gesamtpreis laut '.$portal.' fehlt.'];
}
$payout = $money->payout();
return array_values(array_filter([
$payout['received'] === 0 ? 'Die Auszahlung von '.$portal.' ist noch nicht eingegangen.' : null,
$payout['received'] > 0 && ($payout['outstanding'] ?? 0) > 0 ? 'Von der angekündigten Auszahlung fehlen noch '.Money::format((int) $payout['outstanding']).'.' : null,
$payout['difference'] > 0 ? 'Die Auszahlungsangaben weichen um '.Money::format($payout['difference']).' voneinander ab – ungeklärt.' : null,
]));
}
}