feat: automatic saving of drafts when editing bookings

This commit is contained in:
Björn Fromme
2026-01-06 10:29:17 +01:00
parent 97f8baba06
commit 60c1459902
7 changed files with 759 additions and 52 deletions
+442
View File
@@ -0,0 +1,442 @@
<?php
declare(strict_types=1);
namespace App\Service;
use App\BusProNet\Model\Address;
use App\BusProNet\Model\Travel;
use App\Entity\BookingEditDraft;
use App\Entity\User;
use App\Form\Model\BankAccountDto;
use App\Form\Model\BookingDto;
use App\Form\Model\ParticipantDto;
use App\Repository\BookingEditDraftRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
/**
* Manages draft persistence for the booking edit flow.
*
* This service handles saving, loading, and applying draft data to prevent
* data loss when BusProNet API rejects booking update submissions. Drafts
* are automatically applied on top of fresh API data when a user returns
* to edit a booking.
*/
class BookingEditDraftService
{
public function __construct(
private readonly BookingEditDraftRepository $draftRepository,
private readonly EntityManagerInterface $entityManager,
private readonly BookingFingerprintService $fingerprintService,
private readonly LoggerInterface $logger,
) {
}
/**
* Finds an existing draft for a user and booking combination.
*
* @param User $user The user who owns the draft
* @param int $bookingId The BusProNet booking ID
*
* @return BookingEditDraft|null The draft if found, null otherwise
*/
public function findDraft(User $user, int $bookingId): ?BookingEditDraft
{
return $this->draftRepository->findByUserAndBooking($user, $bookingId);
}
/**
* Saves or updates a draft for the given booking.
*
* Uses an upsert pattern: creates a new draft if none exists,
* or updates the existing draft with new form data.
*
* @param User $user The user who owns the draft
* @param int $bookingId The BusProNet booking ID
* @param BookingDto $bookingDto The booking DTO containing user edits
*/
public function saveDraft(User $user, int $bookingId, BookingDto $bookingDto): void
{
$formData = $this->fingerprintService->extractUserData($bookingDto);
$existingDraft = $this->findDraft($user, $bookingId);
if (null !== $existingDraft) {
$existingDraft->setFormData($formData);
} else {
$draft = new BookingEditDraft($user, $bookingId, $formData);
$this->entityManager->persist($draft);
}
$this->entityManager->flush();
$this->logger->debug('Saved booking edit draft', [
'user_id' => $user->getId(),
'booking_id' => $bookingId,
]);
}
/**
* Deletes a draft after successful booking submission.
*
* @param User $user The user who owns the draft
* @param int $bookingId The BusProNet booking ID
*/
public function deleteDraft(User $user, int $bookingId): void
{
$this->draftRepository->deleteByUserAndBooking($user, $bookingId);
$this->logger->debug('Deleted booking edit draft', [
'user_id' => $user->getId(),
'booking_id' => $bookingId,
]);
}
/**
* Applies draft data to a fresh BookingDto loaded from the API.
*
* This method merges user input from the draft onto fresh API data.
* The draft contains personal data, service selections, and payment info
* that the user previously entered. Services are resolved by ID against
* the current Travel data to ensure prices and availability are current.
*
* @param BookingEditDraft $draft The draft containing saved user data
* @param BookingDto $dto The fresh BookingDto from API (modified in place)
* @param Travel $travel The current travel data for service resolution
*
* @return bool True if draft was applied successfully, false if draft data was invalid
*/
public function applyDraftToDto(BookingEditDraft $draft, BookingDto $dto, Travel $travel): bool
{
try {
$formData = $draft->getFormData();
// Apply payment data
if (isset($formData['paymentMethod'])) {
$dto->paymentMethod = $formData['paymentMethod'];
}
if (isset($formData['bankAccount']) && true === is_array($formData['bankAccount'])) {
$this->applyBankAccountData($dto, $formData['bankAccount']);
}
// Apply participant data
if (isset($formData['participants']) && true === is_array($formData['participants'])) {
foreach ($formData['participants'] as $index => $participantData) {
// Only apply to participants that exist in fresh DTO
if (false === isset($dto->participants[$index])) {
continue;
}
$this->applyParticipantData($dto->participants[$index], $participantData, $travel);
}
}
$this->logger->info('Applied draft to booking DTO', [
'booking_id' => $draft->getBookingId(),
'draft_created_at' => $draft->getCreatedAt()->format('Y-m-d H:i:s'),
]);
return true;
} catch (\Throwable $e) {
$this->logger->error('Failed to apply draft to booking DTO', [
'booking_id' => $draft->getBookingId(),
'error' => $e->getMessage(),
]);
return false;
}
}
/**
* Applies bank account data from draft to BookingDto.
*/
private function applyBankAccountData(BookingDto $dto, array $bankAccountData): void
{
$iban = $bankAccountData['iban'] ?? null;
$accountHolder = $bankAccountData['accountHolder'] ?? null;
if (null === $iban && null === $accountHolder) {
return;
}
if (null === $dto->bankAccount) {
$dto->bankAccount = new BankAccountDto();
}
$dto->bankAccount->iban = $iban;
$dto->bankAccount->accountHolder = $accountHolder;
}
/**
* Applies participant data from draft to a ParticipantDto.
*/
private function applyParticipantData(ParticipantDto $participant, array $data, Travel $travel): void
{
// Personal data
if (isset($data['personalData']) && true === is_array($data['personalData'])) {
$this->applyPersonalData($participant, $data['personalData']);
}
// Address
if (isset($data['address']) && true === is_array($data['address'])) {
$this->applyAddressData($participant, $data['address']);
}
// Body dimensions
if (isset($data['bodyDimensions']) && true === is_array($data['bodyDimensions'])) {
$this->applyBodyDimensions($participant, $data['bodyDimensions']);
}
// Room assignment
if (isset($data['roomAssignment']) && true === is_array($data['roomAssignment'])) {
$this->applyRoomAssignment($participant, $data['roomAssignment']);
}
// License plate
if (true === array_key_exists('licensePlate', $data)) {
$participant->licensePlate = $data['licensePlate'];
}
// Services
if (isset($data['services']) && true === is_array($data['services'])) {
$this->applyServiceSelections($participant, $data['services'], $travel);
}
// Vouchers
if (isset($data['vouchers']) && true === is_array($data['vouchers'])) {
$this->applyVoucherCodes($participant, $data['vouchers']);
}
}
/**
* Applies personal data fields to participant.
*/
private function applyPersonalData(ParticipantDto $participant, array $data): void
{
if (true === array_key_exists('firstName', $data)) {
$participant->firstName = $data['firstName'];
}
if (true === array_key_exists('lastName', $data)) {
$participant->lastName = $data['lastName'];
}
if (true === array_key_exists('dateOfBirth', $data) && null !== $data['dateOfBirth']) {
$participant->dateOfBirth = new \DateTimeImmutable($data['dateOfBirth']);
}
if (true === array_key_exists('email', $data)) {
$participant->email = $data['email'];
}
if (true === array_key_exists('mobile', $data)) {
$participant->mobile = $data['mobile'];
}
if (true === array_key_exists('gender', $data)) {
$participant->gender = $data['gender'];
}
if (true === array_key_exists('nationality', $data)) {
$participant->nationality = $data['nationality'];
}
}
/**
* Applies address data to participant.
*/
private function applyAddressData(ParticipantDto $participant, array $data): void
{
$hasAddressData = null !== ($data['street'] ?? null)
|| null !== ($data['postCode'] ?? null)
|| null !== ($data['city'] ?? null)
|| null !== ($data['country'] ?? null);
if (false === $hasAddressData) {
return;
}
if (null === $participant->address) {
$participant->address = new Address();
}
if (true === array_key_exists('street', $data)) {
$participant->address->street = $data['street'];
}
if (true === array_key_exists('postCode', $data)) {
$participant->address->postCode = $data['postCode'];
}
if (true === array_key_exists('city', $data)) {
$participant->address->city = $data['city'];
}
if (true === array_key_exists('country', $data)) {
$participant->address->country = $data['country'];
}
}
/**
* Applies body dimension data to participant.
*/
private function applyBodyDimensions(ParticipantDto $participant, array $data): void
{
if (true === array_key_exists('height', $data)) {
$participant->height = $data['height'];
}
if (true === array_key_exists('weight', $data)) {
$participant->weight = $data['weight'];
}
if (true === array_key_exists('shoeSize', $data)) {
$participant->shoeSize = $data['shoeSize'];
}
}
/**
* Applies room assignment data to participant.
*/
private function applyRoomAssignment(ParticipantDto $participant, array $data): void
{
if (true === array_key_exists('assignedRoomId', $data)) {
$participant->assignedRoomId = $data['assignedRoomId'];
}
if (true === array_key_exists('remarksRoom', $data)) {
$participant->remarksRoom = $data['remarksRoom'];
}
}
/**
* Applies service selections to participant, resolving IDs against Travel data.
*/
private function applyServiceSelections(ParticipantDto $participant, array $data, Travel $travel): void
{
// Ski pass (single service)
if (true === array_key_exists('skiPass', $data)) {
$participant->skiPass = $this->resolveService($data['skiPass'], $travel->additionalServices);
}
// Courses (array)
if (true === array_key_exists('courses', $data) && true === is_array($data['courses'])) {
$participant->courses = $this->resolveServiceArray($data['courses'], $travel->additionalServices);
}
// Board (array)
if (true === array_key_exists('board', $data) && true === is_array($data['board'])) {
$participant->board = $this->resolveServiceArray($data['board'], $travel->additionalServices);
}
// Rentals (array)
if (true === array_key_exists('rentals', $data) && true === is_array($data['rentals'])) {
$participant->rentals = $this->resolveServiceArray($data['rentals'], $travel->additionalServices);
}
// Rental insurance (single)
if (true === array_key_exists('rentalInsurance', $data)) {
$participant->rentalInsurance = $this->resolveService($data['rentalInsurance'], $travel->additionalServices);
$participant->rentalInsuranceSelected = null !== $participant->rentalInsurance;
}
// Additional services (array)
if (true === array_key_exists('additionalServices', $data) && true === is_array($data['additionalServices'])) {
$participant->additionalServices = $this->resolveServiceArray($data['additionalServices'], $travel->additionalServices);
}
// Transportation outbound (single)
if (true === array_key_exists('transportationOutbound', $data)) {
$participant->transportationOutbound = $this->resolveService($data['transportationOutbound'], $travel->transportationServices);
}
// Transportation inbound (single)
if (true === array_key_exists('transportationInbound', $data)) {
$participant->transportationInbound = $this->resolveService($data['transportationInbound'], $travel->transportationServices);
}
// Pickup (single)
if (true === array_key_exists('pickup', $data)) {
$participant->pickup = $this->resolvePickup($data['pickup'], $travel);
}
// Parking (boolean)
if (true === array_key_exists('parking', $data)) {
$participant->parking = (bool) $data['parking'];
}
// Insurance (single)
if (true === array_key_exists('insurance', $data)) {
$participant->insurance = $this->resolveInsurance($data['insurance'], $travel);
}
// Bulk insurance booking (boolean)
if (true === array_key_exists('bulkInsuranceBooking', $data)) {
$participant->bulkInsuranceBooking = (bool) $data['bulkInsuranceBooking'];
}
}
/**
* Applies voucher codes to participant.
*/
private function applyVoucherCodes(ParticipantDto $participant, array $data): void
{
if (true === array_key_exists('purchaseVoucherCode', $data)) {
$participant->purchaseVoucherCode = $data['purchaseVoucherCode'];
}
if (true === array_key_exists('promoVoucherCode', $data)) {
$participant->promoVoucherCode = $data['promoVoucherCode'];
}
}
/**
* Resolves a single service ID to a Service object from the available services.
*
* @param int|null $serviceId The service ID to resolve
* @param array $services Available services indexed by ID
*
* @return object|null The service object if found, null otherwise
*/
private function resolveService(?int $serviceId, array $services): ?object
{
if (null === $serviceId) {
return null;
}
return $services[$serviceId] ?? null;
}
/**
* Resolves an array of service IDs to Service objects.
*
* @param array $serviceIds Array of service IDs
* @param array $services Available services indexed by ID
*
* @return array Array of resolved Service objects (missing services are skipped)
*/
private function resolveServiceArray(array $serviceIds, array $services): array
{
$resolved = [];
foreach ($serviceIds as $serviceId) {
if (isset($services[$serviceId])) {
$resolved[] = $services[$serviceId];
}
}
return $resolved;
}
/**
* Resolves a pickup ID to a Pickup object.
*/
private function resolvePickup(?int $pickupId, Travel $travel): ?object
{
if (null === $pickupId) {
return null;
}
return $travel->pickupsOutbound[$pickupId] ?? $travel->pickupsInbound[$pickupId] ?? null;
}
/**
* Resolves an insurance ID to an Insurance object.
*/
private function resolveInsurance(?int $insuranceId, Travel $travel): ?object
{
if (null === $insuranceId) {
return null;
}
return $travel->insurances[$insuranceId] ?? null;
}
}